sessions.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.ServerSessionPool = exports.ServerSession = exports.ClientSession = void 0;
  4. exports.maybeClearPinnedConnection = maybeClearPinnedConnection;
  5. exports.applySession = applySession;
  6. exports.updateSessionFromResponse = updateSessionFromResponse;
  7. const bson_1 = require("./bson");
  8. const metrics_1 = require("./cmap/metrics");
  9. const constants_1 = require("./constants");
  10. const error_1 = require("./error");
  11. const mongo_types_1 = require("./mongo_types");
  12. const execute_operation_1 = require("./operations/execute_operation");
  13. const run_command_1 = require("./operations/run_command");
  14. const read_concern_1 = require("./read_concern");
  15. const read_preference_1 = require("./read_preference");
  16. const common_1 = require("./sdam/common");
  17. const timeout_1 = require("./timeout");
  18. const transactions_1 = require("./transactions");
  19. const utils_1 = require("./utils");
  20. const write_concern_1 = require("./write_concern");
  21. /**
  22. * A class representing a client session on the server
  23. *
  24. * NOTE: not meant to be instantiated directly.
  25. * @public
  26. */
  27. class ClientSession extends mongo_types_1.TypedEventEmitter {
  28. /**
  29. * Create a client session.
  30. * @internal
  31. * @param client - The current client
  32. * @param sessionPool - The server session pool (Internal Class)
  33. * @param options - Optional settings
  34. * @param clientOptions - Optional settings provided when creating a MongoClient
  35. */
  36. constructor(client, sessionPool, options, clientOptions) {
  37. super();
  38. /** @internal */
  39. this.timeoutContext = null;
  40. this.on('error', utils_1.noop);
  41. if (client == null) {
  42. // TODO(NODE-3483)
  43. throw new error_1.MongoRuntimeError('ClientSession requires a MongoClient');
  44. }
  45. if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) {
  46. // TODO(NODE-3483)
  47. throw new error_1.MongoRuntimeError('ClientSession requires a ServerSessionPool');
  48. }
  49. options = options ?? {};
  50. this.snapshotEnabled = options.snapshot === true;
  51. if (options.causalConsistency === true && this.snapshotEnabled) {
  52. throw new error_1.MongoInvalidArgumentError('Properties "causalConsistency" and "snapshot" are mutually exclusive');
  53. }
  54. this.client = client;
  55. this.sessionPool = sessionPool;
  56. this.hasEnded = false;
  57. this.clientOptions = clientOptions;
  58. this.timeoutMS = options.defaultTimeoutMS ?? client.s.options?.timeoutMS;
  59. this.explicit = !!options.explicit;
  60. this._serverSession = this.explicit ? this.sessionPool.acquire() : null;
  61. this.txnNumberIncrement = 0;
  62. const defaultCausalConsistencyValue = this.explicit && options.snapshot !== true;
  63. this.supports = {
  64. // if we can enable causal consistency, do so by default
  65. causalConsistency: options.causalConsistency ?? defaultCausalConsistencyValue
  66. };
  67. this.clusterTime = options.initialClusterTime;
  68. this.operationTime = undefined;
  69. this.owner = options.owner;
  70. this.defaultTransactionOptions = { ...options.defaultTransactionOptions };
  71. this.transaction = new transactions_1.Transaction();
  72. }
  73. /** The server id associated with this session */
  74. get id() {
  75. return this.serverSession?.id;
  76. }
  77. get serverSession() {
  78. let serverSession = this._serverSession;
  79. if (serverSession == null) {
  80. if (this.explicit) {
  81. throw new error_1.MongoRuntimeError('Unexpected null serverSession for an explicit session');
  82. }
  83. if (this.hasEnded) {
  84. throw new error_1.MongoRuntimeError('Unexpected null serverSession for an ended implicit session');
  85. }
  86. serverSession = this.sessionPool.acquire();
  87. this._serverSession = serverSession;
  88. }
  89. return serverSession;
  90. }
  91. get loadBalanced() {
  92. return this.client.topology?.description.type === common_1.TopologyType.LoadBalanced;
  93. }
  94. /** @internal */
  95. pin(conn) {
  96. if (this.pinnedConnection) {
  97. throw TypeError('Cannot pin multiple connections to the same session');
  98. }
  99. this.pinnedConnection = conn;
  100. conn.emit(constants_1.PINNED, this.inTransaction() ? metrics_1.ConnectionPoolMetrics.TXN : metrics_1.ConnectionPoolMetrics.CURSOR);
  101. }
  102. /** @internal */
  103. unpin(options) {
  104. if (this.loadBalanced) {
  105. return maybeClearPinnedConnection(this, options);
  106. }
  107. this.transaction.unpinServer();
  108. }
  109. get isPinned() {
  110. return this.loadBalanced ? !!this.pinnedConnection : this.transaction.isPinned;
  111. }
  112. /**
  113. * Frees any client-side resources held by the current session. If a session is in a transaction,
  114. * the transaction is aborted.
  115. *
  116. * Does not end the session on the server.
  117. *
  118. * @param options - Optional settings. Currently reserved for future use
  119. */
  120. async endSession(options) {
  121. try {
  122. if (this.inTransaction()) {
  123. await this.abortTransaction({ ...options, throwTimeout: true });
  124. }
  125. }
  126. catch (error) {
  127. // spec indicates that we should ignore all errors for `endSessions`
  128. if (error.name === 'MongoOperationTimeoutError')
  129. throw error;
  130. (0, utils_1.squashError)(error);
  131. }
  132. finally {
  133. if (!this.hasEnded) {
  134. const serverSession = this.serverSession;
  135. if (serverSession != null) {
  136. // release the server session back to the pool
  137. this.sessionPool.release(serverSession);
  138. // Store a clone of the server session for reference (debugging)
  139. this._serverSession = new ServerSession(serverSession);
  140. }
  141. // mark the session as ended, and emit a signal
  142. this.hasEnded = true;
  143. this.emit('ended', this);
  144. }
  145. maybeClearPinnedConnection(this, { force: true, ...options });
  146. }
  147. }
  148. /**
  149. * @experimental
  150. * An alias for {@link ClientSession.endSession|ClientSession.endSession()}.
  151. */
  152. async [Symbol.asyncDispose]() {
  153. await this.endSession({ force: true });
  154. }
  155. /**
  156. * Advances the operationTime for a ClientSession.
  157. *
  158. * @param operationTime - the `BSON.Timestamp` of the operation type it is desired to advance to
  159. */
  160. advanceOperationTime(operationTime) {
  161. if (this.operationTime == null) {
  162. this.operationTime = operationTime;
  163. return;
  164. }
  165. if (operationTime.greaterThan(this.operationTime)) {
  166. this.operationTime = operationTime;
  167. }
  168. }
  169. /**
  170. * Advances the clusterTime for a ClientSession to the provided clusterTime of another ClientSession
  171. *
  172. * @param clusterTime - the $clusterTime returned by the server from another session in the form of a document containing the `BSON.Timestamp` clusterTime and signature
  173. */
  174. advanceClusterTime(clusterTime) {
  175. if (!clusterTime || typeof clusterTime !== 'object') {
  176. throw new error_1.MongoInvalidArgumentError('input cluster time must be an object');
  177. }
  178. if (!clusterTime.clusterTime || clusterTime.clusterTime._bsontype !== 'Timestamp') {
  179. throw new error_1.MongoInvalidArgumentError('input cluster time "clusterTime" property must be a valid BSON Timestamp');
  180. }
  181. if (!clusterTime.signature ||
  182. clusterTime.signature.hash?._bsontype !== 'Binary' ||
  183. (typeof clusterTime.signature.keyId !== 'bigint' &&
  184. typeof clusterTime.signature.keyId !== 'number' &&
  185. clusterTime.signature.keyId?._bsontype !== 'Long') // apparently we decode the key to number?
  186. ) {
  187. throw new error_1.MongoInvalidArgumentError('input cluster time must have a valid "signature" property with BSON Binary hash and BSON Long keyId');
  188. }
  189. (0, common_1._advanceClusterTime)(this, clusterTime);
  190. }
  191. /**
  192. * Used to determine if this session equals another
  193. *
  194. * @param session - The session to compare to
  195. */
  196. equals(session) {
  197. if (!(session instanceof ClientSession)) {
  198. return false;
  199. }
  200. if (this.id == null || session.id == null) {
  201. return false;
  202. }
  203. return utils_1.ByteUtils.equals(this.id.id.buffer, session.id.id.buffer);
  204. }
  205. /**
  206. * Increment the transaction number on the internal ServerSession
  207. *
  208. * @privateRemarks
  209. * This helper increments a value stored on the client session that will be
  210. * added to the serverSession's txnNumber upon applying it to a command.
  211. * This is because the serverSession is lazily acquired after a connection is obtained
  212. */
  213. incrementTransactionNumber() {
  214. this.txnNumberIncrement += 1;
  215. }
  216. /** @returns whether this session is currently in a transaction or not */
  217. inTransaction() {
  218. return this.transaction.isActive;
  219. }
  220. /**
  221. * Starts a new transaction with the given options.
  222. *
  223. * @remarks
  224. * **IMPORTANT**: Running operations in parallel is not supported during a transaction. The use of `Promise.all`,
  225. * `Promise.allSettled`, `Promise.race`, etc to parallelize operations inside a transaction is
  226. * undefined behaviour.
  227. *
  228. * @param options - Options for the transaction
  229. */
  230. startTransaction(options) {
  231. if (this.snapshotEnabled) {
  232. throw new error_1.MongoCompatibilityError('Transactions are not supported in snapshot sessions');
  233. }
  234. if (this.inTransaction()) {
  235. throw new error_1.MongoTransactionError('Transaction already in progress');
  236. }
  237. if (this.isPinned && this.transaction.isCommitted) {
  238. this.unpin();
  239. }
  240. this.commitAttempted = false;
  241. // increment txnNumber
  242. this.incrementTransactionNumber();
  243. // create transaction state
  244. this.transaction = new transactions_1.Transaction({
  245. readConcern: options?.readConcern ??
  246. this.defaultTransactionOptions.readConcern ??
  247. this.clientOptions?.readConcern,
  248. writeConcern: options?.writeConcern ??
  249. this.defaultTransactionOptions.writeConcern ??
  250. this.clientOptions?.writeConcern,
  251. readPreference: options?.readPreference ??
  252. this.defaultTransactionOptions.readPreference ??
  253. this.clientOptions?.readPreference,
  254. maxCommitTimeMS: options?.maxCommitTimeMS ?? this.defaultTransactionOptions.maxCommitTimeMS
  255. });
  256. this.transaction.transition(transactions_1.TxnState.STARTING_TRANSACTION);
  257. }
  258. /**
  259. * Commits the currently active transaction in this session.
  260. *
  261. * @param options - Optional options, can be used to override `defaultTimeoutMS`.
  262. */
  263. async commitTransaction(options) {
  264. if (this.transaction.state === transactions_1.TxnState.NO_TRANSACTION) {
  265. throw new error_1.MongoTransactionError('No transaction started');
  266. }
  267. if (this.transaction.state === transactions_1.TxnState.STARTING_TRANSACTION ||
  268. this.transaction.state === transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY) {
  269. // the transaction was never started, we can safely exit here
  270. this.transaction.transition(transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY);
  271. return;
  272. }
  273. if (this.transaction.state === transactions_1.TxnState.TRANSACTION_ABORTED) {
  274. throw new error_1.MongoTransactionError('Cannot call commitTransaction after calling abortTransaction');
  275. }
  276. const command = { commitTransaction: 1 };
  277. const timeoutMS = typeof options?.timeoutMS === 'number'
  278. ? options.timeoutMS
  279. : typeof this.timeoutMS === 'number'
  280. ? this.timeoutMS
  281. : null;
  282. const wc = this.transaction.options.writeConcern ?? this.clientOptions?.writeConcern;
  283. if (wc != null) {
  284. if (timeoutMS == null && this.timeoutContext == null) {
  285. write_concern_1.WriteConcern.apply(command, { wtimeoutMS: 10000, w: 'majority', ...wc });
  286. }
  287. else {
  288. const wcKeys = Object.keys(wc);
  289. if (wcKeys.length > 2 || (!wcKeys.includes('wtimeoutMS') && !wcKeys.includes('wTimeoutMS')))
  290. // if the write concern was specified with wTimeoutMS, then we set both wtimeoutMS and wTimeoutMS, guaranteeing at least two keys, so if we have more than two keys, then we can automatically assume that we should add the write concern to the command. If it has 2 or fewer keys, we need to check that those keys aren't the wtimeoutMS or wTimeoutMS options before we add the write concern to the command
  291. write_concern_1.WriteConcern.apply(command, { ...wc, wtimeoutMS: undefined });
  292. }
  293. }
  294. if (this.transaction.state === transactions_1.TxnState.TRANSACTION_COMMITTED || this.commitAttempted) {
  295. if (timeoutMS == null && this.timeoutContext == null) {
  296. write_concern_1.WriteConcern.apply(command, { wtimeoutMS: 10000, ...wc, w: 'majority' });
  297. }
  298. else {
  299. write_concern_1.WriteConcern.apply(command, { w: 'majority', ...wc, wtimeoutMS: undefined });
  300. }
  301. }
  302. if (typeof this.transaction.options.maxTimeMS === 'number') {
  303. command.maxTimeMS = this.transaction.options.maxTimeMS;
  304. }
  305. if (this.transaction.recoveryToken) {
  306. command.recoveryToken = this.transaction.recoveryToken;
  307. }
  308. const operation = new run_command_1.RunCommandOperation(new utils_1.MongoDBNamespace('admin'), command, {
  309. session: this,
  310. readPreference: read_preference_1.ReadPreference.primary,
  311. bypassPinningCheck: true
  312. });
  313. const timeoutContext = this.timeoutContext ??
  314. (typeof timeoutMS === 'number'
  315. ? timeout_1.TimeoutContext.create({
  316. serverSelectionTimeoutMS: this.clientOptions.serverSelectionTimeoutMS,
  317. socketTimeoutMS: this.clientOptions.socketTimeoutMS,
  318. timeoutMS
  319. })
  320. : null);
  321. try {
  322. await (0, execute_operation_1.executeOperation)(this.client, operation, timeoutContext);
  323. this.commitAttempted = undefined;
  324. return;
  325. }
  326. catch (firstCommitError) {
  327. this.commitAttempted = true;
  328. if (firstCommitError instanceof error_1.MongoError && (0, error_1.isRetryableWriteError)(firstCommitError)) {
  329. // SPEC-1185: apply majority write concern when retrying commitTransaction
  330. write_concern_1.WriteConcern.apply(command, { wtimeoutMS: 10000, ...wc, w: 'majority' });
  331. // per txns spec, must unpin session in this case
  332. this.unpin({ force: true });
  333. try {
  334. await (0, execute_operation_1.executeOperation)(this.client, new run_command_1.RunCommandOperation(new utils_1.MongoDBNamespace('admin'), command, {
  335. session: this,
  336. readPreference: read_preference_1.ReadPreference.primary,
  337. bypassPinningCheck: true
  338. }), timeoutContext);
  339. return;
  340. }
  341. catch (retryCommitError) {
  342. // If the retry failed, we process that error instead of the original
  343. if (shouldAddUnknownTransactionCommitResultLabel(retryCommitError)) {
  344. retryCommitError.addErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult);
  345. }
  346. if (shouldUnpinAfterCommitError(retryCommitError)) {
  347. this.unpin({ error: retryCommitError });
  348. }
  349. throw retryCommitError;
  350. }
  351. }
  352. if (shouldAddUnknownTransactionCommitResultLabel(firstCommitError)) {
  353. firstCommitError.addErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult);
  354. }
  355. if (shouldUnpinAfterCommitError(firstCommitError)) {
  356. this.unpin({ error: firstCommitError });
  357. }
  358. throw firstCommitError;
  359. }
  360. finally {
  361. this.transaction.transition(transactions_1.TxnState.TRANSACTION_COMMITTED);
  362. }
  363. }
  364. async abortTransaction(options) {
  365. if (this.transaction.state === transactions_1.TxnState.NO_TRANSACTION) {
  366. throw new error_1.MongoTransactionError('No transaction started');
  367. }
  368. if (this.transaction.state === transactions_1.TxnState.STARTING_TRANSACTION) {
  369. // the transaction was never started, we can safely exit here
  370. this.transaction.transition(transactions_1.TxnState.TRANSACTION_ABORTED);
  371. return;
  372. }
  373. if (this.transaction.state === transactions_1.TxnState.TRANSACTION_ABORTED) {
  374. throw new error_1.MongoTransactionError('Cannot call abortTransaction twice');
  375. }
  376. if (this.transaction.state === transactions_1.TxnState.TRANSACTION_COMMITTED ||
  377. this.transaction.state === transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY) {
  378. throw new error_1.MongoTransactionError('Cannot call abortTransaction after calling commitTransaction');
  379. }
  380. const command = { abortTransaction: 1 };
  381. const timeoutMS = typeof options?.timeoutMS === 'number'
  382. ? options.timeoutMS
  383. : this.timeoutContext?.csotEnabled()
  384. ? this.timeoutContext.timeoutMS // refresh timeoutMS for abort operation
  385. : typeof this.timeoutMS === 'number'
  386. ? this.timeoutMS
  387. : null;
  388. const timeoutContext = timeoutMS != null
  389. ? timeout_1.TimeoutContext.create({
  390. timeoutMS,
  391. serverSelectionTimeoutMS: this.clientOptions.serverSelectionTimeoutMS,
  392. socketTimeoutMS: this.clientOptions.socketTimeoutMS
  393. })
  394. : null;
  395. const wc = this.transaction.options.writeConcern ?? this.clientOptions?.writeConcern;
  396. if (wc != null && timeoutMS == null) {
  397. write_concern_1.WriteConcern.apply(command, { wtimeoutMS: 10000, w: 'majority', ...wc });
  398. }
  399. if (this.transaction.recoveryToken) {
  400. command.recoveryToken = this.transaction.recoveryToken;
  401. }
  402. const operation = new run_command_1.RunCommandOperation(new utils_1.MongoDBNamespace('admin'), command, {
  403. session: this,
  404. readPreference: read_preference_1.ReadPreference.primary,
  405. bypassPinningCheck: true
  406. });
  407. try {
  408. await (0, execute_operation_1.executeOperation)(this.client, operation, timeoutContext);
  409. this.unpin();
  410. return;
  411. }
  412. catch (firstAbortError) {
  413. this.unpin();
  414. if (firstAbortError.name === 'MongoRuntimeError')
  415. throw firstAbortError;
  416. if (options?.throwTimeout && firstAbortError.name === 'MongoOperationTimeoutError') {
  417. throw firstAbortError;
  418. }
  419. if (firstAbortError instanceof error_1.MongoError && (0, error_1.isRetryableWriteError)(firstAbortError)) {
  420. try {
  421. await (0, execute_operation_1.executeOperation)(this.client, operation, timeoutContext);
  422. return;
  423. }
  424. catch (secondAbortError) {
  425. if (secondAbortError.name === 'MongoRuntimeError')
  426. throw secondAbortError;
  427. if (options?.throwTimeout && secondAbortError.name === 'MongoOperationTimeoutError') {
  428. throw secondAbortError;
  429. }
  430. // we do not retry the retry
  431. }
  432. }
  433. // The spec indicates that if the operation times out or fails with a non-retryable error, we should ignore all errors on `abortTransaction`
  434. }
  435. finally {
  436. this.transaction.transition(transactions_1.TxnState.TRANSACTION_ABORTED);
  437. if (this.loadBalanced) {
  438. maybeClearPinnedConnection(this, { force: false });
  439. }
  440. }
  441. }
  442. /**
  443. * This is here to ensure that ClientSession is never serialized to BSON.
  444. */
  445. toBSON() {
  446. throw new error_1.MongoRuntimeError('ClientSession cannot be serialized to BSON.');
  447. }
  448. /**
  449. * Starts a transaction and runs a provided function, ensuring the commitTransaction is always attempted when all operations run in the function have completed.
  450. *
  451. * **IMPORTANT:** This method requires the function passed in to return a Promise. That promise must be made by `await`-ing all operations in such a way that rejections are propagated to the returned promise.
  452. *
  453. * **IMPORTANT:** Running operations in parallel is not supported during a transaction. The use of `Promise.all`,
  454. * `Promise.allSettled`, `Promise.race`, etc to parallelize operations inside a transaction is
  455. * undefined behaviour.
  456. *
  457. * **IMPORTANT:** When running an operation inside a `withTransaction` callback, if it is not
  458. * provided the explicit session in its options, it will not be part of the transaction and it will not respect timeoutMS.
  459. *
  460. *
  461. * @remarks
  462. * - If all operations successfully complete and the `commitTransaction` operation is successful, then the provided function will return the result of the provided function.
  463. * - If the transaction is unable to complete or an error is thrown from within the provided function, then the provided function will throw an error.
  464. * - If the transaction is manually aborted within the provided function it will not throw.
  465. * - If the driver needs to attempt to retry the operations, the provided function may be called multiple times.
  466. *
  467. * Checkout a descriptive example here:
  468. * @see https://www.mongodb.com/blog/post/quick-start-nodejs--mongodb--how-to-implement-transactions
  469. *
  470. * If a command inside withTransaction fails:
  471. * - It may cause the transaction on the server to be aborted.
  472. * - This situation is normally handled transparently by the driver.
  473. * - However, if the application catches such an error and does not rethrow it, the driver will not be able to determine whether the transaction was aborted or not.
  474. * - The driver will then retry the transaction indefinitely.
  475. *
  476. * To avoid this situation, the application must not silently handle errors within the provided function.
  477. * If the application needs to handle errors within, it must await all operations such that if an operation is rejected it becomes the rejection of the callback function passed into withTransaction.
  478. *
  479. * @param fn - callback to run within a transaction
  480. * @param options - optional settings for the transaction
  481. * @returns A raw command response or undefined
  482. */
  483. async withTransaction(fn, options) {
  484. const MAX_TIMEOUT = 120000;
  485. const timeoutMS = options?.timeoutMS ?? this.timeoutMS ?? null;
  486. this.timeoutContext =
  487. timeoutMS != null
  488. ? timeout_1.TimeoutContext.create({
  489. timeoutMS,
  490. serverSelectionTimeoutMS: this.clientOptions.serverSelectionTimeoutMS,
  491. socketTimeoutMS: this.clientOptions.socketTimeoutMS
  492. })
  493. : null;
  494. const startTime = this.timeoutContext?.csotEnabled() ? this.timeoutContext.start : (0, utils_1.now)();
  495. let committed = false;
  496. let result;
  497. try {
  498. while (!committed) {
  499. this.startTransaction(options); // may throw on error
  500. try {
  501. const promise = fn(this);
  502. if (!(0, utils_1.isPromiseLike)(promise)) {
  503. throw new error_1.MongoInvalidArgumentError('Function provided to `withTransaction` must return a Promise');
  504. }
  505. result = await promise;
  506. if (this.transaction.state === transactions_1.TxnState.NO_TRANSACTION ||
  507. this.transaction.state === transactions_1.TxnState.TRANSACTION_COMMITTED ||
  508. this.transaction.state === transactions_1.TxnState.TRANSACTION_ABORTED) {
  509. // Assume callback intentionally ended the transaction
  510. return result;
  511. }
  512. }
  513. catch (fnError) {
  514. if (!(fnError instanceof error_1.MongoError) || fnError instanceof error_1.MongoInvalidArgumentError) {
  515. await this.abortTransaction();
  516. throw fnError;
  517. }
  518. if (this.transaction.state === transactions_1.TxnState.STARTING_TRANSACTION ||
  519. this.transaction.state === transactions_1.TxnState.TRANSACTION_IN_PROGRESS) {
  520. await this.abortTransaction();
  521. }
  522. if (fnError.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError) &&
  523. (this.timeoutContext != null || (0, utils_1.now)() - startTime < MAX_TIMEOUT)) {
  524. continue;
  525. }
  526. throw fnError;
  527. }
  528. while (!committed) {
  529. try {
  530. /*
  531. * We will rely on ClientSession.commitTransaction() to
  532. * apply a majority write concern if commitTransaction is
  533. * being retried (see: DRIVERS-601)
  534. */
  535. await this.commitTransaction();
  536. committed = true;
  537. }
  538. catch (commitError) {
  539. /*
  540. * Note: a maxTimeMS error will have the MaxTimeMSExpired
  541. * code (50) and can be reported as a top-level error or
  542. * inside writeConcernError, ex.
  543. * { ok:0, code: 50, codeName: 'MaxTimeMSExpired' }
  544. * { ok:1, writeConcernError: { code: 50, codeName: 'MaxTimeMSExpired' } }
  545. */
  546. if (!isMaxTimeMSExpiredError(commitError) &&
  547. commitError.hasErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult) &&
  548. (this.timeoutContext != null || (0, utils_1.now)() - startTime < MAX_TIMEOUT)) {
  549. continue;
  550. }
  551. if (commitError.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError) &&
  552. (this.timeoutContext != null || (0, utils_1.now)() - startTime < MAX_TIMEOUT)) {
  553. break;
  554. }
  555. throw commitError;
  556. }
  557. }
  558. }
  559. return result;
  560. }
  561. finally {
  562. this.timeoutContext = null;
  563. }
  564. }
  565. }
  566. exports.ClientSession = ClientSession;
  567. const NON_DETERMINISTIC_WRITE_CONCERN_ERRORS = new Set([
  568. 'CannotSatisfyWriteConcern',
  569. 'UnknownReplWriteConcern',
  570. 'UnsatisfiableWriteConcern'
  571. ]);
  572. function shouldUnpinAfterCommitError(commitError) {
  573. if (commitError instanceof error_1.MongoError) {
  574. if ((0, error_1.isRetryableWriteError)(commitError) ||
  575. commitError instanceof error_1.MongoWriteConcernError ||
  576. isMaxTimeMSExpiredError(commitError)) {
  577. if (isUnknownTransactionCommitResult(commitError)) {
  578. // per txns spec, must unpin session in this case
  579. return true;
  580. }
  581. }
  582. else if (commitError.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) {
  583. return true;
  584. }
  585. }
  586. return false;
  587. }
  588. function shouldAddUnknownTransactionCommitResultLabel(commitError) {
  589. let ok = (0, error_1.isRetryableWriteError)(commitError);
  590. ok ||= commitError instanceof error_1.MongoWriteConcernError;
  591. ok ||= isMaxTimeMSExpiredError(commitError);
  592. ok &&= isUnknownTransactionCommitResult(commitError);
  593. return ok;
  594. }
  595. function isUnknownTransactionCommitResult(err) {
  596. const isNonDeterministicWriteConcernError = err instanceof error_1.MongoServerError &&
  597. err.codeName &&
  598. NON_DETERMINISTIC_WRITE_CONCERN_ERRORS.has(err.codeName);
  599. return (isMaxTimeMSExpiredError(err) ||
  600. (!isNonDeterministicWriteConcernError &&
  601. err.code !== error_1.MONGODB_ERROR_CODES.UnsatisfiableWriteConcern &&
  602. err.code !== error_1.MONGODB_ERROR_CODES.UnknownReplWriteConcern));
  603. }
  604. function maybeClearPinnedConnection(session, options) {
  605. // unpin a connection if it has been pinned
  606. const conn = session.pinnedConnection;
  607. const error = options?.error;
  608. if (session.inTransaction() &&
  609. error &&
  610. error instanceof error_1.MongoError &&
  611. error.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) {
  612. return;
  613. }
  614. const topology = session.client.topology;
  615. // NOTE: the spec talks about what to do on a network error only, but the tests seem to
  616. // to validate that we don't unpin on _all_ errors?
  617. if (conn && topology != null) {
  618. const servers = Array.from(topology.s.servers.values());
  619. const loadBalancer = servers[0];
  620. if (options?.error == null || options?.force) {
  621. loadBalancer.pool.checkIn(conn);
  622. session.pinnedConnection = undefined;
  623. conn.emit(constants_1.UNPINNED, session.transaction.state !== transactions_1.TxnState.NO_TRANSACTION
  624. ? metrics_1.ConnectionPoolMetrics.TXN
  625. : metrics_1.ConnectionPoolMetrics.CURSOR);
  626. if (options?.forceClear) {
  627. loadBalancer.pool.clear({ serviceId: conn.serviceId });
  628. }
  629. }
  630. }
  631. }
  632. function isMaxTimeMSExpiredError(err) {
  633. if (err == null || !(err instanceof error_1.MongoServerError)) {
  634. return false;
  635. }
  636. return (err.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired ||
  637. err.writeConcernError?.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired);
  638. }
  639. /**
  640. * Reflects the existence of a session on the server. Can be reused by the session pool.
  641. * WARNING: not meant to be instantiated directly. For internal use only.
  642. * @public
  643. */
  644. class ServerSession {
  645. /** @internal */
  646. constructor(cloned) {
  647. if (cloned != null) {
  648. const idBytes = Buffer.allocUnsafe(16);
  649. idBytes.set(cloned.id.id.buffer);
  650. this.id = { id: new bson_1.Binary(idBytes, cloned.id.id.sub_type) };
  651. this.lastUse = cloned.lastUse;
  652. this.txnNumber = cloned.txnNumber;
  653. this.isDirty = cloned.isDirty;
  654. return;
  655. }
  656. this.id = { id: new bson_1.Binary((0, utils_1.uuidV4)(), bson_1.Binary.SUBTYPE_UUID) };
  657. this.lastUse = (0, utils_1.now)();
  658. this.txnNumber = 0;
  659. this.isDirty = false;
  660. }
  661. /**
  662. * Determines if the server session has timed out.
  663. *
  664. * @param sessionTimeoutMinutes - The server's "logicalSessionTimeoutMinutes"
  665. */
  666. hasTimedOut(sessionTimeoutMinutes) {
  667. // Take the difference of the lastUse timestamp and now, which will result in a value in
  668. // milliseconds, and then convert milliseconds to minutes to compare to `sessionTimeoutMinutes`
  669. const idleTimeMinutes = Math.round((((0, utils_1.calculateDurationInMs)(this.lastUse) % 86400000) % 3600000) / 60000);
  670. return idleTimeMinutes > sessionTimeoutMinutes - 1;
  671. }
  672. }
  673. exports.ServerSession = ServerSession;
  674. /**
  675. * Maintains a pool of Server Sessions.
  676. * For internal use only
  677. * @internal
  678. */
  679. class ServerSessionPool {
  680. constructor(client) {
  681. if (client == null) {
  682. throw new error_1.MongoRuntimeError('ServerSessionPool requires a MongoClient');
  683. }
  684. this.client = client;
  685. this.sessions = new utils_1.List();
  686. }
  687. /**
  688. * Acquire a Server Session from the pool.
  689. * Iterates through each session in the pool, removing any stale sessions
  690. * along the way. The first non-stale session found is removed from the
  691. * pool and returned. If no non-stale session is found, a new ServerSession is created.
  692. */
  693. acquire() {
  694. const sessionTimeoutMinutes = this.client.topology?.logicalSessionTimeoutMinutes ?? 10;
  695. let session = null;
  696. // Try to obtain from session pool
  697. while (this.sessions.length > 0) {
  698. const potentialSession = this.sessions.shift();
  699. if (potentialSession != null &&
  700. (!!this.client.topology?.loadBalanced ||
  701. !potentialSession.hasTimedOut(sessionTimeoutMinutes))) {
  702. session = potentialSession;
  703. break;
  704. }
  705. }
  706. // If nothing valid came from the pool make a new one
  707. if (session == null) {
  708. session = new ServerSession();
  709. }
  710. return session;
  711. }
  712. /**
  713. * Release a session to the session pool
  714. * Adds the session back to the session pool if the session has not timed out yet.
  715. * This method also removes any stale sessions from the pool.
  716. *
  717. * @param session - The session to release to the pool
  718. */
  719. release(session) {
  720. const sessionTimeoutMinutes = this.client.topology?.logicalSessionTimeoutMinutes ?? 10;
  721. if (this.client.topology?.loadBalanced && !sessionTimeoutMinutes) {
  722. this.sessions.unshift(session);
  723. }
  724. if (!sessionTimeoutMinutes) {
  725. return;
  726. }
  727. this.sessions.prune(session => session.hasTimedOut(sessionTimeoutMinutes));
  728. if (!session.hasTimedOut(sessionTimeoutMinutes)) {
  729. if (session.isDirty) {
  730. return;
  731. }
  732. // otherwise, readd this session to the session pool
  733. this.sessions.unshift(session);
  734. }
  735. }
  736. }
  737. exports.ServerSessionPool = ServerSessionPool;
  738. /**
  739. * Optionally decorate a command with sessions specific keys
  740. *
  741. * @param session - the session tracking transaction state
  742. * @param command - the command to decorate
  743. * @param options - Optional settings passed to calling operation
  744. *
  745. * @internal
  746. */
  747. function applySession(session, command, options) {
  748. if (session.hasEnded) {
  749. return new error_1.MongoExpiredSessionError();
  750. }
  751. // May acquire serverSession here
  752. const serverSession = session.serverSession;
  753. if (serverSession == null) {
  754. return new error_1.MongoRuntimeError('Unable to acquire server session');
  755. }
  756. if (options.writeConcern?.w === 0) {
  757. if (session && session.explicit) {
  758. // Error if user provided an explicit session to an unacknowledged write (SPEC-1019)
  759. return new error_1.MongoAPIError('Cannot have explicit session with unacknowledged writes');
  760. }
  761. return;
  762. }
  763. // mark the last use of this session, and apply the `lsid`
  764. serverSession.lastUse = (0, utils_1.now)();
  765. command.lsid = serverSession.id;
  766. const inTxnOrTxnCommand = session.inTransaction() || (0, transactions_1.isTransactionCommand)(command);
  767. const isRetryableWrite = !!options.willRetryWrite;
  768. if (isRetryableWrite || inTxnOrTxnCommand) {
  769. serverSession.txnNumber += session.txnNumberIncrement;
  770. session.txnNumberIncrement = 0;
  771. // TODO(NODE-2674): Preserve int64 sent from MongoDB
  772. command.txnNumber = bson_1.Long.fromNumber(serverSession.txnNumber);
  773. }
  774. if (!inTxnOrTxnCommand) {
  775. if (session.transaction.state !== transactions_1.TxnState.NO_TRANSACTION) {
  776. session.transaction.transition(transactions_1.TxnState.NO_TRANSACTION);
  777. }
  778. if (session.supports.causalConsistency &&
  779. session.operationTime &&
  780. (0, utils_1.commandSupportsReadConcern)(command)) {
  781. command.readConcern = command.readConcern || {};
  782. Object.assign(command.readConcern, { afterClusterTime: session.operationTime });
  783. }
  784. else if (session.snapshotEnabled) {
  785. command.readConcern = command.readConcern || { level: read_concern_1.ReadConcernLevel.snapshot };
  786. if (session.snapshotTime != null) {
  787. Object.assign(command.readConcern, { atClusterTime: session.snapshotTime });
  788. }
  789. }
  790. return;
  791. }
  792. // now attempt to apply transaction-specific sessions data
  793. // `autocommit` must always be false to differentiate from retryable writes
  794. command.autocommit = false;
  795. if (session.transaction.state === transactions_1.TxnState.STARTING_TRANSACTION) {
  796. session.transaction.transition(transactions_1.TxnState.TRANSACTION_IN_PROGRESS);
  797. command.startTransaction = true;
  798. const readConcern = session.transaction.options.readConcern || session?.clientOptions?.readConcern;
  799. if (readConcern) {
  800. command.readConcern = readConcern;
  801. }
  802. if (session.supports.causalConsistency && session.operationTime) {
  803. command.readConcern = command.readConcern || {};
  804. Object.assign(command.readConcern, { afterClusterTime: session.operationTime });
  805. }
  806. }
  807. return;
  808. }
  809. function updateSessionFromResponse(session, document) {
  810. if (document.$clusterTime) {
  811. (0, common_1._advanceClusterTime)(session, document.$clusterTime);
  812. }
  813. if (document.operationTime && session && session.supports.causalConsistency) {
  814. session.advanceOperationTime(document.operationTime);
  815. }
  816. if (document.recoveryToken && session && session.inTransaction()) {
  817. session.transaction._recoveryToken = document.recoveryToken;
  818. }
  819. if (session?.snapshotEnabled && session.snapshotTime == null) {
  820. // find and aggregate commands return atClusterTime on the cursor
  821. // distinct includes it in the response body
  822. const atClusterTime = document.atClusterTime;
  823. if (atClusterTime) {
  824. session.snapshotTime = atClusterTime;
  825. }
  826. }
  827. }
  828. //# sourceMappingURL=sessions.js.map