Public: anyone can read this; the crew can change it.

Events keep their order across processes: replays resume by the table's own sequence #940

Closed opened this in answer to
Closed without merging

scout/forge:scout/932-events-keep-their-order-across-processes → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
4 files changed +139 −12
src/core/events.ts +18 −7
@@ -92,11 +92,22 @@ export class EventBus {
9292 }
9393 }
9494
95 /**
96 * SQL for "after the event this id names". Events are ordered by the table's
97 * own rowid, which SQLite keeps strictly increasing across every connection;
98 * ids are only in order within one process. A cursor stays an id: it is
99 * looked up to its place in the table. An id naming no event (its repository
100 * was deleted) resumes after the last event whose id sorts at or below it.
101 */
102 const afterCursor = (param: string): string =>
103 `event.rowid > COALESCE((SELECT rowid FROM event WHERE id = ${param}),
104 (SELECT MAX(rowid) FROM event WHERE id <= ${param}), 0)`;
105
95106 export interface ListEventsOptions {
96107 repoId?: string;
97108 /** Restrict to events of this kind. */
98109 kind?: string;
99 /** Return events with id greater than this (exclusive). */
110 /** Return events written after the one with this id (exclusive). */
100111 afterId?: string;
101112 /** @default 100 */
102113 limit?: number;
@@ -126,13 +137,13 @@ export function listEventsVisibleTo(
126137 let where = `event.repo_id IS NOT NULL AND ${repoVisible(viewer !== undefined)}`;
127138 if (options.afterId !== undefined) {
128139 params.push(options.afterId);
129 where += ` AND event.id > ?${params.length}`;
140 where += ` AND ${afterCursor(`?${params.length}`)}`;
130141 }
131142 params.push(options.limit ?? 100);
132143 return db
133144 .query<EventRow, (string | number)[]>(
134145 `SELECT event.* FROM event JOIN repo ON repo.id = event.repo_id
135 WHERE ${where} ORDER BY event.id DESC LIMIT ?${params.length}`,
146 WHERE ${where} ORDER BY event.rowid DESC LIMIT ?${params.length}`,
136147 )
137148 .all(...params)
138149 .map(toEvent);
@@ -172,21 +183,21 @@ export function listEvents(
172183 const params: (string | number)[] = [];
173184 if (options.repoId !== undefined) {
174185 params.push(options.repoId);
175 clauses.push(`repo_id = ?${params.length}`);
186 clauses.push(`event.repo_id = ?${params.length}`);
176187 }
177188 if (options.kind !== undefined) {
178189 params.push(options.kind);
179 clauses.push(`kind = ?${params.length}`);
190 clauses.push(`event.kind = ?${params.length}`);
180191 }
181192 if (options.afterId !== undefined) {
182193 params.push(options.afterId);
183 clauses.push(`id > ?${params.length}`);
194 clauses.push(afterCursor(`?${params.length}`));
184195 }
185196 params.push(options.limit ?? 100);
186197 const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
187198 return db
188199 .query<EventRow, (string | number)[]>(
189 `SELECT * FROM event ${where} ORDER BY id DESC LIMIT ?${params.length}`,
200 `SELECT * FROM event ${where} ORDER BY event.rowid DESC LIMIT ?${params.length}`,
190201 )
191202 .all(...params)
192203 .map(toEvent);
src/core/schema.ts +9
@@ -1501,4 +1501,13 @@ export const migrations: readonly string[] = [
15011501 );
15021502 CREATE INDEX IF NOT EXISTS fork_made_owner ON fork_made(owner_id, made_at);
15031503 `,
1504 // 68 — events are ordered by the table's own rowid (#932), which only
1505 // increases; ids are in order within one process. A single-column index
1506 // carries the rowid, so a repository's or a kind's events read in order.
1507 `
1508 DROP INDEX IF EXISTS event_repo;
1509 DROP INDEX IF EXISTS event_kind;
1510 CREATE INDEX IF NOT EXISTS event_repo ON event(repo_id);
1511 CREATE INDEX IF NOT EXISTS event_kind ON event(kind);
1512 `,
15041513 ];
src/http/sse.ts +15 −5
@@ -17,7 +17,7 @@
1717 import { holdForCaller } from "./caller.ts";
1818 import type { App } from "../app.ts";
1919 import type { User } from "../core/users.ts";
20 import { listEventsVisibleTo } from "../core/events.ts";
20 import { listEvents, listEventsVisibleTo } from "../core/events.ts";
2121 import { audienceFilter } from "../core/event_audience.ts";
2222 import { canRead, getRepoById } from "../core/repos.ts";
2323 import type { ForgeEvent } from "../core/events.ts";
@@ -238,12 +238,22 @@ export function sseStream(
238238 viewer: User | undefined,
239239 ): Response {
240240 const meant = audienceFilter(app.db, viewer);
241 return eventStream(request, (emit) =>
242 app.bus.subscribe((event: ForgeEvent) => {
241 const after =
242 request.headers.get("last-event-id") ??
243 new URL(request.url).searchParams.get("since") ??
244 undefined;
245 return eventStream(request, (emit) => {
246 if (after !== undefined && after !== "") {
247 const missed = listEvents(app.db, { repoId, afterId: after, limit: 200 })
248 .reverse();
249 for (const event of missed)
250 if (meant(event)) emit(event.kind, event, event.id);
251 }
252 return app.bus.subscribe((event: ForgeEvent) => {
243253 // The event id doubles as the SSE id, so a reconnecting client can
244254 // resume from where it stopped.
245255 if (event.repoId === repoId && meant(event))
246256 emit(event.kind, event, event.id);
247 }),
248 );
257 });
258 });
249259 }
test/event-order.test.ts added +97
@@ -0,0 +1,97 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { Database } from "bun:sqlite";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { createRepo } from "../src/actions/repos.ts";
8 import { listEvents, listEventsVisibleTo } from "../src/core/events.ts";
9 import { sseStream, viewerStream } from "../src/http/sse.ts";
10 import { signUpProven as signUp } from "./helpers/verified.ts";
11
12 describe("events keep their order across processes (#932)", () => {
13 let dataDir: string;
14 let app: App;
15 let other: Database;
16 let repoId: string;
17 let first: string;
18 const SMALLER = "00000000000000000000000000";
19
20 beforeAll(async () => {
21 dataDir = await mkdtemp(join(tmpdir(), "forge-order-"));
22 app = createApp({ dataDir, port: 0 });
23 const user = await signUp(app, {
24 username: "orderly",
25 email: "[email protected]",
26 password: "a-long-orderly-password",
27 });
28 if (!user.ok) throw new Error("seed");
29 const repo = await createRepo(app, user.value, {
30 name: "ordered",
31 visibility: "public",
32 });
33 if (!repo.ok) throw new Error("seed repo");
34 repoId = repo.value.id;
35 first = app.bus.append({ kind: "test.first", repoId }).id;
36 // A second process, on its own connection, in the same millisecond, whose
37 // id sorts below the first's.
38 other = new Database(join(dataDir, "forge.db"));
39 other.exec("PRAGMA busy_timeout = 5000");
40 other
41 .query(
42 "INSERT INTO event (id, kind, repo_id, payload) VALUES (?1, 'test.second', ?2, '{}')",
43 )
44 .run(SMALLER, repoId);
45 });
46
47 afterAll(async () => {
48 other.close();
49 app.close();
50 await rm(dataDir, { recursive: true, force: true });
51 });
52
53 test("lists are newest first by write order, and resume after an id by it", () => {
54 const kinds = listEvents(app.db, { repoId }).map((e) => e.kind);
55 expect(kinds.slice(0, 2)).toEqual(["test.second", "test.first"]);
56 expect(
57 listEvents(app.db, { repoId, afterId: first }).map((e) => e.kind),
58 ).toEqual(["test.second"]);
59 expect(
60 listEventsVisibleTo(app.db, undefined, { afterId: first }).map(
61 (e) => e.kind,
62 ),
63 ).toEqual(["test.second"]);
64 });
65
66 test("a cursor naming no event resumes after the last id at or below it", () => {
67 expect(
68 listEvents(app.db, { repoId, afterId: "zzzz" }).map((e) => e.kind),
69 ).toEqual([]);
70 });
71
72 test("both streams resumed after the first miss nothing", async () => {
73 for (const make of [
74 (req: Request) => viewerStream(app, undefined, req),
75 (req: Request) => sseStream(app, repoId, req, undefined),
76 ]) {
77 const ctl = new AbortController();
78 const res = make(
79 new Request("http://x/stream", {
80 headers: { "last-event-id": first },
81 signal: ctl.signal,
82 }),
83 );
84 const reader = res.body!.getReader();
85 let text = "";
86 const decoder = new TextDecoder();
87 while (!text.includes("test.second")) {
88 const { value, done } = await reader.read();
89 if (done) break;
90 text += decoder.decode(value);
91 }
92 ctl.abort();
93 expect(text).toContain(`id: ${SMALLER}`);
94 expect(text).not.toContain("test.first");
95 }
96 });
97 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs