summaryrefslogtreecommitdiff
path: root/src/mongo/db/logical_session_cache_test.cpp
blob: baba6814b3427462acd6269e012d5f125d18d1dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
/**
 *    Copyright (C) 2017 MongoDB Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the GNU Affero General Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#include "mongo/platform/basic.h"

#include "mongo/bson/oid.h"
#include "mongo/db/auth/user_name.h"
#include "mongo/db/logical_session_cache.h"
#include "mongo/db/logical_session_id.h"
#include "mongo/db/logical_session_record.h"
#include "mongo/db/service_liason_mock.h"
#include "mongo/db/sessions_collection_mock.h"
#include "mongo/stdx/future.h"
#include "mongo/stdx/memory.h"
#include "mongo/unittest/unittest.h"

namespace mongo {
namespace {

const Milliseconds kSessionTimeout =
    duration_cast<Milliseconds>(LogicalSessionCache::kLogicalSessionDefaultTimeout);
const Milliseconds kForceRefresh =
    duration_cast<Milliseconds>(LogicalSessionCache::kLogicalSessionDefaultRefresh);

using SessionList = std::list<LogicalSessionId>;

/**
 * Test fixture that sets up a session cache attached to a mock service liason
 * and mock sessions collection implementation.
 */
class LogicalSessionCacheTest : public unittest::Test {
public:
    LogicalSessionCacheTest()
        : _service(std::make_shared<MockServiceLiasonImpl>()),
          _sessions(std::make_shared<MockSessionsCollectionImpl>()) {}

    void setUp() override {
        auto mockService = stdx::make_unique<MockServiceLiason>(_service);
        auto mockSessions = stdx::make_unique<MockSessionsCollection>(_sessions);
        _cache =
            stdx::make_unique<LogicalSessionCache>(std::move(mockService), std::move(mockSessions));
    }

    void tearDown() override {
        _service->join();
    }

    void waitUntilRefreshScheduled() {
        while (service()->jobs() < 2) {
            sleepmillis(10);
        }
    }

    std::unique_ptr<LogicalSessionCache>& cache() {
        return _cache;
    }

    std::shared_ptr<MockServiceLiasonImpl> service() {
        return _service;
    }

    std::shared_ptr<MockSessionsCollectionImpl> sessions() {
        return _sessions;
    }

private:
    std::shared_ptr<MockServiceLiasonImpl> _service;
    std::shared_ptr<MockSessionsCollectionImpl> _sessions;

    std::unique_ptr<LogicalSessionCache> _cache;
};

// Test that session cache fetches new records from the sessions collection
TEST_F(LogicalSessionCacheTest, CacheFetchesNewRecords) {
    auto signedLsid = SignedLogicalSessionId::gen();

    // When the record is not present (and not in the sessions collection) returns an error
    auto res = cache()->fetchAndPromote(signedLsid);
    ASSERT(!res.isOK());

    // When the record is not present (but is in the sessions collection) returns it
    sessions()->add(LogicalSessionRecord::makeAuthoritativeRecord(signedLsid, service()->now()));
    res = cache()->fetchAndPromote(signedLsid);
    ASSERT(res.isOK());

    // When the record is present in the cache, returns it
    sessions()->setFetchHook([](SignedLogicalSessionId id) -> StatusWith<LogicalSessionRecord> {
        // We should not be querying the sessions collection on the next call
        ASSERT(false);
        return {ErrorCodes::NoSuchSession, "no such session"};
    });

    res = cache()->fetchAndPromote(signedLsid);
    ASSERT(res.isOK());
}

