pg-cache 3.31.1 → 3.31.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -110,6 +110,39 @@ process.on('SIGTERM', async () => {
110
110
  });
111
111
  ```
112
112
 
113
+ ### Pool Settings
114
+
115
+ Pools created by `getPgPool` take these settings from `pool` in the config
116
+ passed to it, then from the environment:
117
+
118
+ | Setting | Environment variable | Default |
119
+ |---|---|---|
120
+ | `max` | `PG_POOL_MAX` | `5` |
121
+ | `idleTimeoutMillis` | `PG_POOL_IDLE_TIMEOUT_MS` | `30000` |
122
+ | `connectionTimeoutMillis` | `PG_POOL_CONNECTION_TIMEOUT_MS` | `5000` |
123
+ | `keepAliveInitialDelayMillis` | `PG_POOL_KEEPALIVE_INITIAL_DELAY_MS` | `10000` |
124
+ | `queryTimeoutMillis` | `PG_POOL_QUERY_TIMEOUT_MS` | `0` (no limit) |
125
+
126
+ TCP keepalive is always on for the default TCP driver. With the default delay,
127
+ an idle connection whose server vanished without closing it typically fails
128
+ after about 20 seconds. A cached pool keeps the delay it was created with and
129
+ warns if a later caller requests a different delay.
130
+
131
+ `queryTimeoutMillis` bounds how long a query may wait for PostgreSQL. When it
132
+ passes, the query fails and its connection is closed rather than returned to
133
+ the pool, so the next caller gets a fresh connection. It catches connections
134
+ that went silent; it is not a statement timeout, so keep it above the longest
135
+ statement the pool may run. The GraphQL server defaults to 130 seconds, just
136
+ above the highest request `statement_timeout`, and the same deadline also
137
+ applies to schema introspection on that pool. Standalone `pgpm deploy` has no
138
+ query deadline unless `PG_POOL_QUERY_TIMEOUT_MS` is set in its environment.
139
+
140
+ When a pool is reused, the shortest positive deadline requested for that
141
+ cached pool applies to queries started from then on, including on existing
142
+ clients. A later lookup cannot extend or disable it; `0` means no deadline
143
+ when no caller of that pool requests one. A custom pool driver controls its
144
+ own connection settings.
145
+
113
146
  ## API Reference
114
147
 
115
148
  ### pgCache
package/esm/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  // Main exports from pg-cache package
2
2
  export { getActivePgPoolFactory, hasPgPoolFactory, registerPgPoolFactory } from './driver';
3
3
  export { close, getPgCacheConfig, pgCache, PgPoolCacheManager, teardownPgPools } from './lru';
4
- export { buildConnectionString, defaultPgPoolFactory, getPgPool, getPgPoolConfig } from './pg';
4
+ export { buildConnectionString, defaultPgPoolFactory, getPgPool, getPgPoolConfig, getPgQueryTimeout } from './pg';
package/esm/pg.js CHANGED
@@ -4,7 +4,9 @@ import pg from 'pg';
4
4
  import { getPgEnvOptions } from 'pg-env';
5
5
  import { getActivePgPoolFactory } from './driver';
6
6
  import { pgCache } from './lru';
7
+ import { applyQueryDeadline } from './query-deadline';
7
8
  const log = new Logger('pg-cache');
9
+ const poolPolicies = new WeakMap();
8
10
  export const buildConnectionString = (user, password, host, port, database) => `postgres://${user}:${password}@${host}:${port}/${database}`;
9
11
  /**
10
12
  * Read per-pool configuration from environment variables.
@@ -13,15 +15,35 @@ export const buildConnectionString = (user, password, host, port, database) => `
13
15
  * - PG_POOL_MAX: Maximum clients per pool (default: 5)
14
16
  * - PG_POOL_IDLE_TIMEOUT_MS: Close idle clients after ms (default: 30000)
15
17
  * - PG_POOL_CONNECTION_TIMEOUT_MS: Fail connect() after ms (default: 5000)
18
+ * - PG_POOL_KEEPALIVE_INITIAL_DELAY_MS: Start TCP keepalive probes after ms
19
+ * without traffic (default: 10000). Node sends up to 10 probes one second
20
+ * apart, so a connection whose server vanished fails about 20 s after it
21
+ * went quiet instead of never.
22
+ *
23
+ * The query deadline (PG_POOL_QUERY_TIMEOUT_MS) is not a node-postgres pool
24
+ * option; see `getPgQueryTimeout`.
16
25
  */
