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

opened this

Merged 18h 23m ago, live in production

sold/stream-epoch → main 0 commits

  • Merged. sold/stream-epoch was merged into main as 40fffab.

Review

Sign in to review this change.
8 files changed +87 −10
docs/features/sync.md +4 −2
@@ -6,10 +6,12 @@ row: Ordered change stream (sync)
66
77 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.
88
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`.
1012 - Append: `POST` the same path with `{ "data": <json> }` answers `201 { seq }`. Needs an `rw` token or a session.
1113 - 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.
1315
1416 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`.
1517
src/actions/app_changes.ts +14 −1
@@ -24,6 +24,13 @@ export interface ChangesRead {
2424 /** Pass this as `since` next time. */
2525 readonly next: number;
2626 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;
2734 }
2835
2936 export type ChangesResult<T> = { ok: true; value: T } | { ok: false; error: ChangesRefusal | { invalid: string } };
@@ -67,13 +74,19 @@ export async function readChanges(
6774 room: string,
6875 since: number,
6976 limit?: number,
77 epoch?: string,
7078 ): Promise<ChangesResult<ChangesRead>> {
7179 const g = await gate(app, repo, user);
7280 if (!g.ok) return g;
7381 if (!isRoom(room)) return { ok: false, error: { invalid: "bad room" } };
7482 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 } };
7588 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 } };
7790 }
7891
7992 /** Append one JSON value to a room; answers its sequence number. */
src/apps/changes.ts +12
@@ -10,6 +10,7 @@
1010 import { Database } from "bun:sqlite";
1111 import { mkdirSync } from "node:fs";
1212 import { join } from "node:path";
13 import { id } from "../kernel/id.ts";
1314
1415 export interface Change {
1516 readonly seq: number;
@@ -37,6 +38,11 @@ export const isRoom = (room: unknown): room is string => typeof room === "string
3738 export interface Changes {
3839 append(app: string, room: string, json: string): Appended;
3940 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 };
4046 close(): void;
4147 }
4248
@@ -57,6 +63,8 @@ export function openChanges(dataDir: string, now: () => number = Date.now): Chan
5763 "CREATE TABLE IF NOT EXISTS change (seq INTEGER PRIMARY KEY, room TEXT NOT NULL, json TEXT NOT NULL, at INTEGER NOT NULL)",
5864 );
5965 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());
6068 dbs.set(key, d);
6169 }
6270 return d;
@@ -101,6 +109,10 @@ export function openChanges(dataDir: string, now: () => number = Date.now): Chan
101109 )
102110 .all(room, after, n);
103111 },
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 },
104116 close() {
105117 for (const d of dbs.values()) d.close();
106118 dbs.clear();
src/contract/openapi/routes/getApiV1ReposOwnerNameChangesRoom.ts +1 −1
@@ -4,7 +4,7 @@ export const route: Route = {
44 method: "get",
55 path: `${REPO}/changes/{room}`,
66 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",
88 auth: true,
99 role: "member",
1010 refusals: {
src/http/api/app_changes.ts +1 −1
@@ -31,7 +31,7 @@ export function appChangesRoutes(router: Router<Handler>): void {
3131 if (!repo) return notFound();
3232 const url = new URL(ctx.request.url);
3333 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);
3535 return out.ok ? json(out.value, 200, { "cache-control": "no-store" }) : refusal(out.error);
3636 });
3737 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"
33
44 export const tool: Tool = {
55 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`",
77 description: "An app's ordered change stream: read a room after an offset, or append to it.",
88 inputSchema: {
99 type: "object",
@@ -11,6 +11,7 @@ export const tool: Tool = {
1111 repo: REPO_ARG,
1212 room: { type: "string" },
1313 since: { type: "integer", minimum: 0 },
14 epoch: { type: "string" },
1415 data: {},
1516 },
1617 required: ["repo", "room"],
@@ -25,9 +26,11 @@ export const tool: Tool = {
2526 if (typeof room !== "string") return bad("invalid", "`room` is text");
2627 const since = args["since"] ?? 0;
2728 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");
2831 const out =
2932 args["data"] === undefined
30 ? await readChanges(ctx.app, repo, user, room, since)
33 ? await readChanges(ctx.app, repo, user, room, since, undefined, epoch)
3134 : await appendChange(ctx.app, repo, user, room, JSON.stringify(args["data"]));
3235 if (out.ok) return good(out.value);
3336 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
5151 runAsync(ctx, async () => {
5252 const done = await readChanges(f.app, repo, f.user, room, 0, 100);
5353 if (done.ok) {
54 const again = got !== undefined && got.epoch !== done.value.epoch ? "This stream started again. " : "";
5455 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"}.`;
5657 } else {
5758 got = undefined;
5859 note = wordsOf(done.error);
test/app-changes.test.ts +48 −2
@@ -6,6 +6,7 @@
66 */
77
88 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { Database } from "bun:sqlite";
910 import { mkdtemp, rm } from "node:fs/promises";
1011 import { tmpdir } from "node:os";
1112 import { join } from "node:path";
@@ -23,6 +24,7 @@ import { serve, type Servers } from "../src/http/server.ts";
2324 import { createForgeApp } from "../src/tui/forge.ts";
2425 import { changesScreen } from "../src/tui/screens/app_changes.ts";
2526 import { headlessTerminal } from "../src/tui/term/terminal.ts";
27 import { keyOf } from "../src/web/keymap.ts";
2628 import { settleApp } from "./helpers/tui.ts";
2729 import { quietLogs } from "./helpers/globals.ts";
2830 import { seedAdmin } from "./helpers/admin.ts";
@@ -98,6 +100,41 @@ describe("the change stream over the API and MCP", () => {
98100 await rm(dataDir, { recursive: true, force: true });
99101 });
100102
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
101138 test("two clients read the same order, and a reconnect catches up from an offset", async () => {
102139 expect((await (await post("alice", "lobby", { n: 1 })).json())).toEqual({ seq: 1 });
103140 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", () => {
138175 });
139176
140177 /** 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> {
142179 const terminal = headlessTerminal(120, 40);
143180 const { app: tui, session } = createForgeApp(
144181 app,
@@ -150,7 +187,8 @@ describe("the change stream over the API and MCP", () => {
150187 tui.ctx.push(changesScreen(session, tui.ctx, repo, room));
151188 await settleApp(tui);
152189 for (const k of keys) {
153 terminal.feed(k);
190 if (typeof k === "string") terminal.feed(k);
191 else k();
154192 await settleApp(tui);
155193 }
156194 const text = tui.screen.toText();
@@ -175,6 +213,14 @@ describe("the change stream over the API and MCP", () => {
175213 // Not JSON stays in the prompt and appends nothing; `o` moves to another room.
176214 await screenAs(users.alice!, "hidden", "desk", ["a", "n", "o", "\r"]);
177215 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.");
178224 const moved = await screenAs(users.alice!, "hidden", "desk", ["o", ..."desk".split("").map(() => "\x7f"), ..."other".split(""), "\r"]);
179225 expect(moved).toContain("in other");
180226 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs