summaryrefslogtreecommitdiff
path: root/jstests/sharding/change_streams.js
blob: 97129044f652a8497e495abbe34c6b65ce5e72d1 (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
// Tests the behavior of change streams on sharded collections.
// @tags: [uses_change_streams, requires_majority_read_concern]
(function() {
"use strict";

load('jstests/replsets/libs/two_phase_drops.js');  // For TwoPhaseDropCollectionTest.
load('jstests/aggregation/extras/utils.js');       // For assertErrorCode().
load('jstests/libs/change_stream_util.js');        // For assertChangeStreamEventEq.

function runTest(collName, shardKey) {
    const st = new ShardingTest({
        shards: 2,
        rs: {
            nodes: 1,
            enableMajorityReadConcern: '',
            // Intentionally disable the periodic no-op writer in order to allow the test have
            // control of advancing the cluster time. For when it is enabled later in the test,
            // use a higher frequency for periodic noops to speed up the test.
            setParameter: {periodicNoopIntervalSecs: 1, writePeriodicNoops: false}
        }
    });

    const mongosDB = st.s0.getDB(jsTestName());
    assert.commandWorked(st.s0.adminCommand({enableSharding: mongosDB.getName()}));
    st.ensurePrimaryShard(mongosDB.getName(), st.shard0.shardName);

    const mongosColl = mongosDB[collName];

    //
    // Test that the config server is running with {periodicNoopIntervalSecs: 1}. This ensures that
    // the config server does not unduly delay a change stream despite its low write rate.
    //
    const noopPeriod = assert.commandWorked(
        st.configRS.getPrimary().adminCommand({getParameter: 1, periodicNoopIntervalSecs: 1}));
    assert.eq(noopPeriod.periodicNoopIntervalSecs, 1, noopPeriod);

    //
    // Sanity tests
    //

    // Test that $sort and $group are banned from running in a $changeStream pipeline.
    assertErrorCode(mongosDB.NegativeTest,
                    [{$changeStream: {}}, {$sort: {operationType: 1}}],
                    ErrorCodes.IllegalOperation);
    assertErrorCode(mongosDB.NegativeTest,
                    [{$changeStream: {}}, {$group: {_id: '$documentKey'}}],
                    ErrorCodes.IllegalOperation);

    // Test that using change streams with $out results in an error.
    assertErrorCode(
        mongosColl, [{$changeStream: {}}, {$out: "shouldntWork"}], ErrorCodes.IllegalOperation);

    //
    // Main tests
    //

    function makeShardKey(value) {
        var obj = {};
        obj[shardKey] = value;
        return obj;
    }

    function makeShardKeyDocument(value, optExtraFields) {
        var obj = {};
        if (shardKey !== '_id')
            obj['_id'] = value;
        obj[shardKey] = value;
        return Object.assign(obj, optExtraFields);
    }

    jsTestLog('Testing change streams with shard key ' + shardKey);
    // Shard the test collection and split it into 2 chunks:
    //  [MinKey, 0) - shard0, [0, MaxKey) - shard1
    st.shardColl(mongosColl,
                 makeShardKey(1) /* shard key */,
                 makeShardKey(0) /* split at */,
                 makeShardKey(1) /* move to shard 1 */);

    // Write a document to each chunk.
    assert.commandWorked(mongosColl.insert(makeShardKeyDocument(-1)));
    assert.commandWorked(mongosColl.insert(makeShardKeyDocument(1)));

    let changeStream = mongosColl.aggregate([{$changeStream: {}}]);

    // Test that a change stream can see inserts on shard 0.
    assert.commandWorked(mongosColl.insert(makeShardKeyDocument(1000)));
    assert.commandWorked(mongosColl.insert(makeShardKeyDocument(-1000)));

    assert.soon(() => changeStream.hasNext(), "expected to be able to see the first insert");
    assertChangeStreamEventEq(changeStream.next(), {
        documentKey: makeShardKeyDocument(1000),
        fullDocument: makeShardKeyDocument(1000),
        ns: {db: mongosDB.getName(), coll: mongosColl.getName()},
        operationType: "insert",
    });

    // Because the periodic noop writer is disabled, do another write to shard 0 in order to
    // advance that shard's clock and enabling the stream to return the earlier write to shard 1
    assert.commandWorked(mongosColl.insert(makeShardKeyDocument(1001)));

    assert.soon(() => changeStream.hasNext(), "expected to be able to see the second insert");
    assertChangeStreamEventEq(changeStream.next(), {
        documentKey: makeShardKeyDocument(-1000),
        fullDocument: makeShardKeyDocument(-1000),
        ns: {db: mongosDB.getName(), coll: mongosColl.getName()},
        operationType: "insert",
    });

    // Test that all changes are eventually visible due to the periodic noop writer.
    assert.commandWorked(
        st.rs0.getPrimary().adminCommand({setParameter: 1, writePeriodicNoops: true}));
    assert.commandWorked(
        st.rs1.getPrimary().adminCommand({setParameter: 1, writePeriodicNoops: true}));

    assert.soon(() => changeStream.hasNext());
    assertChangeStreamEventEq(changeStream.next(), {
        documentKey: makeShardKeyDocument(1001),
        fullDocument: makeShardKeyDocument(1001),
        ns: {db: mongosDB.getName(), coll: mongosColl.getName()},
        operationType: "insert",
    });
    changeStream.close();

    jsTestLog('Testing multi-update change streams with shard key ' + shardKey);
    assert.commandWorked(mongosColl.insert(makeShardKeyDocument(10, {a: 0, b: 0})));
    assert.commandWorked(mongosColl.insert(makeShardKeyDocument(-10, {a: 0, b: 0})));
    changeStream = mongosColl.aggregate([{$changeStream: {}}]);

    assert.commandWorked(mongosColl.update({a: 0}, {$set: {b: 2}}, {multi: true}));

    const expectedEvent1 = {
        operationType: "update",
        ns: {db: mongosDB.getName(), coll: mongosColl.getName()},
        documentKey: makeShardKeyDocument(-10),
        updateDescription: {updatedFields: {b: 2}, removedFields: [], truncatedArrays: []},
    };

    const expectedEvent2 = {
        operationType: "update",
        ns: {db: mongosDB.getName(), coll: mongosColl.getName()},
        documentKey: makeShardKeyDocument(10),
        updateDescription: {updatedFields: {b: 2}, removedFields: [], truncatedArrays: []},
    };

    // The multi-update events can be observed in any order, depending on the clusterTime at which
    // they are written on each shard.
    const expectedEvents = [expectedEvent1, expectedEvent2];

    const actualEvents = [];
    for (let expectedEvent of expectedEvents) {
        assert.soon(() => changeStream.hasNext());
        const actualEvent = changeStream.next();
        actualEvents.push(canonicalizeEventForTesting(actualEvent, expectedEvent));
    }
    changeStream.close();

    assert.sameMembers(actualEvents, expectedEvents);

    // Test that it is legal to open a change stream, even if the
    // 'internalQueryProhibitMergingOnMongos' parameter is set.
    assert.commandWorked(
        st.s0.adminCommand({setParameter: 1, internalQueryProhibitMergingOnMongoS: true}));
    let tempCursor = assert.doesNotThrow(() => mongosColl.aggregate([{$changeStream: {}}]));
    tempCursor.close();
    assert.commandWorked(
        st.s0.adminCommand({setParameter: 1, internalQueryProhibitMergingOnMongoS: false}));

    assert.commandWorked(mongosColl.remove({}));
    // We awaited the replication of the first write, so the change stream shouldn't return it.
    // Use { w: "majority" } to deal with journaling correctly, even though we only have one
    // node.
    assert.commandWorked(
        mongosColl.insert(makeShardKeyDocument(0, {a: 1}), {writeConcern: {w: "majority"}}));

    changeStream = mongosColl.aggregate([{$changeStream: {}}]);
    assert(!changeStream.hasNext());

    // Drop the collection and test that we return a "drop" followed by an "invalidate" entry
    // and close the cursor.
    jsTestLog('Testing getMore command closes cursor for invalidate entries with shard key' +
              shardKey);
    mongosColl.drop();
    // Wait for the drop to actually happen.
    assert.soon(() => !TwoPhaseDropCollectionTest.collectionIsPendingDropInDatabase(
                    mongosColl.getDB(), mongosColl.getName()));
    assert.soon(() => changeStream.hasNext());
    assert.eq(changeStream.next().operationType, "drop");
    assert.soon(() => changeStream.hasNext());
    assert.eq(changeStream.next().operationType, "invalidate");
    assert(changeStream.isExhausted());

    jsTestLog('Testing aggregate command closes cursor for invalidate entries with shard key' +
              shardKey);
    // Shard the test collection and split it into 2 chunks:
    //  [MinKey, 0) - shard0, [0, MaxKey) - shard1
    st.shardColl(mongosColl,
                 makeShardKey(1) /* shard key */,
                 makeShardKey(0) /* split at */,
                 makeShardKey(1) /* move to shard 1 */);

    // Write one document to each chunk.
    assert.commandWorked(
        mongosColl.insert(makeShardKeyDocument(-1), {writeConcern: {w: "majority"}}));
    assert.commandWorked(
        mongosColl.insert(makeShardKeyDocument(1), {writeConcern: {w: "majority"}}));

    changeStream = mongosColl.aggregate([{$changeStream: {}}]);
    assert(!changeStream.hasNext());

    // Store a valid resume token before dropping the collection, to be used later in the test
    assert.commandWorked(
        mongosColl.insert(makeShardKeyDocument(-2), {writeConcern: {w: "majority"}}));
    assert.commandWorked(
        mongosColl.insert(makeShardKeyDocument(2), {writeConcern: {w: "majority"}}));

    assert.soon(() => changeStream.hasNext());
    const resumeToken = changeStream.next()._id;

    mongosColl.drop();

    assert.soon(() => changeStream.hasNext());
    assertChangeStreamEventEq(changeStream.next(), {
        documentKey: makeShardKeyDocument(2),
        fullDocument: makeShardKeyDocument(2),
        ns: {db: mongosDB.getName(), coll: mongosColl.getName()},
        operationType: "insert",
    });

    assert.soon(() => changeStream.hasNext());
    assert.eq(changeStream.next().operationType, "drop");

    assert.soon(() => changeStream.hasNext());
    assert.eq(changeStream.next().operationType, "invalidate");

    // With an explicit collation, test that we can resume from before the collection drop
    changeStream = mongosColl.watch([], {resumeAfter: resumeToken, collation: {locale: "simple"}});

    assert.soon(() => changeStream.hasNext());
    assertChangeStreamEventEq(changeStream.next(), {
        documentKey: makeShardKeyDocument(2),
        fullDocument: makeShardKeyDocument(2),
        ns: {db: mongosDB.getName(), coll: mongosColl.getName()},
        operationType: "insert",
    });

    assert.soon(() => changeStream.hasNext());
    assert.eq(changeStream.next().operationType, "drop");

    assert.soon(() => changeStream.hasNext());
    assert.eq(changeStream.next().operationType, "invalidate");

    // Test that we can resume from before the collection drop without an explicit collation.
    assert.commandWorked(mongosDB.runCommand({
        aggregate: mongosColl.getName(),
        pipeline: [{$changeStream: {resumeAfter: resumeToken}}],
        cursor: {}
    }));

    st.stop();
}

runTest('with_id_shard_key', '_id');
runTest('with_non_id_shard_key', 'non_id');
})();