From 4be275868ed6af7a8cb48e9d8aafdb923150c07d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 20:04:40 +0200 Subject: [PATCH 1/5] feat(contract,daemon,http,docs): a worker answers the fleet operations as a fleet of one On a single host, worker.list returns the host itself, built by the same contract function a gateway builds its worker views with. worker.drain, undrain, remove and install-component answer UNSUPPORTED_IN_WORKER_MODE (501, exit 2). The /v1/workers routes are registered in both modes. Closes #270 --- docs/CLI.md | 35 +++++--- docs/CLIENT.md | 17 +++- docs/HTTP-API.md | 35 ++++++-- docs/internal/ARCHITECTURE.md | 19 ++++- e2e/contract-surface.test.ts | 19 ++--- e2e/single-host-fleet.test.ts | 152 ++++++++++++++++++++++++++++++++++ src/cli/index.test.ts | 2 + src/cli/index.ts | 12 +-- src/contract/errors.ts | 16 ++++ src/contract/index.ts | 1 + src/contract/operations.ts | 27 ++---- src/contract/schemas.ts | 4 + src/contract/worker-view.ts | 64 ++++++++++++++ src/daemon/dispatch.ts | 3 +- src/daemon/dispatcher.test.ts | 135 ++++++++++++++++++++++++++++-- src/daemon/dispatcher.ts | 86 +++++++++++++++---- src/daemon/main.ts | 2 + src/daemon/server.test.ts | 13 ++- src/daemon/server.ts | 18 ++-- src/gateway/service.test.ts | 58 +++++++++++++ src/gateway/worker-link.ts | 59 +++---------- src/http/app.test.ts | 47 ++++++++--- src/http/app.ts | 68 ++++++++------- src/http/errors.ts | 5 +- src/simlock-client/client.ts | 5 +- src/simlock-client/types.ts | 13 +-- 26 files changed, 711 insertions(+), 204 deletions(-) create mode 100644 e2e/single-host-fleet.test.ts create mode 100644 src/contract/worker-view.ts diff --git a/docs/CLI.md b/docs/CLI.md index caa7a6634..0e5f09886 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -63,8 +63,9 @@ command starts it again) to bring the platform up. | 2 | `BAD_FRAME` | malformed request frame sent to the daemon | | 2 | `BAD_REQUEST` | request payload failed validation | | 2 | `UNSUPPORTED_IN_GATEWAY_MODE` | this command acts on one machine (its devices, or its installed components) and the daemon answering is a gateway; run it on the worker, or for `component install` name the workers with `--worker` or `--all-workers` | +| 2 | `UNSUPPORTED_IN_WORKER_MODE` | this command acts on a gateway's workers (`worker drain`, `undrain`, `remove`, or `component install --worker`/`--all-workers`) and the daemon answering is a single host; run it against the gateway, or for `component install` drop the worker flag to install on this host | | 2 | `WORKER_CONNECTED` | `worker remove` on a worker whose uplink is still open; `drain` it and let it disconnect first | -| 2 | `UNKNOWN_REQUEST` | the daemon has no such operation — an operation this daemon's mode does not implement (`worker list` against a worker), or a client newer than the daemon | +| 2 | `UNKNOWN_REQUEST` | the daemon has no such operation — usually a client newer than the daemon | | 2 | `PASSTHROUGH_REFUSED` | a `simctl`/`adb` verb simlock refuses, a caller-supplied `--set`/`-P`, or a bare `adb shell` where there is no terminal to give it | | 2 | `UNKNOWN_PASSTHROUGH_TOOL` | a passthrough tool simlock does not wrap | | 2 | `IDEMPOTENCY_CONFLICT` | a lease request reused an idempotency key its requester already sent for a different device; use a new key | @@ -98,7 +99,7 @@ surfaced by `lease renew`) falls back to exit 1; the structured stderr line still reports the specific code — a renew by a running `simlock lease` is the exception, and exits `14`. -The five gateway-mode codes are placed on existing numbers rather than new +The six fleet codes are placed on existing numbers rather than new ones, and the numbers are fixed by the contract's error table in the PRs that implement them: @@ -115,13 +116,16 @@ implement them: later fleet-wide version. `component install` without a worker flag answers it too; with `--worker` or `--all-workers` it installs on the workers you name. +- `UNSUPPORTED_IN_WORKER_MODE` is the same refusal from the other side, and + exits `2` for the same reason: `worker drain`, `undrain` and `remove`, and + `component install` with a worker flag, act on a gateway's workers, and a + single host has none. It is permanent for that daemon. - `UNKNOWN_WORKER` takes `12`, the number the table already gives to "the thing you named cannot be resolved" (`UNKNOWN_MODEL`, `NO_DRIVER`), because that is what it is: a worker id the gateway has no record of. -- `PASSTHROUGH_REFUSED`, `UNKNOWN_PASSTHROUGH_TOOL`, and `UNKNOWN_REQUEST` - are not new codes at all — they are already in the contract's table at exit - `2`, and they are listed here because `device.exec` and the `worker.*` - operations are new ways to reach them. +- `PASSTHROUGH_REFUSED` and `UNKNOWN_PASSTHROUGH_TOOL` are not new codes at + all — they are already in the contract's table at exit `2`, and they are + listed here because `device.exec` is a new way to reach them. - `EXEC_TIMEOUT` joins `QUEUE_TIMEOUT` on `10`, the number that already means "a deadline elapsed". The two can never be confused, since only `lease` produces one and only `simctl`/`adb` produce the other. What *can* collide @@ -808,10 +812,10 @@ gateway has rebuilt its index. Operator commands for the workers connected to a **gateway**. All four need the `admin` role (see [Admin credential -resolution](#admin-credential-resolution)). A worker has no workers of its -own, so it does not implement these operations at all and answers -`UNKNOWN_REQUEST` — they are not a gateway-mode refusal of something a worker -could otherwise do, they are simply not part of a worker's surface. `list` +resolution](#admin-credential-resolution)). A single host answers as a fleet +of one: `list` shows the host itself, and `drain`, `undrain` and `remove` +answer `UNSUPPORTED_IN_WORKER_MODE` (exit 2), because there is no gateway to +take the host out of rotation or forget it. `list` prints one line per worker, or the views as JSON with `--json`; `drain`, `undrain` and `remove` print JSON on stdout, unconditionally — `--json` is a usage error (exit 2) for those three. @@ -1274,7 +1278,8 @@ appears in `simlock catalog` at once. Run the command again. - **Gateway.** A gateway owns no components. Without a worker flag it answers `UNSUPPORTED_IN_GATEWAY_MODE` (exit 2) and says to name workers; - see below. + see below. On a single host, a worker flag answers + `UNSUPPORTED_IN_WORKER_MODE` (exit 2); leave it out. The command takes no `--json`: its output is already JSON, so the flag is a usage error (exit 2), as is a missing or extra argument or a platform other @@ -1696,8 +1701,12 @@ shows the current file with the immediately preceding one prepended. ## `simlock worker ` The operator's view of a fleet. Every subcommand is an admin -operation **on a gateway**; against a worker they answer `UNKNOWN_REQUEST` -(exit 2), because a worker has no worker registry to answer from. +operation. On a single host, `list` prints one line for that host, with the +same fields a gateway shows for each of its workers: its id is the one it +presents to a gateway, its label is `gateway.label`, and it is always +`connected` and never drained. `drain`, `undrain` and `remove` answer +`UNSUPPORTED_IN_WORKER_MODE` (exit 2) on a single host, because there is no +gateway to take it out of rotation or forget it. - `list [--json]` — one line per worker: its id (the worker's own instance identity — stable across restarts, and not its label or host name), its diff --git a/docs/CLIENT.md b/docs/CLIENT.md index ba3ac4c10..4668a3440 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -350,8 +350,8 @@ const { results } = await admin.installComponentOnWorkers( resolves either way; read the outcomes. - It rejects before any worker is asked with `UNKNOWN_WORKER` for an id the gateway does not know, `WORKER_UNREACHABLE` for a named worker it cannot - ask, `FORBIDDEN` for an agent session, and `UNKNOWN_REQUEST` from a daemon - that is not a gateway. + ask, `FORBIDDEN` for an agent session, and `UNSUPPORTED_IN_WORKER_MODE` + from a single host. Use `installComponent` there instead. - A worker's new component is in the gateway's `getCatalog()` by the time the call resolves, unless the gateway could not read that worker's catalog just then; its next read brings it in. Nothing is retried or kept @@ -669,6 +669,19 @@ neither of which changes a call's shape: the lease is not necessarily gone, you simply cannot reach it right now, and it runs on the worker's TTL either way. +The fleet methods on the admin client work against a single host too, which +answers as a fleet of one: + +- `listWorkers()` returns one entry, the host itself, with the same fields a + gateway gives each of its workers. Its `id` is the id the host presents to + a gateway, its `label` is `gateway.label`, and it is always `connected` and + never `drained`. +- `drainWorker`, `undrainWorker`, `removeWorker` and + `installComponentOnWorkers` reject with `UNSUPPORTED_IN_WORKER_MODE`, whose + `details.operation` names the operation. It mirrors + `UNSUPPORTED_IN_GATEWAY_MODE`: the operation exists, but not on this kind of + daemon. Do not retry it. + ## What this client does not do - It does not start or stop the daemon. `connectSimlock`/`connectSimlockAdmin` diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 9ee8703c3..b8ca6f79d 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -750,7 +750,8 @@ installs the component itself under its own `downloads.policy`, Android license setting, disk check and `downloads.timeoutMs`. A worker set to `downloads.policy: "never"` refuses; the gateway has no download policy of its own and stores or forwards no image. A drained worker is asked like any -other. `workers` on a daemon that is not a gateway is `400 UNKNOWN_REQUEST`. +other. `workers` on a single host is `501 UNSUPPORTED_IN_WORKER_MODE`; leave +it out to install on that host. Before any worker is asked, these are JSON errors: @@ -927,10 +928,12 @@ liveness signal — [`GET /v1/workers`](#worker-routes) is how you look at it. ### Worker routes -Role: `operator` for all four. They exist on a **gateway**; a worker has no -workers of its own and does not implement the underlying operations at all. +Role: `operator` for all four. They exist on a **gateway** and on a single +host. A single host answers as a fleet of one: `GET /v1/workers` lists the +host itself, and the other three answer `501 UNSUPPORTED_IN_WORKER_MODE`. -- `GET /v1/workers` — every worker view the gateway currently holds. +- `GET /v1/workers` — every worker view the gateway currently holds, or the + host's own view on a single host. - `POST /v1/workers/{id}/drain` — stop dispatching new requests to this worker; it keeps the leases it already has. - `DELETE /v1/workers/{id}/drain` — undrain it, putting it back in rotation. @@ -1062,9 +1065,18 @@ first. Unknown ids are the one place remove differs: `200 { "removed": false gateway has already forgotten — the same reading `token.revoke` gives an unknown token id. -On a **worker** daemon none of these routes exist: they are not registered at -all, so they answer `404` like any other unrouted path rather than a -gateway-mode refusal. There is nothing for them to act on. +On a **single host** (a daemon in `worker` mode), `GET /v1/workers` returns +one view, the host itself, with the same fields a gateway shows for each of +its workers. `id` is the id the host presents to a gateway, `label` is its +`gateway.label` (absent when unset), `connection` is `connected`, `drained` +is `false`, and `lastSeenAt` is the time of the request. Every other field +comes from the host's own status, devices, catalog and config. A host that +has joined a gateway still answers about itself: its `drained` is `false` +even when the gateway has drained it, because that flag is the gateway's. + +The drain, undrain and remove routes answer `501 UNSUPPORTED_IN_WORKER_MODE` +on a single host, with `operation` in the body: there is no gateway there to +take the host out of rotation or forget it. ### Operator routes @@ -1116,11 +1128,11 @@ Every failure is the same shape the daemon protocol uses: | 404 | `UNKNOWN_WORKER` (`POST`/`DELETE /v1/workers/{id}/drain` naming a worker the gateway does not know), `UNKNOWN_LEASE_REQUEST` (unknown request id), `UNKNOWN_LEASE` (unknown lease id, expired/released, **or `GET /v1/leases/{id}`/`GET /v1/leases/{id}/events` naming another requester's lease** — see [`GET /v1/leases/{id}`](#get-v1leasesid)) | | 409 | `REQUESTER_ALREADY_LEASED` (body names the existing lease id; fleet-wide on a gateway), `IDEMPOTENCY_CONFLICT` (an `Idempotency-Key` repeated with a different device), `REQUEST_NOT_CANCELLABLE` (body names the lease id if the request had already been granted), `WORKER_CONNECTED` (`DELETE /v1/workers/{id}` while its uplink is open), `COMPONENT_NOT_OWNED`, `COMPONENT_IN_USE` (body carries `devices` and `foreignDevices`), `COMPONENT_BUSY` (the three refusals of `DELETE /v1/components/{platform}/{version}`) | | 422 | `UNKNOWN_MODEL`, `RUNTIME_MISSING`, `NO_DRIVER`, `PASSTHROUGH_REFUSED` (a refused `exec` verb, a caller-supplied `--set`/`-P`, a bare `adb shell`), `UNKNOWN_PASSTHROUGH_TOOL` | -| 501 | `UNSUPPORTED_IN_GATEWAY_MODE` (an operation that acts on one machine, asked of a gateway: `POST /v1/components/install`, `GET /v1/components`, `DELETE /v1/components/{platform}/{version}`) | +| 501 | `UNSUPPORTED_IN_GATEWAY_MODE` (an operation that acts on one machine, asked of a gateway: `POST /v1/components/install`, `GET /v1/components`, `DELETE /v1/components/{platform}/{version}`), `UNSUPPORTED_IN_WORKER_MODE` (an operation on a gateway's workers, asked of a single host: `POST`/`DELETE /v1/workers/{id}/drain`, `DELETE /v1/workers/{id}`, `POST /v1/components/install` with `workers`) | | 503 | `NO_CAPACITY` (only with `noWait: true`; response carries `Retry-After`), `WORKER_UNREACHABLE` (a gateway could not reach the worker holding this lease or request) | | 504 | `EXEC_TIMEOUT` (a `device.exec` command outlived `exec.timeoutMs`), `DOWNLOAD_TIMEOUT` (a runtime download, waiting for another download included, outlived `downloads.timeoutMs`) | -Three notes on these codes. +Four notes on these codes. `WORKER_UNREACHABLE` sits on `503` with `NO_CAPACITY` rather than on `502`, because its `kind` is `transport` and every other `transport`-kind code in @@ -1144,6 +1156,11 @@ and removals stay per-worker permanently rather than pending some later fan-out. A component install through a gateway is a different request, one that names its workers. +`UNSUPPORTED_IN_WORKER_MODE` is the same refusal from the other side: the +operation acts on a gateway's workers, and the daemon is a single host. It +is permanent for that daemon, so do not retry it. Both codes carry +`operation` in the body. + `EXEC_TIMEOUT`'s `504` is documented for completeness rather than for the exec route: `POST /v1/leases/{id}/exec` has already answered `200` and begun streaming by the time a command can outlive `exec.timeoutMs`, so on that diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 9802ab2fd..238660e65 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -513,6 +513,18 @@ and `worker.remove` are the operator's edits to them. A **drained** worker keeps its existing leases and receives no new dispatches — the tool for taking a machine down without killing anyone's device. +A worker answers these operations as a **fleet of one** (ADR 0012). +`worker.list` returns one view, the worker itself: its instance id, its +`gateway.label`, `connected`, never drained, `lastSeenAt` the time of the +call. The reported fields come from its own `status.get`, `list.get`, +`catalog.get` and `config.get`, turned into view fields by +`workerViewFields` in `src/contract/worker-view.ts` — the same pure function +`WorkerLink` builds a gateway's views with, so the two cannot disagree about +a field. `worker.drain`, `worker.undrain`, `worker.remove` and +`worker.install-component` answer `UNSUPPORTED_IN_WORKER_MODE` (`501`, exit +`2`), the mirror of `UNSUPPORTED_IN_GATEWAY_MODE`. The `/v1/workers*` routes +are registered in both modes. + Drain is the one piece of worker state the gateway *decides* rather than observes, and it is why the **worker registry** and the worker *view* are two different things. The view is the observation: rebuilt on every connect, @@ -1601,9 +1613,10 @@ last count are not seen; see KNOWN-PITFALLS.md. #### Through a gateway -`worker.install-component` (ADR 0010 §7) is gateway-only: it is in -`GATEWAY_ONLY_OPERATIONS`, so a worker answers `UNKNOWN_REQUEST`, and no -worker ever receives it, which is why it moves no protocol version. Its input +`worker.install-component` (ADR 0010 §7) only installs through a gateway: a +worker refuses it with `UNSUPPORTED_IN_WORKER_MODE` (ADR 0012 §2), and no +worker ever receives it over an uplink, which is why it moves no protocol +version. Its input is `{ platform, version, workers }`; `version` runs `component.install`'s own schema and `workers` is `"all"` or 1 to 64 distinct ids. One function, `relayComponentInstall` in `src/gateway/component-relay.ts`, does the diff --git a/e2e/contract-surface.test.ts b/e2e/contract-surface.test.ts index 0d0f448fc..e51a0dfc1 100644 --- a/e2e/contract-surface.test.ts +++ b/e2e/contract-surface.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { GATEWAY_ONLY_OPERATIONS, OPERATIONS, type OperationName } from "../src/contract/index.js"; +import { OPERATIONS, type OperationName } from "../src/contract/index.js"; import { NodeIpcTransport } from "../src/ports/index.js"; import { SimlockWire, WireCallError } from "../src/simlock-client/wire.js"; import { freeLoopbackPort, withDaemon } from "./helpers/index.js"; @@ -92,20 +92,11 @@ describe("contract surface", () => { expect(probedOperations()).toContain("component.install"); // Asserted as one object rather than per operation so a failure names every unreachable - // operation at once, instead of stopping at the first. The gateway-only operations - // (ADR 0005 §23) are the one deliberate exception: a worker has no worker registry, so - // `UNKNOWN_REQUEST` -- "this daemon does not implement that operation" -- is the honest - // answer rather than a routing mistake. The gateway's own sweep below is what proves they - // are reachable somewhere. + // operation at once, instead of stopping at the first. The `worker.*` operations are + // included: a worker answers them as a fleet of one (ADR 0012), so they parse their input + // here too, even the ones it then refuses with `UNSUPPORTED_IN_WORKER_MODE`. expect(await sweep(env)).toEqual( - Object.fromEntries( - probedOperations().map((name) => [ - name, - (GATEWAY_ONLY_OPERATIONS as readonly string[]).includes(name) - ? "UNKNOWN_REQUEST" - : "BAD_REQUEST", - ]), - ), + Object.fromEntries(probedOperations().map((name) => [name, "BAD_REQUEST"])), ); }); diff --git a/e2e/single-host-fleet.test.ts b/e2e/single-host-fleet.test.ts new file mode 100644 index 000000000..615c84bc6 --- /dev/null +++ b/e2e/single-host-fleet.test.ts @@ -0,0 +1,152 @@ +import { readFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { freeLoopbackPort, waitFor, withDaemon, type TestEnv } from "./helpers/index.js"; + +/** + * A worker answers the fleet operations as a fleet of one: `worker list` and `GET /v1/workers` + * show the host itself, and the operations that act on a gateway's workers refuse with + * `UNSUPPORTED_IN_WORKER_MODE` rather than `UNKNOWN_REQUEST` or `404`. + */ + +/** The id this host presents to a gateway, as its own `instance.json` stores it. */ +async function instanceId(env: TestEnv): Promise { + const stored = JSON.parse(await readFile(join(env.home, "instance.json"), "utf8")) as { + instanceId: string; + }; + return stored.instanceId; +} + +interface HttpHost { + readonly env: TestEnv; + readonly baseUrl: string; + readonly operatorAuth: { readonly authorization: string }; + readonly agentAuth: { readonly authorization: string }; +} + +/** A single host with HTTP on, an operator token and an agent token, once it answers. */ +async function httpHost(): Promise { + const port = await freeLoopbackPort(); + const env = await withDaemon({ + configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, + }); + const baseUrl = `http://127.0.0.1:${port}`; + const bearer = async (role: string) => { + const minted = await env.cli(["token", "create", "--role", role]); + expect(minted.code).toBe(0); + return { authorization: `Bearer ${(minted.json as { secret: string }).secret}` }; + }; + const operatorAuth = await bearer("operator"); + const agentAuth = await bearer("agent"); + await waitFor( + async () => { + try { + return (await fetch(`${baseUrl}/v1/healthz`)).ok; + } catch { + return false; + } + }, + { label: "HTTP listener accepting connections" }, + ); + return { agentAuth, baseUrl, env, operatorAuth }; +} + +describe("a single host as a fleet of one", () => { + it("simlock worker list against a worker prints that worker", async () => { + const env = await withDaemon({ configOverrides: { gateway: { label: "mac-mini-1" } } }); + const id = await instanceId(env); + + const text = await env.cli(["worker", "list"]); + const json = await env.cli(["worker", "list", "--json"]); + + expect(text.code).toBe(0); + const lines = text.stdout.trim().split("\n"); + expect(lines).toHaveLength(1); + expect(lines[0]).toMatch(new RegExp(`^${id} \\(mac-mini-1\\): connected -- `)); + expect(json.code).toBe(0); + expect(json.json).toMatchObject({ + workers: [{ connection: "connected", drained: false, id, label: "mac-mini-1" }], + }); + }); + + it("simlock worker drain against a worker exits 2 with UNSUPPORTED_IN_WORKER_MODE", async () => { + const env = await withDaemon(); + const id = await instanceId(env); + + const result = await env.cli(["worker", "drain", id]); + + expect(result.code).toBe(2); + expect(result.stdout).toBe(""); + expect(result.error?.code).toBe("UNSUPPORTED_IN_WORKER_MODE"); + }); + + it("GET /v1/workers on a worker answers 200 with one worker for an operator token", async () => { + const host = await httpHost(); + const id = await instanceId(host.env); + const status = (await host.env.cli(["status", "--json"])).json as { + capacity: unknown; + host: unknown; + }; + + const response = await fetch(`${host.baseUrl}/v1/workers`, { headers: host.operatorAuth }); + + expect(response.status).toBe(200); + const body = (await response.json()) as { workers: Record[] }; + expect(body.workers).toHaveLength(1); + expect(body.workers[0]).toMatchObject({ + capacity: status.capacity, + connection: "connected", + drained: false, + host: status.host, + id, + }); + }); + + it("GET /v1/workers on a worker answers 403 for an agent token", async () => { + const host = await httpHost(); + + const response = await fetch(`${host.baseUrl}/v1/workers`, { headers: host.agentAuth }); + + expect(response.status).toBe(403); + expect(((await response.json()) as { error: { code: string } }).error.code).toBe("FORBIDDEN"); + }); + + it("POST /v1/workers/{id}/drain on a worker answers 501 UNSUPPORTED_IN_WORKER_MODE", async () => { + const host = await httpHost(); + const id = await instanceId(host.env); + + const response = await fetch(`${host.baseUrl}/v1/workers/${id}/drain`, { + headers: host.operatorAuth, + method: "POST", + }); + + expect(response.status).toBe(501); + expect(await response.json()).toEqual({ + error: { + code: "UNSUPPORTED_IN_WORKER_MODE", + message: expect.any(String), + operation: "worker.drain", + }, + }); + }); + + it("POST /v1/components/install with workers on a worker answers 501", async () => { + const host = await httpHost(); + await host.env.driverLog.clear(); + + const response = await fetch(`${host.baseUrl}/v1/components/install`, { + body: JSON.stringify({ platform: "ios", version: "26.0", workers: "all" }), + headers: { ...host.operatorAuth, "content-type": "application/json" }, + method: "POST", + }); + + expect(response.status).toBe(501); + expect(await response.json()).toMatchObject({ + error: { code: "UNSUPPORTED_IN_WORKER_MODE", operation: "worker.install-component" }, + }); + const calls = await host.env.driverLog.calls(); + expect(calls.some((call) => call.operation === "installComponent")).toBe(false); + }); +}); diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index cf11fe139..f71cc48dc 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -4664,6 +4664,7 @@ async function startTestDaemon(): Promise<{ socketPath: string; daemon: DaemonSe const daemon = new DaemonServer({ capacity: engine, catalog: engine, + instanceId: "instance-test", clock, components: wiring.components, config, @@ -4788,6 +4789,7 @@ async function startInMemoryDaemon(options: { adminSecret, capacity: engine, catalog: engine, + instanceId: "instance-test", clock, components: wiring.components, config, diff --git a/src/cli/index.ts b/src/cli/index.ts index 6dd4215f7..bb3691e82 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -56,7 +56,8 @@ Commands: lease, release, status, list, catalog, cleanup, doctor, nuke, events, daemon, config, token worker - Inspect and manage the workers of a gateway + Inspect and manage the workers of a gateway; on a + single host, list shows the host itself component install [--worker ... | --all-workers] Install a simulator runtime or system image component list [--platform ] @@ -1798,10 +1799,11 @@ function parseTokenRole(value: unknown): "agent" | "operator" | "worker" { } /** - * ADR 0005 §8/§23: the operator's view of a fleet. Every subcommand is one admin operation on - * the gateway, so this function is argument parsing and rendering and nothing else -- a worker - * daemon answers `UNKNOWN_REQUEST` for all four, which surfaces as the daemon's own error line - * rather than a mode check the CLI would have to keep in step. + * ADR 0005 §8/§23: the operator's view of a fleet. Every subcommand is one admin operation, so + * this function is argument parsing and rendering and nothing else. A worker daemon answers as a + * fleet of one (ADR 0012): `list` shows the host itself, and `drain`, `undrain` and `remove` + * answer `UNSUPPORTED_IN_WORKER_MODE`, which surfaces as the daemon's own error line rather than + * a mode check the CLI would have to keep in step. */ async function runWorker( argv: readonly string[], diff --git a/src/contract/errors.ts b/src/contract/errors.ts index 05f2b0d58..4dffdb916 100644 --- a/src/contract/errors.ts +++ b/src/contract/errors.ts @@ -120,6 +120,13 @@ export interface ErrorDetailsMap { * different instruction from "that is not an operation". */ UNSUPPORTED_IN_GATEWAY_MODE: { readonly operation: string }; + /** + * ADR 0012 §2: the mirror of `UNSUPPORTED_IN_GATEWAY_MODE`. The operation exists, this daemon + * is a worker, and the operation only applies to a gateway's workers: `worker.drain`, + * `worker.undrain`, `worker.remove` and `worker.install-component`. Not `UNKNOWN_REQUEST`: the + * operation is known, it just does not apply to a single host. + */ + UNSUPPORTED_IN_WORKER_MODE: { readonly operation: string }; /** ADR 0005 §8: `worker.remove` on a worker whose uplink is currently open. Carries the id * so a caller can say which one without re-parsing the message. */ WORKER_CONNECTED: { readonly workerId: string }; @@ -190,6 +197,7 @@ const CODES_WITH_DECLARED_DETAILS_BY_CODE: Record PASSTHROUGH_REFUSED: true, UNKNOWN_PASSTHROUGH_TOOL: true, UNSUPPORTED_IN_GATEWAY_MODE: true, + UNSUPPORTED_IN_WORKER_MODE: true, WORKER_CONNECTED: true, UNKNOWN_WORKER: true, WORKER_UNREACHABLE: true, @@ -349,6 +357,14 @@ export const ERROR_TABLE: { readonly [Code in SimlockErrorCode]: ErrorTableEntry cliExitCode: 2, httpStatus: 501, }, + // The same 501 and exit 2 as `UNSUPPORTED_IN_GATEWAY_MODE`, for the same reason: a + // well-formed request this daemon's mode does not implement. + UNSUPPORTED_IN_WORKER_MODE: { + code: "UNSUPPORTED_IN_WORKER_MODE", + kind: "domain", + cliExitCode: 2, + httpStatus: 501, + }, // 409, like every other "the resource is not in a state that allows this": the worker is // there, connected, and removing it is a contradiction rather than a missing thing. Exit 2 // for the same reason `UNSUPPORTED_IN_GATEWAY_MODE` takes it -- the caller asked for diff --git a/src/contract/index.ts b/src/contract/index.ts index 57eaafd1c..f8cf4b53e 100644 --- a/src/contract/index.ts +++ b/src/contract/index.ts @@ -4,3 +4,4 @@ export * from "./protocol.js"; export * from "./pushes.js"; export * from "./roles.js"; export * from "./schemas.js"; +export * from "./worker-view.js"; diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 8beca71d2..d0a057948 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -626,11 +626,10 @@ export const tokenRevoke = defineOperation({ // ---- worker.list / worker.drain / worker.undrain / worker.remove (ADR 0005 §8, §23) --------- // -// Gateway-only operations: they act on the gateway's worker registry, which a worker daemon -// does not have. A worker's `Dispatcher` deliberately declares no handler for them at all -// (see `src/daemon/dispatcher.ts`'s `#handlers` type), so asking a worker for one answers -// `UNKNOWN_REQUEST` -- "this daemon does not implement that operation" -- rather than a -// fabricated empty fleet. The gateway's own dispatcher implements all four. +// They act on the gateway's worker registry. A worker answers them as a fleet of one (ADR +// 0012): `worker.list` returns one view, the worker itself, and `worker.drain`, +// `worker.undrain` and `worker.remove` answer `UNSUPPORTED_IN_WORKER_MODE`, since a single host +// has no gateway to drain it or forget it. // // `admin` throughout: these are operator tools (drain a machine for maintenance, forget a // machine that is gone), and ADR 0003 §3's matrix puts every daemon-wide administrative @@ -807,7 +806,7 @@ const workerInstallResultSchema = z.object({ * gateway. The gateway asks each target at the same time with `component.install`, and each * worker answers for itself under its own `downloads.policy`. One result per worker, in * ascending worker id. Progress arrives as `component-progress` pushes carrying `workerId`. - * Gateway-only: a worker answers `UNKNOWN_REQUEST`. + * A worker answers `UNSUPPORTED_IN_WORKER_MODE` (ADR 0012 §2). */ // fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. export const workerInstallComponent = defineOperation({ @@ -886,20 +885,4 @@ export const OPERATIONS = { "component.remove": componentRemove, } as const; -/** - * The operations only a gateway implements (ADR 0005 §23). Named as a set here, rather than - * spelled out again in each dispatcher, so "which operations are gateway-only" has exactly one - * answer: the worker's dispatcher excludes these from its handler table, and the gateway's - * implements them. - */ -export const GATEWAY_ONLY_OPERATIONS = [ - "worker.list", - "worker.drain", - "worker.undrain", - "worker.remove", - "worker.install-component", -] as const satisfies readonly OperationName[]; - -export type GatewayOnlyOperationName = (typeof GATEWAY_ONLY_OPERATIONS)[number]; - export type OperationName = keyof typeof OPERATIONS; diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index 9f519df2f..e90e184b7 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -813,6 +813,10 @@ export const INSTALL_LIST_LIMIT = MAX_LISTED_INSTALLS; * anything, and a `disconnected` view keeps whatever the last successful refresh saw. They are * absent rather than zeroed on purpose -- "no capacity reported" and "no capacity free" are * different facts, and a console that dims one must not read the other as a full machine. + * + * A worker answers `worker.list` with one of these about itself (ADR 0012 §1): `connected`, + * never drained, `lastSeenAt` the time of the call, and every reported field filled from its + * own reads by `workerViewFields` (`worker-view.ts`), the same builder a gateway uses. */ export const workerViewSchema = z.object({ /** The worker's own instance identity (`instance.json`), ADR 0005 §3a: stable across diff --git a/src/contract/worker-view.ts b/src/contract/worker-view.ts new file mode 100644 index 000000000..fb6258d37 --- /dev/null +++ b/src/contract/worker-view.ts @@ -0,0 +1,64 @@ +/** + * The one place a worker's own reads become the fields of its worker view (ADR 0012 §1). + * + * A gateway reads `status.get`, `list.get` for devices, `catalog.get` and `config.get` over a + * worker's uplink; a worker answering `worker.list` about itself reads the same four from its + * own dispatcher. Both call this function, so the two views cannot disagree about a field. Each + * caller adds what only it knows: `id`, `label`, `connection`, `drained`, `lastSeenAt` and + * `version`. + * + * Pure: no I/O, no clock, nothing outside the contract module. + */ +import { z } from "zod"; + +import type { OPERATIONS } from "./operations.js"; +import { statusDeviceSchema, type workerViewSchema } from "./schemas.js"; + +type Output = z.infer<(typeof OPERATIONS)[Name]["output"]>; +type WorkerView = z.infer; + +/** The answers a view is built from. `catalog` and `config` are optional because a gateway's + * per-event refresh re-reads only status and devices; a field left out stays as it was. */ +export interface WorkerReads { + readonly status: Output<"status.get">; + readonly devices: Output<"list.get">; + readonly catalog?: Output<"catalog.get">; + readonly config?: Output<"config.get">; +} + +/** The view fields the reads fill. `catalog`, `downloads` and `lease` are present only when the + * reads that carry them were made. */ +export type WorkerViewReport = Pick< + WorkerView, + "capacity" | "devices" | "health" | "host" | "installs" | "leases" | "queueDepth" +> & + Partial>; + +/** The device shape a view carries. `list.get` answers an admin with full `DeviceRecord`s; + * narrowing them here keeps `driverData` -- an opaque, driver-defined blob -- out of every + * view, on a gateway and on a worker alike. */ +const viewDevicesSchema = z.array(statusDeviceSchema); + +export function workerViewFields(reads: WorkerReads): WorkerViewReport { + const { catalog, config, status } = reads; + return { + capacity: status.capacity, + health: status.daemon.health, + host: status.host, + // ADR 0010 §7: copied as the worker lists them, already bounded by the contract's parse + // (safety rule 10). A worker too old to list installs reports none. + installs: status.installs ?? [], + leases: status.leases, + queueDepth: status.queueDepth, + devices: viewDevicesSchema.parse(reads.devices), + ...(catalog === undefined ? {} : { catalog: catalog.platforms }), + ...(config === undefined + ? {} + : { + // ADR 0010 §7: the worker's own install budget, read with its policy. + downloads: { policy: config.downloads.policy, timeoutMs: config.downloads.timeoutMs }, + // ADR 0005 §15: a gateway compares this against its own `lease.maxTtlMs`. + lease: { maxTtlMs: config.lease.maxTtlMs }, + }), + }; +} diff --git a/src/daemon/dispatch.ts b/src/daemon/dispatch.ts index 8e4c45f0a..072442765 100644 --- a/src/daemon/dispatch.ts +++ b/src/daemon/dispatch.ts @@ -163,8 +163,7 @@ export type ErasedHandler = (input: never, session: DispatchSession) => Promise< export interface DispatchPipeline { /** Handler per operation. An operation with no entry answers `UNKNOWN_REQUEST` -- which is - * how a worker answers `worker.*` and how `daemon.stop` (intercepted by the transport) never - * reaches a handler. */ + * how `daemon.stop` (intercepted by the transport) never reaches a handler. */ readonly handlers: Partial>; /** The two live lookups an `authorize` hook needs (ADR 0003 §1's `ownsLease`). A dispatcher * with no lease state of its own may leave this out: an absent context answers `undefined` diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 088beae4e..b758d9d88 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -19,7 +19,7 @@ import { SerializedDecision, RuntimeMissingError, } from "../core/index.js"; -import { OPERATIONS } from "../contract/index.js"; +import { OPERATIONS, statusDeviceSchema } from "../contract/index.js"; import type { FakeDriverOptions } from "../core/fake-driver.js"; import type { CatalogReader, PassthroughResolver } from "../core/lease-ports.js"; import { @@ -104,6 +104,11 @@ function fakePassthroughOptions( }; } +/** `config` with `gateway.label` set, or unchanged when there is no label. */ +function withGatewayLabel(config: Config, label: string | undefined): Config { + return label === undefined ? config : { ...config, gateway: { ...config.gateway, label } }; +} + async function buildDispatcher( overrides: { readonly downloadsPolicy?: Config["downloads"]["policy"]; @@ -153,6 +158,8 @@ async function buildDispatcher( ComponentInstaller, "claimProvision" | "inProgress" | "install" | "list" | "remove" >; + /** `gateway.label` in this daemon's config; unset by default. */ + readonly gatewayLabel?: string; } = {}, ) { const clock = overrides.clock ?? new FakeClock(1_000); @@ -172,11 +179,14 @@ async function buildDispatcher( ...overrides.driverOptions, ...fakePassthroughOptions(overrides.passthroughTool, overrides.passthroughContextSink), }); - const config = testConfig( - overrides.downloadsPolicy, - overrides.lease ?? {}, - overrides.exec ?? {}, - overrides.capacity, + const config = withGatewayLabel( + testConfig( + overrides.downloadsPolicy, + overrides.lease ?? {}, + overrides.exec ?? {}, + overrides.capacity, + ), + overrides.gatewayLabel, ); const wiring = testComponentWiring({ clock: clock, @@ -235,6 +245,7 @@ async function buildDispatcher( eventHistory: resolveEventHistoryOverride(eventBus, filesystem, overrides.eventHistory), health: () => "running", hostFacts: overrides.hostFacts ?? (() => ({ ...HOST_SYSTEM, tools: [] })), + instanceId: "instance-1", leases: engine, ...(overrides.includeNuke === true ? { nuke: new Nuke({ executor: engine, registry }) } : {}), passthrough: resolvePassthroughOverride(engine, overrides.passthroughOverride), @@ -244,6 +255,7 @@ async function buildDispatcher( reaper, registry, tokens, + version: "1.2.3", }); return { clock, @@ -351,6 +363,117 @@ describe("Dispatcher: parsing", () => { }); }); +/** + * ADR 0012: a worker answers the fleet operations as a fleet of one. `worker.list` is this host's + * own view; the operations that act on a gateway's workers refuse with their own code. + */ +describe("Dispatcher: the fleet operations on a worker", () => { + const admin = session({ principal: "operator", role: "admin" }); + + it("worker.list on a worker returns one view whose id is the instance id", async () => { + const { clock, dispatcher } = await buildDispatcher(); + clock.advance(500); + + const { workers } = await dispatcher.dispatch("worker.list", {}, admin); + + expect(workers).toHaveLength(1); + expect(workers[0]).toMatchObject({ + connection: "connected", + drained: false, + id: "instance-1", + lastSeenAt: 1_500, + version: "1.2.3", + }); + expect(workers[0]).not.toHaveProperty("protocol"); + }); + + it("worker.list on a worker carries gateway.label as label, and no label when it is unset", async () => { + const labelled = await buildDispatcher({ gatewayLabel: "mac-mini-1" }); + const unlabelled = await buildDispatcher(); + + const withLabel = await labelled.dispatcher.dispatch("worker.list", {}, admin); + const withoutLabel = await unlabelled.dispatcher.dispatch("worker.list", {}, admin); + + expect(withLabel.workers[0]?.label).toBe("mac-mini-1"); + expect(withoutLabel.workers[0]).not.toHaveProperty("label"); + }); + + it("worker.list on a worker reports the same capacity, devices, leases, catalog, host and installs as its own reads", async () => { + const { components, dispatcher, driver } = await buildDispatcher({ + driverOptions: { knownModels: ["iPhone 17 Pro"] }, + hostFacts: () => ({ + ...HOST_SYSTEM, + tools: [{ build: "16F6", name: "xcode", platform: "ios", version: "16.4" }], + }), + }); + // One lease on one device, and one install held mid-download: every field has something + // in it, so a field the view dropped or took from the wrong read cannot pass as empty. + await dispatcher.dispatch( + "lease.request", + { model: "iPhone 17 Pro", platform: "ios" }, + session(), + ); + driver.holdInstalls(); + void components.install({ component: "27.0", platform: "ios" }); + await flushPromises(); + + const [{ workers }, status, devices, catalog, config] = await Promise.all([ + dispatcher.dispatch("worker.list", {}, admin), + dispatcher.dispatch("status.get", {}, admin), + dispatcher.dispatch("list.get", { kind: "devices" }, admin), + dispatcher.dispatch("catalog.get", {}, admin), + dispatcher.dispatch("config.get", {}, admin), + ]); + + expect(status.leases).toHaveLength(1); + expect(status.installs).toHaveLength(1); + expect(status.host.tools).toHaveLength(1); + expect(catalog.platforms[0]?.models).toEqual(["iPhone 17 Pro"]); + expect(workers[0]).toMatchObject({ + capacity: status.capacity, + catalog: catalog.platforms, + devices: statusDeviceSchema.array().parse(devices), + downloads: { policy: config.downloads.policy, timeoutMs: config.downloads.timeoutMs }, + health: status.daemon.health, + host: status.host, + installs: status.installs, + lease: { maxTtlMs: config.lease.maxTtlMs }, + leases: status.leases, + queueDepth: status.queueDepth, + }); + expect(workers[0]?.devices).toHaveLength(1); + expect(workers[0]?.devices[0]).not.toHaveProperty("driverData"); + }); + + it.each(["worker.drain", "worker.undrain", "worker.remove"] as const)( + "worker.drain, worker.undrain, worker.remove and worker.install-component on a worker fail with UNSUPPORTED_IN_WORKER_MODE: %s", + async (operation) => { + const { dispatcher } = await buildDispatcher(); + + await expect( + dispatcher.dispatch(operation, { workerId: "instance-1" }, admin), + ).rejects.toMatchObject({ code: "UNSUPPORTED_IN_WORKER_MODE", details: { operation } }); + }, + ); + + it("worker.drain, worker.undrain, worker.remove and worker.install-component on a worker fail with UNSUPPORTED_IN_WORKER_MODE: worker.install-component, installing nothing", async () => { + const { components, dispatcher } = await buildDispatcher(); + const install = vi.spyOn(components, "install"); + + await expect( + dispatcher.dispatch( + "worker.install-component", + { platform: "ios", version: "27.0", workers: "all" }, + admin, + ), + ).rejects.toMatchObject({ + code: "UNSUPPORTED_IN_WORKER_MODE", + details: { operation: "worker.install-component" }, + }); + expect(install).not.toHaveBeenCalled(); + }); +}); + describe("Dispatcher: token.create | token.list | token.revoke", () => { it("creates a token, lists it, then revokes it -- admin only", async () => { const { dispatcher, tokens } = await buildDispatcher(); diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 494f84092..adeef0534 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -38,8 +38,8 @@ import { OPERATIONS, requestedDevice, type ComponentProgress, - type GatewayOnlyOperationName, type OperationName, + workerViewFields, } from "../contract/index.js"; import type { TokenStore } from "../http/token-store.js"; import { @@ -143,6 +143,11 @@ export interface DispatcherOptions { * since the session's `role` is itself resolved from `hello`'s payload (see `session.ts`). */ readonly awaitReady: () => Promise; + /** This daemon's instance id (`instance.json`), the id it presents to a gateway. `worker.list` + * answers with it as the one worker's id (ADR 0012 §1). */ + readonly instanceId: string; + /** This daemon's own version, the one its `hello` reply carries; `worker.list`'s `version`. */ + readonly version: string; } /** @@ -162,9 +167,8 @@ type Handler = ( ) => Promise | unknown; /** Every operation this (worker-mode) dispatcher implements: the contract's set minus - * `daemon.stop` (intercepted by `DaemonServer` itself, ADR 0003 §6) and minus the - * gateway-only ones (ADR 0005 §23). */ -type WorkerOperationName = Exclude; + * `daemon.stop` (intercepted by `DaemonServer` itself, ADR 0003 §6). */ +type WorkerOperationName = Exclude; /** * The transport-independent dispatcher (ADR 0003 §2). One `dispatch()` call does, in order: @@ -172,8 +176,7 @@ type WorkerOperationName = Exclude; @@ -226,6 +226,14 @@ export class Dispatcher { "component.install": this.#componentInstall, "component.list": this.#componentList, "component.remove": this.#componentRemove, + "worker.list": this.#workerList, + "worker.drain": unsupportedOnWorker("worker.drain"), + "worker.undrain": unsupportedOnWorker("worker.undrain"), + "worker.remove": unsupportedOnWorker("worker.remove"), + "worker.install-component": unsupportedOnWorker( + "worker.install-component", + "worker.install-component installs on a gateway's workers, and this daemon is not a gateway; install on this host without naming workers", + ), // "daemon.stop" deliberately absent -- see the class comment; `DaemonServer` never calls // `dispatch()` for a frame type this map has no entry for. }; @@ -601,6 +609,40 @@ export class Dispatcher { #configGet: Handler<"config.get"> = () => this.options.config; + /** + * ADR 0012 §1: this host as its own fleet of one. The fields a gateway reads over the uplink + * come from the same four reads, made here against this dispatcher's own handlers and parsed + * through their output schemas, so they are what a gateway would have received; the + * contract's one builder turns them into a view. `drained` is always `false`: a gateway that + * drained this worker holds that flag, not this host. + */ + #workerList: Handler<"worker.list"> = async (_input, session) => { + const [status, devices, catalog] = await Promise.all([ + this.#statusGet({}, session), + this.#listGet({ kind: "devices" }, session), + this.#catalogGet({}, session), + ]); + const label = this.options.config.gateway.label; + return { + workers: [ + { + ...workerViewFields({ + catalog: OPERATIONS["catalog.get"].output.parse(catalog), + config: OPERATIONS["config.get"].output.parse(this.#configGet({}, session)), + devices: OPERATIONS["list.get"].output.parse(devices), + status: OPERATIONS["status.get"].output.parse(status), + }), + connection: "connected", + drained: false, + id: this.options.instanceId, + lastSeenAt: this.options.clock.now(), + version: this.options.version, + ...(label === undefined ? {} : { label }), + }, + ], + }; + }; + /** * ADR 0010 §4 and §6: an operator's explicit install. The command itself is the consent, so the * one consent function is asked with `true`; only `downloads.policy: "never"` refuses it, and it @@ -724,3 +766,13 @@ function killQuietly(handle: StreamingProcessHandle, signal: NodeJS.Signals): vo // Already gone. } } + +/** ADR 0012 §2: an operation that acts on a gateway's workers, asked of a worker. */ +function unsupportedOnWorker( + operation: OperationName, + message = `${operation} acts on a gateway's workers, and this daemon is not a gateway`, +): ErasedHandler { + return () => { + throw new DispatchError("UNSUPPORTED_IN_WORKER_MODE", message, { operation }); + }; +} diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 2e9846b66..81a8fbd9c 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -369,6 +369,8 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise fitHostFacts(hostFacts.current()), + // ADR 0012 §1: `worker.list` answers with this host under the id it presents to a gateway. + instanceId, host: new DaemonEndpointHost({ connector: ipc, endpoint: socketPath, diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 08069bbc9..d6ace938e 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -1648,8 +1648,8 @@ describe("DaemonServer lease liveness (ADR 0004)", () => { await client.close(); }); - it("answers worker.install-component with UNKNOWN_REQUEST: a worker has no workers to install on", async () => { - const harness = await createHarness(); + it("answers worker.install-component with UNSUPPORTED_IN_WORKER_MODE: a worker has no workers to install on", async () => { + const harness = await createHarness({ resolveRole: { resolve: () => "admin" } }); const client = await createClient(harness.socketPath); await hello(client); @@ -1659,7 +1659,13 @@ describe("DaemonServer lease liveness (ADR 0004)", () => { version: "35", workers: "all", }), - ).resolves.toMatchObject({ error: { code: "UNKNOWN_REQUEST" }, ok: false }); + ).resolves.toMatchObject({ + error: { + code: "UNSUPPORTED_IN_WORKER_MODE", + details: { operation: "worker.install-component" }, + }, + ok: false, + }); await client.close(); }); @@ -2953,6 +2959,7 @@ async function createHarness( ...(options.adminSecret === undefined ? {} : { adminSecret: options.adminSecret }), capacity: engine, catalog: engine, + instanceId: "instance-test", clock, components: wiring.components, config, diff --git a/src/daemon/server.ts b/src/daemon/server.ts index a8428d487..5e80d32f6 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -149,6 +149,8 @@ export interface DaemonServerEngineOptions { readonly leases: LeaseCommands; /** `status.get`'s host block (ADR 0008 §5); see `DispatcherOptions.hostFacts`. */ readonly hostFacts: () => HostFacts; + /** This daemon's instance id; `worker.list` answers with it (see `DispatcherOptions`). */ + readonly instanceId: string; readonly queue: QueueControl; readonly reaper: CleanupReaper; readonly healthMonitor?: LeaseHealthMonitor; @@ -297,6 +299,7 @@ function buildDispatcher( eventHistory: options.eventHistory, health: hooks.health, hostFacts: options.hostFacts, + instanceId: options.instanceId, leases: options.leases, ...(options.logger === undefined ? {} : { logger: options.logger }), ...(options.nuke === undefined ? {} : { nuke: options.nuke }), @@ -307,6 +310,7 @@ function buildDispatcher( reaper: options.reaper, registry: options.registry, ...(options.tokens === undefined ? {} : { tokens: options.tokens }), + version: options.version, }); } @@ -805,7 +809,8 @@ export class DaemonServer { }); } // ADR 0003 §7's typed `details` travel with the code when the thrown error carries any - // (today: the gateway's `WORKER_CONNECTED`/`UNKNOWN_WORKER`/`UNSUPPORTED_IN_GATEWAY_MODE`), + // (today: the gateway's `WORKER_CONNECTED`/`UNKNOWN_WORKER`/`UNSUPPORTED_IN_GATEWAY_MODE`, + // and a worker's `UNSUPPORTED_IN_WORKER_MODE`), // so a socket client can narrow on them exactly as an HTTP one does. await this.#respondError( connection.socket, @@ -1117,10 +1122,9 @@ export class DaemonServer { case "token.revoke": return this.#dispatcher.dispatch("token.revoke", frame.payload, this.#session(connection)); // ADR 0005 §23. Listed here like any other operation: this switch is the socket's whole - // surface, and whether a *given* daemon implements one is the dispatcher's answer, not - // the transport's -- a worker's dispatcher has no handler for these and says - // `UNKNOWN_REQUEST` itself, which is the same code this switch's default produces but - // for the honest reason. + // surface, and what a *given* daemon answers is the dispatcher's business, not the + // transport's -- a worker's dispatcher answers `worker.list` about itself and refuses the + // rest with `UNSUPPORTED_IN_WORKER_MODE` (ADR 0012). case "worker.list": return this.#dispatcher.dispatch( "worker.list", @@ -1313,8 +1317,8 @@ export class DaemonServer { * reconnects repeats the request to join it again. * * A gateway's `worker.install-component` takes the same path: its progress names the worker - * it came from, and the push carries that `workerId` (ADR 0010 §7). A worker's dispatcher has - * no handler for it and answers `UNKNOWN_REQUEST`. + * it came from, and the push carries that `workerId` (ADR 0010 §7). A worker's dispatcher + * refuses it with `UNSUPPORTED_IN_WORKER_MODE` (ADR 0012 §2). */ #installComponent( connection: Connection, diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts index 4558f77d3..227643e1a 100644 --- a/src/gateway/service.test.ts +++ b/src/gateway/service.test.ts @@ -164,6 +164,64 @@ describe("GatewayService", () => { await harness.service.stop(); }); + it("the worker view builder gives a gateway the same view it built before this change", async () => { + // Every field a refresh fills, set to a value that is not a default, and the whole view + // compared as one literal: the expected value is what the gateway built before the view + // builder moved into the contract, so any field the move dropped, renamed or reshaped + // fails here by name. + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient("admin", "9.8.7"); + const install = { + component: "26.0", + platform: "ios" as const, + since: 500, + state: "downloading" as const, + waiters: 2, + }; + worker.status = statusFixture({ + daemon: { health: "starting", mode: "worker" }, + host: hostFixture({ arch: "x64" }), + installs: [install], + leases: [leaseFixture("lease_1", "dev_1")], + queueDepth: 3, + }); + worker.devices = [ + { ...deviceFixture("dev_1", "leased"), createdAt: 1, driverData: { private: true } }, + ]; + worker.catalog = catalogFixture([ + { models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }, + ]); + worker.downloadPolicy = "always"; + worker.downloadTimeoutMs = 45 * 60_000; + worker.leaseMaxTtlMs = 6 * 60 * 60_000; + + await harness.join("wrk_1", worker, "mac-mini-1"); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.lease).toBeDefined()); + + expect(harness.service.workers.view("wrk_1")).toEqual({ + capacity: statusFixture().capacity, + catalog: catalogFixture([{ models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }]) + .platforms, + connection: "connected", + devices: [deviceFixture("dev_1", "leased")], + downloads: { policy: "always", timeoutMs: 45 * 60_000 }, + drained: false, + health: "starting", + host: hostFixture({ arch: "x64" }), + id: "wrk_1", + installs: [install], + label: "mac-mini-1", + lastSeenAt: 1_000, + lease: { maxTtlMs: 6 * 60 * 60_000 }, + leases: [leaseFixture("lease_1", "dev_1")], + queueDepth: 3, + version: "9.8.7", + }); + + await harness.service.stop(); + }); + it("narrows a worker's device records: no driver-private data crosses the fleet", async () => { const harness = fleet(); await harness.service.start(); diff --git a/src/gateway/worker-link.ts b/src/gateway/worker-link.ts index 4330d8062..0e1084b95 100644 --- a/src/gateway/worker-link.ts +++ b/src/gateway/worker-link.ts @@ -15,15 +15,13 @@ * only: routing counts installed runtimes and never reads it (ADR 0009 §3). The uplink session is * admin, so the gateway may read it. */ -import { z } from "zod"; - import type { EventBus, EventName } from "../bus/index.js"; -import { grantedDeviceSchema, isSimlockError, statusDeviceSchema } from "../contract/index.js"; +import { grantedDeviceSchema, isSimlockError, workerViewFields } from "../contract/index.js"; import type { SimlockAdminClient } from "../admin/index.js"; import { connectSimlockAdmin } from "../admin/index.js"; import type { AcceptedUplink, Clock, IpcConnection, Logger } from "../ports/index.js"; import { NoopLogger } from "../ports/index.js"; -import type { WorkerGrantedDevice, WorkerRegistry, WorkerViewSnapshot } from "./worker-registry.js"; +import type { WorkerGrantedDevice, WorkerRegistry } from "./worker-registry.js"; /** * How long the gateway waits for one round trip to a worker before giving up on it. @@ -103,13 +101,7 @@ export interface WorkerLinkOptions { readonly isCurrentLink?: () => boolean; } -/** The device shape a view carries. Worker device records arrive through `list.get` as full - * `DeviceRecord`s (admin's own view of a registry); narrowing them here is what keeps - * `driverData` -- an opaque, driver-defined blob -- from crossing the fleet into a gateway - * client's `status.get`. */ -const viewDevicesSchema = z.array(statusDeviceSchema); - -/** The same `list.get` answer narrowed to the grant shape instead, which keeps `driverDeviceId` +/** The `list.get` answer narrowed to the grant shape rather than the view's device shape, which keeps `driverDeviceId` * for the lease payload a gateway serves its holder (`GET /v1/leases/{id}`). Kept off the view, * in the registry beside it: see `WorkerGrantedDevice`. `list.get`'s contract also admits a * device without `driverDeviceId`, so one that does not parse is left out on its own rather than @@ -379,14 +371,19 @@ export class WorkerLink { // The leases come from `status.get` and the devices from the `list.get` after it, and a // worker keeps a device while a lease holds it, so a lease reported here names a device in // `devices` unless it ended in between. One `refresh` call commits both, so a lease is - // never visible before its device. + // never visible before its device. The view's fields come from the contract's one view + // builder (ADR 0012 §1), the same one a worker answers `worker.list` about itself with; it + // narrows the device records, so no `driverData` crosses the fleet into a gateway client's + // `status.get`. this.options.registry.refresh(this.workerId, { - ...viewStatus(status), - devices: viewDevicesSchema.parse(devices), + ...workerViewFields({ + devices, + status, + ...(catalog === undefined ? {} : { catalog }), + ...(config === undefined ? {} : { config }), + }), grantedDevices: grantedDevices(devices), version: client.daemonVersion, - ...(catalog === undefined ? {} : { catalog: catalog.platforms }), - ...(config === undefined ? {} : viewConfig(config)), }); } @@ -554,36 +551,6 @@ function queueRefresh(queued: QueuedRefresh | undefined, next: RefreshOptions): return { done, options, resolve }; } -/** What a worker's view keeps of its `status.get`. */ -function viewStatus( - status: Awaited>, -): Pick { - return { - capacity: status.capacity, - health: status.daemon.health, - host: status.host, - // ADR 0010 §7: copied as the worker lists them, already bounded by the contract's parse - // (safety rule 10). A worker too old to list installs reports none. - installs: status.installs ?? [], - leases: status.leases, - queueDepth: status.queueDepth, - }; -} - -/** The few keys of a worker's config its view keeps. */ -function viewConfig( - config: Awaited>, -): Pick { - return { - // ADR 0010 §7: the worker's own install budget, read with its policy. - downloads: { policy: config.downloads.policy, timeoutMs: config.downloads.timeoutMs }, - // ADR 0005 §15: the one other field this gateway keeps out of a worker's config, - // alongside `downloads` -- `WorkerRegistry#refresh` is where it is compared against the - // gateway's own `lease.maxTtlMs` and warned about. - lease: { maxTtlMs: config.lease.maxTtlMs }, - }; -} - const defaultConnect: WorkerClientFactory = (connection, principal) => connectSimlockAdmin({ connection, principal }); diff --git a/src/http/app.test.ts b/src/http/app.test.ts index f18843c81..7604dc915 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -1765,22 +1765,49 @@ describe("hardening from review", () => { /** * ADR 0005 §23. The routes themselves are thin -- one dispatch each -- so what is worth - * asserting is which daemon has them at all, that the gateway-only ones reach the right - * operation with the id from the path, and that a refusal's typed `details` reach the body. + * asserting is which daemon has them at all, that they reach the right operation with the id + * from the path, and that a refusal's typed `details` reach the body. What a worker's own + * dispatcher answers on them is the HTTP API e2e flow's business. */ -describe("worker routes (gateway mode)", () => { +describe("worker routes", () => { function gatewayHarness() { return buildHarness({ config: testConfig({}, "gateway") }); } - it("are not routes at all on a worker", async () => { - const { app } = buildHarness(); - - const response = await app.request("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/v1/workers", { headers: operatorAuth }); + it("are routes on a worker too (ADR 0012 §3), each dispatching its operation", async () => { + const { app, config, dispatcher } = buildHarness(); + expect(config.mode).toBe("worker"); + dispatcher.handlers["worker.list"] = () => ({ workers: [] }); + for (const operation of ["worker.drain", "worker.undrain", "worker.remove"] as const) { + dispatcher.handlers[operation] = () => { + throw new DispatchError("UNSUPPORTED_IN_WORKER_MODE", `${operation} is refused`, { + operation, + }); + }; + } - // 404, not 501: a worker has no worker registry, so this is not an endpoint that exists - // and is switched off -- it is not an endpoint. - expect(response.status).toBe(404); + const list = await app.request("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/v1/workers", { headers: operatorAuth }); + const drain = await app.request("/v1/workers/w/drain", { + headers: operatorAuth, + method: "POST", + }); + const undrain = await app.request("/v1/workers/w/drain", { + headers: operatorAuth, + method: "DELETE", + }); + const remove = await app.request("/v1/workers/w", { headers: operatorAuth, method: "DELETE" }); + + expect(list.status).toBe(200); + expect(await list.json()).toEqual({ workers: [] }); + // Each refusal names the operation its handler was reached through, so the body proves + // which route dispatched what. + const refusals = [drain, undrain, remove]; + expect(refusals.map((response) => response.status)).toEqual([501, 501, 501]); + expect(await Promise.all(refusals.map((response) => response.json()))).toEqual( + ["worker.drain", "worker.undrain", "worker.remove"].map((operation) => ({ + error: { code: "UNSUPPORTED_IN_WORKER_MODE", message: expect.any(String), operation }, + })), + ); }); it("GET /v1/workers returns the views", async () => { diff --git a/src/http/app.ts b/src/http/app.ts index ff142485e..041be2c20 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -597,47 +597,45 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa return c.json({ devices }); }); - // ADR 0005 §23's worker routes, registered only on a gateway. A worker daemon has no worker - // registry, so on one these paths are simply not routes -- a `404`, which is what "this - // endpoint has no such resource" means, rather than a `501` implying the fleet exists here - // and is switched off. - if (deps.config.mode === "gateway") { - // Operator-role in effect: `worker.*` are admin operations, so an agent token gets - // `FORBIDDEN`/403 from the shared dispatcher rather than from a second check here. - app.get("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/v1/workers", agentAuth, async (c) => - c.json(await deps.dispatch("worker.list", {}, buildHttpSession(c.get("identity")))), - ); + // ADR 0005 §23's worker routes, registered in both modes (ADR 0012 §3). A worker answers them + // as a fleet of one: `GET /v1/workers` lists this host, and the drain, undrain and remove + // routes answer `501 UNSUPPORTED_IN_WORKER_MODE` from its dispatcher. + // + // Operator-role in effect: `worker.*` are admin operations, so an agent token gets + // `FORBIDDEN`/403 from the shared dispatcher rather than from a second check here. + app.get("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/v1/workers", agentAuth, async (c) => + c.json(await deps.dispatch("worker.list", {}, buildHttpSession(c.get("identity")))), + ); - app.post("/v1/workers/:id/drain", agentAuth, async (c) => - c.json( - await deps.dispatch( - "worker.drain", - { workerId: c.req.param("id") }, - buildHttpSession(c.get("identity")), - ), + app.post("/v1/workers/:id/drain", agentAuth, async (c) => + c.json( + await deps.dispatch( + "worker.drain", + { workerId: c.req.param("id") }, + buildHttpSession(c.get("identity")), ), - ); + ), + ); - app.delete("/v1/workers/:id/drain", agentAuth, async (c) => - c.json( - await deps.dispatch( - "worker.undrain", - { workerId: c.req.param("id") }, - buildHttpSession(c.get("identity")), - ), + app.delete("/v1/workers/:id/drain", agentAuth, async (c) => + c.json( + await deps.dispatch( + "worker.undrain", + { workerId: c.req.param("id") }, + buildHttpSession(c.get("identity")), ), - ); + ), + ); - app.delete("/v1/workers/:id", agentAuth, async (c) => - c.json( - await deps.dispatch( - "worker.remove", - { workerId: c.req.param("id") }, - buildHttpSession(c.get("identity")), - ), + app.delete("/v1/workers/:id", agentAuth, async (c) => + c.json( + await deps.dispatch( + "worker.remove", + { workerId: c.req.param("id") }, + buildHttpSession(c.get("identity")), ), - ); - } + ), + ); app.get("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/v1/events", agentAuth, async (c) => { const since = c.req.query("since"); diff --git a/src/http/errors.ts b/src/http/errors.ts index 478f81b56..8f670586d 100644 --- a/src/http/errors.ts +++ b/src/http/errors.ts @@ -10,8 +10,9 @@ import { } from "../contract/index.js"; /** Every status this frontend ever answers with; keeps `mapError` exhaustive by construction. - * 501 is `UNSUPPORTED_IN_GATEWAY_MODE`'s (ADR 0005 §34): the request was well-formed and the - * daemon is healthy, this endpoint simply does not implement that operation. 504 is + * 501 is `UNSUPPORTED_IN_GATEWAY_MODE`'s (ADR 0005 §34) and `UNSUPPORTED_IN_WORKER_MODE`'s (ADR + * 0012 §2): the request was well-formed and the daemon is healthy, this daemon's mode simply + * does not implement that operation. 504 is * `EXEC_TIMEOUT`'s (ADR 0005 §19e): a `device.exec` command the daemon killed for outrunning * `exec.timeoutMs` is the one case where what this frontend was waiting on never finished, * which is exactly what a gateway timeout says. */ diff --git a/src/simlock-client/client.ts b/src/simlock-client/client.ts index 2d4a83dbb..3001d961b 100644 --- a/src/simlock-client/client.ts +++ b/src/simlock-client/client.ts @@ -242,7 +242,8 @@ export interface SimlockAdminClient extends SimlockClient { listTokens(): Promise; revokeToken(input: TokenRevokeInput): Promise; - /** ADR 0005 §23. Gateway-only: a worker answers `UNKNOWN_REQUEST`, since it has no fleet. */ + /** ADR 0005 §23. A worker lists itself as its only worker; `drainWorker`, `undrainWorker` and + * `removeWorker` reject on a worker with `UNSUPPORTED_IN_WORKER_MODE` (ADR 0012). */ listWorkers(): Promise; drainWorker(input: WorkerDrainInput): Promise; undrainWorker(input: WorkerDrainInput): Promise; @@ -263,7 +264,7 @@ export interface SimlockAdminClient extends SimlockClient { * ADR 0010 §7, gateway-only: installs one component on named workers (`workers: [ids]`) or on * every connected one (`workers: "all"`). Every targeted worker is asked at the same time and * answers for itself; the result lists one entry per worker. `options.onProgress` hears each - * worker's progress with its `workerId`. A worker answers `UNKNOWN_REQUEST`. + * worker's progress with its `workerId`. A worker answers `UNSUPPORTED_IN_WORKER_MODE`. */ installComponentOnWorkers( input: WorkerInstallComponentInput, diff --git a/src/simlock-client/types.ts b/src/simlock-client/types.ts index feb36ad12..d290c3e63 100644 --- a/src/simlock-client/types.ts +++ b/src/simlock-client/types.ts @@ -63,15 +63,16 @@ export type TokenListOutput = OpOutput<"token.list">; export type TokenRevokeInput = OpInput<"token.revoke">; export type TokenRevokeOutput = OpOutput<"token.revoke">; -// ---- gateway-only operations (ADR 0005 §23) ------------------------------------------------- +// ---- fleet operations (ADR 0005 §23) ---------------------------------------------------------- // -// Declared on the admin client like every other admin row. A *worker* has no worker registry -// and implements none of them, so calling one against a worker answers `UNKNOWN_REQUEST` -- -// which is the honest answer, and the reason these are not gated client-side: the daemon says -// what it is, rather than the client guessing from a mode it was never told. +// Declared on the admin client like every other admin row. A *worker* answers them as a fleet +// of one (ADR 0012): `worker.list` returns the worker itself, and drain, undrain and remove +// answer `UNSUPPORTED_IN_WORKER_MODE`. They are not gated client-side: the daemon says what it +// is, rather than the client guessing from a mode it was never told. export type WorkerListOutput = OpOutput<"worker.list">; -/** One worker as the gateway currently sees it -- the shape `simlock worker list` renders. */ +/** One worker as the gateway currently sees it, or a single host as it sees itself -- the shape + * `simlock worker list` renders. */ export type WorkerView = WorkerListOutput["workers"][number]; export type WorkerDrainInput = OpInput<"worker.drain">; export type WorkerDrainOutput = OpOutput<"worker.drain">; From cf5882cd2b234061dff7a5ae6a36df2deffd2ce3 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 20:25:45 +0200 Subject: [PATCH 2/5] test(daemon,http): prove each refusal, the version wiring and the install refusal's message Closes #270 --- src/daemon/dispatcher.test.ts | 52 ++++++++++++++++++++--------------- src/daemon/server.test.ts | 16 +++++++++++ src/http/app.test.ts | 2 +- 3 files changed, 47 insertions(+), 23 deletions(-) diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index b758d9d88..53c16fcd2 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -445,32 +445,40 @@ describe("Dispatcher: the fleet operations on a worker", () => { expect(workers[0]?.devices[0]).not.toHaveProperty("driverData"); }); - it.each(["worker.drain", "worker.undrain", "worker.remove"] as const)( - "worker.drain, worker.undrain, worker.remove and worker.install-component on a worker fail with UNSUPPORTED_IN_WORKER_MODE: %s", - async (operation) => { - const { dispatcher } = await buildDispatcher(); - - await expect( - dispatcher.dispatch(operation, { workerId: "instance-1" }, admin), - ).rejects.toMatchObject({ code: "UNSUPPORTED_IN_WORKER_MODE", details: { operation } }); - }, - ); - - it("worker.drain, worker.undrain, worker.remove and worker.install-component on a worker fail with UNSUPPORTED_IN_WORKER_MODE: worker.install-component, installing nothing", async () => { + it("worker.drain, worker.undrain, worker.remove and worker.install-component on a worker fail with UNSUPPORTED_IN_WORKER_MODE", async () => { const { components, dispatcher } = await buildDispatcher(); const install = vi.spyOn(components, "install"); - - await expect( - dispatcher.dispatch( - "worker.install-component", - { platform: "ios", version: "27.0", workers: "all" }, - admin, + const calls = [ + ["worker.drain", { workerId: "instance-1" }], + ["worker.undrain", { workerId: "instance-1" }], + ["worker.remove", { workerId: "instance-1" }], + ["worker.install-component", { platform: "ios", version: "27.0", workers: "all" }], + ] as const; + + const refusals = await Promise.all( + calls.map(([operation, input]) => + dispatcher.dispatch(operation, input, admin).then( + () => ({ operation, outcome: "answered" }), + (error: unknown) => ({ error, operation }), + ), ), - ).rejects.toMatchObject({ - code: "UNSUPPORTED_IN_WORKER_MODE", - details: { operation: "worker.install-component" }, - }); + ); + + expect(refusals).toEqual( + calls.map(([operation]) => ({ + error: expect.objectContaining({ + code: "UNSUPPORTED_IN_WORKER_MODE", + details: { operation }, + }), + operation, + })), + ); + // The refusal is the whole answer: nothing was installed on this host instead, and the + // message says how to install here. expect(install).not.toHaveBeenCalled(); + expect(String((refusals[3] as { error?: unknown } | undefined)?.error)).toContain( + "install on this host without naming workers", + ); }); }); diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index d6ace938e..3e233c831 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -1648,6 +1648,22 @@ describe("DaemonServer lease liveness (ADR 0004)", () => { await client.close(); }); + it("answers worker.list with this daemon's instance id and the version its hello reports", async () => { + const harness = await createHarness({ resolveRole: { resolve: () => "admin" } }); + const client = await createClient(harness.socketPath); + const greeting = await client.request("hello", { + clientVersion: "test", + protocolVersion: DAEMON_PROTOCOL_VERSION, + }); + expect(greeting).toMatchObject({ ok: true, payload: { version: "test" } }); + + await expect(client.request("worker.list", {})).resolves.toMatchObject({ + ok: true, + payload: { workers: [{ id: "instance-test", version: "test" }] }, + }); + await client.close(); + }); + it("answers worker.install-component with UNSUPPORTED_IN_WORKER_MODE: a worker has no workers to install on", async () => { const harness = await createHarness({ resolveRole: { resolve: () => "admin" } }); const client = await createClient(harness.socketPath); diff --git a/src/http/app.test.ts b/src/http/app.test.ts index 7604dc915..e9f3c9a57 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -1767,7 +1767,7 @@ describe("hardening from review", () => { * ADR 0005 §23. The routes themselves are thin -- one dispatch each -- so what is worth * asserting is which daemon has them at all, that they reach the right operation with the id * from the path, and that a refusal's typed `details` reach the body. What a worker's own - * dispatcher answers on them is the HTTP API e2e flow's business. + * dispatcher answers on them is covered end to end in `e2e/single-host-fleet.test.ts`. */ describe("worker routes", () => { function gatewayHarness() { From 2b5d9eb141d5f1c8a28e692161a0137e5a16f481 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 20:35:46 +0200 Subject: [PATCH 3/5] docs(daemon,gateway,http): make three comments say only what the code and tests prove Closes #270 --- src/daemon/dispatcher.ts | 9 +++++---- src/gateway/service.test.ts | 7 ++++++- src/http/app.test.ts | 3 ++- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index adeef0534..31206ab5a 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -611,10 +611,11 @@ export class Dispatcher { /** * ADR 0012 §1: this host as its own fleet of one. The fields a gateway reads over the uplink - * come from the same four reads, made here against this dispatcher's own handlers and parsed - * through their output schemas, so they are what a gateway would have received; the - * contract's one builder turns them into a view. `drained` is always `false`: a gateway that - * drained this worker holds that flag, not this host. + * come from the same four reads, made here against this dispatcher's own handlers; the + * contract's one builder turns them into a view. The parses only turn the handlers' core + * records into the wire types the builder takes: `worker.list`'s own output schema, applied + * by `dispatch()`, is what bounds and narrows the view on the wire. `drained` is always + * `false`: a gateway that drained this worker holds that flag, not this host. */ #workerList: Handler<"worker.list"> = async (_input, session) => { const [status, devices, catalog] = await Promise.all([ diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts index 227643e1a..5dcbed4c3 100644 --- a/src/gateway/service.test.ts +++ b/src/gateway/service.test.ts @@ -179,7 +179,12 @@ describe("GatewayService", () => { state: "downloading" as const, waiters: 2, }; + const capacity = { + ...statusFixture().capacity, + global: { maxRunning: 4, overLimit: false, reserved: 1, running: 2, warm: 1 }, + }; worker.status = statusFixture({ + capacity, daemon: { health: "starting", mode: "worker" }, host: hostFixture({ arch: "x64" }), installs: [install], @@ -200,7 +205,7 @@ describe("GatewayService", () => { await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.lease).toBeDefined()); expect(harness.service.workers.view("wrk_1")).toEqual({ - capacity: statusFixture().capacity, + capacity, catalog: catalogFixture([{ models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }]) .platforms, connection: "connected", diff --git a/src/http/app.test.ts b/src/http/app.test.ts index e9f3c9a57..292fded73 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -1767,7 +1767,8 @@ describe("hardening from review", () => { * ADR 0005 §23. The routes themselves are thin -- one dispatch each -- so what is worth * asserting is which daemon has them at all, that they reach the right operation with the id * from the path, and that a refusal's typed `details` reach the body. What a worker's own - * dispatcher answers on them is covered end to end in `e2e/single-host-fleet.test.ts`. + * dispatcher answers for all four operations is proven in `src/daemon/dispatcher.test.ts`; + * `e2e/single-host-fleet.test.ts` drives `GET /v1/workers` and the drain route end to end. */ describe("worker routes", () => { function gatewayHarness() { From f0c510b6e5b24f0c4422cc18a93788a204ef8519 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 23:24:57 +0200 Subject: [PATCH 4/5] fix(daemon,contract,gateway,docs): keep worker.list's catalog for the gateway's refresh interval worker.list ran every driver's catalog read on each call, and the console polls GET /v1/workers every second. The worker now keeps the catalog for WORKER_VIEW_REFRESH_INTERVAL_MS, the gateway's own refresh tick, and drops it on component.installed and component.removed. Closes #270 --- docs/HTTP-API.md | 5 ++- docs/internal/ARCHITECTURE.md | 6 ++- src/contract/worker-view.ts | 9 ++++ src/daemon/dispatcher.test.ts | 83 ++++++++++++++++++++++++++++++++++- src/daemon/dispatcher.ts | 48 ++++++++++++++++++-- src/daemon/server.test.ts | 29 +++++++++++- src/daemon/server.ts | 2 + src/gateway/service.ts | 3 +- 8 files changed, 176 insertions(+), 9 deletions(-) diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index b8ca6f79d..db6c97d35 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -1070,7 +1070,10 @@ one view, the host itself, with the same fields a gateway shows for each of its workers. `id` is the id the host presents to a gateway, `label` is its `gateway.label` (absent when unset), `connection` is `connected`, `drained` is `false`, and `lastSeenAt` is the time of the request. Every other field -comes from the host's own status, devices, catalog and config. A host that +comes from the host's own status, devices, catalog and config. Status and +devices are read on every request. The catalog is read again at most every +30 seconds, and straight after a component is installed or removed, as a +gateway reads its workers' catalogs. A host that has joined a gateway still answers about itself: its `drained` is `false` even when the gateway has drained it, because that flag is the gateway's. diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 238660e65..edac3d93c 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -520,7 +520,11 @@ call. The reported fields come from its own `status.get`, `list.get`, `catalog.get` and `config.get`, turned into view fields by `workerViewFields` in `src/contract/worker-view.ts` — the same pure function `WorkerLink` builds a gateway's views with, so the two cannot disagree about -a field. `worker.drain`, `worker.undrain`, `worker.remove` and +a field. The catalog is the one read the worker keeps: `catalog.get` runs +each driver's catalog read (`simctl list` on iOS), and the console polls +`GET /v1/workers` every second, so the dispatcher re-reads it only once +`WORKER_VIEW_REFRESH_INTERVAL_MS` (the gateway's own refresh tick) has +passed, or after `component.installed` or `component.removed`. `worker.drain`, `worker.undrain`, `worker.remove` and `worker.install-component` answer `UNSUPPORTED_IN_WORKER_MODE` (`501`, exit `2`), the mirror of `UNSUPPORTED_IN_GATEWAY_MODE`. The `/v1/workers*` routes are registered in both modes. diff --git a/src/contract/worker-view.ts b/src/contract/worker-view.ts index fb6258d37..e67eb0647 100644 --- a/src/contract/worker-view.ts +++ b/src/contract/worker-view.ts @@ -14,6 +14,15 @@ import { z } from "zod"; import type { OPERATIONS } from "./operations.js"; import { statusDeviceSchema, type workerViewSchema } from "./schemas.js"; +/** + * How often a worker view is re-read in full, catalog and config included, when no event asks + * for it sooner. A gateway refreshes every view on this tick (ADR 0005 §7's backstop), and a + * worker answering `worker.list` about itself re-reads its catalog no more often, so an open + * console polling `GET /v1/workers` does not run a driver's catalog read on every poll. Both + * re-read the catalog at once after a component install. + */ +export const WORKER_VIEW_REFRESH_INTERVAL_MS = 30_000; + type Output = z.infer<(typeof OPERATIONS)[Name]["output"]>; type WorkerView = z.infer; diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 53c16fcd2..fd3c5712c 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -19,7 +19,11 @@ import { SerializedDecision, RuntimeMissingError, } from "../core/index.js"; -import { OPERATIONS, statusDeviceSchema } from "../contract/index.js"; +import { + OPERATIONS, + statusDeviceSchema, + WORKER_VIEW_REFRESH_INTERVAL_MS, +} from "../contract/index.js"; import type { FakeDriverOptions } from "../core/fake-driver.js"; import type { CatalogReader, PassthroughResolver } from "../core/lease-ports.js"; import { @@ -242,6 +246,7 @@ async function buildDispatcher( components: wiring.components, config, doctor, + eventBus, eventHistory: resolveEventHistoryOverride(eventBus, filesystem, overrides.eventHistory), health: () => "running", hostFacts: overrides.hostFacts ?? (() => ({ ...HOST_SYSTEM, tools: [] })), @@ -398,6 +403,82 @@ describe("Dispatcher: the fleet operations on a worker", () => { expect(withoutLabel.workers[0]).not.toHaveProperty("label"); }); + it("worker.list on a worker reads the driver's catalog once per refresh interval, not on every call", async () => { + const { clock, dispatcher, driver } = await buildDispatcher(); + const catalogReads = vi.spyOn(driver, "listCatalog"); + + for (let poll = 0; poll < 5; poll += 1) { + await dispatcher.dispatch("worker.list", {}, admin); + clock.advance(1_000); + } + expect(catalogReads).toHaveBeenCalledTimes(1); + + clock.advance(WORKER_VIEW_REFRESH_INTERVAL_MS); + await dispatcher.dispatch("worker.list", {}, admin); + expect(catalogReads).toHaveBeenCalledTimes(2); + }); + + it("worker.list on a worker lists a runtime installed since its last read, without waiting for the interval", async () => { + const { components, dispatcher } = await buildDispatcher(); + const runtimes = async () => + (await dispatcher.dispatch("worker.list", {}, admin)).workers[0]?.catalog.flatMap( + (entry) => entry.runtimes, + ); + expect(await runtimes()).toEqual(["26.5"]); + + await components.install({ component: "27.0", platform: "ios" }); + + expect(await runtimes()).toEqual(expect.arrayContaining(["26.5", "27.0"])); + }); + + it("worker.list on a worker drops a removed runtime without waiting for the interval", async () => { + const { components, dispatcher } = await buildDispatcher(); + const runtimes = async () => + (await dispatcher.dispatch("worker.list", {}, admin)).workers[0]?.catalog.flatMap( + (entry) => entry.runtimes, + ); + await components.install({ component: "27.0", platform: "ios" }); + expect(await runtimes()).toEqual(expect.arrayContaining(["27.0"])); + + await expect( + components.remove({ platform: "ios", requesterId: "operator", version: "27.0" }), + ).resolves.toMatchObject({ + outcome: "removed", + }); + + expect(await runtimes()).not.toContain("27.0"); + }); + + it("worker.list on a worker reads the catalog again after a read that failed", async () => { + let calls = 0; + const { dispatcher } = await buildDispatcher({ + catalog: { + listCatalog: async () => { + calls += 1; + if (calls === 1) throw new Error("the catalog could not be read"); + return [ + { + defaultRuntime: "26.5", + modelAliases: {}, + models: [], + modelRuntimes: {}, + platform: "ios", + runtimes: ["26.5"], + }, + ]; + }, + }, + }); + + await expect(dispatcher.dispatch("worker.list", {}, admin)).rejects.toThrow( + "the catalog could not be read", + ); + const { workers } = await dispatcher.dispatch("worker.list", {}, admin); + + expect(calls).toBe(2); + expect(workers[0]?.catalog.flatMap((entry) => entry.runtimes)).toEqual(["26.5"]); + }); + it("worker.list on a worker reports the same capacity, devices, leases, catalog, host and installs as its own reads", async () => { const { components, dispatcher, driver } = await buildDispatcher({ driverOptions: { knownModels: ["iPhone 17 Pro"] }, diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 31206ab5a..c2c2f9d3f 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -1,6 +1,6 @@ import { z } from "zod"; -import type { EventHistory } from "../bus/index.js"; +import type { EventBus, EventHistory } from "../bus/index.js"; import { type CleanupReaper, ComponentInUseError, @@ -39,6 +39,7 @@ import { requestedDevice, type ComponentProgress, type OperationName, + WORKER_VIEW_REFRESH_INTERVAL_MS, workerViewFields, } from "../contract/index.js"; import type { TokenStore } from "../http/token-store.js"; @@ -148,6 +149,12 @@ export interface DispatcherOptions { readonly instanceId: string; /** This daemon's own version, the one its `hello` reply carries; `worker.list`'s `version`. */ readonly version: string; + /** + * Where `worker.list` hears that a component was installed or removed, so its kept catalog is + * read again at once rather than on its next interval. Optional for the tests that never call + * `worker.list`; without it the kept catalog is only re-read on the interval. + */ + readonly eventBus?: Pick; } /** @@ -197,9 +204,24 @@ export class Dispatcher { * what a worker answers. */ readonly #handlers: Record; + /** + * `worker.list`'s catalog: the last `catalog.get` answer and when it was read. Kept for + * `WORKER_VIEW_REFRESH_INTERVAL_MS`, the rhythm a gateway re-reads a worker's catalog at, and + * dropped when a component is installed or removed. Without it every `worker.list` runs each + * driver's catalog read (`simctl list` on iOS), and the console polls that route every second. + * Holds the promise, so calls that arrive while a read runs share it; a read that fails is + * dropped, so the next call reads again. + */ + #viewCatalog: { readonly readAt: number; readonly catalog: Promise } | undefined; constructor(private readonly options: DispatcherOptions) { this.#logger = options.logger ?? new NoopLogger(); + // Observers only (architecture rule 5): dropping a kept read decides nothing. + const dropViewCatalog = () => { + this.#viewCatalog = undefined; + }; + options.eventBus?.subscribe("component.installed", dropViewCatalog); + options.eventBus?.subscribe("component.removed", dropViewCatalog); this.#dispatchLogger = this.#logger.child("dispatch"); this.#handlers = { "catalog.get": this.#catalogGet, @@ -614,14 +636,16 @@ export class Dispatcher { * come from the same four reads, made here against this dispatcher's own handlers; the * contract's one builder turns them into a view. The parses only turn the handlers' core * records into the wire types the builder takes: `worker.list`'s own output schema, applied - * by `dispatch()`, is what bounds and narrows the view on the wire. `drained` is always - * `false`: a gateway that drained this worker holds that flag, not this host. + * by `dispatch()`, is what bounds and narrows the view on the wire. The catalog is the kept + * one (see `#viewCatalog`); status and devices are read on every call, as a gateway reads + * them on every worker event. `drained` is always `false`: a gateway that drained this worker + * holds that flag, not this host. */ #workerList: Handler<"worker.list"> = async (_input, session) => { const [status, devices, catalog] = await Promise.all([ this.#statusGet({}, session), this.#listGet({ kind: "devices" }, session), - this.#catalogGet({}, session), + this.#keptViewCatalog(session), ]); const label = this.options.config.gateway.label; return { @@ -644,6 +668,22 @@ export class Dispatcher { }; }; + /** The kept catalog for `worker.list`, read again once it is older than the interval. */ + #keptViewCatalog(session: DispatchSession): Promise { + const now = this.options.clock.now(); + const kept = this.#viewCatalog; + if (kept !== undefined && now - kept.readAt < WORKER_VIEW_REFRESH_INTERVAL_MS) { + return kept.catalog; + } + const catalog = Promise.resolve(this.#catalogGet({}, session)); + const entry = { catalog, readAt: now }; + this.#viewCatalog = entry; + catalog.catch(() => { + if (this.#viewCatalog === entry) this.#viewCatalog = undefined; + }); + return catalog; + } + /** * ADR 0010 §4 and §6: an operator's explicit install. The command itself is the consent, so the * one consent function is asked with `true`; only `downloads.policy: "never"` refuses it, and it diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 3e233c831..a8fb342ce 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -2,7 +2,7 @@ import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { Socket, connect } from "node:net"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { testComponentWiring } from "../core/test-wiring.js"; import { EventBus, EventHistory } from "../bus/index.js"; @@ -1664,6 +1664,33 @@ describe("DaemonServer lease liveness (ADR 0004)", () => { await client.close(); }); + it("re-reads worker.list's kept catalog once this daemon's bus reports a component installed", async () => { + const harness = await createHarness({ resolveRole: { resolve: () => "admin" } }); + const client = await createClient(harness.socketPath); + await hello(client); + const catalogReads = vi.spyOn(harness.driver, "listCatalog"); + + await client.request("worker.list", {}); + await client.request("worker.list", {}); + expect(catalogReads).toHaveBeenCalledTimes(1); + + harness.eventBus.emit( + "component.installed", + { + alreadyPresent: false, + componentId: "27.0", + durationMs: 1, + platform: "ios", + version: "27.0", + }, + "test", + ); + await client.request("worker.list", {}); + + expect(catalogReads).toHaveBeenCalledTimes(2); + await client.close(); + }); + it("answers worker.install-component with UNSUPPORTED_IN_WORKER_MODE: a worker has no workers to install on", async () => { const harness = await createHarness({ resolveRole: { resolve: () => "admin" } }); const client = await createClient(harness.socketPath); diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 5e80d32f6..53d360850 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -296,6 +296,8 @@ function buildDispatcher( ...(options.doctor === undefined ? {} : { doctor: options.doctor }), // The `operation` log line's error code: the same classifier this server answers with. errorCode: classifyError, + // `worker.list` drops its kept catalog when a component is installed or removed. + eventBus: options.eventBus, eventHistory: options.eventHistory, health: hooks.health, hostFacts: options.hostFacts, diff --git a/src/gateway/service.ts b/src/gateway/service.ts index ed8a73097..375f3a9f3 100644 --- a/src/gateway/service.ts +++ b/src/gateway/service.ts @@ -16,6 +16,7 @@ import type { UplinkListener, UplinkListenerFactory, } from "../ports/index.js"; +import { WORKER_VIEW_REFRESH_INTERVAL_MS } from "../contract/index.js"; import { NoopLogger, uplinkOutcome } from "../ports/index.js"; import type { DrainStore } from "./drain-store.js"; import { WorkerLink, type WorkerClientFactory } from "./worker-link.js"; @@ -29,7 +30,7 @@ import { WorkerRegistry } from "./worker-registry.js"; * far below the shortest interesting lease TTL and far above anything that would make a fleet's * worth of `status.get` calls noticeable. */ -const DEFAULT_WORKER_REFRESH_INTERVAL_MS = 30_000; +const DEFAULT_WORKER_REFRESH_INTERVAL_MS = WORKER_VIEW_REFRESH_INTERVAL_MS; /** * P-2: how long a coalescing window for repeated `worker.rejected` refusals stays open. From d7d4af44b492c524c366428cc30a2e776fa2212c Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 23:41:55 +0200 Subject: [PATCH 5/5] fix(daemon,contract,gateway,docs): re-read worker.list's catalog on the gateway's events, and end the subscriptions on stop The worker and the gateway now share one list of events that make a view re-read its catalog. The dispatcher's bus subscriptions end when the daemon stops, a clock set back counts as a stale read, and the tests pin the interval and the shared in-flight read. Closes #270 --- docs/HTTP-API.md | 6 +-- docs/internal/ARCHITECTURE.md | 5 +- src/contract/worker-view.ts | 8 +++ src/daemon/dispatcher.test.ts | 92 +++++++++++++++++++++++++++-------- src/daemon/dispatcher.ts | 54 +++++++++++++------- src/daemon/server.test.ts | 11 +++++ src/daemon/server.ts | 6 ++- src/gateway/worker-link.ts | 11 ++++- 8 files changed, 148 insertions(+), 45 deletions(-) diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index db6c97d35..506aaf4ee 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -1071,9 +1071,9 @@ its workers. `id` is the id the host presents to a gateway, `label` is its `gateway.label` (absent when unset), `connection` is `connected`, `drained` is `false`, and `lastSeenAt` is the time of the request. Every other field comes from the host's own status, devices, catalog and config. Status and -devices are read on every request. The catalog is read again at most every -30 seconds, and straight after a component is installed or removed, as a -gateway reads its workers' catalogs. A host that +devices are read on every request. The catalog is read again every 30 +seconds, and straight after a component is installed, as a gateway reads its +workers' catalogs; a removed component leaves it on the next read. A host that has joined a gateway still answers about itself: its `drained` is `false` even when the gateway has drained it, because that flag is the gateway's. diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index edac3d93c..6d137a657 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -524,7 +524,10 @@ a field. The catalog is the one read the worker keeps: `catalog.get` runs each driver's catalog read (`simctl list` on iOS), and the console polls `GET /v1/workers` every second, so the dispatcher re-reads it only once `WORKER_VIEW_REFRESH_INTERVAL_MS` (the gateway's own refresh tick) has -passed, or after `component.installed` or `component.removed`. `worker.drain`, `worker.undrain`, `worker.remove` and +passed, or after one of `WORKER_VIEW_CATALOG_EVENTS`. Both constants live +in `src/contract/worker-view.ts`, and `WorkerLink` reads the same two, so a +host's view of itself and a gateway's view of it re-read the catalog on the +same rhythm. The dispatcher's subscriptions end when `DaemonServer` stops. `worker.drain`, `worker.undrain`, `worker.remove` and `worker.install-component` answer `UNSUPPORTED_IN_WORKER_MODE` (`501`, exit `2`), the mirror of `UNSUPPORTED_IN_GATEWAY_MODE`. The `/v1/workers*` routes are registered in both modes. diff --git a/src/contract/worker-view.ts b/src/contract/worker-view.ts index e67eb0647..74e535b36 100644 --- a/src/contract/worker-view.ts +++ b/src/contract/worker-view.ts @@ -23,6 +23,14 @@ import { statusDeviceSchema, type workerViewSchema } from "./schemas.js"; */ export const WORKER_VIEW_REFRESH_INTERVAL_MS = 30_000; +/** + * The events after which a worker view's catalog is read again at once, rather than on the + * interval above. One list, read by a gateway's `WorkerLink` and by a worker answering + * `worker.list`, so both re-read on the same events (architecture rule 10). An installed + * component is a new catalog entry (ADR 0010 §7); a removal shows on the next interval. + */ +export const WORKER_VIEW_CATALOG_EVENTS = ["component.installed"] as const; + type Output = z.infer<(typeof OPERATIONS)[Name]["output"]>; type WorkerView = z.infer; diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index fd3c5712c..852eb53db 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -22,6 +22,7 @@ import { import { OPERATIONS, statusDeviceSchema, + WORKER_VIEW_CATALOG_EVENTS, WORKER_VIEW_REFRESH_INTERVAL_MS, } from "../contract/index.js"; import type { FakeDriverOptions } from "../core/fake-driver.js"; @@ -108,6 +109,19 @@ function fakePassthroughOptions( }; } +/** A fake clock that can also be set back, as a wall clock can be. */ +class SettableClock extends FakeClock { + #offset = 0; + + setBack(ms: number): void { + this.#offset -= ms; + } + + override now(): number { + return super.now() + this.#offset; + } +} + /** `config` with `gateway.label` set, or unchanged when there is no label. */ function withGatewayLabel(config: Config, label: string | undefined): Config { return label === undefined ? config : { ...config, gateway: { ...config.gateway, label } }; @@ -407,46 +421,82 @@ describe("Dispatcher: the fleet operations on a worker", () => { const { clock, dispatcher, driver } = await buildDispatcher(); const catalogReads = vi.spyOn(driver, "listCatalog"); - for (let poll = 0; poll < 5; poll += 1) { - await dispatcher.dispatch("worker.list", {}, admin); + // A console polls every second; every poll up to the last millisecond of the interval + // answers from the one read. + await dispatcher.dispatch("worker.list", {}, admin); + for (let elapsed = 1_000; elapsed < WORKER_VIEW_REFRESH_INTERVAL_MS; elapsed += 1_000) { clock.advance(1_000); + await dispatcher.dispatch("worker.list", {}, admin); } + clock.advance(999); + await dispatcher.dispatch("worker.list", {}, admin); expect(catalogReads).toHaveBeenCalledTimes(1); - clock.advance(WORKER_VIEW_REFRESH_INTERVAL_MS); + clock.advance(1); await dispatcher.dispatch("worker.list", {}, admin); expect(catalogReads).toHaveBeenCalledTimes(2); }); - it("worker.list on a worker lists a runtime installed since its last read, without waiting for the interval", async () => { - const { components, dispatcher } = await buildDispatcher(); - const runtimes = async () => - (await dispatcher.dispatch("worker.list", {}, admin)).workers[0]?.catalog.flatMap( - (entry) => entry.runtimes, - ); - expect(await runtimes()).toEqual(["26.5"]); + it("worker.list on a worker shares one catalog read between calls that arrive while it runs", async () => { + const { dispatcher, driver } = await buildDispatcher(); + const catalogReads = vi.spyOn(driver, "listCatalog"); - await components.install({ component: "27.0", platform: "ios" }); + await Promise.all([ + dispatcher.dispatch("worker.list", {}, admin), + dispatcher.dispatch("worker.list", {}, admin), + dispatcher.dispatch("worker.list", {}, admin), + ]); - expect(await runtimes()).toEqual(expect.arrayContaining(["26.5", "27.0"])); + expect(catalogReads).toHaveBeenCalledTimes(1); }); - it("worker.list on a worker drops a removed runtime without waiting for the interval", async () => { + it("worker.list on a worker reads the catalog again when the clock is set back", async () => { + const clock = new SettableClock(100_000); + const { dispatcher, driver } = await buildDispatcher({ clock }); + const catalogReads = vi.spyOn(driver, "listCatalog"); + await dispatcher.dispatch("worker.list", {}, admin); + + clock.setBack(60_000); + await dispatcher.dispatch("worker.list", {}, admin); + + expect(catalogReads).toHaveBeenCalledTimes(2); + }); + + it("worker.list on a worker re-reads its catalog on each event a gateway re-reads a worker's catalog on, until disposed", async () => { + const { dispatcher, driver, eventBus } = await buildDispatcher(); + const catalogReads = vi.spyOn(driver, "listCatalog"); + const payload = { + alreadyPresent: false, + componentId: "27.0", + durationMs: 1, + platform: "ios", + version: "27.0", + }; + expect(WORKER_VIEW_CATALOG_EVENTS).toEqual(["component.installed"]); + await dispatcher.dispatch("worker.list", {}, admin); + + eventBus.emit("component.installed", payload, "test"); + await dispatcher.dispatch("worker.list", {}, admin); + expect(catalogReads).toHaveBeenCalledTimes(2); + + dispatcher.dispose(); + await dispatcher.dispatch("worker.list", {}, admin); + eventBus.emit("component.installed", payload, "test"); + await dispatcher.dispatch("worker.list", {}, admin); + expect(catalogReads).toHaveBeenCalledTimes(3); + }); + + it("worker.list on a worker lists a runtime installed since its last read, without waiting for the interval", async () => { const { components, dispatcher } = await buildDispatcher(); const runtimes = async () => (await dispatcher.dispatch("worker.list", {}, admin)).workers[0]?.catalog.flatMap( (entry) => entry.runtimes, ); - await components.install({ component: "27.0", platform: "ios" }); - expect(await runtimes()).toEqual(expect.arrayContaining(["27.0"])); + expect(await runtimes()).toEqual(["26.5"]); - await expect( - components.remove({ platform: "ios", requesterId: "operator", version: "27.0" }), - ).resolves.toMatchObject({ - outcome: "removed", - }); + await components.install({ component: "27.0", platform: "ios" }); - expect(await runtimes()).not.toContain("27.0"); + expect(await runtimes()).toEqual(expect.arrayContaining(["26.5", "27.0"])); }); it("worker.list on a worker reads the catalog again after a read that failed", async () => { diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index c2c2f9d3f..89415dd7e 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -39,6 +39,7 @@ import { requestedDevice, type ComponentProgress, type OperationName, + WORKER_VIEW_CATALOG_EVENTS, WORKER_VIEW_REFRESH_INTERVAL_MS, workerViewFields, } from "../contract/index.js"; @@ -150,9 +151,9 @@ export interface DispatcherOptions { /** This daemon's own version, the one its `hello` reply carries; `worker.list`'s `version`. */ readonly version: string; /** - * Where `worker.list` hears that a component was installed or removed, so its kept catalog is - * read again at once rather than on its next interval. Optional for the tests that never call - * `worker.list`; without it the kept catalog is only re-read on the interval. + * Where `worker.list` hears `WORKER_VIEW_CATALOG_EVENTS`, so its kept catalog is read again at + * once rather than on its next interval. Optional for the tests that never call `worker.list`; + * without it the kept catalog is only re-read on the interval. */ readonly eventBus?: Pick; } @@ -207,21 +208,24 @@ export class Dispatcher { /** * `worker.list`'s catalog: the last `catalog.get` answer and when it was read. Kept for * `WORKER_VIEW_REFRESH_INTERVAL_MS`, the rhythm a gateway re-reads a worker's catalog at, and - * dropped when a component is installed or removed. Without it every `worker.list` runs each - * driver's catalog read (`simctl list` on iOS), and the console polls that route every second. - * Holds the promise, so calls that arrive while a read runs share it; a read that fails is - * dropped, so the next call reads again. + * dropped on `WORKER_VIEW_CATALOG_EVENTS`, the events a gateway re-reads it on. Without it + * every `worker.list` runs each driver's catalog read (`simctl list` on iOS), and the console + * polls that route every second. Holds the promise, so calls that arrive while a read runs + * share it; a read that fails is dropped, so the next call reads again. */ #viewCatalog: { readonly readAt: number; readonly catalog: Promise } | undefined; + /** Ends the bus subscriptions that drop `#viewCatalog`; see `dispose`. */ + readonly #unsubscribe: (() => void)[] = []; constructor(private readonly options: DispatcherOptions) { this.#logger = options.logger ?? new NoopLogger(); // Observers only (architecture rule 5): dropping a kept read decides nothing. - const dropViewCatalog = () => { - this.#viewCatalog = undefined; - }; - options.eventBus?.subscribe("component.installed", dropViewCatalog); - options.eventBus?.subscribe("component.removed", dropViewCatalog); + for (const event of WORKER_VIEW_CATALOG_EVENTS) { + const unsubscribe = options.eventBus?.subscribe(event, () => { + this.#viewCatalog = undefined; + }); + if (unsubscribe !== undefined) this.#unsubscribe.push(unsubscribe); + } this.#dispatchLogger = this.#logger.child("dispatch"); this.#handlers = { "catalog.get": this.#catalogGet, @@ -261,6 +265,12 @@ export class Dispatcher { }; } + /** Ends this dispatcher's bus subscriptions. `DaemonServer` calls it when the daemon stops. */ + dispose(): void { + for (const unsubscribe of this.#unsubscribe.splice(0)) unsubscribe(); + this.#viewCatalog = undefined; + } + /** ADR 0003 §2's pipeline, run by the shared `runDispatch` (see `./dispatch.js`) over this * dispatcher's own handlers, lease lookups, and startup gate. The ordering and the checks * are the contract's; only the three inputs below are this implementation's. */ @@ -668,18 +678,28 @@ export class Dispatcher { }; }; - /** The kept catalog for `worker.list`, read again once it is older than the interval. */ + /** + * The kept catalog for `worker.list`, read again once it is older than the interval. The age + * is wall-clock time, so one that is negative (the clock was set back) counts as stale rather + * than keeping the catalog for as long as the clock went back. A failed read drops whatever is + * kept, at worst one read newer than it, which costs one more read. + */ #keptViewCatalog(session: DispatchSession): Promise { const now = this.options.clock.now(); const kept = this.#viewCatalog; - if (kept !== undefined && now - kept.readAt < WORKER_VIEW_REFRESH_INTERVAL_MS) { + const age = kept === undefined ? undefined : now - kept.readAt; + if ( + kept !== undefined && + age !== undefined && + age >= 0 && + age < WORKER_VIEW_REFRESH_INTERVAL_MS + ) { return kept.catalog; } const catalog = Promise.resolve(this.#catalogGet({}, session)); - const entry = { catalog, readAt: now }; - this.#viewCatalog = entry; + this.#viewCatalog = { catalog, readAt: now }; catalog.catch(() => { - if (this.#viewCatalog === entry) this.#viewCatalog = undefined; + this.#viewCatalog = undefined; }); return catalog; } diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index a8fb342ce..bebb7656f 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -40,6 +40,7 @@ import { } from "../ports/index.js"; import { DAEMON_PROTOCOL_VERSION } from "../daemon-protocol/index.js"; import { DaemonEndpointHost, type ConnectionHost } from "./connection-host.js"; +import { Dispatcher } from "./dispatcher.js"; import { describeLeaseRequestFailure } from "./error-code.js"; import { AdminAuthenticationFailedError, type SessionRoleResolver } from "./session.js"; import { DaemonServer } from "./server.js"; @@ -1691,6 +1692,16 @@ describe("DaemonServer lease liveness (ADR 0004)", () => { await client.close(); }); + it("disposes the worker's dispatcher, ending its bus subscriptions, when the daemon stops", async () => { + const harness = await createHarness({ resolveRole: { resolve: () => "admin" } }); + const dispose = vi.spyOn(Dispatcher.prototype, "dispose"); + + await harness.daemon.stop("test"); + + expect(dispose).toHaveBeenCalledTimes(1); + dispose.mockRestore(); + }); + it("answers worker.install-component with UNSUPPORTED_IN_WORKER_MODE: a worker has no workers to install on", async () => { const harness = await createHarness({ resolveRole: { resolve: () => "admin" } }); const client = await createClient(harness.socketPath); diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 53d360850..cb6abb6ae 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -335,6 +335,8 @@ export class DaemonServer { */ readonly #parkedDispatches = new Set>(); readonly #dispatcher: ContractDispatcher; + /** The worker's own dispatcher, held to dispose on stop; absent on a gateway. */ + readonly #workerDispatcher: Dispatcher | undefined; readonly #resolveRole: SessionRoleResolver; /** * The worker engine, or `undefined` in gateway mode (ADR 0005 §33: a gateway has no @@ -363,10 +365,11 @@ export class DaemonServer { const engine: DaemonServerEngineOptions = options; this.#engine = engine; this.#ownerRoutedFacts = new OwnerRoutedFactBus(options.eventBus, engine.registry); - this.#dispatcher = buildDispatcher(options, { + this.#workerDispatcher = buildDispatcher(options, { awaitReady: () => this.#awaitReady(), health: () => this.#health, }); + this.#dispatcher = this.#workerDispatcher; } else { // Gateway mode (ADR 0005 §32): the handlers come ready-made, and there is no engine to // hold. Owner-routed facts are inert here, deliberately: the gateway issues no leases of @@ -611,6 +614,7 @@ export class DaemonServer { this.options.eventBus.emit("daemon.stopping", { reason }, "daemon"); for (const unsubscribe of this.#unsubscribeLeaseLost.splice(0)) unsubscribe(); this.#ownerRoutedFacts.dispose(); + this.#workerDispatcher?.dispose(); this.#engine?.reaper.dispose(); this.#engine?.healthMonitor?.dispose(); // ADR 0004 §3: a stop releases nothing. Every lease persists with its deadline, and the diff --git a/src/gateway/worker-link.ts b/src/gateway/worker-link.ts index 0e1084b95..e90af7c21 100644 --- a/src/gateway/worker-link.ts +++ b/src/gateway/worker-link.ts @@ -16,7 +16,12 @@ * admin, so the gateway may read it. */ import type { EventBus, EventName } from "../bus/index.js"; -import { grantedDeviceSchema, isSimlockError, workerViewFields } from "../contract/index.js"; +import { + grantedDeviceSchema, + isSimlockError, + WORKER_VIEW_CATALOG_EVENTS, + workerViewFields, +} from "../contract/index.js"; import type { SimlockAdminClient } from "../admin/index.js"; import { connectSimlockAdmin } from "../admin/index.js"; import type { AcceptedUplink, Clock, IpcConnection, Logger } from "../ports/index.js"; @@ -487,7 +492,9 @@ export class WorkerLink { this.options.eventBus.emit(envelope.event as EventName, payload as never, envelope.module); // ADR 0010 §7: an installed component is a new catalog entry, so that refresh re-reads it. if (changesCapacityOrLeases(envelope.event)) - void this.refresh({ includeCatalog: envelope.event === "component.installed" }); + void this.refresh({ + includeCatalog: (WORKER_VIEW_CATALOG_EVENTS as readonly string[]).includes(envelope.event), + }); } }