summaryrefslogtreecommitdiff
path: root/jstests/change_streams/resume_from_high_water_mark_token.js
blob: edd34db162b560fcc8be4bd6542a7d0c7f5a164f (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
/**
 * Tests that a synthetic high-water-mark (HWM) token obeys the same semantics as a regular token.
 */
(function() {
"use strict";

load("jstests/libs/collection_drop_recreate.js");  // For assert[Drop|Create]Collection.
load("jstests/libs/change_stream_util.js");        // For runCommandChangeStreamPassthroughAware.

// Drop the test collections to assure a clean run.
const collName = jsTestName();
const otherCollName = "unrelated_" + collName;
assertDropCollection(db, collName);
assertDropCollection(db, otherCollName);

// Helper function to ensure that the specified command is not modified by the passthroughs.
function runExactCommand(db, cmdObj) {
    const doNotModifyInPassthroughs = true;
    return runCommandChangeStreamPassthroughAware(db, cmdObj, doNotModifyInPassthroughs);
}

let docId = 0;  // Tracks _id of documents inserted to ensure that we do not duplicate.

// Open a stream on the test collection, before the collection has actually been created. Make
// sure that this command is not modified in the passthroughs, since this behaviour is only
// relevant for single-collection streams.
let cmdResBeforeCollExists = assert.commandWorked(
    runExactCommand(db, {aggregate: collName, pipeline: [{$changeStream: {}}], cursor: {}}));

// We should be able to retrieve a postBatchResumeToken (PBRT) even with no collection present.
let csCursor = new DBCommandCursor(db, cmdResBeforeCollExists);
let pbrtBeforeCollExists = csCursor.getResumeToken();
assert.neq(undefined, pbrtBeforeCollExists);
csCursor.close();

// We can resumeAfter and startAfter the token while the collection still does not exist.
for (let resumeType of ["startAfter", "resumeAfter"]) {
    cmdResBeforeCollExists = assert.commandWorked(runExactCommand(db, {
        aggregate: collName,
        pipeline: [
            {$changeStream: {[resumeType]: pbrtBeforeCollExists}},
            {
                $match:
                    {$or: [{"fullDocument._id": "INSERT_ONE"}, {"fullDocument._id": "INSERT_TWO"}]}
            }
        ],
        cursor: {}
    }));
}
csCursor = new DBCommandCursor(db, cmdResBeforeCollExists);

// If the collection is then created with a case-insensitive collation, the resumed stream
// continues to use the simple collation. We see 'INSERT_TWO' but not 'insert_one'.
const testCollationCollection =
    assertCreateCollection(db, collName, {collation: {locale: "en_US", strength: 2}});
assert.commandWorked(testCollationCollection.insert({_id: "insert_one"}));
assert.commandWorked(testCollationCollection.insert({_id: "INSERT_TWO"}));
assert.soon(() => csCursor.hasNext());
assert.docEq(csCursor.next().fullDocument, {_id: "INSERT_TWO"});
csCursor.close();

// We can resume from the pre-creation high water mark if we do not specify a collation...
let cmdResResumeFromBeforeCollCreated = assert.commandWorked(runExactCommand(db, {
    aggregate: collName,
    pipeline: [
        {$changeStream: {resumeAfter: pbrtBeforeCollExists}},
        {$match: {$or: [{"fullDocument._id": "INSERT_ONE"}, {"fullDocument._id": "INSERT_TWO"}]}}
    ],
    cursor: {}
}));

// ... but we will not inherit the collection's case-insensitive collation, instead defaulting
// to the simple collation. We will therefore match 'INSERT_TWO' but not 'insert_one'.
csCursor = new DBCommandCursor(db, cmdResResumeFromBeforeCollCreated);
assert.soon(() => csCursor.hasNext());
assert.docEq(csCursor.next().fullDocument, {_id: "INSERT_TWO"});
csCursor.close();

// If we do specify a non-simple collation, it will be adopted by the pipeline.
cmdResResumeFromBeforeCollCreated = assert.commandWorked(runExactCommand(db, {
    aggregate: collName,
    pipeline: [
        {$changeStream: {resumeAfter: pbrtBeforeCollExists}},
        {$match: {$or: [{"fullDocument._id": "INSERT_ONE"}, {"fullDocument._id": "INSERT_TWO"}]}}
    ],
    collation: {locale: "en_US", strength: 2},
    cursor: {}
}));

// Now we match both 'insert_one' and 'INSERT_TWO'.
csCursor = new DBCommandCursor(db, cmdResResumeFromBeforeCollCreated);
assert.soon(() => csCursor.hasNext());
assert.docEq(csCursor.next().fullDocument, {_id: "insert_one"});
assert.soon(() => csCursor.hasNext());
assert.docEq(csCursor.next().fullDocument, {_id: "INSERT_TWO"});
csCursor.close();

// Now open a change stream with batchSize:0 in order to produce a new high water mark.
const cmdResCollWithCollation = assert.commandWorked(runExactCommand(db, {
    aggregate: collName,
    pipeline: [
        {$changeStream: {}},
    ],
    cursor: {batchSize: 0}
}));
csCursor = new DBCommandCursor(db, cmdResCollWithCollation);
const hwmFromCollWithCollation = csCursor.getResumeToken();
assert.neq(undefined, hwmFromCollWithCollation);
csCursor.close();

// Insert two more documents into the collection for testing purposes.
assert.commandWorked(testCollationCollection.insert({_id: "insert_three"}));
assert.commandWorked(testCollationCollection.insert({_id: "INSERT_FOUR"}));

// We can resume the stream on the collection using the HWM...
const cmdResResumeWithCollation = assert.commandWorked(runExactCommand(db, {
    aggregate: collName,
    pipeline: [
        {$changeStream: {resumeAfter: hwmFromCollWithCollation}},
        {$match: {$or: [{"fullDocument._id": "INSERT_THREE"}, {"fullDocument._id": "INSERT_FOUR"}]}}
    ],
    cursor: {}
}));
csCursor = new DBCommandCursor(db, cmdResResumeWithCollation);

// ... but we do not inherit the collection's case-insensitive collation, matching 'INSERT_FOUR'
// but not the preceding 'insert_three'.
assert.soon(() => csCursor.hasNext());
assert.docEq(csCursor.next().fullDocument, {_id: "INSERT_FOUR"});
csCursor.close();

// Drop the collection and obtain a new pre-creation high water mark. We will use this later.
assertDropCollection(db, collName);
cmdResBeforeCollExists = assert.commandWorked(
    runExactCommand(db, {aggregate: collName, pipeline: [{$changeStream: {}}], cursor: {}}));
csCursor = new DBCommandCursor(db, cmdResBeforeCollExists);
pbrtBeforeCollExists = csCursor.getResumeToken();
assert.neq(undefined, pbrtBeforeCollExists);
csCursor.close();

// Now create each of the test collections with the default simple collation.
const testCollection = assertCreateCollection(db, collName);
const otherCollection = assertCreateCollection(db, otherCollName);
const adminDB = db.getSiblingDB("admin");

// Open a stream on the test collection, and write a document to it.
csCursor = testCollection.watch();
assert.commandWorked(testCollection.insert({_id: docId++}));

// Write an event to the unrelated collection in order to advance the PBRT, and then consume all
// events. When we see a PBRT that is greater than the timestamp of the last event (stored in
// 'relatedEvent'), we know it must be a synthetic high-water-mark token.
//
// Note that the first insert into the unrelated collection may not be enough to advance the
// PBRT; some passthroughs will group the unrelated write into a transaction with the related
// write, giving them the same timestamp. We put the unrelated insert into the assert.soon loop,
// so that it will eventually get its own transaction with a new timestamp.
let relatedEvent = null;
let hwmToken = null;
assert.soon(() => {
    assert.commandWorked(otherCollection.insert({}));
    if (csCursor.hasNext()) {
        relatedEvent = csCursor.next();
    }
    assert.eq(csCursor.objsLeftInBatch(), 0);
    hwmToken = csCursor.getResumeToken();
    assert.neq(undefined, hwmToken);
    return relatedEvent && bsonWoCompare(hwmToken, relatedEvent._id) > 0;
});
csCursor.close();

// Now write some further documents to the collection before attempting to resume.
for (let i = 0; i < 5; ++i) {
    assert.commandWorked(testCollection.insert({_id: docId++}));
}

// We can resumeAfter and startAfter the high water mark. We only see the latest 5 documents.
for (let resumeType of ["startAfter", "resumeAfter"]) {
    csCursor = testCollection.watch([], {[resumeType]: hwmToken});
    assert.soon(() => {
        if (csCursor.hasNext()) {
            relatedEvent = csCursor.next();
            assert.gt(bsonWoCompare(relatedEvent._id, hwmToken), 0);
            // We never see the first document, whose _id was 0.
            assert.gt(relatedEvent.fullDocument._id, 0);
        }
        // The _id of the last document inserted is (docId-1).
        return relatedEvent.fullDocument._id === (docId - 1);
    });
    csCursor.close();
}

// Now resumeAfter the token that was generated before the collection was created...
cmdResResumeFromBeforeCollCreated = assert.commandWorked(runExactCommand(db, {
    aggregate: collName,
    pipeline: [{$changeStream: {resumeAfter: pbrtBeforeCollExists}}],
    cursor: {}
}));
// ... and confirm that we see all the events that have occurred since then.
csCursor = new DBCommandCursor(db, cmdResResumeFromBeforeCollCreated);
let docCount = 0;
assert.soon(() => {
    if (csCursor.hasNext()) {
        relatedEvent = csCursor.next();
        assert.eq(relatedEvent.fullDocument._id, docCount++);
    }
    return docCount === docId;
});

// Despite the fact that we just resumed from a token which was generated before the collection
// existed and had no UUID, all subsequent HWMs should now have UUIDs. To test this, we first
// get the current resume token, then write a document to the unrelated collection. We then wait
// until the PBRT advances, which means that we now have a new HWM token.
let hwmPostCreation = csCursor.getResumeToken();
assert.commandWorked(otherCollection.insert({}));
assert.soon(() => {
    assert(!csCursor.hasNext());
    return bsonWoCompare(csCursor.getResumeToken(), hwmPostCreation) > 0;
});
hwmPostCreation = csCursor.getResumeToken();
csCursor.close();

// We can resume from the token if the collection is dropped...
assertDropCollection(db, collName);
assert.commandWorked(runExactCommand(db, {
    aggregate: collName,
    pipeline: [{$changeStream: {resumeAfter: hwmPostCreation}}],
    cursor: {}
}));
// ... or if the collection is recreated with a different UUID...
assertCreateCollection(db, collName);
assert.commandWorked(runExactCommand(db, {
    aggregate: collName,
    pipeline: [{$changeStream: {resumeAfter: hwmPostCreation}}],
    cursor: {}
}));
// ... or if we specify an explicit collation.
assert.commandWorked(runExactCommand(db, {
    aggregate: collName,
    pipeline: [{$changeStream: {resumeAfter: hwmPostCreation}}],
    collation: {locale: "simple"},
    cursor: {}
}));

// Even after the collection is recreated, we can still resume from the pre-creation HWM...
cmdResResumeFromBeforeCollCreated = assert.commandWorked(runExactCommand(db, {
    aggregate: collName,
    pipeline: [{$changeStream: {resumeAfter: pbrtBeforeCollExists}}],
    cursor: {}
}));
// ...and we can still see all the events from the collection's original incarnation...
csCursor = new DBCommandCursor(db, cmdResResumeFromBeforeCollCreated);
docCount = 0;
assert.soon(() => {
    if (csCursor.hasNext()) {
        relatedEvent = csCursor.next();
        assert.eq(relatedEvent.fullDocument._id, docCount++);
    }
    return docCount === docId;
});
// ... this time followed by an invalidate, as the collection is dropped.
assert.soon(() => {
    return csCursor.hasNext() && csCursor.next().operationType === "invalidate";
});
csCursor.close();
})();