summaryrefslogtreecommitdiff
path: root/src/mongo/shell/session.js
blob: ae49db63f722862fa4ace3889ee995ab47accf5c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
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
/**
 * Implements the sessions api for the shell.
 */
var {
    DriverSession, SessionOptions, _DummyDriverSession, _DelegatingDriverSession,
} = (function() {
    "use strict";

    function SessionOptions(rawOptions = {}) {
        let _readPreference = rawOptions.readPreference;
        let _readConcern = rawOptions.readConcern;
        let _writeConcern = rawOptions.writeConcern;
        const _initialClusterTime = rawOptions.initialClusterTime;
        const _initialOperationTime = rawOptions.initialOperationTime;
        let _causalConsistency = rawOptions.causalConsistency;
        let _retryWrites = rawOptions.retryWrites;

        this.getReadPreference = function getReadPreference() {
            return _readPreference;
        };

        this.setReadPreference = function setReadPreference(readPreference) {
            _readPreference = readPreference;
        };

        this.getReadConcern = function getReadConcern() {
            return _readConcern;
        };

        this.setReadConcern = function setReadConcern(readConcern) {
            _readConcern = readConcern;
        };

        this.getWriteConcern = function getWriteConcern() {
            return _writeConcern;
        };

        this.setWriteConcern = function setWriteConcern(writeConcern) {
            if (!(writeConcern instanceof WriteConcern)) {
                writeConcern = new WriteConcern(writeConcern);
            }
            _writeConcern = writeConcern;
        };

        this.getInitialClusterTime = function getInitialClusterTime() {
            return _initialClusterTime;
        };

        this.getInitialOperationTime = function getInitialOperationTime() {
            return _initialOperationTime;
        };

        this.isCausalConsistency = function isCausalConsistency() {
            return _causalConsistency;
        };

        this.setCausalConsistency = function setCausalConsistency(causalConsistency = true) {
            _causalConsistency = causalConsistency;
        };

        this.shouldRetryWrites = function shouldRetryWrites() {
            return _retryWrites;
        };

        this.setRetryWrites = function setRetryWrites(retryWrites = true) {
            _retryWrites = retryWrites;
        };
    }

    function SessionAwareClient(client) {
        const kWireVersionSupportingLogicalSession = 6;
        const kWireVersionSupportingCausalConsistency = 6;
        const kWireVersionSupportingRetryableWrites = 6;

        this.getReadPreference = function getReadPreference(driverSession) {
            const sessionOptions = driverSession.getOptions();
            if (sessionOptions.getReadPreference() !== undefined) {
                return sessionOptions.getReadPreference();
            }
            return client.getReadPref();
        };

        this.getReadConcern = function getReadConcern(driverSession) {
            const sessionOptions = driverSession.getOptions();
            if (sessionOptions.getReadConcern() !== undefined) {
                return sessionOptions.getReadConcern();
            }
            if (client.getReadConcern() !== undefined) {
                return {level: client.getReadConcern()};
            }
            return null;
        };

        this.getWriteConcern = function getWriteConcern(driverSession) {
            const sessionOptions = driverSession.getOptions();
            if (sessionOptions.getWriteConcern() !== undefined) {
                return sessionOptions.getWriteConcern();
            }
            return client.getWriteConcern();
        };

        function serverSupports(wireVersion) {
            return client.getMinWireVersion() <= wireVersion &&
                wireVersion <= client.getMaxWireVersion();
        }

        const kCommandsThatSupportReadConcern = new Set([
            "aggregate",
            "count",
            "distinct",
            "explain",
            "find",
            "geoNear",
            "geoSearch",
            "group",
            "mapReduce",
            "mapreduce",
            "parallelCollectionScan",
        ]);

        function canUseReadConcern(cmdObj) {
            let cmdName = Object.keys(cmdObj)[0];

            // If the command is in a wrapped form, then we look for the actual command name inside
            // the query/$query object.
            let cmdObjUnwrapped = cmdObj;
            if (cmdName === "query" || cmdName === "$query") {
                cmdObjUnwrapped = cmdObj[cmdName];
                cmdName = Object.keys(cmdObjUnwrapped)[0];
            }

            if (!kCommandsThatSupportReadConcern.has(cmdName)) {
                return false;
            }

            if (cmdName === "explain") {
                return kCommandsThatSupportReadConcern.has(Object.keys(cmdObjUnwrapped.explain)[0]);
            }

            return true;
        }

        function gossipClusterTime(cmdObj, clusterTime) {
            cmdObj = Object.assign({}, cmdObj);

            const cmdName = Object.keys(cmdObj)[0];

            // If the command is in a wrapped form, then we look for the actual command object
            // inside the query/$query object.
            let cmdObjUnwrapped = cmdObj;
            if (cmdName === "query" || cmdName === "$query") {
                cmdObj[cmdName] = Object.assign({}, cmdObj[cmdName]);
                cmdObjUnwrapped = cmdObj[cmdName];
            }

            if (!cmdObjUnwrapped.hasOwnProperty("$clusterTime")) {
                cmdObjUnwrapped.$clusterTime = clusterTime;
            }

            return cmdObj;
        }

        function injectAfterClusterTime(cmdObj, operationTime) {
            cmdObj = Object.assign({}, cmdObj);

            if (operationTime !== undefined) {
                const cmdName = Object.keys(cmdObj)[0];

                // If the command is in a wrapped form, then we look for the actual command object
                // inside the query/$query object.
                let cmdObjUnwrapped = cmdObj;
                if (cmdName === "query" || cmdName === "$query") {
                    cmdObj[cmdName] = Object.assign({}, cmdObj[cmdName]);
                    cmdObjUnwrapped = cmdObj[cmdName];
                }

                cmdObjUnwrapped.readConcern = Object.assign({}, cmdObjUnwrapped.readConcern);
                const readConcern = cmdObjUnwrapped.readConcern;

                if (!readConcern.hasOwnProperty("afterClusterTime")) {
                    readConcern.afterClusterTime = operationTime;
                }
            }

            return cmdObj;
        }

        function isNonNullObject(obj) {
            return typeof obj === "object" && obj !== null;
        }

        function prepareCommandRequest(driverSession, cmdObj) {
            if (serverSupports(kWireVersionSupportingLogicalSession)) {
                cmdObj = driverSession._serverSession.injectSessionId(cmdObj);
            }

            if (serverSupports(kWireVersionSupportingCausalConsistency) &&
                (client.isReplicaSetMember() || client.isMongos()) &&
                !jsTest.options().skipGossipingClusterTime) {
                // The `clientClusterTime` is the highest clusterTime observed by any connection
                // within this mongo shell.
                const clientClusterTime = client.getClusterTime();
                // The `sessionClusterTime` is the highest clusterTime tracked by the
                // `driverSession` session and may lag behind `clientClusterTime` if operations on
                // other sessions or connections are advancing the clusterTime.
                const sessionClusterTime = driverSession.getClusterTime();

                // We gossip the greater of the client's clusterTime and the session's clusterTime.
                // If this is the first command being sent on this connection and/or session, then
                // it's possible that either clusterTime hasn't been initialized yet. Additionally,
                // if the user specified a malformed clusterTime as part of initialClusterTime, then
                // we want the server to be the one to reject it and therefore write our comparisons
                // using bsonWoCompare() accordingly.
                if (isNonNullObject(clientClusterTime) || isNonNullObject(sessionClusterTime)) {
                    let clusterTimeToGossip;

                    if (!isNonNullObject(sessionClusterTime)) {
                        clusterTimeToGossip = clientClusterTime;
                    } else if (!isNonNullObject(clientClusterTime)) {
                        clusterTimeToGossip = sessionClusterTime;
                    } else {
                        clusterTimeToGossip =
                            (bsonWoCompare({_: clientClusterTime.clusterTime},
                                           {_: sessionClusterTime.clusterTime}) >= 0)
                            ? clientClusterTime
                            : sessionClusterTime;
                    }

                    cmdObj = gossipClusterTime(cmdObj, clusterTimeToGossip);
                }
            }

            if (serverSupports(kWireVersionSupportingCausalConsistency) &&
                (driverSession.getOptions().isCausalConsistency() ||
                 client.isCausalConsistency()) &&
                canUseReadConcern(cmdObj)) {
                // `driverSession._operationTime` is the smallest time needed for performing a
                // causally consistent read using the current session. Note that
                // `client.getClusterTime()` is no smaller than the operation time and would
                // therefore only be less efficient to wait until.
                cmdObj = injectAfterClusterTime(cmdObj, driverSession._operationTime);
            }

            if (jsTest.options().alwaysInjectTransactionNumber &&
                serverSupports(kWireVersionSupportingRetryableWrites) &&
                driverSession.getOptions().shouldRetryWrites() &&
                driverSession._serverSession.canRetryWrites(cmdObj)) {
                cmdObj = driverSession._serverSession.assignTransactionNumber(cmdObj);
            }

            return cmdObj;
        }

        function processCommandResponse(driverSession, res) {
            if (res.hasOwnProperty("operationTime") &&
                bsonWoCompare({_: res.operationTime}, {_: driverSession._operationTime}) > 0) {
                driverSession._operationTime = res.operationTime;
            }

            if (res.hasOwnProperty("$clusterTime")) {
                client.setClusterTime(res.$clusterTime);
            }
        }

        function runClientFunctionWithRetries(
            driverSession, cmdObj, clientFunction, clientFunctionArguments) {
            let cmdName = Object.keys(cmdObj)[0];

            // If the command is in a wrapped form, then we look for the actual command object
            // inside the query/$query object.
            if (cmdName === "query" || cmdName === "$query") {
                cmdObj = cmdObj[cmdName];
                cmdName = Object.keys(cmdObj)[0];
            }

            let numRetries =
                (cmdObj.hasOwnProperty("txnNumber") && !jsTest.options().skipRetryOnNetworkError)
                ? 1
                : 0;

            do {
                try {
                    return clientFunction.apply(client, clientFunctionArguments);
                } catch (e) {
                    // TODO: Should we run an explicit "isMaster" command in order to compare the
                    // wire version of the server after we reconnect to it?
                    if (!isNetworkError(e) || numRetries === 0) {
                        throw e;
                    }
                }

                --numRetries;
            } while (numRetries >= 0);
        }

        this.runCommand = function runCommand(driverSession, dbName, cmdObj, options) {
            cmdObj = prepareCommandRequest(driverSession, cmdObj);

            const res = runClientFunctionWithRetries(
                driverSession, cmdObj, client.runCommand, [dbName, cmdObj, options]);

            processCommandResponse(driverSession, res);
            return res;
        };

        this.runCommandWithMetadata = function runCommandWithMetadata(
            driverSession, dbName, metadata, cmdObj) {
            cmdObj = prepareCommandRequest(driverSession, cmdObj);

            const res = runClientFunctionWithRetries(
                driverSession, cmdObj, client.runCommandWithMetadata, [dbName, metadata, cmdObj]);

            processCommandResponse(driverSession, res);
            return res;
        };
    }

    function ServerSession(client) {
        let _lastUsed = new Date();
        let _nextTxnNum = 0;

        this.client = new SessionAwareClient(client);
        this.handle = client._startSession();

        this.getLastUsed = function getLastUsed() {
            return _lastUsed;
        };

        function updateLastUsed() {
            _lastUsed = new Date();
        }

        this.injectSessionId = function injectSessionId(cmdObj) {
            cmdObj = Object.assign({}, cmdObj);

            const cmdName = Object.keys(cmdObj)[0];

            // If the command is in a wrapped form, then we look for the actual command object
            // inside the query/$query object.
            let cmdObjUnwrapped = cmdObj;
            if (cmdName === "query" || cmdName === "$query") {
                cmdObj[cmdName] = Object.assign({}, cmdObj[cmdName]);
                cmdObjUnwrapped = cmdObj[cmdName];
            }

            if (!cmdObjUnwrapped.hasOwnProperty("lsid")) {
                cmdObjUnwrapped.lsid = this.handle.getId();

                // We consider the session to still be in use by the client any time the session id
                // is injected into the command object as part of making a request.
                updateLastUsed();
            }

            return cmdObj;
        };

        this.assignTransactionNumber = function assignTransactionNumber(cmdObj) {
            cmdObj = Object.assign({}, cmdObj);

            const cmdName = Object.keys(cmdObj)[0];

            // If the command is in a wrapped form, then we look for the actual command object
            // inside the query/$query object.
            let cmdObjUnwrapped = cmdObj;
            if (cmdName === "query" || cmdName === "$query") {
                cmdObj[cmdName] = Object.assign({}, cmdObj[cmdName]);
                cmdObjUnwrapped = cmdObj[cmdName];
            }

            if (!cmdObjUnwrapped.hasOwnProperty("txnNumber")) {
                // Since there's no native support for adding NumberLong instances and getting back
                // another NumberLong instance, converting from a 64-bit floating-point value to a
                // 64-bit integer value will overflow at 2**53.
                cmdObjUnwrapped.txnNumber = new NumberLong(_nextTxnNum);
                ++_nextTxnNum;
            }

            return cmdObj;
        };

        this.canRetryWrites = function canRetryWrites(cmdObj) {
            let cmdName = Object.keys(cmdObj)[0];

            // If the command is in a wrapped form, then we look for the actual command name inside
            // the query/$query object.
            if (cmdName === "query" || cmdName === "$query") {
                cmdObj = cmdObj[cmdName];
                cmdName = Object.keys(cmdObj)[0];
            }

            if (cmdName === "insert") {
                if (!Array.isArray(cmdObj.documents)) {
                    // The command object is malformed, so we'll just leave it as-is and let the
                    // server reject it.
                    return false;
                }

                if (cmdObj.documents.length === 1) {
                    // Single-statement operations (e.g. insertOne()) can be retried.
                    return true;
                }

                // Multi-statement operations (e.g. insertMany()) can be retried if they are
                // executed in order by the server.
                return cmdObj.ordered ? true : false;
            } else if (cmdName === "update") {
                if (!Array.isArray(cmdObj.updates)) {
                    // The command object is malformed, so we'll just leave it as-is and let the
                    // server reject it.
                    return false;
                }

                const hasMultiUpdate = cmdObj.updates.some(updateOp => updateOp.multi);
                if (hasMultiUpdate) {
                    // Operations that modify multiple documents (e.g. updateMany()) cannot be
                    // retried.
                    return false;
                }

                if (cmdObj.updates.length === 1) {
                    // Single-statement operations that modify a single document (e.g. updateOne())
                    // can be retried.
                    return true;
                }

                // Multi-statement operations that each modify a single document (e.g. bulkWrite())
                // can be retried if they are executed in order by the server.
                return cmdObj.ordered ? true : false;
            } else if (cmdName === "delete") {
                if (!Array.isArray(cmdObj.deletes)) {
                    // The command object is malformed, so we'll just leave it as-is and let the
                    // server reject it.
                    return false;
                }

                // We use bsonWoCompare() in order to handle cases where the limit is specified as a
                // NumberInt() or NumberLong() instance.
                const hasMultiDelete = cmdObj.deletes.some(
                    deleteOp => bsonWoCompare({_: deleteOp.limit}, {_: 0}) === 0);
                if (hasMultiDelete) {
                    // Operations that modify multiple documents (e.g. deleteMany()) cannot be
                    // retried.
                    return false;
                }

                if (cmdObj.deletes.length === 1) {
                    // Single-statement operations that modify a single document (e.g. deleteOne())
                    // can be retried.
                    return true;
                }

                // Multi-statement operations that each modify a single document (e.g. bulkWrite())
                // can be retried if they are executed in order by the server.
                return cmdObj.ordered ? true : false;
            } else if (cmdName === "findAndModify" || cmdName === "findandmodify") {
                // Operations that modify a single document (e.g. findOneAndUpdate()) can be
                // retried.
                return true;
            }

            return false;
        };
    }

    function makeDriverSessionConstructor(implMethods) {
        return function(client, options = {}) {
            let _options = options;
            let _hasEnded = false;

            if (!(_options instanceof SessionOptions)) {
                _options = new SessionOptions(_options);
            }

            this._serverSession = implMethods.createServerSession(client);
            this._operationTime = _options.getInitialOperationTime();

            if (_options.getInitialClusterTime() !== undefined) {
                client.setClusterTime(_options.getInitialClusterTime());
            }

            this.getClient = function getClient() {
                return client;
            };

            this._getSessionAwareClient = function _getSessionAwareClient() {
                return this._serverSession.client;
            };

            this.getOptions = function getOptions() {
                return _options;
            };

            this.getOperationTime = function getOperationTime() {
                return this._operationTime;
            };

            this.getClusterTime = function getClusterTime() {
                return client.getClusterTime();
            };

            this.getDatabase = function getDatabase(dbName) {
                const db = client.getDB(dbName);
                db._session = this;
                return db;
            };

            this.hasEnded = function hasEnded() {
                return _hasEnded;
            };

            this.endSession = function endSession() {
                if (this._hasEnded) {
                    return;
                }

                this._hasEnded = true;
                implMethods.endSession(this._serverSession);
            };
        };
    }

    const DriverSession = makeDriverSessionConstructor({
        createServerSession: function createServerSession(client) {
            return new ServerSession(client);
        },

        endSession: function endSession(serverSession) {
            serverSession.handle.end();
        },
    });

    function DelegatingDriverSession(client, originalSession) {
        this._serverSession = originalSession._serverSession;
        Object.defineProperty(this, "_operationTime", {
            get: function() {
                return originalSession._operationTime;
            },
            set: function(operationTime) {
                originalSession._operationTime = operationTime;
            },
        });
        const sessionAwareClient = new SessionAwareClient(client);

        this.getClient = function() {
            return client;
        };

        this._getSessionAwareClient = function() {
            return sessionAwareClient;
        };

        this.getOptions = function() {
            return originalSession.getOptions();
        };

        this.getOperationTime = function getOperationTime() {
            return this._operationTime;
        };

        this.getClusterTime = function getClusterTime() {
            return originalSession.getClusterTime();
        };

        this.getDatabase = function(dbName) {
            const db = client.getDB(dbName);
            db._session = this;
            return db;
        };

        this.hasEnded = function() {
            return originalSession.hasEnded();
        };

        this.endSession = function() {
            return originalSession.endSession();
        };
    }

    const DummyDriverSession = makeDriverSessionConstructor({
        createServerSession: function createServerSession(client) {
            return {
                client: new SessionAwareClient(client),

                injectSessionId: function injectSessionId(cmdObj) {
                    return cmdObj;
                },

                assignTransactionNumber: function assignTransactionNumber(cmdObj) {
                    return cmdObj;
                },

                canRetryWrites: function canRetryWrites(cmdObj) {
                    return false;
                },
            };
        },

        endSession: function endSession(serverSession) {},
    });

    // We don't actually put anything on DriverSession.prototype, but this way
    // `session instanceof DriverSession` will work for DummyDriverSession instances.
    DummyDriverSession.prototype = Object.create(DriverSession.prototype);
    DummyDriverSession.prototype.constructor = DriverSession;

    return {
        DriverSession: DriverSession,
        SessionOptions: SessionOptions,
        _DummyDriverSession: DummyDriverSession,
        _DelegatingDriverSession: DelegatingDriverSession,
    };
})();