Files
photoreport/apps/api/src/realtime.ts
bug-squasher 1c2f813533
ci / typescript (pull_request) Failing after 7s
ci / rust (pull_request) Successful in 7m7s
fix(api): ignore realtime publish after pg pool end
Worker/API shutdown raced fire-and-forget NOTIFY queries, surfacing
"Cannot use a pool after calling end on the pool" (ERRSIG 5282eca99746).

Paperclip-Agent: Bug Squasher (urlKey bug-squasher; id 4669adc7-6368-43ef-bf27-5a601a6b7b83)
Paperclip-Issue: BIT-31177
Paperclip-Run: a5628443-aab8-4d4b-b0c5-089598292667
2026-10-14 23:29:52 +01:00

172 lines
6.1 KiB
TypeScript

import { LIBRARY_CHANNEL, type LibraryMessage, roomForOrg, roomForUser } from "@photoreport/contracts";
import type { Server as HttpServer } from "node:http";
import pg from "pg";
import { Server } from "socket.io";
import type { SessionService } from "./auth/sessions.js";
import type { Db } from "./db.js";
/** Anything that can push library messages to the people of an organization. */
export interface Broadcaster {
library(organizationId: string, message: LibraryMessage): void;
close(): Promise<void>;
}
export const silentBroadcaster: Broadcaster = { library: () => {}, close: async () => {} };
/** Records messages; used by tests. */
export class MemoryBroadcaster implements Broadcaster {
readonly sent: { organizationId: string; message: LibraryMessage }[] = [];
library(organizationId: string, message: LibraryMessage): void {
this.sent.push({ organizationId, message });
}
async close(): Promise<void> {}
}
/**
* Fan-out between processes goes through Postgres LISTEN/NOTIFY on one channel: every API process listens and
* delivers to its own sockets, the ingest worker only publishes. No Redis, no sticky sessions.
*/
const PG_CHANNEL = "photoreport_realtime";
/** NOTIFY payloads are limited to 8000 bytes; batch updates are split so each message fits. */
const IDS_PER_MESSAGE = 100;
interface Envelope {
organizationId: string;
message: LibraryMessage;
}
function split(message: LibraryMessage): LibraryMessage[] {
if (message.type !== "photo.updated" || message.ids.length <= IDS_PER_MESSAGE) return [message];
const parts: LibraryMessage[] = [];
for (let i = 0; i < message.ids.length; i += IDS_PER_MESSAGE) parts.push({ ...message, ids: message.ids.slice(i, i + IDS_PER_MESSAGE) });
return parts;
}
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 };
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.
*/
export function attachRealtime(
server: HttpServer,
deps: { db: Db; sessions: SessionService; databaseUrl: string; corsOrigins: string[]; onError?: (err: unknown) => void },
): Broadcaster {
const onError = deps.onError ?? (() => {});
const pool = new pg.Pool({ connectionString: deps.databaseUrl, max: 2 });
const io = new Server(server, {
path: "/v1/realtime",
transports: ["websocket"],
cors: { origin: deps.corsOrigins, credentials: true },
});
io.use(async (socket, next) => {
try {
const token = typeof socket.handshake.auth?.token === "string" ? socket.handshake.auth.token : "";
const auth = await deps.sessions.verifyAccessToken(token);
const memberships = await deps.db.membership.findMany({ where: { userId: auth.userId }, select: { organizationId: true } });
await socket.join([roomForUser(auth.userId), ...memberships.map((m) => roomForOrg(m.organizationId))]);
next();
} catch {
next(new Error("unauthorized"));
}
});
// 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<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;
try {
const { organizationId, message } = JSON.parse(n.payload) as Envelope;
io.to(roomForOrg(organizationId)).emit(LIBRARY_CHANNEL, message);
} catch (err) {
onError(err);
}
});
client.on("error", (err) => {
onError(err);
client.end().catch(() => {});
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;
};
const ready = listen().catch((err) => {
onError(err);
if (!closed) retry = setTimeout(() => void listen().catch(onError), 1000);
});
return {
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();
},
};
}
/** 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, () => closed, trackPending(pending)),
close: async () => {
if (closed) return;
closed = true;
await Promise.allSettled([...pending]);
await pool.end();
},
};
}