summaryrefslogtreecommitdiff
path: root/jstests/libs/clustered_collections/clustered_capped_utils.js
blob: bbe9a71dde839b722ce6c26269a484886143f8e2 (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
var ClusteredCappedUtils = class {
    // Validate TTL-based deletion on a clustered, capped collection.
    static testClusteredCappedCollectionWithTTL(db, collName, clusterKeyField) {
        jsTest.log("Validating TTL operation on capped clustered collection");

        // Set expireAfterSeconds to a day to safely test that only expired documents are deleted.
        const expireAfterSeconds = 60 * 60 * 24;

        const clusterKey = {[clusterKeyField]: 1};
        const coll = db[collName];
        const now = new Date();
        const batchSize = 10;
        const clusterKeyFieldName = Object.keys(clusterKey)[0];

        coll.drop();

        assert.commandWorked(db.createCollection(
            coll.getName(),
            {clusteredIndex: {key: clusterKey, unique: true}, capped: true, expireAfterSeconds}));

        let docs = [];
        for (let i = batchSize; i; i--) {
            const tenTimesExpiredMs = 10 * expireAfterSeconds * 1000;
            const pastDate = new Date(now - tenTimesExpiredMs - i);
            docs.push({
                [clusterKeyFieldName]: pastDate,
                info: "expired",
            });
        }
        assert.commandWorked(coll.insertMany(docs, {ordered: true}));

        docs = [];
        for (let i = batchSize; i; i--) {
            const recentDate = new Date(now - i);
            docs.push({
                [clusterKeyFieldName]: recentDate,
                info: "unexpired",
            });
        }
        assert.commandWorked(coll.insertMany(docs, {ordered: true}));

        ClusteredCollectionUtil.waitForTTL(db);

        // Only the recent documents survived.
        assert.eq(coll.find().itcount(), batchSize);

        coll.drop();
    }

    static testClusteredTailableCursorCreation(db, collName, clusterKey, isReplicated) {
        jsTest.log(
            "Validating tailable cursor creation on capped clustered collection (isReplicated: " +
            isReplicated + ")");

        assert.commandWorked(db.createCollection(collName, {
            clusteredIndex: {key: {[clusterKey]: 1}, unique: true},
            capped: true,
            expireAfterSeconds: 10
        }));
        if (isReplicated) {
            // Must tail with read concern majority.
            assert.commandFailedWithCode(
                db.runCommand({find: collName, tailable: true, readConcern: {level: "local"}}),
                6049203);
            assert.commandFailedWithCode(
                db.runCommand({find: collName, tailable: true, readConcern: {level: "available"}}),
                6049203);
            assert.commandWorked(
                db.runCommand({find: collName, tailable: true, readConcern: {level: "majority"}}));
        } else {
            assert.commandWorked(
                db.runCommand({find: collName, tailable: true, readConcern: {level: "local"}}));
            assert.commandWorked(
                db.runCommand({find: collName, tailable: true, readConcern: {level: "available"}}));
        }
        db.getCollection(collName).drop();
    }

    // Validate tailable cursor operation along with TTL deletion.
    static testClusteredTailableCursorWithTTL(db, collName, clusterKey, isReplicated, awaitData) {
        jsTest.log(
            "Validating tailable cursor operation on capped clustered collection (isReplicated: " +
            isReplicated + ", awaitData: " + awaitData + ")");

        assert.commandWorked(db.adminCommand({setParameter: 1, ttlMonitorEnabled: false}));

        const oneDayInSeconds = 60 * 60 * 24;
        const oneHourInMilliseconds = 60 * 60 * 1000;
        const nineDaysInMilliseconds = 9 * oneDayInSeconds * 1000;
        const tenDaysInMilliseconds = 10 * oneDayInSeconds * 1000;

        const now = new Date();
        const oneHourAgo = new Date(now - oneHourInMilliseconds);
        const nineDaysAgo = new Date(now - nineDaysInMilliseconds);
        const tenDaysAgo = new Date(now - tenDaysInMilliseconds);

        // Create a clustered capped collection, and insert two old documents subject to imminent
        // TTL deletion, and two recent document which survive TTL deletion.

        assert.commandWorked(db.createCollection(collName, {
            clusteredIndex: {key: {[clusterKey]: 1}, unique: true},
            capped: true,
            expireAfterSeconds: oneDayInSeconds
        }));
        assert.commandWorked(
            db.getCollection(collName).insertOne({[clusterKey]: tenDaysAgo, info: "10 days ago"}));
        assert.commandWorked(
            db.getCollection(collName).insertOne({[clusterKey]: nineDaysAgo, info: "9 days ago"}));
        assert.commandWorked(db.getCollection(collName).insertOne(
            {[clusterKey]: oneHourAgo, info: "1 hour ago - surviving"}));
        assert.commandWorked(
            db.getCollection(collName).insertOne({[clusterKey]: now, info: "now - surviving"}));

        // Tail just past the first two documents, so the cursor can survive the upcoming TTL
        // deletion.
        let tailCommand = {find: collName, batchSize: 1, tailable: true, awaitData: awaitData};
        if (isReplicated) {
            tailCommand['readConcern'] = {level: "majority"};
        } else {
            tailCommand['readConcern'] = {level: "local"};
        }
        const tailable = db.runCommand(tailCommand);
        assert.commandWorked(tailable);
        const cursorId = tailable.cursor.id;
        assert(!bsonBinaryEqual({cursorId: cursorId}, {cursorId: NumberLong(0)}));
        assert.eq("10 days ago", tailable.cursor.firstBatch[0].info);

        {
            let getMore = db.runCommand({getMore: cursorId, collection: collName, batchSize: 1});
            assert.commandWorked(getMore);
            assert.eq("9 days ago", getMore.cursor.nextBatch[0].info);
        }
        {
            let getMore = db.runCommand({getMore: cursorId, collection: collName, batchSize: 1});
            assert.commandWorked(getMore);
            assert.eq("1 hour ago - surviving", getMore.cursor.nextBatch[0].info);
        }
        assert.eq(4, db.getCollection(collName).find().itcount());

        // TTL delete the two old documents.

        assert.commandWorked(db.adminCommand({setParameter: 1, ttlMonitorEnabled: true}));
        ClusteredCollectionUtil.waitForTTL(db);
        assert.eq(2, db.getCollection(collName).find().itcount());

        // Confirm that the tailable getMore can resume from where it was, since the document the
        // cursor is positioned on hasn't been TTL-removed.

        {
            let getMore = db.runCommand({getMore: cursorId, collection: collName, batchSize: 1});
            assert.commandWorked(getMore);
            assert.eq("now - surviving", getMore.cursor.nextBatch[0].info);
        }
        {
            let getMore = db.runCommand({getMore: cursorId, collection: collName});
            assert.commandWorked(getMore);
            assert.eq(0, getMore.cursor.nextBatch.length);
        }
        db.getCollection(collName).drop();
    }

    // Validate tailable cursor not keeping up with TTL deletion - CappedPositionLost.
    static testClusteredTailableCursorCappedPositionLostWithTTL(
        db, collName, clusterKey, isReplicated, awaitData) {
        jsTest.log(
            "Validating tailable cursor falling behind with TTL deletion on capped clustered collection (isReplicated: " +
            isReplicated + ", awaitData: " + awaitData + ")");

        assert.commandWorked(db.adminCommand({setParameter: 1, ttlMonitorEnabled: false}));

        const oneDayInSeconds = 60 * 60 * 24;
        const nineDaysInMilliseconds = 9 * oneDayInSeconds * 1000;
        const tenDaysInMilliseconds = 10 * oneDayInSeconds * 1000;

        const tenDaysAgo = new Date(new Date() - tenDaysInMilliseconds);
        const nineDaysAgo = new Date(new Date() - nineDaysInMilliseconds);
        const today = new Date();

        // Create a clustered capped collection, and insert two old documents subject to imminent
        // TTL deletion, and a recent document.

        assert.commandWorked(db.createCollection(collName, {
            clusteredIndex: {key: {[clusterKey]: 1}, unique: true},
            capped: true,
            expireAfterSeconds: oneDayInSeconds
        }));
        assert.commandWorked(
            db.getCollection(collName).insertOne({[clusterKey]: tenDaysAgo, info: "10 days ago"}));
        assert.commandWorked(
            db.getCollection(collName).insertOne({[clusterKey]: nineDaysAgo, info: "9 days ago"}));
        assert.commandWorked(
            db.getCollection(collName).insertOne({[clusterKey]: today, info: "today - surviving"}));

        // Tail up to and including the first document, before it gets TTL reaped.
        let tailCommand = {find: collName, batchSize: 1, tailable: true, awaitData: awaitData};
        if (isReplicated) {
            tailCommand['readConcern'] = {level: "majority"};
        } else {
            tailCommand['readConcern'] = {level: "local"};
        }
        const tailable = db.runCommand(tailCommand);
        assert.commandWorked(tailable);
        const cursorId = tailable.cursor.id;
        assert(!bsonBinaryEqual({cursorId: cursorId}, {cursorId: NumberLong(0)}));
        assert.eq("10 days ago", tailable.cursor.firstBatch[0].info);

        assert.eq(3, db.getCollection(collName).find().itcount());

        // TTL delete the two old documents, while the tailable cursor is still on the first one.

        assert.commandWorked(db.adminCommand({setParameter: 1, ttlMonitorEnabled: true}));
        ClusteredCollectionUtil.waitForTTL(db);
        assert.eq(1, db.getCollection(collName).find().itcount());

        // Confirm that the tailable cursor returns CappedPositionLost, as the document it was
        // pointing to has been TTL-deleted.

        let getMore = db.runCommand({getMore: cursorId, collection: collName, batchSize: 1});
        assert.commandFailedWithCode(getMore, 136);
        assert.eq(getMore.codeName, "CappedPositionLost");

        db.getCollection(collName).drop();
    }

    // Validate that by design, a cursor on a clustered capped collection can miss documents if they
    // are not inserted in cluster key order.
    static testClusteredTailableCursorOutOfOrderInsertion(
        db, collName, clusterKey, isReplicated, awaitData) {
        jsTest.log(
            "Validating clustered tailable cursor with out-of-order insertions (isReplicated: " +
            isReplicated + ", awaitData: " + awaitData + ")");

        assert.commandWorked(db.adminCommand({setParameter: 1, ttlMonitorEnabled: false}));

        const oneDayInSeconds = 60 * 60 * 24;
        const oneMinuteAgo = new Date(new Date() - 60 * 1000);
        const now = new Date();

        // Create a clustered capped collection and insert a document with a cluster key value equal
        // to now.
        assert.commandWorked(db.createCollection(collName, {
            clusteredIndex: {key: {[clusterKey]: 1}, unique: true},
            capped: true,
            expireAfterSeconds: oneDayInSeconds
        }));
        assert.commandWorked(
            db.getCollection(collName).insertOne({[clusterKey]: now, info: "now"}));

        // Create a tailable cursor and fetch the document inserted.

        let tailCommand = {find: collName, batchSize: 1, tailable: true, awaitData: awaitData};
        if (isReplicated) {
            tailCommand['readConcern'] = {level: "majority"};
        } else {
            tailCommand['readConcern'] = {level: "local"};
        }
        const tailable = db.runCommand(tailCommand);
        assert.commandWorked(tailable);
        const cursorId = tailable.cursor.id;
        assert(!bsonBinaryEqual({cursorId: cursorId}, {cursorId: NumberLong(0)}));
        assert.eq("now", tailable.cursor.firstBatch[0].info);

        // Now insert a document with a cluster key value equal to a minute ago, and verify
        // that the tailable cursor is unable to fetch it.
        assert.commandWorked(db.getCollection(collName).insertOne(
            {[clusterKey]: oneMinuteAgo, info: "1 minute ago"}));

        const getMore = db.runCommand({getMore: cursorId, collection: collName, batchSize: 1});
        assert.commandWorked(getMore);
        assert.eq(0, getMore.cursor.nextBatch.length);

        db.getCollection(collName).drop();
    }

    static testClusteredReplicatedTTLDeletion(db, collName) {
        jsTest.log("Validating replication of TTL deletes on capped clustered collection");

        assert.commandWorked(db.adminCommand({setParameter: 1, ttlMonitorEnabled: false}));

        const oneDayInSeconds = 60 * 60 * 24;
        const tenDaysInMilliseconds = 10 * oneDayInSeconds * 1000;
        const tenDaysAgo = new Date(new Date() - tenDaysInMilliseconds);
        const earlierTenDaysAgo = new Date(tenDaysAgo.getTime - 1);

        // Create clustered capped collection and insert soon-to-be-expired documents.
        assert.commandWorked(db.createCollection(collName, {
            clusteredIndex: {key: {_id: 1}, unique: true},
            capped: true,
            expireAfterSeconds: oneDayInSeconds
        }));
        assert.commandWorked(db.getCollection(collName).insertMany([
            {_id: tenDaysAgo, info: "10 days ago"},
            {_id: earlierTenDaysAgo, info: "10 days ago"}
        ]));
        assert.eq(2, db.getCollection(collName).find().itcount());

        // Expire the documents.
        assert.commandWorked(db.adminCommand({setParameter: 1, ttlMonitorEnabled: true}));
        ClusteredCollectionUtil.waitForTTL(db);
        assert.eq(0, db.getCollection(collName).find().itcount());

        // The TTL deletion has been replicated to the oplog.
        const isBatched = assert.commandWorked(db.adminCommand(
            {getParameter: 1, "ttlMonitorBatchDeletes": 1}))["ttlMonitorBatchDeletes"];
        const ns = db.getName() + "." + collName;

        const featureFlagBatchMultiDeletes = assert.commandWorked(db.adminCommand({
            getParameter: 1,
            "featureFlagBatchMultiDeletes": 1
        }))["featureFlagBatchMultiDeletes"]["value"];

        if (featureFlagBatchMultiDeletes && isBatched) {
            const ops =
                db.getSiblingDB("local")
                    .oplog.rs
                    .find({
                        op: "c",
                        ns: "admin.$cmd",
                        "o.applyOps": {
                            $elemMatch:
                                {op: "d", ns: ns, "o._id": {$in: [tenDaysAgo, earlierTenDaysAgo]}}
                        }
                    })
                    .sort({$natural: -1})
                    .limit(1)
                    .toArray();
            assert.eq(2, ops[0].o.applyOps.length);
        } else {
            assert.eq(1,
                      db.getSiblingDB("local")
                          .oplog.rs.find({op: "d", ns: ns, "o._id": tenDaysAgo})
                          .itcount());
            assert.eq(1,
                      db.getSiblingDB("local")
                          .oplog.rs.find({op: "d", ns: ns, "o._id": earlierTenDaysAgo})
                          .itcount());
        }

        db.getCollection(collName).drop();
    }
};