The catalog answers watched queries: itx.contexts.watch, in three orders, with an answered summary (#17)
jonas, 2026-11-26 23:32 UTC · 6f4fd09ce8078d14904e6aa880964aae40efc555 · parent 9be54f2
16 files changed
- M core/itx/src/context/awake.test.ts
- M core/itx/src/context/awake.ts
- M core/itx/src/context/built-ins.ts
- A core/itx/src/context/catalog-watch.test.ts
- A core/itx/src/context/catalog-watch.ts
- M core/itx/src/context/context-activity-stack.test.ts
- M core/itx/src/context/context-catalog.ts
- M core/itx/src/context/itx-expression-rewriting.ts
- A core/itx/src/context/reactive-catalog.test.ts
- A core/itx/src/context/reactive-catalog.ts
- M core/itx/src/iterate-context-durable-object.ts
- M core/itx/src/iterate-context.ts
- M core/lib/src/api.ts
- M core/lib/src/lib.ts
- A core/mind-worker/src/context/catalog-watch.test.ts
- A core/mind-worker/src/context/fixtures/catalog-watch.ts
M core/itx/src/context/awake.test.ts
@@ -1,15 +1,22 @@ // The dialing side of the awake socket: when a context opens it, how long it holds it and when it // closes it. The accepting side is the runtime's hibernation API, which only a deployed stack has // (core/alchemy/scripts/smoke). -import { expect, test, vi } from "vitest"; +import { expect, onTestFinished, test, vi } from "vitest"; import { + AWAKE_ANSWER_WAIT_MS, AWAKE_CONTEXT_PATH, + AWAKE_SUMMARY_FAILED, + AWAKE_SUMMARY_KEPT, AWAKE_MAX_HOLD_MS, AWAKE_QUIET_MS, + AWAKE_RECOVER_AFTER_MS, AWAKE_REDIAL_AFTER_MS, + AWAKE_SAY_AGAIN_AFTER_MS, + AWAKE_SAY_AGAIN_TRIES, AWAKE_SUMMARY_EVERY_MS, AwakeSocket, decideAwakeSocket, + unansweredSummaryTries, } from "./awake.ts"; test.for([ @@ -180,23 +187,415 @@ vi.useRealTimers(); }); -/** The accepting context, as the dialer sees it: counts dials and the sockets that are open. */ +test("an entry leaves an alarm, and a quiet close with every summary answered takes it away", async () => { + vi.useFakeTimers(); + const far = farEnd(); + let changes = 0; + const awake = new AwakeSocket({ + path: "/agents/a", + dial: far.dial, + busy: () => false, + summary: () => "one", + recoveryChanged: () => (changes += 1), + }); + expect(awake.recoverAt()).toBeNull(); + const enteredAt = Date.now(); + awake.entered(); + // past the longest hold: a context that lives takes the alarm away before it fires + expect(awake.recoverAt()).toBe(enteredAt + AWAKE_RECOVER_AFTER_MS); + awake.entered(); + expect(changes).toBe(1); + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS); + expect(far).toMatchObject({ sent: ["one"], open: 0 }); + expect(awake.recoverAt()).toBeNull(); + expect(changes).toBe(2); + expect(vi.getTimerCount()).toBe(0); + vi.useRealTimers(); +}); + +test("a quiet context keeps its socket for the catalog's answer, and no longer than the answer wait", async () => { + vi.useFakeTimers(); + const far = farEnd(); + far.answers = false; + const unanswered = counted(); + const awake = new AwakeSocket({ + path: "/agents/a", + dial: far.dial, + busy: () => false, + summary: () => "one", + unanswered, + }); + awake.entered(); + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS + AWAKE_ANSWER_WAIT_MS - 1); + expect(far).toMatchObject({ sent: ["one"], open: 1 }); + await vi.advanceTimersByTimeAsync(1); + expect(far).toMatchObject({ open: 0 }); + // the alarm wakes the context to say it again + expect(unanswered).toMatchObject({ tries: 1 }); + expect(awake.recoverAt()).toBe(Date.now() + AWAKE_SAY_AGAIN_AFTER_MS); + expect(vi.getTimerCount()).toBe(0); + vi.useRealTimers(); +}); + +test("work that comes back during the wait for an answer keeps the socket", async () => { + vi.useFakeTimers(); + const far = farEnd(); + far.answers = false; + let summary = "one"; + const awake = new AwakeSocket({ + path: "/agents/a", + dial: far.dial, + busy: () => false, + summary: () => summary, + }); + awake.entered(); + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS + 100); + expect(far).toMatchObject({ sent: ["one"], open: 1 }); + awake.entered(); + summary = "two"; + far.answers = true; + far.answer(); + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS); + expect(far).toMatchObject({ dials: 1, sent: ["one", "two"], open: 0 }); + expect(awake.recoverAt()).toBeNull(); + vi.useRealTimers(); +}); + +test("an unanswered summary is said again by the alarm, at longer waits, and then no more", async () => { + vi.useFakeTimers(); + const far = farEnd(); + far.answers = false; + const unanswered = counted(); + const warned = vi.spyOn(console, "warn").mockImplementation(() => {}); + vi.spyOn(console, "info").mockImplementation(() => {}); + const awake = new AwakeSocket({ + path: "/agents/a", + dial: far.dial, + busy: () => false, + summary: () => "one", + unanswered, + }); + awake.entered(); + const waits: number[] = []; + for (let tried = 1; tried <= AWAKE_SAY_AGAIN_TRIES; tried++) { + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS + AWAKE_ANSWER_WAIT_MS); + expect(unanswered, `try ${tried}`).toMatchObject({ tries: tried }); + const at = awake.recoverAt()!; + waits.push(at - Date.now()); + // the alarm is not due before its time + expect(awake.recover(at - 1)).toBe(false); + await vi.advanceTimersByTimeAsync(at - Date.now()); + expect(awake.recover(Date.now())).toBe(true); + } + expect(waits).toEqual([30_000, 60_000, 120_000, 240_000, 480_000, 960_000, 1_800_000, 1_800_000]); + // the last try is unanswered too: a warning, and nothing is owed + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS + AWAKE_ANSWER_WAIT_MS); + // each try said the summary again, on a socket of its own + expect(far).toMatchObject({ dials: AWAKE_SAY_AGAIN_TRIES + 1, open: 0 }); + expect(far.sent).toHaveLength(AWAKE_SAY_AGAIN_TRIES + 1); + expect(warned).toHaveBeenCalledWith( + expect.objectContaining({ event: "context.awake-summary-gave-up", path: "/agents/a" }), + ); + expect(awake.recoverAt()).toBeNull(); + expect(unanswered).toMatchObject({ tries: 0 }); + expect(vi.getTimerCount()).toBe(0); + vi.useRealTimers(); +}); + +test("the catalog's answer to a summary said again takes the count away", async () => { + vi.useFakeTimers(); + vi.spyOn(console, "info").mockImplementation(() => {}); + const far = farEnd(); + far.answers = false; + const unanswered = counted(); + const awake = new AwakeSocket({ + path: "/agents/a", + dial: far.dial, + busy: () => false, + summary: () => "one", + unanswered, + }); + awake.entered(); + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS + AWAKE_ANSWER_WAIT_MS); + expect(unanswered).toMatchObject({ tries: 1 }); + far.answers = true; + expect(awake.recover(awake.recoverAt()!)).toBe(true); + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS); + expect(far).toMatchObject({ sent: ["one", "one"], open: 0 }); + expect(unanswered).toMatchObject({ tries: 0 }); + expect(awake.recoverAt()).toBeNull(); + vi.useRealTimers(); +}); + +test("a socket that ends with a summary unanswered under a working context: the next socket says it at once", async () => { + vi.useFakeTimers(); + const far = farEnd(); + far.answers = false; + const awake = new AwakeSocket({ + path: "/agents/a", + dial: far.dial, + busy: () => true, + summary: () => "one", + }); + awake.entered(); + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS); + expect(far).toMatchObject({ dials: 1, sent: ["one"] }); + far.closeAll(); + far.answers = true; + // the same words again, and long before the next summary would be due + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS); + expect(far).toMatchObject({ dials: 2, sent: ["one", "one"], open: 1 }); + vi.useRealTimers(); +}); + +test("a context that goes quiet with no socket owes its summary to the alarm", async () => { + vi.useFakeTimers(); + vi.spyOn(console, "info").mockImplementation(() => {}); + const far = farEnd(); + far.refuse = true; + const unanswered = counted(); + const awake = new AwakeSocket({ + path: "/agents/a", + dial: far.dial, + busy: () => false, + summary: () => "one", + unanswered, + }); + awake.entered(); + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS); + expect(far).toMatchObject({ dials: 1, sent: [] }); + expect(unanswered).toMatchObject({ tries: 1 }); + expect(awake.recoverAt()).toBe(Date.now() + AWAKE_SAY_AGAIN_AFTER_MS); + vi.useRealTimers(); +}); + +test("the answer to an earlier summary does not settle a later one that could not be made", async () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + vi.spyOn(console, "info").mockImplementation(() => {}); + const far = farEnd(); + far.answers = false; + let busy = true; + let readable = true; + const unanswered = counted(); + const awake = new AwakeSocket({ + path: "/agents/a", + dial: far.dial, + busy: () => busy, + summary: () => { + if (!readable) throw new Error("the log cannot be read"); + return "one"; + }, + unanswered, + }); + awake.entered(); + await vi.advanceTimersByTimeAsync(AWAKE_SUMMARY_EVERY_MS + AWAKE_QUIET_MS); + expect(far).toMatchObject({ sent: ["one"], open: 1 }); + // the context goes quiet, and its last summary cannot be made while "one" is unanswered + readable = false; + busy = false; + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS); + expect(far).toMatchObject({ sent: ["one"], open: 1 }); + // the catalog answers "one": that is no answer to the summary that never went + far.answer(); + await vi.advanceTimersByTimeAsync(1); + expect(far).toMatchObject({ open: 0 }); + expect(unanswered).toMatchObject({ tries: 1 }); + expect(awake.recoverAt()).toBe(Date.now() - 1 + AWAKE_SAY_AGAIN_AFTER_MS); +}); + +test("a summary that the catalog could not keep is owed, and the context says it again", async () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + vi.spyOn(console, "info").mockImplementation(() => {}); + const far = farEnd(); + far.answerWith = AWAKE_SUMMARY_FAILED; + const unanswered = counted(); + const awake = new AwakeSocket({ + path: "/agents/a", + dial: far.dial, + busy: () => false, + summary: () => "one", + unanswered, + }); + awake.entered(); + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS); + // answered, and not kept: no wait, and the alarm has the context say it again + expect(far).toMatchObject({ sent: ["one"], open: 0 }); + expect(unanswered).toMatchObject({ tries: 1 }); + expect(awake.recoverAt()).toBe(Date.now() + AWAKE_SAY_AGAIN_AFTER_MS); + far.answerWith = AWAKE_SUMMARY_KEPT; + await vi.advanceTimersByTimeAsync(AWAKE_SAY_AGAIN_AFTER_MS); + expect(awake.recover(Date.now())).toBe(true); + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS); + expect(far).toMatchObject({ sent: ["one", "one"], open: 0 }); + expect(unanswered).toMatchObject({ tries: 0 }); + expect(awake.recoverAt()).toBeNull(); +}); + +test("an answer that this release does not know settles a summary, as kept does", async () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + const far = farEnd(); + far.answerWith = "kept-and-more"; + const awake = new AwakeSocket({ + path: "/agents/a", + dial: far.dial, + busy: () => false, + summary: () => "one", + }); + awake.entered(); + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS); + expect(far).toMatchObject({ sent: ["one"], open: 0 }); + expect(awake.recoverAt()).toBeNull(); +}); + +test("an alarm in an object that never entered says the summary: the object before it may have died with it unsaid", async () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + const far = farEnd(); + // a new object: nothing in its memory says whether a summary is owed + const awake = new AwakeSocket({ + path: "/agents/a", + dial: far.dial, + busy: () => false, + summary: () => "one", + }); + expect(awake.recoverAt()).toBeNull(); + expect(awake.recover(Date.now())).toBe(true); + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS); + expect(far).toMatchObject({ dials: 1, sent: ["one"], open: 0 }); + // the catalog answered: nothing is owed, and a later alarm of another kind says nothing + expect(awake.recoverAt()).toBeNull(); + expect(awake.recover(Date.now())).toBe(false); + expect(far).toMatchObject({ dials: 1 }); +}); + +test("an alarm while the context works moves the recovery on and makes no entry", async () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + const far = farEnd(); + const awake = new AwakeSocket({ + path: "/agents/a", + dial: far.dial, + busy: () => true, + summary: () => "one", + }); + const enteredAt = Date.now(); + awake.entered(); + // real entries, the last in the fifth minute, keep the socket past the time of the alarm that + // the first one left + for (let minute = 1; minute <= 5; minute++) { + await vi.advanceTimersByTimeAsync(60_000); + awake.entered(); + } + await vi.advanceTimersByTimeAsync(AWAKE_RECOVER_AFTER_MS - 5 * 60_000); + expect(awake.recoverAt()).toBe(enteredAt + AWAKE_RECOVER_AFTER_MS); + expect(awake.recover(Date.now())).toBe(false); + expect(awake.recoverAt()).toBe(Date.now() + AWAKE_RECOVER_AFTER_MS); + expect(far).toMatchObject({ dials: 1, open: 1 }); + // No entry was made by the alarm: the longest hold still ends the socket five minutes after + // the entry in the fifth minute. + await vi.advanceTimersByTimeAsync( + enteredAt + 5 * 60_000 + AWAKE_MAX_HOLD_MS - Date.now() - AWAKE_QUIET_MS, + ); + expect(far).toMatchObject({ open: 1 }); + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS); + expect(far).toMatchObject({ dials: 1, open: 0 }); + expect(awake.recoverAt()).toBeNull(); +}); + +test("a summary that cannot be made is owed, as an unanswered one is", async () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + vi.spyOn(console, "info").mockImplementation(() => {}); + const far = farEnd(); + const unanswered = counted(); + let readable = false; + const awake = new AwakeSocket({ + path: "/agents/a", + dial: far.dial, + busy: () => false, + summary: () => { + if (!readable) throw new Error("the log cannot be read"); + return "one"; + }, + unanswered, + }); + awake.entered(); + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS); + // no wait for an answer that cannot come + expect(far).toMatchObject({ sent: [], open: 0 }); + expect(unanswered).toMatchObject({ tries: 1 }); + expect(awake.recoverAt()).toBe(Date.now() + AWAKE_SAY_AGAIN_AFTER_MS); + readable = true; + await vi.advanceTimersByTimeAsync(AWAKE_SAY_AGAIN_AFTER_MS); + expect(awake.recover(Date.now())).toBe(true); + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS); + expect(far).toMatchObject({ sent: ["one"], open: 0 }); + expect(unanswered).toMatchObject({ tries: 0 }); + expect(awake.recoverAt()).toBeNull(); +}); + +test("the tries that a context keeps are in a row by time: a count older than an hour counts for nothing", () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + const stored = new Map<string, unknown>(); + const tries = unansweredSummaryTries({ + get: (key: string) => stored.get(key), + put: (key: string, value: unknown) => void stored.set(key, value), + delete: (key: string) => stored.delete(key), + } as Pick<SyncKvStorage, "get" | "put" | "delete">); + expect(tries.count()).toBe(0); + tries.set(3); + vi.advanceTimersByTime(59 * 60_000); + expect(tries.count()).toBe(3); + // the object died before the catalog answered, and the context next went unanswered a day later + vi.advanceTimersByTime(24 * 60 * 60_000); + expect(tries.count()).toBe(0); + tries.set(1); + expect(tries.count()).toBe(1); + tries.set(0); + expect(stored).toMatchObject({ size: 0 }); +}); + +/** Where a context keeps how often its summary went unanswered: its own storage, here a field. */ +function counted() { + const kept = { + tries: 0, + count: () => kept.tries, + set: (tries: number) => void (kept.tries = tries), + }; + return kept; +} + +/** The accepting context, as the dialer sees it: counts dials and the sockets that are open, and + * answers each summary as the catalog does, unless `answers` is off. */ function farEnd() { const closers = new Set<() => void>(); + const answerers = new Set<() => void>(); const far = { dials: 0, open: 0, sent: [] as string[], refuse: false, + answers: true, + /** What the catalog says of each summary. */ + answerWith: AWAKE_SUMMARY_KEPT as string, closeAll: () => closers.forEach((close) => close()), + /** One answer on each open socket: what a catalog that was slow sends at last. */ + answer: () => answerers.forEach((answer) => answer()), dial: async () => { far.dials += 1; if (far.refuse) return { status: 503 }; - const listeners: (() => void)[] = []; + const listeners: Record<string, ((event?: { data: string }) => void)[]> = {}; + const answer = () => + (listeners.message || []).forEach((listener) => listener({ data: far.answerWith })); const close = () => { if (!closers.delete(close)) return; + answerers.delete(answer); far.open -= 1; - listeners.forEach((listener) => listener()); + (listeners.close || []).forEach((listener) => listener()); }; return { status: 101, @@ -204,12 +603,16 @@ accept: () => { far.open += 1; closers.add(close); + answerers.add(answer); }, close, - send: (message: string) => void far.sent.push(message), + send: (message: string) => { + far.sent.push(message); + if (far.answers) queueMicrotask(answer); + }, // the one cast: a test socket has only what the dialer uses - addEventListener: ((_type: string, listener: () => void) => - void listeners.push(listener)) as WebSocket["addEventListener"], + addEventListener: ((type: string, listener: (event?: { data: string }) => void) => + void (listeners[type] ||= []).push(listener)) as WebSocket["addEventListener"], }, }; },
M core/itx/src/context/awake.ts
@@ -18,9 +18,25 @@ // one SQLite row (context-catalog.ts): one row written per wake of a context, beside the rows that // wake writes in its own log. // +// THE CATALOG ANSWERS EACH SUMMARY, on the same socket: it kept it, or it refused it. A context +// that goes quiet keeps its socket until its last summary is answered, at most +// `AWAKE_ANSWER_WAIT_MS`. What stays unanswered is said again: +// - while the context works, on the next socket, at once; +// - after it went quiet, by its own alarm, on the durable ladder (`AWAKE_SAY_AGAIN_AFTER_MS`, +// doubled to at most 30 minutes, `AWAKE_SAY_AGAIN_TRIES` times, then a warning and no more); +// - after its object died with the summary unsaid, by the alarm that every entry leaves no later +// than `AWAKE_RECOVER_AFTER_MS` ahead, and that a quiet close with every answer takes away. The +// object that this alarm wakes has nothing in memory of the one before it, so an alarm in an +// object that never entered says the summary (`recover`). +// So a row of the catalog is behind its context's log for a bounded time, and a row that stays +// behind is in the log of the context that gave up. The alarm is the one durable mark of a summary +// that is owed: it costs a context that has no earlier alarm two alarm writes for each time it +// works, and nothing else is written while the catalog answers. +// // The accepting context is not `/`: every wake of `/` restarts the root's facets, and the root // would wake twice for each wake of any other context. +import { z } from "zod"; import type { ContextActivity } from "iterate/api"; export const AWAKE_CONTEXT_PATH = "/awake"; @@ -39,6 +55,26 @@ export const AWAKE_ACTIVITY_DEBOUNCE_MS = 100; /** After a dial that failed, no other dial for this long. */ export const AWAKE_REDIAL_AFTER_MS = 10_000; +/** What the accepting context answers a summary with, on the same socket. `kept`: it is the + * context's row. `refused`: it is no summary, and would be refused again. Both settle it. + * `failed`: the catalog could not keep it this time, so it is owed, and the context says it + * again. Any other answer is read as `kept`, so that an answer of a later release settles too. */ +export const AWAKE_SUMMARY_KEPT = "kept"; +export const AWAKE_SUMMARY_REFUSED = "refused"; +export const AWAKE_SUMMARY_FAILED = "failed"; +/** How long a context that went quiet keeps its socket for the answer to its last summary. It is + * billed as the quiet window is. The accepting context wakes from hibernation for a summary, + * which took 0.1 to 0.6 s on a deployed mind (26 November 2026). */ +export const AWAKE_ANSWER_WAIT_MS = 3_000; +/** A context that entered keeps an alarm no later than this after the entry, until the catalog + * has answered all it said. It is past the longest hold, so a context that closes its socket + * with every answer takes the alarm away before it fires. */ +export const AWAKE_RECOVER_AFTER_MS = AWAKE_MAX_HOLD_MS + 60_000; +/** After a quiet close with a summary unanswered: the wait before the context says it again. It + * doubles at each try in a row, to at most 30 minutes. */ +export const AWAKE_SAY_AGAIN_AFTER_MS = 30_000; +/** How many times in a row a context says an unanswered summary again before it gives up. */ +export const AWAKE_SAY_AGAIN_TRIES = 8; export type AwakeContext = { path: string; @@ -113,13 +149,15 @@ /** Every context with an open socket here, by path, with when it woke and its latest live * activities. A context that dialed twice (its first socket's close has not arrived) is there - * once, with its earlier wake time and the newest socket state. */ + * once, with its earlier wake time and the newest socket state. `except` is a socket whose close + * is being handled: it counts as closed, whatever its state says. */ export function awakeContexts( ctx: Pick<DurableObjectState, "getWebSockets">, + except?: WebSocket, ): Map<string, AwakeContextState> { const byPath = new Map<string, AwakeContextState & { updatedAt: number }>(); for (const ws of ctx.getWebSockets(AWAKE_WEBSOCKET_TAG)) { - if (ws.readyState !== WebSocket.OPEN) continue; + if (ws === except || ws.readyState !== WebSocket.OPEN) continue; const { path, since, updatedAt, activities } = awakeContextOf(ws); const rank = updatedAt ?? since; const prior = byPath.get(path); @@ -162,6 +200,8 @@ type AwakeDialedSocket = Pick<WebSocket, "accept" | "close" | "addEventListener" | "send">; +const UnansweredTries = z.object({ tries: z.number().int().positive(), at: z.number() }); + type AwakeSocketDeps = { path: string; /** The upgrade request to the accepting context. */ @@ -172,6 +212,12 @@ * socket before the socket closes, and while the context works, whenever it differs from what * was sent last. */ summary?: () => string; + /** `recoverAt()` changed: the context's alarm is set again from it. */ + recoveryChanged?: () => void; + /** How many times in a row the context went quiet with a summary unanswered, kept where the + * end of the object does not lose it. Read only when that happens again, and written then and + * when the catalog answers at last. Absent: counted in memory. */ + unanswered?: { count(): number; set(count: number): void }; }; /** The dialing side: one per context. `entered()` at every entry that is work; the socket and the @@ -188,6 +234,17 @@ #activityDirty = false; #sentSummary: string | undefined; #sentSummaryAt = 0; + /** Summaries that this socket sent and the catalog has not answered. */ + #unanswered = 0; + /** Runs while a quiet context keeps its socket for the answer to its last summary. */ + #answerWait: ReturnType<typeof setTimeout> | undefined; + /** A socket ended with a summary unanswered: the next one says the summary at once. */ + #sayAgain = false; + #recoverAt: number | undefined; + /** This object counted an unanswered summary, or was woken to say one again: the catalog's + * answer then takes the count away. */ + #counted = false; + #triesInMemory = 0; constructor(deps: AwakeSocketDeps) { this.#deps = deps; @@ -195,13 +252,46 @@ entered(): void { if (this.#deps.path === AWAKE_CONTEXT_PATH) return; - this.#lastEntryAt = Date.now(); + const now = Date.now(); + this.#lastEntryAt = now; + // work came back while the socket waited for its last answer: the socket stays + this.#stopAnswerWait(); + if (this.#recoverAt === undefined || this.#recoverAt <= now) + this.#recoverBy(now + AWAKE_RECOVER_AFTER_MS); this.#open(); if (this.#timer === undefined) this.#recheckIn(AWAKE_QUIET_MS); } + /** When the context's alarm must wake it, so that it says its summary again: from an entry + * until the catalog has answered all that the context said. Null: nothing is owed. */ + recoverAt(): number | null { + return this.#recoverAt ?? null; + } + + /** The context's alarm fired with nothing else due. True when the context then enters as for + * work, and so says its summary again: its time to say it has come, or THIS OBJECT NEVER + * ENTERED. The second case is the object after one that died with its summary unsaid: nothing + * in its memory says so, and the alarm that woke it is all that is left of the one before. It + * writes no wake record: the summary is of the log as it is. */ + recover(now: number): boolean { + if (this.#deps.path === AWAKE_CONTEXT_PATH) return false; + const neverEntered = this.#lastEntryAt === 0; + if (!neverEntered && (this.#recoverAt === undefined || this.#recoverAt > now)) return false; + if (this.#timer !== undefined) { + // The context works now: it says its summary as it goes, and its quiet close settles what + // is owed. No entry is made here, so the longest hold still counts from its last real one. + this.#recoverBy(now + AWAKE_RECOVER_AFTER_MS); + return false; + } + this.#counted = true; + this.entered(); + return true; + } + /** Coalesces rapid activity stack mutations and pushes the updated summary while the context - * is awake, without holding an idle context open or leaving a timer after close. */ + * is awake, without holding an idle context open or leaving a timer after close. The commit of + * what the summary says of the context for good (`events.iterate.com/itx/described`) calls it + * too, so a watcher of the catalog sees a new title within the debounce. */ activityChanged(): void { if (this.#deps.path === AWAKE_CONTEXT_PATH || this.#timer === undefined) return; this.#activityDirty = true; @@ -216,6 +306,12 @@ }, AWAKE_ACTIVITY_DEBOUNCE_MS); } + #recoverBy(at: number | undefined): void { + if (at === this.#recoverAt) return; + this.#recoverAt = at; + this.#deps.recoveryChanged?.(); + } + #recheckIn(ms: number): void { this.#timer = setTimeout(() => { this.#timer = undefined; @@ -247,17 +343,38 @@ throw new Error(`the dial was answered ${response.status}`); socket.accept(); this.#socket = socket; + this.#unanswered = 0; + const gone = () => { + if (this.#socket !== socket) return; + this.#socket = undefined; + if (this.#unanswered === 0) return; + // what this socket said may not be kept: the next socket says it at once + this.#unanswered = 0; + this.#sentSummary = undefined; + this.#sayAgain = true; + if (this.#answerWait === undefined) return; + this.#stopAnswerWait(); + this.#wentQuietUnanswered("its socket closed before the answer"); + }; + socket.addEventListener("close", gone); + socket.addEventListener("error", gone); + // each message of the far end answers one summary, in the order they were sent + socket.addEventListener("message", (event: { data?: unknown }) => { + if (this.#socket !== socket || this.#unanswered === 0) return; + this.#unanswered -= 1; + if (event?.data === AWAKE_SUMMARY_FAILED) { + // the catalog could not keep it: it is owed, and the next send says it whole + this.#sentSummary = undefined; + this.#sayAgain = true; + } + if (this.#unanswered === 0 && this.#answerWait !== undefined) this.#quietSettled(); + }); // the context went quiet while the dial was on its way: its summary still goes if (this.#timer === undefined) return this.#close(); - if (this.#activityDirty && this.#activityTimer === undefined) { + if (this.#sayAgain || (this.#activityDirty && this.#activityTimer === undefined)) { this.#activityDirty = false; this.#sendSummary(); } - const gone = () => { - if (this.#socket === socket) this.#socket = undefined; - }; - socket.addEventListener("close", gone); - socket.addEventListener("error", gone); }) .catch((error: unknown) => { this.#noDialBefore = Date.now() + AWAKE_REDIAL_AFTER_MS; @@ -266,13 +383,17 @@ path: this.#deps.path, message: error instanceof Error ? error.message : String(error), }); + // quiet already, and no socket came: nothing said the context's last summary + if (this.#timer === undefined && this.#answerWait === undefined) + this.#wentQuietUnanswered("its dial failed"); }) .finally(() => { this.#dialing = false; }); } - // A summary that fails to be made or sent is sent at a later wake: the log it folds stays. + // A summary that fails to be made or sent is owed, as an unanswered one is: the log it folds + // stays, and it is said again. #sendSummary(): void { if (!this.#socket || !this.#deps.summary) return; try { @@ -281,7 +402,10 @@ this.#socket.send(summary); this.#sentSummary = summary; this.#sentSummaryAt = Date.now(); + this.#sayAgain = false; + this.#unanswered += 1; } catch (error) { + this.#sayAgain = true; console.info({ event: "context.awake-summary-failed", path: this.#deps.path, @@ -290,19 +414,109 @@ } } + // The context is quiet: its last summary goes, and the socket closes when the catalog has + // answered it, or after `AWAKE_ANSWER_WAIT_MS`. #close(): void { if (this.#activityTimer !== undefined) { clearTimeout(this.#activityTimer); this.#activityTimer = undefined; } this.#activityDirty = false; + // a context that says nothing of itself owes the catalog nothing + if (!this.#deps.summary) return this.#closeAnswered(); this.#sendSummary(); + if (!this.#socket) { + // a dial on its way closes the socket it brings (`#open`), with the summary + if (!this.#dialing) this.#wentQuietUnanswered("it had no socket"); + return; + } + if (this.#unanswered === 0) return this.#quietSettled(); + this.#answerWait = setTimeout(() => { + this.#answerWait = undefined; + this.#closeSocket(); + this.#wentQuietUnanswered("the catalog did not answer in time"); + }, AWAKE_ANSWER_WAIT_MS); + } + + /** Quiet, and no answer is outstanding. Nothing is owed when the catalog kept the last summary. + * A summary is still owed when it could not be made or sent, or when the catalog could not + * keep it: an answer to an EARLIER summary settles neither. */ + #quietSettled(): void { + if (!this.#sayAgain) return this.#closeAnswered(); + this.#stopAnswerWait(); + this.#closeSocket(); + this.#wentQuietUnanswered("its last summary could not be made or sent, or was not kept"); + } + + #stopAnswerWait(): void { + if (this.#answerWait === undefined) return; + clearTimeout(this.#answerWait); + this.#answerWait = undefined; + } + + #closeSocket(): void { const socket = this.#socket; this.#socket = undefined; + this.#unanswered = 0; try { socket?.close(1000, "quiet"); } catch { // already closing } } + + /** Quiet, and the catalog answered all that the context said: nothing is owed. */ + #closeAnswered(): void { + this.#stopAnswerWait(); + this.#closeSocket(); + if (this.#counted) { + this.#counted = false; + this.#triesInMemory = 0; + this.#deps.unanswered?.set(0); + } + this.#recoverBy(undefined); + } + + /** Quiet with a summary that the catalog did not answer: the context's alarm wakes it to say + * the summary again, a longer wait at each try in a row, and after the last try nothing does. */ + #wentQuietUnanswered(why: string): void { + this.#sentSummary = undefined; + const tries = (this.#deps.unanswered?.count() ?? this.#triesInMemory) + 1; + const gaveUp = tries > AWAKE_SAY_AGAIN_TRIES; + this.#counted = !gaveUp; + this.#triesInMemory = gaveUp ? 0 : tries; + this.#deps.unanswered?.set(this.#triesInMemory); + if (gaveUp) { + console.warn({ + event: "context.awake-summary-gave-up", + path: this.#deps.path, + message: `the catalog did not answer this context's summary ${AWAKE_SAY_AGAIN_TRIES} times in a row: its row stays as it is until the context next has work`, + why, + }); + return this.#recoverBy(undefined); + } + console.info({ event: "context.awake-summary-unanswered", path: this.#deps.path, why, tries }); + this.#recoverBy( + Date.now() + Math.min(AWAKE_SAY_AGAIN_AFTER_MS * 2 ** (tries - 1), 30 * 60_000), + ); + } +} + +/** How often in a row a context went quiet with a summary unanswered, kept in the context's own + * storage, where the end of its object does not lose it (`AwakeSocketDeps.unanswered`). "In a + * row" is by time: each try comes at most 30 minutes after the one before, so a count that is + * older than an hour is of an earlier row of tries, and counts for nothing. */ +export function unansweredSummaryTries( + kv: Pick<SyncKvStorage, "get" | "put" | "delete">, +): NonNullable<AwakeSocketDeps["unanswered"]> { + return { + count: () => { + const kept = UnansweredTries.safeParse(kv.get("awake-summary-unanswered")).data; + return kept && Date.now() - kept.at < 60 * 60_000 ? kept.tries : 0; + }, + set: (tries) => { + if (tries > 0) kv.put("awake-summary-unanswered", { tries, at: Date.now() }); + else kv.delete("awake-summary-unanswered"); + }, + }; }
M core/itx/src/context/built-ins.ts
@@ -9,7 +9,7 @@ type ItxExpressionInput, InvokeHandle, } from "iterate/expression"; -import type { FacetSpec, IterateContextApi } from "iterate/api"; +import type { CatalogWatches, FacetSpec, IterateContextApi } from "iterate/api"; import { failureKind, ONCE_NOW, retryPlatformFailures } from "iterate/platform-retry"; import type { Cause } from "../cause.ts"; import { refusePlatformIdempotencyKeys, sha256Hex, stampCaller, type Caller } from "../caller.ts"; @@ -37,6 +37,7 @@ import { unavailableError } from "../unavailable.ts"; import { facetSpecOf, hostedFacetMarkerOf } from "../stream/core-processor.ts"; import { AWAKE_CONTEXT_PATH } from "./awake.ts"; +import { catalogWatchTicket, refuseLoadedCode, type CatalogWatchTicket } from "./catalog-watch.ts"; import { DurableObjectNameCodec } from "./paths.ts"; import { requestScriptRun } from "./run.ts"; import type { Connections } from "./connections.ts"; @@ -86,7 +87,11 @@ get(rpcStubKey: string): RpcStubHandle; }; rewriteRules: IterateContextApi["rewriteRules"]; - contexts: IterateContextApi["contexts"]; + contexts: Omit<IterateContextApi["contexts"], "watch"> & { + // The half of a watch that this table gates: the query, checked, as a ticket for the session's + // end, which alone holds the callback and the socket (../iterate-context.ts `#watchContexts`). + watch(query: unknown, options?: unknown): Promise<CatalogWatchTicket>; + }; facets: Omit<IterateContextApi["facets"], "get"> & { get(name: string, spec?: FacetSpec): FacetHandle; }; @@ -434,6 +439,20 @@ contexts() .getByName(DurableObjectNameCodec.stringify(AWAKE_CONTEXT_PATH)) .listContexts(options || {}), + // A ticket opens nothing: the session's end dials the catalog with it (catalog-watch.ts). + // It is answered here so that a watch passes this table as a list does. Both calls are + // for a caller that is no code (`refuseLoadedCode`). + watch: async (query, options) => { + refuseLoadedCode(deps.caller(), "watch"); + return catalogWatchTicket(query, options); + }, + watches: async (options) => { + refuseLoadedCode(deps.caller(), "watches"); + // The cast: workerd's RPC types read a window's bound, a pair, as a list. + return (await contexts() + .getByName(DurableObjectNameCodec.stringify(AWAKE_CONTEXT_PATH)) + .catalogWatches(options || {})) as unknown as CatalogWatches; + }, }, workers: workersRoot({ path,
A core/itx/src/context/catalog-watch.test.ts
@@ -0,0 +1,469 @@ +// The session's end of a watch of the catalog: what it does when the socket into the catalog +// drops, when a frame is missing, when the catalog refuses a query and when the session ends. The +// catalog's end is a socket that a test writes to by hand; the whole path, with a real catalog and +// a real capnweb session, is core/mind-worker/src/context/catalog-watch.test.ts. +import type { CatalogFrame } from "iterate/api"; +import { expect, onTestFinished, test, vi } from "vitest"; +import { + CatalogWatchRelay, + catalogWatchTicket, + isCatalogWatchTicket, + refuseLoadedCode, +} from "./catalog-watch.ts"; +import { + RPC_STUB_PAGER_KEEPALIVE_REQUEST, + RPC_STUB_PAGER_KEEPALIVE_RESPONSE, +} from "./rpc-stubs.ts"; + +test("a watch sends the query once, and the catalog's answer and changes come as frames", async () => { + const far = catalog(); + const relay = far.relay(); + const frames: CatalogFrame<unknown>[] = []; + const watching = relay.watch(ticket({ where: { status: "open" } }), (frame) => + frames.push(frame), + ); + const socket = await far.asked(); + expect(socket).toMatchObject({ + sent: [{ op: "subscribe", sub: "w1", query: { where: { status: "open" } } }], + }); + socket.say({ sub: "w1", q: "q", gen: "g", rev: 4, full: false, reset: [{ path: "/a" }] }); + using _watch = await watching; + socket.say({ gen: "g", rows: [{ path: "/b" }], d: [["w1", 4, 5, ["/a"], ["/b"]]] }); + expect(frames).toEqual([ + { type: "reset", gen: "g", rev: 4, q: "q", full: false, rows: [{ path: "/a" }] }, + { type: "change", gen: "g", from: 4, rev: 5, del: ["/a"], rows: [{ path: "/b" }] }, + ]); +}); + +test("a cursor goes with the query, and its answer is a resume frame", async () => { + const far = catalog(); + const relay = far.relay(); + const frames: CatalogFrame<unknown>[] = []; + const cursor = { gen: "g", rev: 3, q: "q", bound: [7, "/a"] as [number, string] }; + const watching = relay.watch(catalogWatchTicket({ limit: 5 }, { cursor }), (frame) => + frames.push(frame), + ); + const socket = await far.asked(); + expect(socket.sent[0]).toMatchObject({ cursor }); + socket.say({ sub: "w1", q: "q", gen: "g", rev: 6, full: true, ids: ["/a", "/b"], put: [] }); + using _watch = await watching; + expect(frames).toEqual([ + { type: "resume", gen: "g", rev: 6, q: "q", full: true, ids: ["/a", "/b"], rows: [] }, + ]); +}); + +test("one message of the catalog is one batch: every frame but the last says that more comes", async () => { + const far = catalog(); + const relay = far.relay(); + const batch: [string, boolean][] = []; + const first = relay.watch(ticket({ limit: 1 }), (frame) => batch.push(["first", !!frame.more])); + const socket = await far.asked(); + const second = relay.watch(ticket({ limit: 2 }), (frame) => batch.push(["second", !!frame.more])); + await far.asked(2); + for (const sub of ["w1", "w2"]) + socket.say({ sub, q: "q", gen: "g", rev: 1, full: false, reset: [] }); + using _first = await first; + using _second = await second; + batch.length = 0; + socket.say({ + gen: "g", + rows: [{ path: "/a" }], + d: [ + ["w1", 1, 2, [], ["/a"]], + ["w2", 1, 2, [], ["/a"]], + ], + }); + expect(batch).toEqual([ + ["first", true], + ["second", false], + ]); +}); + +test("a write that the catalog sends in several messages goes to its watchers as one batch, when the last has come", async () => { + const far = catalog(); + const relay = far.relay(); + const batch: [string, string[], boolean][] = []; + const watches = ["first", "second", "third"].map((name, at) => + relay.watch(ticket({ limit: at + 1 }), (frame) => + batch.push([name, (frame.rows as { path: string }[]).map((row) => row.path), !!frame.more]), + ), + ); + const socket = await far.asked(3); + for (const sub of ["w1", "w2", "w3"]) + socket.say({ sub, q: "q", gen: "g", rev: 1, full: false, reset: [] }); + const [first, second, third] = await Promise.all(watches); + using _first = first; + using _second = second; + batch.length = 0; + // the first of two messages of one write: nothing goes yet + socket.say({ + gen: "g", + more: true, + rows: [{ path: "/a" }], + d: [ + ["w1", 1, 2, [], ["/a"]], + ["w2", 1, 2, [], ["/a"]], + ], + }); + expect(batch).toEqual([]); + // the third watch goes away between the two messages + third![Symbol.dispose](); + socket.say({ + gen: "g", + rows: [{ path: "/b" }], + d: [ + ["w3", 1, 2, [], ["/b"]], + ["w1", 2, 3, [], ["/b"]], + ], + }); + expect(batch).toEqual([ + ["first", ["/a"], true], + ["second", ["/a"], true], + ["first", ["/b"], false], + ]); +}); + +test("the rest of a write that a dropped socket was sending does not come: its frames are not handed on", async () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + vi.spyOn(console, "info").mockImplementation(() => {}); + const far = catalog(); + const relay = far.relay(); + const frames: CatalogFrame<unknown>[] = []; + const watching = relay.watch(ticket({ limit: 5 }), (frame) => frames.push(frame)); + const socket = await far.asked(); + socket.say({ sub: "w1", q: "q", gen: "g", rev: 1, full: false, reset: [] }); + using _watch = await watching; + socket.say({ gen: "g", more: true, rows: [{ path: "/a" }], d: [["w1", 1, 2, [], ["/a"]]] }); + socket.drop(); + await vi.advanceTimersByTimeAsync(10); + const again = await far.asked(); + again.say({ sub: "w1", q: "q", gen: "g", rev: 3, full: false, reset: [{ path: "/a" }] }); + // the answer of the new socket alone: no half of the write that was cut + expect(frames.map((frame) => frame.type)).toEqual(["reset", "reset"]); +}); + +test("a frame that does not follow the one before asks the query again, and the watcher gets the whole answer", async () => { + const far = catalog(); + const relay = far.relay(); + const frames: CatalogFrame<unknown>[] = []; + const watching = relay.watch(ticket({ limit: 5 }), (frame) => frames.push(frame)); + const socket = await far.asked(); + socket.say({ sub: "w1", q: "q", gen: "g", rev: 4, full: false, reset: [] }); + using _watch = await watching; + // revision 5 never came + socket.say({ gen: "g", rows: [{ path: "/a" }], d: [["w1", 5, 6, [], ["/a"]]] }); + expect(frames).toHaveLength(1); + // asked again with no cursor: this end holds no row to make one from + expect(socket.sent.at(-1)).toEqual({ op: "subscribe", sub: "w1", query: { limit: 5 } }); + // a change that comes before the new answer is older than it, and is not passed on + socket.say({ gen: "g", rows: [], d: [["w1", 6, 7, ["/a"], []]] }); + socket.say({ sub: "w1", q: "q", gen: "g", rev: 7, full: false, reset: [{ path: "/b" }] }); + expect(frames.at(-1)).toMatchObject({ type: "reset", rev: 7, rows: [{ path: "/b" }] }); + expect(frames).toHaveLength(2); +}); + +test("a socket that drops under a live session is dialled again, and every watch gets its whole answer", async () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + vi.spyOn(console, "info").mockImplementation(() => {}); + const far = catalog(); + const relay = far.relay(); + const frames: CatalogFrame<unknown>[] = []; + const watching = relay.watch(ticket({ limit: 5 }), (frame) => frames.push(frame)); + const socket = await far.asked(); + socket.say({ sub: "w1", q: "q", gen: "g", rev: 4, full: false, reset: [{ path: "/a" }] }); + using _watch = await watching; + // a deploy resets the catalog's object: the socket closes + socket.drop(); + await vi.advanceTimersByTimeAsync(10); + const again = await far.asked(); + expect(again).not.toBe(socket); + expect(again).toMatchObject({ sent: [{ op: "subscribe", sub: "w1", query: { limit: 5 } }] }); + again.say({ sub: "w1", q: "q", gen: "h", rev: 1, full: false, reset: [{ path: "/b" }] }); + expect(frames.at(-1)).toEqual({ + type: "reset", + gen: "h", + rev: 1, + q: "q", + full: false, + rows: [{ path: "/b" }], + }); +}); + +test("a watch that starts while the socket is dialled again waits for that dial, and dials none of its own", async () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + vi.spyOn(console, "info").mockImplementation(() => {}); + const far = catalog(); + const relay = far.relay(); + const first = relay.watch(ticket({ limit: 1 }), () => {}); + const socket = await far.asked(); + socket.say({ sub: "w1", q: "q", gen: "g", rev: 4, full: false, reset: [] }); + using _first = await first; + // the socket drops, and the dial that takes its place is slow + let answerTheDial = () => {}; + far.before = new Promise<void>((resolve) => (answerTheDial = resolve)); + socket.drop(); + await vi.advanceTimersByTimeAsync(10); + const frames: CatalogFrame<unknown>[] = []; + const second = relay.watch(ticket({ limit: 2 }), (frame) => frames.push(frame)); + await vi.advanceTimersByTimeAsync(10); + expect(far).toMatchObject({ dials: 2 }); + answerTheDial(); + await vi.advanceTimersByTimeAsync(200); + const again = await far.asked(2); + // one socket for the session: the first watch is asked again on it, and the second asks once + expect(far).toMatchObject({ dials: 2 }); + expect(again.sent.toSorted((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)))).toEqual( + [ + { op: "subscribe", sub: "w1", query: { limit: 1 } }, + { op: "subscribe", sub: "w2", query: { limit: 2 } }, + ], + ); + again.say({ sub: "w2", q: "q", gen: "g", rev: 5, full: false, reset: [{ path: "/a" }] }); + using _second = await second; + expect(frames).toMatchObject([{ type: "reset", rows: [{ path: "/a" }] }]); +}); + +test("a socket whose keepalives go unanswered is taken for dead and dialled again", async () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + vi.spyOn(console, "info").mockImplementation(() => {}); + const far = catalog(); + const relay = far.relay(); + const watching = relay.watch(ticket({ limit: 5 }), () => {}); + const socket = await far.asked(); + socket.say({ sub: "w1", q: "q", gen: "g", rev: 4, full: false, reset: [] }); + using _watch = await watching; + // the runtime answers for a catalog that sleeps: the socket stays + socket.answersKeepalives = true; + await vi.advanceTimersByTimeAsync(60_000); + expect(far).toMatchObject({ dials: 1 }); + // a reset with no close: nothing answers any more + socket.answersKeepalives = false; + await vi.advanceTimersByTimeAsync(20_100); + expect(far).toMatchObject({ dials: 2 }); +}); + +test("when the catalog cannot be dialled again, every watch ends and its handle says why", async () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + const failed = vi.spyOn(console, "error").mockImplementation(() => {}); + const far = catalog(); + const relay = far.relay(); + const watching = relay.watch(ticket({ limit: 5 }), () => {}); + const socket = await far.asked(); + socket.say({ sub: "w1", q: "q", gen: "g", rev: 4, full: false, reset: [] }); + const watch = await watching; + far.refuses = true; + socket.drop(); + await vi.advanceTimersByTimeAsync(61_000); + await expect(watch.ended()).resolves.toMatch(/could not be reached again/); + expect(failed).toHaveBeenCalledWith( + expect.objectContaining({ event: "catalog-watch.redial-failed" }), + ); +}); + +test.for([ + { kind: "query", error: "not a query of the catalog", code: "INVALID_INPUT" }, + { + kind: "limit", + error: "the catalog holds at most 512 different live queries", + code: "WATCH_LIMIT", + }, + // the catalog's own failure has no code: a watcher reads the catalog in another way + { kind: "failed", error: "the catalog failed, and its log says why", code: undefined }, +])( + "a refusal of the catalog ($kind) rejects the call with its own code, and leaves no watch and no socket", + async ({ kind, error, code }) => { + const far = catalog(); + const relay = far.relay(); + const watching = relay.watch(ticket({ limit: 5 }), () => {}); + const socket = await far.asked(); + socket.say({ sub: "w1", kind, error }); + const refusal = await watching.then( + () => undefined, + (thrown: Error & { code?: string }) => thrown, + ); + expect(refusal).toMatchObject({ message: `contexts.watch: ${error}` }); + expect(refusal?.code).toBe(code); + expect(socket).toMatchObject({ closed: true }); + }, +); + +test("a batch ends with the last frame that goes: an entry for a watch that is gone, or is asked again, ends none", async () => { + const far = catalog(); + const relay = far.relay(); + const batch: [string, boolean][] = []; + const watches = ["first", "second", "third"].map((name, at) => + relay.watch(ticket({ limit: at + 1 }), (frame) => batch.push([name, !!frame.more])), + ); + const socket = await far.asked(3); + for (const sub of ["w1", "w2", "w3"]) + socket.say({ sub, q: "q", gen: "g", rev: 1, full: false, reset: [] }); + const [first, second, third] = await Promise.all(watches); + using _first = first; + using _second = second; + batch.length = 0; + // the third watch is gone when the catalog's message for all three comes + third![Symbol.dispose](); + socket.say({ + gen: "g", + rows: [{ path: "/a" }], + d: [ + ["w1", 1, 2, [], ["/a"]], + ["w2", 1, 2, [], ["/a"]], + ["w3", 1, 2, [], ["/a"]], + ], + }); + expect(batch).toEqual([ + ["first", true], + ["second", false], + ]); + // and the second has a gap in the next one: it is asked again, and the first ends the batch + batch.length = 0; + socket.say({ + gen: "g", + rows: [{ path: "/b" }], + d: [ + ["w1", 2, 3, [], ["/b"]], + ["w2", 7, 8, [], ["/b"]], + ], + }); + expect(batch).toEqual([["first", false]]); + expect(socket.sent.at(-1)).toEqual({ op: "subscribe", sub: "w2", query: { limit: 2 } }); +}); + +test("the watcher's dispose takes the query off, and the last watch closes the socket", async () => { + const far = catalog(); + const relay = far.relay(); + const first = relay.watch(ticket({ limit: 1 }), () => {}); + const socket = await far.asked(); + const second = relay.watch(ticket({ limit: 2 }), () => {}); + await far.asked(2); + for (const sub of ["w1", "w2"]) + socket.say({ sub, q: "q", gen: "g", rev: 1, full: false, reset: [] }); + const [one, two] = await Promise.all([first, second]); + one[Symbol.dispose](); + expect(socket.sent.at(-1)).toEqual({ op: "unsubscribe", sub: "w1" }); + expect(socket).toMatchObject({ closed: false }); + await expect(one.ended()).resolves.toBe("the watcher ended it"); + two[Symbol.dispose](); + expect(socket).toMatchObject({ closed: true }); +}); + +test("the session's end ends every watch, closes the socket, and takes no new watch", async () => { + const far = catalog(); + const relay = far.relay(); + const watching = relay.watch(ticket({ limit: 5 }), () => {}); + const socket = await far.asked(); + socket.say({ sub: "w1", q: "q", gen: "g", rev: 1, full: false, reset: [] }); + const watch = await watching; + relay.dispose(); + await expect(watch.ended()).resolves.toBe("the session ended"); + expect(socket).toMatchObject({ closed: true }); + await expect(relay.watch(ticket({ limit: 5 }), () => {})).rejects.toMatchObject({ + code: "UNAVAILABLE", + }); +}); + +test("loaded code is refused the watch and the list of what is watched, whatever its table lets through", () => { + for (const call of ["watch", "watches"] as const) { + expect(() => refuseLoadedCode({ app: true }, call)).toThrow( + expect.objectContaining({ code: "FORBIDDEN", message: expect.stringContaining(call) }), + ); + // a member's session, and the platform's own code + expect(() => refuseLoadedCode({}, call)).not.toThrow(); + } +}); + +test("a ticket is the query, checked: a callback, a second option or a query the catalog cannot answer is refused", () => { + expect(catalogWatchTicket({ under: "/agents", order: "path" }, undefined)).toEqual({ + $itxCatalogWatch: { query: { under: "/agents", order: "path" }, cursor: undefined }, + }); + expect(isCatalogWatchTicket(catalogWatchTicket({}, {}))).toBe(true); + expect(isCatalogWatchTicket([{ path: "/a" }])).toBe(false); + // a function where the options stand: the call did not come through a session's end + expect(() => catalogWatchTicket({}, () => {})).toThrow(/a session's call/); + expect(() => catalogWatchTicket({}, { cursor: {}, more: 1 })).toThrow(/a session's call/); + expect(() => catalogWatchTicket({ orderBy: "title" }, undefined)).toThrow(/orderBy/); + expect(() => catalogWatchTicket({ keys: ["/a"], limit: 2 }, undefined)).toThrow(/stands alone/); +}); + +function ticket(query: Parameters<typeof catalogWatchTicket>[0]) { + return catalogWatchTicket(query, undefined); +} + +/** The catalog's end of a watch socket, written to by hand. */ +function catalog() { + type Listener = (event: { data?: unknown; reason?: string }) => void; + const sockets: FarSocket[] = []; + const onSend: (() => void)[] = []; + class FarSocket { + sent: unknown[] = []; + closed = false; + answersKeepalives = false; + #listeners: Record<string, Listener[]> = {}; + accept() {} + send(raw: string) { + if (this.closed) throw new Error("the socket is closed"); + if (raw === RPC_STUB_PAGER_KEEPALIVE_REQUEST) { + if (this.answersKeepalives) + this.#emit("message", { data: RPC_STUB_PAGER_KEEPALIVE_RESPONSE }); + return; + } + this.sent.push(JSON.parse(raw)); + onSend.splice(0).forEach((heard) => heard()); + } + close() { + this.closed = true; + } + addEventListener(type: string, listener: Listener) { + (this.#listeners[type] ||= []).push(listener); + } + #emit(type: string, event: { data?: unknown; reason?: string }) { + for (const listener of this.#listeners[type] || []) listener(event); + } + /** The catalog sends a message. */ + say(message: unknown) { + this.#emit("message", { data: JSON.stringify(message) }); + } + /** The catalog's object is gone: the socket closes under the session. */ + drop() { + this.closed = true; + this.#emit("close", { reason: "the object was reset" }); + } + } + const far = { + dials: 0, + refuses: false, + /** A dial answers when this settles: a catalog that is slow to come back. */ + before: Promise.resolve(), + /** The newest socket, once the session's end has sent it `count` messages: it listens then. */ + asked: async (count = 1) => { + for (;;) { + const socket = sockets.at(-1); + if (socket && !socket.closed && socket.sent.length >= count) return socket; + await new Promise<void>((heard) => onSend.push(heard)); + } + }, + relay: () => { + const relay = new CatalogWatchRelay({ + dial: async () => { + far.dials += 1; + await far.before; + if (far.refuses) return { status: 503 }; + const socket = new FarSocket(); + sockets.push(socket); + return { status: 101, webSocket: socket as unknown as WebSocket }; + }, + waitUntil: () => {}, + }); + // its keepalive is a timer: a relay that outlives its test would dial in the next one + onTestFinished(() => relay.dispose()); + return relay; + }, + }; + return far; +}
A core/itx/src/context/catalog-watch.ts
@@ -0,0 +1,505 @@ +// catalog-watch.ts — THE SESSION'S END OF A WATCH OF THE CATALOG (`itx.contexts.watch`). A client +// holds a capnweb callback and nothing else: its frames ride the connection that its session has +// already. This file is what stands between that callback and the object that owns the rows: +// +// client ─capnweb, the session's one connection─► the session's end (../iterate-context.ts) +// the session's end ─ONE hibernated WebSocket for all of the session's watches─► /awake +// /awake (reactive-catalog.ts) ─a message for each write─► here ─`onFrame(frame)`─► client +// +// The socket is dialled at the session's first watch and closed with its last one, or with the +// session. It is the kernel's own dial into the context that accepts the awake sockets, as a +// context's awake socket is (awake.ts): no client, no loaded code and no other Worker can open one. +// The callback's stub lives here, in the stateless Worker, never in a Durable Object, so /awake +// hibernates under any number of watchers. +// +// A SOCKET THAT ENDS UNDER A LIVE SESSION (a deploy resets every Durable Object) is dialled again, +// and every watch is asked again with no cursor: each watcher gets a `reset` frame with the whole +// answer. A frame that does not follow the one before (`from`) is treated the same way. When the +// socket cannot be dialled again, every watch ends, and its handle's `ended()` says why. +import { RpcTarget } from "capnweb"; +import { z } from "zod"; +import type { CatalogCursor, CatalogFrame, CatalogQuery } from "iterate/api"; +import { codedError } from "iterate/lib"; +import type { Caller } from "../caller.ts"; +import { unavailableError } from "../unavailable.ts"; +import { redial } from "./redial.ts"; +import { CatalogRefusal, normalizeQuery } from "./reactive-catalog.ts"; +import { + disposeRpcStub, + RPC_STUB_PAGER_KEEPALIVE_REQUEST, + RPC_STUB_PAGER_KEEPALIVE_RESPONSE, +} from "./rpc-stubs.ts"; + +/** On a request to the context that accepts the awake sockets: the upgrade of a watch socket. */ +export const CATALOG_WATCH_HEADER = "x-itx-catalog-watch"; + +/** How long a watch socket that dropped under a live session is dialled again before every watch + * ends: as long as a lent stub's pager (rpc-stub-relay.ts). */ +const REDIAL_DEADLINE_MS = 60_000; +/** A subscribe that the catalog does not answer in this time fails. The first watch of a mind + * waits for the catalog's first fill, a page of 500 rows at a time. */ +const ANSWER_DEADLINE_MS = 60_000; +/** The runtime answers a keepalive for /awake, which sleeps on (the Durable Object's + * `setWebSocketAutoResponse`). Three in a row unanswered: the socket is dead, with no close. */ +const KEEPALIVE_EVERY_MS = 5_000; + +const WatchOptions = z.strictObject({ cursor: z.unknown().optional() }).optional(); + +/** WHAT THE BUILT-IN `contexts.watch(query, options)` ANSWERS: the query, checked, for the + * session's end, which alone holds a callback and a socket. The built-in is reached through a + * context's own table, as `contexts.list` is, so who may list may watch. A ticket is data: it + * opens nothing, and whoever else reads one has what it sent. */ +export type CatalogWatchTicket = { + $itxCatalogWatch: { query: CatalogQuery; cursor?: CatalogCursor }; +}; + +/** WHO MAY WATCH, AND WHO MAY ASK WHAT IS WATCHED: a session that is no code's (a member's, or + * the platform's own). Loaded code is refused, whatever its table lets through: `watches()` + * names the paths and the facts that other sessions ask for, which a rule that narrows + * `contexts.list` for some code does not narrow. The boundary is here, by the caller, and not by + * the name `contexts`. */ +export function refuseLoadedCode(caller: Pick<Caller, "app">, call: "watch" | "watches"): void { + if (caller.app) + throw codedError( + "FORBIDDEN", + `contexts.${call} is a session's call: loaded code reads the catalog with contexts.list(options)`, + ); +} + +export function catalogWatchTicket(query: unknown, options: unknown): CatalogWatchTicket { + const parsed = WatchOptions.safeParse(options); + if (!parsed.success) + throw codedError( + "INVALID_INPUT", + "contexts.watch(query, onFrame, { cursor? }) is a session's call: the callback stays at the session's end, and the only option is a cursor. Loaded code reads the catalog with contexts.list(options)", + ); + try { + normalizeQuery(query); + } catch (error) { + if (error instanceof CatalogRefusal) + throw codedError("INVALID_INPUT", `contexts.watch: ${error.message}`); + throw error; + } + return { + $itxCatalogWatch: { + // checked above, and again by the catalog itself, which trusts no ticket + query: query as CatalogQuery, + cursor: parsed.data?.cursor as CatalogCursor | undefined, + }, + }; +} + +export function isCatalogWatchTicket(value: unknown): value is CatalogWatchTicket { + // oxlint-disable-next-line iterate/simple-truthiness-check -- an answer of any shape: a table may send `contexts` to another object, which answers what it likes + return typeof value === "object" && value !== null && "$itxCatalogWatch" in value; +} + +/** What `itx.contexts.watch` answers: a handle whose dispose ends the watch. `ended()` settles + * when the watch ends in any other way, with the reason: the session ended, or the catalog could + * not be reached again. */ +export class CatalogWatchHandle extends RpcTarget { + readonly #end: () => void; + readonly #ended: Promise<string>; + constructor(end: () => void, ended: Promise<string>) { + super(); + this.#end = end; + this.#ended = ended; + } + ended(): Promise<string> { + return this.#ended; + } + [Symbol.dispose](): void { + this.#end(); + } +} + +/** A watcher's callback as this end holds it: a stub of the client's function, or the function. */ +type FrameCallback = ((frame: CatalogFrame<unknown>) => unknown) & { dup?(): FrameCallback }; + +type Watch = { + query: CatalogQuery; + onFrame: FrameCallback; + /** Of the watch's last frame: a change must follow it. */ + gen: string; + rev: number; + /** Its query went to the catalog on a socket: a socket that takes that one's place asks it + * again. A watch that still waits for the first socket sends its query itself. */ + asked: boolean; + /** Settles the call that made the watch, at the catalog's first answer or its refusal. */ + answered?: { + resolve: () => void; + reject: (error: Error) => void; + timer: ReturnType<typeof setTimeout>; + }; + end: (reason: string) => void; +}; + +/** What the catalog sends down a watch socket (reactive-catalog.ts, "THE WIRE"). */ +const SocketMessage = z.union([ + z.object({ + sub: z.string(), + q: z.string(), + gen: z.string(), + rev: z.number(), + full: z.boolean(), + reset: z.array(z.unknown()).optional(), + ids: z.array(z.string()).optional(), + put: z.array(z.unknown()).optional(), + }), + z.object({ + gen: z.string(), + rows: z.array(z.looseObject({ path: z.string() })), + d: z.array( + z.tuple([z.string(), z.number(), z.number(), z.array(z.string()), z.array(z.string())]), + ), + /** More of the same write comes in the next message. */ + more: z.literal(true).optional(), + }), + z.object({ + sub: z.string().optional(), + error: z.string(), + kind: z.enum(["query", "limit", "failed"]).optional(), + }), +]); + +type DialAnswer = { status: number; webSocket?: WebSocket | null; body?: ReadableStream | null }; + +/** ONE SESSION'S WATCHES, over one socket into the catalog. */ +export class CatalogWatchRelay { + readonly #dial: () => Promise<DialAnswer>; + readonly #waitUntil: (work: Promise<unknown>) => void; + readonly #watches = new Map<string, Watch>(); + #socket: WebSocket | undefined; + #opening: Promise<WebSocket> | undefined; + #keepalive: ReturnType<typeof setInterval> | undefined; + #names = 0; + #over = false; + /** The frames of a write that the catalog sends in several messages: they go when its last + * message has come, as one batch. */ + #heldFrames: { sub: string; watch: Watch; frame: CatalogFrame<unknown> }[] = []; + + constructor(deps: { + /** The upgrade request to the context that accepts the awake sockets. */ + dial: () => Promise<DialAnswer>; + waitUntil: (work: Promise<unknown>) => void; + }) { + this.#dial = deps.dial; + this.#waitUntil = deps.waitUntil; + } + + /** Asks the catalog to keep answering the ticket's query. Resolves when `onFrame` has RETURNED + * from the first frame, the answer: a watcher that awaits the call has the answer. Waiting for + * the function's return is what makes that true for a session that ends in another Worker, + * where the call's answer and a call of the function travel apart, in no order. Rejects with + * the catalog's reason when it refuses the query. */ + async watch(ticket: CatalogWatchTicket, onFrame: FrameCallback): Promise<CatalogWatchHandle> { + if (this.#over) throw unavailableError("disconnected", "contexts.watch: the session ended"); + const { query, cursor } = ticket.$itxCatalogWatch; + // dup first: the stub is the call's alone, and a watch outlives the call + const callback = onFrame.dup ? onFrame.dup() : onFrame; + const sub = `w${(this.#names += 1).toString(36)}`; + let settleEnded = (_reason: string) => {}; + const ended = new Promise<string>((resolve) => (settleEnded = resolve)); + const watch: Watch = { + query, + onFrame: callback, + gen: "", + rev: -1, + asked: false, + end: (reason) => { + if (this.#watches.get(sub) !== watch) return; + this.#watches.delete(sub); + if (watch.answered) { + clearTimeout(watch.answered.timer); + watch.answered.reject(unavailableError("disconnected", `contexts.watch: ${reason}`)); + } + disposeRpcStub(callback); + settleEnded(reason); + if (this.#watches.size === 0) this.#closeSocket(); + }, + }; + this.#watches.set(sub, watch); + // capnweb's death signal for the client's stub: the watch has nobody to tell + (callback as { onRpcBroken?: (broken: () => void) => void }).onRpcBroken?.(() => + this.#drop(sub, "the watcher's session broke"), + ); + try { + const socket = await this.#open(); + await new Promise<void>((resolve, reject) => { + watch.answered = { + resolve, + reject, + timer: setTimeout( + // our own deadline is an overload: the caller may ask again later, never at once + () => + reject(unavailableError("overloaded", "contexts.watch: the catalog did not answer")), + ANSWER_DEADLINE_MS, + ), + }; + socket.send(JSON.stringify({ op: "subscribe", sub, query, cursor })); + watch.asked = true; + }); + } catch (error) { + watch.answered = undefined; + this.#drop(sub, "the watch was refused"); + throw error; + } + return new CatalogWatchHandle(() => this.#drop(sub, "the watcher ended it"), ended); + } + + /** The session's end: every watch ends with it, and the socket closes. Final. */ + dispose(): void { + this.#over = true; + for (const watch of [...this.#watches.values()]) watch.end("the session ended"); + this.#closeSocket(); + } + + #drop(sub: string, reason: string): void { + const watch = this.#watches.get(sub); + if (!watch) return; + try { + this.#socket?.send(JSON.stringify({ op: "unsubscribe", sub })); + } catch { + // a socket that is closing takes its queries with it + } + watch.end(reason); + } + + #closeSocket(): void { + clearInterval(this.#keepalive); + this.#keepalive = undefined; + // the rest of a write that this socket was sending does not come: its watches are asked again + this.#heldFrames = []; + const socket = this.#socket; + this.#socket = undefined; + try { + socket?.close(1000, "no watch is left"); + } catch { + // already closing + } + } + + #open(): Promise<WebSocket> { + if (this.#socket) return Promise.resolve(this.#socket); + this.#opening ||= this.#dial() + .then(async (answer) => { + if (answer.status !== 101 || !answer.webSocket) { + await answer.body?.cancel(); + throw unavailableError( + "disconnected", + `contexts.watch: the catalog answered the dial ${answer.status}`, + ); + } + answer.webSocket.accept(); + // the session ended, or its last watch went, while the dial was on its way + if (this.#over || this.#watches.size === 0) { + answer.webSocket.close(1000, "no watch is left"); + throw unavailableError("disconnected", "contexts.watch: the session ended"); + } + this.#attach(answer.webSocket); + return answer.webSocket; + }) + .finally(() => (this.#opening = undefined)); + return this.#opening; + } + + #attach(socket: WebSocket): void { + this.#socket = socket; + let unanswered = 0; + clearInterval(this.#keepalive); + this.#keepalive = setInterval(() => { + if (this.#socket !== socket) return; + if (unanswered >= 3) return this.#lost(socket, "its keepalives went unanswered"); + // counted before the send: a send that throws is a keepalive that nobody answers + unanswered += 1; + try { + socket.send(RPC_STUB_PAGER_KEEPALIVE_REQUEST); + } catch { + // closing: its close event, or three unanswered keepalives, dials again + } + }, KEEPALIVE_EVERY_MS); + socket.addEventListener("message", (event) => { + unanswered = 0; + if (this.#socket !== socket || typeof event.data !== "string") return; + if (event.data === RPC_STUB_PAGER_KEEPALIVE_RESPONSE) return; + this.#received(event.data); + }); + const gone = (event: { reason?: string }) => this.#lost(socket, event.reason || "it closed"); + socket.addEventListener("close", gone); + socket.addEventListener("error", () => gone({ reason: "it failed" })); + } + + /** The socket ended under watches that live: dial again, and ask every query again. A watch + * that starts meanwhile waits for this dial (`#open`), and dials none of its own: two sockets + * of one session would each get the frames of the watches that were asked on it. */ + #lost(socket: WebSocket, why: string): void { + if (this.#socket !== socket) return; + this.#closeSocket(); + if (this.#over || this.#watches.size === 0) return; + const redialing = redial( + this.#dial as () => Promise<DialAnswer & { webSocket?: WebSocket | null }>, + () => this.#over || this.#watches.size === 0, + REDIAL_DEADLINE_MS, + ).then((redialed) => { + if (!redialed) throw unavailableError("disconnected", "contexts.watch: the session ended"); + if ("gaveUp" in redialed) { + console.error({ + event: "catalog-watch.redial-failed", + message: + "a session's watch socket dropped and could not be dialled again: its watches end", + why, + lastFailure: redialed.gaveUp, + }); + for (const watch of [...this.#watches.values()]) + watch.end("the catalog could not be reached again: watch again"); + throw unavailableError( + "disconnected", + "contexts.watch: the catalog could not be reached again: watch again", + ); + } + console.info({ event: "catalog-watch.redialed", why, attempt: redialed.dials }); + this.#attach(redialed.socket); + for (const [sub, watch] of this.#watches) if (watch.asked) this.#askAgain(sub); + return redialed.socket; + }); + this.#opening = redialing; + this.#waitUntil( + redialing + .then( + () => {}, + () => {}, + ) + .finally(() => { + if (this.#opening === redialing) this.#opening = undefined; + }), + ); + } + + /** The watcher's next frame is the whole answer: it holds a frame that the catalog's next one + * does not follow, or none that this socket knows of. */ + #askAgain(sub: string): void { + const watch = this.#watches.get(sub); + if (!watch) return; + watch.gen = ""; + watch.rev = -1; + try { + this.#socket?.send(JSON.stringify({ op: "subscribe", sub, query: watch.query })); + } catch { + // closing: the socket's end dials again and asks again + } + } + + #received(raw: string): void { + let message: z.infer<typeof SocketMessage>; + try { + message = SocketMessage.parse(JSON.parse(raw)); + } catch { + // the catalog's greeting, and its word that a query is taken off: nothing for a watcher + return; + } + if ("error" in message) { + const watch = this.#watches.get(message.sub || ""); + if (!watch) return; + if (!watch.answered) return watch.end(message.error); + clearTimeout(watch.answered.timer); + // Each kind has its own code, so that a watcher knows what to do: write another query, + // dispose a watch, or read the catalog in another way (`contexts.list`). The catalog's own + // failure has no code: it is a defect, and the catalog reported it. + const text = `contexts.watch: ${message.error}`; + watch.answered.reject( + message.kind === "query" + ? codedError("INVALID_INPUT", text) + : message.kind === "limit" + ? codedError("WATCH_LIMIT", text) + : new Error(text), + ); + return; + } + if ("d" in message) { + const rows = new Map(message.rows.map((row) => [row.path, row])); + for (const [sub, from, rev, del, put] of message.d) { + const watch = this.#watches.get(sub); + // a watch that waits for its answer takes no change: the answer is newer than it + if (!watch || watch.rev < 0) continue; + if (watch.gen !== message.gen || watch.rev !== from) { + this.#askAgain(sub); + continue; + } + watch.rev = rev; + this.#heldFrames.push({ + sub, + watch, + frame: { + type: "change", + gen: message.gen, + from, + rev, + del, + rows: put.map((path) => rows.get(path)), + }, + }); + } + // ONE WRITE IS ONE BATCH, however many messages the catalog cut it into: its frames go + // when the last message has come. `more` is over the frames that go: the last one to go + // ends the batch, whatever the catalog held for a watch that is gone or is asked again. + if (message.more) return; + const batch = this.#heldFrames.filter(({ sub, watch }) => this.#watches.get(sub) === watch); + this.#heldFrames = []; + batch.forEach(({ watch, frame }, at) => + this.#send(watch, at < batch.length - 1 ? { ...frame, more: true } : frame), + ); + return; + } + const watch = this.#watches.get(message.sub); + if (!watch) return; + watch.gen = message.gen; + watch.rev = message.rev; + const head = { gen: message.gen, rev: message.rev, q: message.q, full: message.full }; + const handed = this.#send( + watch, + message.reset + ? { type: "reset", ...head, rows: message.reset } + : { type: "resume", ...head, ids: message.ids || [], rows: message.put || [] }, + ); + const { answered } = watch; + if (!answered) return; + // the call that made the watch settles when the watcher's function has returned from this + // frame; until then the watch's end, or the deadline, still rejects it + void handed.then(() => { + if (watch.answered !== answered) return; + clearTimeout(answered.timer); + watch.answered = undefined; + answered.resolve(); + }); + } + + /** One frame to one watcher: settles when the watcher's function has returned from it, or + * thrown. A change waits for nobody: the catalog's next frame goes when it comes, and a + * function that throws is its own page's fault. */ + #send(watch: Watch, frame: CatalogFrame<unknown>): Promise<void> { + try { + return Promise.resolve(watch.onFrame(frame)).then(disposeRpcStub, () => {}); + } catch { + // a stub that broke: its `onRpcBroken` ends the watch + return Promise.resolve(); + } + } +} + +const relays = new WeakMap<object, CatalogWatchRelay>(); + +/** The one relay of a session: every context that the session reaches by `cd` shares its + * teardown, and so shares the socket. `register` puts the relay's end into that teardown. */ +export function catalogWatchRelayOf( + session: object, + make: () => CatalogWatchRelay, + register: (relay: CatalogWatchRelay) => void, +): CatalogWatchRelay { + let relay = relays.get(session); + if (!relay) { + relay = make(); + relays.set(session, relay); + register(relay); + } + return relay; +}
M core/itx/src/context/context-activity-stack.test.ts
@@ -25,7 +25,7 @@ describeScriptRunActivity, withTrackedActivity, } from "./context-activity-stack.ts"; -import { ContextCatalog, type ContextSummaryMessage } from "./context-catalog.ts"; +import { ContextCatalog, type ContextSummaryMessage, NotASummary } from "./context-catalog.ts"; import { ItxExpressionResolver } from "./itx-expression-rewriting.ts"; defineItxHost({ firstPartyFacets: {} }); @@ -206,7 +206,32 @@ }; const extracted = catalog.store("/agents/builder", JSON.stringify(summaryMsg)); - setAwakeActivities(ws, extracted); + setAwakeActivities(ws, extracted.activities); + // the row as a watched query serves it: the listing, and the two times the orders sort by + expect(extracted.row).toMatchObject({ + path: "/agents/builder", + activeMs: Date.parse("2026-11-25T12:00:05.000Z"), + createdMs: Date.parse("2026-11-25T12:00:00.000Z"), + eventCount: 8, + processors: ["agent"], + description: "Builds pull requests", + }); + expect(extracted.row).not.toHaveProperty("activities"); + expect(extracted.row).not.toHaveProperty("throughOffset"); + // a summary of an earlier offset is not kept, and so is no row for a watcher either + expect( + catalog.store("/agents/builder", JSON.stringify({ ...summaryMsg, throughOffset: 7 })), + ).toMatchObject({ row: undefined }); + expect(catalog.rowsAfter("", 10)).toEqual([extracted.row]); + expect(catalog.rowsAfter("/agents/builder", 10)).toEqual([]); + // one context's row, which a write that the watched copy owes is made again from + expect(catalog.row("/agents/builder")).toEqual(extracted.row); + expect(catalog.row("/agents/nobody")).toBeUndefined(); + // a message that is no summary is refused as such: saying it again would change nothing + expect(() => catalog.store("/agents/builder", "not JSON")).toThrow(NotASummary); + expect(() => catalog.store("/agents/builder", JSON.stringify({ eventCount: "many" }))).toThrow( + NotASummary, + ); // SQLite `context_catalog.summary` must NOT contain ephemeral `activities` const storedColumns = rawRows(); @@ -249,6 +274,8 @@ let open = 0; let busy = true; let stack: string[] = []; + // the accepting context answers each summary, as the catalog does (awake.ts) + const answerers: (() => void)[] = []; const awake = new AwakeSocket({ path: "/agents/a", busy: () => busy, @@ -262,8 +289,13 @@ close: () => { open -= 1; }, - send: (msg: string) => void sent.push(msg), - addEventListener: (() => undefined) as WebSocket["addEventListener"], + send: (msg: string) => { + sent.push(msg); + queueMicrotask(() => answerers.forEach((answer) => answer())); + }, + addEventListener: ((type: string, listener: () => void) => { + if (type === "message") answerers.push(listener); + }) as WebSocket["addEventListener"], }, }), }); @@ -503,8 +535,8 @@ const rows = db.prepare(query).all(...(bindings as never[])) as T[]; return { toArray: () => rows }; } - db.prepare(query).run(...(bindings as never[])); - return { toArray: () => [] as T[] }; + const { changes } = db.prepare(query).run(...(bindings as never[])); + return { toArray: () => [] as T[], rowsWritten: Number(changes) }; }; return { sql: { exec } as unknown as SqlStorage,
M core/itx/src/context/context-catalog.ts
@@ -2,11 +2,13 @@ // storage of the context that accepts the awake sockets (awake.ts). A row is the newest summary // its context sent (context-summary.ts). A list joins the rows with the open sockets, so "awake" // and live `activities` are never stored in SQLite: when a socket closes, both vanish at once. +// A watched query reads a copy of these rows, kept beside them (reactive-catalog.ts). import { z } from "zod"; import type { ContextListing, ContextListOptions } from "iterate/api"; import type { AwakeContextState } from "./awake.ts"; import { activeContextActivities, ContextActivity } from "./context-activity-stack.ts"; import { ContextSummary } from "./context-summary.ts"; +import type { CatalogRowInput } from "./reactive-catalog.ts"; /** Durable fields stored in SQLite `context_catalog.summary` (never live `activities`). */ const StoredContextSummary = ContextSummary.extend({ @@ -20,6 +22,10 @@ }); export type ContextSummaryMessage = z.infer<typeof ContextSummaryMessage>; +/** A message on an awake socket that is no summary: saying it again would be refused again. Any + * other failure of `store` is the catalog's own, and the summary is owed. */ +export class NotASummary extends Error {} + export class ContextCatalog { readonly #sql: SqlStorage; #tableMade = false; @@ -47,11 +53,22 @@ /** Keeps the durable part of `message` as `path`'s row unless the row is of a later offset, and * returns the live `activities` carried on the message so the caller can attach them to the - * open awake socket (never SQLite). A message that is no summary is refused with a thrown error. */ - store(path: string, message: string): ContextActivity[] | undefined { - const { activities, ...durable } = ContextSummaryMessage.parse(JSON.parse(message)); + * open awake socket (never SQLite). `row` is the row as a watched query serves it, when the + * message was kept: the copy beside this table takes it (reactive-catalog.ts). A message that + * is no summary is refused with `NotASummary`. */ + store( + path: string, + message: string, + ): { activities: ContextActivity[] | undefined; row: CatalogRowInput | undefined } { + let parsed: ContextSummaryMessage; + try { + parsed = ContextSummaryMessage.parse(JSON.parse(message)); + } catch (error) { + throw new NotASummary(error instanceof Error ? error.message : String(error)); + } + const { activities, ...durable } = parsed; this.#table(); - this.#sql.exec( + const { rowsWritten } = this.#sql.exec( `INSERT INTO context_catalog (path, through_offset, active_at, summary) VALUES (?, ?, ?, ?) ON CONFLICT (path) DO UPDATE SET through_offset = excluded.through_offset, @@ -63,9 +80,37 @@ durable.lastActivityAt || durable.lastEventAt || "", JSON.stringify(durable), ); - return activities; + return { activities, row: rowsWritten > 0 ? watchedRowOf(path, durable) : undefined }; } + /** One context's row as a watched query serves it: what the copy settles a write from that it + * could not make. Undefined when the catalog has none, or one that no longer parses. */ + row(path: string): CatalogRowInput | undefined { + this.#table(); + const stored = this.#sql + .exec<{ summary: string }>("SELECT summary FROM context_catalog WHERE path = ?", path) + .toArray()[0]; + const summary = stored && StoredContextSummary.safeParse(JSON.parse(stored.summary)); + return summary?.success ? watchedRowOf(path, summary.data) : undefined; + } + + /** A page of the rows, in path order, after the path `after`: what the copy for watched queries + * is first filled from. A row that no longer parses as a summary is left out. */ + rowsAfter(after: string, limit: number): CatalogRowInput[] { + this.#table(); + return this.#sql + .exec<{ path: string; summary: string }>( + "SELECT path, summary FROM context_catalog WHERE path > ? ORDER BY path LIMIT ?", + after, + limit, + ) + .toArray() + .flatMap(({ path, summary }) => { + const stored = StoredContextSummary.safeParse(JSON.parse(summary)); + return stored.success ? [watchedRowOf(path, stored.data)] : []; + }); + } + /** The contexts that match, the most recently active first. `awake` is the open sockets, by * path, with their live in-memory activities. Sleeping contexts never carry `activities`. */ list( @@ -171,4 +216,19 @@ const unlisted = candidates.filter((path) => !storedByPath.has(path)).map(toUnlistedAwake); return [...unlisted, ...listed].slice(0, limit); } +} + +/** A context's row as a watched query serves it (iterate/api `CatalogRow`): its listing, and the + * two times that the orders sort by, as numbers. The order `active` is this table's own order: + * the newest activity, or the newest event without one. A context with no time yet sorts last. */ +function watchedRowOf( + path: string, + { throughOffset: _, ...listing }: z.infer<typeof StoredContextSummary>, +): CatalogRowInput { + return { + path, + activeMs: Date.parse(listing.lastActivityAt || listing.lastEventAt || "") || 0, + createdMs: Date.parse(listing.createdAt || "") || 0, + ...listing, + }; }
M core/itx/src/context/itx-expression-rewriting.ts
@@ -53,7 +53,7 @@ rpcStubs: "live values clients lent here: `rpcStubs.list()` · `rpcStubs.get(key)`", rewriteRules: "this table, described: `await rewriteRules.list()`", contexts: - "the mind's catalog of its contexts, the most recently active first: `await itx.cd('/').contexts.list({ search?, under?, awake?, limit? })` → [{ path, awake?, lastActivityAt, eventCount, eventTypes, recentTypes, processors, description?, metadata? }]; a context describes itself with `itx.append({ type: 'events.iterate.com/itx/described', payload: { description, metadata } })`", + "the mind's catalog of its contexts, the most recently active first: `await itx.cd('/').contexts.list({ search?, under?, awake?, limit? })` → [{ path, awake?, lastActivityAt, eventCount, eventTypes, recentTypes, processors, description?, metadata? }]; a context describes itself with `itx.append({ type: 'events.iterate.com/itx/described', payload: { description, metadata } })`; a session that is no code's keeps a query answered with `contexts.watch({ where?, under?, childrenOf?, order?, limit? } | { keys } | { awake: true }, onFrame)`, and asks who watches what with `contexts.watches()`", facets: "a durable facet hosted here: `facets.get(name)` · `facets.abort(name, reason?)` resets that one facet", abort:
A core/itx/src/context/reactive-catalog.test.ts
@@ -0,0 +1,1145 @@ +// The reactive catalog against a brute-force oracle. The oracle shares no code with the engine: +// its own facts, its own byte order (Buffer.compare), a filter, a sort and a slice over a model of +// the rows. After EVERY operation each watcher's rows must equal the oracle's, each stored window +// must agree with the rows, and a write must send a frame to exactly the queries whose answer it +// changed. +import { DatabaseSync } from "node:sqlite"; +import type { CatalogCursor, CatalogOrder, CatalogQuery } from "iterate/api"; +import { expect, onTestFinished, test, vi } from "vitest"; +import { + CATALOG_LIMITS, + compareTextBinary, + ReactiveCatalog, + type CatalogRowInput, +} from "./reactive-catalog.ts"; + +test("holds against a brute-force oracle through random writes, queries in every order, hibernations and reconnects", () => { + const total = { writes: 0, frames: 0, quiet: 0, resumes: 0, rowsHeld: 0, hibernations: 0 }; + // a short run by default; the long run is 40 seeds of 3,000 operations + const seeds = Number(process.env.CATALOG_TEST_SEEDS || 6); + const steps = Number(process.env.CATALOG_TEST_STEPS || 800); + for (let seed = 1; seed <= seeds; seed++) { + const tally = runSeed(seed, steps); + for (const key of Object.keys(total) as (keyof typeof total)[]) total[key] += tally[key]; + } + console.info({ event: "reactive-catalog.random-run", seeds, steps, ...total }); + // the run did what it is for + expect(total.quiet).toBeGreaterThan(seeds * 20); + expect(total.resumes).toBeGreaterThan(seeds); + expect(total.rowsHeld).toBeGreaterThan(seeds); + expect(total.hibernations).toBeGreaterThan(seeds * 10); +}, 600_000); + +test("orders text as SQLite does, by UTF-8 bytes", () => { + const texts = ["", "a", "a/", "ab", "b", "é", "z", "", "", "😀", "😀a", "𐀀", "", "a", "a😀"]; + for (const a of texts) + for (const b of texts) + expect( + Math.sign(compareTextBinary(a, b)), + `${JSON.stringify(a)} against ${JSON.stringify(b)}`, + ).toBe(Math.sign(byteOrder(a, b))); + // the case that JavaScript's own comparison gets wrong: U+E000 is before an emoji in UTF-8 + expect(["😀", ""].sort()).toEqual(["😀", ""]); + expect(compareTextBinary("", "😀")).toBeLessThan(0); +}); + +test("the six steps of the acceptance test, counted", () => { + using object = fakeObject(); + const catalog = object.wake(); + catalog.fill(); + // 600 open and 400 closed rows + catalog.upsertMany( + Array.from({ length: 1000 }, (_, index) => + task(index, index < 600 ? "open" : "closed", 10_000 - index), + ), + ); + const client = new Client(); + client.connect(catalog); + const spec = { where: { status: "open" }, limit: 50 }; + const statements = () => catalog.counters.statements; + + // 1. the snapshot + let before = statements(); + client.subscribe(catalog, "open", spec); + const sub = client.subs.get("open")!; + expect(sub.rows).toMatchObject({ size: 50 }); + const snapshotStatements = statements() - before; + const paths = () => client.sorted(sub).map((row) => row.path); + expect(paths().slice(0, 1)).toEqual(["/tasks/t0000"]); + expect(paths().slice(49)).toEqual(["/tasks/t0049"]); + + // 2. a row enters: the old 50th leaves in the same frame + before = statements(); + sub.frames = 0; + expect(catalog.upsert(task(2000, "open", 20_000))).toMatchObject({ frames: 1, messages: 1 }); + expect(sub).toMatchObject({ frames: 1 }); + expect(paths()).toHaveLength(50); + expect(paths().slice(0, 1)).toEqual(["/tasks/t2000"]); + expect(sub.rows.has("/tasks/t0049")).toBe(false); + const enterStatements = statements() - before; + + // 3. a row leaves: the 51st takes its place in the same frame + sub.frames = 0; + before = statements(); + expect(catalog.upsert(task(2000, "closed", 20_001))).toMatchObject({ frames: 1 }); + expect(sub).toMatchObject({ frames: 1 }); + expect(paths()).toHaveLength(50); + expect(sub.rows.has("/tasks/t0049")).toBe(true); + const leaveStatements = statements() - before; + + // 4. a row moves inside the window + sub.frames = 0; + expect(catalog.upsert(task(25, "open", 30_000))).toMatchObject({ frames: 1 }); + expect(paths().slice(0, 1)).toEqual(["/tasks/t0025"]); + + // 5. 1,000 unrelated updates of each kind: no frame, and no statement beyond the write's own + sub.frames = 0; + before = statements(); + const seeks = catalog.counters.seeks; + for (let index = 0; index < 1000; index++) + catalog.upsert(task(600 + (index % 400), "closed", 40_000 + index)); + const closedStatements = (statements() - before) / 1000; + before = statements(); + for (let index = 0; index < 500; index++) + catalog.upsert(task(100 + index, "open", 5_000 - index)); + const outsideStatements = (statements() - before) / 500; + expect(sub).toMatchObject({ frames: 0 }); + expect(catalog.counters).toMatchObject({ seeks }); + // the write's own statements: one read of the row, one write of it, the revision, and for each + // of its five facts one entry out and one in, in the index of the order `active` alone + expect({ closedStatements, outsideStatements }).toEqual({ + closedStatements: 13, + outsideStatements: 13, + }); + + // 6. the watcher goes away, four rows change, and it comes back with its cursor + const heldBefore = new Set(sub.rows.keys()); + client.socket!.close(); + object.sockets.delete(client.socket!); + const woken = object.wake(); + woken.upsert(task(3000, "open", 50_000)); + woken.upsert(task(25, "closed", 50_001)); + woken.upsert(task(10, "closed", 50_002)); + woken.upsert(task(3, "open", 50_003)); + client.connect(woken); + client.subscribe(woken, "open", spec, true); + const answer = sub.answers.at(-1)!; + // The new row, the touched row, and ONE row that was never written while the watcher was away: + // two rows closed and one came, so the window took a row from after the watcher's bound. Its + // revision is old, and only the cursor's bound shows that the watcher lacks it. + expect(answer).toMatchObject({ reset: false, put: 3 }); + expect( + [...sub.rows.keys()].filter((path) => !heldBefore.has(path) && path !== "/tasks/t3000"), + ).toEqual(["/tasks/t0050"]); + expect(sub.rows).toMatchObject({ size: heldBefore.size }); + expect(answer.chars).toBeLessThan(sub.answers[0]!.chars / 3); + console.info({ + event: "reactive-catalog.acceptance", + snapshotStatements, + enterStatements, + leaveStatements, + closedStatements, + outsideStatements, + snapshotChars: sub.answers[0]!.chars, + resumeChars: answer.chars, + }); + expect(woken.verify()).toEqual([]); +}); + +test("a row's new activity writes the entries of one order, and a new fact one entry in each", () => { + using object = fakeObject(); + const catalog = object.wake(); + catalog.fill(); + const row = (activeMs: number, status: string) => ({ + path: "/agents/a/b", + activeMs, + createdMs: 5, + processors: ["agent"], + metadata: { status, tags: ["x", "y"] }, + }); + catalog.upsert(row(10, "open")); + // $parent, $under ×3, $processor, status, tags ×2 + const facts = 8; + const count = (table: string) => + object.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get() as { n: number }; + for (const table of ["rcat_fact_active", "rcat_fact_created", "rcat_fact_path"]) + expect(count(table), table).toEqual({ n: facts }); + + // the same row again: one read, and no write + let before = catalog.counters.statements; + expect(catalog.upsert(row(10, "open"))).toMatchObject({ changed: 0 }); + expect(catalog.counters.statements - before).toBe(1); + + // new activity: a read, the row, the revision, and each entry of `active` out and in + before = catalog.counters.statements; + expect(catalog.upsert(row(11, "open"))).toMatchObject({ changed: 1 }); + expect(catalog.counters.statements - before).toBe(3 + 2 * facts); + + // one fact changes and the time stays: one entry out and one in, in each of the three indexes + before = catalog.counters.statements; + expect(catalog.upsert(row(11, "closed"))).toMatchObject({ changed: 1 }); + expect(catalog.counters.statements - before).toBe(3 + 2 * 3); + for (const table of ["rcat_fact_active", "rcat_fact_created", "rcat_fact_path"]) + expect(count(table), table).toEqual({ n: facts }); +}); + +test("refuses a query it cannot answer exactly, with a reason", () => { + using object = fakeObject(); + const catalog = object.wake(); + catalog.fill(); + const client = new Client(); + client.connect(catalog); + const ask = (query: unknown) => { + client.errors = []; + client.subs.set("q", newSub({})); + catalog.handleWatchMessage( + client.socket as never, + JSON.stringify({ op: "subscribe", sub: "q", query }), + ); + return client.errors[0]; + }; + expect(ask({ where: { status: { not: "open" } } })).toMatch(/where\.status/); + expect(ask({ limit: 0 })).toMatch(/limit/); + expect(ask({ limit: 1.5 })).toMatch(/limit/); + expect(ask({ limit: CATALOG_LIMITS.limit + 1 })).toMatch(/limit/); + expect(ask({ orderBy: "title" })).toMatch(/orderBy/); + expect(ask({ order: "title" })).toMatch(/order/); + expect(ask({ keys: ["/a"], limit: 3 })).toMatch(/stands alone/); + expect(ask({ awake: true, order: "path" })).toMatch(/stands alone/); + expect(ask({ under: "tasks" })).toMatch(/starts with/); + expect(ask({ where: { a: "\ud800" } })).toMatch(/not plain text/); + expect(ask("status=open")).toMatch(/not a query/); + // a message that is no request + client.errors = []; + catalog.handleWatchMessage(client.socket as never, "not JSON"); + expect(client.errors[0]).toMatch(/one JSON object/); + // and a write the catalog cannot order + expect(() => catalog.upsert({ path: "/a", activeMs: Number.NaN, createdMs: 1 })).toThrow( + /activeMs/, + ); + expect(() => catalog.upsert({ path: "a", activeMs: 1, createdMs: 1 })).toThrow(/starts with/); + // a refused row in a batch undoes the batch + expect(() => + catalog.upsertMany([ + { path: "/ok", activeMs: 1, createdMs: 1 }, + { path: "/bad", activeMs: 1.5, createdMs: 1 }, + ]), + ).toThrow(); + client.subscribe(catalog, "all", { limit: 5 }); + expect(client.subs.get("all")!.rows).toMatchObject({ size: 0 }); +}); + +test("a cursor of another query gets every row, and a cursor of the same facts serves a larger limit", () => { + using object = fakeObject(); + const catalog = object.wake(); + catalog.fill(); + const model = new Map<string, ModelRow>(); + const rows = [ + ...Array.from({ length: 6 }, (_, index) => ({ + path: `/t/open${index}`, + activeMs: 10 - index, + createdMs: index, + metadata: { status: "open" }, + })), + ...Array.from({ length: 6 }, (_, index) => ({ + path: `/t/closed${index}`, + activeMs: 30 - index, + createdMs: index, + metadata: { status: "closed" }, + })), + ]; + catalog.upsertMany(rows); + rows.forEach((row, index) => + model.set(row.path, { ...row, processors: [], metadata: row.metadata, rev: index + 1 }), + ); + const client = new Client(); + client.connect(catalog); + client.subscribe(catalog, "q", { where: { status: "open" }, limit: 3 }); + const sub = client.subs.get("q")!; + expect(sub.answers.at(-1)).toMatchObject({ reset: true, put: 3 }); + + // the same facts, a larger limit: the cursor holds, and only the three new rows come + client.subscribe(catalog, "q", { where: { status: "open" }, limit: 6 }, true); + expect(sub.answers.at(-1)).toMatchObject({ reset: false, put: 3 }); + expectClientMatches(client, model, "a larger limit"); + + // other facts under the same name, with the old cursor: every closed row is newer than the + // cursor's bound and older than its revision, so a trusted cursor would send no row at all + client.subscribe(catalog, "q", { where: { status: "closed" }, limit: 3 }, true); + expect(sub.answers.at(-1)).toMatchObject({ reset: true, put: 3 }); + expectClientMatches(client, model, "another query"); + + // the same facts in another order: the bound is a key of the old order, so every row comes + client.subscribe(catalog, "q", { where: { status: "closed" }, order: "path", limit: 3 }, true); + expect(sub.answers.at(-1)).toMatchObject({ reset: true, put: 3 }); + expectClientMatches(client, model, "another order"); +}); + +test("the awake list comes from the sockets, with no row and no revision", () => { + using object = fakeObject(); + const catalog = object.wake(); + expect(catalog.awakeWatched()).toBe(false); + object.awake.set("/agents/a", { since: 111 }); + const client = new Client(); + client.connect(catalog); + client.subscribe(catalog, "awake", { awake: true }); + const sub = client.subs.get("awake")!; + expect([...sub.rows.values()]).toEqual([{ path: "/agents/a", since: 111 }]); + expect(catalog.awakeWatched()).toBe(true); + // the awake list needs no row: a watch of it alone keeps the catalog asleep + expect(catalog.active()).toBe(false); + // after a hibernation the window is found in storage, and the frame still arrives + const woken = object.wake(); + const working = { since: 222, activities: [{ key: "run", text: "Runs a script" }] }; + object.awake.set("/agents/b", working); + woken.awakeChanged("/agents/b", working); + object.awake.delete("/agents/a"); + woken.awakeChanged("/agents/a", undefined); + expect([...sub.rows.values()]).toEqual([{ path: "/agents/b", ...working }]); + client.unsubscribe(woken, "awake"); + expect(woken.awakeWatched()).toBe(false); +}); + +test("a window that no socket names goes at its first frame", () => { + using object = fakeObject(); + const catalog = object.wake(); + const client = new Client(); + client.connect(catalog); + client.subscribe(catalog, "open", { where: { status: "open" }, limit: 5 }); + // the socket ends with no close event, and the object hibernates + client.socket!.close(); + object.sockets.delete(client.socket!); + const woken = object.wake(); + expect(woken.watches().windows).toHaveLength(1); + woken.upsert({ path: "/t/1", activeMs: 1, createdMs: 1, metadata: { status: "open" } }); + expect(woken.watches().windows).toHaveLength(0); +}); + +test("nothing is kept before the first watch, and the first watch copies every row of the catalog", () => { + const source = Array.from({ length: 1_203 }, (_, index) => + task(index, index % 3 ? "open" : "closed", 1_000 + index), + ); + // a row that this collection refuses is left out, and the others are kept + source.push({ ...task(0, "open", 1), path: "/tasks/zz-bad", activeMs: 1.5 }); + source.sort((a, b) => byteOrder(a.path, b.path)); + const pages: number[] = []; + using object = fakeObject((after, limit) => { + const page = source.filter((row) => byteOrder(row.path, after) > 0).slice(0, limit); + pages.push(page.length); + return page; + }); + const catalog = object.wake(); + expect(catalog.active()).toBe(false); + // a write before the first watch is no write: no row, no revision + expect(catalog.upsert(task(9_000, "open", 1))).toMatchObject({ changed: 0, rev: 0 }); + expect(catalog.watches()).toMatchObject({ active: false, rows: 0 }); + + const client = new Client(); + client.connect(catalog); + client.subscribe(catalog, "open", { where: { status: "open" }, order: "path", limit: 4 }); + expect(pages).toEqual([500, 500, 204, 0]); + expect(catalog.watches()).toMatchObject({ active: true, rows: 1_203, rev: 1_203 }); + expect(client.sorted(client.subs.get("open")!).map((row) => row.path)).toEqual([ + "/tasks/t0001", + "/tasks/t0002", + "/tasks/t0004", + "/tasks/t0005", + ]); + // from then on a write is kept, and a later object does not fill again + const woken = object.wake(); + expect(woken.upsert(task(9_000, "open", 1))).toMatchObject({ changed: 1, rev: 1_204 }); + woken.fill(); + expect(pages).toHaveLength(4); +}); + +test("a fill that stopped goes on from the last page it wrote", () => { + const source = Array.from({ length: 1_100 }, (_, index) => task(index, "open", index)).sort( + (a, b) => byteOrder(a.path, b.path), + ); + let calls = 0; + using object = fakeObject((after, limit) => { + calls += 1; + if (calls === 2) throw new Error("the object died"); + return source.filter((row) => byteOrder(row.path, after) > 0).slice(0, limit); + }); + expect(() => object.wake().fill()).toThrow("the object died"); + const woken = object.wake(); + // a fill that began keeps what is written meanwhile + expect(woken.active()).toBe(true); + woken.fill(); + expect(woken.watches()).toMatchObject({ rows: 1_100, rev: 1_100 }); + // the second object read the two pages that were left, and the empty page that ends the fill + expect(calls).toBe(5); +}); + +test("tables of another schema are made again and filled again, and a cursor of the old ones gets every row", () => { + const source = [task(1, "open", 10), task(2, "open", 20)]; + using object = fakeObject((after, limit) => + source.filter((row) => byteOrder(row.path, after) > 0).slice(0, limit), + ); + const client = new Client(); + client.connect(object.wake()); + const spec = { where: { status: "open" }, limit: 5 }; + client.subscribe(object.wake(), "open", spec); + const sub = client.subs.get("open")!; + expect(sub.answers.at(-1)).toMatchObject({ reset: true, put: 2 }); + const generation = sub.gen; + + // a later release of the kernel keeps its tables in another shape + object.db.exec("UPDATE rcat_meta SET v = 'an earlier schema' WHERE k = 'schema'"); + client.socket!.close(); + object.sockets.delete(client.socket!); + const later = object.wake(); + client.connect(later); + // The watcher's cursor fits the new tables by its numbers alone: the two rows have the same + // revisions and the same keys again. Only the generation says that it is of other tables. + client.subscribe(later, "open", spec, true); + expect(sub.answers.at(-1)).toMatchObject({ reset: true, put: 2 }); + expect(sub).not.toMatchObject({ gen: generation }); + expect(later.watches({ verify: true })).toMatchObject({ active: true, rows: 2, faults: [] }); +}); + +test("a full socket and a full catalog refuse a query as a limit, not as a fault of the query", () => { + using object = fakeObject(); + const catalog = object.wake(); + catalog.fill(); + // eight sockets, each with as many queries as one may hold, all of them different + const clients = Array.from( + { length: CATALOG_LIMITS.windows / CATALOG_LIMITS.subsPerSocket }, + () => { + const client = new Client(); + client.connect(catalog); + return client; + }, + ); + clients.forEach((client, at) => { + for (let index = 0; index < CATALOG_LIMITS.subsPerSocket; index++) + client.subscribe(catalog, `s${index}`, { + where: { n: at * CATALOG_LIMITS.subsPerSocket + index }, + }); + }); + expect(catalog.watches().windows).toHaveLength(CATALOG_LIMITS.windows); + // one more for a socket that is full + clients[0]!.subscribe(catalog, "one-more", { limit: 3 }); + expect(clients[0]!).toMatchObject({ + refusals: [{ kind: "limit", error: expect.stringContaining("at most 64 watches") }], + }); + // one more for the catalog, on a socket that has room + const late = new Client(); + late.connect(catalog); + late.subscribe(catalog, "q", { limit: 3 }); + expect(late).toMatchObject({ + refusals: [ + { kind: "limit", error: expect.stringContaining("at most 512 different live queries") }, + ], + }); + // a query that another socket watches already is no new one + late.subscribe(catalog, "shared", { where: { n: 5 } }); + expect(late.refusals).toHaveLength(1); + // a socket that ended with no close event: at the limit its windows go, and there is room + clients[1]!.socket!.close(); + object.sockets.delete(clients[1]!.socket!); + const woken = object.wake(); + late.subscribe(woken, "q", { limit: 3 }); + expect(late.refusals).toHaveLength(1); + expect(woken.watches().windows).toHaveLength( + CATALOG_LIMITS.windows - CATALOG_LIMITS.subsPerSocket + 1, + ); + // a query that cannot be answered is the query's own fault + late.subscribe(woken, "bad", { limit: 0 }); + expect(late.refusals.at(-1)).toMatchObject({ kind: "query" }); +}); + +test("no fact of a row is cut in silence: the 65th tag is found, and a row with more facts than the index takes is refused whole", () => { + using object = fakeObject(); + const catalog = object.wake(); + catalog.fill(); + const tags = Array.from({ length: 65 }, (_, index) => `tag-${index}`); + catalog.upsert({ path: "/agents/tagged", activeMs: 1, createdMs: 1, metadata: { tags } }); + const client = new Client(); + client.connect(catalog); + client.subscribe(catalog, "last", { where: { tags: "tag-64" } }); + expect([...client.subs.get("last")!.rows.keys()]).toEqual(["/agents/tagged"]); + + // more facts than the catalog indexes for a row: refused, with the count + const many = Array.from({ length: CATALOG_LIMITS.factsPerRow }, (_, index) => `t${index}`); + expect(() => + catalog.upsert({ path: "/agents/huge", activeMs: 2, createdMs: 2, metadata: { tags: many } }), + ).toThrow(/has 2051 facts, and the catalog indexes at most 2048/); + // as the catalog hands it over: the row leaves the copy, and a watcher sees no old row of it + catalog.upsert({ path: "/agents/huge", activeMs: 1, createdMs: 1, metadata: { tags: ["t0"] } }); + client.subscribe(catalog, "huge", { keys: ["/agents/huge"] }); + expect(client.subs.get("huge")!.rows).toMatchObject({ size: 1 }); + vi.spyOn(console, "info").mockImplementation(() => {}); + catalog.keep({ path: "/agents/huge", activeMs: 2, createdMs: 2, metadata: { tags: many } }); + expect(client.subs.get("huge")!.rows).toMatchObject({ size: 0 }); + expect(catalog.watches()).toMatchObject({ owed: 0 }); + + // a key that starts with `$` is the kernel's: a query cannot name one that it has not + client.subscribe(catalog, "bad", { where: { $owner: "ada" } }); + expect(client.refusals.at(-1)).toMatchObject({ + kind: "query", + error: expect.stringContaining('no fact "$owner"'), + }); + client.subscribe(catalog, "good", { where: { $processor: "agent" } }); + expect(client.refusals).toHaveLength(1); +}); + +test("a write that the copy cannot make is owed: it is reported, and made again from the catalog's own row", () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + const reported = vi.spyOn(console, "error").mockImplementation(() => {}); + using object = fakeObject(); + const catalog = object.wake(); + catalog.fill(); + const client = new Client(); + client.connect(catalog); + client.subscribe(catalog, "open", { where: { status: "open" }, limit: 5 }); + const sub = client.subs.get("open")!; + + // the copy's store fails for one context's row + const boom = task(1, "open", 10); + object.catalogRows.set(boom.path, boom); + object.failing.when = (query, params) => + query.startsWith("INSERT INTO rcat_row") && params[0] === boom.path; + catalog.keep(boom); + expect(sub.rows).toMatchObject({ size: 0 }); + expect(catalog.watches()).toMatchObject({ owed: 1, rows: 0 }); + expect(reported).toHaveBeenCalledTimes(1); + + // another context's summary, before the owed write is due: it is kept, and the debt stays + catalog.keep(task(2, "open", 20)); + expect([...sub.rows.keys()]).toEqual(["/tasks/t0002"]); + expect(catalog.watches()).toMatchObject({ owed: 1 }); + + // an object that wakes knows of the debt, and a write a minute later settles it + object.failing.when = undefined; + vi.advanceTimersByTime(60_000); + const woken = object.wake(); + woken.keep(task(3, "closed", 30)); + expect([...sub.rows.keys()].toSorted()).toEqual(["/tasks/t0001", "/tasks/t0002"]); + expect(woken.watches({ verify: true })).toMatchObject({ owed: 0, faults: [] }); + expect(reported).toHaveBeenCalledTimes(1); +}); + +test("an owed write that keeps failing is tried eight times, at longer waits, and a later summary of that context pays it", () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + vi.spyOn(console, "error").mockImplementation(() => {}); + using object = fakeObject(); + const catalog = object.wake(); + catalog.fill(); + const boom = task(1, "open", 10); + object.catalogRows.set(boom.path, boom); + let tries = 0; + object.failing.when = (query, params) => { + const hit = query.startsWith("INSERT INTO rcat_row") && params[0] === boom.path; + if (hit) tries += 1; + return hit; + }; + catalog.keep(boom); + const waits: number[] = []; + let tick = 0; + for (let step = 0; step < 400 && tries < CATALOG_LIMITS.owedTries; step++) { + const before = tries; + vi.advanceTimersByTime(30_000); + tick += 30_000; + // any other context's summary is a chance to settle what is due + catalog.keep(task(2, "open", 100 + step)); + if (tries > before) { + waits.push(tick); + tick = 0; + } + } + // one minute, then doubled, thirty minutes at most + expect(waits).toEqual([60_000, 120_000, 240_000, 480_000, 960_000, 1_800_000, 1_800_000]); + // and then no more: the mark stays, for a person to see + vi.advanceTimersByTime(24 * 60 * 60_000); + catalog.keep(task(2, "open", 9_999)); + expect(tries).toBe(CATALOG_LIMITS.owedTries); + expect(catalog.watches()).toMatchObject({ owed: 1 }); + // the context's own next summary, which the copy can write, pays the debt + object.failing.when = undefined; + catalog.keep(task(1, "open", 10_000)); + expect(catalog.watches()).toMatchObject({ owed: 0, rows: 2 }); +}); + +test("a write that is longer than one message comes in parts, each but the last marked", () => { + using object = fakeObject(); + const catalog = object.wake(); + catalog.fill(); + const client = new Client(); + client.connect(catalog); + client.subscribe(catalog, "all", { limit: 50 }); + const parts: boolean[] = []; + client.onChange = (message) => parts.push(!!message.more); + // one transaction of 30 rows, each with a description of 20,000 characters + expect( + catalog.upsertMany( + Array.from({ length: 30 }, (_, index) => ({ + ...task(index, "open", index), + description: "x".repeat(20_000), + })), + ), + ).toMatchObject({ changed: 30, frames: 30 }); + expect(parts.length).toBeGreaterThan(1); + expect(parts).toEqual([...parts.slice(0, -1).map(() => true), false]); + expect(client.subs.get("all")!.rows).toMatchObject({ size: 30 }); +}); + +test("one write is one message for a socket, over all of its queries", () => { + using object = fakeObject(); + const catalog = object.wake(); + const client = new Client(); + client.connect(catalog); + client.subscribe(catalog, "open", { where: { status: "open" }, limit: 5 }); + client.subscribe(catalog, "byPath", { under: "/tasks", order: "path", limit: 5 }); + client.subscribe(catalog, "key", { keys: ["/tasks/t0001"] }); + client.messages = 0; + expect(catalog.upsert(task(1, "open", 10))).toMatchObject({ frames: 3, messages: 1 }); + expect(client).toMatchObject({ messages: 1 }); + for (const name of ["open", "byPath", "key"]) + expect(client.subs.get(name)!.rows.has("/tasks/t0001"), name).toBe(true); +}); + +// ── A Durable Object's SQLite, sockets and hibernation, in Node ── + +function sqlOf( + db: DatabaseSync, + failing: { when?: (query: string, params: unknown[]) => boolean }, +) { + // prepared once for each text, as a Durable Object's own `sql.exec` keeps its statements + const prepared = new Map<string, ReturnType<DatabaseSync["prepare"]>>(); + return { + exec(query: string, ...params: unknown[]) { + if (failing.when?.(query, params)) throw new Error("the store said no"); + let statement = prepared.get(query); + if (!statement) prepared.set(query, (statement = db.prepare(query))); + const rows = statement.all(...(params as never[])) as Record<string, unknown>[]; + return { toArray: () => rows }; + }, + }; +} + +class FakeSocket { + readyState = WebSocket.OPEN; + attachment: unknown = null; + onMessage: (raw: string) => void = () => {}; + send(raw: string) { + if (this.readyState !== WebSocket.OPEN) throw new Error("the socket is closed"); + this.onMessage(raw); + } + close() { + this.readyState = WebSocket.CLOSED; + } + serializeAttachment(value: unknown) { + this.attachment = structuredClone(value); + } + deserializeAttachment() { + return structuredClone(this.attachment); + } +} + +function fakeObject(seed: (after: string, limit: number) => CatalogRowInput[] = () => []) { + const db = new DatabaseSync(":memory:"); + const sockets = new Set<FakeSocket>(); + const awake = new Map<string, { since: number; activities?: { key: string; text: string }[] }>(); + const catalogRows = new Map<string, CatalogRowInput>(); + const failing: { when?: (query: string, params: unknown[]) => boolean } = {}; + const ctx = { + getWebSockets: () => [...sockets], + acceptWebSocket: (ws: FakeSocket) => void sockets.add(ws), + getTags: () => ["catalog-watch"], + storage: { + transactionSync<T>(work: () => T): T { + db.exec("BEGIN"); + try { + const answer = work(); + db.exec("COMMIT"); + return answer; + } catch (error) { + db.exec("ROLLBACK"); + throw error; + } + }, + }, + }; + return { + db, + sockets, + awake, + /** A new instance over the same storage and sockets: what a hibernation leaves. */ + wake: () => + new ReactiveCatalog(sqlOf(db, failing) as never, ctx as never, { + awake: () => awake, + seed, + row: (path) => catalogRows.get(path), + }), + /** The catalog's own rows, which a write that the copy owes is made again from. */ + catalogRows, + /** A statement that this answers true for throws, as a store that fails does. */ + failing, + [Symbol.dispose]: () => db.close(), + }; +} + +function task(index: number, status: string, at: number): Omit<ModelRow, "rev"> { + return { + path: `/tasks/t${String(index).padStart(4, "0")}`, + activeMs: at, + createdMs: index, + description: `Task ${index}`, + processors: ["task"], + metadata: { status }, + }; +} + +// ── The oracle ── + +/** A row as these tests write and read it. The engine keeps any body: here a description and a + * count, which change with no change of a sort value. */ +type ModelRow = { + path: string; + activeMs: number; + createdMs: number; + rev: number; + description?: string; + eventCount?: number; + processors: string[]; + metadata: Record<string, unknown>; +}; + +const bytes = new Map<string, Buffer>(); +function byteOrder(a: string, b: string): number { + const of = (text: string) => bytes.get(text) || bytes.set(text, Buffer.from(text)).get(text)!; + return Buffer.compare(of(a), of(b)); +} + +/** A window's order, written again here: the engine's own comparison is what is tested. */ +function windowOrder(order: CatalogOrder | undefined) { + return (a: ModelRow, b: ModelRow) => { + if (order === "path") return byteOrder(a.path, b.path); + const [x, y] = order === "created" ? [a.createdMs, b.createdMs] : [a.activeMs, b.activeMs]; + return x !== y ? y - x : -byteOrder(a.path, b.path); + }; +} + +// a write replaces a model row by a new object, so a row's facts are worked out once +const factsOfRow = new WeakMap<ModelRow, Set<string>>(); +function oracleFacts(row: ModelRow): Set<string> { + const known = factsOfRow.get(row); + if (known) return known; + const facts = new Set<string>(); + factsOfRow.set(row, facts); + const parts = row.path.split("/").filter(Boolean); + if (row.path !== "/") + facts.add(`$parent=${parts.length > 1 ? `/${parts.slice(0, -1).join("/")}` : "/"}`); + parts.forEach((_, index) => facts.add(`$under=/${parts.slice(0, index + 1).join("/")}`)); + for (const name of row.processors) facts.add(`$processor=${name}`); + for (const [key, raw] of Object.entries(row.metadata)) { + if (key.startsWith("$")) continue; + for (const item of Array.isArray(raw) ? raw : [raw]) + if (["string", "number", "boolean"].includes(typeof item)) + facts.add(`${key}=${String(item)}`); + } + return facts; +} + +function oracle(model: ReadonlyMap<string, ModelRow>, spec: CatalogQuery): ModelRow[] { + if (spec.keys) { + const wanted = new Set(spec.keys); + return [...model.values()].filter((row) => wanted.has(row.path)); + } + const wanted: string[] = Object.entries(spec.where || {}).map( + ([key, value]) => `${key}=${String(value)}`, + ); + if (spec.under && spec.under !== "/") wanted.push(`$under=${spec.under}`); + if (spec.childrenOf) wanted.push(`$parent=${spec.childrenOf}`); + return [...model.values()] + .filter((row) => { + const facts = oracleFacts(row); + return wanted.every((fact) => facts.has(fact)); + }) + .sort(windowOrder(spec.order)) + .slice(0, spec.limit || 50); +} + +/** A row as a watcher gets it: a key whose value is absent is not sent. */ +const wireRows = new WeakMap<ModelRow, ModelRow>(); +function wireRow(row: ModelRow): ModelRow { + const known = wireRows.get(row); + if (known) return known; + const wire = JSON.parse(JSON.stringify(row)) as ModelRow; + wireRows.set(row, wire); + return wire; +} + +// ── A watcher: a map of rows for each query, as the session's end keeps none and a page does ── + +type ClientSub = { + spec: CatalogQuery; + rows: Map<string, ModelRow>; + gen: string; + rev: number; + q: string; + /** Change frames since the test last looked. */ + frames: number; + answers: { reset: boolean; put: number; chars: number }[]; +}; + +function newSub(spec: CatalogQuery): ClientSub { + return { spec, rows: new Map(), gen: "", rev: -1, q: "", frames: 0, answers: [] }; +} + +class Client { + socket: FakeSocket | undefined; + subs = new Map<string, ClientSub>(); + errors: string[] = []; + refusals: { kind: string; error: string }[] = []; + onChange: (message: { more?: true }) => void = () => {}; + /** Messages since the test last looked. */ + messages = 0; + + connect(catalog: ReactiveCatalog) { + const socket = new FakeSocket(); + socket.onMessage = (raw) => this.#receive(raw); + this.socket = socket; + catalog.attachWatchSocket(socket as never); + } + + #receive(raw: string) { + const message = JSON.parse(raw); + if (message.hello) return; + this.messages += 1; + if (message.error) { + this.refusals.push({ kind: message.kind, error: message.error }); + return void this.errors.push(message.error); + } + if (message.unsubscribed) return; + if (message.sub) { + const sub = this.subs.get(message.sub)!; + if (message.reset) sub.rows = new Map(message.reset.map((row: ModelRow) => [row.path, row])); + else { + const keep = new Set<string>(message.ids); + for (const path of [...sub.rows.keys()]) if (!keep.has(path)) sub.rows.delete(path); + for (const row of message.put) sub.rows.set(row.path, row); + expect([...sub.rows.keys()].sort()).toEqual([...keep].sort()); + } + Object.assign(sub, { gen: message.gen, rev: message.rev, q: message.q }); + sub.answers.push({ + reset: !!message.reset, + put: (message.reset || message.put).length, + chars: raw.length, + }); + return; + } + this.onChange(message); + const rows = new Map<string, ModelRow>(message.rows.map((row: ModelRow) => [row.path, row])); + for (const [name, from, rev, del, put] of message.d as [ + string, + number, + number, + string[], + string[], + ][]) { + const sub = this.subs.get(name); + if (!sub) throw new Error(`a frame for the query ${name}, which this watcher does not hold`); + expect({ gen: message.gen, from }).toEqual({ gen: sub.gen, from: sub.rev }); + for (const path of del) expect(sub.rows.delete(path), `${name} deletes ${path}`).toBe(true); + for (const path of put) sub.rows.set(path, rows.get(path)!); + sub.rev = rev; + sub.frames += 1; + } + } + + /** The rows of a query in its own order. */ + sorted(sub: ClientSub): ModelRow[] { + return [...sub.rows.values()].sort(windowOrder(sub.spec.order)); + } + + cursorOf(sub: ClientSub): CatalogCursor { + const base = { gen: sub.gen, rev: sub.rev, q: sub.q }; + if (sub.spec.keys) return { ...base, have: [...sub.rows.keys()] }; + const last = this.sorted(sub).at(-1); + if (!last) return { ...base, bound: null }; + const at = + sub.spec.order === "path" ? 0 : sub.spec.order === "created" ? last.createdMs : last.activeMs; + return { ...base, bound: [at, last.path] }; + } + + subscribe(catalog: ReactiveCatalog, name: string, spec: CatalogQuery, withCursor = false) { + const had = this.subs.get(name); + // the cursor is of the rows that the watcher holds, in the order it held them + const cursor = withCursor && had ? this.cursorOf(had) : undefined; + const sub = had && withCursor ? had : newSub(spec); + sub.spec = spec; + this.subs.set(name, sub); + catalog.handleWatchMessage( + this.socket as never, + JSON.stringify({ op: "subscribe", sub: name, query: spec, cursor }), + ); + } + + unsubscribe(catalog: ReactiveCatalog, name: string) { + this.subs.delete(name); + catalog.handleWatchMessage( + this.socket as never, + JSON.stringify({ op: "unsubscribe", sub: name }), + ); + } +} + +/** A watcher's row, and the oracle's row that it was found equal to: a row is an object that a + * write replaces, on both sides, so each pair is compared in depth once. */ +const foundEqual = new WeakMap<ModelRow, ModelRow>(); + +function expectClientMatches(client: Client, model: ReadonlyMap<string, ModelRow>, label: string) { + for (const [name, sub] of client.subs) { + // a keys query has no order of its own + const order = (rows: ModelRow[]) => + sub.spec.keys ? rows.toSorted((a, b) => byteOrder(a.path, b.path)) : rows; + const wanted = order(oracle(model, sub.spec).map(wireRow)); + const have = order(client.sorted(sub)); + if ( + have.length === wanted.length && + have.every((row, at) => foundEqual.get(row) === wanted[at]) + ) + continue; + expect(have, `${label}: query ${name} ${JSON.stringify(sub.spec)}`).toEqual(wanted); + have.forEach((row, at) => foundEqual.set(row, wanted[at]!)); + } + expect(client, label).toMatchObject({ errors: [] }); +} + +// ── The random run ── + +function random(seed: number) { + let state = seed >>> 0; + const next = () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; + const int = (below: number) => Math.floor(next() * below); + return { next, int, pick: <T>(items: readonly T[]): T => items[int(items.length)]! }; +} + +// paths outside ASCII on purpose: U+E000 sorts BEFORE an emoji in UTF-8 and AFTER it in UTF-16 +const PATHS = [ + ...Array.from({ length: 36 }, (_, index) => `/tasks/t${String(index).padStart(2, "0")}`), + ...Array.from({ length: 6 }, (_, index) => `/agents/a${index}`), + "/agents/a0/sub", + "/agents/a1/sub/deeper", + "/docs/😀", + "/docs/x", + "/docs/é", + "/docs/z", + "/docs/😀/child", + "/x", +]; + +const QUERIES: CatalogQuery[] = [ + { where: { status: "open" }, limit: 1 }, + { where: { status: "open" }, limit: 2 }, + { where: { status: "open" }, limit: 7 }, + { where: { status: "open" }, limit: 50 }, + { where: { status: "closed" }, limit: 3 }, + { where: { status: "open", priority: "high" }, limit: 3 }, + { where: { tags: "pinned" }, limit: 5 }, + { where: { tags: "a", status: "open" }, limit: 4 }, + { where: { priority: 3 }, limit: 4 }, + { where: { flag: true }, limit: 2 }, + { under: "/tasks", limit: 7 }, + { under: "/docs", limit: 3 }, + { under: "/agents", where: { kind: "agent" }, limit: 3 }, + { childrenOf: "/agents", limit: 4 }, + { childrenOf: "/docs", limit: 2 }, + { where: { $processor: "agent" }, limit: 3 }, + { limit: 5 }, + { limit: 1 }, + // the other two orders, with one fact, two facts and none + { where: { status: "open" }, order: "created", limit: 3 }, + { where: { status: "open", priority: "high" }, order: "created", limit: 2 }, + { under: "/tasks", order: "created", limit: 6 }, + { order: "created", limit: 4 }, + { order: "created", limit: 1 }, + { where: { status: "open" }, order: "path", limit: 3 }, + { where: { tags: "a", status: "open" }, order: "path", limit: 2 }, + { childrenOf: "/docs", order: "path", limit: 3 }, + { under: "/docs", order: "path", limit: 4 }, + { order: "path", limit: 5 }, + { order: "path", limit: 1 }, +]; + +function randomRow(rng: ReturnType<typeof random>, clock: { now: number }): Omit<ModelRow, "rev"> { + const path = rng.pick(PATHS); + const agent = path.startsWith("/agents"); + // a few timestamps, to force ties; and now and then a fresh one, the newest of all + const activeMs = rng.next() < 0.25 ? (clock.now += 1 + rng.int(3)) : 1_000 + rng.int(6); + const tags = ["a", "b", "pinned"].filter(() => rng.next() < 0.3); + return { + path, + activeMs, + // a context is made once: its time mostly stays, and a few contexts share one + createdMs: rng.next() < 0.1 ? 500 + rng.int(4) : 100 + (path.length % 5), + ...(rng.next() < 0.3 && { description: `about ${rng.int(3)}` }), + ...(rng.next() < 0.5 && { eventCount: rng.int(3) }), + processors: agent ? ["agent"] : rng.next() < 0.2 ? ["task", "agent"] : [], + metadata: { + status: rng.pick(["open", "open", "closed"]), + priority: rng.pick(["high", "normal", 3]), + ...(tags.length > 0 && { tags }), + ...(agent && { kind: "agent" }), + ...(rng.next() < 0.2 && { flag: rng.next() < 0.5 }), + nested: { ignored: true }, + }, + }; +} + +function runSeed(seed: number, steps: number) { + const rng = random(seed); + using object = fakeObject(); + let catalog = object.wake(); + catalog.fill(); + const model = new Map<string, ModelRow>(); + let rev = 0; + const clock = { now: 2_000 }; + const clients: Client[] = []; + const away: Client[] = []; + const tally = { writes: 0, frames: 0, quiet: 0, resumes: 0, rowsHeld: 0, hibernations: 0 }; + + const valueOf = (row: Omit<ModelRow, "rev">) => JSON.stringify(wireRow({ ...row, rev: 0 })); + + /** Applies a write to the model as the engine must apply it. True when it changed a row. */ + const modelUpsert = (input: Omit<ModelRow, "rev">): boolean => { + const old = model.get(input.path); + if (old && valueOf(old) === valueOf(input)) return false; + rev += 1; + model.set(input.path, { ...input, rev }); + return true; + }; + const modelDelete = (path: string): boolean => { + if (!model.delete(path)) return false; + rev += 1; + return true; + }; + const answerOf = (spec: CatalogQuery) => + JSON.stringify(oracle(model, spec).map((row) => [row.path, row.rev])); + + for (let step = 0; step < steps; step++) { + const roll = rng.next(); + const label = `seed ${seed} step ${step}`; + + if (roll < 0.52) { + // one write: a frame goes to exactly the queries whose answer changed + const watched = clients.flatMap((client) => + [...client.subs].map(([name, sub]) => ({ name, sub, before: answerOf(sub.spec) })), + ); + for (const entry of watched) entry.sub.frames = 0; + let changed: boolean; + let result; + const kind = rng.next(); + if (kind < 0.12 && model.size > 0) { + const path = rng.pick([...model.keys()]); + changed = modelDelete(path); + result = catalog.deleteMany([path]); + } else if (kind < 0.2 && model.size > 0) { + // the same row again: no revision, no frame + const { rev: _rev, ...same } = model.get(rng.pick([...model.keys()]))!; + changed = modelUpsert(same); + result = catalog.upsert(same); + } else { + const input = randomRow(rng, clock); + changed = modelUpsert(input); + result = catalog.upsert(input); + } + expect(result, label).toMatchObject({ rev, changed: changed ? 1 : 0 }); + tally.writes += 1; + let expectedFrames = 0; + for (const { sub, before, name } of watched) { + const frames = before === answerOf(sub.spec) ? 0 : 1; + // said only when it fails: an assertion for each query at each write is most of the run + if (sub.frames !== frames) + expect(sub, `${label}: frames for ${name} ${JSON.stringify(sub.spec)}`).toMatchObject({ + frames, + }); + expectedFrames += sub.frames; + } + tally.frames += expectedFrames; + if (expectedFrames === 0) tally.quiet += 1; + } else if (roll < 0.58) { + // a batch in one transaction + const inputs = Array.from({ length: 2 + rng.int(5) }, () => randomRow(rng, clock)); + const changed = inputs.filter((input) => modelUpsert(input)).length; + expect(catalog.upsertMany(inputs), label).toMatchObject({ rev, changed }); + } else if (roll < 0.6 && model.size > 3) { + const paths = [rng.pick([...model.keys()]), rng.pick([...model.keys()]), "/never/there"]; + const changed = paths.filter((path) => modelDelete(path)).length; + expect(catalog.deleteMany(paths), label).toMatchObject({ changed }); + } else if (roll < 0.7) { + if (clients.length < 5 && (clients.length === 0 || rng.next() < 0.4)) { + const client = new Client(); + client.connect(catalog); + clients.push(client); + } + const client = rng.pick(clients); + if (client.subs.size < 6) + client.subscribe( + catalog, + `s${step}`, + rng.next() < 0.15 + ? { keys: Array.from({ length: 1 + rng.int(6) }, () => rng.pick(PATHS)) } + : rng.pick(QUERIES), + ); + } else if (roll < 0.74 && clients.length > 0) { + const client = rng.pick(clients); + if (client.subs.size > 0) client.unsubscribe(catalog, rng.pick([...client.subs.keys()])); + } else if (roll < 0.77 && clients.length > 0) { + // the same name, another query: the old window is let go + const client = rng.pick(clients); + if (client.subs.size > 0) + client.subscribe(catalog, rng.pick([...client.subs.keys()]), rng.pick(QUERIES)); + } else if (roll < 0.82) { + // hibernation: the object's memory goes, its storage and its sockets stay + catalog = object.wake(); + tally.hibernations += 1; + } else if (roll < 0.87 && clients.length > 0) { + // a watcher goes away, with a close event or with none + const client = clients.splice(rng.int(clients.length), 1)[0]!; + const socket = client.socket!; + socket.close(); + object.sockets.delete(socket); + if (rng.next() < 0.5) catalog.handleWatchClose(socket as never); + away.push(client); + } else if (roll < 0.94 && away.length > 0) { + // it comes back on a new socket, with its cursor for each query or with none + const client = away.splice(rng.int(away.length), 1)[0]!; + client.connect(catalog); + const withCursor = rng.next() < 0.8; + for (const [name, sub] of [...client.subs]) { + const held = sub.rows.size; + client.subscribe(catalog, name, sub.spec, withCursor); + const answer = client.subs.get(name)!.answers.at(-1)!; + if (withCursor && !answer.reset) { + tally.resumes += 1; + tally.rowsHeld += Math.max(0, held - answer.put); + } + } + clients.push(client); + } else { + // six queries of the pool, asked anew by a watcher that holds nothing, against the oracle + const fresh = new Client(); + fresh.connect(catalog); + for (let index = 0; index < 6; index++) + fresh.subscribe(catalog, `f${index}`, rng.pick(QUERIES)); + expectClientMatches(fresh, model, `${label}: asked anew`); + catalog.handleWatchClose(fresh.socket as never); + object.sockets.delete(fresh.socket!); + } + for (const client of clients) expectClientMatches(client, model, label); + expect(catalog.verify(), label).toEqual([]); + } + return tally; +}
A core/itx/src/context/reactive-catalog.ts
@@ -0,0 +1,1599 @@ +// reactive-catalog.ts — THE CATALOG AS A COLLECTION THAT ANSWERS REACTIVE QUERIES. It runs in the +// context that accepts the awake sockets (awake.ts), beside the catalog's own rows +// (context-catalog.ts), in tables of its own (`rcat_*`). Nothing under it changes: a context still +// folds its log into a summary and sends it down its awake socket. This file keeps a copy of what +// arrives, as a row with an index of facts, and tells the watchers of a query what a write changed. +// +// A ROW is one context: its path, when it was last active, when it was made, and what its listing +// says of it (iterate/api `CatalogRow`). Its FACTS are every scalar at the top of its metadata (and +// each scalar of a list there), and the kernel's own: `$parent`, `$under` for the path and each +// ancestor, `$processor`. +// +// A WATCHED QUERY is a window over that index: the rows that hold every fact the query names, in +// one order, up to a limit. No query is known ahead of time: a watcher sends one at run time, and +// any two watchers may send different ones (iterate/api `CatalogQuery`). +// +// THE ORDERS. Each is total (the path breaks every tie) and each has one index of the facts: +// active the newest activity first rcat_fact_active (k, v, active_at DESC, path DESC) +// created the newest context first rcat_fact_created (k, v, created_at DESC, path DESC) +// path by path, A to Z rcat_fact_path (k, v, path) +// A row's new activity moves its entries of `active` alone. The entries of the other two change +// only when the row's facts do, so two more orders cost a common write nothing. +// +// For a window the object keeps two values, in SQLite: its SIZE and its BOUND, the sort key of its +// last row (Zero's `take` operator). A write changes a window only when the row's old key or its +// new key is at or before the bound. Any other write costs the window nothing: no statement, no +// frame. A row that leaves a full window is replaced by the one row after the bound, in the same +// frame. +// +// Three kinds of query: +// a window — `{ where, under, childrenOf, order, limit }` +// keys — `{ keys: [paths] }`: exactly these rows, which is what a join asks for +// awake — `{ awake: true }`: the contexts that hold an awake socket now, from the sockets alone +// +// TEXT IS ORDERED AS SQLITE ORDERS IT: a path is compared as UTF-8 bytes, here and in every +// watcher (`compareTextBinary`). JavaScript's `<` puts U+E000 after an emoji, and UTF-8 puts it +// before. +// +// NOTHING IS KEPT UNTIL SOMEONE WATCHES. The first watch copies every row of the catalog, a page +// at a time (`fill`), and from then on each summary that the catalog keeps is written here too. A +// mind that never watches pays for no index. +// +// THE WIRE, as JSON on a hibernated WebSocket of its own. Its other end is the session's end +// (catalog-watch.ts), never a client: a client holds a capnweb callback. +// to the object: { op: "subscribe", sub, query, cursor? } · { op: "unsubscribe", sub } +// the answer to a subscribe: { sub, q, gen, rev, full, reset: [rows] }, or with a cursor the +// object accepts { sub, q, gen, rev, full, ids: [paths], put: [rows] }: every +// path of the window, and only the rows the watcher lacks +// a change: { gen, rows: [rows], d: [[sub, from, rev, [paths to delete], [paths to put]]] } +// ONE message for each socket and write (or batch of writes), over all of the +// socket's queries, so a join never sees half of a write. `from` is the revision +// of the query's frame before. A write that is longer than +// `CATALOG_LIMITS.messageChars` is cut into several messages, and each but the +// last says `more: true`: the session's end hands them on as one batch. +// a refusal: { sub, kind: "query" | "limit" | "failed", error }: the query cannot be +// answered, a limit is reached, or the catalog itself failed +// +// A watcher that comes back sends its cursor `{ gen, rev, q, bound }`: the generation, the +// revision of its last frame, the name of what the query selects, and the sort key of the last row +// it holds. A row is HELD when it is unchanged since `rev` and its key is at or before `bound`. +// The second half matters: a row that backfilled while the watcher was away has an old revision, +// and the watcher never had it. +import { z } from "zod"; +import type { CatalogOrder, CatalogWatches } from "iterate/api"; +import { reportIssue } from "iterate/lib"; +import type { AwakeContextState } from "./awake.ts"; +import { activeContextActivities } from "./context-activity-stack.ts"; + +export const CATALOG_LIMITS = { + /** The most rows of one window. */ + limit: 500, + /** The most live windows of the object, over all sockets. */ + windows: 512, + /** The most queries of one socket. */ + subsPerSocket: 64, + predicates: 8, + keys: 500, + /** No summary that the catalog keeps comes near it (4,000 characters of metadata, a path of + * 512). A row with more is REFUSED, never cut: a fact that is not indexed would be a row that + * a query misses. */ + factsPerRow: 2_048, + factKeyChars: 80, + factValueChars: 200, + pathChars: 512, + /** The most characters of a row's stored JSON. A summary's own limits keep a row far below it: + * 200 event types, 4,000 characters of metadata, 2,000 of description. */ + bodyChars: 32_000, + subChars: 16, + /** A change message is cut into parts of about this many characters. */ + messageChars: 256_000, + /** How many rows one transaction of the first fill writes. */ + fillPage: 500, + /** How many times a write that the copy owes is made again before it is left as it is. */ + owedTries: 8, +} as const; + +const SCHEMA = "1"; +const WATCH_SOCKET_TAG = "catalog-watch"; + +/** A refusal that the watcher or the writer caused: its message goes back to them. */ +export class CatalogRefusal extends Error {} + +/** A refusal that is no fault of the query: the catalog, or the watcher's socket, holds as many + * live queries as it may. */ +export class CatalogLimit extends Error {} + +// ── The order ── + +/** No lone surrogate: such a text has one UTF-8 form, which is what SQLite stores and compares. */ +function wellFormed(text: string): boolean { + for (let i = 0; i < text.length; i++) { + const unit = text.charCodeAt(i); + if (unit < 0xd800 || unit > 0xdfff) continue; + const next = text.charCodeAt(i + 1); + if (unit > 0xdbff || !(next >= 0xdc00 && next <= 0xdfff)) return false; + i += 1; + } + return true; +} + +/** As SQLite's BINARY collation compares two texts: by their UTF-8 bytes. For well-formed strings + * that differs from UTF-16 code unit order in one case: a surrogate (a code point from U+10000) + * against a code unit from U+E000 to U+FFFF. No bytes are made. */ +export function compareTextBinary(a: string, b: string): number { + if (a === b) return 0; + const shared = Math.min(a.length, b.length); + for (let i = 0; i < shared; i++) { + const x = a.charCodeAt(i); + const y = b.charCodeAt(i); + if (x === y) continue; + const xSurrogate = x >= 0xd800 && x <= 0xdfff; + const ySurrogate = y >= 0xd800 && y <= 0xdfff; + if (xSurrogate === ySurrogate) return x < y ? -1 : 1; + return xSurrogate ? 1 : -1; + } + return a.length < b.length ? -1 : 1; +} + +/** Where a row stands in a window: the order's own value (0 for the order `path`), then the path. */ +type SortKey = [at: number, path: string]; + +/** Each order's index of the facts, and the column that holds the order's own value there and in + * `rcat_row`. The order `path` has none: the path is the whole key. */ +const ORDER_INDEX = { + active: { facts: "rcat_fact_active", column: "active_at" }, + created: { facts: "rcat_fact_created", column: "created_at" }, + path: { facts: "rcat_fact_path", column: "" }, +} as const satisfies Record<CatalogOrder, { facts: string; column: string }>; + +/** Negative: `a` is before `b` in the window. */ +function compareSortKeys(order: CatalogOrder, a: SortKey, b: SortKey): number { + if (order === "path") return compareTextBinary(a[1], b[1]); + if (a[0] !== b[0]) return a[0] > b[0] ? -1 : 1; + return -compareTextBinary(a[1], b[1]); +} + +/** `ORDER BY` in a window's order (`forward`) or against it, for the table alias `at`. */ +function orderTerms(order: CatalogOrder, at: string, forward: boolean): string { + const { column } = ORDER_INDEX[order]; + if (!column) return `${at}.path ${forward ? "ASC" : "DESC"}`; + const direction = forward ? "DESC" : "ASC"; + return `${at}.${column} ${direction}, ${at}.path ${direction}`; +} + +/** The rows strictly after `key` in a window's order (`after`), or strictly before it. */ +function beyond(order: CatalogOrder, at: string, after: boolean, key: SortKey): Statement { + const { column } = ORDER_INDEX[order]; + if (!column) return { sql: `${at}.path ${after ? ">" : "<"} ?`, args: [key[1]] }; + return { sql: `(${at}.${column}, ${at}.path) ${after ? "<" : ">"} (?, ?)`, args: [...key] }; +} + +// ── Facts ── + +type Fact = [key: string, value: string]; +const factId = ([key, value]: Fact) => `${key}\0${value}`; + +function usableFact(key: string, value: string): boolean { + return ( + key.length > 0 && + key.length <= CATALOG_LIMITS.factKeyChars && + value.length <= CATALOG_LIMITS.factValueChars && + !key.includes("\0") && + !value.includes("\0") && + wellFormed(key) && + wellFormed(value) + ); +} + +const FactValue = z.union([z.string(), z.number(), z.boolean()]); + +/** The facts of a row: the kernel's own (`$parent`, `$under` for the path and each ancestor, + * `$processor`), then each scalar and each scalar of a list at the top of `metadata`. A key that + * starts with `$` is the kernel's. + * + * NOTHING IS CUT IN SILENCE. A fact that the index cannot hold (a key or a value that is too + * long, or is not plain text) is one that no query can name either: `normalizeQuery` refuses it. + * A row with more facts than `CATALOG_LIMITS.factsPerRow` is refused whole. */ +function extractFacts( + path: string, + processors: readonly string[], + metadata: Record<string, unknown>, +): Fact[] { + const facts: Fact[] = []; + const seen = new Set<string>(); + const add = (key: string, value: string) => { + if (!usableFact(key, value)) return; + const id = factId([key, value]); + if (seen.has(id)) return; + seen.add(id); + facts.push([key, value]); + }; + const parts = path.split("/").filter(Boolean); + if (path !== "/") add("$parent", `/${parts.slice(0, -1).join("/")}`); + parts.forEach((_, index) => add("$under", `/${parts.slice(0, index + 1).join("/")}`)); + for (const processor of processors) add("$processor", processor); + for (const [key, raw] of Object.entries(metadata)) { + if (key.startsWith("$")) continue; + for (const item of Array.isArray(raw) ? raw : [raw]) { + const value = FactValue.safeParse(item); + // a number that is no number (NaN, an infinity) is no fact: it has no one text + if (value.success && (typeof value.data !== "number" || Number.isFinite(value.data))) + add(key, String(value.data)); + } + } + if (facts.length > CATALOG_LIMITS.factsPerRow) + throw new CatalogRefusal( + `the row of ${path} has ${facts.length} facts, and the catalog indexes at most ${CATALOG_LIMITS.factsPerRow} for a row`, + ); + return facts; +} + +// ── Queries ── + +const ContextPath = z + .string() + .startsWith("/", 'a path starts with "/"') + .max(CATALOG_LIMITS.pathChars) + .refine((path) => !path.includes("\0") && wellFormed(path), "a path is well-formed text") + // one spelling of a path: no slash at its end + .transform((path) => (path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path)); + +/** A query as a watcher sends it (iterate/api `CatalogQuery`). Strict: a field that the catalog + * does not know is refused, never dropped, since dropping a condition answers other rows. */ +const WatchedQuery = z.strictObject({ + where: z.record(z.string(), FactValue).optional(), + under: ContextPath.optional(), + childrenOf: ContextPath.optional(), + order: z.enum(["active", "created", "path"]).optional(), + limit: z.number().int().min(1).max(CATALOG_LIMITS.limit).optional(), + keys: z.array(ContextPath).max(CATALOG_LIMITS.keys).optional(), + awake: z.literal(true).optional(), +}); + +type RangeQuery = { kind: "range"; predicates: Fact[]; order: CatalogOrder; limit: number }; +type Query = RangeQuery | { kind: "keys"; keys: string[] } | { kind: "awake" }; + +/** The one form of a query. Two queries that mean the same have the same `key`, and so share a + * window. A query that cannot be answered exactly is refused: nothing is dropped silently. */ +export function normalizeQuery(spec: unknown): { query: Query; key: string } { + const parsed = WatchedQuery.safeParse(spec); + if (!parsed.success) + throw new CatalogRefusal(`not a query of the catalog: ${z.prettifyError(parsed.error)}`); + const { where, under, childrenOf, order, limit, keys, awake } = parsed.data; + const ranged = Boolean(where || under || childrenOf || order || limit); + if (awake) { + if (ranged || keys) throw new CatalogRefusal("`awake: true` stands alone"); + return { query: { kind: "awake" }, key: '{"awake":true}' }; + } + if (keys) { + if (ranged) throw new CatalogRefusal("`keys` stands alone"); + const paths = [...new Set(keys)].sort(compareTextBinary); + return { query: { kind: "keys", keys: paths }, key: JSON.stringify({ k: paths }) }; + } + const facts = new Map<string, Fact>(); + const add = (key: string, value: string) => { + if (!usableFact(key, value)) + throw new CatalogRefusal(`the fact "${key.slice(0, 40)}" is too long or is not plain text`); + facts.set(factId([key, value]), [key, value]); + }; + for (const [key, value] of Object.entries(where || {})) { + // a key that starts with `$` is the kernel's, and a row's own metadata is not indexed under + // one: a query that named another would get no row, and no reason + if (key.startsWith("$") && !["$processor", "$parent", "$under"].includes(key)) + throw new CatalogRefusal( + `the catalog has no fact "${key.slice(0, 40)}": the kernel's own are $processor, $parent and $under`, + ); + add(key, String(value)); + } + if (under && under !== "/") add("$under", under); + if (childrenOf) add("$parent", childrenOf); + if (facts.size > CATALOG_LIMITS.predicates) + throw new CatalogRefusal(`a query names at most ${CATALOG_LIMITS.predicates} facts`); + const query: RangeQuery = { + kind: "range", + predicates: [...facts.values()].sort( + (a, b) => compareTextBinary(a[0], b[0]) || compareTextBinary(a[1], b[1]), + ), + order: order || "active", + limit: limit || 50, + }; + return { query, key: JSON.stringify({ p: query.predicates, o: query.order, l: query.limit }) }; +} + +/** A short name of what a query selects, without its limit: a cursor is good for any limit of the + * same facts in the same order, because its bound says which part the watcher holds. FNV-1a, 32 + * bits. */ +function queryName(query: Query): string { + const text = + query.kind === "range" ? JSON.stringify([query.order, query.predicates]) : query.kind; + let hash = 0x811c9dc5; + for (let i = 0; i < text.length; i++) { + hash ^= text.charCodeAt(i); + hash = Math.imul(hash, 0x01000193); + } + return (hash >>> 0).toString(36); +} + +/** What a watcher holds of a query (iterate/api `CatalogCursor`). */ +const WatcherCursor = z.object({ + gen: z.string(), + rev: z.number(), + q: z.string(), + bound: z.tuple([z.number(), z.string()]).nullable().optional(), + have: z.array(z.string()).optional(), +}); + +// ── Rows ── + +/** A row as its writer hands it over: the whole new value of its path. `activeMs` and `createdMs` + * are what the orders sort by. Every other field is the row's body, which a watcher gets as it + * is: `processors` and `metadata` are in it, and the facts are read from those two. */ +export type CatalogRowInput = { + path: string; + activeMs: number; + createdMs: number; + processors?: string[]; + metadata?: Record<string, unknown>; + [field: string]: unknown; +}; + +type StoredRow = { path: string; active_at: number; created_at: number; rev: number; body: string }; + +/** A stored row as the JSON a watcher gets (iterate/api `CatalogRow`), with no parse: the body is + * an object's JSON, and it always holds `processors`. */ +function rowJson(row: StoredRow): string { + return `{"path":${JSON.stringify(row.path)},"activeMs":${row.active_at},"createdMs":${row.created_at},"rev":${row.rev},${row.body.slice(1)}`; +} + +function keyOf( + order: CatalogOrder, + row: Pick<StoredRow, "active_at" | "created_at" | "path">, +): SortKey { + if (order === "path") return [0, row.path]; + return [order === "active" ? row.active_at : row.created_at, row.path]; +} + +const ROW_COLUMNS = "r.path, r.active_at, r.created_at, r.rev, r.body"; + +// ── Windows ── + +type LiveWindow = { + id: number; + key: string; + query: Query; + /** Of a range query: which fact its index is read by, the one with the fewest rows when the + * window was made. Any choice is correct; this one reads the least. */ + driver: number; + /** Of a range query: `min(matching rows, limit)`. */ + size: number; + /** Of a range query: the sort key of the last row, kept only while the window is full. */ + bound: SortKey | null; + /** The catalog's revision at the window's last frame. */ + rev: number; +}; + +type PendingFrame = { + windowId: number; + from: number; + rev: number; + del: string[]; + /** `[path, the row's JSON]`. */ + put: [string, string][]; +}; + +/** What a watch socket remembers through a hibernation: its id, and its queries by the name the + * watcher gave each. */ +const WatchAttachment = z.object({ sid: z.string(), subs: z.record(z.string(), z.number()) }); + +/** What a watch socket's other end sends. */ +const WatchRequest = z.object({ + op: z.enum(["subscribe", "unsubscribe"]), + sub: z.string().min(1).max(CATALOG_LIMITS.subChars), + query: z.unknown().optional(), + cursor: z.unknown().optional(), +}); + +type Statement = { sql: string; args: unknown[] }; + +/** What the engine needs of the Durable Object it runs in. */ +type CatalogHost = Pick<DurableObjectState, "getWebSockets" | "acceptWebSocket" | "getTags"> & { + storage: Pick<DurableObjectStorage, "transactionSync">; +}; + +/** A watch socket and its queries, by the name the watcher gave each. */ +type WatchSocket = { ws: WebSocket; subs: Map<string, number> }; + +type CatalogDeps = { + /** The contexts that hold an awake socket now, by path. */ + awake: () => ReadonlyMap<string, AwakeContextState>; + /** A page of the catalog's own rows, in path order, after `after`: what the first fill copies. */ + seed: (after: string, limit: number) => CatalogRowInput[]; + /** One context's row in the catalog now: what a write that the copy owes is made again from. */ + row: (path: string) => CatalogRowInput | undefined; +}; + +export class ReactiveCatalog { + readonly #sql: SqlStorage; + readonly #ctx: CatalogHost; + readonly #deps: CatalogDeps; + #ready = false; + #gen = ""; + #rev = 0; + /** How far the first fill came: "" before it began, then the last path it copied, then `done`. */ + #filled: { started: boolean; done: boolean; after: string } = { + started: false, + done: false, + after: "", + }; + + /** Whether the copy owes a write (`rcat_owed`). It is kept in `rcat_meta`, so an object that + * wakes knows it with no other read. */ + #owed = false; + + // What follows is memory that a hibernation drops. Each is read again when it is first needed: + // the windows from `rcat_window`, the sockets from their attachments. + #windows: Map<number, LiveWindow> | undefined; + #windowIdByKey = new Map<string, number>(); + /** A range window is found by its driver fact; one with no fact is under `*`. */ + #rangeWindowsByFact = new Map<string, Set<number>>(); + #keysWindowsByPath = new Map<string, Set<number>>(); + #awakeWindowId: number | undefined; + #sockets: Map<string, WatchSocket> | undefined; + /** window id → socket id → the socket's names for the query. */ + #watchers = new Map<number, Map<string, Set<string>>>(); + + counters = { + statements: 0, + /** Rows that SQLite read and wrote for those statements, index entries too: what a Durable + * Object is billed by. */ + rowsRead: 0, + rowsWritten: 0, + writes: 0, + /** Writes of a row equal to the stored one. */ + sameWrites: 0, + /** Rows whose write changed no window: no statement beyond the write's own, and no frame. */ + quietWrites: 0, + windowChecks: 0, + seeks: 0, + messagesSent: 0, + charsSent: 0, + /** Rows that an answer to a cursor did not send again, because the watcher held them. */ + rowsNotResent: 0, + windowsMade: 0, + windowsDropped: 0, + }; + + constructor(sql: SqlStorage, ctx: CatalogHost, deps: CatalogDeps) { + this.#sql = sql; + this.#ctx = ctx; + this.#deps = deps; + } + + // ── Storage ── + + #ensureTables(): void { + if (this.#ready) return; + this.#sql.exec( + "CREATE TABLE IF NOT EXISTS rcat_meta (k TEXT PRIMARY KEY NOT NULL, v TEXT NOT NULL) WITHOUT ROWID", + ); + const read = () => + new Map( + this.#sql + .exec<{ k: string; v: string }>("SELECT k, v FROM rcat_meta") + .toArray() + .map((row) => [row.k, row.v]), + ); + let meta = read(); + // The tables are made once for a schema. An object that wakes reads `rcat_meta` and no more: + // this runs at the first summary after every wake of the object, watched or not. + if (meta.get("schema") !== SCHEMA) { + // Every row here is a copy of the catalog's own, so tables of another schema are made again + // and filled again. A new generation: no cursor of the old tables is good for the new ones. + for (const table of [ + "rcat_row", + "rcat_fact_active", + "rcat_fact_created", + "rcat_fact_path", + "rcat_window", + "rcat_owed", + ]) + this.#sql.exec(`DROP TABLE IF EXISTS ${table}`); + this.#sql.exec( + `CREATE TABLE rcat_row ( + path TEXT COLLATE BINARY PRIMARY KEY NOT NULL, + active_at INTEGER NOT NULL, + created_at INTEGER NOT NULL, + rev INTEGER NOT NULL, + body TEXT NOT NULL, + facts TEXT NOT NULL + ) WITHOUT ROWID`, + ); + this.#sql.exec("CREATE INDEX rcat_row_active ON rcat_row (active_at DESC, path DESC)"); + this.#sql.exec("CREATE INDEX rcat_row_created ON rcat_row (created_at DESC, path DESC)"); + for (const { facts, column } of Object.values(ORDER_INDEX)) + this.#sql.exec( + `CREATE TABLE ${facts} ( + k TEXT COLLATE BINARY NOT NULL, + v TEXT COLLATE BINARY NOT NULL, + ${column && `${column} INTEGER NOT NULL,`} + path TEXT COLLATE BINARY NOT NULL, + PRIMARY KEY (k, v, ${column && `${column} DESC,`} path${column && " DESC"}) + ) WITHOUT ROWID`, + ); + this.#sql.exec( + `CREATE TABLE rcat_window ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + key TEXT COLLATE BINARY NOT NULL UNIQUE, + driver INTEGER NOT NULL, + size INTEGER NOT NULL, + b_at INTEGER, + b_path TEXT COLLATE BINARY, + rev INTEGER NOT NULL + )`, + ); + this.#sql.exec( + `CREATE TABLE rcat_owed ( + path TEXT COLLATE BINARY PRIMARY KEY NOT NULL, + tries INTEGER NOT NULL, + due_at INTEGER NOT NULL + ) WITHOUT ROWID`, + ); + this.#sql.exec("DELETE FROM rcat_meta"); + // written last: tables that were half made are made again + this.#sql.exec( + "INSERT INTO rcat_meta (k, v) VALUES ('schema', ?), ('gen', ?), ('rev', '0')", + SCHEMA, + crypto.randomUUID().slice(0, 8), + ); + meta = read(); + } + this.#gen = meta.get("gen") || ""; + this.#rev = Number(meta.get("rev") || "0"); + const filled = meta.get("filled"); + this.#filled = { + started: meta.has("filled"), + done: filled === "done", + after: filled?.startsWith(">") ? filled.slice(1) : "", + }; + this.#owed = meta.has("owed"); + this.#ready = true; + } + + #exec<T extends Record<string, SqlStorageValue>>(sql: string, ...args: unknown[]): T[] { + this.counters.statements += 1; + const cursor = this.#sql.exec<T>(sql, ...args); + const rows = cursor.toArray(); + this.counters.rowsRead += cursor.rowsRead || 0; + this.counters.rowsWritten += cursor.rowsWritten || 0; + return rows; + } + + /** Memory that no longer matches SQLite (a transaction that threw) is read again. */ + #forget(): void { + this.#ready = false; + this.#windows = undefined; + this.#sockets = undefined; + } + + /** Whether the catalog keeps rows: false until the first watch, and then for good. A writer + * asks before it builds a row. */ + active(): boolean { + this.#ensureTables(); + return this.#filled.started; + } + + /** THE FIRST FILL: every row of the catalog, copied a page at a time, each page one transaction. + * It runs to its end before the first window is made. A fill that stopped (the object died + * under it) goes on from the last page it wrote. A row that this collection refuses is left + * out, and the others are kept. */ + fill(): void { + this.#ensureTables(); + while (!this.#filled.done) { + const page = this.#deps.seed(this.#filled.after, CATALOG_LIMITS.fillPage); + const last = page.at(-1)?.path; + const mark = last ? `>${last}` : "done"; + const pending: PendingFrame[] = []; + try { + this.#ctx.storage.transactionSync(() => { + for (const row of page) { + try { + this.#upsertOne(row, pending); + } catch (error) { + if (!(error instanceof CatalogRefusal)) throw error; + } + } + this.#exec("UPDATE rcat_meta SET v = ? WHERE k = 'rev'", String(this.#rev)); + this.#exec( + "INSERT INTO rcat_meta (k, v) VALUES ('filled', ?) ON CONFLICT (k) DO UPDATE SET v = excluded.v", + mark, + ); + }); + } catch (error) { + this.#forget(); + throw error; + } + this.#filled = { started: true, done: !last, after: last || "" }; + this.#dispatch(pending); + } + } + + #loadWindows(): Map<number, LiveWindow> { + this.#ensureTables(); + if (this.#windows) return this.#windows; + const windows = new Map<number, LiveWindow>(); + this.#windows = windows; + this.#windowIdByKey = new Map(); + this.#rangeWindowsByFact = new Map(); + this.#keysWindowsByPath = new Map(); + this.#awakeWindowId = undefined; + const rows = this.#exec<{ + id: number; + key: string; + driver: number; + size: number; + b_at: number | null; + b_path: string | null; + rev: number; + }>("SELECT id, key, driver, size, b_at, b_path, rev FROM rcat_window"); + for (const row of rows) + this.#indexWindow(windows, { + id: row.id, + key: row.key, + query: queryOfKey(row.key), + driver: row.driver, + size: row.size, + // oxlint-disable-next-line iterate/simple-truthiness-check -- SQL NULL means "no bound"; a bound's own time may be 0 and its path is never empty + bound: row.b_at === null || row.b_path === null ? null : [row.b_at, row.b_path], + rev: row.rev, + }); + return windows; + } + + #indexWindow(windows: Map<number, LiveWindow>, win: LiveWindow): void { + windows.set(win.id, win); + this.#windowIdByKey.set(win.key, win.id); + const into = (index: Map<string, Set<number>>, at: string) => { + let ids = index.get(at); + if (!ids) index.set(at, (ids = new Set())); + ids.add(win.id); + }; + if (win.query.kind === "range") into(this.#rangeWindowsByFact, driverFactOf(win)); + else if (win.query.kind === "keys") + for (const path of win.query.keys) into(this.#keysWindowsByPath, path); + else this.#awakeWindowId = win.id; + } + + #dropWindow(win: LiveWindow): void { + this.#loadWindows().delete(win.id); + this.#windowIdByKey.delete(win.key); + this.#watchers.delete(win.id); + const out = (index: Map<string, Set<number>>, at: string) => { + const ids = index.get(at); + ids?.delete(win.id); + if (ids?.size === 0) index.delete(at); + }; + if (win.query.kind === "range") out(this.#rangeWindowsByFact, driverFactOf(win)); + else if (win.query.kind === "keys") + for (const path of win.query.keys) out(this.#keysWindowsByPath, path); + else this.#awakeWindowId = undefined; + this.#exec("DELETE FROM rcat_window WHERE id = ?", win.id); + this.counters.windowsDropped += 1; + } + + #saveWindow(win: LiveWindow): void { + this.#exec( + "UPDATE rcat_window SET size = ?, b_at = ?, b_path = ?, rev = ? WHERE id = ?", + win.size, + win.bound ? win.bound[0] : null, + win.bound ? win.bound[1] : null, + win.rev, + win.id, + ); + } + + // ── The statements of a range query. Every one reads one index in its order. ── + + /** FROM and WHERE for a query's rows. With a fact: the driver fact's entries in the index of the + * query's order, and one point lookup in `rcat_fact_path` for each other fact. With none: the + * rows themselves, by the index of the order. `join` adds the row to a fact's entry. */ + #rangeSql( + query: RangeQuery, + driver: number, + ): { from: string; join: string; where: string[]; args: unknown[]; at: string } { + const driven = query.predicates[driver]; + if (!driven) return { from: "rcat_row r", join: "", where: [], args: [], at: "r" }; + const where = ["f0.k = ?", "f0.v = ?"]; + const args: unknown[] = [...driven]; + query.predicates.forEach((fact, index) => { + if (index === driver) return; + where.push( + "EXISTS (SELECT 1 FROM rcat_fact_path fi WHERE fi.k = ? AND fi.v = ? AND fi.path = f0.path)", + ); + args.push(...fact); + }); + return { + from: `${ORDER_INDEX[query.order].facts} f0`, + join: " JOIN rcat_row r ON r.path = f0.path", + where, + args, + at: "f0", + }; + } + + /** The window's rows, in order. */ + #windowSql(query: RangeQuery, driver: number): Statement { + const { from, join, where, args, at } = this.#rangeSql(query, driver); + return { + sql: `SELECT ${ROW_COLUMNS} FROM ${from}${join}${where.length ? ` WHERE ${where.join(" AND ")}` : ""} ORDER BY ${orderTerms(query.order, at, true)} LIMIT ?`, + args: [...args, query.limit], + }; + } + + /** F, the follower: the first row after `bound`. THE BACKFILL. */ + #followerSql(query: RangeQuery, driver: number, bound: SortKey): Statement { + const { from, join, where, args, at } = this.#rangeSql(query, driver); + const after = beyond(query.order, at, true, bound); + return { + sql: `SELECT ${ROW_COLUMNS} FROM ${from}${join} WHERE ${[...where, after.sql].join(" AND ")} ORDER BY ${orderTerms(query.order, at, true)} LIMIT 1`, + args: [...args, ...after.args], + }; + } + + /** The sort key of ONE row, read against the window's order: A, the row above `bound` (the last + * row before it), or with no bound M, the last matching row, which is the bound of a window + * that has just become full. */ + #edgeSql(query: RangeQuery, driver: number, bound: SortKey | null): Statement { + const { from, where, args, at } = this.#rangeSql(query, driver); + const before = bound ? beyond(query.order, at, false, bound) : { sql: "", args: [] }; + const conditions = [...where, before.sql].filter(Boolean); + const column = ORDER_INDEX[query.order].column; + return { + sql: `SELECT ${column ? `${at}.${column}` : "0"} AS at, ${at}.path AS path FROM ${from}${conditions.length ? ` WHERE ${conditions.join(" AND ")}` : ""} ORDER BY ${orderTerms(query.order, at, false)} LIMIT 1`, + args: [...args, ...before.args], + }; + } + + #windowRows(query: RangeQuery, driver: number): StoredRow[] { + const { sql, args } = this.#windowSql(query, driver); + return this.#exec<StoredRow>(sql, ...args); + } + + #follower(win: LiveWindow, query: RangeQuery, bound: SortKey): StoredRow | undefined { + this.counters.seeks += 1; + const { sql, args } = this.#followerSql(query, win.driver, bound); + return this.#exec<StoredRow>(sql, ...args)[0]; + } + + #edge(win: LiveWindow, query: RangeQuery, bound: SortKey | null): SortKey | null { + this.counters.seeks += 1; + const { sql, args } = this.#edgeSql(query, win.driver, bound); + const row = this.#exec<{ at: number; path: string }>(sql, ...args)[0]; + return row ? [row.at, row.path] : null; + } + + /** The fact with the fewest rows, counted up to 1,000 each. */ + #chooseDriver(query: RangeQuery): number { + if (query.predicates.length < 2) return 0; + let best = 0; + let fewest = Infinity; + query.predicates.forEach((fact, index) => { + const counted = + this.#exec<{ n: number }>( + "SELECT COUNT(*) AS n FROM (SELECT 1 FROM rcat_fact_path WHERE k = ? AND v = ? LIMIT 1000)", + ...fact, + )[0]?.n || 0; + if (counted < fewest) { + fewest = counted; + best = index; + } + }); + return best; + } + + #keysRows(paths: readonly string[]): StoredRow[] { + return this.#exec<StoredRow>( + `SELECT ${ROW_COLUMNS} FROM rcat_row r WHERE r.path IN (SELECT value FROM json_each(?)) ORDER BY r.path`, + JSON.stringify(paths), + ); + } + + // ── What the catalog kept ── + + /** A ROW THAT THE CATALOG KEPT (context-catalog.ts) is the row of this copy too, once a mind + * has watched. A row that the copy refuses (one it cannot order or index) is taken out of it: + * a watcher then sees no row of that context, and never an old one. + * + * WHAT THE COPY CANNOT WRITE IT OWES: a durable mark for the path (`rcat_owed`). An owed write + * is made again from the catalog's own row, at a later write or watch, after a wait that + * doubles from one minute to thirty, `CATALOG_LIMITS.owedTries` times in all; a later summary + * of the same context pays it at once. So the copy is behind the catalog for a bounded time + * and never in silence: each failure is reported, and `watches()` counts what is owed. + * + * It throws only when not even the mark could be written. */ + keep(input: CatalogRowInput): void { + if (!this.active()) return; + let written = true; + try { + this.#keepOrRefuse(input); + } catch (error) { + written = false; + reportIssue("reactive-catalog.write", error, { path: input.path }); + this.#owe(input.path); + } + if (!this.#owed) return; + // the write that just went pays this context's own debt + if (written) this.#exec("DELETE FROM rcat_owed WHERE path = ?", input.path); + this.settleOwed(); + } + + #keepOrRefuse(input: CatalogRowInput): void { + try { + this.upsert(input); + } catch (error) { + if (!(error instanceof CatalogRefusal)) throw error; + console.info({ + event: "context.reactive-catalog-row-refused", + path: input.path, + message: error.message, + }); + this.deleteMany([input.path]); + } + } + + /** One more try that failed: the next comes after a minute, then after twice the wait of the + * try before, thirty minutes at most. */ + #owe(path: string): void { + const now = Date.now(); + this.#exec( + `INSERT INTO rcat_owed (path, tries, due_at) VALUES (?, 1, ?) + ON CONFLICT (path) DO UPDATE SET + due_at = ? + MIN(60000 * (1 << MIN(rcat_owed.tries, 5)), 1800000), + tries = rcat_owed.tries + 1`, + path, + now + 60_000, + now, + ); + if (!this.#owed) + this.#exec( + "INSERT INTO rcat_meta (k, v) VALUES ('owed', '1') ON CONFLICT (k) DO UPDATE SET v = '1'", + ); + this.#owed = true; + } + + /** Makes again the writes that the copy owes and that are due, at most 20 a call. */ + settleOwed(): void { + if (!this.active() || !this.#owed) return; + const due = this.#exec<{ path: string }>( + "SELECT path FROM rcat_owed WHERE tries < ? AND due_at <= ? ORDER BY due_at LIMIT 20", + CATALOG_LIMITS.owedTries, + Date.now(), + ); + for (const { path } of due) { + try { + const row = this.#deps.row(path); + // a context that the catalog no longer has is in no answer + if (row) this.#keepOrRefuse(row); + else this.deleteMany([path]); + this.#exec("DELETE FROM rcat_owed WHERE path = ?", path); + } catch (error) { + reportIssue("reactive-catalog.settle", error, { path }); + this.#owe(path); + } + } + if (this.#exec("SELECT 1 AS one FROM rcat_owed LIMIT 1").length > 0) return; + this.#exec("DELETE FROM rcat_meta WHERE k = 'owed'"); + this.#owed = false; + } + + // ── Writes ── + + /** Writes rows, each a whole new value of its path, in one transaction. A row equal to the one + * stored is no write: no revision, no frame. Before the first watch it writes nothing. */ + upsertMany(inputs: readonly CatalogRowInput[]): WriteResult { + return this.#write((out) => inputs.filter((input) => this.#upsertOne(input, out)).length); + } + + upsert(input: CatalogRowInput): WriteResult { + return this.upsertMany([input]); + } + + /** Takes rows out. No writer of the kernel does so today: a context keeps its row for good, here + * as in the catalog. It is the collection's other verb, and the case table needs it. */ + deleteMany(paths: readonly string[]): WriteResult { + return this.#write((out) => paths.filter((path) => this.#deleteOne(path, out)).length); + } + + #write(work: (out: PendingFrame[]) => number): WriteResult { + if (!this.active()) return { rev: this.#rev, changed: 0, frames: 0, messages: 0, chars: 0 }; + const pending: PendingFrame[] = []; + let changed = 0; + try { + this.#ctx.storage.transactionSync(() => { + changed = work(pending); + if (changed > 0) + this.#exec("UPDATE rcat_meta SET v = ? WHERE k = 'rev'", String(this.#rev)); + }); + } catch (error) { + // the transaction is undone, and so the windows and the revision in memory are stale + this.#forget(); + throw error; + } + return { rev: this.#rev, changed, frames: pending.length, ...this.#dispatch(pending) }; + } + + #storedRow(path: string): (StoredRow & { facts: string }) | undefined { + return this.#exec<StoredRow & { facts: string }>( + "SELECT path, active_at, created_at, rev, body, facts FROM rcat_row WHERE path = ?", + path, + )[0]; + } + + #upsertOne(input: CatalogRowInput, out: PendingFrame[]): boolean { + const row = RowInput.safeParse(input); + if (!row.success) + throw new CatalogRefusal(`not a row of the catalog: ${z.prettifyError(row.error)}`); + const { path, activeMs: activeAt, createdMs: createdAt, ...listing } = row.data; + const { processors, metadata } = listing; + const body = JSON.stringify(listing); + if (body.length > CATALOG_LIMITS.bodyChars) + throw new CatalogRefusal( + `the row of ${path} is longer than ${CATALOG_LIMITS.bodyChars} characters`, + ); + const old = this.#storedRow(path); + if (old && old.active_at === activeAt && old.created_at === createdAt && old.body === body) { + this.counters.sameWrites += 1; + return false; + } + const facts = extractFacts(path, processors, metadata); + // the stored list is the truth of what the old row has in each index: no parse of its body + const oldFacts = old ? (JSON.parse(old.facts) as Fact[]) : []; + this.#rev += 1; + const next: StoredRow = { + path, + active_at: activeAt, + created_at: createdAt, + rev: this.#rev, + body, + }; + this.#exec( + `INSERT INTO rcat_row (path, active_at, created_at, rev, body, facts) VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT (path) DO UPDATE SET active_at = excluded.active_at, + created_at = excluded.created_at, rev = excluded.rev, body = excluded.body, + facts = excluded.facts`, + path, + activeAt, + createdAt, + next.rev, + body, + JSON.stringify(facts), + ); + this.#moveFacts(old, oldFacts, next, facts); + this.counters.writes += 1; + this.#notify(old, new Set(oldFacts.map(factId)), next, new Set(facts.map(factId)), out); + return true; + } + + #deleteOne(path: string, out: PendingFrame[]): boolean { + const old = this.#storedRow(path); + if (!old) return false; + const oldFacts = JSON.parse(old.facts) as Fact[]; + this.#rev += 1; + this.#exec("DELETE FROM rcat_row WHERE path = ?", path); + this.#moveFacts(old, oldFacts, undefined, []); + this.counters.writes += 1; + this.#notify(old, new Set(oldFacts.map(factId)), undefined, new Set(), out); + return true; + } + + /** A row's entries in each order's index, brought from what the old row had to what the new one + * has. An entry holds the order's own value, so every entry of an order moves when that value + * does; otherwise only the facts that came or went are written. */ + #moveFacts( + old: StoredRow | undefined, + oldFacts: readonly Fact[], + next: StoredRow | undefined, + nextFacts: readonly Fact[], + ): void { + const oldIds = new Set(oldFacts.map(factId)); + const nextIds = new Set(nextFacts.map(factId)); + for (const [order, { facts: table, column }] of Object.entries(ORDER_INDEX) as [ + CatalogOrder, + (typeof ORDER_INDEX)[CatalogOrder], + ][]) { + const oldAt = old && keyOf(order, old)[0]; + const nextAt = next && keyOf(order, next)[0]; + const moved = oldAt !== nextAt; + const at = column && ` AND ${column} = ?`; + if (old) + for (const fact of oldFacts) + if (moved || !nextIds.has(factId(fact))) + this.#exec( + `DELETE FROM ${table} WHERE k = ? AND v = ?${at} AND path = ?`, + ...fact, + ...(column ? [oldAt] : []), + old.path, + ); + if (next) + for (const fact of nextFacts) + if (moved || !oldIds.has(factId(fact))) + this.#exec( + `INSERT INTO ${table} (k, v, ${column && `${column}, `}path) VALUES (?, ?, ${column && "?, "}?)`, + ...fact, + ...(column ? [nextAt] : []), + next.path, + ); + } + } + + // ── The case table: what one write does to one window ── + + #notify( + old: StoredRow | undefined, + oldFacts: ReadonlySet<string>, + next: StoredRow | undefined, + nextFacts: ReadonlySet<string>, + out: PendingFrame[], + ): void { + const windows = this.#loadWindows(); + if (windows.size === 0) return; + const before = out.length; + const candidates = new Set<number>(); + const collect = (ids: ReadonlySet<number> | undefined) => { + if (ids) for (const id of ids) candidates.add(id); + }; + collect(this.#rangeWindowsByFact.get("*")); + // a window is under ONE of its facts: a row that never held that fact never matched it + for (const fact of oldFacts) collect(this.#rangeWindowsByFact.get(fact)); + for (const fact of nextFacts) collect(this.#rangeWindowsByFact.get(fact)); + for (const id of candidates) { + const win = windows.get(id); + if (win?.query.kind === "range") + this.#advance(win, win.query, old, oldFacts, next, nextFacts, out); + } + + const path = next?.path || old?.path || ""; + for (const id of this.#keysWindowsByPath.get(path) || []) { + const win = windows.get(id); + if (!win) continue; + this.counters.windowChecks += 1; + out.push({ + windowId: id, + from: win.rev, + rev: this.#rev, + del: next ? [] : [path], + put: next ? [[path, rowJson(next)]] : [], + }); + win.rev = this.#rev; + this.#saveWindow(win); + } + if (out.length === before) this.counters.quietWrites += 1; + } + + #advance( + win: LiveWindow, + query: RangeQuery, + old: StoredRow | undefined, + oldFacts: ReadonlySet<string>, + next: StoredRow | undefined, + nextFacts: ReadonlySet<string>, + out: PendingFrame[], + ): void { + this.counters.windowChecks += 1; + const matches = (facts: ReadonlySet<string>) => + query.predicates.every((fact) => facts.has(factId(fact))); + const compare = (a: SortKey, b: SortKey) => compareSortKeys(query.order, a, b); + const oldKey = old && matches(oldFacts) ? keyOf(query.order, old) : null; + const nextKey = next && matches(nextFacts) ? keyOf(query.order, next) : null; + + const emit = (del: string[], put: StoredRow[]) => { + out.push({ + windowId: win.id, + from: win.rev, + rev: this.#rev, + del, + put: put.map((row) => [row.path, rowJson(row)]), + }); + win.rev = this.#rev; + this.#saveWindow(win); + }; + + if (win.size < query.limit) { + // a window with room holds every matching row, and keeps no bound + if (!oldKey && !nextKey) return; + if (!nextKey || !next) { + win.size -= 1; + return emit([oldKey ? oldKey[1] : ""], []); + } + if (!oldKey) { + win.size += 1; + if (win.size === query.limit) win.bound = this.#edge(win, query, null); + } + return emit([], [next]); + } + + const bound = win.bound; + if (!bound) throw new Error(`the full window ${win.id} has no bound`); + const wasIn = !!oldKey && compare(oldKey, bound) <= 0; + if (!wasIn) { + // THE COMMON CASE: neither the old key nor the new one is in the window + if (!nextKey || !next || compare(nextKey, bound) > 0) return; + // the row enters: the last row leaves, and the row above it is the bound + win.bound = this.#edge(win, query, bound); + return emit([bound[1]], [next]); + } + if (!nextKey || !next) { + // the row leaves: the follower takes the place, in the same frame + const follower = this.#follower(win, query, bound); + if (follower) win.bound = keyOf(query.order, follower); + else { + win.size -= 1; + win.bound = null; + } + return emit([oldKey[1]], follower ? [follower] : []); + } + const moved = compare(nextKey, bound); + const wasLast = compare(oldKey, bound) === 0; + if (moved === 0 || (moved < 0 && !wasLast)) return emit([], [next]); + if (moved < 0) { + // the last row moved up: the row that is last now is the bound + win.bound = this.#edge(win, query, bound); + return emit([], [next]); + } + // the row moved to after the bound: the follower is the last row, and it may be this row + const follower = this.#follower(win, query, bound); + if (!follower) throw new Error(`the window ${win.id} lost the row that moved past its bound`); + win.bound = keyOf(query.order, follower); + if (follower.path === next.path) return emit([], [next]); + return emit([oldKey[1]], [follower]); + } + + // ── Awake ── + + /** Whether anyone watches the awake list: when nobody does, the object does nothing for a wake. */ + awakeWatched(): boolean { + this.#loadWindows(); + return this.#awakeWindowId !== undefined; + } + + /** A context woke or said what it does now (`state`), or went quiet (undefined). No row and no + * revision: the awake list is the sockets. */ + awakeChanged(path: string, state: AwakeContextState | undefined): void { + const windows = this.#loadWindows(); + const win = this.#awakeWindowId === undefined ? undefined : windows.get(this.#awakeWindowId); + if (!win) return; + this.#dispatch([ + { + windowId: win.id, + from: win.rev, + rev: win.rev, + del: state ? [] : [path], + put: state ? [[path, awakeJson(path, state)]] : [], + }, + ]); + } + + // ── Sockets ── + + #loadSockets(): Map<string, WatchSocket> { + if (this.#sockets) return this.#sockets; + this.#loadWindows(); + const sockets = new Map<string, WatchSocket>(); + this.#sockets = sockets; + this.#watchers = new Map(); + for (const ws of this.#ctx.getWebSockets(WATCH_SOCKET_TAG)) { + if (ws.readyState !== WebSocket.OPEN) continue; + const attachment = WatchAttachment.safeParse(ws.deserializeAttachment()).data; + if (!attachment) continue; + const subs = new Map(Object.entries(attachment.subs)); + sockets.set(attachment.sid, { ws, subs }); + for (const [sub, windowId] of subs) this.#watch(windowId, attachment.sid, sub); + } + return sockets; + } + + #watch(windowId: number, sid: string, sub: string): void { + let bySocket = this.#watchers.get(windowId); + if (!bySocket) this.#watchers.set(windowId, (bySocket = new Map())); + let subs = bySocket.get(sid); + if (!subs) bySocket.set(sid, (subs = new Set())); + subs.add(sub); + } + + /** Takes a socket's name for a query off its window. A window that nobody watches goes. */ + #unwatch(windowId: number, sid: string, sub: string): void { + const bySocket = this.#watchers.get(windowId); + const subs = bySocket?.get(sid); + subs?.delete(sub); + if (subs?.size === 0) bySocket?.delete(sid); + if (bySocket && bySocket.size > 0) return; + const win = this.#loadWindows().get(windowId); + if (win) this.#dropWindow(win); + } + + /** Sends each socket ONE message with every frame that is for it. Returns what was sent. */ + #dispatch(pending: readonly PendingFrame[]): { messages: number; chars: number } { + if (pending.length === 0) return { messages: 0, chars: 0 }; + const sockets = this.#loadSockets(); + const windows = this.#loadWindows(); + type Part = { rows: Map<string, string>; frames: string[]; chars: number }; + const bySocket = new Map<string, Part[]>(); + for (const frame of pending) { + const watchers = this.#watchers.get(frame.windowId); + if (!watchers?.size) { + // left by a socket that ended with no close event: the window goes at its first frame + const win = windows.get(frame.windowId); + if (win) this.#dropWindow(win); + continue; + } + const tail = `,${frame.from},${frame.rev},${JSON.stringify(frame.del)},${JSON.stringify(frame.put.map(([path]) => path))}]`; + const rowChars = frame.put.reduce((sum, [, json]) => sum + json.length, 0); + for (const [sid, subs] of watchers) { + let parts = bySocket.get(sid); + if (!parts) bySocket.set(sid, (parts = [{ rows: new Map(), frames: [], chars: 0 }])); + let part = parts[parts.length - 1]; + if (!part || part.chars > CATALOG_LIMITS.messageChars) + parts.push((part = { rows: new Map(), frames: [], chars: 0 })); + for (const [path, json] of frame.put) part.rows.set(path, json); + for (const sub of subs) part.frames.push(`[${JSON.stringify(sub)}${tail}`); + part.chars += rowChars + tail.length * subs.size; + } + } + let messages = 0; + let chars = 0; + for (const [sid, parts] of bySocket) { + const socket = sockets.get(sid); + if (!socket) continue; + parts.forEach((part, at) => { + // every part but the last says that more of this write comes: the session's end hands + // a write to its watchers whole (catalog-watch.ts) + const more = at < parts.length - 1 ? ',"more":true' : ""; + const message = `{"gen":${JSON.stringify(this.#gen)},"rows":[${[...part.rows.values()].join(",")}],"d":[${part.frames.join(",")}]${more}}`; + if (!this.#send(socket.ws, message)) return; + messages += 1; + chars += message.length; + }); + } + return { messages, chars }; + } + + #send(ws: WebSocket, message: string): boolean { + try { + ws.send(message); + this.counters.messagesSent += 1; + this.counters.charsSent += message.length; + return true; + } catch { + // a socket that is closing: its close event takes its queries off + return false; + } + } + + /** The upgrade of a watch socket: the object's end is accepted with the hibernation API. */ + acceptWatchWebSocket(): Response { + const pair = new WebSocketPair(); + try { + this.attachWatchSocket(pair[1]); + } catch (error) { + // the limit of sockets on one Durable Object + return new Response(`${error instanceof Error ? error.message : String(error)}\n`, { + status: 503, + }); + } + return new Response(null, { status: 101, webSocket: pair[0] }); + } + + attachWatchSocket(ws: WebSocket): void { + this.#ensureTables(); + this.#ctx.acceptWebSocket(ws, [WATCH_SOCKET_TAG]); + const sid = crypto.randomUUID().slice(0, 12); + ws.serializeAttachment({ sid, subs: {} } satisfies z.infer<typeof WatchAttachment>); + this.#sockets?.set(sid, { ws, subs: new Map() }); + this.#send(ws, JSON.stringify({ hello: { gen: this.#gen, rev: this.#rev } })); + } + + isWatchWebSocket(ws: WebSocket): boolean { + return this.#ctx.getTags(ws).includes(WATCH_SOCKET_TAG); + } + + handleWatchMessage(ws: WebSocket, raw: string | ArrayBuffer): void { + let request: z.infer<typeof WatchRequest> | undefined; + try { + try { + request = WatchRequest.parse(JSON.parse(typeof raw === "string" ? raw : "")); + } catch { + throw new CatalogRefusal( + `a message is one JSON object, { op: "subscribe" | "unsubscribe", sub: a name of 1 to ${CATALOG_LIMITS.subChars} characters, query?, cursor? }`, + ); + } + const sockets = this.#loadSockets(); + const sid = WatchAttachment.safeParse(ws.deserializeAttachment()).data?.sid || ""; + const socket = sockets.get(sid); + if (!socket) throw new CatalogRefusal("this socket is not a watch socket"); + socket.ws = ws; + if (request.op === "subscribe") { + this.#subscribe(sid, socket, request.sub, request.query, request.cursor); + return; + } + const windowId = socket.subs.get(request.sub); + socket.subs.delete(request.sub); + ws.serializeAttachment({ sid, subs: Object.fromEntries(socket.subs) }); + if (windowId !== undefined) this.#unwatch(windowId, sid, request.sub); + this.#send(ws, JSON.stringify({ sub: request.sub, unsubscribed: true })); + } catch (error) { + // What the watcher is told: its query cannot be answered, a limit is reached, or the + // catalog itself failed. The session's end gives each its own code (catalog-watch.ts). + const kind = + error instanceof CatalogRefusal + ? "query" + : error instanceof CatalogLimit + ? "limit" + : "failed"; + if (kind === "failed") { + this.#forget(); + reportIssue("reactive-catalog.watch", error, { sub: request?.sub }); + } + this.#send( + ws, + JSON.stringify({ + sub: request?.sub, + kind, + error: + kind !== "failed" && error instanceof Error + ? error.message + : "the catalog failed, and its log says why", + }), + ); + } + } + + #subscribe(sid: string, socket: WatchSocket, sub: string, spec: unknown, cursor: unknown): void { + const { query, key } = normalizeQuery(spec); + const had = socket.subs.get(sub); + if (had === undefined && socket.subs.size >= CATALOG_LIMITS.subsPerSocket) + throw new CatalogLimit( + `a session holds at most ${CATALOG_LIMITS.subsPerSocket} watches: dispose one first`, + ); + // the awake list is the sockets: it needs no row + if (query.kind !== "awake") { + this.fill(); + // an answer is as right as the copy can make it now + this.settleOwed(); + } + const windows = this.#loadWindows(); + + let win = windows.get(this.#windowIdByKey.get(key) ?? -1); + let rows: StoredRow[] | undefined; + if (!win) { + if (windows.size >= CATALOG_LIMITS.windows) + // windows that no open socket names: left by a socket that ended with no close event + for (const stale of [...windows.values()]) + if (!this.#watchers.get(stale.id)?.size) this.#dropWindow(stale); + if (windows.size >= CATALOG_LIMITS.windows) + throw new CatalogLimit( + `the catalog holds at most ${CATALOG_LIMITS.windows} different live queries`, + ); + const driver = query.kind === "range" ? this.#chooseDriver(query) : 0; + rows = query.kind === "range" ? this.#windowRows(query, driver) : undefined; + const last = + rows && query.kind === "range" && rows.length === query.limit ? rows.at(-1) : undefined; + const bound = last && query.kind === "range" ? keyOf(query.order, last) : null; + const made = this.#exec<{ id: number }>( + "INSERT INTO rcat_window (key, driver, size, b_at, b_path, rev) VALUES (?, ?, ?, ?, ?, ?) RETURNING id", + key, + driver, + rows?.length || 0, + bound ? bound[0] : null, + bound ? bound[1] : null, + this.#rev, + )[0]; + if (!made) throw new Error("the window was not stored"); + win = { id: made.id, key, query, driver, size: rows?.length || 0, bound, rev: this.#rev }; + this.#indexWindow(windows, win); + this.counters.windowsMade += 1; + } + // the socket's name moves to this window before the old one is let go + socket.subs.set(sub, win.id); + socket.ws.serializeAttachment({ sid, subs: Object.fromEntries(socket.subs) }); + this.#watch(win.id, sid, sub); + if (had !== undefined && had !== win.id) this.#unwatch(had, sid, sub); + this.#sendAnswer(socket.ws, sub, win, cursor, rows); + } + + /** The answer to a subscribe: the window now. With a cursor of this generation and this query, + * every path and only the rows the watcher lacks; otherwise every row. */ + #sendAnswer( + ws: WebSocket, + sub: string, + win: LiveWindow, + rawCursor: unknown, + known?: StoredRow[], + ): void { + const query = win.query; + const q = queryName(query); + const head = `{"sub":${JSON.stringify(sub)},"q":"${q}","gen":${JSON.stringify(this.#gen)},"rev":${win.rev}`; + if (query.kind === "awake") { + const awake = [...this.#deps.awake()].map(([path, state]) => awakeJson(path, state)); + this.#send(ws, `${head},"full":false,"reset":[${awake.join(",")}]}`); + return; + } + const rows = + known || + (query.kind === "range" ? this.#windowRows(query, win.driver) : this.#keysRows(query.keys)); + const full = query.kind === "range" && rows.length === query.limit; + const cursor = WatcherCursor.safeParse(rawCursor).data; + if (!cursor || cursor.gen !== this.#gen || cursor.q !== q) { + this.#send(ws, `${head},"full":${full},"reset":[${rows.map(rowJson).join(",")}]}`); + return; + } + const have = new Set(cursor.have); + const { bound } = cursor; + const held = (row: StoredRow) => + row.rev <= cursor.rev && + (query.kind === "range" + ? !!bound && compareSortKeys(query.order, keyOf(query.order, row), bound) <= 0 + : have.has(row.path)); + const put = rows.filter((row) => !held(row)); + this.counters.rowsNotResent += rows.length - put.length; + this.#send( + ws, + `${head},"full":${full},"ids":${JSON.stringify(rows.map((row) => row.path))},"put":[${put.map(rowJson).join(",")}]}`, + ); + } + + handleWatchClose(ws: WebSocket): void { + try { + ws.close(1000, "closed"); + } catch { + // already closing + } + const attachment = WatchAttachment.safeParse(ws.deserializeAttachment()).data; + if (!attachment) return; + const sockets = this.#loadSockets(); + // a socket that closed is no longer open: when memory does not have its queries, they come + // from its attachment + const subs = sockets.get(attachment.sid)?.subs || new Map(Object.entries(attachment.subs)); + sockets.delete(attachment.sid); + for (const [sub, windowId] of subs) this.#unwatch(windowId, attachment.sid, sub); + } + + // ── What a test and a person can ask ── + + /** Each window's stored size and bound against the rows now. Empty when all agree. */ + verify(): string[] { + const faults: string[] = []; + for (const win of this.#loadWindows().values()) { + if (win.query.kind !== "range") continue; + const rows = this.#windowRows(win.query, win.driver); + const last = rows.length === win.query.limit ? rows.at(-1) : undefined; + const bound = last ? keyOf(win.query.order, last) : null; + if (rows.length !== win.size || JSON.stringify(bound) !== JSON.stringify(win.bound)) + faults.push( + `window ${win.id} ${win.key}: stored size ${win.size} bound ${JSON.stringify(win.bound)}, rows give size ${rows.length} bound ${JSON.stringify(bound)}`, + ); + const newest = rows.reduce((max, row) => Math.max(max, row.rev), 0); + if (newest > win.rev) + faults.push( + `window ${win.id}: a row of revision ${newest} is past the window's ${win.rev}`, + ); + } + return faults; + } + + /** Who watches what, and what the object did since it last woke (iterate/api `CatalogWatches`). */ + watches(options: { verify?: boolean; plans?: boolean } = {}): CatalogWatches { + const windows = [...this.#loadWindows().values()]; + const sockets = this.#loadSockets(); + return { + active: this.#filled.started, + gen: this.#gen, + rev: this.#rev, + rows: + this.#sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM rcat_row").toArray()[0]?.n || 0, + sockets: sockets.size, + awake: this.#deps.awake().size, + windows: windows.map((win) => ({ + query: win.key, + size: win.size, + bound: win.bound, + rev: win.rev, + watchers: [...(this.#watchers.get(win.id)?.values() || [])].reduce( + (sum, subs) => sum + subs.size, + 0, + ), + })), + owed: this.#owed + ? this.#sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM rcat_owed").toArray()[0]?.n || 0 + : 0, + counters: { ...this.counters }, + ...(options.verify && { faults: this.verify() }), + ...(options.plans && { plans: this.#plans() }), + }; + } + + /** How SQLite reads the statements that the engine builds, for one fact, two facts and no fact + * in each order. */ + #plans(): Record<string, string[]> { + const plan = ({ sql, args }: Statement) => + this.#sql + .exec<{ detail: string }>(`EXPLAIN QUERY PLAN ${sql}`, ...args) + .toArray() + .map((row) => row.detail); + const plans: Record<string, string[]> = {}; + const at: SortKey = [1_000, "/t"]; + for (const order of Object.keys(ORDER_INDEX) as CatalogOrder[]) { + const queries: Record<string, RangeQuery> = { + "no fact": { kind: "range", predicates: [], order, limit: 50 }, + "one fact": { kind: "range", predicates: [["status", "open"]], order, limit: 50 }, + "two facts": { + kind: "range", + predicates: [ + ["priority", "high"], + ["status", "open"], + ], + order, + limit: 50, + }, + }; + for (const [facts, query] of Object.entries(queries)) { + plans[`${order}, ${facts}: the window`] = plan(this.#windowSql(query, 0)); + plans[`${order}, ${facts}: the follower (the backfill)`] = plan( + this.#followerSql(query, 0, at), + ); + plans[`${order}, ${facts}: the row above the bound`] = plan(this.#edgeSql(query, 0, at)); + plans[`${order}, ${facts}: the last matching row`] = plan(this.#edgeSql(query, 0, null)); + } + } + plans["rows by key"] = plan({ + sql: `SELECT ${ROW_COLUMNS} FROM rcat_row r WHERE r.path IN (SELECT value FROM json_each(?))`, + args: ["[]"], + }); + return plans; + } +} + +type WriteResult = { + /** The catalog's revision after the write. */ + rev: number; + /** How many rows changed: a row equal to the stored one is not counted. */ + changed: number; + /** How many windows got a frame. */ + frames: number; + /** How many socket messages carried them, and their length in characters. */ + messages: number; + chars: number; +}; + +/** A row as the catalog can order and index it. A time that is no whole number of milliseconds + * orders differently in SQLite and in JavaScript, and so does a path that is not well-formed. + * Every other field passes: it is the row's body. */ +const RowInput = z.looseObject({ + path: ContextPath, + activeMs: z.number().int(), + createdMs: z.number().int(), + processors: z.array(z.string()).default([]), + metadata: z.record(z.string(), z.unknown()).default({}), +}); + +/** A window's query, read back from its stored key (`normalizeQuery` wrote it). */ +function queryOfKey(key: string): Query { + const stored = JSON.parse(key) as { p?: Fact[]; o?: CatalogOrder; l?: number; k?: string[] }; + if (stored.p) + return { + kind: "range", + predicates: stored.p, + order: stored.o || "active", + limit: stored.l || 50, + }; + return stored.k ? { kind: "keys", keys: stored.k } : { kind: "awake" }; +} + +function driverFactOf(win: LiveWindow): string { + const fact = win.query.kind === "range" ? win.query.predicates[win.driver] : undefined; + return fact ? factId(fact) : "*"; +} + +/** A row of the awake list (iterate/api `CatalogAwakeRow`). */ +function awakeJson(path: string, state: AwakeContextState): string { + const activities = activeContextActivities(state.activities); + return JSON.stringify({ path, since: state.since, ...(activities.length > 0 && { activities }) }); +}
M core/itx/src/iterate-context-durable-object.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/itx/src/iterate-context.ts
@@ -47,6 +47,15 @@ type ItxExpressionResolver, } from "./context/itx-expression-rewriting.ts"; import { FETCH_UPGRADE_CONTEXT_HEADER, type LentFetchHolder } from "./context/fetch-upgrade.ts"; +import { AWAKE_CONTEXT_PATH } from "./context/awake.ts"; +import { + CATALOG_WATCH_HEADER, + CatalogWatchRelay, + catalogWatchRelayOf, + isCatalogWatchTicket, + refuseLoadedCode, + type CatalogWatchHandle, +} from "./context/catalog-watch.ts"; import { lendRefusal } from "./context/lent-names.ts"; import { FetchRouteConfiguredPayload } from "./fetch-routes.ts"; import type { BuiltInScope } from "./context/built-ins.ts"; @@ -95,8 +104,10 @@ } // Declaration merging types the built-in roots; the prototype fallback below is the runtime. -export interface IterateContextRpcTarget extends Omit<BuiltInScope, "cd" | "facets"> { +export interface IterateContextRpcTarget extends Omit<BuiltInScope, "cd" | "facets" | "contexts"> { facets: IterateContextApi["facets"]; + // `watch` is this edge's own (`#watchContexts`): the table answers its ticket alone + contexts: IterateContextApi["contexts"]; } type StatelessReach = ( @@ -189,7 +200,10 @@ // the context it was reached through has read its answer already if (this.#reachedThrough) return this.#reachedThrough(normalizedItxExpression(call).slice(1), args); - const answer = await this.#dispatch(call, args); + const expression = normalizedItxExpression(call); + const watch = contextsWatchOf(expression, args); + if (watch) return this.#watchContexts(watch); + const answer = await this.#dispatch(expression, args); if (!(answer instanceof Response)) return answer; const refused = await loopLimitOf(answer); if (refused) throw refused; @@ -228,6 +242,59 @@ return this.#invokeOnDurableObject(itxExpression, args); } + /** `itx.contexts.watch(query, onFrame, options?)`: THE CATALOG KEEPS ANSWERING A QUERY, and each + * frame of its answer goes to the caller's function over the caller's own session. The + * function is a live stub, which stays at this edge (the head of this file). So the call has + * two halves: + * 1. the query goes through this context's table, as `contexts.list` goes, to the built-in + * `contexts.watch`, which answers a ticket. Who may list may watch, and a table that + * sends `contexts` elsewhere sends the watch there too; + * 2. with the ticket, the session's ONE socket into the catalog takes the query + * (./context/catalog-watch.ts), and its frames are handed to the function. + * Loaded code has no session whose end could hold the socket, and reads `contexts.list`. */ + async #watchContexts(watch: { + root: ItxExpression; + query: unknown; + onFrame: unknown; + options: unknown; + }): Promise<CatalogWatchHandle> { + refuseLoadedCode(this.#caller, "watch"); + if (typeof watch.onFrame !== "function") + throw codedError( + "INVALID_INPUT", + "contexts.watch(query, onFrame, options?): onFrame is the function that each frame goes to", + ); + const ticket = await this.#dispatch( + [ + ...watch.root, + // an absent option stays absent: the built-in refuses any second argument but `{ cursor? }` + watch.options === undefined + ? ["watch", watch.query] + : ["watch", watch.query, watch.options], + ], + [], + ); + if (!isCatalogWatchTicket(ticket)) + throw codedError( + "NOT_A_METHOD", + "contexts.watch: what answers `contexts` at this context is not the mind's catalog", + ); + return catalogWatchRelayOf( + this.#sessionTeardown, + () => + new CatalogWatchRelay({ + dial: () => + this.#contextNamespace + .getByName(DurableObjectNameCodec.stringify(AWAKE_CONTEXT_PATH)) + .fetch("https://catalog-watch/", { + headers: { Upgrade: "websocket", [CATALOG_WATCH_HEADER]: "1" }, + }), + waitUntil: this.#waitUntil, + }), + (relay) => this.#sessionTeardown.add("catalog-watch", relay), + ).watch(ticket, watch.onFrame as Parameters<CatalogWatchRelay["watch"]>[1]); + } + /** What this context's Durable Object answers as `<steps>.fetch(request)` by this caller. */ #contextFetchRequest(steps: ItxExpression, request: Request): Request { const headers = new Headers(request.headers); @@ -477,6 +544,22 @@ } installPrototypeInvokeFallback(IterateContextRpcTarget, ["itx"]); + +/** The parts of `itx.contexts.watch(query, onFrame, options?)` (or `itx.builtins.contexts.watch`), + * when `expression` is that call, however its arguments came: in its last step, as the dotted + * call puts them, or beside the expression. `root` is what stands before `watch`. */ +function contextsWatchOf( + expression: ItxExpression, + args: unknown[], +): { root: ItxExpression; query: unknown; onFrame: unknown; options: unknown } | undefined { + const last = expression.at(-1); + const root = expression.slice(0, -1); + if (!last || itxExpressionStepName(last) !== "watch" || root.at(-1) !== "contexts") + return undefined; + if (root.length !== (root[1] === "builtins" ? 3 : 2)) return undefined; + const [query, onFrame, options] = typeof last === "string" ? args : [...last.slice(1), ...args]; + return { root, query, onFrame, options }; +} /** THE MIND'S ROOT CONTEXT FOR ONE SESSION THAT ENDS IN ANOTHER WORKER: the boundary ends every * session of the API and holds what this answers as a Workers RPC stub (the mind Worker's
M core/lib/src/api.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/lib/src/lib.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/catalog-watch.test.ts
@@ -0,0 +1,393 @@ +// catalog-watch.test.ts — `itx.contexts.watch` in workerd (./fixtures/catalog-watch.ts): a client +// with one capnweb connection and a callback, real contexts that say what they are through their +// own logs, the object that accepts their awake sockets with its SQLite, and the hibernation API's +// sockets between them. Nothing here writes a row of the catalog: every row comes from a context's +// `events.iterate.com/itx/described` on its own log, as it does in a mind. +import { fileURLToPath } from "node:url"; +import { build } from "esbuild"; +import { Miniflare } from "miniflare"; +import { newWebSocketRpcSession } from "capnweb"; +import type { + CatalogAwakeRow, + CatalogCursor, + CatalogFrame, + CatalogQuery, + CatalogRow, + CatalogWatches, + ContextListing, +} from "iterate/api"; +import { COMPATIBILITY_DATE } from "iterate/compatibility-date"; +import { expect, test } from "vitest"; + +test.for([ + { ends: "the mind's own Worker, as a page's /itx does", path: "/page" }, + { ends: "the boundary, as the API's does", path: "/" }, +])( + "a session that ends in $ends: the answer and then each change come to the watcher's callback", + { timeout: 60_000 }, + async ({ path }) => { + await using runtime = await mind(); + using itx = await session(runtime, path); + await described(itx, "/tasks/one", { status: "open", title: "One" }); + await described(itx, "/tasks/two", { status: "closed", title: "Two" }); + await listed(itx, { "/tasks/one": "open", "/tasks/two": "closed" }); + + // 1. the answer: the open task, and no other context. The call resolves when the watcher's + // function has returned from it, so the answer is here. + const open = watcher(); + using _watch = await itx.contexts.watch({ where: { status: "open" }, limit: 5 }, open.take); + expect(open.frames[0]).toMatchObject({ + type: "reset", + full: false, + rows: [ + { + path: "/tasks/one", + metadata: { status: "open", title: "One" }, + description: "What /tasks/one is for", + processors: [], + }, + ], + }); + // a watched row is the context's listing, with the two times that the orders sort by + const [one] = open.rows(); + expect(one).toMatchObject({ + activeMs: Date.parse(one!.lastActivityAt || one!.lastEventAt || ""), + createdMs: Date.parse(one!.createdAt || ""), + eventCount: expect.any(Number), + eventTypes: { "events.iterate.com/itx/described": 1 }, + }); + + // 2. a context enters the answer: a frame with its row. (A context that works says a little + // more of itself when it goes quiet, so a frame for a row of the answer may follow any time.) + await described(itx, "/tasks/two", { status: "open", title: "Two" }); + await open.until((rows) => rows.length === 2); + expect(open.frames).toContainEqual( + expect.objectContaining({ + type: "change", + del: [], + rows: [expect.objectContaining({ path: "/tasks/two" })], + }), + ); + // the newest activity first + expect(open.rows().map((row) => row.path)).toEqual(["/tasks/two", "/tasks/one"]); + + // 3. a context leaves it: a frame with its path, and no row + await described(itx, "/tasks/one", { status: "closed", title: "One" }); + await open.until((rows) => rows.length === 1); + expect(open.frames).toContainEqual( + expect.objectContaining({ type: "change", del: ["/tasks/one"], rows: [] }), + ); + + // 4. a context that the query does not select reaches this watcher in no frame + await described(itx, "/tasks/three", { status: "closed" }); + await listed(itx, { "/tasks/three": "closed" }); + await quiet(itx); + expect(open.frames.flatMap((frame) => frame.rows.map((row) => row.path))).not.toContain( + "/tasks/three", + ); + + // 5. every frame followed the one before it + expect(open).toMatchObject({ gaps: [] }); + }, +); + +test.for([ + { ends: "the mind's own Worker", path: "/page" }, + { ends: "the boundary", path: "/" }, +])( + "one write is one batch for a session that ends in $ends: a watcher of three queries gets their frames together, the last one marked", + { timeout: 60_000 }, + async ({ path }) => { + await using runtime = await mind(); + using itx = await session(runtime, path); + await described(itx, "/tasks/one", { status: "open" }); + await listed(itx, { "/tasks/one": "open" }); + await quiet(itx); + const batches: string[][] = []; + let batch: string[] = []; + const take = (name: string) => (frame: CatalogFrame) => { + if (frame.type !== "change") return; + batch.push(name); + if (frame.more) return; + batches.push(batch); + batch = []; + }; + using _open = await itx.contexts.watch({ where: { status: "open" } }, take("open")); + using _byPath = await itx.contexts.watch({ under: "/tasks", order: "path" }, take("byPath")); + using _key = await itx.contexts.watch({ keys: ["/tasks/one"] }, take("key")); + // five writes, each of which changes all three answers + for (let round = 1; round <= 5; round++) { + await described(itx, "/tasks/one", { status: "open", title: `Renamed ${round}` }); + await listed(itx, { "/tasks/one": "open" }); + await quiet(itx); + } + await until(() => batches.length >= 5 && batch.length === 0); + // every batch is whole: no frame of one write came after the frame that ends its batch + expect(batches.map((frames) => frames.toSorted())).toEqual( + batches.map(() => ["byPath", "key", "open"]), + ); + }, +); + +test.for([ + { ends: "the mind's own Worker", path: "/page" }, + { ends: "the boundary", path: "/" }, +])( + "a session that ends in $ends: the dispose of a watch's handle takes its query off the catalog, and the others stay", + { timeout: 60_000 }, + async ({ path }) => { + await using runtime = await mind(); + using itx = await session(runtime, path); + const queries = async () => + (await itx.contexts.watches()).windows.map((window) => window.query).toSorted(); + using _kept = await itx.contexts.watch({ limit: 5 }, () => {}); + const gone = await itx.contexts.watch({ order: "path", limit: 7 }, () => {}); + expect(await queries()).toEqual(['{"p":[],"o":"active","l":5}', '{"p":[],"o":"path","l":7}']); + gone[Symbol.dispose](); + await until(async () => (await queries()).length === 1); + expect(await itx.contexts.watches()).toMatchObject({ + sockets: 1, + windows: [{ query: '{"p":[],"o":"active","l":5}', watchers: 1 }], + }); + }, +); + +test( + "a watcher that comes back with its cursor gets every path and only the rows it lacks", + { timeout: 60_000 }, + async () => { + await using runtime = await mind(); + const query: CatalogQuery = { childrenOf: "/tasks", order: "path", limit: 10 }; + let cursor: CatalogCursor; + { + using itx = await session(runtime, "/"); + for (const name of ["a", "b", "c"]) + await described(itx, `/tasks/${name}`, { status: "open" }); + await listed(itx, { "/tasks/a": "open", "/tasks/b": "open", "/tasks/c": "open" }); + // each context has said its last word: no row changes behind the cursor + await quiet(itx); + const first = watcher(); + using _watch = await itx.contexts.watch(query, first.take); + const last = first.frames.at(-1)!; + if (last.type !== "reset") throw new Error("the first answer is every row"); + // by path, A to Z + expect(last.rows.map((row) => row.path)).toEqual(["/tasks/a", "/tasks/b", "/tasks/c"]); + // what the watcher holds: the order `path` has no time, so the bound's first part is 0 + cursor = { gen: last.gen, rev: last.rev, q: last.q, bound: [0, "/tasks/c"] }; + } + // the session is over; one row changes while the watcher is away + using itx = await session(runtime, "/"); + await described(itx, "/tasks/b", { status: "closed" }); + await listed(itx, { "/tasks/b": "closed" }); + await quiet(itx); + const again = watcher(); + using _watch = await itx.contexts.watch(query, again.take, { cursor }); + expect(again.frames[0]).toMatchObject({ + type: "resume", + ids: ["/tasks/a", "/tasks/b", "/tasks/c"], + rows: [{ path: "/tasks/b", metadata: { status: "closed" } }], + }); + }, +); + +test( + "the awake list is a watch too, and the catalog says who watches what", + { timeout: 60_000 }, + async () => { + await using runtime = await mind(); + using itx = await session(runtime, "/page"); + const awake: CatalogFrame<CatalogAwakeRow>[] = []; + using _watch = await itx.contexts.watch<CatalogAwakeRow>( + { awake: true }, + (frame) => void awake.push(frame), + ); + expect(awake[0]).toMatchObject({ type: "reset" }); + // the awake list needs no row: the catalog keeps none until a query asks for rows + expect(await itx.contexts.watches()).toMatchObject({ active: false, rows: 0, sockets: 1 }); + + await described(itx, "/tasks/one", { status: "open" }); + // the context wakes, and a second after its work it goes quiet + await until(() => + awake.some( + (frame) => frame.type === "change" && frame.rows.some((row) => row.path === "/tasks/one"), + ), + ); + await until(() => + awake.some((frame) => frame.type === "change" && frame.del.includes("/tasks/one")), + ); + + using _open = await itx.contexts.watch({ where: { status: "open" } }, () => {}); + const watches = await itx.contexts.watches({ verify: true, plans: true }); + expect(watches).toMatchObject({ active: true, sockets: 1, faults: [] }); + expect(watches.windows.map((window) => window.query).toSorted()).toEqual([ + '{"awake":true}', + '{"p":[["status","open"]],"o":"active","l":50}', + ]); + // WORKERD'S OWN SQLITE reads each statement by one index, in its order: no sort in a + // temporary b-tree, and no scan of an index of facts. With no fact the rows themselves are + // read in the order's own index, which SQLite calls a scan: it stops at the limit. + for (const [statement, plan] of Object.entries(watches.plans!)) { + expect(plan.join(" | "), statement).not.toMatch(/TEMP B-TREE|SCAN f/); + if (!statement.includes("no fact") && statement !== "rows by key") + expect(plan.join(" | "), statement).not.toMatch(/SCAN/); + } + expect(watches.plans!["active, one fact: the follower (the backfill)"]).toEqual([ + "SEARCH f0 USING PRIMARY KEY (k=? AND v=? AND (active_at,path)<(?,?))", + "SEARCH r USING PRIMARY KEY (path=?)", + ]); + }, +); + +test( + "a query that the catalog cannot answer exactly rejects the call, and the end of a session ends its watches", + { timeout: 60_000 }, + async () => { + await using runtime = await mind(); + const itx = await session(runtime, "/"); + await expect(itx.contexts.watch({ orderBy: "title" } as never, () => {})).rejects.toThrow( + /orderBy/, + ); + await expect(itx.contexts.watch({ limit: 5_000 }, () => {})).rejects.toThrow(/limit/); + // a watch is the catalog's alone: another context has no `contexts` + await expect(itx.cd("/tasks/one").contexts.watch({}, () => {})).rejects.toThrow(); + await itx.contexts.watch({ limit: 5 }, () => {}); + expect(await itx.contexts.watches()).toMatchObject({ sockets: 1 }); + itx[Symbol.dispose](); + using other = await session(runtime, "/"); + await until(async () => (await other.contexts.watches()).sockets === 0); + expect(await other.contexts.watches()).toMatchObject({ windows: [] }); + }, +); + +type Session = Disposable & { + cd(path: string): Session; + append(event: { type: string; payload: unknown }): Promise<unknown>; + contexts: { + list(options?: { under?: string }): Promise<ContextListing[]>; + watch<Row = CatalogRow>( + query: CatalogQuery, + onFrame: (frame: CatalogFrame<Row>) => void, + options?: { cursor?: CatalogCursor }, + ): Promise<Disposable>; + watches(options?: { verify?: boolean; plans?: boolean }): Promise<CatalogWatches>; + }; +}; + +async function session(runtime: Miniflare, path: string): Promise<Session> { + const origin = (await runtime.ready).href.replace(/^http/, "ws").replace(/\/$/, ""); + return newWebSocketRpcSession<Session>(`${origin}${path}`) as unknown as Session; +} + +/** A context says what it is, on its own log: the one way a row of the catalog comes to be. */ +async function described(itx: Session, path: string, metadata: Record<string, unknown>) { + await itx.cd(path).append({ + type: "events.iterate.com/itx/described", + payload: { description: `What ${path} is for`, metadata }, + }); +} + +/** Until the catalog has each context's own word of its status: a summary travels the context's + * awake socket first. A context is listed as awake before that, with no row. */ +async function listed(itx: Session, statusByPath: Record<string, string>) { + await until(async () => { + const rows = new Map((await itx.contexts.list()).map((row) => [row.path, row.metadata])); + return Object.entries(statusByPath).every( + ([path, status]) => rows.get(path)?.status === status, + ); + }); +} + +/** Until no context under /tasks is awake: each has sent its last summary and closed its socket. */ +async function quiet(itx: Session) { + await until(async () => + (await itx.contexts.list({ under: "/tasks" })).every((row) => !row.awake), + ); +} + +async function until(done: () => boolean | Promise<boolean>): Promise<void> { + for (let attempt = 0; attempt < 200; attempt++) { + if (await done()) return; + await new Promise((resolve) => setTimeout(resolve, 50)); + } + throw new Error("it did not come within 10 s"); +} + +/** A watcher as a page is one: it keeps the rows of one query, frame by frame. */ +function watcher() { + const rows = new Map<string, CatalogRow>(); + const state = { + frames: [] as CatalogFrame[], + /** A change frame whose `from` is not the revision of the frame before. */ + gaps: [] as CatalogFrame[], + rev: -1, + take: (frame: CatalogFrame) => { + state.frames.push(frame); + if (frame.type === "change") { + if (frame.from !== state.rev) state.gaps.push(frame); + for (const path of frame.del) rows.delete(path); + } else { + const keep = new Set(frame.type === "reset" ? [] : frame.ids); + for (const path of [...rows.keys()]) if (!keep.has(path)) rows.delete(path); + } + for (const row of frame.rows) rows.set(row.path, row); + state.rev = frame.rev; + }, + /** The rows, the newest activity first. */ + rows: () => [...rows.values()].toSorted((a, b) => b.activeMs - a.activeMs), + until: (done: (rows: CatalogRow[]) => boolean) => until(() => done(state.rows())), + }; + return state; +} + +async function mind() { + const fixture = await build({ + entryPoints: [fileURLToPath(new URL("./fixtures/catalog-watch.ts", import.meta.url).href)], + bundle: true, + write: false, + format: "esm", + platform: "neutral", + mainFields: ["module", "main"], + conditions: ["workerd"], + target: "es2022", + external: ["cloudflare:*", "node:*"], + }); + const script = { + compatibilityDate: COMPATIBILITY_DATE, + compatibilityFlags: ["nodejs_compat", "allow_irrevocable_stub_storage"], + manifest: { + mainModule: "worker.js", + modules: { "worker.js": { type: "esm" as const, contents: fixture.outputFiles[0]!.text } }, + }, + }; + const runtime = new Miniflare({ + workers: [ + { + config: { + ...script, + name: "boundary", + env: { MIND: { type: "worker", worker: "mind", exportName: "Mind" } }, + }, + }, + { + config: { + ...script, + name: "mind", + env: { + CONTEXTS: { + type: "durable-object", + worker: "mind", + exportName: "IterateContextDurableObject", + }, + CF_VERSION_METADATA: { type: "version-metadata" }, + }, + exports: { + IterateContextDurableObject: { type: "durable-object", storage: "sqlite" }, + ItxEntrypoint: { type: "worker" }, + }, + }, + }, + ], + }); + await runtime.ready; + return Object.assign(runtime, { [Symbol.asyncDispose]: () => runtime.dispose() }); +}
A core/mind-worker/src/context/fixtures/catalog-watch.ts
@@ -0,0 +1,45 @@ +// catalog-watch.ts — a watch of the mind's catalog (`itx.contexts.watch`) from a client's callback +// to the object that owns the rows and back, run in workerd by ../catalog-watch.test.ts. Two +// Workers of one bundle, as a stack has them: "mind" runs the kernel (core-itx), and "boundary" +// ends a client's capnweb session and holds the mind's part of it through core/boundary-worker's +// own `SessionMind`. A client reaches the mind in the two ways a session ends: +// /page the session ends in the mind's own Worker, as a page's `/itx` does (`serveSession`) +// / the session ends in the boundary, as the API's does (`sessionContext` over Workers RPC) +import { WorkerEntrypoint } from "cloudflare:workers"; +import { newWebSocketRpcSession } from "capnweb"; +import { defineItxHost, serveSession, sessionContext } from "core-itx"; +import { SessionMind, type MindApiStub } from "../../../../boundary-worker/src/session-mind.ts"; + +export { IterateContextDurableObject, ItxEntrypoint } from "core-itx"; + +type Env = { MIND: Service<Mind> }; + +defineItxHost({ firstPartyFacets: {} }); + +const member = { principal: { actor: "usr_aaaaabbbbbccccc", email: "member@mind.example" } }; + +export class Mind extends WorkerEntrypoint<Env> { + override fetch() { + return serveSession(this.ctx, { caller: member, endsAt: null, endReason: "" }); + } + + api() { + return sessionContext((promise) => this.ctx.waitUntil(promise), member); + } +} + +export default { + async fetch(request: Request, env: Env) { + if (new URL(request.url).pathname === "/page") return env.MIND.fetch(request); + // the boundary: the client's session, whose `mind` is the mind's own part of it + // (core/boundary-worker/src/control-plane-api.ts `#watchedMind`) + const stub = (await env.MIND.api()) as unknown as MindApiStub; + const pair = new WebSocketPair(); + pair[1].accept(); + newWebSocketRpcSession( + pair[1] as unknown as WebSocket, + new SessionMind(stub, (dial) => env.MIND.fetch(dial), false), + ); + return new Response(null, { status: 101, webSocket: pair[0] }); + }, +} satisfies ExportedHandler<Env>;