diff --git a/apps/api/src/realtime.ts b/apps/api/src/realtime.ts index 07bb522..a42d177 100644 --- a/apps/api/src/realtime.ts +++ b/apps/api/src/realtime.ts @@ -93,7 +93,14 @@ export function attachRealtime( deps: { db: Db; sessions: SessionService; databaseUrl: string; corsOrigins: string[]; onError?: (err: unknown) => void }, ): Broadcaster { const onError = deps.onError ?? (() => {}); + let closed = false; const pool = new pg.Pool({ connectionString: deps.databaseUrl, max: 2 }); + // An idle pooled client killed by Postgres (restart, pg_terminate_backend, error 57P01) surfaces as an + // 'error' event on the pool itself; without a listener Node throws and crashes the process (BIT-32447). + pool.on("error", (err) => { + if (closed || isPoolEndedError(err)) return; + onError(err); + }); const io = new Server(server, { path: "/v1/realtime", transports: ["websocket"], @@ -114,7 +121,6 @@ export function attachRealtime( // A dedicated connection listens; it reconnects if Postgres restarts. let listener: pg.Client | undefined; - let closed = false; let retry: NodeJS.Timeout | undefined; const pending = new Set>(); const listen = async () => { @@ -183,6 +189,11 @@ export function attachRealtime( export function createRemoteBroadcaster(databaseUrl: string, onError: (err: unknown) => void = () => {}): Broadcaster { const pool = new pg.Pool({ connectionString: databaseUrl, max: 1 }); let closed = false; + // Same guard as attachRealtime: an idle client killed by Postgres (57P01) must not crash the worker (BIT-32447). + pool.on("error", (err) => { + if (closed || isPoolEndedError(err)) return; + onError(err); + }); const pending = new Set>(); const desk = (userId: string, command: DeskCommand) => { if (closed) return; diff --git a/apps/api/test/realtime.test.ts b/apps/api/test/realtime.test.ts index ab3258c..1407ea9 100644 --- a/apps/api/test/realtime.test.ts +++ b/apps/api/test/realtime.test.ts @@ -1,5 +1,6 @@ import { LIBRARY_CHANNEL, type LibraryMessage } from "@photoreport/contracts"; import type { AddressInfo } from "node:net"; +import pg from "pg"; import { io, type Socket } from "socket.io-client"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { buildApp } from "../src/app.js"; @@ -75,4 +76,47 @@ describe("realtime", () => { await worker.close(); expect(errors.filter((e) => e instanceof Error && /pool after calling end/i.test(e.message))).toEqual([]); }); + + it("does not crash when Postgres terminates an idle pooled connection (BIT-32447)", async () => { + const errors: unknown[] = []; + const worker = createRemoteBroadcaster(ctx.config.DATABASE_URL, (err) => errors.push(err)); + const message: LibraryMessage = { + type: "photo.updated", + ids: ["3f2a9c1e-5b7d-4e8a-9c21-7d4e5f6a8b90"], + patch: { flag: "PICK" }, + }; + // Establish the pool's single connection by publishing once. + worker.library("00000000-0000-0000-8000-000000000002", message); + // Give the NOTIFY query a moment to complete so the client returns idle to the pool. + await new Promise((r) => setTimeout(r, 200)); + + // An uncaughtException here would fail the test. + const uncaught: unknown[] = []; + const onUncaught = (err: unknown) => uncaught.push(err); + process.once("uncaughtException", onUncaught); + + try { + // Find the pool's idle backend and terminate it, simulating an admin command (error 57P01). + const admin = new pg.Client({ connectionString: ctx.config.DATABASE_URL }); + await admin.connect(); + const db = await admin.query<{ pid: number }>( + `SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND state = 'idle' AND pid <> pg_backend_pid()`, + ); + for (const { pid } of db.rows) await admin.query(`SELECT pg_terminate_backend($1)`, [pid]); + await admin.end(); + + // The pool emits 'error' for the killed client; wait for it to reach onError. + await new Promise((r) => setTimeout(r, 500)); + expect(uncaught).toEqual([]); + expect(errors.some((e) => e instanceof Error && /terminating connection/i.test(e.message))).toBe(true); + + // The pool must recover and publish again on a fresh connection without throwing. + worker.library("00000000-0000-0000-8000-000000000003", message); + await new Promise((r) => setTimeout(r, 300)); + expect(uncaught).toEqual([]); + } finally { + process.removeListener("uncaughtException", onUncaught); + await worker.close(); + } + }); });