@steve31415/baselib 3.66.0 → 3.67.0

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.
Files changed (3) hide show
  1. package/dist/db.d.ts +26 -5
  2. package/dist/db.js +39 -5
  3. package/package.json +1 -1
package/dist/db.d.ts CHANGED
@@ -49,8 +49,8 @@ export interface PoolOptions {
49
49
  /** Receives idle-client errors (see logPoolErrors). Without one they go to
50
50
  * stderr — on the Cloud Logging backstop, but not in Axiom. */
51
51
  logger?: Logger;
52
- /** Tuning for `probeIdleCheckouts` (defaults IDLE_PROBE_AFTER_MS and
53
- * IDLE_PROBE_TIMEOUT_MS); tests shorten them. */
52
+ /** Tuning for `probeIdleCheckouts` (defaults IDLE_PROBE_AFTER_MS,
53
+ * IDLE_PROBE_TIMEOUT_MS and LOSS_PROBE_WINDOW_MS); tests shorten them. */
54
54
  idleProbe?: IdleProbeOptions;
55
55
  }
56
56
  /** Why a fleet-wide statement timeout (mirror, 2026-09-08): a transaction an
@@ -117,6 +117,18 @@ export declare const IDLE_PROBE_AFTER_MS = 10000;
117
117
  /** How long the probe waits. A healthy `select 1` takes a millisecond or
118
118
  * two; a half-open socket would otherwise wait for TCP to give up. */
119
119
  export declare const IDLE_PROBE_TIMEOUT_MS = 3000;
120
+ /** After a pool loses a connection, every reused client is probed for this
121
+ * long, however briefly it sat idle. A connection cut rarely kills one
122
+ * socket: since 2026-11-13 Cloud Run cuts all of an instance's connections
123
+ * on the instance's side (12-hour instance cuts, the twice-daily windows;
124
+ * KNOWN_LOG_PATTERNS fleet entry "database pool: idle client error"), and
125
+ * each pooled socket learns of it only when next written to. Without this,
126
+ * every checkout in the first seconds after a cut could draw a dead
127
+ * sibling (mirror 2026-11-17 10:17Z: four job workers in 180 ms; chime's
128
+ * LISTEN bridge, its reconnect and its retry). 30 s covers the pile-up
129
+ * seen (all within 10 s of the first loss) with room; each loss restarts
130
+ * it, and it costs one `select 1` per checkout only inside it. */
131
+ export declare const LOSS_PROBE_WINDOW_MS = 30000;
120
132
  /** Keep a pg connection's death from killing the process, and log every
121
133
  * way a pool loses or fails to get a connection as one WARN family:
122
134
  * `kind=db-connection-loss`, `meta.phase`:
@@ -165,9 +177,14 @@ export declare function logPoolErrors(pool: pg.Pool, logger?: Logger, options?:
165
177
  export interface IdleProbeOptions {
166
178
  afterIdleMs?: number;
167
179
  timeoutMs?: number;
180
+ /** How long after a connection loss every reused client is probed
181
+ * (default LOSS_PROBE_WINDOW_MS). */
182
+ afterLossMs?: number;
168
183
  }
169
184
  /** Hand out no pooled client that died while idle. A client idle for
170
- * `afterIdleMs` or more runs `select 1` (bounded by `timeoutMs`) before
185
+ * `afterIdleMs` or more, or any reused client within `afterLossMs` of the
186
+ * pool's last connection loss (a cut kills the siblings too; see
187
+ * LOSS_PROBE_WINDOW_MS), runs `select 1` (bounded by `timeoutMs`) before
171
188
  * the borrower gets it; if that fails the client is discarded, one WARN
172
189
  * (`kind=db-connection-loss`, `phase=idle`, `detectedAt=checkout`) is
173
190
  * logged, and the checkout is retried, ending at a fresh connection at
@@ -175,8 +192,12 @@ export interface IdleProbeOptions {
175
192
  * ran on the dead client. What stays unretried, as before: a connection
176
193
  * that dies after the probe, mid-statement or mid-transaction (the
177
194
  * borrower sees the error; whether a lone statement took effect is
178
- * unknowable), and a failed new connection (`phase=connect`). New clients
179
- * and recently used ones are not probed. Both connect forms are covered
195
+ * unknowable), a failed new connection (`phase=connect`), and the
196
+ * first checkout to meet a cut (nothing has been lost yet to warn of it).
197
+ * New clients, and recently used ones outside the window, are not probed;
198
+ * a probe the window caused logs `sinceLossMs` on its WARN. Losses are
199
+ * seen through `logPoolErrors` (idle and checked-out) and this probe
200
+ * itself, so a hand-built pool needs both to get the full window. Both connect forms are covered
180
201
  * (`pool.query` checks out in callback form). `createPool` attaches this;
181
202
  * exported for a pool an app built itself. Idempotent per pool. */
