peppa/bench/sqlite/lib/notify.ts
Асель 50b1d1afec PEP-36: benchmark SQLite vs Postgres and propose Bun + SQLite stack
bench/sqlite (outside the workspace): Peppa-like load with 10/20 runners,
a hook process per event, MCP, bot, web and watchdog; bun:sqlite,
node:sqlite, better-sqlite3, a single-writer service and Postgres; notify
replacements (cursor polling, fs.watch on WAL, unix-socket push); a
ceiling test; a schema port to sqlite with a data copy from Postgres and
a check of drizzle transactions.

openspec/changes/pep-36-lightweight-stack: proposal, design with the
numbers, specs (platform-storage, service-monitoring), phased tasks.
No product code changes; the move waits for the PM's decision.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 16:28:59 +05:00

50 lines
2.1 KiB
TypeScript

// 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}`);
}