-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathclient_side_operations_timeout.prose.test.ts
More file actions
1416 lines (1295 loc) · 53.1 KB
/
client_side_operations_timeout.prose.test.ts
File metadata and controls
1416 lines (1295 loc) · 53.1 KB
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
/* Specification prose tests */
import { Readable } from 'node:stream';
import { expect } from 'chai';
import * as semver from 'semver';
import * as sinon from 'sinon';
import { pipeline } from 'stream/promises';
import {
Binary,
ClientEncryption,
type CommandStartedEvent,
type CommandSucceededEvent,
GridFSBucket,
MongoBulkWriteError,
MongoClient,
MongoOperationTimeoutError,
MongoServerSelectionError,
ObjectId
} from '../../../src';
import { now, squashError } from '../../../src/utils';
import {
clearFailPoint,
configureFailPoint,
configureMongocryptdSpawnHooks,
type FailCommandFailPoint,
makeMultiBatchWrite,
measureDuration
} from '../../tools/utils';
import { filterForCommands } from '../shared';
describe('CSOT spec prose tests', function () {
let internalClient: MongoClient;
let client: MongoClient;
beforeEach(async function () {
internalClient = this.configuration.newClient();
});
afterEach(async function () {
await internalClient?.close();
await client?.close();
});
describe('1. Multi-batch writes', { requires: { topology: 'single', mongodb: '>=4.4' } }, () => {
/**
* This test MUST only run against standalones on server versions 4.4 and higher.
* The `insertMany` call takes an exceedingly long time on replicasets and sharded
* clusters. Drivers MAY adjust the timeouts used in this test to allow for differing
* bulk encoding performance.
*
* 1. Using `internalClient`, drop the `db.coll` collection.
* 1. Using `internalClient`, set the following fail point:
* ```js
* {
* configureFailPoint: "failCommand",
* mode: {
* times: 2
* },
* data: {
* failCommands: ["insert"],
* blockConnection: true,
* blockTimeMS: 1010
* }
* }
* ```
* 1. Create a new MongoClient (referred to as `client`) with `timeoutMS=2000`.
* 1. Using `client`, insert 50 1-megabyte documents in a single `insertMany` call.
* - Expect this to fail with a timeout error.
* 1. Verify that two `insert` commands were executed against `db.coll` as part of the `insertMany` call.
*/
const failpoint: FailCommandFailPoint = {
configureFailPoint: 'failCommand',
mode: {
times: 2
},
data: {
failCommands: ['insert'],
blockConnection: true,
blockTimeMS: 1010
}
};
beforeEach(async function () {
await internalClient
.db('db')
.collection('bulkWriteTest')
.drop()
.catch(() => null);
await internalClient.db('admin').command(failpoint);
client = this.configuration.newClient({ timeoutMS: 2000, monitorCommands: true });
});
it('performs two inserts which fail to complete before 2000 ms', async () => {
const inserts = [];
client.on('commandStarted', ev => inserts.push(ev));
const a = new Uint8Array(1000000 - 22);
const oneMBDocs = Array.from({ length: 50 }, (_, _id) => ({ _id, a }));
const error = await client
.db('db')
.collection<{ _id: number; a: Uint8Array }>('bulkWriteTest')
.insertMany(oneMBDocs)
.catch(error => error);
expect(error).to.be.instanceOf(MongoBulkWriteError);
expect(error.errorResponse).to.be.instanceOf(MongoOperationTimeoutError);
expect(inserts.map(ev => ev.commandName)).to.deep.equal(['insert', 'insert']);
});
});
context('2. maxTimeMS is not set for commands sent to mongocryptd', () => {
/**
* This test MUST only be run against enterprise server versions 4.2 and higher.
*
* 1. Launch a mongocryptd process on 23000.
* 1. Create a MongoClient (referred to as `client`) using the URI `mongodb://localhost:23000/?timeoutMS=1000`.
* 1. Using `client`, execute the `{ ping: 1 }` command against the `admin` database.
* 1. Verify via command monitoring that the `ping` command sent did not contain a `maxTimeMS` field.
*/
let client: MongoClient;
const mongocryptdTestPort = '23000';
configureMongocryptdSpawnHooks({ port: mongocryptdTestPort });
beforeEach(async function () {
client = new MongoClient(`mongodb://localhost:${mongocryptdTestPort}/?timeoutMS=1000`, {
monitorCommands: true
});
});
afterEach(async function () {
await client.close();
sinon.restore();
});
it('maxTimeMS is not set', async function () {
const commandStarted = [];
client.on('commandStarted', ev => commandStarted.push(ev));
await client.connect();
await client
.db('admin')
.command({ ping: 1 })
.catch(e => squashError(e));
expect(commandStarted).to.have.lengthOf(1);
expect(commandStarted[0].command).to.not.have.property('maxTimeMS');
});
});
context('3. ClientEncryption', () => {
/**
* Each test under this category MUST only be run against server versions 4.4 and higher. In these tests,
* `LOCAL_MASTERKEY` refers to the following base64:
* ```text
* Mng0NCt4ZHVUYUJCa1kxNkVyNUR1QURhZ2h2UzR2d2RrZzh0cFBwM3R6NmdWMDFBMUN3YkQ5aXRRMkhGRGdQV09wOGVNYUMxT2k3NjZKelhaQmRCZGJkTXVyZG9uSjFk
* ```
* For each test, perform the following setup:
*
* 1. Using `internalClient`, drop and create the `keyvault.datakeys` collection.
* 1. Create a MongoClient (referred to as `keyVaultClient`) with `timeoutMS=10`.
* 1. Create a `ClientEncryption` object that wraps `keyVaultClient` (referred to as `clientEncryption`). Configure this object with `keyVaultNamespace` set to `keyvault.datakeys` and the following KMS providers map:
* ```js
* { local: { key: <base64 decoding of LOCAL_MASTERKEY> } }
* ```
*/
let keyVaultClient: MongoClient;
let clientEncryption: ClientEncryption;
const LOCAL_MASTERKEY = Buffer.from(
'Mng0NCt4ZHVUYUJCa1kxNkVyNUR1QURhZ2h2UzR2d2RrZzh0cFBwM3R6NmdWMDFBMUN3YkQ5aXRRMkhGRGdQV09wOGVNYUMxT2k3NjZKelhaQmRCZGJkTXVyZG9uSjFk',
'base64'
);
const clientEncryptionMetadata: MongoDBMetadataUI = {
requires: {
clientSideEncryption: true,
mongodb: '>=7.0.0',
topology: '!single'
}
} as const;
const timeoutMS = 100;
beforeEach(async function () {
await internalClient
.db('keyvault')
.collection('datakeys')
.drop()
.catch(() => null);
await internalClient.db('keyvault').collection('datakeys');
keyVaultClient = this.configuration.newClient({}, { timeoutMS, monitorCommands: true });
clientEncryption = new ClientEncryption(keyVaultClient, {
keyVaultNamespace: 'keyvault.datakeys',
kmsProviders: { local: { key: LOCAL_MASTERKEY } }
});
});
afterEach(async function () {
await internalClient
.db()
.admin()
.command({
configureFailPoint: 'failCommand',
mode: 'off'
} as FailCommandFailPoint);
await keyVaultClient.close();
await internalClient.close();
});
context('createDataKey', () => {
/**
* 1. Using `internalClient`, set the following fail point:
* ```js
* {
* configureFailPoint: "failCommand",
* mode: {
* times: 1
* },
* data: {
* failCommands: ["insert"],
* blockConnection: true,
* blockTimeMS: 15
* }
* }
* ```
* 1. Call `clientEncryption.createDataKey()` with the `local` KMS provider.
* - Expect this to fail with a timeout error.
* 1. Verify that an `insert` command was executed against to `keyvault.datakeys` as part of the `createDataKey` call.
*/
it('times out due to timeoutMS', clientEncryptionMetadata, async function () {
await internalClient
.db()
.admin()
.command({
configureFailPoint: 'failCommand',
mode: {
times: 1
},
data: {
failCommands: ['insert'],
blockConnection: true,
blockTimeMS: 150
}
} as FailCommandFailPoint);
const commandStarted: CommandStartedEvent[] = [];
keyVaultClient.on('commandStarted', ev => commandStarted.push(ev));
const { duration, result: err } = await measureDuration(() =>
clientEncryption.createDataKey('local').catch(e => e)
);
expect(err).to.be.instanceOf(MongoOperationTimeoutError);
expect(duration).to.be.within(timeoutMS - 100, timeoutMS + 100);
const command = commandStarted[0].command;
expect(command).to.have.property('insert', 'datakeys');
expect(command).to.have.property('$db', 'keyvault');
});
});
context('encrypt', () => {
/**
* 1. Call `client_encryption.createDataKey()` with the `local` KMS provider.
* - Expect a BSON binary with subtype 4 to be returned, referred to as `datakeyId`.
* 1. Using `internalClient`, set the following fail point:
* ```js
* {
* configureFailPoint: "failCommand",
* mode: {
* times: 1
* },
* data: {
* failCommands: ["find"],
* blockConnection: true,
* blockTimeMS: 15
* }
* }
* ```
* 1. Call `clientEncryption.encrypt()` with the value `hello`, the algorithm `AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic`, and the keyId `datakeyId`.
* - Expect this to fail with a timeout error.
* 1. Verify that a `find` command was executed against the `keyvault.datakeys` collection as part of the `encrypt` call.
*/
it('times out due to timeoutMS', clientEncryptionMetadata, async function () {
const datakeyId = await clientEncryption.createDataKey('local');
expect(datakeyId).to.be.instanceOf(Binary);
expect(datakeyId.sub_type).to.equal(Binary.SUBTYPE_UUID);
await internalClient
.db()
.admin()
.command({
configureFailPoint: 'failCommand',
mode: {
times: 1
},
data: {
failCommands: ['find'],
blockConnection: true,
blockTimeMS: 150
}
} as FailCommandFailPoint);
const commandStarted: CommandStartedEvent[] = [];
keyVaultClient.on('commandStarted', ev => commandStarted.push(ev));
const { duration, result: err } = await measureDuration(() =>
clientEncryption
.encrypt('hello', {
algorithm: `AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic`,
keyId: datakeyId
})
.catch(e => e)
);
expect(err).to.be.instanceOf(MongoOperationTimeoutError);
expect(duration).to.be.within(timeoutMS - 100, timeoutMS + 100);
const command = commandStarted[0].command;
expect(command).to.have.property('find', 'datakeys');
expect(command).to.have.property('$db', 'keyvault');
});
});
context('decrypt', () => {
/**
* 1. Call `clientEncryption.createDataKey()` with the `local` KMS provider.
* - Expect this to return a BSON binary with subtype 4, referred to as `dataKeyId`.
* 1. Call `clientEncryption.encrypt()` with the value `hello`, the algorithm `AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic`, and the keyId `dataKeyId`.
* - Expect this to return a BSON binary with subtype 6, referred to as `encrypted`.
* 1. Close and re-create the `keyVaultClient` and `clientEncryption` objects.
* 1. Using `internalClient`, set the following fail point:
* ```js
* {
* configureFailPoint: "failCommand",
* mode: {
* times: 1
* },
* data: {
* failCommands: ["find"],
* blockConnection: true,
* blockTimeMS: 15
* }
* }
* ```
* 1. Call `clientEncryption.decrypt()` with the value `encrypted`.
* - Expect this to fail with a timeout error.
* 1. Verify that a `find` command was executed against the `keyvault.datakeys` collection as part of the `decrypt` call.
*/
it('times out due to timeoutMS', clientEncryptionMetadata, async function () {
const datakeyId = await clientEncryption.createDataKey('local');
expect(datakeyId).to.be.instanceOf(Binary);
expect(datakeyId.sub_type).to.equal(Binary.SUBTYPE_UUID);
// pre-compute 'hello' encryption, otherwise the data key is cached sometimes and find in stateMachine.execute never runs
const encrypted = Binary.createFromBase64(
'Af6ie/LRP0uoisAZthHPUs0CKzTBFIkJr8kxmOk1pV1C/6K54otT8QvNJgNTNG2CNpThhfdXaObuOMMReNlTgwapqPYCb/HJRQ1Nfma6uA3cTg==',
6
);
expect(encrypted).to.be.instanceOf(Binary);
expect(encrypted.sub_type).to.equal(Binary.SUBTYPE_ENCRYPTED);
await internalClient
.db()
.admin()
.command({
configureFailPoint: 'failCommand',
mode: {
times: 1
},
data: {
failCommands: ['find'],
blockConnection: true,
blockTimeMS: 150
}
} as FailCommandFailPoint);
const commandStarted: CommandStartedEvent[] = [];
keyVaultClient.on('commandStarted', ev => commandStarted.push(ev));
const { duration, result: err } = await measureDuration(() =>
clientEncryption.decrypt(encrypted).catch(e => e)
);
expect(err).to.be.instanceOf(MongoOperationTimeoutError);
expect(duration).to.be.within(timeoutMS - 100, timeoutMS + 100);
const command = commandStarted[0].command;
expect(command).to.have.property('find', 'datakeys');
expect(command).to.have.property('$db', 'keyvault');
});
});
});
/** TODO(DRIVERS-2884): Drivers should not interrupt creating connections with a client-side timeout */
context.skip('4. Background Connection Pooling', () => {
/**
* The tests in this section MUST only be run if the server version is 4.4 or higher and the URI has authentication
* fields (i.e. a username and password). Each test in this section requires drivers to create a MongoClient and then wait
* for some CMAP events to be published. Drivers MUST wait for up to 10 seconds and fail the test if the specified events
* are not published within that time.
*/
context('timeoutMS used for handshake commands', () => {
/**
* 1. Using `internalClient`, set the following fail point:
* ```js
* {
* configureFailPoint: "failCommand",
* mode: {
* times: 1
* },
* data: {
* failCommands: ["saslContinue"],
* blockConnection: true,
* blockTimeMS: 15,
* appName: "timeoutBackgroundPoolTest"
* }
* }
* ```
* 1. Create a MongoClient (referred to as `client`) configured with the following:
* - `minPoolSize` of 1
* - `timeoutMS` of 10
* - `appName` of `timeoutBackgroundPoolTest`
* - CMAP monitor configured to listen for `ConnectionCreatedEvent` and `ConnectionClosedEvent` events.
* 1. Wait for a `ConnectionCreatedEvent` and a `ConnectionClosedEvent` to be published.
*/
});
context('timeoutMS is refreshed for each handshake command', () => {
/**
* 1. Using `internalClient`, set the following fail point:
* ```js
* {
* configureFailPoint: "failCommand",
* mode: "alwaysOn",
* data: {
* failCommands: ["hello", "isMaster", "saslContinue"],
* blockConnection: true,
* blockTimeMS: 15,
* appName: "refreshTimeoutBackgroundPoolTest"
* }
* }
* ```
* 1. Create a MongoClient (referred to as `client`) configured with the following:
* - `minPoolSize` of 1
* - `timeoutMS` of 20
* - `appName` of `refreshTimeoutBackgroundPoolTest`
* - CMAP monitor configured to listen for `ConnectionCreatedEvent` and `ConnectionReady` events.
* 1. Wait for a `ConnectionCreatedEvent` and a `ConnectionReady` to be published.
*/
});
});
context('5. Blocking Iteration Methods', () => {
const metadata = { requires: { mongodb: '>=4.4' } };
/**
* Tests in this section MUST only be run against server versions 4.4 and higher and only apply to drivers that have a
* blocking method for cursor iteration that executes `getMore` commands in a loop until a document is available or an
* error occurs.
*/
const failpoint: FailCommandFailPoint = {
configureFailPoint: 'failCommand',
mode: 'alwaysOn',
data: {
failCommands: ['getMore'],
blockConnection: true,
blockTimeMS: 90
}
};
let internalClient: MongoClient;
let client: MongoClient;
let commandStarted: CommandStartedEvent[];
let commandSucceeded: CommandSucceededEvent[];
beforeEach(async function () {
internalClient = this.configuration.newClient();
await internalClient
.db('db')
.collection('coll')
.drop()
.catch(() => null);
// Creating capped collection to be able to create tailable find cursor
const coll = await internalClient
.db('db')
.createCollection('coll', { capped: true, size: 1_000_000 });
await coll.insertOne({ x: 1 });
await internalClient.db().admin().command(failpoint);
client = this.configuration.newClient(undefined, {
monitorCommands: true,
timeoutMS: 150,
minPoolSize: 20
});
await client.connect();
commandStarted = [];
commandSucceeded = [];
client.on('commandStarted', ev => commandStarted.push(ev));
client.on('commandSucceeded', ev => commandSucceeded.push(ev));
});
afterEach(async function () {
await internalClient
.db()
.admin()
.command({ ...failpoint, mode: 'off' });
await internalClient.close();
await client.close();
});
context('Tailable cursors', () => {
/**
* 1. Using `internalClient`, drop the `db.coll` collection.
* 1. Using `internalClient`, insert the document `{ x: 1 }` into `db.coll`.
* 1. Using `internalClient`, set the following fail point:
* ```js
* {
* configureFailPoint: "failCommand",
* mode: "alwaysOn",
* data: {
* failCommands: ["getMore"],
* blockConnection: true,
* blockTimeMS: 15
* }
* }
* ```
* 1. Create a new MongoClient (referred to as `client`) with `timeoutMS=20`.
* 1. Using `client`, create a tailable cursor on `db.coll` with `cursorType=tailable`.
* - Expect this to succeed and return a cursor with a non-zero ID.
* 1. Call either a blocking or non-blocking iteration method on the cursor.
* - Expect this to succeed and return the document `{ x: 1 }` without sending a `getMore` command.
* 1. Call the blocking iteration method on the resulting cursor.
* - Expect this to fail with a timeout error.
* 1. Verify that a `find` command and two `getMore` commands were executed against the `db.coll` collection during the test.
*/
it('send correct number of finds and getMores', metadata, async function () {
const cursor = client
.db('db')
.collection('coll')
.find({}, { tailable: true })
.project({ _id: 0 });
const doc = await cursor.next();
expect(doc).to.deep.equal({ x: 1 });
// Check that there are no getMores sent
expect(commandStarted.filter(e => e.command.getMore != null)).to.have.lengthOf(0);
const maybeError = await cursor.next().then(
() => null,
e => e
);
expect(maybeError).to.be.instanceof(MongoOperationTimeoutError);
// Expect 1 find
expect(commandStarted.filter(e => e.command.find != null)).to.have.lengthOf(1);
// Expect 2 getMore
expect(commandStarted.filter(e => e.command.getMore != null)).to.have.lengthOf(2);
});
});
context('Change Streams', () => {
/**
* 1. Using `internalClient`, drop the `db.coll` collection.
* 1. Using `internalClient`, set the following fail point:
* ```js
* {
* configureFailPoint: "failCommand",
* mode: "alwaysOn",
* data: {
* failCommands: ["getMore"],
* blockConnection: true,
* blockTimeMS: 15
* }
* }
* ```
* 1. Create a new MongoClient (referred to as `client`) with `timeoutMS=20`.
* 1. Using `client`, use the `watch` helper to create a change stream against `db.coll`.
* - Expect this to succeed and return a change stream with a non-zero ID.
* 1. Call the blocking iteration method on the resulting change stream.
* - Expect this to fail with a timeout error.
* 1. Verify that an `aggregate` command and two `getMore` commands were executed against the `db.coll` collection during the test.
*/
it(
'sends correct number of aggregate and getMores',
{ requires: { mongodb: '>=4.4', topology: '!single' } },
async function () {
// NOTE: we don't check for a non-zero ID since we lazily send the initial aggregate to the
// server. See ChangeStreamCursor._initialize
const changeStream = client
.db('db')
.collection('coll')
.watch([], { timeoutMS: 120, maxAwaitTimeMS: 10 });
// @ts-expect-error private method
await changeStream.cursor.cursorInit();
const maybeError = await changeStream.next().then(
() => null,
e => e
);
expect(maybeError).to.be.instanceof(MongoOperationTimeoutError);
const aggregates = commandStarted
.filter(e => e.command.aggregate != null)
.map(e => e.command);
const getMores = commandStarted
.filter(e => e.command.getMore != null)
.map(e => e.command);
// Expect 1 aggregate
expect(aggregates).to.have.lengthOf(1);
// Expect 2 getMores
expect(getMores).to.have.lengthOf(2);
}
);
});
});
context('6. GridFS - Upload', () => {
/** Tests in this section MUST only be run against server versions 4.4 and higher. */
const metadata: MongoDBMetadataUI = {
requires: { mongodb: '>=4.4' }
};
let client: MongoClient;
beforeEach(async function () {
const internalClient = this.configuration.newClient(
this.configuration.url({ useMultipleMongoses: false })
);
await internalClient
.db('db')
.dropCollection('files')
.catch(() => null);
await internalClient
.db('db')
.dropCollection('chunks')
.catch(() => null);
await internalClient.close();
client = this.configuration.newClient(
this.configuration.url({ useMultipleMongoses: false }),
{ timeoutMS: 150 }
);
});
afterEach(async function () {
await clearFailPoint(
this.configuration,
'failCommand',
this.configuration.url({ useMultipleMongoses: false })
);
await client?.close();
});
it('uploads via openUploadStream can be timed out', metadata, async function () {
// 1. Using `internalClient`, drop and re-create the `db.fs.files` and `db.fs.chunks` collections.
// 2. Using `internalClient`, set the following fail point:
// ```javascript
// {
// configureFailPoint: "failCommand",
// mode: { times: 1 },
// data: {
// failCommands: ["insert"],
// blockConnection: true,
// blockTimeMS: 200
// }
// }
// ```
// 3. Create a new MongoClient (referred to as `client`) with `timeoutMS=150`.
// 4. Using `client`, create a GridFS bucket (referred to as `bucket`) that wraps the `db` database.
// 5. Call `bucket.open_upload_stream()` with the filename `filename` to create an upload stream (referred to as
// `uploadStream`).
// - Expect this to succeed and return a non-null stream.
// 6. Using `uploadStream`, upload a single `0x12` byte.
// 7. Call `uploadStream.close()` to flush the stream and insert chunks.
// - Expect this to fail with a timeout error.
await configureFailPoint(
this.configuration,
{
configureFailPoint: 'failCommand',
mode: { times: 1 },
data: {
failCommands: ['insert'],
blockConnection: true,
blockTimeMS: 200
}
},
this.configuration.url({ useMultipleMongoses: false })
);
const bucket = new GridFSBucket(client.db('db'));
const stream = bucket.openUploadStream('filename');
const maybeError = await pipeline(Readable.from(Buffer.from('13', 'hex')), stream).catch(
error => error
);
expect(maybeError).to.be.instanceof(MongoOperationTimeoutError);
});
it('Aborting an upload stream can be timed out', metadata, async function () {
// 1. Using `internalClient`, drop and re-create the `db.fs.files` and `db.fs.chunks` collections.
// 2. Using `internalClient`, set the following fail point:
// ```javascript
// {
// configureFailPoint: "failCommand",
// mode: { times: 1 },
// data: {
// failCommands: ["delete"],
// blockConnection: true,
// blockTimeMS: 200
// }
// }
// ```
// 3. Create a new MongoClient (referred to as `client`) with `timeoutMS=150`.
// 4. Using `client`, create a GridFS bucket (referred to as `bucket`) that wraps the `db` database with
// `chunkSizeBytes=2`.
// 5. Call `bucket.open_upload_stream()` with the filename `filename` to create an upload stream (referred to as
// `uploadStream`).
// - Expect this to succeed and return a non-null stream.
// 6. Using `uploadStream`, upload the bytes `[0x01, 0x02, 0x03, 0x04]`.
// 7. Call `uploadStream.abort()`.
// - Expect this to fail with a timeout error.
await configureFailPoint(
this.configuration,
{
configureFailPoint: 'failCommand',
mode: { times: 1 },
data: {
failCommands: ['delete'],
blockConnection: true,
blockTimeMS: 200
}
},
this.configuration.url({ useMultipleMongoses: false })
);
const bucket = new GridFSBucket(client.db('db'), { chunkSizeBytes: 2 });
const uploadStream = bucket.openUploadStream('filename');
await pipeline(Readable.from(Buffer.from('01020304', 'hex')), uploadStream, {
end: false
});
const timeoutError = await uploadStream.abort().catch(error => error);
expect(timeoutError).to.be.instanceOf(MongoOperationTimeoutError);
uploadStream.destroy();
});
});
context('7. GridFS - Download', () => {
let internalClient: MongoClient;
let client: MongoClient;
const metadata: MongoDBMetadataUI = {
requires: { mongodb: '>=4.4' }
};
beforeEach(async function () {
internalClient = this.configuration.newClient();
await internalClient
.db('db')
.dropCollection('files')
.catch(() => null);
await internalClient
.db('db')
.dropCollection('chunks')
.catch(() => null);
const files = await internalClient.db('db').createCollection('files');
await files.insertOne({
_id: new ObjectId('000000000000000000000005'),
length: 10,
chunkSize: 4,
uploadDate: new Date('1970-01-01T00:00:00.000Z'),
md5: '57d83cd477bfb1ccd975ab33d827a92b',
filename: 'length-10',
contentType: 'application/octet-stream',
aliases: [],
metadata: {}
});
client = this.configuration.newClient(undefined, { timeoutMS: 100 });
});
afterEach(async function () {
if (internalClient) {
await internalClient
.db()
.admin()
.command({ configureFailPoint: 'failCommand', mode: 'off' });
await internalClient.close();
}
if (client) {
await client.close();
}
});
// This test MUST only be run against server versions 4.4 and higher. Drivers SHOULD apply
// [useMultipleMongoses=false](../../unified-test-format/unified-test-format.md#entity) as described in the unified test
// format when testing on sharded clusters to ensure failpoint are hit by only using one mongos.
// 1. Using `internalClient`, drop and re-create the `db.fs.files` and `db.fs.chunks` collections.
// 2. Using `internalClient`, insert the following document into the `db.fs.files` collection:
// ```javascript
// {
// "_id": {
// "$oid": "000000000000000000000005"
// },
// "length": 10,
// "chunkSize": 4,
// "uploadDate": {
// "$date": "1970-01-01T00:00:00.000Z"
// },
// "md5": "57d83cd477bfb1ccd975ab33d827a92b",
// "filename": "length-10",
// "contentType": "application/octet-stream",
// "aliases": [],
// "metadata": {}
// }
// ```
// 3. Create a new MongoClient (referred to as `client`) with `timeoutMS=150`.
// 4. Using `client`, create a GridFS bucket (referred to as `bucket`) that wraps the `db` database.
// 5. Call `bucket.open_download_stream` with the id `{ "$oid": "000000000000000000000005" }` to create a download stream
// (referred to as `downloadStream`).
// - Expect this to succeed and return a non-null stream.
// 6. Using `internalClient`, set the following fail point:
// ```javascript
// {
// configureFailPoint: "failCommand",
// mode: { times: 1 },
// data: {
// failCommands: ["find"],
// blockConnection: true,
// blockTimeMS: 200
// }
// }
// ```
// 7. Read from the `downloadStream`.
// - Expect this to fail with a timeout error.
// 8. Verify that two `find` commands were executed during the read: one against `db.fs.files` and another against
// `db.fs.chunks`.
it('download streams can be timed out', metadata, async function () {
const bucket = new GridFSBucket(client.db('db'));
const downloadStream = bucket.openDownloadStream(new ObjectId('000000000000000000000005'));
const failpoint: FailCommandFailPoint = {
configureFailPoint: 'failCommand',
mode: { times: 1 },
data: {
failCommands: ['find'],
blockConnection: true,
blockTimeMS: 150
}
};
await internalClient.db().admin().command(failpoint);
const maybeError = await downloadStream.toArray().then(
() => null,
e => e
);
expect(maybeError).to.be.instanceOf(MongoOperationTimeoutError);
});
});
context('8. Server Selection', () => {
context('using sinon timer', function () {
let clock: sinon.SinonFakeTimers;
beforeEach(function () {
clock = sinon.useFakeTimers();
});
afterEach(function () {
clock.restore();
});
it.skip('serverSelectionTimeoutMS honored if timeoutMS is not set', async function () {
/**
* 1. Create a MongoClient (referred to as `client`) with URI `mongodb://invalid/?serverSelectionTimeoutMS=10`.
* 1. Using `client`, execute the command `{ ping: 1 }` against the `admin` database.
* - Expect this to fail with a server selection timeout error after no more than 15ms.
*/
/** NOTE: This is the original implementation of this test, but it was flaky, so was
* replaced by the current implementation using sinon fake timers
* ```ts
* client = new MongoClient('mongodb://invalid/?serverSelectionTimeoutMS=10');
* const admin = client.db('test').admin();
* const start = performance.now();
* const maybeError = await admin.ping().then(
* () => null,
* e => e
* );
* const end = performance.now();
*
* expect(maybeError).to.be.instanceof(MongoServerSelectionError);
* expect(end - start).to.be.lte(15)
* ```
*/
client = new MongoClient('mongodb://invalid/?serverSelectionTimeoutMS=10');
const admin = client.db('test').admin();
const maybeError = admin.ping().then(
() => null,
e => e
);
await clock.tickAsync(11);
expect(await maybeError).to.be.instanceof(MongoServerSelectionError);
}).skipReason =
'TODO(NODE-6223): Auto connect performs extra server selection. Explicit connect throws on invalid host name';
});
it.skip("timeoutMS honored for server selection if it's lower than serverSelectionTimeoutMS", async function () {
/**
* 1. Create a MongoClient (referred to as `client`) with URI `mongodb://invalid/?timeoutMS=10&serverSelectionTimeoutMS=20`.
* 1. Using `client`, run the command `{ ping: 1 }` against the `admin` database.
* - Expect this to fail with a server selection timeout error after no more than 15ms.
*/
client = new MongoClient('mongodb://invalid/?timeoutMS=10&serverSelectionTimeoutMS=20');
const start = now();
const maybeError = await client
.db('test')
.admin()
.ping()
.then(
() => null,
e => e
);
const end = now();
expect(maybeError).to.be.instanceof(MongoOperationTimeoutError);
expect(end - start).to.be.lte(15);
}).skipReason =
'TODO(NODE-6223): Auto connect performs extra server selection. Explicit connect throws on invalid host name';
it.skip("timeoutMS honored for server selection if it's lower than serverSelectionTimeoutMS", async function () {
/**
* 1. Create a MongoClient (referred to as `client`) with URI `mongodb://invalid/?timeoutMS=10&serverSelectionTimeoutMS=20`.
* 1. Using `client`, run the command `{ ping: 1 }` against the `admin` database.
* - Expect this to fail with a server selection timeout error after no more than 15ms.
*/
client = new MongoClient('mongodb://invalid/?timeoutMS=10&serverSelectionTimeoutMS=20');
const start = now();
const maybeError = await client
.db('test')
.admin()
.ping()
.then(
() => null,
e => e
);
const end = now();
expect(maybeError).to.be.instanceof(MongoOperationTimeoutError);
expect(end - start).to.be.lte(15);
}).skipReason =
'TODO(NODE-6223): Auto connect performs extra server selection. Explicit connect throws on invalid host name';
it.skip("serverSelectionTimeoutMS honored for server selection if it's lower than timeoutMS", async function () {
/**
* 1. Create a MongoClient (referred to as `client`) with URI `mongodb://invalid/?timeoutMS=20&serverSelectionTimeoutMS=10`.
* 1. Using `client`, run the command `{ ping: 1 }` against the `admin` database.
* - Expect this to fail with a server selection timeout error after no more than 15ms.
*/
client = new MongoClient('mongodb://invalid/?timeoutMS=20&serverSelectionTimeoutMS=10');
const start = now();
const maybeError = await client
.db('test')
.admin()
.ping()
.then(
() => null,
e => e
);
const end = now();
expect(maybeError).to.be.instanceof(MongoOperationTimeoutError);
expect(end - start).to.be.lte(15);
}).skipReason =
'TODO(NODE-6223): Auto connect performs extra server selection. Explicit connect throws on invalid host name';
it.skip('serverSelectionTimeoutMS honored for server selection if timeoutMS=0', async function () {
/**
* 1. Create a MongoClient (referred to as `client`) with URI `mongodb://invalid/?timeoutMS=0&serverSelectionTimeoutMS=10`.
* 1. Using `client`, run the command `{ ping: 1 }` against the `admin` database.
* - Expect this to fail with a server selection timeout error after no more than 15ms.
*/
client = new MongoClient('mongodb://invalid/?timeoutMS=0&serverSelectionTimeoutMS=10');
const start = now();
const maybeError = await client
.db('test')
.admin()
.ping()
.then(
() => null,
e => e
);
const end = now();