All files / src/cmap connection_pool.ts

95.66% Statements 265/277
88.43% Branches 130/147
97.72% Functions 43/44
95.52% Lines 256/268

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830404x     404x                           404x                   404x   404x 404x                   404x 404x 404x                         404x           404x                                                         404x                                                                       404x                                             404x         404x         404x         404x         404x         404x         404x         404x         404x         404x         404x     3244462x 3244462x   3244462x                       3244462x           3244462x 3244462x 3244462x 3244462x 3244462x 3244462x 3244462x 3244462x 3244462x 3244462x 3244462x 3244462x 3244462x 3244462x   3244462x 3244462x   3244462x 3244462x           55912106x                 16753283x         2938124x             18136444x       6782196x       2950665x       78027746x       31476307x       5302x                                   30x             2749170x 144738x   2604432x 2604432x 2604432x 2604432x                 13463902x 13463902x         13463902x   13463902x   13463902x             13463902x 3438x 3438x     13463902x 13463902x   13463902x 13463902x 13463902x   14678x 495x 495x   495x       495x           495x 262x       233x   14183x   13463902x 13463902x                   13446737x 4188x   13442549x 13442549x 13442549x   13442549x 13334771x 13334771x     13442549x 13442549x         13442549x 107778x 107778x     13442549x                   80021x 30x       79991x 7500x 7500x         7500x 7500x     7500x       7500x   7500x       7500x     72491x 72491x 72491x 72491x 72491x   72491x 72491x 59984x               72491x 1505x     72491x                 1505x 300x 300x 300x             3225550x 916x       3224634x     3224634x 3224634x     3224634x 3224634x 3224634x   3224634x 1949870x       1949870x   3224634x 3224634x               2x 2x     2x 2x           2x 2x         2x           2x   2x         3297125x 3297125x 9627x               111516x         111516x       29327756x 29327756x 1953089x 1953089x 1953089x     27374667x       15885207x                 15885207x 15885207x 15885207x 15881469x   3738x 3738x 3738x       2078017x                 2078017x   2078017x 2078017x         2078017x     2069006x 941x 941x 941x 941x       2068065x 15072529x     2068065x 228079x 228079x   228079x 228079x   228079x 228079x 5355x   222724x 222724x         2068065x 2068065x         2068065x 2068065x     9011x 9011x 9011x                   9011x 8931x   9011x           2748900x 2748900x 2594646x     4396277x   154254x             105631x 105631x 104313x 104313x   105631x 104313x 104313x 99493x           48623x 48623x 44975x             32280291x     32280291x   32280291x 15194124x 15194124x         15194124x 3717x 3717x     15190407x 2111x 2111x 2111x       2111x 2111x 2111x     15188296x 3699366x     11488930x 11488930x       11488930x 11485672x 11485672x         11485672x 11485672x       32280291x 32280291x         1972402x 1972402x     1972402x 1972402x 216x 216x     1972186x 8634x                   8634x 1963552x 1963552x 1963552x       1963552x     1972402x     32280291x                                  
import { clearTimeout, setTimeout } from 'timers';
 
import type { ObjectId } from '../bson';
import {
  APM_EVENTS,
  CONNECTION_CHECK_OUT_FAILED,
  CONNECTION_CHECK_OUT_STARTED,
  CONNECTION_CHECKED_IN,
  CONNECTION_CHECKED_OUT,
  CONNECTION_CLOSED,
  CONNECTION_CREATED,
  CONNECTION_POOL_CLEARED,
  CONNECTION_POOL_CLOSED,
  CONNECTION_POOL_CREATED,
  CONNECTION_POOL_READY,
  CONNECTION_READY
} from '../constants';
import {
  type AnyError,
  type MongoError,
  MongoInvalidArgumentError,
  MongoMissingCredentialsError,
  MongoNetworkError,
  MongoOperationTimeoutError,
  MongoRuntimeError,
  MongoServerError
} from '../error';
import { type Abortable, CancellationToken, TypedEventEmitter } from '../mongo_types';
import type { Server } from '../sdam/server';
import { type TimeoutContext, TimeoutError } from '../timeout';
import {
  addAbortListener,
  type Callback,
  kDispose,
  List,
  makeCounter,
  noop,
  now,
  promiseWithResolvers
} from '../utils';
import { connect } from './connect';
import { Connection, type ConnectionEvents, type ConnectionOptions } from './connection';
import {
  ConnectionCheckedInEvent,
  ConnectionCheckedOutEvent,
  ConnectionCheckOutFailedEvent,
  ConnectionCheckOutStartedEvent,
  ConnectionClosedEvent,
  ConnectionCreatedEvent,
  ConnectionPoolClearedEvent,
  ConnectionPoolClosedEvent,
  ConnectionPoolCreatedEvent,
  ConnectionPoolReadyEvent,
  ConnectionReadyEvent
} from './connection_pool_events';
import {
  PoolClearedError,
  PoolClearedOnNetworkError,
  PoolClosedError,
  WaitQueueTimeoutError
} from './errors';
import { ConnectionPoolMetrics } from './metrics';
 