// Test that the getFromCache method does not make calls to the sessions collection
TEST_F(LogicalSessionCacheTest, TestCacheHitsOnly) {
    auto signedLsid = SignedLogicalSessionId::gen();

    // When the record is not present (and not in the sessions collection), returns an error
    auto res = cache()->promote(signedLsid);
    ASSERT(!res.isOK());

    // When the record is not present (but is in the sessions collection), returns an error
    sessions()->add(LogicalSessionRecord::makeAuthoritativeRecord(signedLsid, service()->now()));
    res = cache()->promote(signedLsid);
    ASSERT(!res.isOK());

    // When the record is present, returns the owner
    cache()->fetchAndPromote(signedLsid).transitional_ignore();
    res = cache()->promote(signedLsid);
    ASSERT(res.isOK());
}

// Test that fetching from the cache updates the lastUse date of records
TEST_F(LogicalSessionCacheTest, FetchUpdatesLastUse) {
    auto signedLsid = SignedLogicalSessionId::gen();

    auto start = service()->now();

    // Insert the record into the sessions collection with 'start'
    sessions()->add(LogicalSessionRecord::makeAuthoritativeRecord(signedLsid, start));

    // Fast forward time and fetch
    service()->fastForward(Milliseconds(500));
    ASSERT(start != service()->now());
    auto res = cache()->fetchAndPromote(signedLsid);
    ASSERT(res.isOK());

    // Now that we fetched, lifetime of session should be extended
    service()->fastForward(kSessionTimeout - Milliseconds(500));
    res = cache()->fetchAndPromote(signedLsid);
    ASSERT(res.isOK());

    // We fetched again, so lifetime extended again
    service()->fastForward(kSessionTimeout - Milliseconds(10));
    res = cache()->fetchAndPromote(signedLsid);
    ASSERT(res.isOK());

    // Fast forward and hit-only fetch
    service()->fastForward(kSessionTimeout - Milliseconds(10));
    res = cache()->promote(signedLsid);
    ASSERT(res.isOK());

    // Lifetime extended again
    service()->fastForward(Milliseconds(11));
    res = cache()->promote(signedLsid);
    ASSERT(res.isOK());

    // Let record expire, we should not be able to get it from the cache
    service()->fastForward(kSessionTimeout + Milliseconds(1));
    res = cache()->promote(signedLsid);
    ASSERT(!res.isOK());
}

// Test the startSession method
TEST_F(LogicalSessionCacheTest, StartSession) {
    auto signedLsid = SignedLogicalSessionId::gen();

    // Test starting a new session
    auto res = cache()->startSession(signedLsid);
    ASSERT(res.isOK());
    ASSERT(sessions()->has(signedLsid.getLsid()));

    // Try to start a session that is already in the sessions collection and our
    // local cache, should fail
    res = cache()->startSession(signedLsid);
    ASSERT(!res.isOK());

    // Try to start a session that is already in the sessions collection but
    // is not in our local cache, should fail
    auto record2 = LogicalSessionRecord::makeAuthoritativeRecord(SignedLogicalSessionId::gen(),
                                                                 service()->now());
    auto signedLsid2 = record2.getSignedLsid();
    sessions()->add(std::move(record2));
    res = cache()->startSession(signedLsid2);
    ASSERT(!res.isOK());

    // Try to start a session that has expired from our cache, and is no
    // longer in the sessions collection, should succeed
    service()->fastForward(Milliseconds(kSessionTimeout.count() + 5));
    sessions()->remove(signedLsid.getLsid());
    ASSERT(!sessions()->has(signedLsid.getLsid()));
    res = cache()->startSession(signedLsid);
    ASSERT(res.isOK());
    ASSERT(sessions()->has(signedLsid.getLsid()));
}