17
26
  export function getPgPoolConfig(overrides) {
18
27
  return {
19
28
  max: overrides?.max ?? parseEnvNumber(process.env.PG_POOL_MAX) ?? 5,
20
29
  idleTimeoutMillis: overrides?.idleTimeoutMillis ?? parseEnvNumber(process.env.PG_POOL_IDLE_TIMEOUT_MS) ?? 30000,
21
30
  connectionTimeoutMillis: overrides?.connectionTimeoutMillis ?? parseEnvNumber(process.env.PG_POOL_CONNECTION_TIMEOUT_MS) ?? 5000,
31
+ keepAlive: true,
32
+ keepAliveInitialDelayMillis: overrides?.keepAliveInitialDelayMillis ?? parseEnvNumber(process.env.PG_POOL_KEEPALIVE_INITIAL_DELAY_MS) ?? 10000,
22
33
  ...(overrides?.allowExitOnIdle !== undefined && { allowExitOnIdle: overrides.allowExitOnIdle }),
23
34
  };
24
35
  }
36
+ /**
37
+ * How long a query on a pool's connection may wait for PostgreSQL before the
38
+ * connection is given up (see `applyQueryDeadline`): `overrides`, then
39
+ * PG_POOL_QUERY_TIMEOUT_MS, then `fallback` (default 0, no limit). The
40
+ * limit is off by default because pg-cache also serves migrations whose
41
+ * statements may run for a long time; a server that bounds its statements
42
+ * passes its own fallback.
43
+ */
44
+ export function getPgQueryTimeout(overrides, fallback = 0) {
45
+ return overrides?.queryTimeoutMillis ?? parseEnvNumber(process.env.PG_POOL_QUERY_TIMEOUT_MS) ?? fallback;
46
+ }
25
47
  /**
26
48
  * Default pool factory: builds a real `pg.Pool` over TCP. This is the behavior
27
49
  * used whenever no alternate driver is registered (see `./driver`).
@@ -32,6 +54,12 @@ export const defaultPgPoolFactory = (pgConfig) => {
32
54
  const connectionString = buildConnectionString(user, password, host, port, database);
33
55
  const poolConfig = getPgPoolConfig(pgConfig.pool);
34
56
  const pgPool = new pg.Pool({ connectionString, ...poolConfig });
57
+ const policy = {
58
+ queryTimeoutMillis: getPgQueryTimeout(pgConfig.pool),
59
+ keepAliveInitialDelayMillis: poolConfig.keepAliveInitialDelayMillis ?? 10000,
60
+ warnedAboutKeepAlive: false
61
+ };
62
+ poolPolicies.set(pgPool, policy);
35
63
  /**
36
64
  * IMPORTANT: Pool-level error handler for idle connection errors.
37
65
  *
@@ -101,10 +129,13 @@ export const defaultPgPoolFactory = (pgConfig) => {
101
129
  * query on that client), and the pool discards the broken client when it is
102
130
  * released. An idle client's error also reaches the pool handler above, so
103
131
  * this one logs at debug level instead of reporting it twice.
132
+ *
133
+ * The same hook bounds every query on the client by the pool's query
134
+ * deadline, when one is set (see `applyQueryDeadline`).
104
135
  */
