From ca223e3656565cf49574d2fb66ef8d5b8f9b10df Mon Sep 17 00:00:00 2001 From: imaxouning Date: Mon, 23 Nov 2026 16:07:46 +0300 Subject: [PATCH] fix(dispatcher): isolate healthcheck connections (CLOUDFRONT-67362) --- README.md | 6 +- lib/dispatcher.ts | 252 ++++++++++++++++++++++----------------- package-lock.json | 13 ++ package.json | 1 + tests/dispatcher.test.js | 218 +++++++++++++++++++++++++++++++-- 5 files changed, 369 insertions(+), 121 deletions(-) diff --git a/README.md b/README.md index d98788d..0d430dd 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ export const {db, CoreBaseModel, helpers} = initDB({ - `logger`: Provide the `info` and `error` callbacks for logging messages - `dispatcherOptions`: Settings for connection balancing (none of the options are required) - `healthcheckInterval`: Health check interval in milliseconds, default value: 5000ms - - `healthcheckTimeout`: Health check interval in milliseconds, default value: 700ms + - `healthcheckTimeout`: Health check deadline in milliseconds, including connection acquisition and the query, default value: 700ms - `suppressStatusLogs`: Boolean value that disables database health-check status logs (useful for developers) - `beforeTerminate`: Function called before terminating a connection, must return a Promise - `topologyMode`: Connection topology, either `primary-replica` (the default) or `proxy` @@ -68,7 +68,7 @@ export const {db, CoreBaseModel, helpers} = initDB({ - `{kind: 'fastest'}` (the default): always picks the host with the lowest latest health-check latency; among equally fast hosts, the first one in the connection list - `{kind: 'round-robin', latencyToleranceMs?: number}`: healthy hosts are used in turn, spreading load across them. Without `latencyToleranceMs`, every healthy host takes part regardless of latency, so with hosts in several data centers part of the load goes to distant ones. Set `latencyToleranceMs` to rotate only hosts whose latest health-check latency is within that value of the fastest one, e.g. `10` to skip distant hosts, or `0` to rotate only the hosts sharing the lowest latency - `knexOptions`: Non-required additional options that will be passed to Knex before initialization -- `onKnexCreated`: Optional callback called synchronously for each Knex instance created by the dispatcher, before database health checks start. Use it to attach instrumentation, event listeners, or plugins that do not require an active database connection. If it throws, initialization fails. The callback receives the Knex instance and returns nothing. +- `onKnexCreated`: Optional callback called synchronously for each application Knex instance created by the dispatcher, before database health checks start. Use it to attach instrumentation, event listeners, or plugins that do not require an active database connection. If it throws, initialization fails. The callback receives the Knex instance and returns nothing. - `onHealthcheck`: Optional synchronous callback called after each database health check with a snapshot of every host's availability, latency, and role. In `primary-replica` mode, unavailable hosts have the `unknown` role; proxy connections do not include a role. It is called even when `suppressStatusLogs` is enabled. Callback errors do not interrupt database routing or subsequent health checks. When all connection strings point to equivalent proxy or router instances, such as SPQR routers, use `proxy` mode. Healthy endpoints are then eligible for both primary and replica queries, and the endpoint with the lowest latest health-check latency is selected (with the `round-robin` balancing strategy, endpoints are rotated instead): @@ -101,6 +101,8 @@ The `initDB` constructor exports three elements: `db`, `CoreBaseModel`, and `hel `db`: Instance of the [PGDispatcher](https://github.com/gravity-ui/postgreskit/blob/main/lib/dispatcher.ts) module responsible for connection balancing. Under the hood, this module creates N instances of knex (N is the number of hosts passed in `connectionString`). By default, it polls the database hosts every `healthcheckInterval` milliseconds, requesting if they are primary hosts or replica hosts (using the `SELECT pg_is_in_recovery()` query). In `proxy` topology mode, it uses `SELECT 1` instead and routes both `db.primary` and `db.replica` to the fastest healthy endpoint (or rotates between healthy endpoints with the `round-robin` balancing strategy). +Health checks use a separate `pg` pool with at most one extra connection per host, so application pool saturation does not delay probes. Probe latency includes acquiring this connection and executing the query; timed-out connections are destroyed. Connection URL options, including TLS and authentication, apply to both pools. Application Knex hooks and pool settings do not apply to probes. Termination closes both pools. + Public `db` methods: - `ready`: Function that returns a Promise that is resolved after the database connection has been established. This function is useful when you do not want to start query processing until the database is ready: for this, add `await db.ready(); next()` as middleware diff --git a/lib/dispatcher.ts b/lib/dispatcher.ts index 3d8ea07..3e0b54d 100644 --- a/lib/dispatcher.ts +++ b/lib/dispatcher.ts @@ -2,6 +2,7 @@ import {URL} from 'url'; import knexBuilder from 'knex'; import type {Knex} from 'knex'; +import {Pool, type PoolClient} from 'pg'; import type { BalancingStrategy, @@ -40,6 +41,9 @@ export interface PDConstructorArgs { interface PDConnection { host: string; knex: Knex; + healthcheckPool: Pool; + check?: Promise; + cancelCheck?: () => void; primary: boolean; healthy: boolean; latency: number; @@ -96,7 +100,9 @@ export class PGDispatcher { private logger: {info: InfoLogger; error: ErrorLogger}; private onHealthcheck?: PGHealthcheckHandler; private hcTimer?: Timeout | null; - private isInit = false; + private initialHealthcheck: Promise; + private healthcheck?: Promise; + private termination?: Promise; private isTerminating = false; private readonly balancingStrategy: BalancingStrategy; private balancingCursor = 0; @@ -123,9 +129,19 @@ export class PGDispatcher { connection: connectionString, }); onKnexCreated?.(knex); + const healthcheckPool = new Pool({ + connectionString, + min: 0, + max: 1, + connectionTimeoutMillis: options.healthcheckTimeout, + }); + healthcheckPool.on('error', (error) => { + this.logger.error({error, data: {host: url.hostname, phase: 'idle'}}); + }); return { host: url.hostname, knex, + healthcheckPool, primary: false, healthy: false, latency: Infinity, @@ -150,9 +166,10 @@ export class PGDispatcher { }, }; - this.initHealthcheck().catch((error) => { - this.logger.error({error}); - }); + this.initialHealthcheck = this.performHealthcheck(); + this.hcTimer = setInterval(() => { + this.performHealthcheck(); + }, this.options.healthcheckInterval); } get knexConfig() { @@ -160,42 +177,41 @@ export class PGDispatcher { } async ready() { - if (!this.isInit) { - await this.knexReady(); - await Promise.all(this.connections.map((c) => this.checkDatabase(c))); - - this.isInit = true; - } - - return Promise.resolve(); + await this.initialHealthcheck; } terminate() { + if (this.termination) { + return this.termination; + } this.isTerminating = true; if (this.hcTimer) { clearInterval(this.hcTimer); + this.hcTimer = null; } - - return Promise.all( - this.connections.map((c) => - c.knex - .destroy() - .then(() => { - this.logger.info({ - message: 'Connection successfully terminated', - data: {host: c.host}, - }); - }) - .catch((error) => - this.logger.error({ - message: 'Error during connection terminating', - error, - data: {host: c.host}, - }), - ), + this.connections.forEach((connection) => connection.cancelCheck?.()); + this.termination = Promise.all( + this.connections.flatMap((c) => + [c.knex.destroy(), c.healthcheckPool.end()].map((closing) => + closing + .then(() => { + this.logger.info({ + message: 'Connection successfully terminated', + data: {host: c.host}, + }); + }) + .catch((error) => + this.logger.error({ + message: 'Error during connection terminating', + error, + data: {host: c.host}, + }), + ), + ), ), ); + return this.termination; } get primary() { @@ -249,23 +265,18 @@ export class PGDispatcher { } } - private async initHealthcheck() { - await this.knexReady(); - + private performHealthcheck(): Promise { if (this.isTerminating) { - return; + return Promise.resolve(); } - - const performHealthcheck = () => { - const checkups = this.connections.map((connection) => - this.checkDatabase(connection).catch((error) => { - this.logger.error({message: 'Unhandled error during database checkup', error}); - connection.healthy = false; - connection.primary = false; - }), - ); - Promise.all(checkups).then(() => { - // Connections hold shared current state; this is not an isolated per-cycle result. + if (this.healthcheck) { + return this.healthcheck; + } + this.healthcheck = Promise.all(this.connections.map((c) => this.checkDatabase(c))) + .then(() => { + if (this.isTerminating) { + return; + } const status = this.getHealthcheckStatus(); if (!this.options.suppressHealthcheckStatusLogs) { this.logger.info({ @@ -282,26 +293,21 @@ export class PGDispatcher { }); } this.notifyHealthcheck(status); + }) + .finally(() => { + this.healthcheck = undefined; }); - }; - - performHealthcheck(); - - this.hcTimer = setInterval(() => { - performHealthcheck(); - }, this.options.healthcheckInterval); + return this.healthcheck; } - private async performCheckupQuery(knex: Knex): Promise { + private async performCheckupQuery(client: PoolClient): Promise { if (this.isProxyMode) { - await knex.raw('SELECT 1;').timeout(this.options.healthcheckTimeout); + await client.query('SELECT 1;'); return {pingOk: true, primary: false}; } - const result = await knex - .raw('SELECT pg_is_in_recovery();') - .timeout(this.options.healthcheckTimeout); + const result = await client.query('SELECT pg_is_in_recovery();'); const isReplica = result && result.rows && result.rows[0] && result.rows[0].pg_is_in_recovery; @@ -312,61 +318,91 @@ export class PGDispatcher { return {pingOk, primary: isPrimary}; } - private async checkDatabase(connection: PDConnection) { - let deadline: ReturnType | undefined; - - try { - const startTime = new Date().getTime(); - type RaceCheckupResult = PDCheckupResult | null; - const checkupResult: RaceCheckupResult = (await Promise.race([ - Promise.resolve(this.performCheckupQuery(connection.knex)).catch((error) => { - this.logger.error({message: 'Error performing database checkup', error}); - }), - new Promise((resolve) => { - deadline = setTimeout( - () => resolve(null), - this.options.healthcheckTimeout + 10, - ); - }), - ])) as RaceCheckupResult; - connection.latency = new Date().getTime() - startTime; - - if (checkupResult) { - connection.healthy = checkupResult.pingOk; - connection.primary = checkupResult.primary; - } else { - if (connection.latency > this.options.healthcheckTimeout) { - this.logger.error({ - message: 'Database checkup timeouted', - data: {host: connection.host}, - }); - } else { + private checkDatabase(connection: PDConnection): Promise { + if (connection.check) { + return connection.check; + } + const startTime = Date.now(); + let phase = 'acquire'; + let expired = false; + let client: PoolClient | undefined; + let released = false; + const release = (destroy = false) => { + if (client && !released) { + released = true; + client.release(destroy); + client.removeListener('error', onClientError); + } + }; + let rejectDeadline: (error: Error) => void; + const deadlineResult = new Promise((_, reject) => { + rejectDeadline = reject; + }); + function onClientError(error: Error) { + expired = true; + release(true); + rejectDeadline(error); + } + const cancel = () => { + expired = true; + // Destroy an in-flight query's socket; never return it to the idle pool. + release(true); + rejectDeadline(new Error('Database checkup timeouted')); + }; + const deadline = setTimeout(cancel, this.options.healthcheckTimeout); + connection.cancelCheck = cancel; + const physicalCheck = (async () => { + try { + client = await connection.healthcheckPool.connect(); + client.on('error', onClientError); + if (expired) { + release(true); + throw new Error('Database checkup timeouted'); + } + phase = 'query'; + return await this.performCheckupQuery(client); + } catch (error) { + // Driver-side query timeouts may reject before the server stops executing. + release(true); + throw error; + } finally { + release(); + } + })(); + const result = Promise.race([physicalCheck, deadlineResult]) + .then((checkup) => { + if (!this.isTerminating) { + connection.healthy = checkup.pingOk; + connection.primary = checkup.primary; + } + }) + .catch((error) => { + if (!this.isTerminating) { + connection.healthy = false; + connection.primary = false; this.logger.error({ - message: 'Database checkup failed', - data: {host: connection.host}, + message: 'Error performing database checkup', + error, + data: {host: connection.host, phase}, }); } - - connection.healthy = false; - connection.primary = false; - } - } catch (error) { - connection.healthy = false; - connection.primary = false; - this.logger.error({ - message: 'Database checkup failed', - error: error as Error, - data: {host: connection.host}, - }); - } finally { - if (deadline !== undefined) { + }) + .finally(() => { clearTimeout(deadline); - } - } - } - - private async knexReady() { - await Promise.all(this.connections.map((c) => c.knex)); + connection.cancelCheck = undefined; + connection.latency = Date.now() - startTime; + }); + connection.check = result; + // The deadline reports failure immediately. Keep single-flight protection until + // the physical operation settles so late completion cannot overlap a new probe. + physicalCheck + .catch(() => {}) + .finally(() => { + result.then(() => { + connection.check = undefined; + }); + }); + return result; } private getHealthcheckStatus(): PGHealthcheckStatus { diff --git a/package-lock.json b/package-lock.json index 3a3a342..635b35b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -24,6 +24,7 @@ "@types/jest": "^29.5.13", "@types/lodash": "^4.17.7", "@types/node": "^18.16.16", + "@types/pg": "^8.23.1", "@types/supertest": "^6.0.2", "@typescript-eslint/eslint-plugin": "^8.6.0", "eslint": "^8.56.0", @@ -2587,6 +2588,18 @@ "integrity": "sha512-NpaM49IGQQAUlBhHMF82QH80J08os4ZmyF9MkpCzWAGuOHqE4gTEbhzd7L3l5LmWuZ6E0OiC1FweQ4tsiW35+g==", "dev": true }, + "node_modules/@types/pg": { + "version": "8.23.1", + "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.23.1.tgz", + "integrity": "sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "pg-protocol": "*", + "pg-types": "^2.2.0" + } + }, "node_modules/@types/semver": { "version": "7.5.8", "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.8.tgz", diff --git a/package.json b/package.json index c456ca9..f12a227 100644 --- a/package.json +++ b/package.json @@ -37,6 +37,7 @@ "@types/jest": "^29.5.13", "@types/lodash": "^4.17.7", "@types/node": "^18.16.16", + "@types/pg": "^8.23.1", "@types/supertest": "^6.0.2", "@typescript-eslint/eslint-plugin": "^8.6.0", "eslint": "^8.56.0", diff --git a/tests/dispatcher.test.js b/tests/dispatcher.test.js index 606c884..c8aa8e3 100644 --- a/tests/dispatcher.test.js +++ b/tests/dispatcher.test.js @@ -1,8 +1,10 @@ /* eslint-env jest */ jest.mock('knex', () => jest.fn()); +jest.mock('pg', () => ({Pool: jest.fn()})); const knexBuilder = require('knex'); +const {Pool} = require('pg'); const {defaultDispatcherOptions} = require('../build/constants'); const {initDB} = require('../build/core'); @@ -11,12 +13,21 @@ const {PGDispatcher} = require('../build/dispatcher'); const activeDispatchers = []; function createKnex(checkup) { - const timeout = jest.fn(() => checkup()); - + const probe = { + query: jest.fn(() => checkup()), + release: jest.fn(), + on: jest.fn(), + removeListener: jest.fn(), + }; return { destroy: jest.fn(() => Promise.resolve()), - raw: jest.fn(() => ({timeout})), - timeout, + raw: jest.fn(() => new Promise(() => {})), + probe, + healthcheckPool: { + connect: jest.fn(() => Promise.resolve(probe)), + end: jest.fn(() => Promise.resolve()), + on: jest.fn(), + }, }; } @@ -31,8 +42,11 @@ function failedCheckup() { return Promise.reject(new Error('Proxy unavailable')); } -function createDispatcher(clients, options = {}, onHealthcheck) { - clients.forEach((client) => knexBuilder.mockImplementationOnce(() => client)); +function createDispatcher(clients, options = {}, onHealthcheck, constructorOptions = {}) { + clients.forEach((client) => { + knexBuilder.mockImplementationOnce(() => client); + Pool.mockImplementationOnce(() => client.healthcheckPool); + }); const logger = { error: jest.fn(), @@ -50,6 +64,7 @@ function createDispatcher(clients, options = {}, onHealthcheck) { ...options, }, onHealthcheck, + ...constructorOptions, }); activeDispatchers.push(dispatcher); @@ -74,8 +89,8 @@ describe('PGDispatcher topology modes', () => { await dispatcher.ready(); expect(defaultDispatcherOptions.topologyMode).toBe('primary-replica'); - expect(primary.raw).toHaveBeenCalledWith('SELECT pg_is_in_recovery();'); - expect(replica.raw).toHaveBeenCalledWith('SELECT pg_is_in_recovery();'); + expect(primary.probe.query).toHaveBeenCalledWith('SELECT pg_is_in_recovery();'); + expect(replica.probe.query).toHaveBeenCalledWith('SELECT pg_is_in_recovery();'); expect(dispatcher.primary).toBe(primary); expect(dispatcher.replica).toBe(replica); }); @@ -108,8 +123,8 @@ describe('PGDispatcher topology modes', () => { await dispatcher.ready(); for (const proxy of [slowerProxy, fasterProxy, unhealthyProxy]) { - expect(proxy.raw).toHaveBeenCalledWith('SELECT 1;'); - expect(proxy.raw).not.toHaveBeenCalledWith('SELECT pg_is_in_recovery();'); + expect(proxy.probe.query).toHaveBeenCalledWith('SELECT 1;'); + expect(proxy.probe.query).not.toHaveBeenCalledWith('SELECT pg_is_in_recovery();'); } expect(dispatcher.primary).toBe(fasterProxy); expect(dispatcher.replica).toBe(fasterProxy); @@ -324,6 +339,184 @@ describe('PGDispatcher healthcheck timer cleanup', () => { }); }); +describe('PGDispatcher isolated probes', () => { + beforeEach(() => { + jest.useFakeTimers(); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + + test('a saturated work pool does not remove the primary or delay probe latency', async () => { + const primary = createKnex(() => Promise.resolve({rows: [{pg_is_in_recovery: false}]})); + const onKnexCreated = jest.fn(); + const onHealthcheck = jest.fn(); + const knexOptions = {pool: {min: 0, max: 20}, acquireConnectionTimeout: 40000}; + const {dispatcher} = createDispatcher([primary], {}, onHealthcheck, { + knexOptions, + onKnexCreated, + }); + await dispatcher.ready(); + + // All 20 application requests remain pending throughout the next probe. + Array.from({length: 20}, () => dispatcher.primary.raw('SELECT pg_sleep(60);')); + await jest.advanceTimersByTimeAsync(60_000); + + expect(dispatcher.primary).toBe(primary); + expect(primary.raw).toHaveBeenCalledTimes(20); + expect(primary.probe.query).toHaveBeenCalledTimes(2); + expect(onHealthcheck).toHaveBeenLastCalledWith( + expect.objectContaining({ + connections: [ + expect.objectContaining({healthy: true, role: 'primary', latency: 0}), + ], + }), + ); + expect(onKnexCreated).toHaveBeenCalledTimes(1); + expect(onKnexCreated).toHaveBeenCalledWith(primary); + expect(knexBuilder).toHaveBeenLastCalledWith(expect.objectContaining(knexOptions)); + expect(Pool).toHaveBeenLastCalledWith({ + connectionString: 'postgresql://user:password@database-0.example/db', + min: 0, + max: 1, + connectionTimeoutMillis: 100, + }); + }); + + test('an actual probe failure removes a previously healthy primary and reports query phase', async () => { + const primary = createKnex(() => Promise.resolve({rows: [{pg_is_in_recovery: false}]})); + const onHealthcheck = jest.fn(); + const {dispatcher, logger} = createDispatcher([primary], {}, onHealthcheck); + await dispatcher.ready(); + expect(dispatcher.primary).toBe(primary); + primary.probe.query.mockRejectedValue(new Error('Connection terminated unexpectedly')); + + await jest.advanceTimersByTimeAsync(60_000); + + expect(() => dispatcher.primary).toThrow( + expect.objectContaining({code: 'ERR_DB_NOT_AVAILABLE'}), + ); + expect(logger.error).toHaveBeenCalledWith('PGDispatcher error', expect.any(Error), { + host: 'database-0.example', + phase: 'query', + }); + expect(onHealthcheck).toHaveBeenLastCalledWith( + expect.objectContaining({ + connections: [expect.objectContaining({healthy: false, role: 'unknown'})], + }), + ); + }); + + test('constructor, concurrent ready calls and timer share one pending physical probe', async () => { + let finish; + const primary = createKnex( + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + const {dispatcher} = createDispatcher([primary], {healthcheckInterval: 10}); + const ready = Promise.all([dispatcher.ready(), dispatcher.ready()]); + await jest.advanceTimersByTimeAsync(30); + expect(primary.healthcheckPool.connect).toHaveBeenCalledTimes(1); + expect(primary.probe.query).toHaveBeenCalledTimes(1); + + finish({rows: [{pg_is_in_recovery: false}]}); + await ready; + expect(dispatcher.primary).toBe(primary); + await dispatcher.terminate(); + expect(jest.getTimerCount()).toBe(0); + }); + + test('timeout destroys the client without overlapping probes or accepting late success', async () => { + let finish; + const primary = createKnex( + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + const {dispatcher} = createDispatcher([primary], {healthcheckInterval: 10}); + const ready = dispatcher.ready(); + await jest.advanceTimersByTimeAsync(150); + await ready; + + expect(primary.probe.release).toHaveBeenCalledTimes(1); + expect(primary.probe.release).toHaveBeenCalledWith(true); + expect(primary.healthcheckPool.connect).toHaveBeenCalledTimes(1); + expect(() => dispatcher.primary).toThrow(); + finish({rows: [{pg_is_in_recovery: false}]}); + await jest.advanceTimersByTimeAsync(0); + expect(() => dispatcher.primary).toThrow(); + + primary.probe.query.mockResolvedValue({rows: [{pg_is_in_recovery: false}]}); + await jest.advanceTimersByTimeAsync(10); + expect(dispatcher.primary).toBe(primary); + await dispatcher.terminate(); + expect(primary.destroy).toHaveBeenCalledTimes(1); + expect(primary.healthcheckPool.end).toHaveBeenCalledTimes(1); + expect(jest.getTimerCount()).toBe(0); + }); + + test.each(['failure', 'pending'])( + 'cleans both pools during connection acquisition %s', + async (outcome) => { + const primary = createKnex(() => Promise.resolve({rows: [{pg_is_in_recovery: false}]})); + if (outcome === 'failure') { + primary.healthcheckPool.connect.mockRejectedValue(new Error('Connection refused')); + } else { + primary.healthcheckPool.connect.mockReturnValue(new Promise(() => {})); + } + const {dispatcher, logger} = createDispatcher([primary]); + const ready = dispatcher.ready(); + await jest.advanceTimersByTimeAsync(100); + await ready; + expect(logger.error).toHaveBeenCalledWith('PGDispatcher error', expect.any(Error), { + host: 'database-0.example', + phase: 'acquire', + }); + expect(primary.probe.query).not.toHaveBeenCalled(); + await Promise.all([dispatcher.terminate(), dispatcher.terminate()]); + expect(primary.destroy).toHaveBeenCalledTimes(1); + expect(primary.healthcheckPool.end).toHaveBeenCalledTimes(1); + expect(jest.getTimerCount()).toBe(0); + }, + ); + + test('handles idle pool errors through the existing logger', async () => { + const primary = createKnex(() => Promise.resolve({rows: [{pg_is_in_recovery: false}]})); + const {dispatcher, logger} = createDispatcher([primary]); + await dispatcher.ready(); + const idleError = new Error('Idle connection lost'); + const [, handleError] = primary.healthcheckPool.on.mock.calls[0]; + handleError(idleError); + expect(logger.error).toHaveBeenCalledWith('PGDispatcher error', idleError, { + host: 'database-0.example', + phase: 'idle', + }); + }); + + test('handles errors on an acquired probe client and destroys it', async () => { + const primary = createKnex(() => new Promise(() => {})); + const {dispatcher, logger} = createDispatcher([primary]); + const ready = dispatcher.ready(); + await jest.advanceTimersByTimeAsync(0); + const clientError = new Error('Probe socket failed'); + const [, handleError] = primary.probe.on.mock.calls[0]; + handleError(clientError); + await ready; + + expect(primary.probe.release).toHaveBeenCalledWith(true); + expect(primary.probe.removeListener).toHaveBeenCalledWith('error', handleError); + expect(() => dispatcher.primary).toThrow(); + expect(logger.error).toHaveBeenCalledWith('PGDispatcher error', clientError, { + host: 'database-0.example', + phase: 'query', + }); + }); +}); + describe('PGDispatcher balancing strategies', () => { function pick(dispatcher, role, times) { return Array.from({length: times}, () => dispatcher[role]); @@ -399,7 +592,10 @@ describe('PGDispatcher balancing strategies', () => { createKnex(successfulCheckup({value: 1})), createKnex(successfulCheckup({value: 1})), ]; - proxies.forEach((proxy) => knexBuilder.mockImplementationOnce(() => proxy)); + proxies.forEach((proxy) => { + knexBuilder.mockImplementationOnce(() => proxy); + Pool.mockImplementationOnce(() => proxy.healthcheckPool); + }); const {db, terminate} = initDB({ connectionString: 'postgresql://db-0.example/db,postgresql://db-1.example/db',