Public: anyone can read this; the crew can change it.
A change stream says which stream it is, so a client knows when its numbers started again #17736
Merged 18h 23m ago, live in production
sold/stream-epoch → main 0 commits
8 files
changed +87
−10
docs/features/sync.md +4 −2
| @@ -6,10 +6,12 @@ row: Ordered change stream (sync) | ||
| 6 | 6 | |
| 7 | 7 | An app declares `"sync": true` at the top level of `forge.json` and gets a per-app ordered change stream from the forge, with no dependency. A change is any JSON value (at most 8 KB) appended to a **room**; the forge numbers it, gap-free within the app, so every client reads the same order. |
| 8 | 8 | |
| 9 | - Read: `GET /api/v1/repos/:owner/:name/changes/:room?since=N` answers `{ changes: [{ seq, room, data, at }], next, here }`, oldest first, at most 500 (`limit` narrows). Send `next` as `since` after a reconnect to catch up from where you stopped. | |
| 9 | - Read: `GET /api/v1/repos/:owner/:name/changes/:room?since=N` answers `{ changes: [{ seq, room, data, at }], next, here }`, oldest first, at most 500 (`limit` narrows). Send `next` as `since` after a reconnect to catch up from where you stopped, and `epoch` with it. | |
| 10 | - `epoch` names the stream. A forge restored without it starts a new one, and its numbers start again at 1. A read whose `epoch` is another stream's answers `{ changes: [], next: 0, epoch, reset: true }`: forget what you read, keep the new `epoch`, and read from 0. | |
| 11 | - A client that sends no `epoch` is answered the same `reset` only while its `since` is past the last number. It then reads from 0 by following `next`, and sees the new stream whole, on top of what it held. Once new changes have passed its `since`, it goes on from there and does not see the earlier ones. Send `epoch`. | |
| 10 | 12 | - Append: `POST` the same path with `{ "data": <json> }` answers `201 { seq }`. Needs an `rw` token or a session. |
| 11 | 13 | - Presence: each read marks the reader present; `here` lists the usernames that touched the room in the last 30 seconds (in memory, not kept). |
| 12 | - MCP: the `changes` tool, `{ repo, room, since?, data? }`: with `data` it appends, without it reads. It is not in the short default list; `find_tool` reaches it. | |
| 14 | - MCP: the `changes` tool, `{ repo, room, since?, epoch?, data? }`: with `data` it appends, without it reads. It is not in the short default list; `find_tool` reaches it. | |
| 13 | 15 | |
| 14 | 16 | Whoever may enter the app (`canEnterApp`) may read and append. An app that has not declared `sync` answers `404 not_synced`; a room name is letters, digits, `_`, `.`, `-` (64); an append over the rate (100 a second per app) is refused `429` (`retry-after: 1`); a body or value over the size is `413`/`422`; a read-only token is `403`. Rows live in `<data>/changes/<app>.sqlite` (bun:sqlite) on the forge, so they survive a restart. Code: `src/apps/changes.ts`, `src/apps/room_presence.ts`, `src/actions/app_changes.ts`; test `test/app-changes.test.ts`. |
| 15 | 17 |
src/actions/app_changes.ts +14 −1
| @@ -24,6 +24,13 @@ export interface ChangesRead { | ||
| 24 | 24 | /** Pass this as `since` next time. */ |
| 25 | 25 | readonly next: number; |
| 26 | 26 | readonly here: readonly string[]; |
| 27 | /** Which stream this is: send it back beside `since`. */ | |
| 28 | readonly epoch: string; | |
| 29 | /** | |
| 30 | * `since` is of a stream that is no more: forget what was read and read again from `next`, 0. | |
| 31 | * Absent otherwise. | |
| 32 | */ | |
| 33 | readonly reset?: true; | |
| 27 | 34 | } |
| 28 | 35 | |
| 29 | 36 | export type ChangesResult<T> = { ok: true; value: T } | { ok: false; error: ChangesRefusal | { invalid: string } }; |
| @@ -67,13 +74,19 @@ export async function readChanges( | ||
| 67 | 74 | room: string, |
| 68 | 75 | since: number, |
| 69 | 76 | limit?: number, |
| 77 | epoch?: string, | |
| 70 | 78 | ): Promise<ChangesResult<ChangesRead>> { |
| 71 | 79 | const g = await gate(app, repo, user); |
| 72 | 80 | if (!g.ok) return g; |
| 73 | 81 | if (!isRoom(room)) return { ok: false, error: { invalid: "bad room" } }; |
| 74 | 82 | const here = presence.touch(g.value, room, user?.username ?? "guest"); |
| 83 | const now = store(app).at(g.value); | |
| 84 | // Numbers read from another stream mean nothing in this one. A client that names no epoch shows | |
| 85 | // it only while its number is past the last one here. | |
| 86 | if (since > 0 && ((epoch !== undefined && epoch !== now.epoch) || since > now.last)) | |
| 87 | return { ok: true, value: { changes: [], next: 0, here, epoch: now.epoch, reset: true } }; | |
| 75 | 88 | const rows = store(app).since(g.value, room, since, limit); |
| 76 | return { ok: true, value: { ...view(rows, since), here } }; | |
| 89 | return { ok: true, value: { ...view(rows, since), here, epoch: now.epoch } }; | |
| 77 | 90 | } |
| 78 | 91 | |
| 79 | 92 | /** Append one JSON value to a room; answers its sequence number. */ |
src/apps/changes.ts +12
| @@ -10,6 +10,7 @@ | ||
| 10 | 10 | import { Database } from "bun:sqlite"; |
| 11 | 11 | import { mkdirSync } from "node:fs"; |
| 12 | 12 | import { join } from "node:path"; |
| 13 | import { id } from "../kernel/id.ts"; | |
| 13 | 14 | |
| 14 | 15 | export interface Change { |
| 15 | 16 | readonly seq: number; |
| @@ -37,6 +38,11 @@ export const isRoom = (room: unknown): room is string => typeof room === "string | ||
| 37 | 38 | export interface Changes { |
| 38 | 39 | append(app: string, room: string, json: string): Appended; |
| 39 | 40 | since(app: string, room: string, seq: number, limit?: number): Change[]; |
| 41 | /** | |
| 42 | * Which stream this is, and its last sequence number over every room. `epoch` is made with the | |
| 43 | * file and kept in it: another one means that the numbers started again. | |
| 44 | */ | |
| 45 | at(app: string): { readonly epoch: string; readonly last: number }; | |
| 40 | 46 | close(): void; |
| 41 | 47 | } |
| 42 | 48 | |
| @@ -57,6 +63,8 @@ export function openChanges(dataDir: string, now: () => number = Date.now): Chan | ||
| 57 | 63 | "CREATE TABLE IF NOT EXISTS change (seq INTEGER PRIMARY KEY, room TEXT NOT NULL, json TEXT NOT NULL, at INTEGER NOT NULL)", |
| 58 | 64 | ); |
| 59 | 65 | d.run("CREATE INDEX IF NOT EXISTS change_room ON change (room, seq)"); |
| 66 | d.run("CREATE TABLE IF NOT EXISTS stream (one INTEGER PRIMARY KEY CHECK (one = 1), epoch TEXT NOT NULL)"); | |
| 67 | d.query("INSERT OR IGNORE INTO stream (one, epoch) VALUES (1, ?1)").run(id()); | |
| 60 | 68 | dbs.set(key, d); |
| 61 | 69 | } |
| 62 | 70 | return d; |
| @@ -101,6 +109,10 @@ export function openChanges(dataDir: string, now: () => number = Date.now): Chan | ||
| 101 | 109 | ) |
| 102 | 110 | .all(room, after, n); |
| 103 | 111 | }, |
| 112 | at(app) { | |
| 113 | if (typeof app !== "string" || !APP.test(app)) return { epoch: "", last: 0 }; | |
| 114 | return db(app).query<{ epoch: string; last: number }, []>("SELECT epoch, (SELECT COALESCE(MAX(seq), 0) FROM change) AS last FROM stream").get()!; | |
| 115 | }, | |
| 104 | 116 | close() { |
| 105 | 117 | for (const d of dbs.values()) d.close(); |
| 106 | 118 | dbs.clear(); |
src/contract/openapi/routes/getApiV1ReposOwnerNameChangesRoom.ts +1 −1
| @@ -4,7 +4,7 @@ export const route: Route = { | ||
| 4 | 4 | method: "get", |
| 5 | 5 | path: `${REPO}/changes/{room}`, |
| 6 | 6 | summary: "Read an app's change stream after an offset", |
| 7 | detail: "Read a room of the app's ordered change stream after `since` (403 you may not enter the app, 422 a bad room); answers { changes, next, here }; the app declares sync in forge.json", | |
| 7 | detail: "Read a room of the app's ordered change stream after `since` (403 you may not enter the app, 422 a bad room); answers { changes, next, here, epoch }, and { reset: true, next: 0 } when `epoch` or `since` is of another stream; the app declares sync in forge.json", | |
| 8 | 8 | auth: true, |
| 9 | 9 | role: "member", |
| 10 | 10 | refusals: { |
src/http/api/app_changes.ts +1 −1
| @@ -31,7 +31,7 @@ export function appChangesRoutes(router: Router<Handler>): void { | ||
| 31 | 31 | if (!repo) return notFound(); |
| 32 | 32 | const url = new URL(ctx.request.url); |
| 33 | 33 | const limit = url.searchParams.get("limit"); |
| 34 | const out = await readChanges(ctx.app, repo, ctx.auth.user, room(ctx), whole(url.searchParams.get("since")), limit === null ? undefined : whole(limit)); | |
| 34 | const out = await readChanges(ctx.app, repo, ctx.auth.user, room(ctx), whole(url.searchParams.get("since")), limit === null ? undefined : whole(limit), url.searchParams.get("epoch") ?? undefined); | |
| 35 | 35 | return out.ok ? json(out.value, 200, { "cache-control": "no-store" }) : refusal(out.error); |
| 36 | 36 | }); |
| 37 | 37 | router.add("POST", "/api/v1/repos/:owner/:name/changes/:room", async (ctx) => { |
src/http/mcp/tools/changes.ts +5 −2
| @@ -3,7 +3,7 @@ import { bad, good, isAnswer, REPO_ARG, repoArg, type Tool } from "../shared.ts" | ||
| 3 | 3 | |
| 4 | 4 | export const tool: Tool = { |
| 5 | 5 | name: "changes", |
| 6 | doc: "`{ repo, room, since?, data? }` as `GET`/`POST …/changes/:room` (forge.json `sync`): `data` (JSON) appends: `{ seq }`; else reads `{ changes, next, here }` after `since`", | |
| 6 | doc: "`{ repo, room, since?, epoch?, data? }` as `GET`/`POST …/changes/:room` (forge.json `sync`): `data` (JSON) appends: `{ seq }`; else reads `{ changes, next, here, epoch, reset? }` after `since`", | |
| 7 | 7 | description: "An app's ordered change stream: read a room after an offset, or append to it.", |
| 8 | 8 | inputSchema: { |
| 9 | 9 | type: "object", |
| @@ -11,6 +11,7 @@ export const tool: Tool = { | ||
| 11 | 11 | repo: REPO_ARG, |
| 12 | 12 | room: { type: "string" }, |
| 13 | 13 | since: { type: "integer", minimum: 0 }, |
| 14 | epoch: { type: "string" }, | |
| 14 | 15 | data: {}, |
| 15 | 16 | }, |
| 16 | 17 | required: ["repo", "room"], |
| @@ -25,9 +26,11 @@ export const tool: Tool = { | ||
| 25 | 26 | if (typeof room !== "string") return bad("invalid", "`room` is text"); |
| 26 | 27 | const since = args["since"] ?? 0; |
| 27 | 28 | if (typeof since !== "number" || !Number.isInteger(since) || since < 0) return bad("invalid", "`since` is a whole number from 0"); |
| 29 | const epoch = args["epoch"]; | |
| 30 | if (epoch !== undefined && typeof epoch !== "string") return bad("invalid", "`epoch` is the text a read answered"); | |
| 28 | 31 | const out = |
| 29 | 32 | args["data"] === undefined |
| 30 | ? await readChanges(ctx.app, repo, user, room, since) | |
| 33 | ? await readChanges(ctx.app, repo, user, room, since, undefined, epoch) | |
| 31 | 34 | : await appendChange(ctx.app, repo, user, room, JSON.stringify(args["data"])); |
| 32 | 35 | if (out.ok) return good(out.value); |
| 33 | 36 | if (typeof out.error === "object" && out.error.invalid === "too many changes") return bad("rate_limited", "too many changes in a second; try again shortly"); |
src/tui/screens/app_changes.ts +2 −1
| @@ -51,8 +51,9 @@ export function changesScreen(f: Session, ctx: Ctx, repo: Repo, firstRoom: strin | ||
| 51 | 51 | runAsync(ctx, async () => { |
| 52 | 52 | const done = await readChanges(f.app, repo, f.user, room, 0, 100); |
| 53 | 53 | if (done.ok) { |
| 54 | const again = got !== undefined && got.epoch !== done.value.epoch ? "This stream started again. " : ""; | |
| 54 | 55 | got = done.value; |
| 55 | note = `${got.changes.length} in ${room}; here: ${got.here.join(", ") || "no one"}.`; | |
| 56 | note = `${again}${got.changes.length} in ${room}; here: ${got.here.join(", ") || "no one"}.`; | |
| 56 | 57 | } else { |
| 57 | 58 | got = undefined; |
| 58 | 59 | note = wordsOf(done.error); |
test/app-changes.test.ts +48 −2
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; |
| 9 | import { Database } from "bun:sqlite"; | |
| 9 | 10 | import { mkdtemp, rm } from "node:fs/promises"; |
| 10 | 11 | import { tmpdir } from "node:os"; |
| 11 | 12 | import { join } from "node:path"; |
| @@ -23,6 +24,7 @@ import { serve, type Servers } from "../src/http/server.ts"; | ||
| 23 | 24 | import { createForgeApp } from "../src/tui/forge.ts"; |
| 24 | 25 | import { changesScreen } from "../src/tui/screens/app_changes.ts"; |
| 25 | 26 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; |
| 27 | import { keyOf } from "../src/web/keymap.ts"; | |
| 26 | 28 | import { settleApp } from "./helpers/tui.ts"; |
| 27 | 29 | import { quietLogs } from "./helpers/globals.ts"; |
| 28 | 30 | import { seedAdmin } from "./helpers/admin.ts"; |
| @@ -98,6 +100,41 @@ describe("the change stream over the API and MCP", () => { | ||
| 98 | 100 | await rm(dataDir, { recursive: true, force: true }); |
| 99 | 101 | }); |
| 100 | 102 | |
| 103 | test("a stream that started again tells a client that was further on", async () => { | |
| 104 | for (let n = 1; n <= 3; n++) await post("alice", "again", { n }, "alice/hidden"); | |
| 105 | const held: any = await (await get("alice", "again", "", "alice/hidden")).json(); | |
| 106 | expect(held.next).toBe(3); | |
| 107 | const q = (since: number, epoch?: string) => `?since=${since}${epoch === undefined ? "" : `&epoch=${epoch}`}`; | |
| 108 | const read = async (since: number, epoch?: string): Promise<any> => (await get("alice", "again", q(since, epoch), "alice/hidden")).json(); | |
| 109 | // The same stream: nothing new, nothing to forget. | |
| 110 | expect(await read(3, held.epoch)).toEqual({ changes: [], next: 3, here: ["alice"], epoch: held.epoch }); | |
| 111 | ||
| 112 | // The forge comes back without the stream's file, as a restore leaves it. | |
| 113 | servers.stop(); | |
| 114 | app.close(); | |
| 115 | await rm(join(dataDir, "changes"), { recursive: true, force: true }); | |
| 116 | app = createApp({ dataDir, port: 0 }); | |
| 117 | servers = await serve(app); | |
| 118 | await post("alice", "again", { n: "a" }, "alice/hidden"); | |
| 119 | ||
| 120 | const reset = await read(3, held.epoch); | |
| 121 | expect(reset).toEqual({ changes: [], next: 0, here: ["alice"], epoch: expect.any(String), reset: true }); | |
| 122 | expect(reset.epoch).not.toBe(held.epoch); | |
| 123 | // A client from before epochs is told while its number is past the last one. | |
| 124 | expect(await read(3)).toMatchObject({ next: 0, reset: true }); | |
| 125 | // MCP says the same. | |
| 126 | expect(JSON.parse((await rpc("alice", { repo: "alice/hidden", room: "again", since: 3, epoch: held.epoch })).text)).toMatchObject({ next: 0, reset: true }); | |
| 127 | // Reading again from 0 is the whole new stream. | |
| 128 | expect((await read(0, reset.epoch)).changes.map((c: any) => c.data.n)).toEqual(["a"]); | |
| 129 | ||
| 130 | for (const n of ["b", "c", "d"]) await post("alice", "again", { n }, "alice/hidden"); | |
| 131 | // The numbers have passed it: the epoch still tells; without one the client goes on from 3. | |
| 132 | expect(await read(3, held.epoch)).toMatchObject({ changes: [], next: 0, reset: true }); | |
| 133 | const old = await read(3); | |
| 134 | expect(old.reset).toBeUndefined(); | |
| 135 | expect(old.changes.map((c: any) => c.data.n)).toEqual(["d"]); | |
| 136 | }); | |
| 137 | ||
| 101 | 138 | test("two clients read the same order, and a reconnect catches up from an offset", async () => { |
| 102 | 139 | expect((await (await post("alice", "lobby", { n: 1 })).json())).toEqual({ seq: 1 }); |
| 103 | 140 | expect((await (await post("bob", "lobby", { n: 2 })).json())).toEqual({ seq: 2 }); |
| @@ -138,7 +175,7 @@ describe("the change stream over the API and MCP", () => { | ||
| 138 | 175 | }); |
| 139 | 176 | |
| 140 | 177 | /** Drive the terminal screen as `user` (undefined: a guest); `keys` are fed in turn. */ |
| 141 | async function screenAs(user: User | undefined, repoName: string, room: string, keys: string[]): Promise<string> { | |
| 178 | async function screenAs(user: User | undefined, repoName: string, room: string, keys: (string | (() => void))[]): Promise<string> { | |
| 142 | 179 | const terminal = headlessTerminal(120, 40); |
| 143 | 180 | const { app: tui, session } = createForgeApp( |
| 144 | 181 | app, |
| @@ -150,7 +187,8 @@ describe("the change stream over the API and MCP", () => { | ||
| 150 | 187 | tui.ctx.push(changesScreen(session, tui.ctx, repo, room)); |
| 151 | 188 | await settleApp(tui); |
| 152 | 189 | for (const k of keys) { |
| 153 | terminal.feed(k); | |
| 190 | if (typeof k === "string") terminal.feed(k); | |
| 191 | else k(); | |
| 154 | 192 | await settleApp(tui); |
| 155 | 193 | } |
| 156 | 194 | const text = tui.screen.toText(); |
| @@ -175,6 +213,14 @@ describe("the change stream over the API and MCP", () => { | ||
| 175 | 213 | // Not JSON stays in the prompt and appends nothing; `o` moves to another room. |
| 176 | 214 | await screenAs(users.alice!, "hidden", "desk", ["a", "n", "o", "\r"]); |
| 177 | 215 | expect(((await (await get("alice", "desk", "", "alice/hidden")).json()) as any).changes.length).toBe(2); |
| 216 | // Read again after the stream became another one: the screen says so. | |
| 217 | const another = (): void => { | |
| 218 | const db = new Database(join(dataDir, "changes", "hidden.sqlite")); | |
| 219 | db.run("UPDATE stream SET epoch = 'another'"); | |
| 220 | db.close(); | |
| 221 | }; | |
| 222 | expect(await screenAs(users.alice!, "hidden", "desk", [keyOf("reread")])).not.toContain("started again"); | |
| 223 | expect(await screenAs(users.alice!, "hidden", "desk", [another, keyOf("reread")])).toContain("This stream started again."); | |
| 178 | 224 | const moved = await screenAs(users.alice!, "hidden", "desk", ["o", ..."desk".split("").map(() => "\x7f"), ..."other".split(""), "\r"]); |
| 179 | 225 | expect(moved).toContain("in other"); |
| 180 | 226 | }); |
new above
offline