diff --git a/apps/api/src/realtime.ts b/apps/api/src/realtime.ts index a9ca7c5..b8d26fd 100644 --- a/apps/api/src/realtime.ts +++ b/apps/api/src/realtime.ts @@ -42,15 +42,40 @@ function split(message: LibraryMessage): LibraryMessage[] { return parts; } -function publisher(pool: pg.Pool, onError: (err: unknown) => void) { +function isPoolEndedError(err: unknown): boolean { + return err instanceof Error && /pool after calling end/i.test(err.message); +} + +/** + * Fire-and-forget NOTIFY publisher. Guards against use after close (BIT-31177): worker/API shutdown + * races in-flight library() calls and would otherwise surface "Cannot use a pool after calling end". + */ +function publisher( + pool: pg.Pool, + onError: (err: unknown) => void, + isClosed: () => boolean, + track: (p: Promise) => void, +) { return (organizationId: string, message: LibraryMessage) => { + if (isClosed()) return; for (const part of split(message)) { const payload: Envelope = { organizationId, message: part }; - pool.query("SELECT pg_notify($1, $2)", [PG_CHANNEL, JSON.stringify(payload)]).catch(onError); + const q = pool.query("SELECT pg_notify($1, $2)", [PG_CHANNEL, JSON.stringify(payload)]).catch((err) => { + if (isClosed() && isPoolEndedError(err)) return; + onError(err); + }); + track(q); } }; } +function trackPending(pending: Set>) { + return (p: Promise) => { + pending.add(p); + void p.finally(() => pending.delete(p)); + }; +} + /** * Socket.io on the API's HTTP server. Clients authenticate with their access token and join one room per * organization they belong to plus their own user room. WebSocket transport only. @@ -83,7 +108,9 @@ export function attachRealtime( let listener: pg.Client | undefined; let closed = false; let retry: NodeJS.Timeout | undefined; + const pending = new Set>(); const listen = async () => { + if (closed) return; const client = new pg.Client({ connectionString: deps.databaseUrl }); client.on("notification", (n) => { if (n.channel !== PG_CHANNEL || !n.payload) return; @@ -100,6 +127,10 @@ export function attachRealtime( if (!closed) retry = setTimeout(() => void listen().catch(onError), 1000); }); await client.connect(); + if (closed) { + await client.end().catch(() => {}); + return; + } await client.query(`LISTEN ${PG_CHANNEL}`); listener = client; }; @@ -109,13 +140,15 @@ export function attachRealtime( }); return { - library: publisher(pool, onError), + library: publisher(pool, onError, () => closed, trackPending(pending)), close: async () => { + if (closed) return; closed = true; if (retry) clearTimeout(retry); await ready; await io.close(); await listener?.end().catch(() => {}); + await Promise.allSettled([...pending]); await pool.end(); }, }; @@ -124,9 +157,14 @@ export function attachRealtime( /** For processes without sockets (the ingest worker): publishes to the API processes through Postgres. */ export function createRemoteBroadcaster(databaseUrl: string, onError: (err: unknown) => void = () => {}): Broadcaster { const pool = new pg.Pool({ connectionString: databaseUrl, max: 1 }); + let closed = false; + const pending = new Set>(); return { - library: publisher(pool, onError), + library: publisher(pool, onError, () => closed, trackPending(pending)), close: async () => { + if (closed) return; + closed = true; + await Promise.allSettled([...pending]); await pool.end(); }, }; diff --git a/apps/api/test/realtime.test.ts b/apps/api/test/realtime.test.ts index ab45755..ab3258c 100644 --- a/apps/api/test/realtime.test.ts +++ b/apps/api/test/realtime.test.ts @@ -60,4 +60,19 @@ describe("realtime", () => { } expect(leaked).toEqual([]); }); + + it("does not report pool-after-end when library() races close() (BIT-31177)", 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" }, + }; + worker.library("00000000-0000-4000-8000-000000000001", message); + await worker.close(); + worker.library("00000000-0000-4000-8000-000000000001", message); + await worker.close(); + expect(errors.filter((e) => e instanceof Error && /pool after calling end/i.test(e.message))).toEqual([]); + }); });