Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,15 @@ 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`
- `balancingStrategy`: How a host is chosen for `db.replica` (and for both `db.primary` and `db.replica` in `proxy` mode), an object with a `kind` field:
- `{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):
Expand Down Expand Up @@ -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
Expand Down
252 changes: 144 additions & 108 deletions lib/dispatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -40,6 +41,9 @@ export interface PDConstructorArgs {
interface PDConnection {
host: string;
knex: Knex;
healthcheckPool: Pool;
check?: Promise<void>;
cancelCheck?: () => void;
primary: boolean;
healthy: boolean;
latency: number;
Expand Down Expand Up @@ -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<void>;
private healthcheck?: Promise<void>;
private termination?: Promise<void[]>;
private isTerminating = false;
private readonly balancingStrategy: BalancingStrategy;
private balancingCursor = 0;
Expand All @@ -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,
Expand All @@ -150,52 +166,52 @@ 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() {
return this.knexOptions;
}

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() {
Expand Down Expand Up @@ -249,23 +265,18 @@ export class PGDispatcher {
}
}

private async initHealthcheck() {
await this.knexReady();

private performHealthcheck(): Promise<void> {
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({
Expand All @@ -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<PDCheckupResult> {
private async performCheckupQuery(client: PoolClient): Promise<PDCheckupResult> {
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;
Expand All @@ -312,61 +318,91 @@ export class PGDispatcher {
return {pingOk, primary: isPrimary};
}

private async checkDatabase(connection: PDConnection) {
let deadline: ReturnType<typeof setTimeout> | 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<void> {
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<never>((_, 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 {
Expand Down
13 changes: 13 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading