execute_operation.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.executeOperation = void 0;
  4. const error_1 = require("../error");
  5. const read_preference_1 = require("../read_preference");
  6. const server_selection_1 = require("../sdam/server_selection");
  7. const utils_1 = require("../utils");
  8. const operation_1 = require("./operation");
  9. const MMAPv1_RETRY_WRITES_ERROR_CODE = error_1.MONGODB_ERROR_CODES.IllegalOperation;
  10. const MMAPv1_RETRY_WRITES_ERROR_MESSAGE = 'This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.';
  11. function executeOperation(client, operation, callback) {
  12. return (0, utils_1.maybeCallback)(() => executeOperationAsync(client, operation), callback);
  13. }
  14. exports.executeOperation = executeOperation;
  15. async function executeOperationAsync(client, operation) {
  16. if (!(operation instanceof operation_1.AbstractCallbackOperation)) {
  17. // TODO(NODE-3483): Extend MongoRuntimeError
  18. throw new error_1.MongoRuntimeError('This method requires a valid operation instance');
  19. }
  20. if (client.topology == null) {
  21. // Auto connect on operation
  22. if (client.s.hasBeenClosed) {
  23. throw new error_1.MongoNotConnectedError('Client must be connected before running operations');
  24. }
  25. client.s.options[Symbol.for('@@mdb.skipPingOnConnect')] = true;
  26. try {
  27. await client.connect();
  28. }
  29. finally {
  30. delete client.s.options[Symbol.for('@@mdb.skipPingOnConnect')];
  31. }
  32. }
  33. const { topology } = client;
  34. if (topology == null) {
  35. throw new error_1.MongoRuntimeError('client.connect did not create a topology but also did not throw');
  36. }
  37. // The driver sessions spec mandates that we implicitly create sessions for operations
  38. // that are not explicitly provided with a session.
  39. let session = operation.session;
  40. let owner;
  41. if (session == null) {
  42. owner = Symbol();
  43. session = client.startSession({ owner, explicit: false });
  44. }
  45. else if (session.hasEnded) {
  46. throw new error_1.MongoExpiredSessionError('Use of expired sessions is not permitted');
  47. }
  48. else if (session.snapshotEnabled && !topology.capabilities.supportsSnapshotReads) {
  49. throw new error_1.MongoCompatibilityError('Snapshot reads require MongoDB 5.0 or later');
  50. }
  51. const readPreference = operation.readPreference ?? read_preference_1.ReadPreference.primary;
  52. const inTransaction = !!session?.inTransaction();
  53. if (inTransaction && !readPreference.equals(read_preference_1.ReadPreference.primary)) {
  54. throw new error_1.MongoTransactionError(`Read preference in a transaction must be primary, not: ${readPreference.mode}`);
  55. }
  56. if (session?.isPinned && session.transaction.isCommitted && !operation.bypassPinningCheck) {
  57. session.unpin();
  58. }
  59. let selector;
  60. if (operation.hasAspect(operation_1.Aspect.MUST_SELECT_SAME_SERVER)) {
  61. // GetMore and KillCursor operations must always select the same server, but run through
  62. // server selection to potentially force monitor checks if the server is
  63. // in an unknown state.
  64. selector = (0, server_selection_1.sameServerSelector)(operation.server?.description);
  65. }
  66. else if (operation.trySecondaryWrite) {
  67. // If operation should try to write to secondary use the custom server selector
  68. // otherwise provide the read preference.
  69. selector = (0, server_selection_1.secondaryWritableServerSelector)(topology.commonWireVersion, readPreference);
  70. }
  71. else {
  72. selector = readPreference;
  73. }
  74. const server = await topology.selectServerAsync(selector, { session });
  75. if (session == null) {
  76. // No session also means it is not retryable, early exit
  77. return operation.execute(server, undefined);
  78. }
  79. if (!operation.hasAspect(operation_1.Aspect.RETRYABLE)) {
  80. // non-retryable operation, early exit
  81. try {
  82. return await operation.execute(server, session);
  83. }
  84. finally {
  85. if (session?.owner != null && session.owner === owner) {
  86. await session.endSession().catch(() => null);
  87. }
  88. }
  89. }
  90. const willRetryRead = topology.s.options.retryReads && !inTransaction && operation.canRetryRead;
  91. const willRetryWrite = topology.s.options.retryWrites &&
  92. !inTransaction &&
  93. (0, utils_1.supportsRetryableWrites)(server) &&
  94. operation.canRetryWrite;
  95. const hasReadAspect = operation.hasAspect(operation_1.Aspect.READ_OPERATION);
  96. const hasWriteAspect = operation.hasAspect(operation_1.Aspect.WRITE_OPERATION);
  97. const willRetry = (hasReadAspect && willRetryRead) || (hasWriteAspect && willRetryWrite);
  98. if (hasWriteAspect && willRetryWrite) {
  99. operation.options.willRetryWrite = true;
  100. session.incrementTransactionNumber();
  101. }
  102. try {
  103. return await operation.execute(server, session);
  104. }
  105. catch (operationError) {
  106. if (willRetry && operationError instanceof error_1.MongoError) {
  107. return await retryOperation(operation, operationError, {
  108. session,
  109. topology,
  110. selector
  111. });
  112. }
  113. throw operationError;
  114. }
  115. finally {
  116. if (session?.owner != null && session.owner === owner) {
  117. await session.endSession().catch(() => null);
  118. }
  119. }
  120. }
  121. async function retryOperation(operation, originalError, { session, topology, selector }) {
  122. const isWriteOperation = operation.hasAspect(operation_1.Aspect.WRITE_OPERATION);
  123. const isReadOperation = operation.hasAspect(operation_1.Aspect.READ_OPERATION);
  124. if (isWriteOperation && originalError.code === MMAPv1_RETRY_WRITES_ERROR_CODE) {
  125. throw new error_1.MongoServerError({
  126. message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE,
  127. errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE,
  128. originalError
  129. });
  130. }
  131. if (isWriteOperation && !(0, error_1.isRetryableWriteError)(originalError)) {
  132. throw originalError;
  133. }
  134. if (isReadOperation && !(0, error_1.isRetryableReadError)(originalError)) {
  135. throw originalError;
  136. }
  137. if (originalError instanceof error_1.MongoNetworkError &&
  138. session.isPinned &&
  139. !session.inTransaction() &&
  140. operation.hasAspect(operation_1.Aspect.CURSOR_CREATING)) {
  141. // If we have a cursor and the initial command fails with a network error,
  142. // we can retry it on another connection. So we need to check it back in, clear the
  143. // pool for the service id, and retry again.
  144. session.unpin({ force: true, forceClear: true });
  145. }
  146. // select a new server, and attempt to retry the operation
  147. const server = await topology.selectServerAsync(selector, { session });
  148. if (isWriteOperation && !(0, utils_1.supportsRetryableWrites)(server)) {
  149. throw new error_1.MongoUnexpectedServerResponseError('Selected server does not support retryable writes');
  150. }
  151. try {
  152. return await operation.execute(server, session);
  153. }
  154. catch (retryError) {
  155. if (retryError instanceof error_1.MongoError &&
  156. retryError.hasErrorLabel(error_1.MongoErrorLabel.NoWritesPerformed)) {
  157. throw originalError;
  158. }
  159. throw retryError;
  160. }
  161. }
  162. //# sourceMappingURL=execute_operation.js.map