/** @public */
export interface ConnectionPoolOptions extends Omit<ConnectionOptions, 'id' | 'generation'> {
  /** The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections. */
  maxPoolSize: number;
  /** The minimum number of connections that MUST exist at any moment in a single connection pool. */
  minPoolSize: number;
  /** The maximum number of connections that may be in the process of being established concurrently by the connection pool. */
  maxConnecting: number;
  /** The maximum amount of time a connection should remain idle in the connection pool before being marked idle. */
  maxIdleTimeMS: number;
  /** The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit. */
  waitQueueTimeoutMS: number;
  /** If we are in load balancer mode. */
  loadBalanced: boolean;
  /** @internal */
  minPoolSizeCheckFrequencyMS?: number;
}
 
/** @internal */
export interface WaitQueueMember {
  resolve: (conn: Connection) => void;
  reject: (err: AnyError) => void;
  cancelled: boolean;
  checkoutTime: number;
}
 
/** @internal */
export const PoolState = Object.freeze({
  paused: 'paused',
  ready: 'ready',
  closed: 'closed'
} as const);
 
type PoolState = (typeof PoolState)[keyof typeof PoolState];
 
/**
 * @public
 * @deprecated This interface is deprecated and will be removed in a future release as it is not used
 * in the driver
 */
export interface CloseOptions {
  force?: boolean;
}
 
/** @public */
export type ConnectionPoolEvents = {
  connectionPoolCreated(event: ConnectionPoolCreatedEvent): void;
  connectionPoolReady(event: ConnectionPoolReadyEvent): void;
  connectionPoolClosed(event: ConnectionPoolClosedEvent): void;
  connectionPoolCleared(event: ConnectionPoolClearedEvent): void;
  connectionCreated(event: ConnectionCreatedEvent): void;
  connectionReady(event: ConnectionReadyEvent): void;
  connectionClosed(event: ConnectionClosedEvent): void;
  connectionCheckOutStarted(event: ConnectionCheckOutStartedEvent): void;
  connectionCheckOutFailed(event: ConnectionCheckOutFailedEvent): void;
  connectionCheckedOut(event: ConnectionCheckedOutEvent): void;
  connectionCheckedIn(event: ConnectionCheckedInEvent): void;
} & Omit<ConnectionEvents, 'close' | 'message'>;
 
/**
 * A pool of connections which dynamically resizes, and emit events related to pool activity
 * @internal
 */
export class ConnectionPool extends TypedEventEmitter<ConnectionPoolEvents> {
  public options: Readonly<ConnectionPoolOptions>;
  /**  An integer representing the SDAM generation of the pool */
  public generation: number;
  /** A map of generations to service ids */
  public serviceGenerations: Map<string, number>;
 
  private poolState: PoolState;
  private server: Server;
  private connections: List<Connection>;
  private pending: number;
  private checkedOut: Set<Connection>;
  private minPoolSizeTimer?: NodeJS.Timeout;
  private connectionCounter: Generator<number>;
  private cancellationToken: CancellationToken;
  private waitQueue: List<WaitQueueMember>;
  private metrics: ConnectionPoolMetrics;
  private processingWaitQueue: boolean;
 