// Test that records in the cache are properly refreshed until they expire
TEST_F(LogicalSessionCacheTest, CacheRefreshesOwnRecords) {
    // Insert two records into the cache
    auto signedLsid1 = SignedLogicalSessionId::gen();
    auto signedLsid2 = SignedLogicalSessionId::gen();
    cache()->startSession(signedLsid1).transitional_ignore();
    cache()->startSession(signedLsid2).transitional_ignore();

    stdx::promise<int> hitRefresh;
    auto refreshFuture = hitRefresh.get_future();

    // Advance time to first refresh point, check that refresh happens, and
    // that it includes both our records
    sessions()->setRefreshHook([&hitRefresh](LogicalSessionIdSet sessions) {
        hitRefresh.set_value(sessions.size());
        return LogicalSessionIdSet{};
    });

    // Wait for the refresh to happen
    service()->fastForward(kForceRefresh);
    refreshFuture.wait();
    ASSERT_EQ(refreshFuture.get(), 2);

    sessions()->clearHooks();

    stdx::promise<LogicalSessionId> refresh2;
    auto refresh2Future = refresh2.get_future();

    // Use one of the records
    auto res = cache()->fetchAndPromote(signedLsid1);
    ASSERT(res.isOK());

    // Advance time so that one record expires
    // Ensure that first record was refreshed, and second was thrown away
    sessions()->setRefreshHook([&refresh2](LogicalSessionIdSet sessions) {
        // We should only have one record here, the other should have expired
        ASSERT_EQ(sessions.size(), size_t(1));
        refresh2.set_value(*(sessions.begin()));
        return LogicalSessionIdSet{};
    });

    // Wait until the second job has been scheduled
    waitUntilRefreshScheduled();

    service()->fastForward(kSessionTimeout - kForceRefresh + Milliseconds(1));
    refresh2Future.wait();
    ASSERT_EQ(refresh2Future.get(), signedLsid1.getLsid());
}

// Test that cache deletes records that fail to refresh
TEST_F(LogicalSessionCacheTest, CacheDeletesRecordsThatFailToRefresh) {
    // Put two sessions into the cache
    auto signedLsid1 = SignedLogicalSessionId::gen();
    auto signedLsid2 = SignedLogicalSessionId::gen();
    cache()->startSession(signedLsid1).transitional_ignore();
    cache()->startSession(signedLsid2).transitional_ignore();

    stdx::promise<void> hitRefresh;
    auto refreshFuture = hitRefresh.get_future();

    // Record 1 fails to refresh
    sessions()->setRefreshHook([&hitRefresh, &signedLsid1](LogicalSessionIdSet sessions) {
        ASSERT_EQ(sessions.size(), size_t(2));
        hitRefresh.set_value();
        return LogicalSessionIdSet{signedLsid1.getLsid()};
    });

    // Force a refresh
    service()->fastForward(kForceRefresh);
    refreshFuture.wait();

    // Ensure that one record is still there and the other is gone
    auto res = cache()->promote(signedLsid1);
    ASSERT(!res.isOK());
    res = cache()->promote(signedLsid2);
    ASSERT(res.isOK());
}

// Test that we don't remove records that fail to refresh if they are active on the service
TEST_F(LogicalSessionCacheTest, KeepActiveSessionAliveEvenIfRefreshFails) {
    // Put two sessions into the cache, one into the service
    auto signedLsid1 = SignedLogicalSessionId::gen();
    auto signedLsid2 = SignedLogicalSessionId::gen();
    cache()->startSession(signedLsid1).transitional_ignore();
    service()->add(signedLsid1.getLsid());
    cache()->startSession(signedLsid2).transitional_ignore();

    stdx::promise<void> hitRefresh;
    auto refreshFuture = hitRefresh.get_future();

    // SignedLsid 1 fails to refresh
    sessions()->setRefreshHook([&hitRefresh, &signedLsid1](LogicalSessionIdSet sessions) {
        ASSERT_EQ(sessions.size(), size_t(2));
        hitRefresh.set_value();
        return LogicalSessionIdSet{signedLsid1.getLsid()};
    });

    // Force a refresh
    service()->fastForward(kForceRefresh);
    refreshFuture.wait();

    // Ensure that both signedLsids are still there
    auto res = cache()->promote(signedLsid1);
    ASSERT(res.isOK());
    res = cache()->promote(signedLsid2);
    ASSERT(res.isOK());
}

