diff --git a/src/contract/AGENTS.md b/src/contract/AGENTS.md index a463ecc81..715684d66 100644 --- a/src/contract/AGENTS.md +++ b/src/contract/AGENTS.md @@ -55,7 +55,7 @@ Three identities: ## Protocol version -- `PROTOCOL_VERSION_RANGE` in `protocol.ts` holds it, now `{ min: 51, max: 51 }`. `DAEMON_PROTOCOL_VERSION` (`src/daemon-protocol/`) is its `max`. +- `PROTOCOL_VERSION_RANGE` in `protocol.ts` holds it, now `{ min: 52, max: 52 }`. `DAEMON_PROTOCOL_VERSION` (`src/daemon-protocol/`) is its `max`. - Every change to a contract shape bumps it by one in the same PR. Move `min` too, unless a compatibility path stays side by side. `.agents/scripts/protocol-bump-check.mjs` checks it on push and in CI; it counts every file here as a shape but tests, `index.ts` and the @@ -68,7 +68,7 @@ Three identities: - `SimlockErrorCode` is a closed union (`ErrorDetailsMap`). `ERROR_TABLE` gives each code `kind` (`transport` | `protocol` | `domain`), `cliExitCode` and `httpStatus`. -- `HISTORY_NOT_KEPT` (exit 12, 422, `details.oldestTs`) and `HISTORY_UNAVAILABLE` (exit 1, 503) are `usage.get`'s; `includeLedger` adds `requests[]` (at most 100,000, newest; `ledgerTruncated` when cut); the window it takes is bounded by `usageWindowSchema` (integers to 8.64e15, `from < to`, 90 days at most) and `usageWindow` (`usage-window.ts`) parses the CLI's flags once for every surface. +- `HISTORY_NOT_KEPT` (exit 12, 422, `details.oldestTs`) and `HISTORY_UNAVAILABLE` (exit 1, 503) are `usage.get`'s and `events.replay`'s with `beforeId`; `includeLedger` adds `requests[]` (at most 100,000, newest; `ledgerTruncated` when cut); the window it takes is bounded by `usageWindowSchema` (integers to 8.64e15, `from < to`, 90 days at most) and `usageWindow` (`usage-window.ts`) parses the CLI's flags once for every surface. `events.replay` takes `beforeId` and `limit` (1 to 500), refused with `sinceTs`; `eventsPageQuery` (`events-page.ts`) parses the HTTP query once, with the bounds. - `fromWireError` wraps an unknown code as `UNKNOWN_DAEMON_ERROR`. That code and `CANCELLED` are built client side only. - `CODES_WITH_DECLARED_DETAILS`: codes whose `details` are contract. The compiler keeps it diff --git a/src/contract/events-page.test.ts b/src/contract/events-page.test.ts new file mode 100644 index 000000000..f2b28bd3e --- /dev/null +++ b/src/contract/events-page.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from "vitest"; + +import { eventsPageQuery } from "./events-page.js"; + +describe("eventsPageQuery", () => { + it("accepts 5, 500 and an id evt_a-B_9, and refuses 0, 501, 05, +5, ' 5', 5.0, 1e2, x, an id not-an-id, before with since, and limit with since, each with its message", () => { + expect(eventsPageQuery({ limit: "5" })).toEqual({ page: { limit: 5 } }); + expect(eventsPageQuery({ limit: "500" })).toEqual({ page: { limit: 500 } }); + expect(eventsPageQuery({ before: "evt_a-B_9" })).toEqual({ page: { beforeId: "evt_a-B_9" } }); + expect(eventsPageQuery({ since: "1h" })).toEqual({ page: {} }); + + const badLimit = { refused: "limit must be a whole number from 1 to 500" }; + for (const limit of ["0", "501", "05", "+5", " 5", "5.0", "1e2", "x", ""]) { + expect(eventsPageQuery({ before: "evt_abc", limit })).toEqual(badLimit); + } + for (const before of ["not-an-id", "evt_", ""]) { + expect(eventsPageQuery({ before })).toEqual({ refused: "before must be an event id" }); + } + expect(eventsPageQuery({ before: "evt_abc", since: "1h" })).toEqual({ + refused: "before and since cannot be used together", + }); + expect(eventsPageQuery({ limit: "50", since: "1h" })).toEqual({ + refused: "limit and since cannot be used together", + }); + }); +}); diff --git a/src/contract/events-page.ts b/src/contract/events-page.ts new file mode 100644 index 000000000..378b4462d --- /dev/null +++ b/src/contract/events-page.ts @@ -0,0 +1,54 @@ +import { EVENT_ID_PATTERN } from "./schemas.js"; + +export const EVENTS_PAGE_MAX = 500; +export const EVENTS_PAGE_DEFAULT = 100; + +export interface EventsPageAsk { + readonly before?: string | undefined; + readonly limit?: string | undefined; + readonly since?: string | undefined; +} + +export type EventsPageAnswer = + | { readonly page: { readonly beforeId?: string; readonly limit?: number } } + | { readonly refused: string }; + +const LIMIT_DIGITS = /^[1-9]\d{0,2}$/; + +export function eventsPageQuery(ask: EventsPageAsk): EventsPageAnswer { + if (ask.before !== undefined && !EVENT_ID_PATTERN.test(ask.before)) { + return { refused: "before must be an event id" }; + } + const limit = ask.limit === undefined ? undefined : parseLimit(ask.limit); + if (ask.limit !== undefined && limit === undefined) { + return { refused: "limit must be a whole number from 1 to 500" }; + } + if (ask.since !== undefined && ask.before !== undefined) { + return { refused: "before and since cannot be used together" }; + } + if (ask.since !== undefined && limit !== undefined) { + return { refused: "limit and since cannot be used together" }; + } + return { + page: { + ...(ask.before === undefined ? {} : { beforeId: ask.before }), + ...(limit === undefined ? {} : { limit }), + }, + }; +} + +function parseLimit(value: string): number | undefined { + if (!LIMIT_DIGITS.test(value)) return undefined; + const limit = Number(value); + return limit <= EVENTS_PAGE_MAX ? limit : undefined; +} + +export const EVENTS_PAGE_WITH_SINCE_MESSAGE = "beforeId and limit cannot be used with sinceTs"; + +export function eventsPageWithoutSince(input: { + readonly beforeId?: unknown; + readonly limit?: unknown; + readonly sinceTs?: unknown; +}): boolean { + return input.sinceTs === undefined || (input.beforeId === undefined && input.limit === undefined); +} diff --git a/src/contract/index.ts b/src/contract/index.ts index 787307fa8..2805ce050 100644 --- a/src/contract/index.ts +++ b/src/contract/index.ts @@ -8,5 +8,6 @@ export * from "./pushes.js"; export * from "./relay.js"; export * from "./roles.js"; export * from "./schemas.js"; +export * from "./events-page.js"; export * from "./usage-window.js"; export * from "./worker-view.js"; diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index 43764ef7f..ed0e761cd 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -1631,3 +1631,18 @@ describe("usage.get input", () => { expect(parse({ from: 0 }).success).toBe(false); }); }); + +describe("events.replay input", () => { + const parse = (input: unknown) => OPERATIONS["events.replay"].input.safeParse(input); + + it("accepts beforeId and limit in bounds, and refuses limit 0, 501 and 1.5, a beforeId of evt_ or abc, and beforeId or limit with sinceTs", () => { + expect(parse({ beforeId: "evt_abc", limit: 1 }).success).toBe(true); + expect(parse({ limit: 500 }).success).toBe(true); + expect(parse({ sinceTs: 5 }).success).toBe(true); + + for (const limit of [0, 501, 1.5]) expect(parse({ limit }).success).toBe(false); + for (const beforeId of ["evt_", "abc"]) expect(parse({ beforeId }).success).toBe(false); + expect(parse({ beforeId: "evt_abc", sinceTs: 5 }).success).toBe(false); + expect(parse({ limit: 5, sinceTs: 5 }).success).toBe(false); + }); +}); diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 7d2a1ddfd..25b84a0bb 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -10,6 +10,11 @@ import { z } from "zod"; import { CONSOLE_URL_MAX_LENGTH } from "./console-url.js"; +import { + EVENTS_PAGE_MAX, + EVENTS_PAGE_WITH_SINCE_MESSAGE, + eventsPageWithoutSince, +} from "./events-page.js"; import { parseOsConstraint } from "./os-range.js"; import { relayChannelSchema, relayHeadersSchema, relayIdSchema } from "./relay.js"; import { ownsLease, type AuthorizeContext, type Role } from "./roles.js"; @@ -24,6 +29,7 @@ import { deviceRecordSchema, doctorReportSchema, eventEnvelopeSchema, + EVENT_ID_PATTERN, hostFactsSchema, historyStatusSchema, hostLoadSchema, @@ -645,7 +651,13 @@ export const eventsReplay = defineOperation({ name: "events.replay", role: "admin", effect: "read", - input: z.object({ sinceTs: z.number().optional() }), + input: z + .object({ + beforeId: z.string().regex(EVENT_ID_PATTERN).optional(), + limit: z.number().int().min(1).max(EVENTS_PAGE_MAX).optional(), + sinceTs: z.number().optional(), + }) + .refine(eventsPageWithoutSince, { message: EVENTS_PAGE_WITH_SINCE_MESSAGE }), output: z.array(eventEnvelopeSchema), }); diff --git a/src/contract/protocol.test.ts b/src/contract/protocol.test.ts index 9ded06cb0..5f06d3ed2 100644 --- a/src/contract/protocol.test.ts +++ b/src/contract/protocol.test.ts @@ -48,6 +48,6 @@ describe("helloRequestSchema", () => { describe("PROTOCOL_VERSION_RANGE", () => { it("is one above the base branch's, for the alerts.test operation", () => { - expect(PROTOCOL_VERSION_RANGE).toEqual({ max: 51, min: 51 }); + expect(PROTOCOL_VERSION_RANGE).toEqual({ max: 52, min: 52 }); }); }); diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index e389ca30f..d537902ce 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -10,7 +10,7 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 51, max: 51 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 52, max: 52 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; diff --git a/src/daemon-protocol/index.test.ts b/src/daemon-protocol/index.test.ts index 7552c3b31..6ceef37ca 100644 --- a/src/daemon-protocol/index.test.ts +++ b/src/daemon-protocol/index.test.ts @@ -9,7 +9,7 @@ import { describe("daemon protocol", () => { it("keeps the current protocol version and newline framing", () => { - expect(DAEMON_PROTOCOL_VERSION).toBe(51); + expect(DAEMON_PROTOCOL_VERSION).toBe(52); expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n'); }); diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index aaa4cc678..f386f1cc2 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -52,7 +52,7 @@ An HTTP bind failure after a good start stops the daemon (`http-start-failed`). Principal: `hello.principal`, else `SIMLOCK_AGENT_ID`, else the daemon's pid. Both are fixed for the connection's life. 3. **Version** — ranges overlap → highest common version. `PROTOCOL_VERSION_RANGE` - is `{ min: 51, max: 51 }` (`src/contract/protocol.ts`). No overlap → the + is `{ min: 52, max: 52 }` (`src/contract/protocol.ts`). No overlap → the connection stays open, and every request but `daemon.stop` gets `PROTOCOL_VERSION_UNSUPPORTED`. 4. **Request** — one frame → one `dispatch()` call. While stopping: `DAEMON_STOPPING`. diff --git a/src/daemon/dispatch.ts b/src/daemon/dispatch.ts index 92ffd1895..b452733e7 100644 --- a/src/daemon/dispatch.ts +++ b/src/daemon/dispatch.ts @@ -15,6 +15,8 @@ */ import type { z } from "zod"; +import type { EventEnvelope } from "../bus/index.js"; +import type { EventsPageRead } from "../history/index.js"; import type { Clock } from "../ports/clock.js"; import type { Logger } from "../ports/logger.js"; import type { LinkChannel } from "../link/index.js"; @@ -430,3 +432,27 @@ export async function usageAnswer( { oldestTs: result.oldestTs }, ); } + +export async function eventsPageAnswer(read: Promise): Promise { + let result: EventsPageRead; + try { + result = await read; + } catch (error) { + throw new DispatchError( + "INTERNAL", + `The events could not be read: ${error instanceof Error ? error.message : String(error)}`, + ); + } + if (result.kind === "events") return result.events; + if (result.kind === "unavailable") { + throw new DispatchError( + "HISTORY_UNAVAILABLE", + "The history could not be read, so no older events can be returned; see daemon.log.", + ); + } + throw new DispatchError( + "HISTORY_NOT_KEPT", + `The history does not hold that event; it starts at ${new Date(result.oldestTs).toISOString()}.`, + { oldestTs: result.oldestTs }, + ); +} diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 891c2fb13..c7e458017 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -15,6 +15,7 @@ import type { EventHistoryHandle } from "../history/index.js"; import { fixedEventHistory, HOUR, + plainProjection, removeUsageRigs, requested, ringEventHistory, @@ -133,8 +134,8 @@ function stallOptions( function resolveEventHistoryOverride( eventBus: EventBus, - override: Pick | undefined, -): Pick { + override: Pick | undefined, +): Pick { return override ?? ringEventHistory(eventBus); } @@ -270,7 +271,7 @@ async function buildDispatcher( readonly passthroughOverride?: PassthroughResolver; readonly execEnv?: NodeJS.ProcessEnv; /** Stands in for the event history, so `events.replay` can be checked against it. */ - readonly eventHistory?: Pick; + readonly eventHistory?: Pick; readonly historyPath?: string; readonly withoutTokens?: boolean; /** `status.get`'s host block; a fixed machine with no tools by default. */ @@ -1358,6 +1359,7 @@ describe("Dispatcher: events.replay", () => { asked.push(input); return fromHistory; }, + replayPage: async () => ({ events: [], kind: "events" }), status: () => ({ opened: true, writing: true }), }, }); @@ -1369,6 +1371,77 @@ describe("Dispatcher: events.replay", () => { }); }); +describe("Dispatcher: events.replay paging", () => { + afterEach(removeUsageRigs); + + const admin = session({ role: "admin" }); + + async function pagedRig( + rows: number, + options: Parameters[0] = {}, + ): Promise<{ + readonly rig: Awaited>; + readonly ids: string[]; + readonly dispatcher: Dispatcher; + }> { + const rig = await usageRig(options); + for (let row = 0; row < rows; row += 1) { + rig.at(T0 + row); + rig.emit("daemon.stopping", { reason: `r${row + 1}` }); + } + const { dispatcher } = await buildDispatcher({ eventHistory: rig.history }); + return { dispatcher, ids: rig.bus.replay().map((event) => event.id), rig }; + } + + const reasons = (events: readonly { readonly payload?: unknown }[]): unknown[] => + events.map((event) => (event.payload as { reason: string }).reason); + + it("events.replay with beforeId and limit pages through the worker dispatcher over a real history: the page, HISTORY_NOT_KEPT, an empty table, HISTORY_UNAVAILABLE, and 100 at most for beforeId alone", async () => { + const { dispatcher, ids } = await pagedRig(150); + const page = await dispatcher.dispatch( + "events.replay", + { beforeId: ids[4] as string, limit: 2 }, + admin, + ); + expect(reasons(page)).toEqual(["r3", "r4"]); + const unbounded = await dispatcher.dispatch( + "events.replay", + { beforeId: ids[149] as string }, + admin, + ); + expect(unbounded).toHaveLength(100); + await expect( + dispatcher.dispatch("events.replay", { beforeId: "evt_gone", limit: 2 }, admin), + ).rejects.toMatchObject({ code: "HISTORY_NOT_KEPT", details: { oldestTs: T0 } }); + + const empty = await pagedRig(0); + await expect( + empty.dispatcher.dispatch("events.replay", { beforeId: "evt_any", limit: 2 }, admin), + ).resolves.toEqual([]); + + const failing = plainProjection("failing", () => ({ + apply: () => { + throw new Error("projection broke"); + }, + prune: () => undefined, + })); + const notWriting = await pagedRig(1, { projections: [failing] }); + expect(notWriting.rig.history.status().writing).toBe(false); + const unstarted = await buildDispatcher(); + for (const { dispatcher: target } of [notWriting, unstarted]) { + await expect( + target.dispatch("events.replay", { beforeId: "evt_any", limit: 2 }, admin), + ).rejects.toMatchObject({ code: "HISTORY_UNAVAILABLE" }); + } + }); + + it("events.replay with limit alone returns the newest n events, oldest first, through the worker dispatcher", async () => { + const { dispatcher } = await pagedRig(5); + const page = await dispatcher.dispatch("events.replay", { limit: 2 }, admin); + expect(reasons(page)).toEqual(["r4", "r5"]); + }); +}); + describe("Dispatcher: config.get eventLog", () => { it("config.get reports eventLog.retention and maxBytes and no rotateBytes", async () => { const { dispatcher } = await buildDispatcher(); @@ -4507,6 +4580,8 @@ describe("Dispatcher: usage.get", () => { const gate = { open: true }; const eventHistory = { replay: (input?: { readonly sinceTs?: number }) => rig.history.replay(input), + replayPage: (input: { readonly beforeId?: string; readonly limit: number }) => + rig.history.replayPage(input), status: () => ({ ...rig.history.status(), opened: gate.open && rig.history.status().opened }), }; return { eventHistory, gate, rig, ...options }; diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 5989ab179..c35b20bc8 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -56,6 +56,7 @@ import { capabilityReason, type capabilitySchema, consoleUrlField, + EVENTS_PAGE_DEFAULT, fitPlatformCatalog, OPERATIONS, requestedDevice, @@ -72,6 +73,7 @@ import { DispatchError, identityGet, runDispatch, + eventsPageAnswer, usageAnswer, type DispatchSession, type ErasedHandler, @@ -137,7 +139,7 @@ export interface DispatcherOptions { readonly components: Pick; readonly config: Config; readonly doctor?: Doctor; - readonly eventHistory: Pick; + readonly eventHistory: Pick; readonly deviceModes: DeviceModeReader; readonly leases: LeaseCommands; readonly logger?: Logger; @@ -812,7 +814,16 @@ export class Dispatcher { #usageGet: Handler<"usage.get"> = (input) => usageAnswer(this.#usage.get(input)); #eventsReplay: Handler<"events.replay"> = (input) => - this.options.eventHistory.replay(input.sinceTs === undefined ? {} : { sinceTs: input.sinceTs }); + input.beforeId === undefined && input.limit === undefined + ? this.options.eventHistory.replay( + input.sinceTs === undefined ? {} : { sinceTs: input.sinceTs }, + ) + : eventsPageAnswer( + this.options.eventHistory.replayPage({ + ...(input.beforeId === undefined ? {} : { beforeId: input.beforeId }), + limit: input.limit ?? EVENTS_PAGE_DEFAULT, + }), + ); #eventsSubscribe: Handler<"events.subscribe"> = (_input, session) => { const subscriptionId = session.manageEventSubscription(true); diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 9eee108bd..0d7f3f493 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -228,8 +228,9 @@ describe("DaemonServer", () => { [46, "cannot call identity.get"], [47, "cannot read config.get's http.proxyAuth"], [48, "cannot read config.get's gateway.alerts"], + [51, "cannot page events.replay with beforeId or limit"], ])( - "answers PROTOCOL_VERSION_UNSUPPORTED, naming protocol 51, to a client on protocol %i, which %s", + "answers PROTOCOL_VERSION_UNSUPPORTED, naming protocol 52, to a client on protocol %i, which %s", async (version) => { const harness = await createHarness(); const previous = await createClient(harness.socketPath); @@ -239,7 +240,7 @@ describe("DaemonServer", () => { ).resolves.toMatchObject({ error: { code: "PROTOCOL_VERSION_UNSUPPORTED", - details: { client: { min: version, max: version }, daemon: { min: 51, max: 51 } }, + details: { client: { min: version, max: version }, daemon: { min: 52, max: 52 } }, }, ok: false, }); diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 0ee1186e6..6ed3ceb0a 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -146,7 +146,7 @@ export interface DaemonServerEngineOptions { readonly catalog: CatalogReader; readonly components: Pick; readonly doctor?: Doctor; - readonly eventHistory: Pick; + readonly eventHistory: Pick; readonly historyPath?: string; readonly leases: LeaseCommands; readonly hostFacts: () => HostFacts; diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index 43063a415..1c3ba6433 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -169,7 +169,7 @@ class FakeDirectory implements WorkerDirectory { function harness( options: { - readonly eventHistory?: Pick; + readonly eventHistory?: Pick; readonly historyPath?: string; readonly tokenRecords?: readonly { id: string; label?: string }[]; readonly withoutTokens?: boolean; @@ -832,6 +832,7 @@ describe("GatewayDispatcher", () => { asked.push(input); return fromHistory; }, + replayPage: async () => ({ events: [], kind: "events" }), status: () => ({ opened: true, writing: true }), }, }); @@ -842,6 +843,45 @@ describe("GatewayDispatcher", () => { expect(asked).toEqual([{ sinceTs: 10 }]); }); + it("events.replay with beforeId returns a worker's relayed event with payload.workerId", async () => { + const rig = await usageRig({ fleet: true }); + rig.relay("w-1", "daemon.stopping", { reason: "from-worker" }); + rig.emit("daemon.stopping", { reason: "local" }); + const newest = rig.bus.replay().at(-1) as { id: string }; + const { dispatcher } = harness({ eventHistory: rig.history }); + + const page = await dispatcher.dispatch( + "events.replay", + { beforeId: newest.id, limit: 5 }, + session(), + ); + + expect(page).toEqual([ + expect.objectContaining({ payload: expect.objectContaining({ workerId: "w-1" }) }), + ]); + }); + + it("events.replay with limit alone returns the newest n events, oldest first, through the gateway dispatcher", async () => { + const rig = await usageRig({ fleet: true }); + for (const reason of ["a", "b", "c"]) rig.emit("daemon.stopping", { reason }); + const { dispatcher } = harness({ eventHistory: rig.history }); + + const page = await dispatcher.dispatch("events.replay", { limit: 2 }, session()); + + expect(page.map((event) => (event.payload as { reason: string }).reason)).toEqual(["b", "c"]); + }); + + it("events.replay with beforeId and no limit returns at most 100 events through the gateway dispatcher", async () => { + const rig = await usageRig({ fleet: true }); + for (let n = 0; n < 130; n += 1) rig.emit("daemon.stopping", { reason: `r${n}` }); + const newest = rig.bus.replay().at(-1) as { id: string }; + const { dispatcher } = harness({ eventHistory: rig.history }); + + const page = await dispatcher.dispatch("events.replay", { beforeId: newest.id }, session()); + + expect(page).toHaveLength(100); + }); + it.each([ { health: "running" as const, @@ -1976,6 +2016,8 @@ describe("GatewayDispatcher: usage.get", () => { const gate = { open: true }; const eventHistory = { replay: (input?: { readonly sinceTs?: number }) => rig.history.replay(input), + replayPage: (input: { readonly beforeId?: string; readonly limit: number }) => + rig.history.replayPage(input), status: () => ({ ...rig.history.status(), opened: gate.open && rig.history.status().opened }), }; return { eventHistory, gate, rig }; diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts index eb07950f4..247ec4488 100644 --- a/src/gateway/dispatcher.ts +++ b/src/gateway/dispatcher.ts @@ -39,6 +39,7 @@ import { createUsageReader, type UsageReader } from "../core/index.js"; import type { EventHistoryHandle } from "../history/index.js"; import { consoleUrlField, + EVENTS_PAGE_DEFAULT, OPERATIONS, requestedDevice, type OperationName, @@ -48,6 +49,7 @@ import { DispatchError, identityGet, runDispatch, + eventsPageAnswer, usageAnswer, type DispatchSession, type ErasedHandler, @@ -95,7 +97,7 @@ export interface GatewayDispatcherOptions { readonly historyPath?: string; /** The gateway's own config -- what `config.get` returns (ADR 0005 §34). */ readonly config: GatewayConfig; - readonly eventHistory: Pick; + readonly eventHistory: Pick; readonly workers: WorkerRegistry; /** * why: ADR 0035 §1; declared here, not imported from `src/alerts`, which this module may not @@ -341,7 +343,16 @@ export class GatewayDispatcher { #usageGet: Handler<"usage.get"> = (input) => usageAnswer(this.#usage.get(input)); #eventsReplay: Handler<"events.replay"> = (input) => - this.options.eventHistory.replay(input.sinceTs === undefined ? {} : { sinceTs: input.sinceTs }); + input.beforeId === undefined && input.limit === undefined + ? this.options.eventHistory.replay( + input.sinceTs === undefined ? {} : { sinceTs: input.sinceTs }, + ) + : eventsPageAnswer( + this.options.eventHistory.replayPage({ + ...(input.beforeId === undefined ? {} : { beforeId: input.beforeId }), + limit: input.limit ?? EVENTS_PAGE_DEFAULT, + }), + ); #eventsSubscribe: Handler<"events.subscribe"> = (_input, session) => { const subscriptionId = session.manageEventSubscription(true); diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts index 568f82d76..22ddb4105 100644 --- a/src/gateway/service.test.ts +++ b/src/gateway/service.test.ts @@ -1265,7 +1265,7 @@ describe("GatewayService", () => { min: PROTOCOL_VERSION_RANGE.max - 1, max: PROTOCOL_VERSION_RANGE.max - 1, }; - expect(PROTOCOL_VERSION_RANGE.max).toBe(51); + expect(PROTOCOL_VERSION_RANGE.max).toBe(52); expect(negotiateProtocolVersion(PROTOCOL_VERSION_RANGE, previous)).toBeUndefined(); const harness = fleet(); await harness.service.start(); diff --git a/src/history/AGENTS.md b/src/history/AGENTS.md index baa46d370..cd1a749eb 100644 --- a/src/history/AGENTS.md +++ b/src/history/AGENTS.md @@ -9,7 +9,7 @@ Flows: [startup](../../docs/internal/flows/startup.md). Catalog: [EVENTS.md](../ | File | Role | | -------------- | ------------------------------------------------------------------------------------------------ | -| `index.ts` | the handle (`replay`, `status`, `start`, `stop`) and the CLI reader | +| `index.ts` | the handle (`replay`, `replayPage`, `status`, `start`, `stop`) and the CLI reader | | `database.ts` | pragmas, schema, the read query (`quick_check` and the lock-error test are in `ports/sqlite.ts`) | | `prune.ts` | age, size, projection prune, vacuum and checkpoint | | `versions.ts` | `projection_versions`: migrate, refuse, the rebuild mark | @@ -25,7 +25,7 @@ Flows: [startup](../../docs/internal/flows/startup.md). Catalog: [EVENTS.md](../ 3. **Catch up** — the ring's events are written in `seq` order, not time order (`INSERT OR IGNORE` by `id`; `index.ts` `#start`). After a set-aside only the events seen since the factory ran are. A projection whose check failed takes no step meanwhile. 4. **Write** — each event is one transaction: `BEGIN`, insert the row, run every projection's `apply` when the row is new, `COMMIT`. 5. **Prune** — after start and every hour: delete rows older than `eventLog.retention`, then the oldest 1 000 at a time while the stored size is over `eventLog.maxBytes`, then each projection's `prune` (rows older than `metrics.retention`), then `incremental_vacuum` and `wal_checkpoint(TRUNCATE)`. -6. **Read** — `replay({ sinceTs })` selects `timestamp > ?` ordered by timestamp, seq, rowid; a row whose id fails `EVENT_ID_PATTERN` is skipped. `openHistoryReader` does the same read-only for the CLI when no daemon answers; a missing file is empty, an unreadable one throws. +6. **Read** — `replay({ sinceTs })` selects `timestamp > ?` ordered by timestamp, seq, rowid; a row whose id fails `EVENT_ID_PATTERN` is skipped. `openHistoryReader` does the same read-only for the CLI when no daemon answers; a missing file is empty, an unreadable one throws. `replayPage({ beforeId?, limit })` never throws: with `beforeId` it selects the `limit` rows before that row's `(timestamp, seq, rowid)` and returns them oldest first (`not-kept` with the oldest row's timestamp when the id is not stored and the table has rows, `unavailable` when the file is not readable or not writing or the read fails); without it, the newest `limit` rows, or the ring's newest when the file is not readable or not writing or the read fails. 7. **Stop** — `stop()` cancels the timer and closes the file. A `start()` still awaiting closes what it opened and returns. ## State and timers diff --git a/src/history/database.ts b/src/history/database.ts index f8a6a47e3..50f8091b0 100644 --- a/src/history/database.ts +++ b/src/history/database.ts @@ -10,6 +10,16 @@ export const INSERT_EVENT_SQL = const SELECT_SINCE_SQL = "SELECT envelope FROM events WHERE timestamp > ? ORDER BY timestamp, seq, rowid"; +const SELECT_CURSOR_SQL = "SELECT timestamp, seq, rowid AS position FROM events WHERE id = ?"; + +const SELECT_BEFORE_SQL = + "SELECT envelope FROM events WHERE (timestamp, seq, rowid) < (?, ?, ?) ORDER BY timestamp DESC, seq DESC, rowid DESC LIMIT ?"; + +const SELECT_NEWEST_SQL = + "SELECT envelope FROM events ORDER BY timestamp DESC, seq DESC, rowid DESC LIMIT ?"; + +const SELECT_OLDEST_SQL = "SELECT timestamp FROM events ORDER BY timestamp, seq, rowid LIMIT 1"; + export function configureDatabase(database: SqliteDatabase): void { database.exec(`PRAGMA busy_timeout=${BUSY_TIMEOUT_MS}`); database.exec("PRAGMA auto_vacuum=INCREMENTAL"); @@ -55,14 +65,40 @@ export function envelopeSize(json: string): number { } export function selectEventsSince(database: SqliteDatabase, sinceTs: number): EventEnvelope[] { + return parseEnvelopes(database.prepare(SELECT_SINCE_SQL).all(sinceTs)); +} + +function parseEnvelopes(rows: readonly Record[]): EventEnvelope[] { const events: EventEnvelope[] = []; - for (const row of database.prepare(SELECT_SINCE_SQL).all(sinceTs)) { + for (const row of rows) { const envelope = parseEnvelope(row.envelope); if (envelope !== undefined) events.push(envelope); } return events; } +export function selectEventsBefore( + database: SqliteDatabase, + beforeId: string, + limit: number, +): EventEnvelope[] | undefined { + const cursor = database.prepare(SELECT_CURSOR_SQL).get(beforeId); + if (cursor === undefined) return undefined; + const rows = database + .prepare(SELECT_BEFORE_SQL) + .all(Number(cursor.timestamp), Number(cursor.seq), Number(cursor.position), limit); + return parseEnvelopes(rows).reverse(); +} + +export function selectNewestEvents(database: SqliteDatabase, limit: number): EventEnvelope[] { + return parseEnvelopes(database.prepare(SELECT_NEWEST_SQL).all(limit)).reverse(); +} + +export function selectOldestTimestamp(database: SqliteDatabase): number | undefined { + const row = database.prepare(SELECT_OLDEST_SQL).get(); + return row === undefined ? undefined : Number(row.timestamp); +} + export function parseEnvelope(stored: unknown): EventEnvelope | undefined { if (typeof stored !== "string") return undefined; let value: unknown; diff --git a/src/history/history.test.ts b/src/history/history.test.ts index 48aff80fa..f5f16b9b8 100644 --- a/src/history/history.test.ts +++ b/src/history/history.test.ts @@ -261,6 +261,57 @@ describe("createEventHistory", () => { expect(replayed).toEqual([newer, newest]); }); + it("replayPage with beforeId and limit returns the limit events just older than the named one, oldest first, and stops short at the start of the history", async () => { + const rigged = await rig(); + const history = rigged.history(); + await history.start(); + const rows = [1, 2, 3, 4, 5].map((n) => relayed(rigged.bus, `evt_row${n}`, NOW + n)); + + const middle = await history.replayPage({ beforeId: "evt_row4", limit: 2 }); + const start = await history.replayPage({ beforeId: "evt_row2", limit: 5 }); + await history.stop(); + + const failing = await rig(); + const sqlite = new ProbeSqliteOpener({ + fault: (call) => { + if (call.kind === "prepare" && /rowid\) { + const earlierRun = await rig(); + const earlierWriter = earlierRun.history(); + await earlierWriter.start(); + const first = relayed(earlierRun.bus, "evt_tie_z", NOW); + await earlierWriter.stop(); + const laterRun = await rig({ directory: earlierRun.directory }); + const laterWriter = laterRun.history(); + await laterWriter.start(); + const second = relayed(laterRun.bus, "evt_tie_a", NOW); + relayed(laterRun.bus, "evt_tie_last", NOW + 1); + + const newest = await laterWriter.replayPage({ beforeId: "evt_tie_last", limit: 1 }); + const older = await laterWriter.replayPage({ beforeId: "evt_tie_a", limit: 1 }); + await laterWriter.stop(); + expect(first.seq).toBe(second.seq); + expect([newest, older]).toEqual([ + { events: [second], kind: "events" }, + { events: [first], kind: "events" }, + ]); + }); + it("a second insert of an event with an id already stored adds no row and runs no projection step", async () => { const rigged = await rig(); const projection = recordingProjection(); @@ -403,6 +454,53 @@ describe("createEventHistory", () => { await history.stop(); }); + it("replayPage with limit alone returns the newest n, oldest first, and the newest n held in memory when the history is unreadable or its read throws", async () => { + const served = await rig({ capacity: 3 }); + const history = served.history(); + await history.start(); + const rows = [1, 2, 3, 4].map((n) => relayed(served.bus, `evt_row${n}`, NOW + n)); + const fromFile = await history.replayPage({ limit: 3 }); + await history.stop(); + + const unread = await rig({ capacity: 3 }); + const unreadable = [1, 2, 3].map((n) => relayed(unread.bus, `evt_row${n}`, NOW + n)); + const fromUnstarted = await unread.history().replayPage({ limit: 2 }); + + const failing = await rig({ capacity: 2 }); + const sqlite = new ProbeSqliteOpener({ + fault: (call) => { + if (call.kind === "prepare" && /DESC/i.test(call.sql)) throw new Error("read failed"); + }, + }); + const throwing = failing.history({ sqlite }); + await throwing.start(); + relayed(failing.bus, "evt_one", NOW + 1); + const held = [2, 3].map((n) => relayed(failing.bus, `evt_held${n}`, NOW + n)); + const fromThrowing = await throwing.replayPage({ limit: 5 }); + await throwing.stop(); + + const halted = await rig(); + const definition = plainProjection("halting", () => ({ + apply: (envelope) => { + if ((envelope.payload as { reason?: string }).reason === "boom") { + throw new Error("projection failed"); + } + }, + prune: () => undefined, + })); + const stopped = halted.history({ projections: [definition] }); + await stopped.start(); + const stoppedHeld = ["fine", "boom", "after"].map((reason) => stopping(halted.bus, reason)); + const fromStopped = await stopped.replayPage({ limit: 5 }); + await stopped.stop(); + + expect(fromFile).toEqual({ events: rows.slice(1), kind: "events" }); + expect(fromUnstarted).toEqual({ events: unreadable.slice(1), kind: "events" }); + expect(fromThrowing).toEqual({ events: held, kind: "events" }); + expect(levelRecords(failing, "warn")).toBe(1); + expect(fromStopped).toEqual({ events: stoppedHeld, kind: "events" }); + }); + it("opens a new file with incremental auto_vacuum, WAL, synchronous NORMAL and a 5 s busy timeout", async () => { const rigged = await rig(); const sqlite = new ProbeSqliteOpener(); diff --git a/src/history/index.ts b/src/history/index.ts index 59e1ed0be..e6adeeecf 100644 --- a/src/history/index.ts +++ b/src/history/index.ts @@ -17,7 +17,10 @@ import { configureDatabase, envelopeSize, INSERT_EVENT_SQL, + selectEventsBefore, selectEventsSince, + selectNewestEvents, + selectOldestTimestamp, } from "./database.js"; import { HISTORY_DB_NAME } from "./names.js"; import { pruneHistory, totalEventBytes } from "./prune.js"; @@ -58,8 +61,17 @@ export interface EventHistoryStatus { readonly rebuildFailed?: true; } +export type EventsPageRead = + | { readonly kind: "events"; readonly events: EventEnvelope[] } + | { readonly kind: "not-kept"; readonly oldestTs: number } + | { readonly kind: "unavailable" }; + export interface EventHistoryHandle { replay(input?: { readonly sinceTs?: number }): Promise; + replayPage(input: { + readonly beforeId?: string; + readonly limit: number; + }): Promise; status(): EventHistoryStatus; start(): Promise; stop(): Promise; @@ -140,6 +152,44 @@ class EventHistory implements EventHistoryHandle { } } + async replayPage(input: { + readonly beforeId?: string; + readonly limit: number; + }): Promise { + const database = this.#database; + if (input.beforeId === undefined) return { events: this.#newest(input.limit), kind: "events" }; + if (database === undefined || !this.#readable || !this.#writing) return { kind: "unavailable" }; + try { + const events = selectEventsBefore(database, input.beforeId, input.limit); + if (events !== undefined) return { events, kind: "events" }; + const oldestTs = selectOldestTimestamp(database); + return oldestTs === undefined + ? { events: [], kind: "events" } + : { kind: "not-kept", oldestTs }; + } catch (error: unknown) { + this.#options.logger.warn("History page read failed", { + error: describe(error), + path: this.#path, + }); + return { kind: "unavailable" }; + } + } + + #newest(limit: number): EventEnvelope[] { + const database = this.#database; + if (database !== undefined && this.#readable && this.#writing) { + try { + return selectNewestEvents(database, limit); + } catch (error: unknown) { + this.#options.logger.warn("History read failed; paging from memory", { + error: describe(error), + path: this.#path, + }); + } + } + return this.#options.bus.replay().slice(-limit); + } + async start(): Promise { if (this.#started || this.#stopped) return; this.#started = true; diff --git a/src/history/testing.ts b/src/history/testing.ts index b3ae6d12c..6dd1d92b3 100644 --- a/src/history/testing.ts +++ b/src/history/testing.ts @@ -113,6 +113,7 @@ function answeredStatement(rows: Record[]): SqliteStatement { export function fixedEventHistory(status: EventHistoryStatus): EventHistoryHandle { return { replay: () => Promise.resolve([]), + replayPage: () => Promise.resolve({ events: [], kind: "events" }), start: () => Promise.resolve(), status: () => status, stop: () => Promise.resolve(), @@ -198,6 +199,7 @@ export interface UsageRigOptions { readonly at?: number; readonly eventRetention?: number; readonly directory?: string; + readonly projections?: readonly HistoryProjectionDefinition[]; } export async function usageRig(options: UsageRigOptions = {}): Promise { @@ -218,7 +220,7 @@ export async function usageRig(options: UsageRigOptions = {}): Promise filesystem: new NodeFilesystem(), logger: new NoopLogger(), projectionOptions: { fleet: options.fleet ?? false, metricsRetentionMs: 90 * DAY }, - projections: Object.values(HISTORY_PROJECTIONS), + projections: options.projections ?? Object.values(HISTORY_PROJECTIONS), sqlite: new NodeSqliteOpener(), }); await history.start(); diff --git a/src/http/AGENTS.md b/src/http/AGENTS.md index 0600e5cb7..9e589a63e 100644 --- a/src/http/AGENTS.md +++ b/src/http/AGENTS.md @@ -64,6 +64,7 @@ agent-device front and the stream (`/v1/stream`). opened by an identity with `expiresAt` (a proxy JWT) ends then (`sse.ts`, `app.ts`). - `GET /v1/events/stream` — dispatches `events.subscribe` (admin, readiness), then subscribes to the `EventBus` itself. +- `GET /v1/events` — reads `since`, `before` and `limit` through `eventsPageQuery` (contract), refused as 400 before dispatching `events.replay`; `HISTORY_NOT_KEPT` maps to 422 with `oldestTs`, `HISTORY_UNAVAILABLE` to 503 here too. - `GET /v1/stats` — parses `since`/`from`/`to` with `usageWindow` (contract) and `ledger=1`, all refused as 400 before dispatching `usage.get` (the dispatcher answers an agent token 403, `HISTORY_NOT_KEPT` maps to 422 with `oldestTs`, `HISTORY_UNAVAILABLE` to 503). - `GET /v1/leases/{id}/events` — the lease's notices; ends on `lease_lost`. - `POST /v1/leases/{id}/exec` → `device.exec`. The stream opens on `onStarted`; a failure diff --git a/src/http/app.test.ts b/src/http/app.test.ts index e177f7d2a..60b0a9ffa 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -2104,6 +2104,51 @@ describe("operator-only listing routes", () => { expect(JSON.stringify(await response.json())).toContain("Invalid duration: nonsense"); }); + it("GET /v1/events with before and limit dispatches events.replay with beforeId and limit, and answers HISTORY_NOT_KEPT with 422 and oldestTs in the body and HISTORY_UNAVAILABLE with 503", async () => { + const { app, dispatcher } = buildHarness(); + const asked: unknown[] = []; + dispatcher.handlers["events.replay"] = (input) => { + asked.push(input); + throw new DispatchError("HISTORY_NOT_KEPT", "The history does not hold that event.", { + oldestTs: 1_234, + }); + }; + const notKept = await app.request("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/v1/events?before=evt_abc&limit=50", { + headers: operatorAuth, + }); + dispatcher.handlers["events.replay"] = () => { + throw new DispatchError("HISTORY_UNAVAILABLE", "The history could not be read."); + }; + const unavailable = await app.request("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/v1/events?before=evt_abc", { headers: operatorAuth }); + + expect(asked).toEqual([{ beforeId: "evt_abc", limit: 50 }]); + expect(notKept.status).toBe(422); + expect(await notKept.json()).toMatchObject({ + error: { code: "HISTORY_NOT_KEPT", oldestTs: 1_234 }, + }); + expect(unavailable.status).toBe(503); + expect(await unavailable.json()).toMatchObject({ error: { code: "HISTORY_UNAVAILABLE" } }); + }); + + it.each([ + ["before=evt_abc&limit=0", "limit must be a whole number from 1 to 500"], + ["before=evt_abc&limit=501", "limit must be a whole number from 1 to 500"], + ["before=evt_abc&limit=x", "limit must be a whole number from 1 to 500"], + ["before=not-an-id", "before must be an event id"], + ["before=evt_abc&since=1h", "before and since cannot be used together"], + ["limit=50&since=1h", "limit and since cannot be used together"], + ])("GET /v1/events?%s answers 400 BAD_REQUEST before dispatching", async (query, message) => { + const { app, dispatcher } = buildHarness(); + dispatcher.handlers["events.replay"] = () => { + throw new Error("should not be called"); + }; + + const response = await app.request(`/v1/events?${query}`, { headers: operatorAuth }); + + expect(response.status).toBe(400); + expect(await response.json()).toMatchObject({ error: { code: "BAD_REQUEST", message } }); + }); + describe("GET /v1/stats", () => { const NOW = Date.parse("2026-10-16T12:00:00Z"); const HOUR = 3_600_000; diff --git a/src/http/app.ts b/src/http/app.ts index a7566b338..1ef4134aa 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -6,6 +6,7 @@ import type { EventBus } from "../bus/index.js"; import { type ComponentProgress, describeSchemaIssues, + eventsPageQuery, refuseModelWithClass, deviceClassSchema, leaseIdSchema, @@ -694,10 +695,16 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa app.get("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/v1/events", agentAuth, async (c) => { const since = c.req.query("since"); + const answer = eventsPageQuery({ + before: c.req.query("before"), + limit: c.req.query("limit"), + since, + }); + if ("refused" in answer) throw badRequest(answer.refused); const sinceTs = since === undefined ? undefined : deps.clock.now() - parseDuration(since); const events = await deps.dispatch( "events.replay", - sinceTs === undefined ? {} : { sinceTs }, + sinceTs === undefined ? answer.page : { ...answer.page, sinceTs }, buildHttpSession(c.get("identity")), ); return c.json({ events }); diff --git a/website/src/content/docs/docs/reference/events.mdx b/website/src/content/docs/docs/reference/events.mdx index e31eeb066..e8c55be69 100644 --- a/website/src/content/docs/docs/reference/events.mdx +++ b/website/src/content/docs/docs/reference/events.mdx @@ -41,8 +41,11 @@ With `--follow`, each line that arrives live wraps the event in an `event` field | ----------------------------- | --------------------------------------------------------------------------------------------- | | `GET /v1/events` | `{"events": [...]}`: the recent events kept in memory. | | `GET /v1/events?since=2h` | `{"events": [...]}`: events from the history, same duration format as the CLI. | +| `GET /v1/events?before=evt_…&limit=100` | `{"events": [...]}`: the `limit` events just older than that event, oldest first. Fewer than `limit` means the history ends there. | | `GET /v1/events/stream` | A server-sent event stream. Each message's `event` is the event name and its `data` the event as JSON. | +`limit` is 1 to 500, and 100 when only `before` is given; `limit` alone returns the newest events. `before` and `limit` cannot be combined with `since`. A bad `before` or `limit` is `400 BAD_REQUEST`; a `before` the history no longer holds is `422 HISTORY_NOT_KEPT` with `oldestTs`; an unreadable history is `503 HISTORY_UNAVAILABLE`. + ```sh curl -N -H "Authorization: Bearer $SIMLOCK_TOKEN" https://simlock-gw.example.com/v1/events/stream ```