105
136
  pgPool.on('connect', (client) => {
106
- client.on('error', (err) => {
107
- log.debug(`Pool ${database} client connection error [${err.code || 'unknown'}]: ${err.message}`);
137
+ applyQueryDeadline(client, () => policy.queryTimeoutMillis, (err) => log.debug(`Pool ${database} client connection error [${err.code || 'unknown'}]: ${err.message}`), (queryTimeoutMillis) => {
138
+ log.warn(`Pool ${database}: no answer from PostgreSQL within ${queryTimeoutMillis} ms; closing the connection`);
108
139
  });
109
140
  });
110
141
  return pgPool;
@@ -114,8 +145,24 @@ export const getPgPool = (pgConfig) => {
114
145
  const { database } = config;
115
146
  if (pgCache.has(database)) {
116
147
  const cached = pgCache.get(database);
117
- if (cached)
148
+ if (cached) {
149
+ const policy = poolPolicies.get(cached);
150
+ if (policy) {
151
+ const requested = getPgQueryTimeout(pgConfig.pool);
152
+ if (Number.isFinite(requested) && requested > 0 &&
153
+ (!(policy.queryTimeoutMillis > 0) || requested < policy.queryTimeoutMillis)) {
154
+ policy.queryTimeoutMillis = requested;
155
+ }
156
+ const keepAliveDelay = pgConfig.pool?.keepAliveInitialDelayMillis ??
157
+ parseEnvNumber(process.env.PG_POOL_KEEPALIVE_INITIAL_DELAY_MS);
158
+ if (keepAliveDelay !== undefined && keepAliveDelay !== policy.keepAliveInitialDelayMillis &&
159
+ !policy.warnedAboutKeepAlive) {
160
+ policy.warnedAboutKeepAlive = true;
161
+ log.warn(`Pool ${database} already has TCP keepalive configured with a ${policy.keepAliveInitialDelayMillis} ms delay; ignoring later delay ${keepAliveDelay} ms`);
162
+ }
163
+ }
118
164
  return cached;
165
+ }
119
166
  }
120
167
  // Route through the registered driver (default = pg.Pool over TCP). A custom
121
168
  // factory may return any QueryablePool (e.g. an in-process PGlite pool); it is
@@ -0,0 +1,106 @@
1
+ /** Node's largest timer delay; `setTimeout` treats anything longer as 1 ms. */
2
+ const MAX_TIMER_DELAY = 2_147_483_647;
3
+ /** What node-postgres rejects a query with when its own `query_timeout` passes. */
4
+ const PG_LOCAL_READ_TIMEOUT = 'Query read timeout';
5
+ /**
6
+ * Bound how long each query on `client` may wait for PostgreSQL.
7
+ *
8
+ * A live server ends a slow statement itself (statement_timeout), and the
9
+ * connection stays usable. A connection that went silent cannot: its server
10
+ * vanished without closing it, the network path drops its packets, or the
11
+ * server stopped answering. node-postgres then waits for an answer that never
12
+ * comes. The wait is forever when the query was already acknowledged, and
13
+ * about 15 minutes of TCP retransmission otherwise, and every caller that
14
+ * later checks the client out of the pool waits behind it.
15
+ *
16
+ * node-postgres' own `query_timeout` is not enough: it fails the query but
17
+ * keeps the connection, so the caller's next query on it (a ROLLBACK, or the
18
+ * next request once the client is back in the pool) queues behind the
19
+ * unanswered one. When this deadline passes, the socket is destroyed instead,
20
+ * as pg-pool does when connecting takes too long: the unanswered query and
21
+ * every query queued behind it fail at once, and the pool discards the client
22
+ * when it is released. A query that fails on the caller's own `query_timeout`
23
+ * closes its connection the same way.
24
+ *
25
+ * Submittable queries (cursors, streams, COPY) are left alone: they can
26
+ * legitimately wait on whoever consumes them.
27
+ */
28
+ export const applyQueryDeadline = (client, getTimeoutMillis, onConnectionError, onTimeout) => {
29
+ let connectionError;
30
+ client.on('error', (error) => {
31
+ connectionError ??= error;
32
+ onConnectionError(error);
33
+ });
34
+ const query = client.query;
35
+ const destroy = (error) => {
36
+ client
37
+ .connection.stream.destroy(error);
38
+ };
39
+ const expire = (timeoutMillis) => {
40
+ const error = Object.assign(new Error(`Query read timeout: PostgreSQL did not answer within ${timeoutMillis} ms; the connection was closed`),
41
+ // The same code a dead socket reports when TCP gives up on it.
42
+ { code: 'ETIMEDOUT' });
43
+ onTimeout?.(timeoutMillis);
44
+ destroy(error);
45
+ };
46
+ function boundedQuery(config, values, callback) {
47
+ if (config == null || typeof config.submit === 'function') {
48
+ return query.call(this, config, values, callback);
49
+ }
50
+ const timeoutMillis = getTimeoutMillis();
51
+ const enabled = Number.isFinite(timeoutMillis) && timeoutMillis > 0;
52
+ const timer = enabled
53
+ ? setTimeout(expire, Math.min(timeoutMillis, MAX_TIMER_DELAY), timeoutMillis)
54
+ : undefined;
55
+ // The open socket keeps the process alive while a query is pending; the
56
+ // timer alone must not (a client may be unref()ed).
57
+ timer?.unref();
58
+ const settle = (err) => {
59
+ clearTimeout(timer);
60
+ // A caller's own `query_timeout` fails the query but leaves it unanswered
61
+ // on the connection, exactly what this deadline exists to clear.
62
+ if (!(err instanceof Error))
63
+ return;
64
+ if (enabled && err.message === PG_LOCAL_READ_TIMEOUT)
65
+ destroy(err);
66
+ if (err.severity === 'FATAL')
67
+ connectionError ??= err;
68
+ // A failed ROLLBACK can replace the original connection error with a
69
+ // generic failure on the unusable client.
70
+ if (connectionError && connectionError !== err)
71
+ err.cause ??= connectionError;
72
+ };
73
+ const settling = (cb) => (err, result) => {
74
+ settle(err);
75
+ cb(err, result);
76
+ };
77
+ let result;
78
+ try {
79
+ if (typeof values === 'function') {
80
+ return query.call(this, config, settling(values));
81
+ }
82
+ if (typeof callback === 'function') {
83
+ return query.call(this, config, values, settling(callback));
84
+ }
85
+ const ownCallback = config.callback;
86
+ if (typeof ownCallback === 'function') {
87
+ return query.call(this, { ...config, callback: settling(ownCallback) }, values);
88
+ }
89
+ result = query.call(this, config, values);
90
+ }
91
+ catch (error) {
92
+ // Nothing was sent; the timer must not outlive this call.
93
+ settle();
94
+ throw error;
95
+ }
96
+ if (result && typeof result.then === 'function') {
97
+ result.then(() => settle(), settle);
98
+ }
99
+ else {
100
+ // No way to observe completion: never risk closing a healthy connection.
101
+ settle();
102
+ }
103
+ return result;
104
+ }
105
+ client.query = boundedQuery;
106
+ };
package/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { getActivePgPoolFactory, hasPgPoolFactory, registerPgPoolFactory } from './driver';
2
2
  export { close, getPgCacheConfig, pgCache, PgPoolCacheManager, teardownPgPools } from './lru';
3
- export { buildConnectionString, defaultPgPoolFactory, getPgPool, getPgPoolConfig } from './pg';
3
+ export { buildConnectionString, defaultPgPoolFactory, getPgPool, getPgPoolConfig, getPgQueryTimeout } from './pg';
4
4
  export type { PgPoolFactory, QueryableClient, QueryablePool } from './driver';
5
5
  export type { PgCacheConfig, PoolCleanupCallback } from './lru';
package/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getPgPoolConfig = exports.getPgPool = exports.defaultPgPoolFactory = exports.buildConnectionString = exports.teardownPgPools = exports.PgPoolCacheManager = exports.pgCache = exports.getPgCacheConfig = exports.registerPgPoolFactory = exports.hasPgPoolFactory = exports.getActivePgPoolFactory = void 0;
3
+ exports.getPgQueryTimeout = exports.getPgPoolConfig = exports.getPgPool = exports.defaultPgPoolFactory = exports.buildConnectionString = exports.teardownPgPools = exports.PgPoolCacheManager = exports.pgCache = exports.getPgCacheConfig = exports.registerPgPoolFactory = exports.hasPgPoolFactory = exports.getActivePgPoolFactory = void 0;
4
4
  // Main exports from pg-cache package
5
5
  var driver_1 = require("./driver");
6
6
  Object.defineProperty(exports, "getActivePgPoolFactory", { enumerable: true, get: function () { return driver_1.getActivePgPoolFactory; } });
@@ -17,3 +17,4 @@ Object.defineProperty(exports, "buildConnectionString", { enumerable: true, get:
17
17
  Object.defineProperty(exports, "defaultPgPoolFactory", { enumerable: true, get: function () { return pg_1.defaultPgPoolFactory; } });
18
18
  Object.defineProperty(exports, "getPgPool", { enumerable: true, get: function () { return pg_1.getPgPool; } });
19
19
  Object.defineProperty(exports, "getPgPoolConfig", { enumerable: true, get: function () { return pg_1.getPgPoolConfig; } });
20
+ Object.defineProperty(exports, "getPgQueryTimeout", { enumerable: true, get: function () { return pg_1.getPgQueryTimeout; } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pg-cache",
3
- "version": "3.31.1",
3
+ "version": "3.31.3",
4
4
  "author": "Constructive <developers@constructive.io>",
5
5
  "description": "PostgreSQL connection pool LRU cache manager",
6
6
  "main": "index.js",
@@ -22,10 +22,10 @@
22
22
  "dependencies": {
23
23
  "lru-cache": "^11.2.7",
24
24
  "pg": "^8.21.0",
25
- "@pgpmjs/types": "^2.59.1",
26
- "@pgpmjs/logger": "^2.27.1",
27
- "12factor-env": "^1.34.1",
28
- "pg-env": "^1.33.1"
25
+ "12factor-env": "^1.34.2",
26
+ "@pgpmjs/logger": "^2.27.2",
27
+ "@pgpmjs/types": "^2.59.3",
28
+ "pg-env": "^1.33.3"
29
29
  },
30
30
  "devDependencies": {
31
31
  "@types/pg": "^8.20.4",
package/pg.d.ts CHANGED
@@ -9,8 +9,24 @@ export declare const buildConnectionString: (user: string, password: string, hos
9
9
  * - PG_POOL_MAX: Maximum clients per pool (default: 5)
10
10
  * - PG_POOL_IDLE_TIMEOUT_MS: Close idle clients after ms (default: 30000)
11
11
  * - PG_POOL_CONNECTION_TIMEOUT_MS: Fail connect() after ms (default: 5000)
12
+ * - PG_POOL_KEEPALIVE_INITIAL_DELAY_MS: Start TCP keepalive probes after ms
13
+ * without traffic (default: 10000). Node sends up to 10 probes one second
14
+ * apart, so a connection whose server vanished fails about 20 s after it
15
+ * went quiet instead of never.
16
+ *
17
+ * The query deadline (PG_POOL_QUERY_TIMEOUT_MS) is not a node-postgres pool
18
+ * option; see `getPgQueryTimeout`.
12
19
  */
13
20
  export declare function getPgPoolConfig(overrides?: PgPoolConfig): pg.PoolConfig;
21
+ /**
22
+ * How long a query on a pool's connection may wait for PostgreSQL before the
23
+ * connection is given up (see `applyQueryDeadline`): `overrides`, then
24
+ * PG_POOL_QUERY_TIMEOUT_MS, then `fallback` (default 0, no limit). The
25
+ * limit is off by default because pg-cache also serves migrations whose
26
+ * statements may run for a long time; a server that bounds its statements
27
+ * passes its own fallback.
28
+ */
29
+ export declare function getPgQueryTimeout(overrides?: PgPoolConfig, fallback?: number): number;
14
30
  /**
15
31
  * Default pool factory: builds a real `pg.Pool` over TCP. This is the behavior
16
32
  * used whenever no alternate driver is registered (see `./driver`).
package/pg.js CHANGED
@@ -5,13 +5,16 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.getPgPool = exports.defaultPgPoolFactory = exports.buildConnectionString = void 0;
7
7
  exports.getPgPoolConfig = getPgPoolConfig;
8
+ exports.getPgQueryTimeout = getPgQueryTimeout;
8
9
  const logger_1 = require("@pgpmjs/logger");
9
10
  const _12factor_env_1 = require("12factor-env");
10
11
  const pg_1 = __importDefault(require("pg"));
11
12
  const pg_env_1 = require("pg-env");
12
13
  const driver_1 = require("./driver");
13
14
  const lru_1 = require("./lru");
15
+ const query_deadline_1 = require("./query-deadline");
14
16
  const log = new logger_1.Logger('pg-cache');
17
+ const poolPolicies = new WeakMap();
15
18
  const buildConnectionString = (user, password, host, port, database) => `postgres://${user}:${password}@${host}:${port}/${database}`;
16
19
  exports.buildConnectionString = buildConnectionString;
17
20
  /**
@@ -21,15 +24,35 @@ exports.buildConnectionString = buildConnectionString;
21
24
  * - PG_POOL_MAX: Maximum clients per pool (default: 5)
22
25
  * - PG_POOL_IDLE_TIMEOUT_MS: Close idle clients after ms (default: 30000)
23
26
  * - PG_POOL_CONNECTION_TIMEOUT_MS: Fail connect() after ms (default: 5000)
27
+ * - PG_POOL_KEEPALIVE_INITIAL_DELAY_MS: Start TCP keepalive probes after ms
28
+ * without traffic (default: 10000). Node sends up to 10 probes one second
29
+ * apart, so a connection whose server vanished fails about 20 s after it
30
+ * went quiet instead of never.
31
+ *
32
+ * The query deadline (PG_POOL_QUERY_TIMEOUT_MS) is not a node-postgres pool
33
+ * option; see `getPgQueryTimeout`.
24
34
  */
25
35
  function getPgPoolConfig(overrides) {
26
36
  return {
27
37
  max: overrides?.max ?? (0, _12factor_env_1.parseEnvNumber)(process.env.PG_POOL_MAX) ?? 5,
28
38
  idleTimeoutMillis: overrides?.idleTimeoutMillis ?? (0, _12factor_env_1.parseEnvNumber)(process.env.PG_POOL_IDLE_TIMEOUT_MS) ?? 30000,
29
39
  connectionTimeoutMillis: overrides?.connectionTimeoutMillis ?? (0, _12factor_env_1.parseEnvNumber)(process.env.PG_POOL_CONNECTION_TIMEOUT_MS) ?? 5000,
40
+ keepAlive: true,
41
+ keepAliveInitialDelayMillis: overrides?.keepAliveInitialDelayMillis ?? (0, _12factor_env_1.parseEnvNumber)(process.env.PG_POOL_KEEPALIVE_INITIAL_DELAY_MS) ?? 10000,
30
42
  ...(overrides?.allowExitOnIdle !== undefined && { allowExitOnIdle: overrides.allowExitOnIdle }),
31
43
  };
32
44
  }
45
+ /**
46
+ * How long a query on a pool's connection may wait for PostgreSQL before the
47
+ * connection is given up (see `applyQueryDeadline`): `overrides`, then
48
+ * PG_POOL_QUERY_TIMEOUT_MS, then `fallback` (default 0, no limit). The
49
+ * limit is off by default because pg-cache also serves migrations whose
50
+ * statements may run for a long time; a server that bounds its statements
51
+ * passes its own fallback.
52
+ */
53
+ function getPgQueryTimeout(overrides, fallback = 0) {
54
+ return overrides?.queryTimeoutMillis ?? (0, _12factor_env_1.parseEnvNumber)(process.env.PG_POOL_QUERY_TIMEOUT_MS) ?? fallback;
55
+ }
33
56
  /**
34
57
  * Default pool factory: builds a real `pg.Pool` over TCP. This is the behavior
35
58
  * used whenever no alternate driver is registered (see `./driver`).
@@ -40,6 +63,12 @@ const defaultPgPoolFactory = (pgConfig) => {
40
63
  const connectionString = (0, exports.buildConnectionString)(user, password, host, port, database);
41
64
  const poolConfig = getPgPoolConfig(pgConfig.pool);
42
65
  const pgPool = new pg_1.default.Pool({ connectionString, ...poolConfig });
66
+ const policy = {
67
+ queryTimeoutMillis: getPgQueryTimeout(pgConfig.pool),
68
+ keepAliveInitialDelayMillis: poolConfig.keepAliveInitialDelayMillis ?? 10000,
69
+ warnedAboutKeepAlive: false
70
+ };
71
+ poolPolicies.set(pgPool, policy);
43
72
  /**
44
73
  * IMPORTANT: Pool-level error handler for idle connection errors.
45
74
  *
@@ -109,10 +138,13 @@ const defaultPgPoolFactory = (pgConfig) => {
109
138
  * query on that client), and the pool discards the broken client when it is
110
139
  * released. An idle client's error also reaches the pool handler above, so
111
140
  * this one logs at debug level instead of reporting it twice.
141
+ *
142
+ * The same hook bounds every query on the client by the pool's query
143
+ * deadline, when one is set (see `applyQueryDeadline`).
112
144
  */
113
145
  pgPool.on('connect', (client) => {
114
- client.on('error', (err) => {
115
- log.debug(`Pool ${database} client connection error [${err.code || 'unknown'}]: ${err.message}`);
146
+ (0, query_deadline_1.applyQueryDeadline)(client, () => policy.queryTimeoutMillis, (err) => log.debug(`Pool ${database} client connection error [${err.code || 'unknown'}]: ${err.message}`), (queryTimeoutMillis) => {
147
+ log.warn(`Pool ${database}: no answer from PostgreSQL within ${queryTimeoutMillis} ms; closing the connection`);
116
148
  });
117
149
  });
118
150
  return pgPool;
@@ -123,8 +155,24 @@ const getPgPool = (pgConfig) => {
123
155
  const { database } = config;
124
156
  if (lru_1.pgCache.has(database)) {
125
157
  const cached = lru_1.pgCache.get(database);
126
- if (cached)
158
+ if (cached) {
159
+ const policy = poolPolicies.get(cached);
160
+ if (policy) {
161
+ const requested = getPgQueryTimeout(pgConfig.pool);
162
+ if (Number.isFinite(requested) && requested > 0 &&
163
+ (!(policy.queryTimeoutMillis > 0) || requested < policy.queryTimeoutMillis)) {
164
+ policy.queryTimeoutMillis = requested;
165
+ }
166
+ const keepAliveDelay = pgConfig.pool?.keepAliveInitialDelayMillis ??
167
+ (0, _12factor_env_1.parseEnvNumber)(process.env.PG_POOL_KEEPALIVE_INITIAL_DELAY_MS);
168
+ if (keepAliveDelay !== undefined && keepAliveDelay !== policy.keepAliveInitialDelayMillis &&
169
+ !policy.warnedAboutKeepAlive) {
170
+ policy.warnedAboutKeepAlive = true;
171
+ log.warn(`Pool ${database} already has TCP keepalive configured with a ${policy.keepAliveInitialDelayMillis} ms delay; ignoring later delay ${keepAliveDelay} ms`);
172
+ }
173
+ }
127
174
  return cached;
175
+ }
128
176
  }
129
177
  // Route through the registered driver (default = pg.Pool over TCP). A custom
130
178
  // factory may return any QueryablePool (e.g. an in-process PGlite pool); it is
@@ -0,0 +1,27 @@
1
+ import type pg from 'pg';
2
+ /**
3
+ * Bound how long each query on `client` may wait for PostgreSQL.
4
+ *
5
+ * A live server ends a slow statement itself (statement_timeout), and the
6
+ * connection stays usable. A connection that went silent cannot: its server
7
+ * vanished without closing it, the network path drops its packets, or the
8
+ * server stopped answering. node-postgres then waits for an answer that never
9
+ * comes. The wait is forever when the query was already acknowledged, and
10
+ * about 15 minutes of TCP retransmission otherwise, and every caller that
11
+ * later checks the client out of the pool waits behind it.
12
+ *
13
+ * node-postgres' own `query_timeout` is not enough: it fails the query but
14
+ * keeps the connection, so the caller's next query on it (a ROLLBACK, or the
15
+ * next request once the client is back in the pool) queues behind the
16
+ * unanswered one. When this deadline passes, the socket is destroyed instead,
17
+ * as pg-pool does when connecting takes too long: the unanswered query and
18
+ * every query queued behind it fail at once, and the pool discards the client
19
+ * when it is released. A query that fails on the caller's own `query_timeout`
20
+ * closes its connection the same way.
21
+ *
22
+ * Submittable queries (cursors, streams, COPY) are left alone: they can
23
+ * legitimately wait on whoever consumes them.
24
+ */
25
+ export declare const applyQueryDeadline: (client: pg.ClientBase, getTimeoutMillis: () => number, onConnectionError: (error: Error & {
26
+ code?: string;
27
+ }) => void, onTimeout?: (timeoutMillis: number) => void) => void;
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.applyQueryDeadline = void 0;
4
+ /** Node's largest timer delay; `setTimeout` treats anything longer as 1 ms. */
5
+ const MAX_TIMER_DELAY = 2_147_483_647;
6
+ /** What node-postgres rejects a query with when its own `query_timeout` passes. */
7
+ const PG_LOCAL_READ_TIMEOUT = 'Query read timeout';
8
+ /**
9
+ * Bound how long each query on `client` may wait for PostgreSQL.
10
+ *
11
+ * A live server ends a slow statement itself (statement_timeout), and the
12
+ * connection stays usable. A connection that went silent cannot: its server
13
+ * vanished without closing it, the network path drops its packets, or the
14
+ * server stopped answering. node-postgres then waits for an answer that never
15
+ * comes. The wait is forever when the query was already acknowledged, and
16
+ * about 15 minutes of TCP retransmission otherwise, and every caller that
17
+ * later checks the client out of the pool waits behind it.
18
+ *
19
+ * node-postgres' own `query_timeout` is not enough: it fails the query but
20
+ * keeps the connection, so the caller's next query on it (a ROLLBACK, or the
21
+ * next request once the client is back in the pool) queues behind the
22
+ * unanswered one. When this deadline passes, the socket is destroyed instead,
23
+ * as pg-pool does when connecting takes too long: the unanswered query and
24
+ * every query queued behind it fail at once, and the pool discards the client
25
+ * when it is released. A query that fails on the caller's own `query_timeout`
26
+ * closes its connection the same way.
27
+ *
28
+ * Submittable queries (cursors, streams, COPY) are left alone: they can
29
+ * legitimately wait on whoever consumes them.
30
+ */
31
+ const applyQueryDeadline = (client, getTimeoutMillis, onConnectionError, onTimeout) => {
32
+ let connectionError;
33
+ client.on('error', (error) => {
34
+ connectionError ??= error;
35
+ onConnectionError(error);
36
+ });
37
+ const query = client.query;
38
+ const destroy = (error) => {
39
+ client
40
+ .connection.stream.destroy(error);
41
+ };
42
+ const expire = (timeoutMillis) => {
43
+ const error = Object.assign(new Error(`Query read timeout: PostgreSQL did not answer within ${timeoutMillis} ms; the connection was closed`),
44
+ // The same code a dead socket reports when TCP gives up on it.
45
+ { code: 'ETIMEDOUT' });
46
+ onTimeout?.(timeoutMillis);
47
+ destroy(error);
48
+ };
49
+ function boundedQuery(config, values, callback) {
50
+ if (config == null || typeof config.submit === 'function') {
51
+ return query.call(this, config, values, callback);
52
+ }
53
+ const timeoutMillis = getTimeoutMillis();
54
+ const enabled = Number.isFinite(timeoutMillis) && timeoutMillis > 0;
55
+ const timer = enabled
56
+ ? setTimeout(expire, Math.min(timeoutMillis, MAX_TIMER_DELAY), timeoutMillis)
57
+ : undefined;
58
+ // The open socket keeps the process alive while a query is pending; the
59
+ // timer alone must not (a client may be unref()ed).
60
+ timer?.unref();
61
+ const settle = (err) => {
62
+ clearTimeout(timer);
63
+ // A caller's own `query_timeout` fails the query but leaves it unanswered
64
+ // on the connection, exactly what this deadline exists to clear.
65
+ if (!(err instanceof Error))
66
+ return;
67
+ if (enabled && err.message === PG_LOCAL_READ_TIMEOUT)
68
+ destroy(err);
69
+ if (err.severity === 'FATAL')
70
+ connectionError ??= err;
71
+ // A failed ROLLBACK can replace the original connection error with a
72
+ // generic failure on the unusable client.
73
+ if (connectionError && connectionError !== err)
74
+ err.cause ??= connectionError;
75
+ };
76
+ const settling = (cb) => (err, result) => {
77
+ settle(err);
78
+ cb(err, result);
79
+ };
80
+ let result;
81
+ try {
82
+ if (typeof values === 'function') {
83
+ return query.call(this, config, settling(values));
84
+ }
85
+ if (typeof callback === 'function') {
86
+ return query.call(this, config, values, settling(callback));
87
+ }
88
+ const ownCallback = config.callback;
89
+ if (typeof ownCallback === 'function') {
90
+ return query.call(this, { ...config, callback: settling(ownCallback) }, values);
91
+ }
92
+ result = query.call(this, config, values);
93
+ }
94
+ catch (error) {
95
+ // Nothing was sent; the timer must not outlive this call.
96
+ settle();
97
+ throw error;
98
+ }
99
+ if (result && typeof result.then === 'function') {
100
+ result.then(() => settle(), settle);
101
+ }
102
+ else {
103
+ // No way to observe completion: never risk closing a healthy connection.
104
+ settle();
105
+ }
106
+ return result;
107
+ }
108
+ client.query = boundedQuery;
109
+ };
110
+ exports.applyQueryDeadline = applyQueryDeadline;