-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathconnection.ts
869 lines (756 loc) · 24.9 KB
/
connection.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
import { MessageStream, OperationDescription } from './message_stream';
import { StreamDescription, StreamDescriptionOptions } from './stream_description';
import {
CommandStartedEvent,
CommandFailedEvent,
CommandSucceededEvent
} from './command_monitoring_events';
import { applySession, ClientSession, updateSessionFromResponse } from '../sessions';
import {
uuidV4,
ClientMetadata,
now,
calculateDurationInMs,
Callback,
MongoDBNamespace,
maxWireVersion,
HostAddress
} from '../utils';
import {
AnyError,
MongoDriverError,
MongoMissingDependencyError,
MongoCompatibilityError,
MongoError,
MongoNetworkError,
MongoNetworkTimeoutError,
MongoServerError,
MongoWriteConcernError
} from '../error';
import {
BinMsg,
WriteProtocolMessageType,
Response,
KillCursor,
GetMore,
Query,
OpQueryOptions,
Msg
} from './commands';
import { BSONSerializeOptions, Document, Long, pluckBSONSerializeOptions } from '../bson';
import type { AutoEncrypter } from '../deps';
import type { MongoCredentials } from './auth/mongo_credentials';
import type { Stream } from './connect';
import { applyCommonQueryOptions, getReadPreference, isSharded } from './wire_protocol/shared';
import { ReadPreference, ReadPreferenceLike } from '../read_preference';
import { isTransactionCommand } from '../transactions';
import type { W, WriteConcern, WriteConcernOptions } from '../write_concern';
import type { ServerApi, SupportedNodeConnectionOptions } from '../mongo_client';
import { CancellationToken, TypedEventEmitter } from '../mongo_types';
/** @internal */
const kStream = Symbol('stream');
/** @internal */
const kQueue = Symbol('queue');
/** @internal */
const kMessageStream = Symbol('messageStream');
/** @internal */
const kGeneration = Symbol('generation');
/** @internal */
const kLastUseTime = Symbol('lastUseTime');
/** @internal */
const kClusterTime = Symbol('clusterTime');
/** @internal */
const kDescription = Symbol('description');
/** @internal */
const kIsMaster = Symbol('ismaster');
/** @internal */
const kAutoEncrypter = Symbol('autoEncrypter');
/** @internal */
export interface QueryOptions extends BSONSerializeOptions {
readPreference: ReadPreference;
documentsReturnedIn?: string;
batchSize?: number;
limit?: number;
skip?: number;
projection?: Document;
tailable?: boolean;
awaitData?: boolean;
noCursorTimeout?: boolean;
/** @deprecated use `noCursorTimeout` instead */
timeout?: boolean;
partial?: boolean;
oplogReplay?: boolean;
}
/** @public */
export interface CommandOptions extends BSONSerializeOptions {
command?: boolean;
slaveOk?: boolean;
/** Specify read preference if command supports it */
readPreference?: ReadPreferenceLike;
raw?: boolean;
monitoring?: boolean;
fullResult?: boolean;
socketTimeoutMS?: number;
/** Session to use for the operation */
session?: ClientSession;
documentsReturnedIn?: string;
noResponse?: boolean;
// FIXME: NODE-2802
willRetryWrite?: boolean;
// FIXME: NODE-2781
writeConcern?: WriteConcernOptions | WriteConcern | W;
}
/** @internal */
export interface GetMoreOptions extends CommandOptions {
batchSize?: number;
maxTimeMS?: number;
maxAwaitTimeMS?: number;
comment?: Document | string;
}
/** @public */
export interface ConnectionOptions
extends SupportedNodeConnectionOptions,
StreamDescriptionOptions {
// Internal creation info
id: number | '<monitor>';
generation: number;
hostAddress: HostAddress;
// Settings
autoEncrypter?: AutoEncrypter;
serverApi?: ServerApi;
monitorCommands: boolean;
/** @internal */
connectionType?: typeof Connection;
credentials?: MongoCredentials;
connectTimeoutMS?: number;
tls: boolean;
keepAlive?: boolean;
keepAliveInitialDelay?: number;
noDelay?: boolean;
socketTimeoutMS?: number;
cancellationToken?: CancellationToken;
metadata: ClientMetadata;
}
/** @public */
export interface DestroyOptions {
/** Force the destruction. */
force?: boolean;
}
/** @public */
export type ConnectionEvents = {
commandStarted(event: CommandStartedEvent): void;
commandSucceeded(event: CommandSucceededEvent): void;
commandFailed(event: CommandFailedEvent): void;
clusterTimeReceived(clusterTime: Document): void;
close(): void;
message(message: any): void;
};
/** @internal */
export class Connection extends TypedEventEmitter<ConnectionEvents> {
id: number | '<monitor>';
address: string;
socketTimeoutMS: number;
monitorCommands: boolean;
closed: boolean;
destroyed: boolean;
lastIsMasterMS?: number;
serverApi?: ServerApi;
helloOk?: boolean;
/** @internal */
[kDescription]: StreamDescription;
/** @internal */
[kGeneration]: number;
/** @internal */
[kLastUseTime]: number;
/** @internal */
[kQueue]: Map<number, OperationDescription>;
/** @internal */
[kMessageStream]: MessageStream;
/** @internal */
[kStream]: Stream;
/** @internal */
[kIsMaster]: Document;
/** @internal */
[kClusterTime]: Document;
/** @event */
static readonly COMMAND_STARTED = 'commandStarted' as const;
/** @event */
static readonly COMMAND_SUCCEEDED = 'commandSucceeded' as const;
/** @event */
static readonly COMMAND_FAILED = 'commandFailed' as const;
/** @event */
static readonly CLUSTER_TIME_RECEIVED = 'clusterTimeReceived' as const;
/** @event */
static readonly CLOSE = 'close' as const;
/** @event */
static readonly MESSAGE = 'message' as const;
constructor(stream: Stream, options: ConnectionOptions) {
super();
this.id = options.id;
this.address = streamIdentifier(stream);
this.socketTimeoutMS = options.socketTimeoutMS ?? 0;
this.monitorCommands = options.monitorCommands;
this.serverApi = options.serverApi;
this.closed = false;
this.destroyed = false;
this[kDescription] = new StreamDescription(this.address, options);
this[kGeneration] = options.generation;
this[kLastUseTime] = now();
// setup parser stream and message handling
this[kQueue] = new Map();
this[kMessageStream] = new MessageStream({
...options,
maxBsonMessageSize: this.ismaster?.maxBsonMessageSize
});
this[kMessageStream].on('message', messageHandler(this));
this[kStream] = stream;
stream.on('error', () => {
/* ignore errors, listen to `close` instead */
});
this[kMessageStream].on('error', error => this.handleIssue({ destroy: error }));
stream.on('close', () => this.handleIssue({ isClose: true }));
stream.on('timeout', () => this.handleIssue({ isTimeout: true, destroy: true }));
// hook the message stream up to the passed in stream
stream.pipe(this[kMessageStream]);
this[kMessageStream].pipe(stream);
}
get description(): StreamDescription {
return this[kDescription];
}
get ismaster(): Document {
return this[kIsMaster];
}
// the `connect` method stores the result of the handshake ismaster on the connection
set ismaster(response: Document) {
this[kDescription].receiveResponse(response);
this[kDescription] = Object.freeze(this[kDescription]);
// TODO: remove this, and only use the `StreamDescription` in the future
this[kIsMaster] = response;
}
get generation(): number {
return this[kGeneration] || 0;
}
get idleTime(): number {
return calculateDurationInMs(this[kLastUseTime]);
}
get clusterTime(): Document {
return this[kClusterTime];
}
get stream(): Stream {
return this[kStream];
}
markAvailable(): void {
this[kLastUseTime] = now();
}
handleIssue(issue: { isTimeout?: boolean; isClose?: boolean; destroy?: boolean | Error }): void {
if (this.closed) {
return;
}
if (issue.destroy) {
this[kStream].destroy(typeof issue.destroy === 'boolean' ? undefined : issue.destroy);
}
this.closed = true;
for (const [, op] of this[kQueue]) {
if (issue.isTimeout) {
op.cb(
new MongoNetworkTimeoutError(`connection ${this.id} to ${this.address} timed out`, {
beforeHandshake: this.ismaster == null
})
);
} else if (issue.isClose) {
op.cb(new MongoNetworkError(`connection ${this.id} to ${this.address} closed`));
} else {
op.cb(typeof issue.destroy === 'boolean' ? undefined : issue.destroy);
}
}
this[kQueue].clear();
this.emit(Connection.CLOSE);
}
destroy(): void;
destroy(callback: Callback): void;
destroy(options: DestroyOptions): void;
destroy(options: DestroyOptions, callback: Callback): void;
destroy(options?: DestroyOptions | Callback, callback?: Callback): void {
if (typeof options === 'function') {
callback = options;
options = { force: false };
}
options = Object.assign({ force: false }, options);
if (this[kStream] == null || this.destroyed) {
this.destroyed = true;
if (typeof callback === 'function') {
callback();
}
return;
}
if (options.force) {
this[kStream].destroy();
this.destroyed = true;
if (typeof callback === 'function') {
callback();
}
return;
}
this[kStream].end(() => {
this.destroyed = true;
if (typeof callback === 'function') {
callback();
}
});
}
/** @internal */
command(
ns: MongoDBNamespace,
cmd: Document,
options: CommandOptions | undefined,
callback: Callback
): void {
if (!(ns instanceof MongoDBNamespace)) {
// TODO(NODE-3483): Replace this with a MongoCommandError
throw new MongoDriverError('Must provide a MongoDBNamespace instance');
}
const readPreference = getReadPreference(cmd, options);
const shouldUseOpMsg = supportsOpMsg(this);
const session = options?.session;
let clusterTime = this.clusterTime;
let finalCmd = Object.assign({}, cmd);
const inTransaction = session && (session.inTransaction() || isTransactionCommand(finalCmd));
if (this.serverApi) {
const { version, strict, deprecationErrors } = this.serverApi;
finalCmd.apiVersion = version;
if (strict != null) finalCmd.apiStrict = strict;
if (deprecationErrors != null) finalCmd.apiDeprecationErrors = deprecationErrors;
}
if (hasSessionSupport(this) && session) {
if (
session.clusterTime &&
clusterTime &&
session.clusterTime.clusterTime.greaterThan(clusterTime.clusterTime)
) {
clusterTime = session.clusterTime;
}
// We need to unpin any read or write commands that happen outside of a pinned
// transaction, so we check if we have a pinned transaction that is no longer
// active, and unpin for all except start or commit.
if (
!session.transaction.isActive &&
session.transaction.isPinned &&
!finalCmd.startTransaction &&
!finalCmd.commitTransaction
) {
session.transaction.unpinServer();
}
const err = applySession(session, finalCmd, options as CommandOptions);
if (err) {
return callback(err);
}
}
// if we have a known cluster time, gossip it
if (clusterTime) {
finalCmd.$clusterTime = clusterTime;
}
if (isSharded(this) && !shouldUseOpMsg && readPreference && readPreference.mode !== 'primary') {
finalCmd = {
$query: finalCmd,
$readPreference: readPreference.toJSON()
};
}
const commandOptions: Document = Object.assign(
{
command: true,
numberToSkip: 0,
numberToReturn: -1,
checkKeys: false,
// This value is not overridable
slaveOk: readPreference.slaveOk()
},
options
);
const cmdNs = `${ns.db}.$cmd`;
const message = shouldUseOpMsg
? new Msg(cmdNs, finalCmd, commandOptions)
: new Query(cmdNs, finalCmd, commandOptions);
const commandResponseHandler = inTransaction
? (err?: AnyError, ...args: Document[]) => {
// We need to add a TransientTransactionError errorLabel, as stated in the transaction spec.
if (
err &&
err instanceof MongoNetworkError &&
!err.hasErrorLabel('TransientTransactionError')
) {
err.addErrorLabel('TransientTransactionError');
}
if (
session &&
!cmd.commitTransaction &&
err &&
err instanceof MongoError &&
err.hasErrorLabel('TransientTransactionError')
) {
session.transaction.unpinServer();
}
return callback(err, ...args);
}
: callback;
try {
write(this, message, commandOptions, commandResponseHandler);
} catch (err) {
commandResponseHandler(err);
}
}
/** @internal */
query(ns: MongoDBNamespace, cmd: Document, options: QueryOptions, callback: Callback): void {
const isExplain = cmd.$explain != null;
const readPreference = options.readPreference ?? ReadPreference.primary;
const batchSize = options.batchSize || 0;
const limit = options.limit;
const numberToSkip = options.skip || 0;
let numberToReturn = 0;
if (
limit &&
(limit < 0 || (limit !== 0 && limit < batchSize) || (limit > 0 && batchSize === 0))
) {
numberToReturn = limit;
} else {
numberToReturn = batchSize;
}
if (isExplain) {
// nToReturn must be 0 (match all) or negative (match N and close cursor)
// nToReturn > 0 will give explain results equivalent to limit(0)
numberToReturn = -Math.abs(limit || 0);
}
const queryOptions: OpQueryOptions = {
numberToSkip,
numberToReturn,
pre32Limit: typeof limit === 'number' ? limit : undefined,
checkKeys: false,
slaveOk: readPreference.slaveOk()
};
if (options.projection) {
queryOptions.returnFieldSelector = options.projection;
}
const query = new Query(ns.toString(), cmd, queryOptions);
if (typeof options.tailable === 'boolean') {
query.tailable = options.tailable;
}
if (typeof options.oplogReplay === 'boolean') {
query.oplogReplay = options.oplogReplay;
}
if (typeof options.timeout === 'boolean') {
query.noCursorTimeout = !options.timeout;
} else if (typeof options.noCursorTimeout === 'boolean') {
query.noCursorTimeout = options.noCursorTimeout;
}
if (typeof options.awaitData === 'boolean') {
query.awaitData = options.awaitData;
}
if (typeof options.partial === 'boolean') {
query.partial = options.partial;
}
write(
this,
query,
{ fullResult: true, ...pluckBSONSerializeOptions(options) },
(err, result) => {
if (err || !result) return callback(err, result);
if (isExplain && result.documents && result.documents[0]) {
return callback(undefined, result.documents[0]);
}
callback(undefined, result);
}
);
}
/** @internal */
getMore(
ns: MongoDBNamespace,
cursorId: Long,
options: GetMoreOptions,
callback: Callback<Document>
): void {
const fullResult = typeof options.fullResult === 'boolean' ? options.fullResult : false;
const wireVersion = maxWireVersion(this);
if (!cursorId) {
// TODO(NODE-3483): Replace this with a MongoCommandError
callback(new MongoDriverError('Invalid internal cursor state, no known cursor id'));
return;
}
if (wireVersion < 4) {
const getMoreOp = new GetMore(ns.toString(), cursorId, { numberToReturn: options.batchSize });
const queryOptions = applyCommonQueryOptions(
{},
Object.assign(options, { ...pluckBSONSerializeOptions(options) })
);
queryOptions.fullResult = true;
queryOptions.command = true;
write(this, getMoreOp, queryOptions, (err, response) => {
if (fullResult) return callback(err, response);
if (err) return callback(err);
callback(undefined, { cursor: { id: response.cursorId, nextBatch: response.documents } });
});
return;
}
const getMoreCmd: Document = {
getMore: cursorId,
collection: ns.collection
};
if (typeof options.batchSize === 'number') {
getMoreCmd.batchSize = Math.abs(options.batchSize);
}
if (typeof options.maxAwaitTimeMS === 'number') {
getMoreCmd.maxTimeMS = options.maxAwaitTimeMS;
}
const commandOptions = Object.assign(
{
returnFieldSelector: null,
documentsReturnedIn: 'nextBatch'
},
options
);
this.command(ns, getMoreCmd, commandOptions, callback);
}
/** @internal */
killCursors(
ns: MongoDBNamespace,
cursorIds: Long[],
options: CommandOptions,
callback: Callback
): void {
if (!cursorIds || !Array.isArray(cursorIds)) {
// TODO(NODE-3483): Replace this with a MongoCommandError
throw new MongoDriverError(`Invalid list of cursor ids provided: ${cursorIds}`);
}
if (maxWireVersion(this) < 4) {
try {
write(
this,
new KillCursor(ns.toString(), cursorIds),
{ noResponse: true, ...options },
callback
);
} catch (err) {
callback(err);
}
return;
}
this.command(
ns,
{ killCursors: ns.collection, cursors: cursorIds },
{ fullResult: true, ...options },
(err, response) => {
if (err || !response) return callback(err);
if (response.cursorNotFound) {
return callback(new MongoNetworkError('cursor killed or timed out'), null);
}
if (!Array.isArray(response.documents) || response.documents.length === 0) {
return callback(
new MongoDriverError(
`invalid killCursors result returned for cursor id ${cursorIds[0]}`
)
);
}
callback(undefined, response.documents[0]);
}
);
}
}
/** @public */
export const APM_EVENTS = [
Connection.COMMAND_STARTED,
Connection.COMMAND_SUCCEEDED,
Connection.COMMAND_FAILED
];
/** @internal */
export class CryptoConnection extends Connection {
/** @internal */
[kAutoEncrypter]?: AutoEncrypter;
constructor(stream: Stream, options: ConnectionOptions) {
super(stream, options);
this[kAutoEncrypter] = options.autoEncrypter;
}
/** @internal @override */
command(ns: MongoDBNamespace, cmd: Document, options: CommandOptions, callback: Callback): void {
const autoEncrypter = this[kAutoEncrypter];
if (!autoEncrypter) {
return callback(new MongoMissingDependencyError('No AutoEncrypter available for encryption'));
}
const serverWireVersion = maxWireVersion(this);
if (serverWireVersion === 0) {
// This means the initial handshake hasn't happened yet
return super.command(ns, cmd, options, callback);
}
if (serverWireVersion < 8) {
callback(
new MongoCompatibilityError('Auto-encryption requires a minimum MongoDB version of 4.2')
);
return;
}
autoEncrypter.encrypt(ns.toString(), cmd, options, (err, encrypted) => {
if (err || encrypted == null) {
callback(err, null);
return;
}
super.command(ns, encrypted, options, (err, response) => {
if (err || response == null) {
callback(err, response);
return;
}
autoEncrypter.decrypt(response, options, callback);
});
});
}
}
function hasSessionSupport(conn: Connection) {
return conn.description.logicalSessionTimeoutMinutes != null;
}
function supportsOpMsg(conn: Connection) {
const description = conn.description;
if (description == null) {
return false;
}
return maxWireVersion(conn) >= 6 && !description.__nodejs_mock_server__;
}
function messageHandler(conn: Connection) {
return function messageHandler(message: BinMsg | Response) {
// always emit the message, in case we are streaming
conn.emit('message', message);
const operationDescription = conn[kQueue].get(message.responseTo);
if (!operationDescription) {
return;
}
const callback = operationDescription.cb;
// SERVER-45775: For exhaust responses we should be able to use the same requestId to
// track response, however the server currently synthetically produces remote requests
// making the `responseTo` change on each response
conn[kQueue].delete(message.responseTo);
if ('moreToCome' in message && message.moreToCome) {
// requeue the callback for next synthetic request
conn[kQueue].set(message.requestId, operationDescription);
} else if (operationDescription.socketTimeoutOverride) {
conn[kStream].setTimeout(conn.socketTimeoutMS);
}
try {
// Pass in the entire description because it has BSON parsing options
message.parse(operationDescription);
} catch (err) {
// If this error is generated by our own code, it will already have the correct class applied
// if it is not, then it is coming from a catastrophic data parse failure or the BSON library
// in either case, it should not be wrapped
callback(err);
return;
}
if (message.documents[0]) {
const document: Document = message.documents[0];
const session = operationDescription.session;
if (session) {
updateSessionFromResponse(session, document);
}
if (document.$clusterTime) {
conn[kClusterTime] = document.$clusterTime;
conn.emit(Connection.CLUSTER_TIME_RECEIVED, document.$clusterTime);
}
if (operationDescription.command) {
if (document.writeConcernError) {
callback(new MongoWriteConcernError(document.writeConcernError, document));
return;
}
if (document.ok === 0 || document.$err || document.errmsg || document.code) {
callback(new MongoServerError(document));
return;
}
} else {
// Pre 3.2 support
if (document.ok === 0 || document.$err || document.errmsg) {
callback(new MongoServerError(document));
return;
}
}
}
callback(undefined, operationDescription.fullResult ? message : message.documents[0]);
};
}
function streamIdentifier(stream: Stream) {
if (typeof stream.address === 'function') {
return `${stream.remoteAddress}:${stream.remotePort}`;
}
return uuidV4().toString('hex');
}
function write(
conn: Connection,
command: WriteProtocolMessageType,
options: CommandOptions,
callback: Callback
) {
if (typeof options === 'function') {
callback = options;
}
options = options ?? {};
const operationDescription: OperationDescription = {
requestId: command.requestId,
cb: callback,
session: options.session,
fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false,
noResponse: typeof options.noResponse === 'boolean' ? options.noResponse : false,
documentsReturnedIn: options.documentsReturnedIn,
command: !!options.command,
// for BSON parsing
promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true,
promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true,
promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false,
bsonRegExp: typeof options.bsonRegExp === 'boolean' ? options.bsonRegExp : false,
raw: typeof options.raw === 'boolean' ? options.raw : false,
started: 0
};
if (conn[kDescription] && conn[kDescription].compressor) {
operationDescription.agreedCompressor = conn[kDescription].compressor;
if (conn[kDescription].zlibCompressionLevel) {
operationDescription.zlibCompressionLevel = conn[kDescription].zlibCompressionLevel;
}
}
if (typeof options.socketTimeoutMS === 'number') {
operationDescription.socketTimeoutOverride = true;
conn[kStream].setTimeout(options.socketTimeoutMS);
}
// if command monitoring is enabled we need to modify the callback here
if (conn.monitorCommands) {
conn.emit(Connection.COMMAND_STARTED, new CommandStartedEvent(conn, command));
operationDescription.started = now();
operationDescription.cb = (err, reply) => {
if (err) {
conn.emit(
Connection.COMMAND_FAILED,
new CommandFailedEvent(conn, command, err, operationDescription.started)
);
} else {
if (reply && (reply.ok === 0 || reply.$err)) {
conn.emit(
Connection.COMMAND_FAILED,
new CommandFailedEvent(conn, command, reply, operationDescription.started)
);
} else {
conn.emit(
Connection.COMMAND_SUCCEEDED,
new CommandSucceededEvent(conn, command, reply, operationDescription.started)
);
}
}
if (typeof callback === 'function') {
callback(err, reply);
}
};
}
if (!operationDescription.noResponse) {
conn[kQueue].set(operationDescription.requestId, operationDescription);
}
try {
conn[kMessageStream].writeCommand(command, operationDescription);
} catch (e) {
if (!operationDescription.noResponse) {
conn[kQueue].delete(operationDescription.requestId);
operationDescription.cb(e);
return;
}
}
if (operationDescription.noResponse) {
operationDescription.cb();
}
}