peppa/bench/sqlite/lib/db.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

173 lines
6.2 KiB
TypeScript

// Uniform async DB access for the benchmark: bun:sqlite, node:sqlite, better-sqlite3,
// Postgres (postgres.js) and a "writer" client that sends writes to one writer process.
// SQL is written in SQLite dialect with `?` params; the Postgres adapter renumbers them.
import { request } from "node:http";
export type Stmt = [sql: string, params?: unknown[]];
export type Row = Record<string, unknown>;
export interface Db {
all(sql: string, params?: unknown[]): Promise<Row[]>;
/** Runs statements in one write transaction; returns each statement's rows. */
tx(stmts: Stmt[]): Promise<Row[][]>;
/** SQLITE_BUSY retries made by the last tx (0 for Postgres/writer). */
lastBusy: number;
close(): Promise<void>;
/** Postgres only: raw client for LISTEN/NOTIFY. */
pg?: any;
}
export type Backend = "bun" | "node" | "better" | "pg" | "writer";
export const BUSY_TIMEOUT_MS = Number(process.env.BENCH_BUSY_TIMEOUT_MS ?? 5000);
// busy_timeout must come first: with 20 hook processes opening the file at once, any
// statement before it (even journal_mode) can fail at once with SQLITE_BUSY_RECOVERY.
// journal_mode=WAL is persistent, so it is set once when the file is created (run.ts).
const PRAGMAS = [
`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`,
"PRAGMA synchronous = NORMAL",
"PRAGMA foreign_keys = ON",
];
function isBusy(e: unknown) {
const s = String((e as any)?.code ?? "") + " " + String((e as any)?.message ?? e);
return /SQLITE_BUSY|database is locked/i.test(s);
}
/** Wraps a synchronous SQLite driver: BEGIN IMMEDIATE + retry on SQLITE_BUSY. */
function syncSqlite(exec: (sql: string) => void, all: (sql: string, p: unknown[]) => Row[], close: () => void): Db {
const db: Db = {
lastBusy: 0,
async all(sql, params = []) {
return all(sql, params);
},
async tx(stmts) {
db.lastBusy = 0;
for (;;) {
try {
exec("BEGIN IMMEDIATE");
try {
const out = stmts.map(([s, p]) => all(s, p ?? []));
exec("COMMIT");
return out;
} catch (e) {
try { exec("ROLLBACK"); } catch {}
throw e;
}
} catch (e) {
// busy_timeout already waited BUSY_TIMEOUT_MS; count it and give up after 3.
if (!isBusy(e) || ++db.lastBusy >= 3) throw e;
}
}
},
async close() {
close();
},
};
return db;
}
export async function openSqlite(kind: "bun" | "node" | "better", path: string, readonly = false): Promise<Db> {
if (kind === "bun") {
const { Database } = await import("bun:sqlite" as string);
const d = new Database(path, readonly ? { readonly: true } : { create: true });
for (const p of PRAGMAS) d.exec(p);
return syncSqlite((s) => d.exec(s), (s, p) => d.query(s).all(...p), () => d.close());
}
if (kind === "node") {
const { DatabaseSync } = await import("node:sqlite");
const d = new DatabaseSync(path, { readOnly: readonly });
for (const p of PRAGMAS) d.exec(p);
const cache = new Map<string, any>();
const prep = (s: string) => cache.get(s) ?? (cache.set(s, d.prepare(s)), cache.get(s));
return syncSqlite((s) => d.exec(s), (s, p) => prep(s).all(...(p as any[])) as Row[], () => d.close());
}
const { default: Better } = await import("better-sqlite3");
const d = new Better(path, { readonly });
for (const p of PRAGMAS) d.exec(p);
const cache = new Map<string, any>();
const prep = (s: string) => cache.get(s) ?? (cache.set(s, d.prepare(s)), cache.get(s));
return syncSqlite(
(s) => d.exec(s),
(s, p) => {
const st = prep(s);
return st.reader ? st.all(...p) : (st.run(...p), []);
},
() => d.close(),
);
}
const toPg = (s: string) => {
let i = 0;
return s.replace(/\?/g, () => `$${++i}`);
};
export async function openPg(url: string, max = 1): Promise<Db> {
const { default: postgres } = await import("postgres");
const sql = postgres(url, { max, onnotice: () => {} });
return {
lastBusy: 0,
pg: sql,
async all(s, p = []) {
return (await sql.unsafe(toPg(s), p as any[])) as unknown as Row[];
},
async tx(stmts) {
return (await sql.begin(async (t: any) => {
const out: Row[][] = [];
for (const [s, p] of stmts) out.push(await t.unsafe(toPg(s), p ?? []));
return out;
})) as Row[][];
},
async close() {
await sql.end({ timeout: 1 });
},
};
}
export async function httpUnix(socketPath: string, path: string, body: unknown): Promise<any> {
// Bun's fetch speaks unix sockets natively and starts much faster than node:http there.
if (typeof (globalThis as any).Bun !== "undefined") {
const r = await fetch(`http://writer${path}`, { method: "POST", body: JSON.stringify(body), unix: socketPath } as RequestInit);
const j = await r.json();
if (!r.ok) throw new Error(j?.error ?? `HTTP ${r.status}`);
return j;
}
return new Promise((resolve, reject) => {
const data = JSON.stringify(body);
const req = request(
{ socketPath, path, method: "POST", headers: { "content-type": "application/json", "content-length": Buffer.byteLength(data) } },
(res) => {
let buf = "";
res.setEncoding("utf8");
res.on("data", (c) => (buf += c));
res.on("end", () => {
const j = buf ? JSON.parse(buf) : null;
res.statusCode === 200 ? resolve(j) : reject(new Error(j?.error ?? `HTTP ${res.statusCode}`));
});
},
);
req.on("error", reject);
req.end(data);
});
}
/** Writes go to the writer process over a unix socket; reads go straight to the file (WAL readers never block). */
export async function openWriterClient(socketPath: string, dbPath: string, readKind: "bun" | "node"): Promise<Db> {
const reader = await openSqlite(readKind, dbPath, true);
return {
lastBusy: 0,
all: (s, p) => reader.all(s, p),
async tx(stmts) {
return (await httpUnix(socketPath, "/tx", { stmts })).rows;
},
close: () => reader.close(),
};
}
export async function openDb(backend: Backend, env = process.env): Promise<Db> {
if (backend === "pg") return openPg(env.BENCH_PG_URL!);
if (backend === "writer") return openWriterClient(env.BENCH_WRITER_SOCK!, env.BENCH_DB!, (env.BENCH_READ_KIND as any) ?? "bun");
return openSqlite(backend, env.BENCH_DB!);
}