  /**
   * Emitted when the connection pool is created.
   * @event
   */
  static readonly CONNECTION_POOL_CREATED = CONNECTION_POOL_CREATED;
  /**
   * Emitted once when the connection pool is closed
   * @event
   */
  static readonly CONNECTION_POOL_CLOSED = CONNECTION_POOL_CLOSED;
  /**
   * Emitted each time the connection pool is cleared and it's generation incremented
   * @event
   */
  static readonly CONNECTION_POOL_CLEARED = CONNECTION_POOL_CLEARED;
  /**
   * Emitted each time the connection pool is marked ready
   * @event
   */
  static readonly CONNECTION_POOL_READY = CONNECTION_POOL_READY;
  /**
   * Emitted when a connection is created.
   * @event
   */
  static readonly CONNECTION_CREATED = CONNECTION_CREATED;
  /**
   * Emitted when a connection becomes established, and is ready to use
   * @event
   */
  static readonly CONNECTION_READY = CONNECTION_READY;
  /**
   * Emitted when a connection is closed
   * @event
   */
  static readonly CONNECTION_CLOSED = CONNECTION_CLOSED;
  /**
   * Emitted when an attempt to check out a connection begins
   * @event
   */
  static readonly CONNECTION_CHECK_OUT_STARTED = CONNECTION_CHECK_OUT_STARTED;
  /**
   * Emitted when an attempt to check out a connection fails
   * @event
   */
  static readonly CONNECTION_CHECK_OUT_FAILED = CONNECTION_CHECK_OUT_FAILED;
  /**
   * Emitted each time a connection is successfully checked out of the connection pool
   * @event
   */
  static readonly CONNECTION_CHECKED_OUT = CONNECTION_CHECKED_OUT;
  /**
   * Emitted each time a connection is successfully checked into the connection pool
   * @event
   */
  static readonly CONNECTION_CHECKED_IN = CONNECTION_CHECKED_IN;
 
  constructor(server: Server, options: ConnectionPoolOptions) {
    super();
    this.on('error', noop);
 
    this.options = Object.freeze({
      connectionType: Connection,
      ...options,
      maxPoolSize: options.maxPoolSize ?? 100,
      minPoolSize: options.minPoolSize ?? 0,
      maxConnecting: options.maxConnecting ?? 2,
      maxIdleTimeMS: options.maxIdleTimeMS ?? 0,
      waitQueueTimeoutMS: options.waitQueueTimeoutMS ?? 0,
      minPoolSizeCheckFrequencyMS: options.minPoolSizeCheckFrequencyMS ?? 100,
      autoEncrypter: options.autoEncrypter
    });
 
    Iif (this.options.minPoolSize > this.options.maxPoolSize) {
      throw new MongoInvalidArgumentError(
        'Connection pool minimum size must not be greater than maximum pool size'
      );
    }
 
    this.poolState = PoolState.paused;
    this.server = server;
    this.connections = new List();
    this.pending = 0;
    this.checkedOut = new Set();
    this.minPoolSizeTimer = undefined;
    this.generation = 0;
    this.serviceGenerations = new Map();
    this.connectionCounter = makeCounter(1);
    this.cancellationToken = new CancellationToken();
    this.cancellationToken.setMaxListeners(Infinity);
    this.waitQueue = new List();
    this.metrics = new ConnectionPoolMetrics();
    this.processingWaitQueue = false;
 
    this.mongoLogger = this.server.topology.client?.mongoLogger;
    this.component = 'connection';
 
    process.nextTick(() => {
      this.emitAndLog(ConnectionPool.CONNECTION_POOL_CREATED, new ConnectionPoolCreatedEvent(this));
    });
  }
 
  /** The address of the endpoint the pool is connected to */
  get address(): string {
    return this.options.hostAddress.toString();
  }
 
  /**
   * Check if the pool has been closed
   *
   * TODO(NODE-3263): We can remove this property once shell no longer needs it
   */
  get closed(): boolean {
    return this.poolState === PoolState.closed;
  }
 
  /** An integer expressing how many total connections (available + pending + in use) the pool currently has */
  get totalConnectionCount(): number {
    return (
      this.availableConnectionCount + this.pendingConnectionCount + this.currentCheckedOutCount
    );
  }
 
  /** An integer expressing how many connections are currently available in the pool. */
  get availableConnectionCount(): number {
    return this.connections.length;
  }
 
  get pendingConnectionCount(): number {
    return this.pending;
  }
 
  get currentCheckedOutCount(): number {
    return this.checkedOut.size;
  }
 
