connection_pool.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.ConnectionPool = void 0;
  4. const Denque = require("denque");
  5. const constants_1 = require("../constants");
  6. const error_1 = require("../error");
  7. const logger_1 = require("../logger");
  8. const mongo_types_1 = require("../mongo_types");
  9. const utils_1 = require("../utils");
  10. const connect_1 = require("./connect");
  11. const connection_1 = require("./connection");
  12. const connection_pool_events_1 = require("./connection_pool_events");
  13. const errors_1 = require("./errors");
  14. const metrics_1 = require("./metrics");
  15. /** @internal */
  16. const kLogger = Symbol('logger');
  17. /** @internal */
  18. const kConnections = Symbol('connections');
  19. /** @internal */
  20. const kPermits = Symbol('permits');
  21. /** @internal */
  22. const kMinPoolSizeTimer = Symbol('minPoolSizeTimer');
  23. /** @internal */
  24. const kGeneration = Symbol('generation');
  25. /** @internal */
  26. const kServiceGenerations = Symbol('serviceGenerations');
  27. /** @internal */
  28. const kConnectionCounter = Symbol('connectionCounter');
  29. /** @internal */
  30. const kCancellationToken = Symbol('cancellationToken');
  31. /** @internal */
  32. const kWaitQueue = Symbol('waitQueue');
  33. /** @internal */
  34. const kCancelled = Symbol('cancelled');
  35. /** @internal */
  36. const kMetrics = Symbol('metrics');
  37. /** @internal */
  38. const kCheckedOut = Symbol('checkedOut');
  39. /** @internal */
  40. const kProcessingWaitQueue = Symbol('processingWaitQueue');
  41. /**
  42. * A pool of connections which dynamically resizes, and emit events related to pool activity
  43. * @internal
  44. */
  45. class ConnectionPool extends mongo_types_1.TypedEventEmitter {
  46. /** @internal */
  47. constructor(options) {
  48. var _a, _b, _c, _d;
  49. super();
  50. this.closed = false;
  51. this.options = Object.freeze({
  52. ...options,
  53. connectionType: connection_1.Connection,
  54. maxPoolSize: (_a = options.maxPoolSize) !== null && _a !== void 0 ? _a : 100,
  55. minPoolSize: (_b = options.minPoolSize) !== null && _b !== void 0 ? _b : 0,
  56. maxIdleTimeMS: (_c = options.maxIdleTimeMS) !== null && _c !== void 0 ? _c : 0,
  57. waitQueueTimeoutMS: (_d = options.waitQueueTimeoutMS) !== null && _d !== void 0 ? _d : 0,
  58. autoEncrypter: options.autoEncrypter,
  59. metadata: options.metadata
  60. });
  61. if (this.options.minPoolSize > this.options.maxPoolSize) {
  62. throw new error_1.MongoInvalidArgumentError('Connection pool minimum size must not be greater than maximum pool size');
  63. }
  64. this[kLogger] = new logger_1.Logger('ConnectionPool');
  65. this[kConnections] = new Denque();
  66. this[kPermits] = this.options.maxPoolSize;
  67. this[kMinPoolSizeTimer] = undefined;
  68. this[kGeneration] = 0;
  69. this[kServiceGenerations] = new Map();
  70. this[kConnectionCounter] = (0, utils_1.makeCounter)(1);
  71. this[kCancellationToken] = new mongo_types_1.CancellationToken();
  72. this[kCancellationToken].setMaxListeners(Infinity);
  73. this[kWaitQueue] = new Denque();
  74. this[kMetrics] = new metrics_1.ConnectionPoolMetrics();
  75. this[kCheckedOut] = 0;
  76. this[kProcessingWaitQueue] = false;
  77. process.nextTick(() => {
  78. this.emit(ConnectionPool.CONNECTION_POOL_CREATED, new connection_pool_events_1.ConnectionPoolCreatedEvent(this));
  79. ensureMinPoolSize(this);
  80. });
  81. }
  82. /** The address of the endpoint the pool is connected to */
  83. get address() {
  84. return this.options.hostAddress.toString();
  85. }
  86. /** An integer representing the SDAM generation of the pool */
  87. get generation() {
  88. return this[kGeneration];
  89. }
  90. /** An integer expressing how many total connections (active + in use) the pool currently has */
  91. get totalConnectionCount() {
  92. return this[kConnections].length + (this.options.maxPoolSize - this[kPermits]);
  93. }
  94. /** An integer expressing how many connections are currently available in the pool. */
  95. get availableConnectionCount() {
  96. return this[kConnections].length;
  97. }
  98. get waitQueueSize() {
  99. return this[kWaitQueue].length;
  100. }
  101. get loadBalanced() {
  102. return this.options.loadBalanced;
  103. }
  104. get serviceGenerations() {
  105. return this[kServiceGenerations];
  106. }
  107. get currentCheckedOutCount() {
  108. return this[kCheckedOut];
  109. }
  110. /**
  111. * Get the metrics information for the pool when a wait queue timeout occurs.
  112. */
  113. waitQueueErrorMetrics() {
  114. return this[kMetrics].info(this.options.maxPoolSize);
  115. }
  116. /**
  117. * Check a connection out of this pool. The connection will continue to be tracked, but no reference to it
  118. * will be held by the pool. This means that if a connection is checked out it MUST be checked back in or
  119. * explicitly destroyed by the new owner.
  120. */
  121. checkOut(callback) {
  122. this.emit(ConnectionPool.CONNECTION_CHECK_OUT_STARTED, new connection_pool_events_1.ConnectionCheckOutStartedEvent(this));
  123. if (this.closed) {
  124. this.emit(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, 'poolClosed'));
  125. callback(new errors_1.PoolClosedError(this));
  126. return;
  127. }
  128. const waitQueueMember = { callback };
  129. const waitQueueTimeoutMS = this.options.waitQueueTimeoutMS;
  130. if (waitQueueTimeoutMS) {
  131. waitQueueMember.timer = setTimeout(() => {
  132. waitQueueMember[kCancelled] = true;
  133. waitQueueMember.timer = undefined;
  134. this.emit(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, 'timeout'));
  135. waitQueueMember.callback(new errors_1.WaitQueueTimeoutError(this.loadBalanced
  136. ? this.waitQueueErrorMetrics()
  137. : 'Timed out while checking out a connection from connection pool', this.address));
  138. }, waitQueueTimeoutMS);
  139. }
  140. this[kCheckedOut] = this[kCheckedOut] + 1;
  141. this[kWaitQueue].push(waitQueueMember);
  142. process.nextTick(processWaitQueue, this);
  143. }
  144. /**
  145. * Check a connection into the pool.
  146. *
  147. * @param connection - The connection to check in
  148. */
  149. checkIn(connection) {
  150. const poolClosed = this.closed;
  151. const stale = connectionIsStale(this, connection);
  152. const willDestroy = !!(poolClosed || stale || connection.closed);
  153. if (!willDestroy) {
  154. connection.markAvailable();
  155. this[kConnections].unshift(connection);
  156. }
  157. this[kCheckedOut] = this[kCheckedOut] - 1;
  158. this.emit(ConnectionPool.CONNECTION_CHECKED_IN, new connection_pool_events_1.ConnectionCheckedInEvent(this, connection));
  159. if (willDestroy) {
  160. const reason = connection.closed ? 'error' : poolClosed ? 'poolClosed' : 'stale';
  161. destroyConnection(this, connection, reason);
  162. }
  163. process.nextTick(processWaitQueue, this);
  164. }
  165. /**
  166. * Clear the pool
  167. *
  168. * Pool reset is handled by incrementing the pool's generation count. Any existing connection of a
  169. * previous generation will eventually be pruned during subsequent checkouts.
  170. */
  171. clear(serviceId) {
  172. if (this.loadBalanced && serviceId) {
  173. const sid = serviceId.toHexString();
  174. const generation = this.serviceGenerations.get(sid);
  175. // Only need to worry if the generation exists, since it should
  176. // always be there but typescript needs the check.
  177. if (generation == null) {
  178. // TODO(NODE-3483)
  179. throw new error_1.MongoRuntimeError('Service generations are required in load balancer mode.');
  180. }
  181. else {
  182. // Increment the generation for the service id.
  183. this.serviceGenerations.set(sid, generation + 1);
  184. }
  185. }
  186. else {
  187. this[kGeneration] += 1;
  188. }
  189. this.emit('connectionPoolCleared', new connection_pool_events_1.ConnectionPoolClearedEvent(this, serviceId));
  190. }
  191. close(_options, _cb) {
  192. let options = _options;
  193. const callback = (_cb !== null && _cb !== void 0 ? _cb : _options);
  194. if (typeof options === 'function') {
  195. options = {};
  196. }
  197. options = Object.assign({ force: false }, options);
  198. if (this.closed) {
  199. return callback();
  200. }
  201. // immediately cancel any in-flight connections
  202. this[kCancellationToken].emit('cancel');
  203. // drain the wait queue
  204. while (this.waitQueueSize) {
  205. const waitQueueMember = this[kWaitQueue].pop();
  206. if (waitQueueMember) {
  207. if (waitQueueMember.timer) {
  208. clearTimeout(waitQueueMember.timer);
  209. }
  210. if (!waitQueueMember[kCancelled]) {
  211. // TODO(NODE-3483): Replace with MongoConnectionPoolClosedError
  212. waitQueueMember.callback(new error_1.MongoRuntimeError('Connection pool closed'));
  213. }
  214. }
  215. }
  216. // clear the min pool size timer
  217. const minPoolSizeTimer = this[kMinPoolSizeTimer];
  218. if (minPoolSizeTimer) {
  219. clearTimeout(minPoolSizeTimer);
  220. }
  221. // end the connection counter
  222. if (typeof this[kConnectionCounter].return === 'function') {
  223. this[kConnectionCounter].return(undefined);
  224. }
  225. // mark the pool as closed immediately
  226. this.closed = true;
  227. (0, utils_1.eachAsync)(this[kConnections].toArray(), (conn, cb) => {
  228. this.emit(ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(this, conn, 'poolClosed'));
  229. conn.destroy(options, cb);
  230. }, err => {
  231. this[kConnections].clear();
  232. this.emit(ConnectionPool.CONNECTION_POOL_CLOSED, new connection_pool_events_1.ConnectionPoolClosedEvent(this));
  233. callback(err);
  234. });
  235. }
  236. /**
  237. * Runs a lambda with an implicitly checked out connection, checking that connection back in when the lambda
  238. * has completed by calling back.
  239. *
  240. * NOTE: please note the required signature of `fn`
  241. *
  242. * @remarks When in load balancer mode, connections can be pinned to cursors or transactions.
  243. * In these cases we pass the connection in to this method to ensure it is used and a new
  244. * connection is not checked out.
  245. *
  246. * @param conn - A pinned connection for use in load balancing mode.
  247. * @param fn - A function which operates on a managed connection
  248. * @param callback - The original callback
  249. */
  250. withConnection(conn, fn, callback) {
  251. if (conn) {
  252. // use the provided connection, and do _not_ check it in after execution
  253. fn(undefined, conn, (fnErr, result) => {
  254. if (typeof callback === 'function') {
  255. if (fnErr) {
  256. callback(fnErr);
  257. }
  258. else {
  259. callback(undefined, result);
  260. }
  261. }
  262. });
  263. return;
  264. }
  265. this.checkOut((err, conn) => {
  266. // don't callback with `err` here, we might want to act upon it inside `fn`
  267. fn(err, conn, (fnErr, result) => {
  268. if (typeof callback === 'function') {
  269. if (fnErr) {
  270. callback(fnErr);
  271. }
  272. else {
  273. callback(undefined, result);
  274. }
  275. }
  276. if (conn) {
  277. this.checkIn(conn);
  278. }
  279. });
  280. });
  281. }
  282. }
  283. exports.ConnectionPool = ConnectionPool;
  284. /**
  285. * Emitted when the connection pool is created.
  286. * @event
  287. */
  288. ConnectionPool.CONNECTION_POOL_CREATED = constants_1.CONNECTION_POOL_CREATED;
  289. /**
  290. * Emitted once when the connection pool is closed
  291. * @event
  292. */
  293. ConnectionPool.CONNECTION_POOL_CLOSED = constants_1.CONNECTION_POOL_CLOSED;
  294. /**
  295. * Emitted each time the connection pool is cleared and it's generation incremented
  296. * @event
  297. */
  298. ConnectionPool.CONNECTION_POOL_CLEARED = constants_1.CONNECTION_POOL_CLEARED;
  299. /**
  300. * Emitted when a connection is created.
  301. * @event
  302. */
  303. ConnectionPool.CONNECTION_CREATED = constants_1.CONNECTION_CREATED;
  304. /**
  305. * Emitted when a connection becomes established, and is ready to use
  306. * @event
  307. */
  308. ConnectionPool.CONNECTION_READY = constants_1.CONNECTION_READY;
  309. /**
  310. * Emitted when a connection is closed
  311. * @event
  312. */
  313. ConnectionPool.CONNECTION_CLOSED = constants_1.CONNECTION_CLOSED;
  314. /**
  315. * Emitted when an attempt to check out a connection begins
  316. * @event
  317. */
  318. ConnectionPool.CONNECTION_CHECK_OUT_STARTED = constants_1.CONNECTION_CHECK_OUT_STARTED;
  319. /**
  320. * Emitted when an attempt to check out a connection fails
  321. * @event
  322. */
  323. ConnectionPool.CONNECTION_CHECK_OUT_FAILED = constants_1.CONNECTION_CHECK_OUT_FAILED;
  324. /**
  325. * Emitted each time a connection is successfully checked out of the connection pool
  326. * @event
  327. */
  328. ConnectionPool.CONNECTION_CHECKED_OUT = constants_1.CONNECTION_CHECKED_OUT;
  329. /**
  330. * Emitted each time a connection is successfully checked into the connection pool
  331. * @event
  332. */
  333. ConnectionPool.CONNECTION_CHECKED_IN = constants_1.CONNECTION_CHECKED_IN;
  334. function ensureMinPoolSize(pool) {
  335. if (pool.closed || pool.options.minPoolSize === 0) {
  336. return;
  337. }
  338. const minPoolSize = pool.options.minPoolSize;
  339. for (let i = pool.totalConnectionCount; i < minPoolSize; ++i) {
  340. createConnection(pool);
  341. }
  342. pool[kMinPoolSizeTimer] = setTimeout(() => ensureMinPoolSize(pool), 10);
  343. }
  344. function connectionIsStale(pool, connection) {
  345. const serviceId = connection.serviceId;
  346. if (pool.loadBalanced && serviceId) {
  347. const sid = serviceId.toHexString();
  348. const generation = pool.serviceGenerations.get(sid);
  349. return connection.generation !== generation;
  350. }
  351. return connection.generation !== pool[kGeneration];
  352. }
  353. function connectionIsIdle(pool, connection) {
  354. return !!(pool.options.maxIdleTimeMS && connection.idleTime > pool.options.maxIdleTimeMS);
  355. }
  356. function createConnection(pool, callback) {
  357. const connectOptions = {
  358. ...pool.options,
  359. id: pool[kConnectionCounter].next().value,
  360. generation: pool[kGeneration],
  361. cancellationToken: pool[kCancellationToken]
  362. };
  363. pool[kPermits]--;
  364. (0, connect_1.connect)(connectOptions, (err, connection) => {
  365. if (err || !connection) {
  366. pool[kPermits]++;
  367. pool[kLogger].debug(`connection attempt failed with error [${JSON.stringify(err)}]`);
  368. if (typeof callback === 'function') {
  369. callback(err);
  370. }
  371. return;
  372. }
  373. // The pool might have closed since we started trying to create a connection
  374. if (pool.closed) {
  375. connection.destroy({ force: true });
  376. return;
  377. }
  378. // forward all events from the connection to the pool
  379. for (const event of [...constants_1.APM_EVENTS, connection_1.Connection.CLUSTER_TIME_RECEIVED]) {
  380. connection.on(event, (e) => pool.emit(event, e));
  381. }
  382. pool.emit(ConnectionPool.CONNECTION_CREATED, new connection_pool_events_1.ConnectionCreatedEvent(pool, connection));
  383. if (pool.loadBalanced) {
  384. connection.on(connection_1.Connection.PINNED, pinType => pool[kMetrics].markPinned(pinType));
  385. connection.on(connection_1.Connection.UNPINNED, pinType => pool[kMetrics].markUnpinned(pinType));
  386. const serviceId = connection.serviceId;
  387. if (serviceId) {
  388. let generation;
  389. const sid = serviceId.toHexString();
  390. if ((generation = pool.serviceGenerations.get(sid))) {
  391. connection.generation = generation;
  392. }
  393. else {
  394. pool.serviceGenerations.set(sid, 0);
  395. connection.generation = 0;
  396. }
  397. }
  398. }
  399. connection.markAvailable();
  400. pool.emit(ConnectionPool.CONNECTION_READY, new connection_pool_events_1.ConnectionReadyEvent(pool, connection));
  401. // if a callback has been provided, check out the connection immediately
  402. if (typeof callback === 'function') {
  403. callback(undefined, connection);
  404. return;
  405. }
  406. // otherwise add it to the pool for later acquisition, and try to process the wait queue
  407. pool[kConnections].push(connection);
  408. process.nextTick(processWaitQueue, pool);
  409. });
  410. }
  411. function destroyConnection(pool, connection, reason) {
  412. pool.emit(ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(pool, connection, reason));
  413. // allow more connections to be created
  414. pool[kPermits]++;
  415. // destroy the connection
  416. process.nextTick(() => connection.destroy());
  417. }
  418. function processWaitQueue(pool) {
  419. if (pool.closed || pool[kProcessingWaitQueue]) {
  420. return;
  421. }
  422. pool[kProcessingWaitQueue] = true;
  423. while (pool.waitQueueSize) {
  424. const waitQueueMember = pool[kWaitQueue].peekFront();
  425. if (!waitQueueMember) {
  426. pool[kWaitQueue].shift();
  427. continue;
  428. }
  429. if (waitQueueMember[kCancelled]) {
  430. pool[kWaitQueue].shift();
  431. continue;
  432. }
  433. if (!pool.availableConnectionCount) {
  434. break;
  435. }
  436. const connection = pool[kConnections].shift();
  437. if (!connection) {
  438. break;
  439. }
  440. const isStale = connectionIsStale(pool, connection);
  441. const isIdle = connectionIsIdle(pool, connection);
  442. if (!isStale && !isIdle && !connection.closed) {
  443. pool.emit(ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(pool, connection));
  444. if (waitQueueMember.timer) {
  445. clearTimeout(waitQueueMember.timer);
  446. }
  447. pool[kWaitQueue].shift();
  448. waitQueueMember.callback(undefined, connection);
  449. }
  450. else {
  451. const reason = connection.closed ? 'error' : isStale ? 'stale' : 'idle';
  452. destroyConnection(pool, connection, reason);
  453. }
  454. }
  455. const maxPoolSize = pool.options.maxPoolSize;
  456. if (pool.waitQueueSize && (maxPoolSize <= 0 || pool.totalConnectionCount < maxPoolSize)) {
  457. createConnection(pool, (err, connection) => {
  458. const waitQueueMember = pool[kWaitQueue].shift();
  459. if (!waitQueueMember || waitQueueMember[kCancelled]) {
  460. if (!err && connection) {
  461. pool[kConnections].push(connection);
  462. }
  463. pool[kProcessingWaitQueue] = false;
  464. return;
  465. }
  466. if (err) {
  467. pool.emit(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(pool, err));
  468. }
  469. else if (connection) {
  470. pool.emit(ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(pool, connection));
  471. }
  472. if (waitQueueMember.timer) {
  473. clearTimeout(waitQueueMember.timer);
  474. }
  475. waitQueueMember.callback(err, connection);
  476. pool[kProcessingWaitQueue] = false;
  477. process.nextTick(() => processWaitQueue(pool));
  478. });
  479. }
  480. else {
  481. pool[kProcessingWaitQueue] = false;
  482. }
  483. }
  484. //# sourceMappingURL=connection_pool.js.map