server.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.Server = void 0;
  4. const connection_1 = require("../cmap/connection");
  5. const connection_pool_1 = require("../cmap/connection_pool");
  6. const errors_1 = require("../cmap/errors");
  7. const constants_1 = require("../constants");
  8. const error_1 = require("../error");
  9. const mongo_types_1 = require("../mongo_types");
  10. const aggregate_1 = require("../operations/aggregate");
  11. const transactions_1 = require("../transactions");
  12. const utils_1 = require("../utils");
  13. const write_concern_1 = require("../write_concern");
  14. const common_1 = require("./common");
  15. const monitor_1 = require("./monitor");
  16. const server_description_1 = require("./server_description");
  17. const server_selection_1 = require("./server_selection");
  18. const stateTransition = (0, utils_1.makeStateMachine)({
  19. [common_1.STATE_CLOSED]: [common_1.STATE_CLOSED, common_1.STATE_CONNECTING],
  20. [common_1.STATE_CONNECTING]: [common_1.STATE_CONNECTING, common_1.STATE_CLOSING, common_1.STATE_CONNECTED, common_1.STATE_CLOSED],
  21. [common_1.STATE_CONNECTED]: [common_1.STATE_CONNECTED, common_1.STATE_CLOSING, common_1.STATE_CLOSED],
  22. [common_1.STATE_CLOSING]: [common_1.STATE_CLOSING, common_1.STATE_CLOSED]
  23. });
  24. /** @internal */
  25. class Server extends mongo_types_1.TypedEventEmitter {
  26. /**
  27. * Create a server
  28. */
  29. constructor(topology, description, options) {
  30. super();
  31. this.on('error', utils_1.noop);
  32. this.serverApi = options.serverApi;
  33. const poolOptions = { hostAddress: description.hostAddress, ...options };
  34. this.topology = topology;
  35. this.pool = new connection_pool_1.ConnectionPool(this, poolOptions);
  36. this.s = {
  37. description,
  38. options,
  39. state: common_1.STATE_CLOSED,
  40. operationCount: 0
  41. };
  42. for (const event of [...constants_1.CMAP_EVENTS, ...constants_1.APM_EVENTS]) {
  43. this.pool.on(event, (e) => this.emit(event, e));
  44. }
  45. this.pool.on(connection_1.Connection.CLUSTER_TIME_RECEIVED, (clusterTime) => {
  46. this.clusterTime = clusterTime;
  47. });
  48. if (this.loadBalanced) {
  49. this.monitor = null;
  50. // monitoring is disabled in load balancing mode
  51. return;
  52. }
  53. // create the monitor
  54. this.monitor = new monitor_1.Monitor(this, this.s.options);
  55. for (const event of constants_1.HEARTBEAT_EVENTS) {
  56. this.monitor.on(event, (e) => this.emit(event, e));
  57. }
  58. this.monitor.on('resetServer', (error) => markServerUnknown(this, error));
  59. this.monitor.on(Server.SERVER_HEARTBEAT_SUCCEEDED, (event) => {
  60. this.emit(Server.DESCRIPTION_RECEIVED, new server_description_1.ServerDescription(this.description.hostAddress, event.reply, {
  61. roundTripTime: this.monitor?.roundTripTime,
  62. minRoundTripTime: this.monitor?.minRoundTripTime
  63. }));
  64. if (this.s.state === common_1.STATE_CONNECTING) {
  65. stateTransition(this, common_1.STATE_CONNECTED);
  66. this.emit(Server.CONNECT, this);
  67. }
  68. });
  69. }
  70. get clusterTime() {
  71. return this.topology.clusterTime;
  72. }
  73. set clusterTime(clusterTime) {
  74. this.topology.clusterTime = clusterTime;
  75. }
  76. get description() {
  77. return this.s.description;
  78. }
  79. get name() {
  80. return this.s.description.address;
  81. }
  82. get autoEncrypter() {
  83. if (this.s.options && this.s.options.autoEncrypter) {
  84. return this.s.options.autoEncrypter;
  85. }
  86. return;
  87. }
  88. get loadBalanced() {
  89. return this.topology.description.type === common_1.TopologyType.LoadBalanced;
  90. }
  91. /**
  92. * Initiate server connect
  93. */
  94. connect() {
  95. if (this.s.state !== common_1.STATE_CLOSED) {
  96. return;
  97. }
  98. stateTransition(this, common_1.STATE_CONNECTING);
  99. // If in load balancer mode we automatically set the server to
  100. // a load balancer. It never transitions out of this state and
  101. // has no monitor.
  102. if (!this.loadBalanced) {
  103. this.monitor?.connect();
  104. }
  105. else {
  106. stateTransition(this, common_1.STATE_CONNECTED);
  107. this.emit(Server.CONNECT, this);
  108. }
  109. }
  110. closeCheckedOutConnections() {
  111. return this.pool.closeCheckedOutConnections();
  112. }
  113. /** Destroy the server connection */
  114. close() {
  115. if (this.s.state === common_1.STATE_CLOSED) {
  116. return;
  117. }
  118. stateTransition(this, common_1.STATE_CLOSING);
  119. if (!this.loadBalanced) {
  120. this.monitor?.close();
  121. }
  122. this.pool.close();
  123. stateTransition(this, common_1.STATE_CLOSED);
  124. this.emit('closed');
  125. }
  126. /**
  127. * Immediately schedule monitoring of this server. If there already an attempt being made
  128. * this will be a no-op.
  129. */
  130. requestCheck() {
  131. if (!this.loadBalanced) {
  132. this.monitor?.requestCheck();
  133. }
  134. }
  135. async command(operation, timeoutContext) {
  136. if (this.s.state === common_1.STATE_CLOSING || this.s.state === common_1.STATE_CLOSED) {
  137. throw new error_1.MongoServerClosedError();
  138. }
  139. const session = operation.session;
  140. let conn = session?.pinnedConnection;
  141. this.incrementOperationCount();
  142. if (conn == null) {
  143. try {
  144. conn = await this.pool.checkOut({ timeoutContext, signal: operation.options.signal });
  145. }
  146. catch (checkoutError) {
  147. this.decrementOperationCount();
  148. if (!(checkoutError instanceof errors_1.PoolClearedError))
  149. this.handleError(checkoutError);
  150. throw checkoutError;
  151. }
  152. }
  153. let reauthPromise = null;
  154. const cleanup = () => {
  155. this.decrementOperationCount();
  156. if (session?.pinnedConnection !== conn) {
  157. if (reauthPromise != null) {
  158. // The reauth promise only exists if it hasn't thrown.
  159. const checkBackIn = () => {
  160. this.pool.checkIn(conn);
  161. };
  162. void reauthPromise.then(checkBackIn, checkBackIn);
  163. }
  164. else {
  165. this.pool.checkIn(conn);
  166. }
  167. }
  168. };
  169. let cmd;
  170. try {
  171. cmd = operation.buildCommand(conn, session);
  172. }
  173. catch (e) {
  174. cleanup();
  175. throw e;
  176. }
  177. const options = operation.buildOptions(timeoutContext);
  178. const ns = operation.ns;
  179. if (this.loadBalanced && isPinnableCommand(cmd, session) && !session?.pinnedConnection) {
  180. session?.pin(conn);
  181. }
  182. options.directConnection = this.topology.s.options.directConnection;
  183. const omitReadPreference = operation instanceof aggregate_1.AggregateOperation &&
  184. operation.hasWriteStage &&
  185. (0, utils_1.maxWireVersion)(conn) < server_selection_1.MIN_SECONDARY_WRITE_WIRE_VERSION;
  186. if (omitReadPreference) {
  187. delete options.readPreference;
  188. }
  189. if (this.description.iscryptd) {
  190. options.omitMaxTimeMS = true;
  191. }
  192. try {
  193. try {
  194. const res = await conn.command(ns, cmd, options, operation.SERVER_COMMAND_RESPONSE_TYPE);
  195. (0, write_concern_1.throwIfWriteConcernError)(res);
  196. return res;
  197. }
  198. catch (commandError) {
  199. throw this.decorateCommandError(conn, cmd, options, commandError);
  200. }
  201. }
  202. catch (operationError) {
  203. if (operationError instanceof error_1.MongoError &&
  204. operationError.code === error_1.MONGODB_ERROR_CODES.Reauthenticate) {
  205. reauthPromise = this.pool.reauthenticate(conn);
  206. reauthPromise.then(undefined, error => {
  207. reauthPromise = null;
  208. (0, utils_1.squashError)(error);
  209. });
  210. await (0, utils_1.abortable)(reauthPromise, options);
  211. reauthPromise = null; // only reachable if reauth succeeds
  212. try {
  213. const res = await conn.command(ns, cmd, options, operation.SERVER_COMMAND_RESPONSE_TYPE);
  214. (0, write_concern_1.throwIfWriteConcernError)(res);
  215. return res;
  216. }
  217. catch (commandError) {
  218. throw this.decorateCommandError(conn, cmd, options, commandError);
  219. }
  220. }
  221. else {
  222. throw operationError;
  223. }
  224. }
  225. finally {
  226. cleanup();
  227. }
  228. }
  229. /**
  230. * Handle SDAM error
  231. * @internal
  232. */
  233. handleError(error, connection) {
  234. if (!(error instanceof error_1.MongoError)) {
  235. return;
  236. }
  237. const isStaleError = error.connectionGeneration && error.connectionGeneration < this.pool.generation;
  238. if (isStaleError) {
  239. return;
  240. }
  241. const isNetworkNonTimeoutError = error instanceof error_1.MongoNetworkError && !(error instanceof error_1.MongoNetworkTimeoutError);
  242. const isNetworkTimeoutBeforeHandshakeError = error instanceof error_1.MongoNetworkError && error.beforeHandshake;
  243. const isAuthHandshakeError = error.hasErrorLabel(error_1.MongoErrorLabel.HandshakeError);
  244. if (isNetworkNonTimeoutError || isNetworkTimeoutBeforeHandshakeError || isAuthHandshakeError) {
  245. // In load balanced mode we never mark the server as unknown and always
  246. // clear for the specific service id.
  247. if (!this.loadBalanced) {
  248. error.addErrorLabel(error_1.MongoErrorLabel.ResetPool);
  249. markServerUnknown(this, error);
  250. }
  251. else if (connection) {
  252. this.pool.clear({ serviceId: connection.serviceId });
  253. }
  254. }
  255. else {
  256. if ((0, error_1.isSDAMUnrecoverableError)(error)) {
  257. if (shouldHandleStateChangeError(this, error)) {
  258. const shouldClearPool = (0, error_1.isNodeShuttingDownError)(error);
  259. if (this.loadBalanced && connection && shouldClearPool) {
  260. this.pool.clear({ serviceId: connection.serviceId });
  261. }
  262. if (!this.loadBalanced) {
  263. if (shouldClearPool) {
  264. error.addErrorLabel(error_1.MongoErrorLabel.ResetPool);
  265. }
  266. markServerUnknown(this, error);
  267. process.nextTick(() => this.requestCheck());
  268. }
  269. }
  270. }
  271. }
  272. }
  273. /**
  274. * Ensure that error is properly decorated and internal state is updated before throwing
  275. * @internal
  276. */
  277. decorateCommandError(connection, cmd, options, error) {
  278. if (typeof error !== 'object' || error == null || !('name' in error)) {
  279. throw new error_1.MongoRuntimeError('An unexpected error type: ' + typeof error);
  280. }
  281. if (error.name === 'AbortError' && 'cause' in error && error.cause instanceof error_1.MongoError) {
  282. error = error.cause;
  283. }
  284. if (!(error instanceof error_1.MongoError)) {
  285. // Node.js or some other error we have not special handling for
  286. return error;
  287. }
  288. if (connectionIsStale(this.pool, connection)) {
  289. return error;
  290. }
  291. const session = options?.session;
  292. if (error instanceof error_1.MongoNetworkError) {
  293. if (session && !session.hasEnded && session.serverSession) {
  294. session.serverSession.isDirty = true;
  295. }
  296. // inActiveTransaction check handles commit and abort.
  297. if (inActiveTransaction(session, cmd) &&
  298. !error.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) {
  299. error.addErrorLabel(error_1.MongoErrorLabel.TransientTransactionError);
  300. }
  301. if ((isRetryableWritesEnabled(this.topology) || (0, transactions_1.isTransactionCommand)(cmd)) &&
  302. (0, utils_1.supportsRetryableWrites)(this) &&
  303. !inActiveTransaction(session, cmd)) {
  304. error.addErrorLabel(error_1.MongoErrorLabel.RetryableWriteError);
  305. }
  306. }
  307. else {
  308. if ((isRetryableWritesEnabled(this.topology) || (0, transactions_1.isTransactionCommand)(cmd)) &&
  309. (0, error_1.needsRetryableWriteLabel)(error, (0, utils_1.maxWireVersion)(this), this.description.type) &&
  310. !inActiveTransaction(session, cmd)) {
  311. error.addErrorLabel(error_1.MongoErrorLabel.RetryableWriteError);
  312. }
  313. }
  314. if (session &&
  315. session.isPinned &&
  316. error.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) {
  317. session.unpin({ force: true });
  318. }
  319. this.handleError(error, connection);
  320. return error;
  321. }
  322. /**
  323. * Decrement the operation count, returning the new count.
  324. */
  325. decrementOperationCount() {
  326. return (this.s.operationCount -= 1);
  327. }
  328. /**
  329. * Increment the operation count, returning the new count.
  330. */
  331. incrementOperationCount() {
  332. return (this.s.operationCount += 1);
  333. }
  334. }
  335. exports.Server = Server;
  336. /** @event */
  337. Server.SERVER_HEARTBEAT_STARTED = constants_1.SERVER_HEARTBEAT_STARTED;
  338. /** @event */
  339. Server.SERVER_HEARTBEAT_SUCCEEDED = constants_1.SERVER_HEARTBEAT_SUCCEEDED;
  340. /** @event */
  341. Server.SERVER_HEARTBEAT_FAILED = constants_1.SERVER_HEARTBEAT_FAILED;
  342. /** @event */
  343. Server.CONNECT = constants_1.CONNECT;
  344. /** @event */
  345. Server.DESCRIPTION_RECEIVED = constants_1.DESCRIPTION_RECEIVED;
  346. /** @event */
  347. Server.CLOSED = constants_1.CLOSED;
  348. /** @event */
  349. Server.ENDED = constants_1.ENDED;
  350. function markServerUnknown(server, error) {
  351. // Load balancer servers can never be marked unknown.
  352. if (server.loadBalanced) {
  353. return;
  354. }
  355. if (error instanceof error_1.MongoNetworkError && !(error instanceof error_1.MongoNetworkTimeoutError)) {
  356. server.monitor?.reset();
  357. }
  358. server.emit(Server.DESCRIPTION_RECEIVED, new server_description_1.ServerDescription(server.description.hostAddress, undefined, { error }));
  359. }
  360. function isPinnableCommand(cmd, session) {
  361. if (session) {
  362. return (session.inTransaction() ||
  363. (session.transaction.isCommitted && 'commitTransaction' in cmd) ||
  364. 'aggregate' in cmd ||
  365. 'find' in cmd ||
  366. 'getMore' in cmd ||
  367. 'listCollections' in cmd ||
  368. 'listIndexes' in cmd ||
  369. 'bulkWrite' in cmd);
  370. }
  371. return false;
  372. }
  373. function connectionIsStale(pool, connection) {
  374. if (connection.serviceId) {
  375. return (connection.generation !== pool.serviceGenerations.get(connection.serviceId.toHexString()));
  376. }
  377. return connection.generation !== pool.generation;
  378. }
  379. function shouldHandleStateChangeError(server, err) {
  380. const etv = err.topologyVersion;
  381. const stv = server.description.topologyVersion;
  382. return (0, server_description_1.compareTopologyVersion)(stv, etv) < 0;
  383. }
  384. function inActiveTransaction(session, cmd) {
  385. return session && session.inTransaction() && !(0, transactions_1.isTransactionCommand)(cmd);
  386. }
  387. /** this checks the retryWrites option passed down from the client options, it
  388. * does not check if the server supports retryable writes */
  389. function isRetryableWritesEnabled(topology) {
  390. return topology.s.options.retryWrites !== false;
  391. }
  392. //# sourceMappingURL=server.js.map