182
203
  export declare function probeIdleCheckouts(pool: pg.Pool, logger?: Logger, options?: IdleProbeOptions): void;
package/dist/db.js CHANGED
@@ -125,6 +125,18 @@ export const IDLE_PROBE_AFTER_MS = 10_000;
125
125
  * two; a half-open socket would otherwise wait for TCP to give up. */
126
126
  export const IDLE_PROBE_TIMEOUT_MS = 3_000;
127
127
  const IDLE_PROBE_SQL = 'select 1 /* baselib idle probe */';
128
+ /** After a pool loses a connection, every reused client is probed for this
129
+ * long, however briefly it sat idle. A connection cut rarely kills one
130
+ * socket: since 2026-11-13 Cloud Run cuts all of an instance's connections
131
+ * on the instance's side (12-hour instance cuts, the twice-daily windows;
132
+ * KNOWN_LOG_PATTERNS fleet entry "database pool: idle client error"), and
133
+ * each pooled socket learns of it only when next written to. Without this,
134
+ * every checkout in the first seconds after a cut could draw a dead
135
+ * sibling (mirror 2026-11-17 10:17Z: four job workers in 180 ms; chime's
136
+ * LISTEN bridge, its reconnect and its retry). 30 s covers the pile-up
137
+ * seen (all within 10 s of the first loss) with room; each loss restarts
138
+ * it, and it costs one `select 1` per checkout only inside it. */
139
+ export const LOSS_PROBE_WINDOW_MS = 30_000;
128
140
  const CONNECTION_LOSS_KIND = 'db-connection-loss';
