diff --git a/CHANGELOG.md b/CHANGELOG.md index ab1f99b56..e8a781a5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -216,6 +216,17 @@ those changes add, alongside the breaking changes above. `EXEC_TIMEOUT` error code (CLI exit `10`, the code the other "ran out of time" outcome already uses, and HTTP `504`) rather than reporting the exit code the kill produced. +- **events:** every business event is also written to `~/.simlock/events.jsonl`, + one JSON line each, so the history survives a daemon restart or crash. + `simlock events --since` and `GET /v1/events?since=` read it, reaching past + a restart and past the 1000 events kept in memory; with no daemon running, + `simlock events --since` (without `--follow`) reads the file and starts + none. `--since` with + `--follow` prints that history, then streams, with nothing lost or repeated + where they meet. The file is capped by the new `eventLog.rotateBytes` + (default 5 MiB, one rotated generation). `daemon.log` no longer gets its own + copies of `component.installed` and `device.slimmed`; read them from the + event file. ### ADR 0005: gateway and worker modes diff --git a/docs/CLI.md b/docs/CLI.md index 605dd9bf5..31fb7840d 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -627,7 +627,7 @@ catalog lists is leasable *somewhere*, not necessarily everywhere. republished on the gateway's bus with `workerId` added to the payload, alongside the gateway's own `worker.*` and `request.dispatched` facts (see [EVENTS.md](EVENTS.md)). `--follow` and `--since` work as always, over the -gateway's own ring buffer. +gateway's own event history. **`simlock simctl` and `simlock adb`** keep working, but not the same way underneath. Against a **worker** they behave exactly as documented above: the @@ -1042,8 +1042,22 @@ offer. ## `simlock events [--follow] [--since ]` -Stream the business-event ring buffer (see [EVENTS.md](EVENTS.md)) as JSON -lines. `--follow` keeps streaming; `--since 1h` replays recent history. +Print business events (see [EVENTS.md](EVENTS.md)) as JSON lines. + +- With no flags, prints the recent events the daemon holds in memory + (`eventBuffer.capacity`, 1000 by default), which start empty after a + restart. +- `--since 1h` reaches further back. Every event is also written to + `~/.simlock/events.jsonl`, which survives restarts and crashes, so + `--since` returns events from before the last restart and beyond the + in-memory limit, back to the oldest event the file still holds. The file + is capped by `eventLog.rotateBytes` (see + [CONFIGURATION.md](CONFIGURATION.md)); the oldest events go first. +- `--since` without `--follow`, with no daemon running, reads the file + directly and does not start a daemon. `--follow` starts one as usual. +- `--follow` keeps streaming live events. With `--since`, it prints that + history first and then streams, with no event missing or printed twice + where the two meet. Against a **gateway** this is the fleet's stream: every connected worker's business events, republished on the gateway's bus with `workerId` added to @@ -1052,10 +1066,10 @@ the payload, interleaved with the gateway's own `worker.connected` / `worker.drain-started` / `worker.drain-ended` / `request.dispatched` facts. `worker.rejected` is how you find out why a machine never appeared in `simlock worker list` at all — it reports an uplink refused at the door, -which nothing else records. It is one ring buffer like -any other, so it resets when the gateway restarts and it holds only what -arrived while the gateway was up — a worker's events from before its uplink -connected are not backfilled. +which nothing else records. The gateway writes these relayed events to its +own `events.jsonl` along with its own, so `--since` reaches back across a +gateway restart. It holds only what arrived while the gateway was up — a +worker's events from before its uplink connected are not backfilled. ## `simlock daemon ` @@ -1251,7 +1265,7 @@ fleet; `simlock worker remove` then forgets its view. ### `SIMLOCK_HOME` Overrides the data directory the CLI, MCP server, and daemon all use for -`config.json`, `state.json`, `daemon.sock`, `daemon.log`, and — unless +`config.json`, `state.json`, `daemon.sock`, `daemon.log`, `events.jsonl`, and — unless overridden — the device roots themselves under `devices/`. Defaults to `~/.simlock`. Because devices live under it, it needs a local volume with tens of gigabytes free. All three frontends resolve it through the same function diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index af66704f3..020bb04b2 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -38,7 +38,8 @@ a warning. Inspect the effective, merged configuration at any time with | `gateway.execTimeoutMs` | **Gateway side.** Backstop on a proxied `device.exec`, deliberately longer than the worker's own `exec.timeoutMs`, which is the authoritative one. | `11 minutes` | | `gateway.leaseRequestTimeoutMs` | **Gateway side.** Backstop on a forwarded `lease.request` -- expiry answers `WORKER_UNREACHABLE`, freeing the request for the queue's own deadline/cancel handling again. | `5 minutes` | | `diskPressure.freeBytesThreshold` | Free disk space below which Simlock treats the machine as under disk pressure. | `10 GiB` | -| `eventBuffer.capacity` | Number of business events kept in the in-memory ring buffer (see `simlock events`). | `1000` | +| `eventBuffer.capacity` | Number of recent business events kept in memory, which `simlock events` without `--since` replays. | `1000` | +| `eventLog.rotateBytes` | Size of the event file, `~/.simlock/events.jsonl`, before it rotates. Every business event is written there and survives a daemon restart. One rotated generation, `events.jsonl.1`, is kept, so the history on disk stays within about twice this size and the oldest events are dropped first. | `5 MiB` | | `health.enabled` | Master switch for leased-device crash detection and recovery. | `true` | | `health.probeIntervalMs` | How often the health monitor observes leased devices against driver reality. | `30 seconds` | | `health.stableObservations` | Consecutive `stopped` observations required before a leased device is treated as crashed; guards against transient `Booting`/`Shutting Down`/adb-offline readings. | `2` | @@ -134,7 +135,7 @@ local agents whether or not its gateway is reachable, and `http.enabled` stays off by default. **A gateway reads a deliberately small slice of this file**: `mode`, `http.*`, -`log.*`, `lease.*`, `eventBuffer.*` and `gateway.*`. Every other key — +`log.*`, `lease.*`, `eventBuffer.*`, `eventLog.*` and `gateway.*`. Every other key — capacity, drivers, downloads, idle, warmPool, health, ios, android, stalledTransition — configures devices, which a gateway does not have; each one present in a gateway's config is reported with a warning and ignored, the same treatment an @@ -200,7 +201,7 @@ does not apply to it. It reads: | `gateway.routing`, `gateway.disconnectedRetentionMs`, `gateway.execTimeoutMs`, `gateway.leaseRequestTimeoutMs` | how to run the fleet | | `http.*` | it is the fleet's contact point | | `lease.*` | `defaultTtlMs`/`maxTtlMs` bound what its own clients may ask for, before a request is dispatched — see below | -| `log.*`, `eventBuffer.*` | logging and the event ring buffer, as anywhere | +| `log.*`, `eventBuffer.*`, `eventLog.*` | logging and the event history, as anywhere | **Both ends have a `lease.*` block, and on a fleet lease the gateway's is the one that decides the width.** A request arriving at a gateway with no `ttlMs` diff --git a/docs/EVENTS.md b/docs/EVENTS.md index 70a63992c..e5add0bbf 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -127,9 +127,12 @@ documented above arrives with an extra field: additive, and only ever on a gateway. The events in this section's own table are the gateway's own, and carry no `workerId` beyond the worker they are about. -Two consequences of relaying rather than owning: the gateway's ring buffer -only holds what arrived while its uplinks were up (a worker's events from -before it connected are not backfilled), and a worker's own +Relayed events are written to the gateway's own event file +(`events.jsonl`) along with its own, so `simlock events --since` against a +gateway reaches back across a gateway restart. Two consequences of relaying +rather than owning: the gateway's history only holds what arrived while its +uplinks were up (a worker's events from before it connected are not +backfilled), and a worker's own `simlock events` keeps showing exactly what it always did, un-prefixed and unaware that anything is watching. @@ -142,5 +145,9 @@ lease index, rather than trusting the relayed payload's `ownerId` verbatim. ## Conventions recap - Every event carries: `timestamp`, `event`, `payload`, emitting module. -- Events are appended to a ring buffer that powers `simlock events --follow` - and serves as the audit trail. +- Events are appended to an in-memory ring buffer, which `simlock events` + without `--since` replays, and to the event file `~/.simlock/events.jsonl`, + one JSON line per event with the same fields. The file survives daemon + restarts and crashes, is what `simlock events --since` reads, and is the + durable record: no event is copied into `daemon.log`. It is capped by + `eventLog.rotateBytes`, keeping one rotated generation. diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 5f621e977..8f52b7471 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -621,8 +621,12 @@ an all-or-nothing that leaves the operator guessing. - `GET /v1/leases` — every active lease (`simlock list --leases`). - `GET /v1/devices` — every managed device, with state and `transitionAgeMs` (`simlock list --devices`). -- `GET /v1/events?since=` — replay from the in-memory business-event - ring buffer (`simlock events`). +- `GET /v1/events?since=` — replay business events newer than + `since` (`simlock events --since`). They come from the daemon's event file, + so they include events from before a daemon restart and beyond the 1000 + held in memory, back to the oldest event the file still holds + (`eventLog.rotateBytes`). Without `since`, the recent events held in + memory. - `GET /v1/events/stream` — Server-Sent Events follow of the event bus (`simlock events --follow`). diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 4fb88e966..cc94f4289 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -169,8 +169,8 @@ agent / console ──token auth──> │ HTTP frontend + unix socket the fleet. - **What a gateway does not do.** It starts no drivers, validates no device roots, and runs no reaper, health monitor or capacity strategy; of the - config it reads only `mode`, `http.*`, `log.*`, `lease.*`, `eventBuffer.*` - and `gateway.*` (worker-only keys warn and are ignored). It always listens + config it reads only `mode`, `http.*`, `log.*`, `lease.*`, `eventBuffer.*`, + `eventLog.*` and `gateway.*` (worker-only keys warn and are ignored). It always listens on HTTP — that is how agents reach it and what the uplink upgrades from — so `http.enabled: false` in gateway mode fails the start rather than being silently overridden. `nuke.run`, `cleanup.run`, `doctor.run` and @@ -665,8 +665,9 @@ views, and `workerId` on every device and lease in the aggregate. annotated with the workers that have it. Worker business events are republished on the gateway's bus with `workerId` -added to the payload and land in the gateway's own ring buffer, so `simlock -events --follow` against a gateway shows the whole fleet. The gateway also +added to the payload and land in the gateway's own ring buffer and event +file, so `simlock events --follow` against a gateway shows the whole fleet and +`--since` reaches back across a gateway restart. The gateway also emits its own facts — `worker.connected`, `worker.disconnected`, `worker.rejected`, `worker.removed`, `worker.drain-started`, `worker.drain-ended`, and `request.dispatched`; see [EVENTS.md](EVENTS.md). @@ -1371,32 +1372,38 @@ kicked off has settled — `simlock status` already reports each device's own state (`reclaiming` included), so a separate aggregate would duplicate information already visible per-device rather than add any. -Operational logging is a separate concern from the event bus: `simlock events` -carries business facts (lease granted, device cleaned up, …) in an in-memory -ring buffer that resets on restart, while the `Logger` port writes durable, -structured JSON lines — one per record — for startup, socket claim/recovery, -driver discovery, connection lifecycle, shutdown, and unexpected/handled -errors. `startDaemon` builds the production `Logger` (`JsonLinesLogger` over a -`NodeFileLogSink`) from `config.log` right after config loads, then hands -module-scoped children (`logger.child("server")`, `.child("connection-host")`, -`.child("driver-discovery")`) to each component so every line is attributable. -The sink tracks bytes written and rotates `daemon.log` to `daemon.log.1` -(replacing any previous generation) once `config.log.rotateBytes` is exceeded, -so growth is bounded and `simlock daemon logs` reads the rotated generation -before the current file. The one exception is the fatal top-level handler: it -cannot depend on `config.log` having loaded successfully, so it builds its own -logger straight from the default log path at a fixed level, falling back to -`console.error` only if that itself fails. - -`startDaemon` also subscribes `logger.child("components")` to `component.installed` -(`wireComponentInstallLogging` in `src/daemon/main.ts`) so a component simlock -installed on an agent's behalf stays attributable in `daemon.log` after the -event ring buffer resets on restart — the same durable-vs-ring-buffer split as -everything else in this section, applied to component installs specifically -because there is no registry entry or uninstall for them to be recovered from -otherwise (see "Out of scope" in the #67 issue). The log line carries -`requesterId` whenever the event payload has one, so the durable record names -which agent's request caused the install, not just that one happened. +Operational logging is a separate concern from the event bus (ADR 0006): two +records, and no fact is copied from one into the other. The `Logger` port +writes durable, structured JSON lines — one per record — for startup, socket +claim/recovery, driver discovery, connection lifecycle, shutdown, and +unexpected/handled errors. `startDaemon` builds the production `Logger` +(`JsonLinesLogger` over a `NodeFileLogSink`) from `config.log` right after +config loads, then hands module-scoped children (`logger.child("server")`, +`.child("connection-host")`, `.child("driver-discovery")`) to each component +so every line is attributable. The sink tracks bytes written and rotates +`daemon.log` to `daemon.log.1` (replacing any previous generation) once +`config.log.rotateBytes` is exceeded, so growth is bounded and `simlock daemon +logs` reads the rotated generation before the current file. The one exception +is the fatal top-level handler: it cannot depend on `config.log` having loaded +successfully, so it builds its own logger straight from the default log path +at a fixed level, falling back to `console.error` only if that itself fails. + +Business facts live in the bus's two records. The ring buffer +(`eventBuffer.capacity`) holds recent events in memory and resets on restart. +`EventHistory` (`src/bus/event-file.ts`) subscribes to every event and writes +each envelope as one JSON line to `events.jsonl` in the data directory, +through a second `NodeFileLogSink` that `startDaemon` opens right after the +bus with `config.eventLog.rotateBytes`. That file is the durable record and +the audit trail: it survives restarts and crashes, rotates independently of +`daemon.log`, and on a gateway holds the relayed fleet events too. A file +that cannot be opened, or a write that fails, costs the history and never the +daemon or the emitter: one error line, writing stops, and replay falls back +to the ring. `events.replay` in both dispatchers asks `EventHistory`: without +`sinceTs` it answers from the ring, with `sinceTs` from the file (current +file, then its rotated generation, deduplicated by `seq` and `timestamp`). +The CLI reads the file itself only for `simlock events --since` when no +daemon answers; `--follow` subscribes first, replays, and drops replayed +pushes, so the join neither loses nor repeats an event. ## Device requests diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index 14c51d27f..f88f00c16 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -162,9 +162,12 @@ field: additive, and only ever on a gateway. The seven events in this section's own table are the gateway's own, and carry no `workerId` beyond the worker they are about. -Two consequences of relaying rather than owning: the gateway's ring buffer -only holds what arrived while its uplinks were up (a worker's events from -before it connected are not backfilled), and a worker's own +Relayed events are written to the gateway's own event file +(`events.jsonl`) along with its own, so `simlock events --since` against a +gateway reaches back across a gateway restart. Two consequences of relaying +rather than owning: the gateway's history only holds what arrived while its +uplinks were up (a worker's events from before it connected are not +backfilled), and a worker's own `simlock events` keeps showing exactly what it always did, un-prefixed and unaware that anything is watching. @@ -185,5 +188,9 @@ verbatim off the wire. ## Conventions recap - Every event carries: `timestamp`, `event`, `payload`, emitting module. -- Events are appended to a ring buffer that powers `simlock events --follow` - and serves as the audit trail. +- Events are appended to an in-memory ring buffer, which `simlock events` + without `--since` replays, and to the event file `~/.simlock/events.jsonl`, + one JSON line per event with the same fields. The file survives daemon + restarts and crashes, is what `simlock events --since` reads, and is the + durable record: no event is copied into `daemon.log`. It is capped by + `eventLog.rotateBytes`, keeping one rotated generation. See ADR 0006. diff --git a/docs/internal/KNOWN-PITFALLS.md b/docs/internal/KNOWN-PITFALLS.md index 7141f9ae3..94fa0b02a 100644 --- a/docs/internal/KNOWN-PITFALLS.md +++ b/docs/internal/KNOWN-PITFALLS.md @@ -329,8 +329,9 @@ step, and `Driver.resolveSpec`'s signature carries no progress callback the way `provision`/`makeReady` do. A CLI or MCP caller waiting on a multi-minute install today sees nothing on the wire between its request and either the eventual grant or a timeout; the only visibility is the daemon's -own `component.install-started` bus event (`simlock events --follow`) and log -line, neither reaching the waiting connection itself. Threading a +own `component.install-started` bus event (`simlock events --follow`, and +the event file behind `simlock events --since`), which never reaches the +waiting connection itself. There is no `daemon.log` line for it. Threading a `downloading` stage through would mean widening the `Driver` interface (`resolveSpec` gaining an `onProgress`-shaped option, both drivers implementing it), a new `LeaseProgress` variant, and CLI/MCP wire changes — diff --git a/docs/internal/agent-rules/events.md b/docs/internal/agent-rules/events.md index b99917807..b087576fb 100644 --- a/docs/internal/agent-rules/events.md +++ b/docs/internal/agent-rules/events.md @@ -24,8 +24,9 @@ Rules for defining and emitting events on the daemon's event bus. have to query state that may have moved on. Treat payload shape as a public contract: additive changes only. 7. **Every event carries** `timestamp`, `event`, `payload`, and the emitting - module, and is appended to the ring buffer (this powers `simlock events` - and the audit trail). + module, and is appended to the ring buffer and to the event file + (`events.jsonl`, ADR 0006). The ring powers `simlock events`; the file + powers `simlock events --since` and is the audit trail. 8. **New events are documented in the same change.** Adding or modifying an event requires updating [../EVENTS.md](../EVENTS.md) — name, payload, emission point, status. diff --git a/e2e/event-history.test.ts b/e2e/event-history.test.ts new file mode 100644 index 000000000..d58caec3f --- /dev/null +++ b/e2e/event-history.test.ts @@ -0,0 +1,162 @@ +import { existsSync } from "node:fs"; +import { mkdir, readFile, stat } from "node:fs/promises"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; + +import { type TestEnv, waitFor, withDaemon } from "./helpers/index.js"; + +interface Envelope { + readonly seq: number; + readonly timestamp: number; + readonly event: string; + readonly payload: Record; + readonly module: string; +} + +async function prepare(env: TestEnv): Promise { + await env.driverScript.set({ + ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, + }); +} + +async function leaseDevice(env: TestEnv): Promise { + const lease = await env.cli([ + "lease", + "--platform", + "ios", + "--device", + "iPhone 16", + "--os", + "18.4", + "--detach", + ]); + expect(lease.code).toBe(0); + return (lease.json as { lease: { id: string } }).lease.id; +} + +function parseLines(contents: string): Envelope[] { + return contents + .split("\n") + .filter((line) => line.trim() !== "") + .map((line) => JSON.parse(line) as Envelope); +} + +async function eventFile(env: TestEnv): Promise { + const path = join(env.home, "events.jsonl"); + const rotated = existsSync(`${path}.1`) ? await readFile(`${path}.1`, "utf8") : ""; + return parseLines(rotated + (await readFile(path, "utf8"))); +} + +function grantOf(events: readonly Envelope[], leaseId: string): Envelope | undefined { + return events.find( + (entry) => entry.event === "lease.granted" && entry.payload.leaseId === leaseId, + ); +} + +describe("event history", () => { + it("prints a lease granted before a daemon restart with simlock events --since 1h after it", async () => { + const env = await withDaemon(); + await prepare(env); + const leaseId = await leaseDevice(env); + const before = grantOf(await eventFile(env), leaseId); + expect(before).toBeDefined(); + + await env.restartDaemon(); + const history = await env.cli(["events", "--since", "1h"]); + + expect(history.code).toBe(0); + expect(grantOf(parseLines(history.stdout), leaseId)).toEqual(before); + }); + + it("writes every event file line as JSON carrying seq, timestamp, event, payload and module", async () => { + const env = await withDaemon(); + await prepare(env); + const leaseId = await leaseDevice(env); + expect((await env.cli(["release", leaseId])).code).toBe(0); + + const lines = (await readFile(join(env.home, "events.jsonl"), "utf8")).trimEnd().split("\n"); + + expect(lines.length).toBeGreaterThan(1); + for (const line of lines) { + expect(Object.keys(JSON.parse(line) as object).sort()).toEqual([ + "event", + "module", + "payload", + "seq", + "timestamp", + ]); + } + }); + + it("prints the history with the daemon stopped, and the daemon stays stopped", async () => { + const env = await withDaemon(); + await prepare(env); + const leaseId = await leaseDevice(env); + await env.cli(["daemon", "stop"]); + await waitFor(() => !existsSync(env.socketPath), { label: "daemon socket removed" }); + + const history = await env.cli(["events", "--since", "1h"]); + + expect(history.code).toBe(0); + expect(grantOf(parseLines(history.stdout), leaseId)).toBeDefined(); + expect(existsSync(env.socketPath)).toBe(false); + const status = await env.cli(["daemon", "status", "--json"]); + expect(status.json).toEqual({ status: "stopped" }); + }); + + it("keeps events.jsonl plus events.jsonl.1 under twice eventLog.rotateBytes, holding the newest event", async () => { + const rotateBytes = 8 * 1024; + const env = await withDaemon({ configOverrides: { eventLog: { rotateBytes } } }); + await prepare(env); + let lastLeaseId = ""; + for (let round = 0; round < 8; round++) { + lastLeaseId = await leaseDevice(env); + expect((await env.cli(["release", lastLeaseId])).code).toBe(0); + } + + const path = join(env.home, "events.jsonl"); + await waitFor( + async () => + (await eventFile(env)).some( + (entry) => entry.event === "lease.released" && entry.payload.leaseId === lastLeaseId, + ), + { label: "the last release in the event file" }, + ); + expect(existsSync(`${path}.1`)).toBe(true); + const total = (await stat(path)).size + (await stat(`${path}.1`)).size; + expect(total).toBeLessThanOrEqual(2 * rotateBytes); + }); + + it("keeps every emitted event in the event file after daemon.log rotates", async () => { + const env = await withDaemon({ configOverrides: { log: { rotateBytes: 1024 } } }); + await prepare(env); + for (let round = 0; round < 3; round++) { + const leaseId = await leaseDevice(env); + expect((await env.cli(["release", leaseId])).code).toBe(0); + } + expect(existsSync(`${env.logPath}.1`)).toBe(true); + + // The ring holds every event this daemon emitted; the file must hold each of them. + const ring = await env.cli(["events"]); + expect(ring.code).toBe(0); + const emitted = parseLines(ring.stdout); + const onDisk = new Set( + (await eventFile(env)).map((entry) => `${entry.seq}:${entry.timestamp}`), + ); + + expect(emitted.length).toBeGreaterThan(0); + expect(emitted.filter((entry) => !onDisk.has(`${entry.seq}:${entry.timestamp}`))).toEqual([]); + }); + + it("grants and releases a lease with a directory at the event file's path", async () => { + const env = await withDaemon({ mode: "auto" }); + await mkdir(join(env.home, "events.jsonl")); + expect((await env.startDaemon()).code).toBe(0); + await prepare(env); + + const leaseId = await leaseDevice(env); + const release = await env.cli(["release", leaseId]); + + expect(release.code).toBe(0); + }); +}); diff --git a/e2e/helpers/events.ts b/e2e/helpers/events.ts index f862b7601..afa28d8bb 100644 --- a/e2e/helpers/events.ts +++ b/e2e/helpers/events.ts @@ -8,7 +8,7 @@ export interface RecordedEvent { readonly module: string; } -/** Replays the business-event ring buffer via `simlock events --since`, parsed. */ +/** Replays the business-event history via `simlock events --since`, parsed. */ export async function events(env: NodeJS.ProcessEnv, since = "1h"): Promise { const result = await cli(["events", "--since", since], env); if (result.code !== 0) { diff --git a/e2e/http-api.test.ts b/e2e/http-api.test.ts index df3d83201..352862c3e 100644 --- a/e2e/http-api.test.ts +++ b/e2e/http-api.test.ts @@ -308,4 +308,53 @@ describe("HTTP API", () => { await env.cli(["release", lease?.id ?? ""]); }); + + it("GET /v1/events?since=1h returns an event from before a daemon restart", async () => { + const port = await reservePort(); + const env = await withDaemon({ + configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, + }); + await env.driverScript.set({ + ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, + }); + const lease = await env.cli([ + "lease", + "--platform", + "ios", + "--device", + "iPhone 16", + "--os", + "18.4", + "--detach", + ]); + expect(lease.code).toBe(0); + const leaseId = (lease.json as { lease: { id: string } }).lease.id; + const token = await env.cli(["token", "create", "--role", "operator"]); + const operatorAuth = { authorization: `Bearer ${(token.json as { secret: string }).secret}` }; + + await env.restartDaemon(); + const baseUrl = `http://127.0.0.1:${port}`; + await waitFor( + async () => { + try { + return (await fetch(`${baseUrl}/v1/healthz`)).ok; + } catch { + return false; + } + }, + { label: "HTTP gateway accepting connections after the restart" }, + ); + const response = await fetch(`${baseUrl}/v1/events?since=1h`, { headers: operatorAuth }); + + expect(response.status).toBe(200); + const body = (await response.json()) as { + events: { event: string; payload: { leaseId?: string } }[]; + }; + expect(body.events).toContainEqual( + expect.objectContaining({ + event: "lease.granted", + payload: expect.objectContaining({ leaseId }), + }), + ); + }); }); diff --git a/src/bus/event-file.test.ts b/src/bus/event-file.test.ts new file mode 100644 index 000000000..c6eded316 --- /dev/null +++ b/src/bus/event-file.test.ts @@ -0,0 +1,266 @@ +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { + FakeClock, + type Filesystem, + JsonLinesLogger, + MemoryFilesystem, + MemoryLogSink, + NodeFileLogSink, + NodeFilesystem, +} from "../ports/index.js"; +import { + EVENT_FILE_NAME, + EventBus, + type EventEnvelope, + EventHistory, + readEventFile, +} from "./index.js"; + +const directories: string[] = []; + +afterEach(async () => { + await Promise.all( + directories.splice(0).map((path) => rm(path, { force: true, recursive: true })), + ); +}); + +async function eventFilePath(): Promise { + const directory = await mkdtemp(join(tmpdir(), "simlock-event-file-")); + directories.push(directory); + return join(directory, EVENT_FILE_NAME); +} + +function memoryLogger(): { readonly logger: JsonLinesLogger; readonly sink: MemoryLogSink } { + const sink = new MemoryLogSink(); + return { logger: new JsonLinesLogger({ clock: new FakeClock(), sink }), sink }; +} + +function history(options: { + readonly bus: EventBus; + readonly path: string; + readonly sink?: NodeFileLogSink | { write(line: string): void }; + readonly filesystem?: Filesystem; + readonly logger?: JsonLinesLogger; +}): EventHistory { + return new EventHistory({ + bus: options.bus, + filesystem: options.filesystem ?? new NodeFilesystem(), + logger: options.logger ?? memoryLogger().logger, + path: options.path, + ...(options.sink === undefined ? {} : { sink: options.sink }), + }); +} + +function envelope(seq: number, timestamp: number): EventEnvelope { + return { + seq, + timestamp, + event: "daemon.stopping", + payload: { reason: `r${seq}` }, + module: "daemon", + }; +} + +function lines(...envelopes: EventEnvelope[]): string { + return envelopes.map((entry) => `${JSON.stringify(entry)}\n`).join(""); +} + +describe("EventHistory", () => { + it("writes every emitted event as one JSON line equal to its envelope", async () => { + const path = await eventFilePath(); + const bus = new EventBus(new FakeClock(1_000)); + history({ bus, path, sink: new NodeFileLogSink({ path }) }); + + const first = bus.emit("daemon.stopping", { reason: "line\nbreak" }, "daemon"); + const second = bus.emit( + "lease.expired", + { leaseId: "l-1", deviceId: "d-1", ownerId: "o-1" }, + "leases", + ); + + const written = (await readFile(path, "utf8")).trimEnd().split("\n"); + expect(written.map((line) => JSON.parse(line) as unknown)).toEqual([first, second]); + }); + + it("logs a throwing sink once, and later events still reach the ring and other subscribers", async () => { + const path = await eventFilePath(); + const bus = new EventBus(new FakeClock(1_000)); + const { logger, sink: logSink } = memoryLogger(); + const write = vi.fn(() => { + throw new Error("disk full"); + }); + history({ bus, path, sink: { write }, logger }); + const delivered: string[] = []; + bus.subscribeAll((entry) => delivered.push(entry.event)); + + bus.emit("daemon.stopping", { reason: "a" }, "daemon"); + bus.emit("daemon.stopping", { reason: "b" }, "daemon"); + + expect(write).toHaveBeenCalledTimes(1); + expect(logSink.records.filter((record) => record.level === "error")).toHaveLength(1); + expect(delivered).toEqual(["daemon.stopping", "daemon.stopping"]); + expect(bus.replay().map((entry) => entry.payload)).toEqual([{ reason: "a" }, { reason: "b" }]); + }); + + it("replays with sinceTs the events an earlier bus wrote to the same file", async () => { + const path = await eventFilePath(); + const earlierSink = new NodeFileLogSink({ path }); + const earlier = new EventBus(new FakeClock(1_000)); + history({ bus: earlier, path, sink: earlierSink }); + const granted = earlier.emit( + "lease.granted", + { leaseId: "l-1", deviceId: "d-1", requester: "agent" }, + "leases", + ); + earlierSink.close(); + + const later = new EventBus(new FakeClock(2_000)); + const restarted = history({ bus: later, path, sink: new NodeFileLogSink({ path }) }); + + expect(await restarted.replay({ sinceTs: 0 })).toEqual([granted]); + }); + + it("replays with sinceTs the events the ring has already overwritten", async () => { + const path = await eventFilePath(); + const bus = new EventBus(new FakeClock(1_000), 1); + const events = history({ bus, path, sink: new NodeFileLogSink({ path }) }); + + const first = bus.emit("daemon.stopping", { reason: "a" }, "daemon"); + const second = bus.emit("daemon.stopping", { reason: "b" }, "daemon"); + + expect(bus.replay()).toEqual([second]); + expect(await events.replay({ sinceTs: 0 })).toEqual([first, second]); + }); + + it("replays the ring without sinceTs and reads no file", async () => { + const path = await eventFilePath(); + const bus = new EventBus(new FakeClock(1_000)); + const filesystem = new NodeFilesystem(); + const readSpy = vi.spyOn(filesystem, "readFile"); + const events = history({ bus, filesystem, path, sink: new NodeFileLogSink({ path }) }); + const emitted = bus.emit("daemon.stopping", { reason: "a" }, "daemon"); + + expect(await events.replay()).toEqual([emitted]); + expect(readSpy).not.toHaveBeenCalled(); + }); + + it("replays with sinceTs from the ring when there is no sink", async () => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/data"); + await filesystem.writeFileAtomic("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/data/events.jsonl", lines(envelope(9, 900))); + const bus = new EventBus(new FakeClock(1_000)); + const events = history({ bus, filesystem, path: "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/data/events.jsonl" }); + const emitted = bus.emit("daemon.stopping", { reason: "a" }, "daemon"); + + expect(await events.replay({ sinceTs: 0 })).toEqual([emitted]); + }); + + it("replays with sinceTs from the ring when the event file cannot be read", async () => { + const path = await eventFilePath(); + const bus = new EventBus(new FakeClock(1_000)); + const filesystem = new NodeFilesystem(); + vi.spyOn(filesystem, "readFile").mockRejectedValue( + Object.assign(new Error("permission denied"), { code: "EACCES" }), + ); + const events = history({ bus, filesystem, path, sink: new NodeFileLogSink({ path }) }); + const emitted = bus.emit("daemon.stopping", { reason: "a" }, "daemon"); + + expect(await events.replay({ sinceTs: 0 })).toEqual([emitted]); + }); + + it("replays with sinceTs from the ring once the writer has stopped", async () => { + const path = await eventFilePath(); + const bus = new EventBus(new FakeClock(1_000)); + let fail = false; + const fileSink = new NodeFileLogSink({ path }); + const events = history({ + bus, + path, + sink: { + write: (line) => { + if (fail) throw new Error("disk full"); + fileSink.write(line); + }, + }, + }); + bus.emit("daemon.stopping", { reason: "on disk" }, "daemon"); + fail = true; + bus.emit("daemon.stopping", { reason: "memory only" }, "daemon"); + + expect((await events.replay({ sinceTs: 0 })).map((entry) => entry.payload)).toEqual([ + { reason: "on disk" }, + { reason: "memory only" }, + ]); + }); +}); + +describe("readEventFile", () => { + async function filesystemWith(files: Record): Promise { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/data"); + for (const [path, contents] of Object.entries(files)) { + await filesystem.writeFileAtomic(path, contents); + } + return filesystem; + } + + it("returns the rotated generation before the current file", async () => { + const filesystem = await filesystemWith({ + "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/data/events.jsonl": lines(envelope(3, 300), envelope(4, 400)), + "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/data/events.jsonl.1": lines(envelope(1, 100), envelope(2, 200)), + }); + + const read = await readEventFile(filesystem, "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/data/events.jsonl", { sinceTs: 0 }); + + expect(read.map((entry) => entry.seq)).toEqual([1, 2, 3, 4]); + }); + + it("returns once a generation that shows up in both reads, and skips none", async () => { + const filesystem = await filesystemWith({ + "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/data/events.jsonl": lines(envelope(2, 200), envelope(3, 300)), + "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/data/events.jsonl.1": lines(envelope(1, 100)), + }); + // A rotation lands between the two reads, whichever file is read first: what was current + // becomes the rotated generation, and the new current file holds one later event. + const read = filesystem.readFile.bind(filesystem); + let rotated = false; + vi.spyOn(filesystem, "readFile").mockImplementation(async (path) => { + const contents = await read(path); + if (!rotated) { + rotated = true; + const current = await read("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/data/events.jsonl"); + await filesystem.writeFileAtomic("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/data/events.jsonl.1", current); + await filesystem.writeFileAtomic("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/data/events.jsonl", lines(envelope(4, 400))); + } + return contents; + }); + + const result = await readEventFile(filesystem, "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/data/events.jsonl", { sinceTs: 0 }); + + expect(result.map((entry) => entry.seq)).toEqual([2, 3]); + }); + + it("skips a JSON line that is not an envelope and returns the lines around it", async () => { + const filesystem = await filesystemWith({ + "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/data/events.jsonl": `${lines(envelope(1, 100))}null\n[]\n{"seq":"2"}\n${lines(envelope(3, 300))}`, + }); + + const read = await readEventFile(filesystem, "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/data/events.jsonl", { sinceTs: 0 }); + + expect(read.map((entry) => entry.seq)).toEqual([1, 3]); + }); + + it("skips a line that is not JSON and returns the lines around it", async () => { + const filesystem = await filesystemWith({ + "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/data/events.jsonl": `${lines(envelope(1, 100))}{"seq":2,"times\n${lines(envelope(3, 300))}`, + }); + + const read = await readEventFile(filesystem, "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/data/events.jsonl", { sinceTs: 0 }); + + expect(read.map((entry) => entry.seq)).toEqual([1, 3]); + }); +}); diff --git a/src/bus/event-file.ts b/src/bus/event-file.ts new file mode 100644 index 000000000..500dda36f --- /dev/null +++ b/src/bus/event-file.ts @@ -0,0 +1,124 @@ +import { type Filesystem, isMissingPathError, type Logger, type LogSink } from "../ports/index.js"; +import type { EventBus, EventEnvelope } from "./index.js"; + +/** The durable record of every business event, in the data directory (ADR 0006). */ +export const EVENT_FILE_NAME = "events.jsonl"; + +/** + * Every envelope in the event file newer than `sinceTs`, oldest first. The current file is + * read before its rotated generation (`.1`), so a rotation landing between the two reads + * can only make one generation show up twice -- never make one go missing -- and the repeat is + * dropped by `seq` and `timestamp`. A line that is not JSON (a write cut short by a crash) is + * skipped; a file that is not there is empty. + */ +export async function readEventFile( + filesystem: Filesystem, + path: string, + { sinceTs }: { readonly sinceTs: number }, +): Promise { + const current = await readLines(filesystem, path); + const rotated = await readLines(filesystem, `${path}.1`); + const seen = new Set(); + const envelopes: EventEnvelope[] = []; + for (const line of [...rotated, ...current]) { + const envelope = parseEnvelope(line); + if (envelope === undefined || envelope.timestamp <= sinceTs) continue; + const key = eventKey(envelope); + if (seen.has(key)) continue; + seen.add(key); + envelopes.push(envelope); + } + return envelopes; +} + +/** What identifies one event across the ring, the file and a live push: `seq` restarts with + * every daemon, so it is paired with the timestamp. */ +export function eventKey(event: { readonly seq: number; readonly timestamp: number }): string { + return `${event.seq}:${event.timestamp}`; +} + +async function readLines(filesystem: Filesystem, path: string): Promise { + try { + return (await filesystem.readFile(path)).split("\n"); + } catch (error: unknown) { + if (isMissingPathError(error)) return []; + throw error; + } +} + +function parseEnvelope(line: string): EventEnvelope | undefined { + if (line.trim() === "") return undefined; + let value: unknown; + try { + value = JSON.parse(line); + } catch { + return undefined; + } + if ( + typeof value !== "object" || + value === null || + typeof (value as { seq?: unknown }).seq !== "number" || + typeof (value as { timestamp?: unknown }).timestamp !== "number" + ) { + return undefined; + } + return value as EventEnvelope; +} + +export interface EventHistoryOptions { + readonly bus: EventBus; + /** Where each event is written. Absent when the event file could not be opened. */ + readonly sink?: LogSink; + readonly filesystem: Filesystem; + /** The event file the sink writes, read back by `replay({ sinceTs })`. */ + readonly path: string; + readonly logger: Logger; +} + +/** + * The bus's history: the in-memory ring for recent events, the event file for everything a + * restart or the ring's capacity would otherwise lose. The writer is an observer (events rule + * 5): a write that fails is logged once and writing stops, and nothing reaches the emitter. + */ +export class EventHistory { + readonly #options: EventHistoryOptions; + #writing: boolean; + + constructor(options: EventHistoryOptions) { + this.#options = options; + const { sink } = options; + this.#writing = sink !== undefined; + if (sink === undefined) return; + options.bus.subscribeAll((envelope) => { + if (!this.#writing) return; + try { + sink.write(JSON.stringify(envelope)); + } catch (error: unknown) { + this.#writing = false; + options.logger.error("Event file write failed; events are no longer written to it", { + error: error instanceof Error ? error.message : String(error), + path: options.path, + }); + } + }); + } + + /** + * Without `sinceTs`, the ring, as `simlock events` has always answered. With it, the event + * file while the writer is writing; the ring when there is no file to trust. + */ + async replay(input: { readonly sinceTs?: number } = {}): Promise { + const { bus, filesystem, logger, path } = this.#options; + if (input.sinceTs === undefined) return bus.replay(); + if (!this.#writing) return bus.replay({ sinceTs: input.sinceTs }); + try { + return await readEventFile(filesystem, path, { sinceTs: input.sinceTs }); + } catch (error: unknown) { + logger.warn("Event file read failed; replaying from memory", { + error: error instanceof Error ? error.message : String(error), + path, + }); + return bus.replay({ sinceTs: input.sinceTs }); + } + } +} diff --git a/src/bus/index.ts b/src/bus/index.ts index 5d006e7a4..3c8964632 100644 --- a/src/bus/index.ts +++ b/src/bus/index.ts @@ -403,3 +403,5 @@ export class EventBus { } } } + +export { EVENT_FILE_NAME, EventHistory, eventKey, readEventFile } from "./event-file.js"; diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 1e92c4e65..9044f3e20 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -6,7 +6,7 @@ import { Readable } from "node:stream"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { EventBus } from "../bus/index.js"; +import { EventBus, EventHistory } from "../bus/index.js"; import { type Config, CleanupReaper, FakeDriver, LeaseEngine, Registry } from "../core/index.js"; import { CryptoTokenSecrets, @@ -17,6 +17,7 @@ import { MemoryIpcTransport, NodeFilesystem, NodeIpcTransport, + NoopLogger, SocketPathTooLongError, type Filesystem, type IdGenerator, @@ -33,6 +34,7 @@ import type { DeviceRecoveredPush, DeviceUnhealthyPush, DoctorReport, + EventPush, LeaseGrant, LeaseListOutput, LeaseRecord, @@ -2720,6 +2722,194 @@ describe("CLI: mcp command (ADR 0003 §11 -- lazy module load)", () => { }); }); +describe("CLI: events history", () => { + const hour = 3_600_000; + + function envelope(seq: number, timestamp: number) { + return { seq, timestamp, event: "lease.granted", payload: { seq }, module: "leases" }; + } + + function printed(stdout: string): unknown[] { + return stdout + .trimEnd() + .split("\n") + .map((line) => JSON.parse(line) as unknown); + } + + it("events --since with nothing listening prints the file's events and launches no daemon", async () => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/simlock"); + await filesystem.writeFileAtomic( + "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/simlock/events.jsonl", + [envelope(1, 500), envelope(2, hour + 500)].map((entry) => JSON.stringify(entry)).join("\n"), + ); + const launcher = new FakeDaemonLauncher(() => { + throw new Error("a daemon was launched"); + }); + const output = outputCapture({ + ...realCliEnvironmentPorts(filesystem), + clock: new FakeClock(2 * hour), + launcher, + }); + + const exitCode = await runCli(["events", "--since", "1h"], output.environmentWith()); + + expect(launcher.launches).toBe(0); + expect(exitCode).toBe(0); + expect(printed(output.stdout)).toEqual([envelope(2, hour + 500)]); + }); + + it("events --since reports a daemon that refuses the handshake rather than reading the file", async () => { + const output = outputCapture(); + let fileRead = false; + const exitCode = await runCli( + ["events", "--since", "1h"], + output.environmentWith({ + connectExistingAdmin: async () => { + throw new SimlockError("PROTOCOL_VERSION_UNSUPPORTED", "protocol", "no overlap", { + client: { min: 5, max: 5 }, + daemon: { min: 4, max: 4 }, + daemonVersion: "0.9.0", + }); + }, + readEventFile: async () => { + fileRead = true; + return []; + }, + }), + ); + + expect(exitCode).not.toBe(0); + expect(fileRead).toBe(false); + expect(output.stderr).toContain("PROTOCOL_VERSION_UNSUPPORTED"); + }); + + it("events --since with a daemon listening replays through the daemon", async () => { + const output = outputCapture(); + const asked: unknown[] = []; + let fileRead = false; + const exitCode = await runCli( + ["events", "--since", "1h"], + output.environmentWith({ + clock: new FakeClock(2 * hour), + connectExistingAdmin: async () => + fakeClient({ + replayEvents: async (input) => { + asked.push(input); + return [envelope(7, hour + 1)]; + }, + }), + readEventFile: async () => { + fileRead = true; + return []; + }, + }), + ); + + expect(exitCode).toBe(0); + expect(asked).toEqual([{ sinceTs: hour }]); + expect(printed(output.stdout)).toEqual([envelope(7, hour + 1)]); + expect(fileRead).toBe(false); + }); + + it("events --follow prints an event emitted between the subscribe and the replay exactly once", async () => { + const output = outputCapture(); + const signals = new EventEmitter(); + let listener: ((push: EventPush) => void) | undefined; + const push = (seq: number): EventPush => ({ + subscriptionId: "sub_1", + event: envelope(seq, seq), + }); + const runPromise = runCli( + ["events", "--follow"], + output.environmentWith({ + connectAdmin: async () => + fakeClient({ + subscribeEvents: async (onEvent) => { + listener = onEvent; + return async () => {}; + }, + replayEvents: async () => { + // Emitted after the subscribe and before the replay answers: the replay holds + // seq 2, and seq 3 lands just after its snapshot. + listener?.(push(2)); + listener?.(push(3)); + return [envelope(1, 1), envelope(2, 2)]; + }, + }), + signals: signals as unknown as CliEnvironment["signals"], + }), + ); + await settle(); + listener?.(push(4)); + signals.emit("SIGINT"); + + expect(await runPromise).toBe(0); + expect(printed(output.stdout)).toEqual([envelope(1, 1), envelope(2, 2), push(3), push(4)]); + }); + + it("events --since --follow prints the history once and then the live events", async () => { + const output = outputCapture(); + const signals = new EventEmitter(); + const asked: unknown[] = []; + let listener: ((push: EventPush) => void) | undefined; + const push = (seq: number): EventPush => ({ + subscriptionId: "sub_1", + event: envelope(seq, seq), + }); + const runPromise = runCli( + ["events", "--since", "1h", "--follow"], + output.environmentWith({ + clock: new FakeClock(2 * hour), + connectAdmin: async () => + fakeClient({ + subscribeEvents: async (onEvent) => { + listener = onEvent; + return async () => {}; + }, + replayEvents: async (input) => { + asked.push(input); + listener?.(push(2)); + return [envelope(1, 1), envelope(2, 2)]; + }, + }), + signals: signals as unknown as CliEnvironment["signals"], + }), + ); + await settle(); + listener?.(push(3)); + signals.emit("SIGINT"); + + expect(await runPromise).toBe(0); + expect(asked).toEqual([{ sinceTs: hour }]); + expect(printed(output.stdout)).toEqual([envelope(1, 1), envelope(2, 2), push(3)]); + }); + + it("events --follow without --since asks for no sinceTs", async () => { + const output = outputCapture(); + const signals = new EventEmitter(); + const asked: unknown[] = []; + const runPromise = runCli( + ["events", "--follow"], + output.environmentWith({ + connectAdmin: async () => + fakeClient({ + replayEvents: async (input) => { + asked.push(input); + return []; + }, + }), + signals: signals as unknown as CliEnvironment["signals"], + }), + ); + await settle(); + signals.emit("SIGINT"); + + expect(await runPromise).toBe(0); + expect(asked).toEqual([{}]); + }); +}); + describe("CLI: daemon logs (ADR 0003 §11 -- must work when the daemon is dead)", () => { it("reads the log file without connecting to the daemon at all", async () => { const output = outputCapture(); @@ -3143,6 +3333,7 @@ function outputCapture(ports?: CliEnvironmentPorts): OutputCapture { writeConfigFile: async () => {}, validateConfig: async () => {}, readLogFile: async () => "", + readEventFile: async () => [], signals: new EventEmitter() as unknown as CliEnvironment["signals"], parentWatch: new FakeParentWatch(), stderr: stderrOut, @@ -3228,6 +3419,12 @@ async function startTestDaemon(): Promise<{ socketPath: string; daemon: DaemonSe config, defaultRequesterId: "test-process", eventBus, + eventHistory: new EventHistory({ + bus: eventBus, + filesystem: new MemoryFilesystem(), + logger: new NoopLogger(), + path: "/events.jsonl", + }), host: new DaemonEndpointHost({ connector: new NodeIpcTransport(), endpoint: socketPath, @@ -3337,6 +3534,12 @@ async function startInMemoryDaemon(options: { config, defaultRequesterId: "test-process", eventBus, + eventHistory: new EventHistory({ + bus: eventBus, + filesystem: new MemoryFilesystem(), + logger: new NoopLogger(), + path: "/events.jsonl", + }), host: new DaemonEndpointHost({ connector: ipcTransport, endpoint: socketPath, @@ -3400,6 +3603,7 @@ function testConfig(): Config { }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, + eventLog: { rotateBytes: 5 * 1024 * 1024 }, warmPool: { quarantine: { maxRetries: 3, diff --git a/src/cli/index.ts b/src/cli/index.ts index 1ea88ae01..044b262c5 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -2,6 +2,7 @@ import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { parseArgs } from "node:util"; +import { EVENT_FILE_NAME, type EventEnvelope, eventKey, readEventFile } from "../bus/index.js"; import { loadConfig, type ConfigOverrides } from "../core/index.js"; import { IpcError, @@ -29,7 +30,9 @@ import { connectSimlockAdmin } from "../admin/index.js"; import { isSimlockError, type CatalogGetOutput, + type AnySimlockError, type DoctorReport, + type EventPush, type LeaseGrant, type SimlockAdminClient, type StatusGetOutput, @@ -160,6 +163,8 @@ export interface CliEnvironment { * `writeConfigFile` is ever called. Throws (any error) for an invalid merged config. */ readonly validateConfig: (merged: Record) => Promise; readonly readLogFile?: () => Promise; + /** The event file's history newer than `sinceTs`, for `events --since` with no daemon running. */ + readonly readEventFile: (sinceTs: number) => Promise; /** Loads the MCP frontend only when the `mcp` command is dispatched. */ readonly loadMcpStdio?: () => Promise; readonly runMcpStdio?: () => Promise; @@ -450,6 +455,8 @@ export function buildCliEnvironment( if (unknownKeyWarnings.length > 0) throw new Error(unknownKeyWarnings.join("; ")); }, readLogFile: async () => readLogFile(filesystem, logPath), + readEventFile: (sinceTs) => + readEventFile(filesystem, join(dataDirectory, EVENT_FILE_NAME), { sinceTs }), signals: ports.signals ?? process, stderr: ports.stderr ?? process.stderr, stdout: ports.stdout ?? process.stdout, @@ -1417,19 +1424,19 @@ async function runEvents( environment.stdout.write("Usage: simlock events [--follow] [--since ]\n"); return 0; } - const client = await connectDaemonClient(environment, token); + const sinceTs = + typeof values.since === "string" + ? environment.clock.now() - parseDuration(values.since) + : undefined; + const follow = values.follow === true; + const client = await connectForEvents(environment, token, follow ? undefined : sinceTs); + if (client === undefined) return 0; + const replayInput = sinceTs === undefined ? {} : { sinceTs }; try { - const sinceTs = - typeof values.since === "string" - ? environment.clock.now() - parseDuration(values.since) - : undefined; - for (const event of await client.replayEvents(sinceTs === undefined ? {} : { sinceTs })) { - writeResult(environment, event); - } - if (values.follow) { - const unsubscribe = await client.subscribeEvents((event) => writeResult(environment, event)); - await waitForTermination(environment.signals).settled; - await unsubscribe(); + if (follow) { + await followEvents(client, replayInput, environment); + } else { + for (const event of await client.replayEvents(replayInput)) writeResult(environment, event); } return 0; } finally { @@ -1437,6 +1444,63 @@ async function runEvents( } } +/** + * Connects for `simlock events`. History alone (`--since` without `--follow`, passed as + * `historySinceTs`) needs no daemon: with nothing listening it prints the event file's history + * and resolves `undefined` rather than starting one. + */ +async function connectForEvents( + environment: CliEnvironment, + token: string | undefined, + historySinceTs: number | undefined, +): Promise { + if (historySinceTs === undefined) return connectDaemonClient(environment, token); + try { + return await connectDaemonClient(environment, token, { launch: false }); + } catch (error: unknown) { + if (daemonRefusal(error) !== undefined) throw error; + for (const event of await environment.readEventFile(historySinceTs)) { + writeResult(environment, event); + } + return undefined; + } +} + +/** + * Prints the replay, then streams until a termination signal. Subscribes before replaying, so + * nothing emitted in between is lost; a push the replay already holds is printed once. + */ +async function followEvents( + client: SimlockAdminClient, + replayInput: { readonly sinceTs?: number }, + environment: CliEnvironment, +): Promise { + let buffered: EventPush[] | undefined = []; + const unsubscribe = await client.subscribeEvents((event) => { + if (buffered === undefined) writeResult(environment, event); + else buffered.push(event); + }); + const replayed = await client.replayEvents(replayInput); + for (const event of replayed) writeResult(environment, event); + const printed = new Set(replayed.map(eventKey)); + const pending = buffered; + buffered = undefined; + for (const push of pending) { + if (!printed.has(eventKey(push.event))) writeResult(environment, push); + } + await waitForTermination(environment.signals).settled; + await unsubscribe(); +} + +/** + * The refusal, when a failed connection reached a daemon that answered and refused it (a + * `SimlockError` of a kind other than `transport`); `undefined` when nothing is listening. + * `daemon status` reports the second as "stopped"; `events --since` reads the event file. + */ +function daemonRefusal(error: unknown): AnySimlockError | undefined { + return isSimlockError(error) && error.kind !== "transport" ? error : undefined; +} + // fallow-ignore-next-line complexity -- daemon subcommand parsing is a single CLI boundary. async function runDaemon( argv: readonly string[], @@ -1494,14 +1558,17 @@ async function runDaemon( // anything else (a raw `IpcError`, or a `transport`-kind `SimlockError` such as // `DAEMON_CONNECTION_LOST`) means nothing is listening -- the pre-existing "stopped" // outcome. - if (isSimlockError(error) && error.kind !== "transport") { + const refusal = daemonRefusal(error); + if (refusal !== undefined) { if (values.json) { writeResult(environment, { status: "handshake-refused", - error: { code: error.code, message: error.message }, + error: { code: refusal.code, message: refusal.message }, }); } else { - environment.stdout.write(`Daemon handshake refused: ${error.code}: ${error.message}\n`); + environment.stdout.write( + `Daemon handshake refused: ${refusal.code}: ${refusal.message}\n`, + ); } return 1; } diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index 9b3a28863..56e53847b 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -448,6 +448,8 @@ export const configSchema = z.object({ level: z.enum(["debug", "info", "warn", "error"]), rotateBytes: z.number(), }), + // Optional: a newer gateway parses this from an older worker's `config.get`. + eventLog: z.object({ rotateBytes: z.number() }).optional(), http: z.object({ enabled: z.boolean(), host: z.string(), diff --git a/src/core/acquisition-planner.test.ts b/src/core/acquisition-planner.test.ts index 4716a75c1..89e16be00 100644 --- a/src/core/acquisition-planner.test.ts +++ b/src/core/acquisition-planner.test.ts @@ -56,6 +56,7 @@ const config: Config = { }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, + eventLog: { rotateBytes: 5 * 1024 * 1024 }, }; function device( diff --git a/src/core/cleanup/idle-destroy.test.ts b/src/core/cleanup/idle-destroy.test.ts index a5b818047..451ba0d35 100644 --- a/src/core/cleanup/idle-destroy.test.ts +++ b/src/core/cleanup/idle-destroy.test.ts @@ -56,6 +56,7 @@ const config: Config = { }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, + eventLog: { rotateBytes: 5 * 1024 * 1024 }, }; function view( diff --git a/src/core/cleanup/idle-shutdown.test.ts b/src/core/cleanup/idle-shutdown.test.ts index e087ecb71..39ac925a9 100644 --- a/src/core/cleanup/idle-shutdown.test.ts +++ b/src/core/cleanup/idle-shutdown.test.ts @@ -54,6 +54,7 @@ const config: Config = { }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, + eventLog: { rotateBytes: 5 * 1024 * 1024 }, }; function view(now: number): RegistryView { diff --git a/src/core/config.test.ts b/src/core/config.test.ts index 024e4e11a..d8f9ef89c 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -100,6 +100,7 @@ describe("loadConfig", () => { }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, + eventLog: { rotateBytes: 5 * 1024 * 1024 }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, warmPool: { @@ -228,6 +229,21 @@ describe("loadConfig", () => { ).rejects.toThrow("log.rotateBytes"); }); + it("defaults eventLog.rotateBytes to 5 MiB and rejects zero and negative values", async () => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/agent/.simlock"); + + const defaults = await loadConfig({ configPath, filesystem, systemStats: createStats() }); + expect(defaults.eventLog).toEqual({ rotateBytes: 5 * 1024 * 1024 }); + + for (const rotateBytes of [0, -1]) { + await filesystem.writeFileAtomic(configPath, JSON.stringify({ eventLog: { rotateBytes } })); + await expect( + loadConfig({ configPath, filesystem, systemStats: createStats() }), + ).rejects.toThrow("eventLog.rotateBytes"); + } + }); + it("applies a file-level warm-pool quarantine override", async () => { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/home/agent/.simlock"); @@ -1189,6 +1205,14 @@ describe("loadConfig modes (ADR 0005)", () => { expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('Ignoring "lease"')); }); + it("raises no unknown-key warning for eventLog.rotateBytes in a gateway config", async () => { + const warn = vi.fn(); + const config = await load({ mode: "gateway", eventLog: { rotateBytes: 1024 } }, { warn }); + + expect(warn).not.toHaveBeenCalled(); + expect(config.eventLog.rotateBytes).toBe(1024); + }); + it("warns about android.emulator on a gateway without refusing the config", async () => { const warn = vi.fn(); const config = await load( diff --git a/src/core/config.ts b/src/core/config.ts index c1d0d71cb..14121be2b 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -163,6 +163,8 @@ export interface Config { readonly diskPressure: { readonly freeBytesThreshold: number }; readonly eventBuffer: { readonly capacity: number }; readonly log: { readonly level: LogLevel; readonly rotateBytes: number }; + /** The event file (`events.jsonl`): its size before it rotates, one generation kept. */ + readonly eventLog: { readonly rotateBytes: number }; readonly http: { readonly enabled: boolean; readonly host: string; @@ -385,6 +387,7 @@ const GATEWAY_CONFIG_KEYS: readonly string[] = [ "log", "lease", "eventBuffer", + "eventLog", "gateway", ]; @@ -600,6 +603,7 @@ function defaultConfig( diskPressure: { freeBytesThreshold: 10 * 1024 ** 3 }, eventBuffer: { capacity: 1_000 }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, + eventLog: { rotateBytes: 5 * 1024 * 1024 }, // ADR 0005 §2: a gateway always listens on HTTP, so that is its default rather than // something every operator has to remember to switch on; a worker's HTTP gateway stays // opt-in exactly as before. @@ -738,6 +742,7 @@ function configValidators(strategy: CapacityStrategyName): Record }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, + eventLog: { rotateBytes: 5 * 1024 * 1024 }, warmPool: { quarantine: { maxRetries: 3, diff --git a/src/core/lease-acquisition-coordinator.test.ts b/src/core/lease-acquisition-coordinator.test.ts index 0f1c03f1a..2673f9c00 100644 --- a/src/core/lease-acquisition-coordinator.test.ts +++ b/src/core/lease-acquisition-coordinator.test.ts @@ -63,6 +63,7 @@ function config(maxDevices = 1): Config { }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, + eventLog: { rotateBytes: 5 * 1024 * 1024 }, warmPool: { quarantine: { maxRetries: 3, diff --git a/src/core/lease-engine.test.ts b/src/core/lease-engine.test.ts index 0fa789cd4..55089b4fc 100644 --- a/src/core/lease-engine.test.ts +++ b/src/core/lease-engine.test.ts @@ -65,6 +65,7 @@ function config(overrides: Partial = {}): Config { }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, + eventLog: { rotateBytes: 5 * 1024 * 1024 }, warmPool: { quarantine: { maxRetries: 3, diff --git a/src/core/lease-health-monitor.test.ts b/src/core/lease-health-monitor.test.ts index 78382724a..ec5a50f33 100644 --- a/src/core/lease-health-monitor.test.ts +++ b/src/core/lease-health-monitor.test.ts @@ -59,6 +59,7 @@ function config(overrides: Partial = {}): Config { }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, + eventLog: { rotateBytes: 5 * 1024 * 1024 }, stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, diff --git a/src/core/nuke.test.ts b/src/core/nuke.test.ts index fe6170304..c9622f64c 100644 --- a/src/core/nuke.test.ts +++ b/src/core/nuke.test.ts @@ -187,6 +187,7 @@ function config(): Config { }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, + eventLog: { rotateBytes: 5 * 1024 * 1024 }, warmPool: { quarantine: { maxRetries: 3, diff --git a/src/core/reaper.test.ts b/src/core/reaper.test.ts index 4721640e0..7bc0bd314 100644 --- a/src/core/reaper.test.ts +++ b/src/core/reaper.test.ts @@ -82,6 +82,7 @@ function config(): Config { }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, + eventLog: { rotateBytes: 5 * 1024 * 1024 }, warmPool: { quarantine: { maxRetries: 3, diff --git a/src/core/warm-pool-coordinator.test.ts b/src/core/warm-pool-coordinator.test.ts index f5c27db2c..da60ddbc7 100644 --- a/src/core/warm-pool-coordinator.test.ts +++ b/src/core/warm-pool-coordinator.test.ts @@ -65,6 +65,7 @@ const config: Config = { }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, + eventLog: { rotateBytes: 5 * 1024 * 1024 }, }; class TestRegistry { diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 254402c36..d4e65b98c 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from "vitest"; -import { EventBus } from "../bus/index.js"; +import { EventBus, type EventEnvelope, EventHistory } from "../bus/index.js"; import { CleanupReaper, Doctor, @@ -20,6 +20,7 @@ import { FakeSystemStats, MemoryFilesystem, NodeProcessRunner, + NoopLogger, ScriptedProcessRunner, type ProcessRunner, } from "../ports/index.js"; @@ -52,6 +53,17 @@ function resolvePassthroughOverride( return override ?? engine; } +function resolveEventHistoryOverride( + eventBus: EventBus, + filesystem: MemoryFilesystem, + override: Pick | undefined, +): Pick { + return ( + override ?? + new EventHistory({ bus: eventBus, filesystem, logger: new NoopLogger(), path: "/events.jsonl" }) + ); +} + async function buildDispatcher( overrides: { readonly downloadsPolicy?: Config["downloads"]["policy"]; @@ -87,6 +99,8 @@ async function buildDispatcher( * `device.exec` command a *real* `NodeProcessRunner` can actually spawn (`node -e ...` * takes no `--set`), rather than `ScriptedProcessRunner`'s scripted chunks. */ readonly passthroughOverride?: PassthroughResolver; + /** Stands in for the event history, so `events.replay` can be checked against it. */ + readonly eventHistory?: Pick; } = {}, ) { const clock = overrides.clock ?? new FakeClock(1_000); @@ -172,7 +186,7 @@ async function buildDispatcher( clock, config, doctor, - eventBus, + eventHistory: resolveEventHistoryOverride(eventBus, filesystem, overrides.eventHistory), health: () => "running", leases: engine, ...(overrides.includeNuke === true ? { nuke: new Nuke({ executor: engine, registry }) } : {}), @@ -656,6 +670,28 @@ describe("Dispatcher: lease.release-all", () => { }); }); +describe("Dispatcher: events.replay", () => { + it("events.replay with sinceTs returns what the event history returns", async () => { + const fromHistory: EventEnvelope[] = [ + { seq: 7, timestamp: 50, event: "daemon.stopping", payload: { reason: "x" }, module: "d" }, + ]; + const asked: unknown[] = []; + const { dispatcher } = await buildDispatcher({ + eventHistory: { + replay: async (input) => { + asked.push(input); + return fromHistory; + }, + }, + }); + + await expect( + dispatcher.dispatch("events.replay", { sinceTs: 10 }, session({ role: "admin" })), + ).resolves.toEqual(fromHistory); + expect(asked).toEqual([{ sinceTs: 10 }]); + }); +}); + describe("Dispatcher: nuke.run", () => { it("rejects an agent session with FORBIDDEN, without deleting anything", async () => { const { dispatcher, registry } = await buildDispatcher({ includeNuke: true }); @@ -1372,6 +1408,7 @@ function testConfig( }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, + eventLog: { rotateBytes: 5 * 1024 * 1024 }, warmPool: { quarantine: { maxRetries: 3, diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 8ed9ece21..53cc0cc14 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -1,6 +1,6 @@ import { z } from "zod"; -import type { EventBus } from "../bus/index.js"; +import type { EventHistory } from "../bus/index.js"; import { type CleanupReaper, type Config, @@ -82,7 +82,8 @@ export interface DispatcherOptions { readonly clock: Clock; readonly config: Config; readonly doctor?: Doctor; - readonly eventBus: EventBus; + /** Answers `events.replay`: the ring, or the event file for a `sinceTs`. */ + readonly eventHistory: Pick; readonly leases: LeaseCommands; readonly logger?: Logger; readonly nuke?: Nuke; @@ -546,7 +547,7 @@ export class Dispatcher { }; #eventsReplay: Handler<"events.replay"> = (input) => - this.options.eventBus.replay(input.sinceTs === undefined ? {} : { sinceTs: input.sinceTs }); + this.options.eventHistory.replay(input.sinceTs === undefined ? {} : { sinceTs: input.sinceTs }); #eventsSubscribe: Handler<"events.subscribe"> = (_input, session) => { const subscriptionId = session.manageEventSubscription(true); diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index b158c7d45..25adbc788 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -1,4 +1,4 @@ -import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { connect, createServer, Server } from "node:net"; @@ -26,7 +26,6 @@ import { emitComponentInstallDiagnostic, emitSlimDiagnostic, startDaemon, - wireComponentInstallLogging, type DriverDiscoveryContext, type StartDaemonOptions, } from "./main.js"; @@ -68,6 +67,14 @@ async function start( return { daemon, sink }; } +async function writeModule(contents: string): Promise { + const directory = await mkdtemp(join(tmpdir(), "simlock-drivers-module-")); + temporaryDirectories.push(directory); + const modulePath = join(directory, "drivers.mjs"); + await writeFile(modulePath, contents, "utf8"); + return modulePath; +} + /** A driver whose disposal is observable, which `FakeDriver` deliberately is not. */ class DisposableFakeDriver extends FakeDriver { constructor( @@ -954,116 +961,61 @@ describe("slim diagnostic bridging", () => { }); }); -describe("wireComponentInstallLogging", () => { - it('writes a durable structured log line under logger.child("components") when component.installed fires', () => { - const clock = new FakeClock(1_000); - const sink = new MemoryLogSink(); - const logger = new JsonLinesLogger({ clock, level: "debug", sink }); - const eventBus = new EventBus(clock); - - wireComponentInstallLogging(eventBus, logger); - eventBus.emit( - "component.installed", - { componentId: "18.6", durationMs: 42_000, platform: "ios" }, - "driver-diagnostics", - ); - - expect(sink.records).toContainEqual( - expect.objectContaining({ - level: "info", - message: "Component installed", - module: "daemon.components", - fields: { componentId: "18.6", durationMs: 42_000, platform: "ios" }, - }), - ); - }); - - it("includes requesterId in the durable log line when the event carries one", () => { - const clock = new FakeClock(1_000); - const sink = new MemoryLogSink(); - const logger = new JsonLinesLogger({ clock, level: "debug", sink }); - const eventBus = new EventBus(clock); - - wireComponentInstallLogging(eventBus, logger); - eventBus.emit( - "component.installed", - { componentId: "18.6", durationMs: 42_000, platform: "ios", requesterId: "agent-1" }, - "driver-diagnostics", - ); +describe("startDaemon event file", () => { + const previousModule = process.env.SIMLOCK_DRIVERS_MODULE; - expect(sink.records).toContainEqual( - expect.objectContaining({ - level: "info", - message: "Component installed", - module: "daemon.components", - fields: { - componentId: "18.6", - durationMs: 42_000, - platform: "ios", - requesterId: "agent-1", - }, - }), - ); + afterEach(() => { + if (previousModule === undefined) { + delete process.env.SIMLOCK_DRIVERS_MODULE; + } else { + process.env.SIMLOCK_DRIVERS_MODULE = previousModule; + } }); - it("does not log for component.install-started or component.install-failed", () => { - const clock = new FakeClock(1_000); - const sink = new MemoryLogSink(); - const logger = new JsonLinesLogger({ clock, level: "debug", sink }); - const eventBus = new EventBus(clock); + it("starts a daemon whose event file cannot be opened, and logs one error line", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock-main-event-file-")); + temporaryDirectories.push(directory); + await mkdir(join(directory, "events.jsonl")); - wireComponentInstallLogging(eventBus, logger); - eventBus.emit( - "component.install-started", - { componentId: "18.6", platform: "ios" }, - "driver-diagnostics", - ); - eventBus.emit( - "component.install-failed", - { componentId: "18.6", durationMs: 1_000, error: "boom", platform: "ios" }, - "driver-diagnostics", - ); + const { daemon, sink } = await start({ dataDirectory: directory }); - expect(sink.records).toEqual([]); + expect(daemon.health).toBe("running"); + expect( + sink.records.filter( + (record) => record.level === "error" && record.module === "daemon.events", + ), + ).toHaveLength(1); }); - it('writes a durable structured log line under logger.child("slim") when device.slimmed fires', () => { - const clock = new FakeClock(1_000); - const sink = new MemoryLogSink(); - const logger = new JsonLinesLogger({ clock, level: "debug", sink }); - const eventBus = new EventBus(clock); - - wireComponentInstallLogging(eventBus, logger); - eventBus.emit( - "device.slimmed", - { - address: "simlock-ios-1-address", - categories: ["siri", "spotlight"], - deviceId: "simlock-ios-1", - durationMs: 12_000, - labelCount: 170, - platform: "ios", - signature: "sig-abc123", - unknownLabels: [], - }, - "driver-diagnostics", + it("writes no daemon log line for component.installed and device.slimmed", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock-main-event-file-")); + temporaryDirectories.push(directory); + // The daemon's own bus is reachable only through what it hands discovery. + process.env.SIMLOCK_DRIVERS_MODULE = await writeModule( + `export function createDrivers({ eventBus }) { + eventBus.emit("component.installed", { componentId: "18.6", durationMs: 1, platform: "ios" }, "test"); + eventBus.emit("device.slimmed", { + address: "a", categories: [], deviceId: "d", durationMs: 1, labelCount: 0, + platform: "ios", signature: "s", unknownLabels: [], + }, "test"); + return []; + }`, ); - expect(sink.records).toContainEqual( - expect.objectContaining({ - level: "info", - message: "Device slimmed", - module: "daemon.slim", - fields: { - categories: ["siri", "spotlight"], - deviceId: "simlock-ios-1", - durationMs: 12_000, - labelCount: 170, - signature: "sig-abc123", - unknownLabels: [], - }, - }), - ); + const { sink } = await start({ dataDirectory: directory, drivers: undefined }); + + const written = (await readFile(join(directory, "events.jsonl"), "utf8")) + .trimEnd() + .split("\n") + .map((line) => (JSON.parse(line) as { event: string }).event); + expect(written).toEqual(expect.arrayContaining(["component.installed", "device.slimmed"])); + expect( + sink.records.filter((record) => + JSON.stringify(record).match( + /component\.installed|device\.slimmed|Component installed|Device slimmed/, + ), + ), + ).toEqual([]); }); }); @@ -1078,14 +1030,6 @@ describe("discoverDrivers with SIMLOCK_DRIVERS_MODULE", () => { } }); - async function writeModule(contents: string): Promise { - const directory = await mkdtemp(join(tmpdir(), "simlock-drivers-module-")); - temporaryDirectories.push(directory); - const modulePath = join(directory, "drivers.mjs"); - await writeFile(modulePath, contents, "utf8"); - return modulePath; - } - async function discover(sink: MemoryLogSink) { const logger = new JsonLinesLogger({ clock: new FakeClock(), level: "debug", sink }); return discoverDrivers({ diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 5aae95f17..632dd27ed 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -2,7 +2,7 @@ import { homedir } from "node:os"; import { join, resolve } from "node:path"; import { pathToFileURL } from "node:url"; -import { EventBus } from "../bus/index.js"; +import { EVENT_FILE_NAME, EventBus, EventHistory } from "../bus/index.js"; import { type Config, type ConfigOverrides, @@ -129,10 +129,7 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise { - const { clock, config, dataDirectory, eventBus, filesystem, idGenerator, logger } = options; + const { clock, config, dataDirectory, eventBus, eventHistory, filesystem, idGenerator, logger } = + options; // The gateway's own identity, used to namespace the principal it announces to each worker // (ADR 0005 §27's shape) so a worker's logs attribute what the gateway did to the gateway. const instanceId = await loadInstanceId({ @@ -614,7 +615,7 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise gatewayService.closeLinksForToken(tokenId), config, coordinator: fleetCoordinator, - eventBus, + eventHistory, health: () => daemon.health, leaseIndex, logger: logger.child("gateway"), @@ -989,7 +990,7 @@ async function loadDriversModule( * bus event. Drivers never depend on the event bus directly (architecture rule 5 -- loose * coupling via the bus is for observers only) -- this is the one place, at driver construction, * that bridges the driver's diagnostic callback to a post-commit fact for observers (`simlock - * events`, and the durable-log subscription in `startDaemon`). + * events`, and the event file behind it). */ export function emitComponentInstallDiagnostic( eventBus: Pick, @@ -1048,7 +1049,7 @@ export function emitComponentInstallDiagnostic( * `emitComponentInstallDiagnostic`: the driver never depends on the event bus directly * (architecture rule 5) -- this is the one place, at driver construction, that bridges the * driver's `onSlimmed` callback to a post-commit fact for observers (`simlock events`, and the - * durable-log subscription in `startDaemon`). A *skipped* slim is deliberately not bridged here + * event file behind it). A *skipped* slim is deliberately not bridged here * -- see `onSlimSkipped` in `discoverDrivers`, which logs it instead (see `docs/internal/EVENTS.md`). */ export function emitSlimDiagnostic(eventBus: Pick): (fact: SlimmedFact) => void { @@ -1098,38 +1099,33 @@ export function bridgeAndroidDriverDiagnostic( } /** - * Durable bookkeeping for component installs (and iOS slims, below): the event ring buffer - * (`simlock events`) resets on daemon restart, so a component simlock installed -- or a device it - * slimmed -- on an agent's behalf is only attributable later through this log line -- see the - * `Logger` port ("Operational logging is a separate concern from the event bus" in - * ARCHITECTURE.md). + * Every event the daemon emits, also in `events.jsonl` (ADR 0006). An event file that cannot be + * opened costs the history, never the daemon: one error line, and replay answers from the ring. */ -export function wireComponentInstallLogging( - eventBus: Pick, - logger: Logger, -): void { - const componentsLogger = logger.child("components"); - eventBus.subscribe("component.installed", (envelope) => { - componentsLogger.info("Component installed", { - componentId: envelope.payload.componentId, - durationMs: envelope.payload.durationMs, - platform: envelope.payload.platform, - ...(envelope.payload.requesterId === undefined - ? {} - : { requesterId: envelope.payload.requesterId }), - }); - }); - - const slimLogger = logger.child("slim"); - eventBus.subscribe("device.slimmed", (envelope) => { - slimLogger.info("Device slimmed", { - categories: envelope.payload.categories, - deviceId: envelope.payload.deviceId, - durationMs: envelope.payload.durationMs, - labelCount: envelope.payload.labelCount, - signature: envelope.payload.signature, - unknownLabels: envelope.payload.unknownLabels, +function openEventHistory(options: { + readonly config: Config; + readonly dataDirectory: string; + readonly eventBus: EventBus; + readonly filesystem: Filesystem; + readonly logger: Logger; +}): EventHistory { + const path = join(options.dataDirectory, EVENT_FILE_NAME); + const logger = options.logger.child("events"); + let sink: NodeFileLogSink | undefined; + try { + sink = new NodeFileLogSink({ maxBytes: options.config.eventLog.rotateBytes, path }); + } catch (error: unknown) { + logger.error("Event file could not be opened; events are kept in memory only", { + error: error instanceof Error ? error.message : String(error), + path, }); + } + return new EventHistory({ + bus: options.eventBus, + filesystem: options.filesystem, + logger, + path, + ...(sink === undefined ? {} : { sink }), }); } diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index b5fb108bd..0c3b1adb8 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -4,7 +4,7 @@ import { join } from "node:path"; import { Socket, connect } from "node:net"; import { afterEach, describe, expect, it } from "vitest"; -import { EventBus } from "../bus/index.js"; +import { EventBus, EventHistory } from "../bus/index.js"; import { type Config, type DriverRejection, @@ -28,6 +28,7 @@ import { MemoryLogSink, NodeFilesystem, NodeIpcTransport, + NoopLogger, ScriptedProcessRunner, type IpcConnection, type Logger, @@ -2716,6 +2717,12 @@ async function createHarness( : { driverRejections: options.driverRejections }), defaultRequesterId: "test-process", eventBus, + eventHistory: new EventHistory({ + bus: eventBus, + filesystem: new MemoryFilesystem(), + logger: new NoopLogger(), + path: "/events.jsonl", + }), host: options.host ?? new DaemonEndpointHost({ @@ -3041,6 +3048,7 @@ function testConfig( }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, + eventLog: { rotateBytes: 5 * 1024 * 1024 }, warmPool: { quarantine: { maxRetries: 3, diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 15a0adb81..822718edb 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -1,6 +1,6 @@ import { z } from "zod"; -import { type EventBus, type EventEnvelope } from "../bus/index.js"; +import { type EventBus, type EventEnvelope, type EventHistory } from "../bus/index.js"; import { type Config, type LeaseProgress, @@ -138,6 +138,8 @@ export interface DaemonServerEngineOptions { readonly capacity: CapacityReader; readonly catalog: CatalogReader; readonly doctor?: Doctor; + /** What `events.replay` answers from; see `EventHistory`. */ + readonly eventHistory: Pick; readonly leases: LeaseCommands; readonly queue: QueueControl; readonly reaper: CleanupReaper; @@ -281,7 +283,7 @@ function buildDispatcher( clock: options.clock, config: options.config, ...(options.doctor === undefined ? {} : { doctor: options.doctor }), - eventBus: options.eventBus, + eventHistory: options.eventHistory, health: hooks.health, leases: options.leases, ...(options.logger === undefined ? {} : { logger: options.logger }), diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index b8e89a503..2df6819f3 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -1,9 +1,9 @@ import { describe, expect, it } from "vitest"; -import { EventBus } from "../bus/index.js"; +import { EventBus, type EventEnvelope, EventHistory } from "../bus/index.js"; import { OPERATIONS, type OperationName } from "../contract/index.js"; import type { DispatchSession } from "../daemon/dispatch.js"; -import { FakeClock } from "../ports/index.js"; +import { FakeClock, MemoryFilesystem, NoopLogger } from "../ports/index.js"; import { GatewayDispatcher, type GatewayTokenStore } from "./dispatcher.js"; import { MemoryDrainStore } from "./drain-store.js"; import { FleetLeaseCoordinator } from "./fleet-coordinator.js"; @@ -106,7 +106,7 @@ class FakeDirectory implements WorkerDirectory { } } -function harness() { +function harness(options: { readonly eventHistory?: Pick } = {}) { const clock = new FakeClock(1_000); const eventBus = new EventBus(clock); const workers = new WorkerRegistry({ @@ -144,7 +144,14 @@ function harness() { }, config: gatewayConfig, coordinator, - eventBus, + eventHistory: + options.eventHistory ?? + new EventHistory({ + bus: eventBus, + filesystem: new MemoryFilesystem(), + logger: new NoopLogger(), + path: "/events.jsonl", + }), health: () => "running", leaseIndex, tokens, @@ -380,6 +387,26 @@ describe("GatewayDispatcher", () => { }); }); + it("events.replay with sinceTs returns what the event history returns", async () => { + const fromHistory: EventEnvelope[] = [ + { seq: 7, timestamp: 50, event: "daemon.stopping", payload: { reason: "x" }, module: "d" }, + ]; + const asked: unknown[] = []; + const { dispatcher } = harness({ + eventHistory: { + replay: async (input) => { + asked.push(input); + return fromHistory; + }, + }, + }); + + await expect(dispatcher.dispatch("events.replay", { sinceTs: 10 }, session())).resolves.toEqual( + fromHistory, + ); + expect(asked).toEqual([{ sinceTs: 10 }]); + }); + it("mints and revokes its own tokens, worker join tokens included", async () => { const { dispatcher, tokens } = harness(); diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts index 9f712a266..e5cf1aa68 100644 --- a/src/gateway/dispatcher.ts +++ b/src/gateway/dispatcher.ts @@ -29,7 +29,7 @@ */ import type { z } from "zod"; -import type { EventBus } from "../bus/index.js"; +import type { EventHistory } from "../bus/index.js"; import { OPERATIONS, type OperationName, type tokenRecordSchema } from "../contract/index.js"; import { DispatchError, @@ -83,7 +83,8 @@ export interface GatewayTokenStore { export interface GatewayDispatcherOptions { /** The gateway's own config -- what `config.get` returns (ADR 0005 §34). */ readonly config: GatewayConfig; - readonly eventBus: EventBus; + /** Answers `events.replay`: the ring, or the event file for a `sinceTs`. */ + readonly eventHistory: Pick; readonly workers: WorkerRegistry; readonly tokens?: GatewayTokenStore; /** @@ -205,7 +206,7 @@ export class GatewayDispatcher { #configGet: Handler<"config.get"> = () => this.options.config; #eventsReplay: Handler<"events.replay"> = (input) => - this.options.eventBus.replay(input.sinceTs === undefined ? {} : { sinceTs: input.sinceTs }); + this.options.eventHistory.replay(input.sinceTs === undefined ? {} : { sinceTs: input.sinceTs }); #eventsSubscribe: Handler<"events.subscribe"> = (_input, session) => { const subscriptionId = session.manageEventSubscription(true); diff --git a/src/http/test-fakes.ts b/src/http/test-fakes.ts index 793e55f5a..7fcd8de6d 100644 --- a/src/http/test-fakes.ts +++ b/src/http/test-fakes.ts @@ -55,6 +55,7 @@ export function testConfig( ...overrides, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, + eventLog: { rotateBytes: 5 * 1024 * 1024 }, stalledTransition: { minimumThresholdMs: 60_000, thresholdMultiplier: 3 }, warmPool: { quarantine: { diff --git a/src/ports/logger.ts b/src/ports/logger.ts index cd20eb210..c87e5a881 100644 --- a/src/ports/logger.ts +++ b/src/ports/logger.ts @@ -135,7 +135,8 @@ export interface NodeFileLogSinkOptions { * inherited append fd on this same path for uncaught fatal output -- see below), and is * the only kind of write that reliably lands from a handler where the process is about * to exit. This is sound only because volume is low by design: operational lifecycle - * lines (startup, connection churn, shutdown), not per-request logging. + * lines (startup, connection churn, shutdown) in `daemon.log`, and one line per business + * event in `events.jsonl` -- not per-request logging. * * `#bytesWritten` only counts what this sink itself writes. The daemon launcher's * inherited fd can append a fatal crash dump to the same file without going through @@ -167,8 +168,8 @@ export class NodeFileLogSink implements LogSink { } /** - * Not called anywhere in production: `startDaemon` builds this sink once at startup - * and never tears it down, relying on the fd closing at process exit. Deliberate -- + * Not called anywhere in production: `startDaemon` builds its sinks (`daemon.log`, + * `events.jsonl`) once at startup and never tears them down, relying on the fd closing at process exit. Deliberate -- * threading a close-on-shutdown path through `main.ts` would couple the daemon's * shutdown sequence to this specific adapter for no real benefit. Kept as a public * method purely so tests can close and reopen deterministically.