  get waitQueueSize(): number {
    return this.waitQueue.length;
  }
 
  get loadBalanced(): boolean {
    return this.options.loadBalanced;
  }
 
  get serverError() {
    return this.server.description.error;
  }
 
  /**
   * This is exposed ONLY for use in mongosh, to enable
   * killing all connections if a user quits the shell with
   * operations in progress.
   *
   * This property may be removed as a part of NODE-3263.
   */
  get checkedOutConnections() {
    return this.checkedOut;
  }
 
  /**
   * Get the metrics information for the pool when a wait queue timeout occurs.
   */
  private waitQueueErrorMetrics(): string {
    return this.metrics.info(this.options.maxPoolSize);
  }
 
  /**
   * Set the pool state to "ready"
   */
  ready(): void {
    if (this.poolState !== PoolState.paused) {
      return;
    }
    this.poolState = PoolState.ready;
    this.emitAndLog(ConnectionPool.CONNECTION_POOL_READY, new ConnectionPoolReadyEvent(this));
    clearTimeout(this.minPoolSizeTimer);
    this.ensureMinPoolSize();
  }
 
  /**
   * Check a connection out of this pool. The connection will continue to be tracked, but no reference to it
   * will be held by the pool. This means that if a connection is checked out it MUST be checked back in or
   * explicitly destroyed by the new owner.
   */
  async checkOut(options: { timeoutContext: TimeoutContext } & Abortable): Promise<Connection> {
    const checkoutTime = now();
    this.emitAndLog(
      ConnectionPool.CONNECTION_CHECK_OUT_STARTED,
      new ConnectionCheckOutStartedEvent(this)
    );
 
    const { promise, resolve, reject } = promiseWithResolvers<Connection>();
 
    const timeout = options.timeoutContext.connectionCheckoutTimeout;
 
    const waitQueueMember: WaitQueueMember = {
      resolve,
      reject,
      cancelled: false,
      checkoutTime
    };
 
    const abortListener = addAbortListener(options.signal, function () {
      waitQueueMember.cancelled = true;
      reject(this.reason);
    });
 
    this.waitQueue.push(waitQueueMember);
    process.nextTick(() => this.processWaitQueue());
 
    try {
      timeout?.throwIfExpired();
      return await (timeout ? Promise.race([promise, timeout]) : promise);
    } catch (error) {
      if (TimeoutError.is(error)) {
        timeout?.clear();
        waitQueueMember.cancelled = true;
 
        this.emitAndLog(
          ConnectionPool.CONNECTION_CHECK_OUT_FAILED,
          new ConnectionCheckOutFailedEvent(this, 'timeout', waitQueueMember.checkoutTime)
        );
        const timeoutError = new WaitQueueTimeoutError(
          this.loadBalanced
            ? this.waitQueueErrorMetrics()
            : 'Timed out while checking out a connection from connection pool',
          this.address
        );
        if (options.timeoutContext.csotEnabled()) {
          throw new MongoOperationTimeoutError('Timed out during connection checkout', {
            cause: timeoutError
          });
        }
        throw timeoutError;
      }
      throw error;
    } finally {
      abortListener?.[kDispose]();
      timeout?.clear();
    }
  }
 
  /**
   * Check a connection into the pool.
   *
   * @param connection - The connection to check in
   */
  checkIn(connection: Connection): void {
    if (!this.checkedOut.has(connection)) {
      return;
    }
    const poolClosed = this.closed;
    const stale = this.connectionIsStale(connection);
    const willDestroy = !!(poolClosed || stale || connection.closed);
 
    if (!willDestroy) {
      connection.markAvailable();
      this.connections.unshift(connection);
    }
 
    this.checkedOut.delete(connection);
    this.emitAndLog(
      ConnectionPool.CONNECTION_CHECKED_IN,
      new ConnectionCheckedInEvent(this, connection)
    );
 
    if (willDestroy) {
      const reason = connection.closed ? 'error' : poolClosed ? 'poolClosed' : 'stale';
      this.destroyConnection(connection, reason);
    }
 
    process.nextTick(() => this.processWaitQueue());
  }
 