// Test that session cache properly expires signedLsids after 30 minutes of no use
TEST_F(LogicalSessionCacheTest, BasicSessionExpiration) {
    // Insert a signedLsid
    auto signedLsid = SignedLogicalSessionId::gen();
    cache()->startSession(signedLsid).transitional_ignore();
    auto res = cache()->promote(signedLsid);
    ASSERT(res.isOK());

    // Force it to expire
    service()->fastForward(Milliseconds(kSessionTimeout.count() + 5));

    // Check that it is no longer in the cache
    res = cache()->promote(signedLsid);
    ASSERT(!res.isOK());
}

// Test that we keep refreshing sessions that are active on the service
TEST_F(LogicalSessionCacheTest, LongRunningQueriesAreRefreshed) {
    auto signedLsid = SignedLogicalSessionId::gen();

    // Insert one active signedLsid on the service, none in the cache
    service()->add(signedLsid.getLsid());

    stdx::mutex mutex;
    stdx::condition_variable cv;
    int count = 0;

    sessions()->setRefreshHook([&cv, &mutex, &count, &signedLsid](LogicalSessionIdSet sessions) {
        ASSERT_EQ(*(sessions.begin()), signedLsid.getLsid());
        {
            stdx::unique_lock<stdx::mutex> lk(mutex);
            count++;
        }
        cv.notify_all();

        return LogicalSessionIdSet{};
    });

    // Force a refresh, it should refresh our active session
    service()->fastForward(kForceRefresh);
    {
        stdx::unique_lock<stdx::mutex> lk(mutex);
        cv.wait(lk, [&count] { return count == 1; });
    }

    // Wait until the next job has been scheduled
    waitUntilRefreshScheduled();

    // Force a session timeout, session is still on the service
    service()->fastForward(kSessionTimeout);
    {
        stdx::unique_lock<stdx::mutex> lk(mutex);
        cv.wait(lk, [&count] { return count == 2; });
    }

    // Wait until the next job has been scheduled
    waitUntilRefreshScheduled();

    // Force another refresh, check that it refreshes that active signedLsid again
    service()->fastForward(kForceRefresh);
    {
        stdx::unique_lock<stdx::mutex> lk(mutex);
        cv.wait(lk, [&count] { return count == 3; });
    }
}

// Test that the set of signedLsids we refresh is a sum of cached + active signedLsids
TEST_F(LogicalSessionCacheTest, RefreshCachedAndServiceSignedLsidsTogether) {
    // Put one session into the cache, one into the service
    auto signedLsid1 = SignedLogicalSessionId::gen();
    service()->add(signedLsid1.getLsid());
    auto signedLsid2 = SignedLogicalSessionId::gen();
    cache()->startSession(signedLsid2).transitional_ignore();

    stdx::promise<void> hitRefresh;
    auto refreshFuture = hitRefresh.get_future();

    // Both signedLsids refresh
    sessions()->setRefreshHook([&hitRefresh](LogicalSessionIdSet sessions) {
        ASSERT_EQ(sessions.size(), size_t(2));
        hitRefresh.set_value();
        return LogicalSessionIdSet{};
    });

    // Force a refresh
    service()->fastForward(kForceRefresh);
    refreshFuture.wait();
}

// Test large sets of cache-only session signedLsids
TEST_F(LogicalSessionCacheTest, ManySignedLsidsInCacheRefresh) {
    int count = LogicalSessionCache::kLogicalSessionCacheDefaultCapacity;
    for (int i = 0; i < count; i++) {
        auto signedLsid = SignedLogicalSessionId::gen();
        cache()->startSession(signedLsid).transitional_ignore();
    }

    stdx::promise<void> hitRefresh;
    auto refreshFuture = hitRefresh.get_future();

    // Check that all signedLsids refresh
    sessions()->setRefreshHook([&hitRefresh, &count](LogicalSessionIdSet sessions) {
        ASSERT_EQ(sessions.size(), size_t(count));
        hitRefresh.set_value();
        return LogicalSessionIdSet{};
    });

    // Force a refresh
    service()->fastForward(kForceRefresh);
    refreshFuture.wait();
}

