connection_pool.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.ConnectionPool = exports.PoolState = void 0;
  4. const timers_1 = require("timers");
  5. const constants_1 = require("../constants");
  6. const error_1 = require("../error");
  7. const mongo_types_1 = require("../mongo_types");
  8. const utils_1 = require("../utils");
  9. const connect_1 = require("./connect");
  10. const connection_1 = require("./connection");
  11. const connection_pool_events_1 = require("./connection_pool_events");
  12. const errors_1 = require("./errors");
  13. const metrics_1 = require("./metrics");
  14. /** @internal */
  15. const kServer = Symbol('server');
  16. /** @internal */
  17. const kConnections = Symbol('connections');
  18. /** @internal */
  19. const kPending = Symbol('pending');
  20. /** @internal */
  21. const kCheckedOut = Symbol('checkedOut');
  22. /** @internal */
  23. const kMinPoolSizeTimer = Symbol('minPoolSizeTimer');
  24. /** @internal */
  25. const kGeneration = Symbol('generation');
  26. /** @internal */
  27. const kServiceGenerations = Symbol('serviceGenerations');
  28. /** @internal */
  29. const kConnectionCounter = Symbol('connectionCounter');
  30. /** @internal */
  31. const kCancellationToken = Symbol('cancellationToken');
  32. /** @internal */
  33. const kWaitQueue = Symbol('waitQueue');
  34. /** @internal */
  35. const kCancelled = Symbol('cancelled');
  36. /** @internal */
  37. const kMetrics = Symbol('metrics');
  38. /** @internal */
  39. const kProcessingWaitQueue = Symbol('processingWaitQueue');
  40. /** @internal */
  41. const kPoolState = Symbol('poolState');
  42. /** @internal */
  43. exports.PoolState = Object.freeze({
  44. paused: 'paused',
  45. ready: 'ready',
  46. closed: 'closed'
  47. });
  48. /**
  49. * A pool of connections which dynamically resizes, and emit events related to pool activity
  50. * @internal
  51. */
  52. class ConnectionPool extends mongo_types_1.TypedEventEmitter {
  53. constructor(server, options) {
  54. super();
  55. this.options = Object.freeze({
  56. ...options,
  57. connectionType: connection_1.Connection,
  58. maxPoolSize: options.maxPoolSize ?? 100,
  59. minPoolSize: options.minPoolSize ?? 0,
  60. maxConnecting: options.maxConnecting ?? 2,
  61. maxIdleTimeMS: options.maxIdleTimeMS ?? 0,
  62. waitQueueTimeoutMS: options.waitQueueTimeoutMS ?? 0,
  63. minPoolSizeCheckFrequencyMS: options.minPoolSizeCheckFrequencyMS ?? 100,
  64. autoEncrypter: options.autoEncrypter,
  65. metadata: options.metadata
  66. });
  67. if (this.options.minPoolSize > this.options.maxPoolSize) {
  68. throw new error_1.MongoInvalidArgumentError('Connection pool minimum size must not be greater than maximum pool size');
  69. }
  70. this[kPoolState] = exports.PoolState.paused;
  71. this[kServer] = server;
  72. this[kConnections] = new utils_1.List();
  73. this[kPending] = 0;
  74. this[kCheckedOut] = new Set();
  75. this[kMinPoolSizeTimer] = undefined;
  76. this[kGeneration] = 0;
  77. this[kServiceGenerations] = new Map();
  78. this[kConnectionCounter] = (0, utils_1.makeCounter)(1);
  79. this[kCancellationToken] = new mongo_types_1.CancellationToken();
  80. this[kCancellationToken].setMaxListeners(Infinity);
  81. this[kWaitQueue] = new utils_1.List();
  82. this[kMetrics] = new metrics_1.ConnectionPoolMetrics();
  83. this[kProcessingWaitQueue] = false;
  84. this.mongoLogger = this[kServer].topology.client.mongoLogger;
  85. this.component = 'connection';
  86. process.nextTick(() => {
  87. this.emitAndLog(ConnectionPool.CONNECTION_POOL_CREATED, new connection_pool_events_1.ConnectionPoolCreatedEvent(this));
  88. });
  89. }
  90. /** The address of the endpoint the pool is connected to */
  91. get address() {
  92. return this.options.hostAddress.toString();
  93. }
  94. /**
  95. * Check if the pool has been closed
  96. *
  97. * TODO(NODE-3263): We can remove this property once shell no longer needs it
  98. */
  99. get closed() {
  100. return this[kPoolState] === exports.PoolState.closed;
  101. }
  102. /** An integer representing the SDAM generation of the pool */
  103. get generation() {
  104. return this[kGeneration];
  105. }
  106. /** An integer expressing how many total connections (available + pending + in use) the pool currently has */
  107. get totalConnectionCount() {
  108. return (this.availableConnectionCount + this.pendingConnectionCount + this.currentCheckedOutCount);
  109. }
  110. /** An integer expressing how many connections are currently available in the pool. */
  111. get availableConnectionCount() {
  112. return this[kConnections].length;
  113. }
  114. get pendingConnectionCount() {
  115. return this[kPending];
  116. }
  117. get currentCheckedOutCount() {
  118. return this[kCheckedOut].size;
  119. }
  120. get waitQueueSize() {
  121. return this[kWaitQueue].length;
  122. }
  123. get loadBalanced() {
  124. return this.options.loadBalanced;
  125. }
  126. get serviceGenerations() {
  127. return this[kServiceGenerations];
  128. }
  129. get serverError() {
  130. return this[kServer].description.error;
  131. }
  132. /**
  133. * This is exposed ONLY for use in mongosh, to enable
  134. * killing all connections if a user quits the shell with
  135. * operations in progress.
  136. *
  137. * This property may be removed as a part of NODE-3263.
  138. */
  139. get checkedOutConnections() {
  140. return this[kCheckedOut];
  141. }
  142. /**
  143. * Get the metrics information for the pool when a wait queue timeout occurs.
  144. */
  145. waitQueueErrorMetrics() {
  146. return this[kMetrics].info(this.options.maxPoolSize);
  147. }
  148. /**
  149. * Set the pool state to "ready"
  150. */
  151. ready() {
  152. if (this[kPoolState] !== exports.PoolState.paused) {
  153. return;
  154. }
  155. this[kPoolState] = exports.PoolState.ready;
  156. this.emitAndLog(ConnectionPool.CONNECTION_POOL_READY, new connection_pool_events_1.ConnectionPoolReadyEvent(this));
  157. (0, timers_1.clearTimeout)(this[kMinPoolSizeTimer]);
  158. this.ensureMinPoolSize();
  159. }
  160. /**
  161. * Check a connection out of this pool. The connection will continue to be tracked, but no reference to it
  162. * will be held by the pool. This means that if a connection is checked out it MUST be checked back in or
  163. * explicitly destroyed by the new owner.
  164. */
  165. checkOut(callback) {
  166. this.emitAndLog(ConnectionPool.CONNECTION_CHECK_OUT_STARTED, new connection_pool_events_1.ConnectionCheckOutStartedEvent(this));
  167. const waitQueueTimeoutMS = this.options.waitQueueTimeoutMS;
  168. const waitQueueMember = {
  169. callback,
  170. timeoutController: new utils_1.TimeoutController(waitQueueTimeoutMS)
  171. };
  172. waitQueueMember.timeoutController.signal.addEventListener('abort', () => {
  173. waitQueueMember[kCancelled] = true;
  174. waitQueueMember.timeoutController.clear();
  175. this.emitAndLog(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, 'timeout'));
  176. waitQueueMember.callback(new errors_1.WaitQueueTimeoutError(this.loadBalanced
  177. ? this.waitQueueErrorMetrics()
  178. : 'Timed out while checking out a connection from connection pool', this.address));
  179. });
  180. this[kWaitQueue].push(waitQueueMember);
  181. process.nextTick(() => this.processWaitQueue());
  182. }
  183. /**
  184. * Check a connection into the pool.
  185. *
  186. * @param connection - The connection to check in
  187. */
  188. checkIn(connection) {
  189. if (!this[kCheckedOut].has(connection)) {
  190. return;
  191. }
  192. const poolClosed = this.closed;
  193. const stale = this.connectionIsStale(connection);
  194. const willDestroy = !!(poolClosed || stale || connection.closed);
  195. if (!willDestroy) {
  196. connection.markAvailable();
  197. this[kConnections].unshift(connection);
  198. }
  199. this[kCheckedOut].delete(connection);
  200. this.emitAndLog(ConnectionPool.CONNECTION_CHECKED_IN, new connection_pool_events_1.ConnectionCheckedInEvent(this, connection));
  201. if (willDestroy) {
  202. const reason = connection.closed ? 'error' : poolClosed ? 'poolClosed' : 'stale';
  203. this.destroyConnection(connection, reason);
  204. }
  205. process.nextTick(() => this.processWaitQueue());
  206. }
  207. /**
  208. * Clear the pool
  209. *
  210. * Pool reset is handled by incrementing the pool's generation count. Any existing connection of a
  211. * previous generation will eventually be pruned during subsequent checkouts.
  212. */
  213. clear(options = {}) {
  214. if (this.closed) {
  215. return;
  216. }
  217. // handle load balanced case
  218. if (this.loadBalanced) {
  219. const { serviceId } = options;
  220. if (!serviceId) {
  221. throw new error_1.MongoRuntimeError('ConnectionPool.clear() called in load balanced mode with no serviceId.');
  222. }
  223. const sid = serviceId.toHexString();
  224. const generation = this.serviceGenerations.get(sid);
  225. // Only need to worry if the generation exists, since it should
  226. // always be there but typescript needs the check.
  227. if (generation == null) {
  228. throw new error_1.MongoRuntimeError('Service generations are required in load balancer mode.');
  229. }
  230. else {
  231. // Increment the generation for the service id.
  232. this.serviceGenerations.set(sid, generation + 1);
  233. }
  234. this.emitAndLog(ConnectionPool.CONNECTION_POOL_CLEARED, new connection_pool_events_1.ConnectionPoolClearedEvent(this, { serviceId }));
  235. return;
  236. }
  237. // handle non load-balanced case
  238. const interruptInUseConnections = options.interruptInUseConnections ?? false;
  239. const oldGeneration = this[kGeneration];
  240. this[kGeneration] += 1;
  241. const alreadyPaused = this[kPoolState] === exports.PoolState.paused;
  242. this[kPoolState] = exports.PoolState.paused;
  243. this.clearMinPoolSizeTimer();
  244. if (!alreadyPaused) {
  245. this.emitAndLog(ConnectionPool.CONNECTION_POOL_CLEARED, new connection_pool_events_1.ConnectionPoolClearedEvent(this, {
  246. interruptInUseConnections
  247. }));
  248. }
  249. if (interruptInUseConnections) {
  250. process.nextTick(() => this.interruptInUseConnections(oldGeneration));
  251. }
  252. this.processWaitQueue();
  253. }
  254. /**
  255. * Closes all stale in-use connections in the pool with a resumable PoolClearedOnNetworkError.
  256. *
  257. * Only connections where `connection.generation <= minGeneration` are killed.
  258. */
  259. interruptInUseConnections(minGeneration) {
  260. for (const connection of this[kCheckedOut]) {
  261. if (connection.generation <= minGeneration) {
  262. this.checkIn(connection);
  263. connection.onError(new errors_1.PoolClearedOnNetworkError(this));
  264. }
  265. }
  266. }
  267. close(_options, _cb) {
  268. let options = _options;
  269. const callback = (_cb ?? _options);
  270. if (typeof options === 'function') {
  271. options = {};
  272. }
  273. options = Object.assign({ force: false }, options);
  274. if (this.closed) {
  275. return callback();
  276. }
  277. // immediately cancel any in-flight connections
  278. this[kCancellationToken].emit('cancel');
  279. // end the connection counter
  280. if (typeof this[kConnectionCounter].return === 'function') {
  281. this[kConnectionCounter].return(undefined);
  282. }
  283. this[kPoolState] = exports.PoolState.closed;
  284. this.clearMinPoolSizeTimer();
  285. this.processWaitQueue();
  286. (0, utils_1.eachAsync)(this[kConnections].toArray(), (conn, cb) => {
  287. this.emitAndLog(ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(this, conn, 'poolClosed'));
  288. conn.destroy({ force: !!options.force }, cb);
  289. }, err => {
  290. this[kConnections].clear();
  291. this.emitAndLog(ConnectionPool.CONNECTION_POOL_CLOSED, new connection_pool_events_1.ConnectionPoolClosedEvent(this));
  292. callback(err);
  293. });
  294. }
  295. /**
  296. * Runs a lambda with an implicitly checked out connection, checking that connection back in when the lambda
  297. * has completed by calling back.
  298. *
  299. * NOTE: please note the required signature of `fn`
  300. *
  301. * @remarks When in load balancer mode, connections can be pinned to cursors or transactions.
  302. * In these cases we pass the connection in to this method to ensure it is used and a new
  303. * connection is not checked out.
  304. *
  305. * @param conn - A pinned connection for use in load balancing mode.
  306. * @param fn - A function which operates on a managed connection
  307. * @param callback - The original callback
  308. */
  309. withConnection(conn, fn, callback) {
  310. if (conn) {
  311. // use the provided connection, and do _not_ check it in after execution
  312. fn(undefined, conn, (fnErr, result) => {
  313. if (fnErr) {
  314. return this.withReauthentication(fnErr, conn, fn, callback);
  315. }
  316. callback(undefined, result);
  317. });
  318. return;
  319. }
  320. this.checkOut((err, conn) => {
  321. // don't callback with `err` here, we might want to act upon it inside `fn`
  322. fn(err, conn, (fnErr, result) => {
  323. if (fnErr) {
  324. if (conn) {
  325. this.withReauthentication(fnErr, conn, fn, callback);
  326. }
  327. else {
  328. callback(fnErr);
  329. }
  330. }
  331. else {
  332. callback(undefined, result);
  333. }
  334. if (conn) {
  335. this.checkIn(conn);
  336. }
  337. });
  338. });
  339. }
  340. withReauthentication(fnErr, conn, fn, callback) {
  341. if (fnErr instanceof error_1.MongoError && fnErr.code === error_1.MONGODB_ERROR_CODES.Reauthenticate) {
  342. this.reauthenticate(conn, fn, (error, res) => {
  343. if (error) {
  344. return callback(error);
  345. }
  346. callback(undefined, res);
  347. });
  348. }
  349. else {
  350. callback(fnErr);
  351. }
  352. }
  353. /**
  354. * Reauthenticate on the same connection and then retry the operation.
  355. */
  356. reauthenticate(connection, fn, callback) {
  357. const authContext = connection.authContext;
  358. if (!authContext) {
  359. return callback(new error_1.MongoRuntimeError('No auth context found on connection.'));
  360. }
  361. const credentials = authContext.credentials;
  362. if (!credentials) {
  363. return callback(new error_1.MongoMissingCredentialsError('Connection is missing credentials when asked to reauthenticate'));
  364. }
  365. const resolvedCredentials = credentials.resolveAuthMechanism(connection.hello || undefined);
  366. const provider = connect_1.AUTH_PROVIDERS.get(resolvedCredentials.mechanism);
  367. if (!provider) {
  368. return callback(new error_1.MongoMissingCredentialsError(`Reauthenticate failed due to no auth provider for ${credentials.mechanism}`));
  369. }
  370. provider.reauth(authContext).then(() => {
  371. fn(undefined, connection, (fnErr, fnResult) => {
  372. if (fnErr) {
  373. return callback(fnErr);
  374. }
  375. callback(undefined, fnResult);
  376. });
  377. }, error => callback(error));
  378. }
  379. /** Clear the min pool size timer */
  380. clearMinPoolSizeTimer() {
  381. const minPoolSizeTimer = this[kMinPoolSizeTimer];
  382. if (minPoolSizeTimer) {
  383. (0, timers_1.clearTimeout)(minPoolSizeTimer);
  384. }
  385. }
  386. destroyConnection(connection, reason) {
  387. this.emitAndLog(ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(this, connection, reason));
  388. // destroy the connection
  389. process.nextTick(() => connection.destroy({ force: false }));
  390. }
  391. connectionIsStale(connection) {
  392. const serviceId = connection.serviceId;
  393. if (this.loadBalanced && serviceId) {
  394. const sid = serviceId.toHexString();
  395. const generation = this.serviceGenerations.get(sid);
  396. return connection.generation !== generation;
  397. }
  398. return connection.generation !== this[kGeneration];
  399. }
  400. connectionIsIdle(connection) {
  401. return !!(this.options.maxIdleTimeMS && connection.idleTime > this.options.maxIdleTimeMS);
  402. }
  403. /**
  404. * Destroys a connection if the connection is perished.
  405. *
  406. * @returns `true` if the connection was destroyed, `false` otherwise.
  407. */
  408. destroyConnectionIfPerished(connection) {
  409. const isStale = this.connectionIsStale(connection);
  410. const isIdle = this.connectionIsIdle(connection);
  411. if (!isStale && !isIdle && !connection.closed) {
  412. return false;
  413. }
  414. const reason = connection.closed ? 'error' : isStale ? 'stale' : 'idle';
  415. this.destroyConnection(connection, reason);
  416. return true;
  417. }
  418. createConnection(callback) {
  419. const connectOptions = {
  420. ...this.options,
  421. id: this[kConnectionCounter].next().value,
  422. generation: this[kGeneration],
  423. cancellationToken: this[kCancellationToken]
  424. };
  425. this[kPending]++;
  426. // This is our version of a "virtual" no-I/O connection as the spec requires
  427. this.emitAndLog(ConnectionPool.CONNECTION_CREATED, new connection_pool_events_1.ConnectionCreatedEvent(this, { id: connectOptions.id }));
  428. (0, connect_1.connect)(connectOptions, (err, connection) => {
  429. if (err || !connection) {
  430. this[kPending]--;
  431. this.emitAndLog(ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(this, { id: connectOptions.id, serviceId: undefined }, 'error',
  432. // TODO(NODE-5192): Remove this cast
  433. err));
  434. if (err instanceof error_1.MongoNetworkError || err instanceof error_1.MongoServerError) {
  435. err.connectionGeneration = connectOptions.generation;
  436. }
  437. callback(err ?? new error_1.MongoRuntimeError('Connection creation failed without error'));
  438. return;
  439. }
  440. // The pool might have closed since we started trying to create a connection
  441. if (this[kPoolState] !== exports.PoolState.ready) {
  442. this[kPending]--;
  443. connection.destroy({ force: true });
  444. callback(this.closed ? new errors_1.PoolClosedError(this) : new errors_1.PoolClearedError(this));
  445. return;
  446. }
  447. // forward all events from the connection to the pool
  448. for (const event of [...constants_1.APM_EVENTS, connection_1.Connection.CLUSTER_TIME_RECEIVED]) {
  449. connection.on(event, (e) => this.emit(event, e));
  450. }
  451. if (this.loadBalanced) {
  452. connection.on(connection_1.Connection.PINNED, pinType => this[kMetrics].markPinned(pinType));
  453. connection.on(connection_1.Connection.UNPINNED, pinType => this[kMetrics].markUnpinned(pinType));
  454. const serviceId = connection.serviceId;
  455. if (serviceId) {
  456. let generation;
  457. const sid = serviceId.toHexString();
  458. if ((generation = this.serviceGenerations.get(sid))) {
  459. connection.generation = generation;
  460. }
  461. else {
  462. this.serviceGenerations.set(sid, 0);
  463. connection.generation = 0;
  464. }
  465. }
  466. }
  467. connection.markAvailable();
  468. this.emitAndLog(ConnectionPool.CONNECTION_READY, new connection_pool_events_1.ConnectionReadyEvent(this, connection));
  469. this[kPending]--;
  470. callback(undefined, connection);
  471. return;
  472. });
  473. }
  474. ensureMinPoolSize() {
  475. const minPoolSize = this.options.minPoolSize;
  476. if (this[kPoolState] !== exports.PoolState.ready || minPoolSize === 0) {
  477. return;
  478. }
  479. this[kConnections].prune(connection => this.destroyConnectionIfPerished(connection));
  480. if (this.totalConnectionCount < minPoolSize &&
  481. this.pendingConnectionCount < this.options.maxConnecting) {
  482. // NOTE: ensureMinPoolSize should not try to get all the pending
  483. // connection permits because that potentially delays the availability of
  484. // the connection to a checkout request
  485. this.createConnection((err, connection) => {
  486. if (err) {
  487. this[kServer].handleError(err);
  488. }
  489. if (!err && connection) {
  490. this[kConnections].push(connection);
  491. process.nextTick(() => this.processWaitQueue());
  492. }
  493. if (this[kPoolState] === exports.PoolState.ready) {
  494. (0, timers_1.clearTimeout)(this[kMinPoolSizeTimer]);
  495. this[kMinPoolSizeTimer] = (0, timers_1.setTimeout)(() => this.ensureMinPoolSize(), this.options.minPoolSizeCheckFrequencyMS);
  496. }
  497. });
  498. }
  499. else {
  500. (0, timers_1.clearTimeout)(this[kMinPoolSizeTimer]);
  501. this[kMinPoolSizeTimer] = (0, timers_1.setTimeout)(() => this.ensureMinPoolSize(), this.options.minPoolSizeCheckFrequencyMS);
  502. }
  503. }
  504. processWaitQueue() {
  505. if (this[kProcessingWaitQueue]) {
  506. return;
  507. }
  508. this[kProcessingWaitQueue] = true;
  509. while (this.waitQueueSize) {
  510. const waitQueueMember = this[kWaitQueue].first();
  511. if (!waitQueueMember) {
  512. this[kWaitQueue].shift();
  513. continue;
  514. }
  515. if (waitQueueMember[kCancelled]) {
  516. this[kWaitQueue].shift();
  517. continue;
  518. }
  519. if (this[kPoolState] !== exports.PoolState.ready) {
  520. const reason = this.closed ? 'poolClosed' : 'connectionError';
  521. const error = this.closed ? new errors_1.PoolClosedError(this) : new errors_1.PoolClearedError(this);
  522. this.emitAndLog(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, reason, error));
  523. waitQueueMember.timeoutController.clear();
  524. this[kWaitQueue].shift();
  525. waitQueueMember.callback(error);
  526. continue;
  527. }
  528. if (!this.availableConnectionCount) {
  529. break;
  530. }
  531. const connection = this[kConnections].shift();
  532. if (!connection) {
  533. break;
  534. }
  535. if (!this.destroyConnectionIfPerished(connection)) {
  536. this[kCheckedOut].add(connection);
  537. this.emitAndLog(ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(this, connection));
  538. waitQueueMember.timeoutController.clear();
  539. this[kWaitQueue].shift();
  540. waitQueueMember.callback(undefined, connection);
  541. }
  542. }
  543. const { maxPoolSize, maxConnecting } = this.options;
  544. while (this.waitQueueSize > 0 &&
  545. this.pendingConnectionCount < maxConnecting &&
  546. (maxPoolSize === 0 || this.totalConnectionCount < maxPoolSize)) {
  547. const waitQueueMember = this[kWaitQueue].shift();
  548. if (!waitQueueMember || waitQueueMember[kCancelled]) {
  549. continue;
  550. }
  551. this.createConnection((err, connection) => {
  552. if (waitQueueMember[kCancelled]) {
  553. if (!err && connection) {
  554. this[kConnections].push(connection);
  555. }
  556. }
  557. else {
  558. if (err) {
  559. this.emitAndLog(ConnectionPool.CONNECTION_CHECK_OUT_FAILED,
  560. // TODO(NODE-5192): Remove this cast
  561. new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, 'connectionError', err));
  562. }
  563. else if (connection) {
  564. this[kCheckedOut].add(connection);
  565. this.emitAndLog(ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(this, connection));
  566. }
  567. waitQueueMember.timeoutController.clear();
  568. waitQueueMember.callback(err, connection);
  569. }
  570. process.nextTick(() => this.processWaitQueue());
  571. });
  572. }
  573. this[kProcessingWaitQueue] = false;
  574. }
  575. }
  576. /**
  577. * Emitted when the connection pool is created.
  578. * @event
  579. */
  580. ConnectionPool.CONNECTION_POOL_CREATED = constants_1.CONNECTION_POOL_CREATED;
  581. /**
  582. * Emitted once when the connection pool is closed
  583. * @event
  584. */
  585. ConnectionPool.CONNECTION_POOL_CLOSED = constants_1.CONNECTION_POOL_CLOSED;
  586. /**
  587. * Emitted each time the connection pool is cleared and it's generation incremented
  588. * @event
  589. */
  590. ConnectionPool.CONNECTION_POOL_CLEARED = constants_1.CONNECTION_POOL_CLEARED;
  591. /**
  592. * Emitted each time the connection pool is marked ready
  593. * @event
  594. */
  595. ConnectionPool.CONNECTION_POOL_READY = constants_1.CONNECTION_POOL_READY;
  596. /**
  597. * Emitted when a connection is created.
  598. * @event
  599. */
  600. ConnectionPool.CONNECTION_CREATED = constants_1.CONNECTION_CREATED;
  601. /**
  602. * Emitted when a connection becomes established, and is ready to use
  603. * @event
  604. */
  605. ConnectionPool.CONNECTION_READY = constants_1.CONNECTION_READY;
  606. /**
  607. * Emitted when a connection is closed
  608. * @event
  609. */
  610. ConnectionPool.CONNECTION_CLOSED = constants_1.CONNECTION_CLOSED;
  611. /**
  612. * Emitted when an attempt to check out a connection begins
  613. * @event
  614. */
  615. ConnectionPool.CONNECTION_CHECK_OUT_STARTED = constants_1.CONNECTION_CHECK_OUT_STARTED;
  616. /**
  617. * Emitted when an attempt to check out a connection fails
  618. * @event
  619. */
  620. ConnectionPool.CONNECTION_CHECK_OUT_FAILED = constants_1.CONNECTION_CHECK_OUT_FAILED;
  621. /**
  622. * Emitted each time a connection is successfully checked out of the connection pool
  623. * @event
  624. */
  625. ConnectionPool.CONNECTION_CHECKED_OUT = constants_1.CONNECTION_CHECKED_OUT;
  626. /**
  627. * Emitted each time a connection is successfully checked into the connection pool
  628. * @event
  629. */
  630. ConnectionPool.CONNECTION_CHECKED_IN = constants_1.CONNECTION_CHECKED_IN;
  631. exports.ConnectionPool = ConnectionPool;
  632. //# sourceMappingURL=connection_pool.js.map