-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathchange_stream.test.ts
2775 lines (2363 loc) · 95 KB
/
change_stream.test.ts
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { strict as assert } from 'assert';
import { expect } from 'chai';
import { on, once } from 'events';
import { gte, lt } from 'semver';
import * as sinon from 'sinon';
import { PassThrough } from 'stream';
import { setTimeout } from 'timers';
import {
AbstractCursor,
type ChangeStream,
type ChangeStreamOptions,
type Collection,
type CommandStartedEvent,
type Db,
isHello,
Long,
MongoAPIError,
MongoChangeStreamError,
type MongoClient,
MongoServerError,
ReadPreference,
type ResumeToken
} from '../../mongodb';
import * as mock from '../../tools/mongodb-mock/index';
import {
type FailPoint,
getSymbolFrom,
sleep,
TestBuilder,
UnifiedTestSuiteBuilder
} from '../../tools/utils';
import { delay, filterForCommands } from '../shared';
const initIteratorMode = async (cs: ChangeStream) => {
const kInit = getSymbolFrom(AbstractCursor.prototype, 'kInit');
const initEvent = once(cs.cursor, 'init');
await cs.cursor[kInit]();
await initEvent;
return;
};
const is4_2Server = (serverVersion: string) =>
gte(serverVersion, '4.2.0') && lt(serverVersion, '4.3.0');
// Define the pipeline processing changes
const pipeline = [
{ $addFields: { addedField: 'This is a field added using $addFields' } },
{ $project: { documentKey: false } },
{ $addFields: { comment: 'The documentKey field has been projected out of this document.' } }
];
describe('Change Streams', function () {
let client: MongoClient;
let collection: Collection;
let changeStream: ChangeStream;
let db: Db;
beforeEach(async function () {
const configuration = this.configuration;
client = configuration.newClient();
await client.connect();
db = client.db('integration_tests');
await db.createCollection('test').catch(() => null);
const csDb = client.db('changestream_integration_test');
await csDb.dropDatabase().catch(() => null);
await csDb.createCollection('test').catch(() => null);
collection = csDb.collection('test');
changeStream = collection.watch();
});
afterEach(async () => {
sinon.restore();
await changeStream.close();
await client.close();
await mock.cleanup();
});
context('ChangeStreamCursor options', function () {
let client, db, collection;
beforeEach(function () {
client = this.configuration.newClient();
db = client.db('db');
collection = db.collection('collection');
});
afterEach(async function () {
await client.close();
client = undefined;
db = undefined;
collection = undefined;
});
context('fullDocument', () => {
it('does not set fullDocument if no value is provided', function () {
const changeStream = client.watch();
expect(changeStream).not.to.have.nested.property(
'cursor.pipeline[0].$changeStream.fullDocument'
);
});
it('does not validate the value passed in for the fullDocument property', function () {
const changeStream = client.watch([], { fullDocument: 'invalid value' });
expect(changeStream).to.have.nested.property(
'cursor.pipeline[0].$changeStream.fullDocument',
'invalid value'
);
});
it('assigns fullDocument to the correct value if it is passed as an option', function () {
const changeStream = client.watch([], { fullDocument: 'updateLookup' });
expect(changeStream).to.have.nested.property(
'cursor.pipeline[0].$changeStream.fullDocument',
'updateLookup'
);
});
});
context('allChangesForCluster', () => {
it('assigns allChangesForCluster to true if the ChangeStream.type is Cluster', function () {
const changeStream = client.watch();
expect(changeStream).to.have.nested.property(
'cursor.pipeline[0].$changeStream.allChangesForCluster',
true
);
});
it('does not assign allChangesForCluster if the ChangeStream.type is Db', function () {
const changeStream = db.watch();
expect(changeStream).not.to.have.nested.property(
'cursor.pipeline[0].$changeStream.allChangesForCluster'
);
});
it('does not assign allChangesForCluster if the ChangeStream.type is Collection', function () {
const changeStream = collection.watch();
expect(changeStream).not.to.have.nested.property(
'cursor.pipeline[0].$changeStream.allChangesForCluster'
);
});
});
it('ignores any invalid option values', function () {
const changeStream = collection.watch([], { invalidOption: true });
expect(changeStream).not.to.have.nested.property(
'cursor.pipeline[0].$changeStream.invalidOption'
);
});
});
it('should close the listeners after the cursor is closed', {
metadata: { requires: { topology: 'replicaset' } },
async test() {
const collection = db.collection('closesListeners');
const changeStream = collection.watch(pipeline);
const willBeChanges = on(changeStream, 'change');
await once(changeStream.cursor, 'init');
await collection.insertOne({ a: 1 });
await willBeChanges.next();
expect(changeStream.cursorStream?.listenerCount('data')).to.equal(1);
await changeStream.close();
expect(changeStream.cursorStream).to.not.exist;
}
});
it('should create a ChangeStream on a collection and emit change events', {
metadata: { requires: { topology: 'replicaset' } },
async test() {
const collection = db.collection('docsDataEvent');
const changeStream = collection.watch(pipeline);
const willBeChanges = on(changeStream, 'change');
await once(changeStream.cursor, 'init');
await collection.insertOne({ d: 4 });
await collection.updateOne({ d: 4 }, { $inc: { d: 2 } });
const changes = [
(await willBeChanges.next()).value[0],
(await willBeChanges.next()).value[0]
];
await changeStream.close();
expect(changes).to.have.length(2);
expect(changes[0]).to.not.have.property('documentKey');
expect(changes[0]).to.containSubset({
operationType: 'insert',
fullDocument: { d: 4 },
ns: {
db: 'integration_tests',
coll: 'docsDataEvent'
},
comment: 'The documentKey field has been projected out of this document.'
});
expect(changes[1]).to.containSubset({
operationType: 'update',
updateDescription: {
updatedFields: { d: 6 }
}
});
}
});
it('should support creating multiple simultaneous ChangeStreams', {
metadata: { requires: { topology: 'replicaset' } },
test: function (done) {
const configuration = this.configuration;
const client = configuration.newClient();
client.connect((err, client) => {
expect(err).to.not.exist;
this.defer(() => client.close());
const database = client.db('integration_tests');
const collection1 = database.collection('simultaneous1');
const collection2 = database.collection('simultaneous2');
const changeStream1 = collection1.watch([{ $addFields: { changeStreamNumber: 1 } }]);
this.defer(() => changeStream1.close());
const changeStream2 = collection2.watch([{ $addFields: { changeStreamNumber: 2 } }]);
this.defer(() => changeStream2.close());
const changeStream3 = collection2.watch([{ $addFields: { changeStreamNumber: 3 } }]);
this.defer(() => changeStream3.close());
setTimeout(() => {
this.defer(
collection1.insertMany([{ a: 1 }]).then(() => collection2.insertMany([{ a: 1 }]))
);
}, 50);
Promise.resolve()
.then(() =>
Promise.all([changeStream1.hasNext(), changeStream2.hasNext(), changeStream3.hasNext()])
)
.then(function (hasNexts) {
// Check all the Change Streams have a next item
assert.ok(hasNexts[0]);
assert.ok(hasNexts[1]);
assert.ok(hasNexts[2]);
return Promise.all([changeStream1.next(), changeStream2.next(), changeStream3.next()]);
})
.then(function (changes) {
// Check the values of the change documents are correct
assert.equal(changes[0].operationType, 'insert');
assert.equal(changes[1].operationType, 'insert');
assert.equal(changes[2].operationType, 'insert');
expect(changes[0]).to.have.nested.property('fullDocument.a', 1);
expect(changes[1]).to.have.nested.property('fullDocument.a', 1);
expect(changes[2]).to.have.nested.property('fullDocument.a', 1);
expect(changes[0]).to.have.nested.property('ns.db', 'integration_tests');
expect(changes[1]).to.have.nested.property('ns.db', 'integration_tests');
expect(changes[2]).to.have.nested.property('ns.db', 'integration_tests');
expect(changes[0]).to.have.nested.property('ns.coll', 'simultaneous1');
expect(changes[1]).to.have.nested.property('ns.coll', 'simultaneous2');
expect(changes[2]).to.have.nested.property('ns.coll', 'simultaneous2');
expect(changes[0]).to.have.nested.property('changeStreamNumber', 1);
expect(changes[1]).to.have.nested.property('changeStreamNumber', 2);
expect(changes[2]).to.have.nested.property('changeStreamNumber', 3);
})
.then(
() => done(),
err => done(err)
);
});
}
});
it('should properly close ChangeStream cursor', {
metadata: { requires: { topology: 'replicaset' } },
test: function (done) {
const configuration = this.configuration;
const client = configuration.newClient();
client.connect((err, client) => {
expect(err).to.not.exist;
this.defer(() => client.close());
const database = client.db('integration_tests');
const changeStream = database.collection('changeStreamCloseTest').watch(pipeline);
this.defer(() => changeStream.close());
assert.equal(changeStream.closed, false);
assert.equal(changeStream.cursor.closed, false);
changeStream.close(err => {
expect(err).to.not.exist;
// Check the cursor is closed
expect(changeStream.closed).to.be.true;
expect(changeStream.cursor).property('closed', true);
done();
});
});
}
});
it(
'should error when attempting to create a ChangeStream with a forbidden aggregation pipeline stage',
{
metadata: { requires: { topology: 'replicaset' } },
test: function (done) {
const configuration = this.configuration;
const client = configuration.newClient();
client.connect((err, client) => {
expect(err).to.not.exist;
this.defer(() => client.close());
const forbiddenStage = {};
const forbiddenStageName = '$alksdjfhlaskdfjh';
forbiddenStage[forbiddenStageName] = 2;
const database = client.db('integration_tests');
const changeStream = database.collection('forbiddenStageTest').watch([forbiddenStage]);
this.defer(() => changeStream.close());
changeStream.next(err => {
assert.ok(err);
assert.ok(err.message);
assert.ok(
err.message.indexOf(`Unrecognized pipeline stage name: '${forbiddenStageName}'`) > -1
);
done();
});
});
}
}
);
it('should cache the change stream resume token using iterator form', {
metadata: { requires: { topology: 'replicaset' } },
async test() {
await initIteratorMode(changeStream);
collection.insertOne({ a: 1 });
const hasNext = await changeStream.hasNext();
expect(hasNext).to.be.true;
const change = await changeStream.next();
expect(change).to.have.property('_id').that.deep.equals(changeStream.resumeToken);
}
});
it('should cache the change stream resume token using event listener form', {
metadata: { requires: { topology: 'replicaset' } },
async test() {
const willBeChange = once(changeStream, 'change');
await once(changeStream.cursor, 'init');
collection.insertOne({ a: 1 });
const [change] = await willBeChange;
expect(change).to.have.property('_id').that.deep.equals(changeStream.resumeToken);
}
});
it('should error if resume token projected out of change stream document using iterator', {
metadata: { requires: { topology: 'replicaset' } },
test(done) {
const configuration = this.configuration;
const client = configuration.newClient();
client.connect((err, client) => {
expect(err).to.not.exist;
const database = client.db('integration_tests');
const collection = database.collection('resumetokenProjectedOutCallback');
const changeStream = collection.watch([{ $project: { _id: false } }]);
changeStream.hasNext(() => {
// trigger initialize
});
changeStream.cursor.on('init', () => {
collection.insertOne({ b: 2 }, (err, res) => {
expect(err).to.be.undefined;
expect(res).to.exist;
changeStream.next(err => {
expect(err).to.exist;
changeStream.close(() => {
client.close(() => {
done();
});
});
});
});
});
});
}
});
it('should error if resume token projected out of change stream document using event listeners', {
metadata: { requires: { topology: 'replicaset' } },
async test() {
const changeStream = collection.watch([{ $project: { _id: false } }]);
const willBeChangeOrError = once(changeStream, 'change').catch(error => error);
await once(changeStream.cursor, 'init');
await collection.insertOne({ a: 1 });
const error = await willBeChangeOrError;
await changeStream.close();
if (error instanceof MongoServerError) {
// Newer servers
expect(error).to.be.instanceOf(MongoServerError);
expect(error).to.have.property('code', 280); // ChangeStreamFatalError code
} else if (error instanceof MongoChangeStreamError) {
// Older servers do not error, but the driver will
expect(error).to.be.instanceOf(MongoChangeStreamError);
expect(error.message).to.match(/that lacks a resume token/);
} else {
expect.fail(`error needs to be a known instance, got ${error.constructor.name}`);
}
}
});
it('should invalidate change stream on collection rename using event listeners', {
metadata: { requires: { topology: 'replicaset', mongodb: '>=4.2' } },
async test() {
const willBeChange = once(changeStream, 'change');
await once(changeStream.cursor, 'init');
collection.insertOne({ a: 1 });
const [change] = await willBeChange;
expect(change).to.have.property('operationType', 'insert');
expect(change).to.have.nested.property('fullDocument.a', 1);
const willBeClose = once(changeStream, 'close');
const changes = on(changeStream, 'change');
await collection.rename('renamedDocs', { dropTarget: true });
const [renameChange] = (await changes.next()).value;
expect(renameChange).to.have.property('operationType', 'rename');
const [invalidateChange] = (await changes.next()).value;
expect(invalidateChange).to.have.property('operationType', 'invalidate');
await willBeClose; // Server will close this changestream
}
});
it('should invalidate change stream on database drop using iterator form', {
metadata: { requires: { topology: 'replicaset', mongodb: '>=4.2' } },
async test() {
const db = client.db('droppableDb');
const collection = db.collection('invalidateCallback');
// ensure ns exists before making cs
await collection.insertOne({ random: Math.random() });
const changeStream = collection.watch(pipeline);
await initIteratorMode(changeStream);
await collection.insertOne({ a: 1 });
const insertChange = await changeStream.next();
expect(insertChange).to.have.property('operationType', 'insert');
await db.dropDatabase();
const dropChange = await changeStream.next();
expect(dropChange).to.have.property('operationType', 'drop');
const invalidateChange = await changeStream.next();
expect(invalidateChange).to.have.property('operationType', 'invalidate');
const hasNext = await changeStream.hasNext();
expect(hasNext).to.be.false;
expect(changeStream.closed).to.be.true;
}
});
it('should resume from point in time using user-provided resumeAfter', {
metadata: { requires: { topology: 'replicaset' } },
async test() {
const collection = db.collection('resumeAfterTest2');
await collection.drop().catch(() => null);
let resumeToken;
const docs = [{ a: 0 }, { a: 1 }, { a: 2 }];
let secondChangeStream;
const firstChangeStream = collection.watch(pipeline);
this.defer(() => firstChangeStream.close());
return initIteratorMode(firstChangeStream)
.then(() =>
collection
.insertMany([docs[0]])
.then(() => collection.insertOne(docs[1]))
.then(() => collection.insertOne(docs[2]))
)
.then(() => firstChangeStream.hasNext())
.then(hasNext => {
assert.equal(true, hasNext);
return firstChangeStream.next();
})
.then(change => {
expect(change).to.have.property('operationType', 'insert');
expect(change).to.have.nested.property('fullDocument.a', docs[0].a);
// Save the resumeToken
resumeToken = change._id;
return firstChangeStream.next();
})
.then(change => {
expect(change).to.have.property('operationType', 'insert');
expect(change).to.have.nested.property('fullDocument.a', docs[1].a);
return firstChangeStream.next();
})
.then(change => {
expect(change).to.have.property('operationType', 'insert');
expect(change).to.have.nested.property('fullDocument.a', docs[2].a);
return firstChangeStream.close();
})
.then(() => {
secondChangeStream = collection.watch(pipeline, {
resumeAfter: resumeToken
});
this.defer(() => secondChangeStream.close());
return initIteratorMode(secondChangeStream).then(() => delay(200));
})
.then(() => secondChangeStream.hasNext())
.then(hasNext => {
assert.equal(true, hasNext);
return secondChangeStream.next();
})
.then(change => {
assert.equal(change.operationType, 'insert');
assert.equal(change.fullDocument.a, docs[1].a);
return secondChangeStream.next();
})
.then(change => {
assert.equal(change.operationType, 'insert');
assert.equal(change.fullDocument.a, docs[2].a);
return secondChangeStream.close();
});
}
});
it('should support full document lookup', {
metadata: { requires: { topology: 'replicaset' } },
async test() {
const collection = db.collection('fullDocumentLookup');
const changeStream = collection.watch([], { fullDocument: 'updateLookup' });
await initIteratorMode(changeStream);
const { insertedId: _id } = await collection.insertOne({ f: 128 });
const insertChange = await changeStream.next();
expect(insertChange).to.have.property('operationType', 'insert');
expect(insertChange).to.have.nested.property('fullDocument.f', 128);
expect(insertChange).to.not.have.nested.property('fullDocument.c');
await collection.updateOne({ _id }, { $set: { c: 2 } });
const updateChange = await changeStream.next();
expect(updateChange).to.have.property('operationType', 'update');
expect(updateChange).to.have.property('fullDocument').that.is.a('object');
expect(updateChange).to.have.nested.property('fullDocument.f', 128);
expect(updateChange).to.have.nested.property('fullDocument.c', 2);
expect(updateChange).to.have.nested.property('updateDescription.updatedFields.c', 2);
await changeStream.close();
}
});
it('should support full document lookup with deleted documents', {
metadata: { requires: { topology: 'replicaset' } },
test: function () {
const database = client.db('integration_tests');
const collection = database.collection('fullLookupTest');
const changeStream = collection.watch(pipeline, { fullDocument: 'updateLookup' });
return initIteratorMode(changeStream)
.then(() =>
collection.insertMany([{ i: 128 }]).then(() => collection.deleteOne({ i: 128 }))
)
.then(() => changeStream.hasNext())
.then(function (hasNext) {
assert.equal(true, hasNext);
return changeStream.next();
})
.then(function (change) {
expect(change).to.have.property('operationType', 'insert');
expect(change).to.have.nested.property('fullDocument.i', 128);
expect(change).to.have.nested.property('ns.db', database.databaseName);
expect(change).to.have.nested.property('ns.coll', collection.collectionName);
expect(change).to.not.have.property('documentKey');
expect(change).to.have.property(
'comment',
'The documentKey field has been projected out of this document.'
);
// Trigger the second database event
return collection.updateOne({ i: 128 }, { $set: { c: 2 } });
})
.then(() => changeStream.hasNext())
.then(function (hasNext) {
assert.equal(true, hasNext);
return changeStream.next();
})
.then(function (change) {
expect(change).to.have.property('operationType', 'delete');
expect(change).to.not.have.property('lookedUpDocument');
})
.finally(() => {
return changeStream.close();
});
}
});
it('should create Change Streams with correct read preferences', {
metadata: { requires: { topology: 'replicaset' } },
test: function () {
const configuration = this.configuration;
const client = configuration.newClient();
return client.connect().then(client => {
this.defer(() => client.close());
// should get preference from database
const database = client.db('integration_tests', {
readPreference: ReadPreference.PRIMARY_PREFERRED
});
const changeStream0 = database.collection('docs0').watch(pipeline);
this.defer(() => changeStream0.close());
assert.deepEqual(
changeStream0.cursor.readPreference.preference,
ReadPreference.PRIMARY_PREFERRED
);
// should get preference from collection
const collection = database.collection('docs1', {
readPreference: ReadPreference.SECONDARY_PREFERRED
});
const changeStream1 = collection.watch(pipeline);
assert.deepEqual(
changeStream1.cursor.readPreference.preference,
ReadPreference.SECONDARY_PREFERRED
);
this.defer(() => changeStream1.close());
// should get preference from Change Stream options
const changeStream2 = collection.watch(pipeline, {
readPreference: ReadPreference.NEAREST
});
this.defer(() => changeStream2.close());
assert.deepEqual(changeStream2.cursor.readPreference.preference, ReadPreference.NEAREST);
});
}
});
it('should support piping of Change Streams', {
metadata: { requires: { topology: 'replicaset' } },
async test() {
await initIteratorMode(changeStream);
const outStream = new PassThrough({ objectMode: true });
// @ts-expect-error: transform requires a Document return type
changeStream.stream({ transform: JSON.stringify }).pipe(outStream);
const willBeData = once(outStream, 'data');
await collection.insertMany([{ a: 1 }]);
const [data] = await willBeData;
const parsedEvent = JSON.parse(data);
expect(parsedEvent).to.have.nested.property('fullDocument.a', 1);
outStream.destroy();
}
});
describe('should error when used as iterator and emitter concurrently', function () {
let client, coll, changeStream, kMode;
beforeEach(async function () {
client = this.configuration.newClient();
await client.connect();
coll = client.db(this.configuration.db).collection('tester');
changeStream = coll.watch();
kMode = getSymbolFrom(changeStream, 'mode');
});
afterEach(async function () {
await changeStream.close();
await client?.close();
});
it('should throw when mixing event listeners with iterator methods', {
metadata: { requires: { topology: 'replicaset' } },
async test() {
expect(changeStream).to.have.property(kMode, false);
changeStream.on('change', () => {
// ChangeStream detects emitter usage via 'newListener' event
// so this covers all emitter methods
});
await once(changeStream.cursor, 'init');
expect(changeStream).to.have.property(kMode, 'emitter');
const errRegex = /ChangeStream cannot be used as an iterator/;
const nextError = await changeStream.next().catch(error => error);
expect(nextError.message).to.match(errRegex);
const hasNextError = await changeStream.hasNext().catch(error => error);
expect(hasNextError.message).to.match(errRegex);
const tryNextError = await changeStream.tryNext().catch(error => error);
expect(tryNextError.message).to.match(errRegex);
}
});
it('should throw when mixing iterator methods with event listeners', {
metadata: { requires: { topology: 'replicaset' } },
async test() {
await initIteratorMode(changeStream);
expect(changeStream).to.have.property(kMode, false);
const res = await changeStream.tryNext();
expect(res).to.not.exist;
expect(changeStream).to.have.property(kMode, 'iterator');
expect(() => {
changeStream.on('change', () => {
// This does throw synchronously
// the newListener event is called sync
// which calls streamEvents, which calls setIsEmitter, which will throw
});
}).to.throw(/ChangeStream cannot be used as an EventEmitter/);
}
});
});
describe('should properly handle a changeStream event being processed mid-close', function () {
let client, coll, changeStream;
function write() {
return Promise.resolve()
.then(() => coll.insertOne({ a: 1 }))
.then(() => coll.insertOne({ b: 2 }));
}
function lastWrite() {
return coll.insertOne({ c: 3 });
}
beforeEach(function () {
client = this.configuration.newClient();
return client.connect().then(_client => {
client = _client;
coll = client.db(this.configuration.db).collection('tester');
changeStream = coll.watch();
});
});
afterEach(async function () {
await changeStream?.close();
await client?.close();
coll = undefined;
changeStream = undefined;
client = undefined;
});
it('when invoked with promises', {
metadata: { requires: { topology: 'replicaset' } },
test: function () {
const read = () => {
return Promise.resolve()
.then(() => changeStream.next())
.then(() => changeStream.next())
.then(() => {
this.defer(lastWrite());
const nextP = changeStream.next();
return changeStream.close().then(() => nextP);
});
};
return Promise.all([read(), write()]).then(
() => Promise.reject(new Error('Expected operation to fail with error')),
err => expect(err.message).to.equal('ChangeStream is closed')
);
}
});
it('when invoked with callbacks', {
metadata: { requires: { topology: 'replicaset' } },
test: function (done) {
const ops = [];
changeStream.next(() => {
changeStream.next(() => {
ops.push(lastWrite());
// explicitly close the change stream after the write has begun
ops.push(changeStream.close());
changeStream.next(err => {
try {
expect(err)
.property('message')
.to.match(/ChangeStream is closed/);
Promise.all(ops).then(() => done(), done);
} catch (e) {
done(e);
}
});
});
});
ops.push(
write().catch(() => {
// ignore
})
);
}
});
it.skip('when invoked using eventEmitter API', {
metadata: {
requires: { topology: 'replicaset' }
},
async test() {
const changes = on(changeStream, 'change');
await once(changeStream.cursor, 'init');
await write();
await lastWrite().catch(() => null);
let counter = 0;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
for await (const _ of changes) {
counter += 1;
if (counter === 2) {
await changeStream.close();
break;
}
}
const result = await Promise.race([changes.next(), sleep(800).then(() => 42)]);
expect(result, 'should not have recieved a third event').to.equal(42);
}
}).skipReason =
'This test only worked because of timing, changeStream.close does not remove the change listener';
});
describe('iterator api', function () {
describe('#tryNext()', function () {
it('should return null on single iteration of empty cursor', {
metadata: { requires: { topology: 'replicaset' } },
async test() {
const doc = await changeStream.tryNext();
expect(doc).to.be.null;
}
});
it('should iterate a change stream until first empty batch', {
metadata: { requires: { topology: 'replicaset' } },
async test() {
// tryNext doesn't send the initial agg, just checks the driver document batch cache
const firstTry = await changeStream.tryNext();
expect(firstTry).to.be.null;
await initIteratorMode(changeStream);
await collection.insertOne({ a: 42 });
const secondTry = await changeStream.tryNext();
expect(secondTry).to.be.an('object');
const thirdTry = await changeStream.tryNext();
expect(thirdTry).to.be.null;
}
});
});
describe('#asyncIterator', function () {
describe('for-await iteration', function () {
it(
'can iterate through changes',
{ requires: { topology: '!single', mongodb: '>=4.2' } },
async function () {
changeStream = collection.watch([]);
await initIteratorMode(changeStream);
const docs = [{ city: 'New York City' }, { city: 'Seattle' }, { city: 'Boston' }];
await collection.insertMany(docs);
for await (const change of changeStream) {
const { fullDocument } = change;
const expectedDoc = docs.shift();
expect(fullDocument.city).to.equal(expectedDoc.city);
if (docs.length === 0) {
break;
}
}
expect(docs).to.have.length(0, 'expected to find all docs before exiting loop');
}
);
it(
'cannot be resumed from partial iteration',
{ requires: { topology: '!single' } },
async function () {
changeStream = collection.watch([]);
await initIteratorMode(changeStream);
const docs = [{ city: 'New York City' }, { city: 'Seattle' }, { city: 'Boston' }];
await collection.insertMany(docs);
for await (const change of changeStream) {
const { fullDocument } = change;
const expectedDoc = docs.shift();
expect(fullDocument.city).to.equal(expectedDoc.city);
break;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
for await (const change of changeStream) {
expect.fail('Change stream was resumed after partial iteration');
}
expect(docs).to.have.length(
2,
'expected to find remaining docs after partial iteration'
);
}
);
it(
'cannot be used with emitter-based iteration',
{ requires: { topology: '!single' } },
async function () {
changeStream = collection.watch([]);
changeStream.on('change', sinon.stub());
try {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
for await (const change of changeStream) {
expect.fail('Async iterator was used with emitter-based iteration');
}
} catch (error) {
expect(error).to.be.instanceOf(MongoAPIError);
}
}
);
it(
'can be used with raw iterator API',
{ requires: { topology: '!single' } },
async function () {
changeStream = collection.watch([]);
await initIteratorMode(changeStream);