// Replacements for Postgres LISTEN/NOTIFY, all measured the same way: the consumer is // woken up somehow, then reads new events after its cursor from the database. // pg — LISTEN/NOTIFY (today's Peppa) // poll:N — select events where id > cursor every N ms // fswatch — fs.watch on the -wal file (+5 s safety poll) // push — the writer (or a tiny hub) pushes event ids over a unix socket import { watch } from "node:fs"; import { request } from "node:http"; import type { Db } from "./db.ts"; import { httpUnix } from "./db.ts"; export const CHANNEL = "peppa_events"; /** Called by event producers after commit. */ export async function publish(db: Db, mode: string, eventId: number, env = process.env) { if (mode === "pg") await db.pg.unsafe(`select pg_notify('${CHANNEL}', $1)`, [JSON.stringify({ type: "progress", eventId })]); else if (mode === "push" && env.BENCH_BACKEND !== "writer") await httpUnix(env.BENCH_HUB_SOCK!, "/publish", { ids: [eventId] }).catch(() => {}); // writer backend publishes itself after commit; poll/fswatch need nothing. } /** Subscribes `wake` to new events; returns a stop function. */ export function subscribe(db: Db, mode: string, wake: () => void, env = process.env): () => void { if (mode === "pg") { let l: any; db.pg.listen(CHANNEL, () => wake()).then((x: any) => (l = x)); return () => l?.unlisten(); } if (mode.startsWith("poll:")) { const t = setInterval(wake, Number(mode.slice(5))); return () => clearInterval(t); } if (mode === "fswatch") { const w = watch(env.BENCH_DB! + "-wal", () => wake()); const t = setInterval(wake, 5000); return () => (w.close(), clearInterval(t)); } if (mode === "push") { const sock = env.BENCH_BACKEND === "writer" ? env.BENCH_WRITER_SOCK! : env.BENCH_HUB_SOCK!; const req = request({ socketPath: sock, path: "/subscribe", method: "GET" }, (res) => { res.setEncoding("utf8"); res.on("data", () => wake()); }); req.on("error", () => {}); req.end(); const t = setInterval(wake, 5000); return () => (req.destroy(), clearInterval(t)); } throw new Error(`unknown notify mode ${mode}`); }