  /**
   * Clear the pool
   *
   * Pool reset is handled by incrementing the pool's generation count. Any existing connection of a
   * previous generation will eventually be pruned during subsequent checkouts.
   */
  clear(options: { serviceId?: ObjectId; interruptInUseConnections?: boolean } = {}): void {
    if (this.closed) {
      return;
    }
 
    // handle load balanced case
    if (this.loadBalanced) {
      const { serviceId } = options;
      Iif (!serviceId) {
        throw new MongoRuntimeError(
          'ConnectionPool.clear() called in load balanced mode with no serviceId.'
        );
      }
      const sid = serviceId.toHexString();
      const generation = this.serviceGenerations.get(sid);
      // Only need to worry if the generation exists, since it should
      // always be there but typescript needs the check.
      Iif (generation == null) {
        throw new MongoRuntimeError('Service generations are required in load balancer mode.');
      } else {
        // Increment the generation for the service id.
        this.serviceGenerations.set(sid, generation + 1);
      }
      this.emitAndLog(
        ConnectionPool.CONNECTION_POOL_CLEARED,
        new ConnectionPoolClearedEvent(this, { serviceId })
      );
      return;
    }
    // handle non load-balanced case
    const interruptInUseConnections = options.interruptInUseConnections ?? false;
    const oldGeneration = this.generation;
    this.generation += 1;
    const alreadyPaused = this.poolState === PoolState.paused;
    this.poolState = PoolState.paused;
 
    this.clearMinPoolSizeTimer();
    if (!alreadyPaused) {
      this.emitAndLog(
        ConnectionPool.CONNECTION_POOL_CLEARED,
        new ConnectionPoolClearedEvent(this, {
          interruptInUseConnections
        })
      );
    }
 
    if (interruptInUseConnections) {
      process.nextTick(() => this.interruptInUseConnections(oldGeneration));
    }
 
    this.processWaitQueue();
  }
 
  /**
   * Closes all stale in-use connections in the pool with a resumable PoolClearedOnNetworkError.
   *
   * Only connections where `connection.generation <= minGeneration` are killed.
   */
  private interruptInUseConnections(minGeneration: number) {
    for (const connection of this.checkedOut) {
      Eif (connection.generation <= minGeneration) {
        connection.onError(new PoolClearedOnNetworkError(this));
        this.checkIn(connection);
      }
    }
  }
 
  /** Close the pool */
  close(): void {
    if (this.closed) {
      return;
    }
 
    // immediately cancel any in-flight connections
    this.cancellationToken.emit('cancel');
 
    // end the connection counter
    Eif (typeof this.connectionCounter.return === 'function') {
      this.connectionCounter.return(undefined);
    }
 
    this.poolState = PoolState.closed;
    this.clearMinPoolSizeTimer();
    this.processWaitQueue();
 
    for (const conn of this.connections) {
      this.emitAndLog(
        ConnectionPool.CONNECTION_CLOSED,
        new ConnectionClosedEvent(this, conn, 'poolClosed')
      );
      conn.destroy();
    }
    this.connections.clear();
    this.emitAndLog(ConnectionPool.CONNECTION_POOL_CLOSED, new ConnectionPoolClosedEvent(this));
  }
 
  /**
   * @internal
   * Reauthenticate a connection
   */
  async reauthenticate(connection: Connection): Promise<void> {
    const authContext = connection.authContext;
    Iif (!authContext) {
      throw new MongoRuntimeError('No auth context found on connection.');
    }
    const credentials = authContext.credentials;
    Iif (!credentials) {
      throw new MongoMissingCredentialsError(
        'Connection is missing credentials when asked to reauthenticate'
      );
    }
 
    const resolvedCredentials = credentials.resolveAuthMechanism(connection.hello);
    const provider = this.server.topology.client.s.authProviders.getOrCreateProvider(
      resolvedCredentials.mechanism,
      resolvedCredentials.mechanismProperties
    );
 
    Iif (!provider) {
      throw new MongoMissingCredentialsError(
        `Reauthenticate failed due to no auth provider for ${credentials.mechanism}`
      );
    }
 
    await provider.reauth(authContext);
 
    return;
  }
 
  /** Clear the min pool size timer */
  private clearMinPoolSizeTimer(): void {
    const minPoolSizeTimer = this.minPoolSizeTimer;
    if (minPoolSizeTimer) {
      clearTimeout(minPoolSizeTimer);
    }
  }
 
