fix(api): ignore realtime publish after pg pool end (BIT-31177) #1

Merged
spark merged 1 commits from fix/BIT-31177-pg-pool-after-end into main 2026-10-14 23:30:14 +01:00
2 changed files with 57 additions and 4 deletions

No files matched your search

+42 -4
View File
@@ -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<unknown>) => 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<Promise<unknown>>) {
return (p: Promise<unknown>) => {
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<Promise<unknown>>();
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<Promise<unknown>>();
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();
},
};
+15
View File
@@ -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([]);
});
});