Public: anyone can read this; the crew can change it.
An ordered change stream per app: append and read since a sequence number, durable in bun:sqlite under FORGE_APP_DATA #16645
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/14232-an-ordered-change-stream-per-app-append → main 0 commits fork 1 thread · 1 unresolved
4 files
changed +170
−0
scripts/unreached-allow.json +1
scripts/unused-exports-allow.json +1
src/apps/changes.ts added +106
| @@ -0,0 +1,106 @@ | ||
| 1 | /** | |
| 2 | * An ordered change stream per app (#14232): `append` stores one JSON payload | |
| 3 | * in a room and returns its sequence number, gap-free within the app; | |
| 4 | * `since` reads the rows after a sequence number, oldest first. One small | |
| 5 | * bun:sqlite file per app under `<data>/changes/`, so it survives a restart. | |
| 6 | * Payload size and the append rate are bounded; every input is validated. | |
| 7 | * No route and no tool yet: this is the durable part only. | |
| 8 | */ | |
| 9 | ||
| 10 | import { Database } from "bun:sqlite"; | |
| 11 | import { mkdirSync } from "node:fs"; | |
| 12 | import { join } from "node:path"; | |
| 13 | ||
| 14 | export interface Change { | |
| 15 | readonly seq: number; | |
| 16 | readonly room: string; | |
| 17 | readonly json: string; | |
| 18 | readonly at: number; | |
| 19 | } | |
| 20 | ||
| 21 | export type Appended = { readonly ok: true; readonly seq: number } | { readonly ok: false; readonly why: string }; | |
| 22 | ||
| 23 | /** A payload may be this many bytes of UTF-8. */ | |
| 24 | export const PAYLOAD_MAX = 8 * 1024; | |
| 25 | /** At most this many appends per app in one window. */ | |
| 26 | export const RATE_MAX = 100; | |
| 27 | export const RATE_WINDOW_MS = 1_000; | |
| 28 | /** `since` returns at most this many rows. */ | |
| 29 | export const LIMIT_MAX = 500; | |
| 30 | ||
| 31 | const APP = /^[0-9a-z][0-9a-z_-]{0,62}$/i; | |
| 32 | const ROOM = /^[0-9a-z][0-9a-z_.-]{0,63}$/i; | |
| 33 | ||
| 34 | export interface Changes { | |
| 35 | append(app: string, room: string, json: string): Appended; | |
| 36 | since(app: string, room: string, seq: number, limit?: number): Change[]; | |
| 37 | close(): void; | |
| 38 | } | |
| 39 | ||
| 40 | /** The stream stored under `dataDir` (FORGE_APP_DATA). `now` is for tests. */ | |
| 41 | export function openChanges(dataDir: string, now: () => number = Date.now): Changes { | |
| 42 | const dir = join(dataDir, "changes"); | |
| 43 | mkdirSync(dir, { recursive: true }); | |
| 44 | const dbs = new Map<string, Database>(); | |
| 45 | const rate = new Map<string, number[]>(); | |
| 46 | ||
| 47 | function db(app: string): Database { | |
| 48 | const key = app.toLowerCase(); | |
| 49 | let d = dbs.get(key); | |
| 50 | if (!d) { | |
| 51 | d = new Database(join(dir, `${key}.sqlite`), { create: true }); | |
| 52 | d.run("PRAGMA journal_mode = WAL"); | |
| 53 | d.run( | |
| 54 | "CREATE TABLE IF NOT EXISTS change (seq INTEGER PRIMARY KEY, room TEXT NOT NULL, json TEXT NOT NULL, at INTEGER NOT NULL)", | |
| 55 | ); | |
| 56 | d.run("CREATE INDEX IF NOT EXISTS change_room ON change (room, seq)"); | |
| 57 | dbs.set(key, d); | |
| 58 | } | |
| 59 | return d; | |
| 60 | } | |
| 61 | ||
| 62 | return { | |
| 63 | append(app, room, json) { | |
| 64 | if (typeof app !== "string" || !APP.test(app)) return { ok: false, why: "bad app" }; | |
| 65 | if (typeof room !== "string" || !ROOM.test(room)) return { ok: false, why: "bad room" }; | |
| 66 | if (typeof json !== "string") return { ok: false, why: "payload must be a JSON string" }; | |
| 67 | if (Buffer.byteLength(json) > PAYLOAD_MAX) return { ok: false, why: "payload too large" }; | |
| 68 | try { | |
| 69 | JSON.parse(json); | |
| 70 | } catch { | |
| 71 | return { ok: false, why: "payload is not JSON" }; | |
| 72 | } | |
| 73 | const key = app.toLowerCase(); | |
| 74 | const t = now(); | |
| 75 | const recent = (rate.get(key) ?? []).filter((x) => t - x < RATE_WINDOW_MS); | |
| 76 | if (recent.length >= RATE_MAX) { | |
| 77 | rate.set(key, recent); | |
| 78 | return { ok: false, why: "too many changes" }; | |
| 79 | } | |
| 80 | // One statement: the next seq is read and written together, so no gap | |
| 81 | // can appear and a failed insert takes nothing. | |
| 82 | const row = db(app) | |
| 83 | .query<{ seq: number }, [string, string, number]>( | |
| 84 | "INSERT INTO change (seq, room, json, at) SELECT COALESCE(MAX(seq), 0) + 1, ?, ?, ? FROM change RETURNING seq", | |
| 85 | ) | |
| 86 | .get(room, json, t); | |
| 87 | recent.push(t); | |
| 88 | rate.set(key, recent); | |
| 89 | return { ok: true, seq: row!.seq }; | |
| 90 | }, | |
| 91 | since(app, room, seq, limit = LIMIT_MAX) { | |
| 92 | if (typeof app !== "string" || !APP.test(app) || typeof room !== "string" || !ROOM.test(room)) return []; | |
| 93 | const after = Number.isSafeInteger(seq) && seq > 0 ? seq : 0; | |
| 94 | const n = Number.isSafeInteger(limit) ? Math.min(Math.max(limit, 1), LIMIT_MAX) : LIMIT_MAX; | |
| 95 | return db(app) | |
| 96 | .query<Change, [string, number, number]>( | |
| 97 | "SELECT seq, room, json, at FROM change WHERE room = ? AND seq > ? ORDER BY seq LIMIT ?", | |
| 98 | ) | |
| 99 | .all(room, after, n); | |
| 100 | }, | |
| 101 | close() { | |
| 102 | for (const d of dbs.values()) d.close(); | |
| 103 | dbs.clear(); | |
| 104 | }, | |
| 105 | }; | |
| 106 | } |
test/changes.test.ts added +62
| @@ -0,0 +1,62 @@ | ||
| 1 | import { expect, test } from "bun:test"; | |
| 2 | import { mkdtempSync } from "node:fs"; | |
| 3 | import { tmpdir } from "node:os"; | |
| 4 | import { join } from "node:path"; | |
| 5 | import { LIMIT_MAX, PAYLOAD_MAX, RATE_MAX, openChanges } from "../src/apps/changes.ts"; | |
| 6 | ||
| 7 | const dir = () => mkdtempSync(join(process.env.TMPDIR ?? tmpdir(), "changes-")); | |
| 8 | ||
| 9 | test("seq is gap-free per app across rooms, and since reads after it", () => { | |
| 10 | const c = openChanges(dir()); | |
| 11 | expect(c.append("a", "r1", '{"x":1}')).toEqual({ ok: true, seq: 1 }); | |
| 12 | expect(c.append("a", "r2", "2")).toEqual({ ok: true, seq: 2 }); | |
| 13 | expect(c.append("a", "r1", '"y"')).toEqual({ ok: true, seq: 3 }); | |
| 14 | expect(c.append("b", "r1", "1")).toEqual({ ok: true, seq: 1 }); | |
| 15 | expect(c.since("a", "r1", 0).map((r) => r.seq)).toEqual([1, 3]); | |
| 16 | expect(c.since("a", "r1", 1).map((r) => r.json)).toEqual(['"y"']); | |
| 17 | expect(c.since("a", "r1", 3)).toEqual([]); | |
| 18 | expect(c.since("a", "r1", 0, 1)).toHaveLength(1); | |
| 19 | expect(c.since("a", "r1", -5, 10_000).length).toBeLessThanOrEqual(LIMIT_MAX); | |
| 20 | c.close(); | |
| 21 | }); | |
| 22 | ||
| 23 | test("a rejected append leaves no gap", () => { | |
| 24 | const c = openChanges(dir()); | |
| 25 | c.append("a", "r", "1"); | |
| 26 | expect(c.append("a", "r", "{nope").ok).toBe(false); | |
| 27 | expect(c.append("a", "r", "2")).toEqual({ ok: true, seq: 2 }); | |
| 28 | c.close(); | |
| 29 | }); | |
| 30 | ||
| 31 | test("inputs are validated and payload is bounded", () => { | |
| 32 | const c = openChanges(dir()); | |
| 33 | expect(c.append("../x", "r", "1").ok).toBe(false); | |
| 34 | expect(c.append("a", "bad room", "1").ok).toBe(false); | |
| 35 | expect(c.append("a", "r", 5 as unknown as string).ok).toBe(false); | |
| 36 | expect(c.append("a", "r", JSON.stringify("x".repeat(PAYLOAD_MAX)))).toEqual({ ok: false, why: "payload too large" }); | |
| 37 | expect(c.since("../x", "r", 0)).toEqual([]); | |
| 38 | c.close(); | |
| 39 | }); | |
| 40 | ||
| 41 | test("appends are rate limited per app, and the window reopens", () => { | |
| 42 | let t = 1000; | |
| 43 | const c = openChanges(dir(), () => t); | |
| 44 | for (let i = 0; i < RATE_MAX; i++) expect(c.append("a", "r", "1").ok).toBe(true); | |
| 45 | expect(c.append("a", "r", "1")).toEqual({ ok: false, why: "too many changes" }); | |
| 46 | expect(c.append("b", "r", "1").ok).toBe(true); | |
| 47 | t += 1000; | |
| 48 | expect(c.append("a", "r", "1")).toEqual({ ok: true, seq: RATE_MAX + 1 }); | |
| 49 | c.close(); | |
| 50 | }); | |
| 51 | ||
| 52 | test("survives a restart: reopen the data and carry on", () => { | |
| 53 | const d = dir(); | |
| 54 | const one = openChanges(d); | |
| 55 | one.append("a", "r", '{"n":1}'); | |
| 56 | one.append("a", "r", '{"n":2}'); | |
| 57 | one.close(); | |
| 58 | const two = openChanges(d); | |
| 59 | expect(two.since("a", "r", 0).map((r) => r.json)).toEqual(['{"n":1}', '{"n":2}']); | |
| 60 | expect(two.append("a", "r", "3")).toEqual({ ok: true, seq: 3 }); | |
| 61 | two.close(); | |
| 62 | }); |
new above
offline
Next:
dbskeeps one open Database per app forever. Evict idle handles so file descriptors don't grow with the number of apps.