  private destroyConnection(
    connection: Connection,
    reason: 'error' | 'idle' | 'stale' | 'poolClosed'
  ) {
    this.emitAndLog(
      ConnectionPool.CONNECTION_CLOSED,
      new ConnectionClosedEvent(this, connection, reason)
    );
    // destroy the connection
    connection.destroy();
  }
 
  private connectionIsStale(connection: Connection) {
    const serviceId = connection.serviceId;
    if (this.loadBalanced && serviceId) {
      const sid = serviceId.toHexString();
      const generation = this.serviceGenerations.get(sid);
      return connection.generation !== generation;
    }
 
    return connection.generation !== this.generation;
  }
 
  private connectionIsIdle(connection: Connection) {
    return !!(this.options.maxIdleTimeMS && connection.idleTime > this.options.maxIdleTimeMS);
  }
 
  /**
   * Destroys a connection if the connection is perished.
   *
   * @returns `true` if the connection was destroyed, `false` otherwise.
   */
  private destroyConnectionIfPerished(connection: Connection): boolean {
    const isStale = this.connectionIsStale(connection);
    const isIdle = this.connectionIsIdle(connection);
    if (!isStale && !isIdle && !connection.closed) {
      return false;
    }
    const reason = connection.closed ? 'error' : isStale ? 'stale' : 'idle';
    this.destroyConnection(connection, reason);
    return true;
  }
 
  private createConnection(callback: Callback<Connection>) {
    const connectOptions: ConnectionOptions = {
      ...this.options,
      id: this.connectionCounter.next().value,
      generation: this.generation,
      cancellationToken: this.cancellationToken,
      mongoLogger: this.mongoLogger,
      authProviders: this.server.topology.client.s.authProviders
    };
 
    this.pending++;
    // This is our version of a "virtual" no-I/O connection as the spec requires
    const connectionCreatedTime = now();
    this.emitAndLog(
      ConnectionPool.CONNECTION_CREATED,
      new ConnectionCreatedEvent(this, { id: connectOptions.id })
    );
 
    connect(connectOptions).then(
      connection => {
        // The pool might have closed since we started trying to create a connection
        if (this.poolState !== PoolState.ready) {
          this.pending--;
          connection.destroy();
          callback(this.closed ? new PoolClosedError(this) : new PoolClearedError(this));
          return;
        }
 
        // forward all events from the connection to the pool
        for (const event of [...APM_EVENTS, Connection.CLUSTER_TIME_RECEIVED]) {
          connection.on(event, (e: any) => this.emit(event, e));
        }
 
        if (this.loadBalanced) {
          connection.on(Connection.PINNED, pinType => this.metrics.markPinned(pinType));
          connection.on(Connection.UNPINNED, pinType => this.metrics.markUnpinned(pinType));
 
          const serviceId = connection.serviceId;
          Eif (serviceId) {
            let generation;
            const sid = serviceId.toHexString();
            if ((generation = this.serviceGenerations.get(sid))) {
              connection.generation = generation;
            } else {
              this.serviceGenerations.set(sid, 0);
              connection.generation = 0;
            }
          }
        }
 
        connection.markAvailable();
        this.emitAndLog(
          ConnectionPool.CONNECTION_READY,
          new ConnectionReadyEvent(this, connection, connectionCreatedTime)
        );
 
        this.pending--;
        callback(undefined, connection);
      },
      error => {
        this.pending--;
        this.server.handleError(error);
        this.emitAndLog(
          ConnectionPool.CONNECTION_CLOSED,
          new ConnectionClosedEvent(
            this,
            { id: connectOptions.id, serviceId: undefined },
            'error',
            // TODO(NODE-5192): Remove this cast
            error as MongoError
          )
        );
        if (error instanceof MongoNetworkError || error instanceof MongoServerError) {
          error.connectionGeneration = connectOptions.generation;
        }
        callback(error ?? new MongoRuntimeError('Connection creation failed without error'));
      }
    );
  }
 