// Test larger sets of service-only session signedLsids
TEST_F(LogicalSessionCacheTest, ManyLongRunningSessionsRefresh) {
    int count = LogicalSessionCache::kLogicalSessionCacheDefaultCapacity;
    for (int i = 0; i < count; i++) {
        auto lsid = LogicalSessionId::gen();
        service()->add(lsid);
    }

    stdx::promise<void> hitRefresh;
    auto refreshFuture = hitRefresh.get_future();

    // Check that all signedLsids refresh
    sessions()->setRefreshHook([&hitRefresh, &count](LogicalSessionIdSet sessions) {
        ASSERT_EQ(sessions.size(), size_t(count));
        hitRefresh.set_value();
        return LogicalSessionIdSet{};
    });

    // Force a refresh
    service()->fastForward(kForceRefresh);
    refreshFuture.wait();
}

// Test larger mixed sets of cache/service active sessions
TEST_F(LogicalSessionCacheTest, ManySessionsRefreshComboDeluxe) {
    int count = LogicalSessionCache::kLogicalSessionCacheDefaultCapacity;
    for (int i = 0; i < count; i++) {
        auto lsid = LogicalSessionId::gen();
        service()->add(lsid);

        auto lsid2 = SignedLogicalSessionId::gen();
        cache()->startSession(lsid2).transitional_ignore();
    }

    stdx::mutex mutex;
    stdx::condition_variable cv;
    int refreshes = 0;
    int nRefreshed = 0;

    // Check that all signedLsids refresh successfully
    sessions()->setRefreshHook(
        [&refreshes, &mutex, &cv, &nRefreshed](LogicalSessionIdSet sessions) {
            {
                stdx::unique_lock<stdx::mutex> lk(mutex);
                refreshes++;
                nRefreshed = sessions.size();
            }
            cv.notify_all();

            return LogicalSessionIdSet{};
        });

    // Force a refresh
    service()->fastForward(kForceRefresh);
    {
        stdx::unique_lock<stdx::mutex> lk(mutex);
        cv.wait(lk, [&refreshes] { return refreshes == 1; });
    }
    ASSERT_EQ(nRefreshed, count * 2);

    // Remove all of the service sessions, should just refresh the cache entries
    // (and make all but one fail to refresh)
    service()->clear();
    sessions()->setRefreshHook(
        [&refreshes, &mutex, &cv, &nRefreshed](LogicalSessionIdSet sessions) {
            {
                stdx::unique_lock<stdx::mutex> lk(mutex);
                refreshes++;
                nRefreshed = sessions.size();
            }
            cv.notify_all();

            sessions.erase(sessions.begin());
            return sessions;
        });

    // Wait for job to be scheduled
    waitUntilRefreshScheduled();

    // Force another refresh
    service()->fastForward(kForceRefresh);
    {
        stdx::unique_lock<stdx::mutex> lk(mutex);
        cv.wait(lk, [&refreshes] { return refreshes == 2; });
    }

    // We should not have refreshed any sessions from the service, only the cache
    ASSERT_EQ(nRefreshed, count);

    // Wait for job to be scheduled
    waitUntilRefreshScheduled();

    // Force a third refresh
    service()->fastForward(kForceRefresh);
    {
        stdx::unique_lock<stdx::mutex> lk(mutex);
        cv.wait(lk, [&refreshes] { return refreshes == 3; });
    }

    // Since all but one signedLsid failed to refresh, third set should just have one signedLsid
    ASSERT_EQ(nRefreshed, 1);
}

}  // namespace
}  // namespace mongo