129
141
  const ACQUIRE_FAILED_MESSAGE = {
130
142
  connect: 'database pool: new connection failed',
@@ -147,10 +159,17 @@ const instrumented = new WeakSet();
147
159
  // Clients under an idle probe: their death is reported once, by the probe,
148
160
  // as an idle loss rather than a checked-out one.
149
161
  const probing = new WeakSet();
162
+ // When each pool last lost a client's connection (an idle error, a
163
+ // checked-out loss, a probe finding one dead): `probeIdleCheckouts` probes
164
+ // every reused client for LOSS_PROBE_WINDOW_MS after it.
165
+ const lastLossAt = new WeakMap();
150
166
  /** One `kind=db-connection-loss` WARN, the shape every pool loss shares. */
151
167
  function connectionLossWarner(pool, logger, credentialExpiry) {
152
168
  const log = logger?.with({ kind: CONNECTION_LOSS_KIND });
153
169
  return (phase, message, err, since, extra = {}) => {
170
+ // A failed connect or a starved wait loses no existing connection.
171
+ if (phase === 'idle' || phase === 'checked-out')
172
+ lastLossAt.set(pool, Date.now());
154
173
  const expiry = credentialExpiry?.();
155
174
  const meta = {
156
175
  phase,
@@ -391,7 +410,9 @@ function timeNewConnections(pool, logger, options) {
391
410
  }
392
411
  const probed = new WeakSet();
393
412
  /** Hand out no pooled client that died while idle. A client idle for
394
- * `afterIdleMs` or more runs `select 1` (bounded by `timeoutMs`) before
413
+ * `afterIdleMs` or more, or any reused client within `afterLossMs` of the
414
+ * pool's last connection loss (a cut kills the siblings too; see
415
+ * LOSS_PROBE_WINDOW_MS), runs `select 1` (bounded by `timeoutMs`) before
395
416
  * the borrower gets it; if that fails the client is discarded, one WARN
396
417
  * (`kind=db-connection-loss`, `phase=idle`, `detectedAt=checkout`) is
397
418
  * logged, and the checkout is retried, ending at a fresh connection at
@@ -399,8 +420,12 @@ const probed = new WeakSet();
399
420
  * ran on the dead client. What stays unretried, as before: a connection
400
421
  * that dies after the probe, mid-statement or mid-transaction (the
401
422
  * borrower sees the error; whether a lone statement took effect is
402
- * unknowable), and a failed new connection (`phase=connect`). New clients
403
- * and recently used ones are not probed. Both connect forms are covered
423
+ * unknowable), a failed new connection (`phase=connect`), and the
424
+ * first checkout to meet a cut (nothing has been lost yet to warn of it).
425
+ * New clients, and recently used ones outside the window, are not probed;
426
+ * a probe the window caused logs `sinceLossMs` on its WARN. Losses are
427
+ * seen through `logPoolErrors` (idle and checked-out) and this probe
428
+ * itself, so a hand-built pool needs both to get the full window. Both connect forms are covered
404
429
  * (`pool.query` checks out in callback form). `createPool` attaches this;
405
430
  * exported for a pool an app built itself. Idempotent per pool. */
406
431
  export function probeIdleCheckouts(pool, logger, options = {}) {
@@ -409,6 +434,7 @@ export function probeIdleCheckouts(pool, logger, options = {}) {
409
434
  probed.add(pool);
410
435
  const afterIdleMs = options.afterIdleMs ?? IDLE_PROBE_AFTER_MS;
411
436
  const timeoutMs = options.timeoutMs ?? IDLE_PROBE_TIMEOUT_MS;
437
+ const afterLossMs = options.afterLossMs ?? LOSS_PROBE_WINDOW_MS;
412
438
  const releasedAt = new WeakMap();
413
439
  pool.on('release', (_err, client) => releasedAt.set(client, Date.now()));
414
440
  const warn = connectionLossWarner(pool, logger);
@@ -419,7 +445,12 @@ export function probeIdleCheckouts(pool, logger, options = {}) {
419
445
  for (;;) {
420
446
  const client = await connect();
421
447
  const idleSince = releasedAt.get(client);
422
- if (idleSince === undefined || Date.now() - idleSince < afterIdleMs)
448
+ if (idleSince === undefined)
449
+ return client;
450
+ const now = Date.now();
451
+ const lossAt = lastLossAt.get(pool);
452
+ const sinceLossMs = lossAt === undefined || now - lossAt >= afterLossMs ? undefined : now - lossAt;
453
+ if (now - idleSince < afterIdleMs && sinceLossMs === undefined)
423
454
  return client;
424
455
  probing.add(client);
425
456
  // The death also arrives as a client 'error', possibly after the
@@ -444,7 +475,10 @@ export function probeIdleCheckouts(pool, logger, options = {}) {
444
475
  }
445
476
  catch (err) {
446
477
  const error = err instanceof Error ? err : new Error(String(err));
447
- warn('idle', 'database pool: idle client found dead at checkout; replaced', error, idleSince, { detectedAt: 'checkout' });
478
+ warn('idle', 'database pool: idle client found dead at checkout; replaced', error, idleSince, {
479
+ detectedAt: 'checkout',
480
+ ...(now - idleSince < afterIdleMs ? { sinceLossMs } : {}),
481
+ });
448
482
  client.release(error);
449
483
  }
450
484
  finally {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@steve31415/baselib",
3
- "version": "3.66.0",
3
+ "version": "3.67.0",
4
4
  "description": "Plasticine new-world shared platform library: logging, auth, service-to-service auth, db, HTTP, sync, app updates",
5
5
  "type": "module",
6
6
  "license": "MIT",