  private ensureMinPoolSize() {
    const minPoolSize = this.options.minPoolSize;
    if (this.poolState !== PoolState.ready || minPoolSize === 0) {
      return;
    }
 
    this.connections.prune(connection => this.destroyConnectionIfPerished(connection));
 
    if (
      this.totalConnectionCount < minPoolSize &&
      this.pendingConnectionCount < this.options.maxConnecting
    ) {
      // NOTE: ensureMinPoolSize should not try to get all the pending
      // connection permits because that potentially delays the availability of
      // the connection to a checkout request
      this.createConnection((err, connection) => {
        if (!err && connection) {
          this.connections.push(connection);
          process.nextTick(() => this.processWaitQueue());
        }
        if (this.poolState === PoolState.ready) {
          clearTimeout(this.minPoolSizeTimer);
          this.minPoolSizeTimer = setTimeout(
            () => this.ensureMinPoolSize(),
            this.options.minPoolSizeCheckFrequencyMS
          );
        }
      });
    } else {
      clearTimeout(this.minPoolSizeTimer);
      this.minPoolSizeTimer = setTimeout(
        () => this.ensureMinPoolSize(),
        this.options.minPoolSizeCheckFrequencyMS
      );
    }
  }
 
  private processWaitQueue() {
    Iif (this.processingWaitQueue) {
      return;
    }
    this.processingWaitQueue = true;
 
    while (this.waitQueueSize) {
      const waitQueueMember = this.waitQueue.first();
      Iif (!waitQueueMember) {
        this.waitQueue.shift();
        continue;
      }
 
      if (waitQueueMember.cancelled) {
        this.waitQueue.shift();
        continue;
      }
 
      if (this.poolState !== PoolState.ready) {
        const reason = this.closed ? 'poolClosed' : 'connectionError';
        const error = this.closed ? new PoolClosedError(this) : new PoolClearedError(this);
        this.emitAndLog(
          ConnectionPool.CONNECTION_CHECK_OUT_FAILED,
          new ConnectionCheckOutFailedEvent(this, reason, waitQueueMember.checkoutTime, error)
        );
        this.waitQueue.shift();
        waitQueueMember.reject(error);
        continue;
      }
 
      if (!this.availableConnectionCount) {
        break;
      }
 
      const connection = this.connections.shift();
      Iif (!connection) {
        break;
      }
 
      if (!this.destroyConnectionIfPerished(connection)) {
        this.checkedOut.add(connection);
        this.emitAndLog(
          ConnectionPool.CONNECTION_CHECKED_OUT,
          new ConnectionCheckedOutEvent(this, connection, waitQueueMember.checkoutTime)
        );
 
        this.waitQueue.shift();
        waitQueueMember.resolve(connection);
      }
    }
 
    const { maxPoolSize, maxConnecting } = this.options;
    while (
      this.waitQueueSize > 0 &&
      this.pendingConnectionCount < maxConnecting &&
      (maxPoolSize === 0 || this.totalConnectionCount < maxPoolSize)
    ) {
      const waitQueueMember = this.waitQueue.shift();
      Iif (!waitQueueMember || waitQueueMember.cancelled) {
        continue;
      }
      this.createConnection((err, connection) => {
        if (waitQueueMember.cancelled) {
          Eif (!err && connection) {
            this.connections.push(connection);
          }
        } else {
          if (err) {
            this.emitAndLog(
              ConnectionPool.CONNECTION_CHECK_OUT_FAILED,
              // TODO(NODE-5192): Remove this cast
              new ConnectionCheckOutFailedEvent(
                this,
                'connectionError',
                waitQueueMember.checkoutTime,
                err as MongoError
              )
            );
            waitQueueMember.reject(err);
          } else Eif (connection) {
            this.checkedOut.add(connection);
            this.emitAndLog(
              ConnectionPool.CONNECTION_CHECKED_OUT,
              new ConnectionCheckedOutEvent(this, connection, waitQueueMember.checkoutTime)
            );
            waitQueueMember.resolve(connection);
          }
        }
        process.nextTick(() => this.processWaitQueue());
      });
    }
    this.processingWaitQueue = false;
  }
}
 
/**
 * A callback provided to `withConnection`
 * @internal
 *
 * @param error - An error instance representing the error during the execution.
 * @param connection - The managed connection which was checked out of the pool.
 * @param callback - A function to call back after connection management is complete
 */
export type WithConnectionCallback = (
  error: MongoError | undefined,
  connection: Connection | undefined,
  callback: Callback<Connection>
) => void;