All files / src/connection pool-counters.ts

100% Statements 15/15
100% Branches 6/6
100% Functions 13/13
100% Lines 10/10

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                              31x         101x         94x         41x         45x         31x       271x                               13x 13x 13x      
import type { Pool } from 'pg';
import type { ConnectionPool, PoolCounters } from './connection-types.ts';
 
/** The part of a `pg.Pool` that the counters read. */
export type CountedPool = Pick<Pool, 'totalCount' | 'idleCount' | 'waitingCount'> &
  Readonly<{ options: Readonly<{ max?: number }> }>;
 
/** Live counters summed over one or more `pg` pools. */
export class PoolSum implements PoolCounters {
  readonly #pools: readonly CountedPool[];
 
  /**
   * @param pools - Pools to sum; none gives zeros.
   */
  constructor(pools: readonly CountedPool[]) {
    this.#pools = pools;
  }
 
  /** @inheritDoc */
  get size(): number {
    return this.#sum((pool) => pool.totalCount);
  }
 
  /** @inheritDoc */
  get available(): number {
    return this.#sum((pool) => pool.idleCount);
  }
 
  /** @inheritDoc */
  get using(): number {
    return this.size - this.available;
  }
 
  /** @inheritDoc */
  get waiting(): number {
    return this.#sum((pool) => pool.waitingCount);
  }
 
  /** @inheritDoc */
  get maxSize(): number {
    return this.#sum((pool) => pool.options.max ?? 10);
  }
 
  #sum(read: (pool: CountedPool) => number): number {
    return this.#pools.reduce((total, pool) => total + read(pool), 0);
  }
}
 
/** The `pool` of the connection manager: totals over every pool, plus the writer and the replicas when replication is configured. */
export class ManagerPools extends PoolSum implements ConnectionPool {
  /** @inheritDoc */
  readonly write: PoolCounters | undefined;
  /** @inheritDoc */
  readonly read: PoolCounters | undefined;
 
  /**
   * @param writer - Writer pool.
   * @param readers - Read replica pools; empty when replication is not configured.
   */
  constructor(writer: CountedPool, readers: readonly CountedPool[]) {
    super([writer, ...readers]);
    this.write = readers.length === 0 ? undefined : new PoolSum([writer]);
    this.read = readers.length === 0 ? undefined : new PoolSum(readers);
  }
}