diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 718df5fd8..248e76f4d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -99,6 +99,93 @@ modes](#gateway-and-worker-modes-adr-0005) below for that topology. - **Daemon**: owns all state, serializes all decisions. Started on demand, reachable over a unix socket. +## Gateway and worker modes (ADR 0005) + +`config.mode` selects what a daemon *is*. Everything above describes a +**worker**: the default, and what every simlock daemon was before ADR 0005 — +it owns the devices on one machine. A **gateway** owns no devices at all. +Workers connect *to* it, and it fronts them: + +``` + ┌──────────────── gateway (mode: "gateway") ─────────────┐ +agent / console ──token auth──> │ HTTP frontend + unix socket │ + │ GatewayDispatcher ── worker views ──┐ │ + └──────────────────────────────────────┼─────────────────┘ + ▲ one inbound port │ + uplink ────┘ (ws upgrade on │ status.get, list.get, + (worker dials out) /v1/uplink) │ catalog.get, config.get, + ▲ ▼ events.subscribe + ┌────────────────────────────────┴─────┐ ┌───────────────────────────────┐ + │ worker (mode: "worker", the default) │ │ worker │ + │ drivers · registry · capacity · … │ │ … │ + └──────────────────────────────────────┘ └───────────────────────────────┘ +``` + +- **Workers dial out; the gateway never reaches in.** The only inbound port in + a fleet is the gateway's, so a worker behind NAT, on a laptop, or on a CI + runner joins with two config keys: `gateway.url` (the gateway's base URL, + from which `/v1/uplink` is derived) and `gateway.token`, a join token minted + on the gateway with `simlock token create --role worker`. A `worker`-role + token opens an uplink and nothing else — it is `403` on every other `/v1` + route, and an `agent`/`operator` token is `403` at `/v1/uplink`. +- **The uplink carries the existing contract, with the gateway as the protocol + client.** It is the same newline-delimited JSON framing the unix socket uses, + upgraded from the gateway's own HTTP listener. The worker's `DaemonServer` + accepts it as one more connection and grants that session the `admin` role — + not because of the transport (ADR 0003 §5 forbids that), but because *this + daemon dialled out*, to the URL in its own config, with the token from that + same file, which the gateway verified before the connection existed. An + operator who does not want a gateway administering a machine removes two + config keys. +- **A gateway is a second implementation of the contract's handlers, not a + second contract** (`src/gateway/`). Same dispatch pipeline, same operation + declarations, same role checks; the handlers read *worker views* instead of a + registry and a lease engine. Every frontend — CLI, MCP, HTTP, + `simlock/client` — works against a gateway unchanged, because they only ever + see the contract. +- **A worker view** is what the gateway knows about one worker: id (the + worker's own `instance.json` identity), label, connection state + (`connected` / `disconnected` / `incompatible`), daemon health and version, + capacity per platform, download policy, queue depth, leases, devices, + catalog, drain state, and a last-seen timestamp. It is rebuilt over the + uplink — `status.get`, `list.get`, `catalog.get`, `config.get` and + `events.subscribe` on connect, a refresh on every worker event about a lease + or a device, and a slow periodic tick as a backstop — and never persisted. + A gateway restart re-derives every view from the workers that reconnect. +- **The uplink is the reachability signal**: no polling. A closed uplink flips + the view to `disconnected` immediately and keeps its last-known state, so a + machine that vanished holding a device is still visible. The view is + forgotten only when every lease on it has passed its deadline *and* + `gateway.disconnectedRetentionMs` (default 24 h) has elapsed, or when an + operator runs `simlock worker remove` — which refuses a worker that is still + connected. +- **Aggregation.** `status.get` on a gateway returns the same shape a worker + does — capacity summed over connected workers, every device and lease + carrying a `workerId`, the gateway's own queue depth — plus a `workers` + array of views and `daemon.mode: "gateway"`. `catalog.get` is the union of + the connected workers' catalogs, each model and runtime annotated with the + workers that have it. Worker events are republished on the gateway's bus + with `workerId` added, so `simlock events --follow` against a gateway shows + the fleet. +- **What a gateway does not do.** It starts no drivers, validates no device + roots, and runs no reaper, health monitor or capacity strategy; of the + config it reads only `mode`, `http.*`, `log.*`, `lease.*`, `eventBuffer.*` + and `gateway.*` (worker-only keys warn and are ignored). It always listens + on HTTP — that is how agents reach it and what the uplink upgrades from — so + `http.enabled: false` in gateway mode fails the start rather than being + silently overridden. `nuke.run`, `cleanup.run`, `doctor.run` and + `driver.passthrough` answer `UNSUPPORTED_IN_GATEWAY_MODE` permanently: they + act on one machine's devices, and stay per-worker. The lease lifecycle + (`lease.request`/`renew`/`release`/`cancel`/`release-all`) and `device.exec` + answer the same code until the fleet queue and routing land; reads — + `lease.list`, + `list.get`, `status.get`, `catalog.get`, `events.*` — already answer for the + whole fleet. +- **The one piece of persisted gateway state** is the drained set + (`workers.json`, owner-only): drain is an operator's decision about a + machine, not a fact the machine reports, so it must survive both the + reconnect an operator is about to cause and a gateway restart. + ## Contract, dispatcher, and roles (ADR 0003) Every daemon operation is declared exactly once, in `src/contract/`: a name diff --git a/docs/CLI.md b/docs/CLI.md index d8a0ee38a..67c2d7078 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -866,13 +866,21 @@ A device currently `provisioning` or `reclaiming` carries a derived and `list --devices` well before it crosses the threshold that would make `doctor` flag it as stalled. -Human-oriented overview: daemon health, managed capacity (used/limit per -platform), running and reserved capacity (globally and per platform), every -managed device with its state, current leases (who — the agent id, see [Agent -identity](#agent-identity) — since when, and when each was last renewed), and -queue depth. `--json` for the structured equivalent. `overLimit` is true when a -lowered limit cannot yet be met, for example because active leases consume all -running slots. +Human-oriented overview: daemon health *and mode*, managed capacity +(used/limit per platform), running and reserved capacity (globally and per +platform), every managed device with its state, current leases (who — the agent +id, see [Agent identity](#agent-identity) — since when, and when each was last +renewed), and queue depth. `--json` for the structured equivalent. `overLimit` +is true when a lowered limit cannot yet be met, for example because active +leases consume all running slots. + +Against a **gateway** (`config.mode: "gateway"`, ADR 0005) the same command +answers for the whole fleet, in the same shape: the daemon line reads +`running (gateway)`, capacity is summed across the connected workers, one line +per worker precedes the devices, and every device and lease names the worker it +lives on (`Device dev_7 on wrk_a: leased`). `--json` gains a `workers` array of +[worker views](#simlock-worker-listdrainundrainremove) and a `workerId` on each +device and lease; `daemon.mode` says which kind of daemon answered. The daemon block carries `mode` (`"worker"` or `"gateway"`) — the one field that tells a client which kind of daemon answered. Against a **gateway** the @@ -893,6 +901,13 @@ agent id (see [Agent identity](#agent-identity)) that holds it, and its `lastRenewedAt` is when the lease was last renewed (set at grant, then on every renew) — the same field `status` renders as "last renewed". +Against a gateway, `--devices` and `--leases` list the whole fleet with a +`workerId` on every row. The device rows are the narrower shape `status` +returns rather than a worker's full registry records: a gateway has never held +a device's driver address or a driver's private data, and does not invent one. +`--rules` lists nothing on a gateway — cleanup rules are a machine's own +configuration, and a gateway runs no reaper. + ## `simlock catalog [--platform ] [--json]` Lists what can actually be leased, so an agent can pick a valid `--device` @@ -1015,7 +1030,10 @@ connected are not backfilled. ## `simlock daemon ` Manage the daemon explicitly. Other commands auto-start it on demand; `daemon` -exists for operators and debugging. `stop` does not touch leases: they persist, +exists for operators and debugging. `start` starts whichever mode +`config.mode` selects — a worker (the default) or a gateway (ADR 0005) — and +`status` reports it, both in the human line (`Daemon: running (gateway)`) and +as `daemon.mode` under `--json`. `stop` does not touch leases: they persist, and the next daemon restores each one's TTL timer from its deadline. What a stop does end is the connections to it — a running `simlock lease` cannot reconnect, so it exits `1` with a `DAEMON_CONNECTION_LOST` line naming a lease @@ -1050,6 +1068,39 @@ handled errors. Growth is bounded: once the file passes `log.rotateBytes` it is rotated to `daemon.log.1` (replacing any previous generation), so `logs` always shows the current file with the immediately preceding one prepended. +## `simlock worker ` + +The operator's view of a fleet (ADR 0005). 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. + +- `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 + label if it set one, connection state, capacity, and how many leases it + holds. A worker the gateway cannot speak to shows `incompatible` with both + protocol ranges, which is what version skew looks like from here. `--json` + prints the raw worker views, which is what the console renders. +- `drain ` / `undrain ` — a drained worker keeps its + existing leases and receives no new dispatches: the way to take a machine + out of service without killing anyone's device. The flag is persisted by the + gateway, so it survives both the worker's reconnect and a gateway restart — + draining a machine and then rebooting it does not quietly put it back into + rotation. Both are idempotent; an id the gateway has no view of is + `UNKNOWN_WORKER` (exit 12). +- `remove ` — forgets a **disconnected** worker's view. A connected + one is refused with `WORKER_CONNECTED` (exit 2): it would announce itself + again on its very next frame. An id with no view answers + `{"removed":false}` rather than failing — forgetting something already + forgotten is done, not an error. A view is also forgotten automatically once + every lease on it has passed its deadline and + `gateway.disconnectedRetentionMs` (default 24 h) has elapsed. + +```console +$ simlock worker list +wrk_9f2c (mac-mini-1): connected -- ios 1/2, android 0/1, 1 lease(s) +wrk_4a10 (ci-runner-3): disconnected, drained -- ios 0/4, android 0/2, 0 lease(s) +``` + ## `simlock config [get |set ]` Show the effective configuration (defaults + config file + overrides): the @@ -1120,6 +1171,19 @@ are daemon operations (admin role) — the daemon is the only process that ever reads or writes `tokens.json`; the CLI is a thin client over the same `simlock/admin` connection every other admin command uses. +Three roles: + +- `agent` — the ordinary HTTP bearer token; one token is one requester. +- `operator` — everything an agent can do, plus the admin-only routes; also + accepted as the admin credential at `hello` (see + [admin credential resolution](#admin-credential-resolution)). +- `worker` — a **join token** (ADR 0005): minted on a *gateway* and put in a + worker's `gateway.token`. It authorizes exactly one thing, opening an uplink + at `GET /v1/uplink`, and is `403` on every other `/v1` route; conversely an + `agent` or `operator` token is `403` at `/v1/uplink`. Revoking one closes the + uplink, and the worker keeps retrying at its backoff cap until an operator + mints a replacement. + `create` prints the minted secret **once**, alongside the token record: ```json diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 2522ce23e..f3c47dc4a 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -28,6 +28,11 @@ a warning. Inspect the effective, merged configuration at any time with | `http.host` | Address the HTTP listener binds. `127.0.0.1` keeps it loopback-only; reaching it remotely is the operator's own tunnel (Tailscale, cloudflared, reverse proxy) — Simlock does no TLS termination in v1. | `127.0.0.1` | | `http.port` | Port the HTTP listener binds. Must be an integer `1`-`65535`. | `4700` | | `exec.timeoutMs` | How long a single `device.exec` command (the remote half of `simlock simctl` / `simlock adb` — see [CLI.md](CLI.md#reaching-a-leased-device)) may run before Simlock kills it and fails the call with `EXEC_TIMEOUT`. Output is streamed, never buffered, so there is no size limit to go with it. | `10 minutes` | +| `gateway.url` | **Worker side.** The gateway's base URL (`ws://host:port` or `wss://...`); the worker derives the uplink endpoint (`/v1/uplink`) from it. Set together with `gateway.token`, or not at all. | unset (this worker has no gateway) | +| `gateway.token` | **Worker side.** The join token this worker presents, minted on the gateway with `simlock token create --role worker`. | unset | +| `gateway.label` | **Worker side.** Display name for this worker in the gateway's views. Need not be unique, and is never used to route. | unset (views show the worker's id) | +| `gateway.disconnectedRetentionMs` | **Gateway side.** How long a disconnected worker's view is kept before the gateway forgets it. The clock only applies once every lease on that view has passed its deadline. | `24 hours` | +| `gateway.execTimeoutMs` | **Gateway side.** Backstop on a proxied `device.exec`, deliberately longer than the worker's own `exec.timeoutMs`, which is the authoritative one. | `11 minutes` | | `diskPressure.freeBytesThreshold` | Free disk space below which Simlock treats the machine as under disk pressure. | `10 GiB` | | `eventBuffer.capacity` | Number of business events kept in the in-memory ring buffer (see `simlock events`). | `1000` | | `health.enabled` | Master switch for leased-device crash detection and recovery. | `true` | @@ -55,21 +60,23 @@ must be non-negative numbers (milliseconds and bytes, respectively). `stalledTransition.minimumThresholdMs` must be a non-negative number. `http.enabled` is a boolean, `http.host` a string, and `http.port` an integer in `1`-`65535`. +`mode` is `worker` or `gateway`; `gateway.url`, `gateway.token` and +`gateway.label` are strings, and `gateway.disconnectedRetentionMs` and +`gateway.execTimeoutMs` positive numbers. `ios.slim.enabled` is a boolean, `ios.slim.categories` an array of non-empty strings, and `ios.slim.bootTimeoutMs` a positive number. `mode` must be exactly `"worker"` or `"gateway"`. `gateway.url` must be an absolute `ws`/`wss` URL — `http`/`https` are rejected — and `gateway.token` a non-empty string; **in `mode: "worker"`**, setting either without the other is rejected at load and the daemon does not start, because a half-configured -uplink would -otherwise come up looking like an ordinary standalone worker. That rule does +uplink would otherwise come up looking like an ordinary standalone worker. That rule does not apply in `mode: "gateway"`, where both keys are worker-side and are warned about and ignored like every other worker key — a gateway is not misconfigured by leftovers from the config it was flipped out of. `gateway.label` is a non-empty string, `gateway.routing` one of the registered routing policies, and `exec.timeoutMs`, `gateway.execTimeoutMs`, -and `gateway.disconnectedRetentionMs` positive numbers. **`mode: "gateway"` with -`http.enabled: false` is rejected at load** (ADR 0005 §2), naming the key: a +and `gateway.disconnectedRetentionMs` positive numbers. +**`mode: "gateway"` with `http.enabled: false` is rejected at load** (ADR 0005 §2), naming the key: a gateway is the fleet's contact point over HTTP, so one nothing can reach has no safe reading. `lease.defaultTtlMs` and `lease.maxTtlMs` must be positive numbers, and @@ -89,6 +96,49 @@ explicit smaller `--ttl`, and the new width sticks from then on. See [CLI.md](CLI.md#simlock-config-get-keyset-key-value) for the `simlock config` command itself. +## Gateway and worker modes + +`mode` selects what `simlock daemon start` starts ([ADR +0005](adr/0005-gateway-and-worker-modes.md)). The default, `worker`, is what +every simlock daemon has always been. `gateway` is a daemon that owns no +devices and fronts the workers connected to it — see +[ARCHITECTURE.md](ARCHITECTURE.md#gateway-and-worker-modes-adr-0005). + +**Joining a fleet takes two keys on the worker**, and they are required +together: `gateway.url` (the gateway's base URL) and `gateway.token` (a join +token minted on the gateway with `simlock token create --role worker`). One +without the other fails the start naming the missing key — a worker that +silently never joined would look exactly like one whose gateway is down. +`gateway.url` must be a `ws://` or `wss://` URL, checked at load rather than +at dial time, so a typo names the key instead of surfacing as an endless +reconnect loop. Nothing else about the worker changes: it keeps serving its +local agents whether or not its gateway is reachable, and `http.enabled` stays +off by default. + +**A gateway reads a deliberately small slice of this file**: `mode`, `http.*`, +`log.*`, `lease.*`, `eventBuffer.*` and `gateway.*`. Every other key — +capacity, drivers, downloads, idle, warmPool, health, ios, stalledTransition — +configures devices, which a gateway does not have; each one present in a +gateway's config is reported with a warning and ignored, the same treatment an +unknown key gets. The worker-side `gateway.url`/`token`/`label` are warned +about there too. Nothing is stripped: the same file can be copied between a +worker and a gateway with only `mode` differing, and the warning is what makes +the difference visible rather than silent. + +**`http.enabled` is not optional for a gateway.** It defaults to `true` in +gateway mode (it stays `false` for a worker), and an explicit `false` fails the +start naming the key. HTTP is how agents reach a fleet *and* what the worker +uplink upgrades from, so a gateway without it is a process nothing can reach +and no worker can join — quietly overriding the operator's value would be +worse than refusing it. Switching a daemon between modes is therefore a +two-key edit, `mode` and (if it was set) `http.enabled`. + +The gateway keeps one small file of its own beside `tokens.json`: +`workers.json`, owner-only, holding the ids of workers an operator has +drained. Drain is a decision about a machine rather than something the machine +reports, so it has to survive both the worker's reconnect and a gateway +restart; every other part of a worker view is rebuilt from the worker itself. + ### Retired `lease.*` keys [ADR 0004](adr/0004-ttl-first-leases-on-every-transport.md) collapsed the @@ -148,6 +198,15 @@ worker's**, or requests that the gateway happily accepts will fail on whichever machine they land on, which is the least debuggable version of this mistake. +The gateway does not enforce this for you — clamping its own cap to the +minimum of its workers' would make fleet policy shift as machines come and +go, and the gateway's cap is meant to be explicit policy, not a computed +minimum. What it does instead: when a worker's own reported `lease.maxTtlMs` +is below the gateway's, the gateway logs a warning naming the worker and +both values the moment that worker's view is built (at join, and again if +the mismatch changes on a later refresh) — loud enough to catch the +misconfiguration without silently overriding it. + Everything else — `capacity.*`, `idle.*`, `warmPool.*`, `health.*`, `stalledTransition.*`, `drivers.*`, `ios.slim.*`, `diskPressure.*`, `downloads.*`, and the worker-side `gateway.url`/`gateway.token`/ diff --git a/docs/EVENTS.md b/docs/EVENTS.md index 5c719bd5d..c2725e7a5 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -154,6 +154,34 @@ before it connected are not backfilled), and a worker's own `simlock events` keeps showing exactly what it always did, un-prefixed and unaware that anything is watching. +## Fleet (gateway mode) + +Emitted only by a daemon in gateway mode ([ADR +0005](adr/0005-gateway-and-worker-modes.md) §22), about the workers connected +to it. + +| Event | Payload (key fields) | Emitted when | Emitter | Status | +|---|---|---|---|---| +| `worker.connected` | worker id, label, worker's daemon version | a worker's uplink opened and its `hello` completed, so the gateway can drive it. A worker whose `hello` found no overlapping protocol range emits nothing: it is in the registry as `incompatible`, which is where an operator finds it | WorkerRegistry | implemented | +| `worker.rejected` | reason (unauthenticated/forbidden), worker id, label, occasionally a count | an uplink was turned away at the door, before any session existed: `unauthenticated` (401) for a missing or unrecognized join token — a revoked or mistyped one lands here — and `forbidden` (403) for a real token whose role is not `worker`. Version skew is deliberately not one of these: that uplink authenticated, so the worker enters the registry as `incompatible` and emits nothing. A refused peer proves no identity, so `workerId` and `label` are only what the connection claimed and may be absent. `count`, present only above one, is how many identical (reason, claimed id) refusals the *previous* coalescing window absorbed — a flood of refused dials collapses to one event per window rather than one per attempt, since the ring buffer they land in is bounded by count, not bytes | GatewayService | implemented | +| `worker.disconnected` | worker id, label, lease count | a worker's uplink closed. `leaseCount` is what its view still shows it holding — how much is stranded, and why the view is kept rather than dropped | WorkerRegistry | implemented | +| `worker.removed` | worker id, label, reason (operator/retention) | a disconnected worker's view was forgotten: by `simlock worker remove`, or because every lease on it had expired and `gateway.disconnectedRetentionMs` elapsed | WorkerRegistry | implemented | +| `worker.drain-started` | worker id, label | `simlock worker drain` flagged a worker: it keeps its leases and receives no new dispatches | WorkerRegistry | implemented | +| `worker.drain-ended` | worker id, label | `simlock worker undrain` cleared that flag | WorkerRegistry | implemented | + +Drain and undrain are idempotent, and an event is a fact about a *change*: +draining an already-drained worker succeeds and emits nothing. + +**A worker's own events are republished on the gateway's bus** with `workerId` +added to the payload, under their original names and with their original +emitting module — the fact happened in that worker's lease engine or reaper, +and rewriting either would make the audit trail lie about where. That is what +makes `simlock events` and `simlock events --follow` against a gateway a +fleet-wide view, and it is the one place a payload documented above arrives +with an extra field: additive, and only ever on a gateway. The six events in +this section are the gateway's own, and carry no `workerId` beyond the worker +they are about. + ## Conventions recap - Every event carries: `timestamp`, `event`, `payload`, emitting module. diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index d8cd4ff79..9d9c87b07 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -683,6 +683,10 @@ route it arrives as the stream's terminal `error` event — as does a `WORKER_UNREACHABLE` that only happens mid-stream. The status is what a client mapping the code without a route in front of it should use. +`404` also covers `UNKNOWN_WORKER` (body names the `workerId`) on the worker +routes. Where an error carries typed details, they are inlined beside `code` +and `message` — details are contract, message text is not. + ## Lifecycle semantics - **Daemon restart.** In-flight lease requests are in-memory and do not diff --git a/docs/adr/0005-gateway-and-worker-modes.md b/docs/adr/0005-gateway-and-worker-modes.md index 704da7da5..5bd082aec 100644 --- a/docs/adr/0005-gateway-and-worker-modes.md +++ b/docs/adr/0005-gateway-and-worker-modes.md @@ -178,11 +178,13 @@ physical machine. slow periodic tick as a backstop. `config.get` is read **once per connect** and not on the refresh path — config is daemon input, read at start, so a worker whose configuration changed has restarted and - reconnected anyway — and the gateway keeps exactly one field out of it: - the worker's effective `downloads.policy`, which the view carries and - routing (requirement 13) needs in order to know whether a worker may - install a missing runtime at all. It is a routing input, never an - override: the worker still clamps `allowDownload` through its own policy. + reconnected anyway — and the gateway keeps two fields out of it: the + worker's effective `downloads.policy`, which the view carries and routing + (requirement 13) needs in order to know whether a worker may install a + missing runtime at all (a routing input, never an override: the worker + still clamps `allowDownload` through its own policy); and the worker's own + `lease.maxTtlMs`, which the view also carries so the gateway can warn when + it is lower than the gateway's own (requirement 15). ### Worker registry (gateway side) @@ -283,7 +285,17 @@ physical machine. lease's width is decided at the gateway — but what it dispatches is an ordinary `lease.request`, so a worker with a lower cap still refuses it. Keep a gateway's `lease.maxTtlMs` at or below every worker's, or - requests the gateway accepts fail on whichever machine they land on. + requests the gateway accepts fail on whichever machine they land on. The + gateway warns rather than clamps: when a worker's view is built and its + own reported `lease.maxTtlMs` is below the gateway's, the gateway logs a + warning naming the worker and both values, at join and again if the + mismatch changes on a later refresh. It does not lower its own cap to + match — that would make a fleet's policy drift with whichever machines + happen to be connected, contradicting "a fleet lease's width is decided + at the gateway" two sentences up — so the requests already described + above still fail on the low-capped worker; the warning only makes the + cause visible where it was decided, rather than leaving an operator to + find it from the failures downstream. 16. A gateway lease id names its worker, so renew, release, and reads route without consulting any state of its own: it is the owning worker's id, then a `.`, then the worker's own lease id, and routing **splits on the diff --git a/docs/known-pitfalls.md b/docs/known-pitfalls.md index 0d60bba6c..919cf5985 100644 --- a/docs/known-pitfalls.md +++ b/docs/known-pitfalls.md @@ -803,6 +803,55 @@ dispatches without touching the leases anyone already holds. [ADR 0005](adr/0005-gateway-and-worker-modes.md) and recorded in [IDEAS.md](IDEAS.md#capacity-slices-reserved-for-the-gateway). +## A worker's claimed id is never verified against its join token + +`WORKER_ID_HEADER` (`x-simlock-worker-id`) travels on the WebSocket upgrade +request, alongside — but entirely independent of — the `Authorization: Bearer` +join token `authenticate` checks (ADR 0005 §4). A `worker`-role token proves +only that the *dial* is authorized to open an uplink; it says nothing about +which worker id the dial is entitled to claim, and nothing on the gateway's +side cross-checks the two. `GatewayService#accept` then keys everything — +`#links`, the registry's view, the drain flag — by that unverified claim, and +a reconnect under the same id is trusted to *be* a reconnect (`#accept` +closes the previous link and replaces it, exactly ADR 0005 §6's own +reconnect story). + +**The pitfall:** any holder of a valid `worker`-role join token — every +worker in the fleet shares one token per `simlock token create --role worker` +unless an operator mints one per machine — can dial claiming *any* worker id, +including one another real worker currently holds. `#accept`'s reconnect +logic cannot distinguish this from a genuine reconnect: it closes the real +worker's link, inherits its view and drain state under the new (impostor) +connection, and the real worker is evicted with no more warning than an +ordinary network blip would produce. Two smaller issues share the same root +cause: `workerId` is taken from an unauthenticated header before truncation +(`MAX_CLAIMED_FIELD_LENGTH`, P3), so two ids differing only past that length +collide as the same map key; and nothing filters non-printable characters out +of it before it reaches a view, a log line, or `simlock worker list`'s +output. + +**Why this is not fixed in the #117/#118 stack:** proving `workerId` against +the token would mean either binding one join token to one worker id at +`token create` time (a real workflow change — an operator names the worker +when minting its token, and a fleet that currently shares one token across +every machine cannot any more without minting per-machine ones first) or +having each worker generate and persist its own keypair and sign its claimed +id (a second credential mechanism beside the join token ADR 0005 already +specifies). Either is a real design decision for a later ADR, not a fix that +belongs inside a gateway-skeleton PR whose own scope is making the fleet +*visible* before it is routable. + +**Status:** accepted as a gap for v1, tracked here per `safety.md` rule 8 +("ownership proven not inferred") rather than left unrecorded. Mitigating +factors: exploiting it requires a real `worker`-role join token, which is +already the credential an operator hands only to machines meant to join the +fleet, and the blast radius is one worker's view and drain flag, not any +device a lease actually holds (leases stay the workers' own local business +until #118 routes them through the gateway). Truncation-driven id collisions +and non-printable `workerId`s are narrower, cheaper mitigations that do not +require the credential redesign above and are worth doing without waiting for +it. + ## `simlock simctl` / `simlock adb` can hang forever reading a piped stdin ADR 0005 §19c: a piped stdin is read to EOF first, then sent as `device.exec`'s diff --git a/e2e/contract-surface.test.ts b/e2e/contract-surface.test.ts index 9dd3ece73..db93eb3f5 100644 --- a/e2e/contract-surface.test.ts +++ b/e2e/contract-surface.test.ts @@ -1,9 +1,10 @@ import { describe, expect, it } from "vitest"; -import { OPERATIONS, type OperationName } from "../src/contract/index.js"; +import { GATEWAY_ONLY_OPERATIONS, 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 { withDaemon } from "./helpers/index.js"; +import { freeLoopbackPort, withDaemon } from "./helpers/index.js"; +import type { TestEnv } from "./helpers/env.js"; /** * The contract's own surface, checked against a daemon that is actually running. @@ -44,28 +45,27 @@ describe("contract surface", () => { */ const UNPARSEABLE_PAYLOAD = "not-an-object"; - it("answers every operation it declares, rather than falling through to UNKNOWN_REQUEST", async () => { - const env = await withDaemon(); - // The sweep talks to the daemon directly, so nothing here would start one implicitly the - // way `env.cli` does. - expect((await env.startDaemon()).code).toBe(0); + /** Every operation this sweep probes: the registry minus the one the transport intercepts. */ + function probedOperations(): OperationName[] { + const probed = Object.keys(OPERATIONS).filter( + (name) => !INTERCEPTED.has(name), + ) as OperationName[]; + // Guards the guard: if `INTERCEPTED` ever swallowed the registry, a sweep would pass by + // doing nothing at all. + expect(probed.length).toBeGreaterThan(15); + return probed; + } + /** The code each operation answers an unparseable payload with, keyed by operation. */ + async function sweep(env: TestEnv): Promise> { // The real client transport, not a hand-rolled one: `SimlockWire.call` takes the // operation name as a plain string, which is exactly what a sweep over the registry // needs and what the typed `SimlockClient` facade deliberately does not expose. const wire = new SimlockWire(await new NodeIpcTransport().connect(env.socketPath)); try { await wire.hello({ principal: "contract-surface-agent" }); - - const probed = Object.keys(OPERATIONS).filter( - (name) => !INTERCEPTED.has(name), - ) as OperationName[]; - // Guards the guard: if `INTERCEPTED` ever swallowed the registry, the loop below - // would pass by doing nothing at all. - expect(probed.length).toBeGreaterThan(15); - const answers = await Promise.all( - probed.map(async (name) => { + probedOperations().map(async (name) => { try { await wire.call(name, UNPARSEABLE_PAYLOAD); return [name, "accepted an unparseable payload"] as const; @@ -77,15 +77,52 @@ describe("contract surface", () => { } }), ); - - // Asserted as one object rather than per operation so a failure names every - // unreachable operation at once, instead of stopping at the first. - expect(Object.fromEntries(answers)).toEqual( - Object.fromEntries(probed.map((name) => [name, "BAD_REQUEST"])), - ); + return Object.fromEntries(answers); } finally { await wire.close(); } + } + + it("answers every operation it declares, rather than falling through to UNKNOWN_REQUEST", async () => { + const env = await withDaemon(); + // The sweep talks to the daemon directly, so nothing here would start one implicitly the + // way `env.cli` does. + expect((await env.startDaemon()).code).toBe(0); + + // 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. + expect(await sweep(env)).toEqual( + Object.fromEntries( + probedOperations().map((name) => [ + name, + (GATEWAY_ONLY_OPERATIONS as readonly string[]).includes(name) + ? "UNKNOWN_REQUEST" + : "BAD_REQUEST", + ]), + ), + ); + }); + + it("answers every operation on a gateway too, including the ones it refuses", async () => { + // ADR 0005 §32: the gateway is a second implementation of the same contract, reached + // through the same socket switch -- so it needs the same sweep. Every operation must parse + // its input before deciding anything, so even the ones a gateway answers + // `UNSUPPORTED_IN_GATEWAY_MODE` reject an unparseable payload with `BAD_REQUEST` first. + // Anything that came back `UNKNOWN_REQUEST` here would be an operation a gateway forgot. + const port = await freeLoopbackPort(); + const env = await withDaemon({ + configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, + driver: "none", + }); + expect((await env.startDaemon()).code).toBe(0); + + expect(await sweep(env)).toEqual( + Object.fromEntries(probedOperations().map((name) => [name, "BAD_REQUEST"])), + ); }); /** diff --git a/e2e/gateway-fleet.test.ts b/e2e/gateway-fleet.test.ts new file mode 100644 index 000000000..28889dfe5 --- /dev/null +++ b/e2e/gateway-fleet.test.ts @@ -0,0 +1,258 @@ +import { describe, expect, it } from "vitest"; + +import { freeLoopbackPort, waitFor, withDaemon } from "./helpers/index.js"; +import type { TestEnv } from "./helpers/env.js"; + +/** + * ADR 0005 #117 end to end, with real processes: a gateway daemon, two worker daemons that dial + * it over a real WebSocket, and the CLI an operator would actually use. + * + * What this flow proves that the unit suites cannot: the uplink is a real network connection on + * the gateway's own HTTP port, the join token is a real credential minted on the gateway and + * read from a worker's config file, and `simlock status` against the gateway aggregates two + * separate machines' registries. + */ + +interface WorkerView { + readonly id: string; + readonly label?: string; + readonly connection: "connected" | "disconnected" | "incompatible"; + readonly drained: boolean; + readonly capacity?: { readonly ios: { readonly limit: number } }; + readonly catalog: readonly { readonly platform: string; readonly models: readonly string[] }[]; +} + +interface StatusView { + readonly daemon: { readonly mode: string }; + readonly capacity: { readonly ios: { readonly limit: number } }; + readonly workers?: readonly WorkerView[]; +} + +async function listWorkers(gateway: TestEnv): Promise { + const result = await gateway.cli(["worker", "list", "--json"]); + expect(result.code).toBe(0); + return (result.json as { workers: WorkerView[] }).workers; +} + +/** Polls the *gateway*, never a worker: the gateway's own view is what this flow is about. */ +async function waitForWorkers( + gateway: TestEnv, + predicate: (workers: WorkerView[]) => boolean, + label: string, +): Promise { + let workers: WorkerView[] = []; + await waitFor( + async () => { + workers = await listWorkers(gateway); + return predicate(workers); + }, + { label, timeout: 30_000 }, + ); + return workers; +} + +/** A worker's per-platform limit, or 0 if the view has no capacity yet. Out here so the test + * body below stays a sequence of assertions rather than a chain of fallbacks. */ +function iosLimit(worker: WorkerView | undefined): number { + return worker?.capacity?.ios.limit ?? 0; +} + +/** The id of the worker an operator would recognize by `label`. Throws rather than degrading + * to `""`, which would silently turn "no such worker" into a request for one. */ +function idOf(workers: readonly WorkerView[], label: string): string { + const worker = workers.find((candidate) => candidate.label === label); + if (worker === undefined) throw new Error(`No worker labelled ${label}`); + return worker.id; +} + +function connectionOf(workers: readonly WorkerView[], label: string): string | undefined { + return workers.find((worker) => worker.label === label)?.connection; +} + +function iosModels(json: unknown): readonly string[] { + const platforms = (json as { platforms: { platform: string; models?: string[] }[] }).platforms; + return platforms.find((entry) => entry.platform === "ios")?.models ?? []; +} + +describe("gateway fleet", () => { + it("two workers join, status aggregates them, a kill disconnects one, drain flags the other", async () => { + const port = await freeLoopbackPort(); + // `driver: "none"`: a gateway starts no drivers and warns about every worker-only key in + // its config (ADR 0005 §2), so it gets no fake-driver wiring and no capacity seeding. + const gateway = await withDaemon({ + configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, + driver: "none", + }); + + // 1. The gateway mints a join token. `--role worker` is what makes it a join token and + // nothing else: it opens an uplink and no `/v1` route. + const minted = await gateway.cli(["token", "create", "--role", "worker"]); + expect(minted.code).toBe(0); + const { secret, token } = minted.json as { secret: string; token: { role: string } }; + expect(token.role).toBe("worker"); + + // 2. Two workers, each with its own SIMLOCK_HOME (and therefore its own instance identity), + // join with the same token and the gateway's base URL. + const fleetConfig = { gateway: { token: secret, url: `ws://127.0.0.1:${port}` } }; + const workerA = await withDaemon({ + configOverrides: { gateway: { ...fleetConfig.gateway, label: "worker-a" } }, + }); + await workerA.driverScript.set({ + ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, + }); + const workerB = await withDaemon({ + configOverrides: { gateway: { ...fleetConfig.gateway, label: "worker-b" } }, + }); + await workerB.driverScript.set({ + ios: { knownModels: ["iPhone 17"], availableOsVersions: ["18.4"] }, + }); + + const joined = await waitForWorkers( + gateway, + (workers) => + workers.length === 2 && workers.every((worker) => worker.connection === "connected"), + "both workers connected to the gateway", + ); + expect(joined.map((worker) => worker.label).sort()).toEqual(["worker-a", "worker-b"]); + // Two machines, two identities: the ids are the workers' own `instance.json`, never a name + // the gateway invented or a label an operator chose. + expect(new Set(joined.map((worker) => worker.id)).size).toBe(2); + + // 3. `simlock status` against the gateway is the same shape one machine returns, summed. + const status = await gateway.cli(["status", "--json"]); + expect(status.code).toBe(0); + const statusView = status.json as StatusView; + expect(statusView.daemon.mode).toBe("gateway"); + expect(statusView.workers).toHaveLength(2); + expect(iosLimit(joined[0])).toBeGreaterThan(0); + expect(statusView.capacity.ios.limit).toBe(iosLimit(joined[0]) + iosLimit(joined[1])); + + // 4. The catalog is the union, and says which worker each model came from. + await waitFor( + async () => { + const models = iosModels((await gateway.cli(["catalog", "--json"])).json); + return models.includes("iPhone 16") && models.includes("iPhone 17"); + }, + { label: "the gateway's catalog unions both workers", timeout: 30_000 }, + ); + const catalog = await gateway.cli(["catalog", "--json"]); + const iosCatalog = ( + catalog.json as { + platforms: { platform: string; modelWorkers?: Record }[]; + } + ).platforms.find((entry) => entry.platform === "ios"); + expect(iosCatalog?.modelWorkers?.["iPhone 16"]).toEqual([idOf(joined, "worker-a")]); + + // 5. Killing a worker flips its view without anyone polling it: the uplink closing *is* the + // signal (ADR 0005 §6). The gateway's own backstop tick is 30s, and this must not need + // it -- so a short deadline here is the assertion. + await workerA.killDaemon(); + const surviving = await waitForWorkers( + gateway, + (workers) => connectionOf(workers, "worker-a") === "disconnected", + "the killed worker's view flipped to disconnected", + ); + // The other worker is untouched, and the dead one's view is kept rather than dropped. + expect(surviving).toHaveLength(2); + expect(connectionOf(surviving, "worker-b")).toBe("connected"); + + // 6. Draining flags the surviving worker (what #118's dispatch will honour), and the flag + // is on the view an operator reads back. + const workerBId = idOf(surviving, "worker-b"); + const drain = await gateway.cli(["worker", "drain", workerBId]); + expect(drain.code).toBe(0); + expect(drain.json).toEqual({ drained: true, workerId: workerBId }); + expect((await listWorkers(gateway)).find((worker) => worker.id === workerBId)?.drained).toBe( + true, + ); + + // 7. Removing a *connected* worker is refused; the disconnected one is forgotten. + const refused = await gateway.cli(["worker", "remove", workerBId]); + expect(refused.error?.code).toBe("WORKER_CONNECTED"); + const workerAId = idOf(surviving, "worker-a"); + const removed = await gateway.cli(["worker", "remove", workerAId]); + expect(removed.code).toBe(0); + expect(await listWorkers(gateway)).toHaveLength(1); + + // 8. A worker's own *business* events -- not just the gateway's own connect/disconnect + // facts, which carry `workerId` too and would pass this check even with republishing + // (`WorkerLink#onWorkerEvent`) deleted outright -- reach the gateway's buffer with + // `workerId` attached, which is what makes `simlock events` against a gateway a + // fleet-wide view (ADR 0005 §22). Driven deterministically: a real `lease.granted` on + // worker B's own daemon, requested directly against its socket (routing across the + // fleet is #118's, not this PR's), well after its `events.subscribe` was established at + // connect. `module` is asserted as `lease-lifecycle` -- the emitting engine's own name, + // unchanged by republishing -- specifically because it is not one of the six subjects + // `docs/EVENTS.md` calls "the gateway's own" (`worker.*`), so this cannot be satisfied by + // a gateway-authored fact that merely happens to name worker B. + const events = await gateway.events(); + const connectedFacts = events.filter((event) => event.event === "worker.connected"); + expect(connectedFacts).toHaveLength(2); + + const held = workerB.cliBackground([ + "lease", + "--platform", + "ios", + "--device", + "iPhone 17", + "--os", + "18.4", + "--agent-id", + "gw-fleet-c3", + ]); + const grant = JSON.parse(await held.firstStdoutLine()) as { lease: { id: string } }; + + await waitFor( + async () => { + const latest = await gateway.events(); + return latest.some( + (event) => + event.event === "lease.granted" && + event.module === "lease-lifecycle" && + (event.payload as { leaseId?: string; workerId?: string }).leaseId === grant.lease.id && + (event.payload as { workerId?: string }).workerId === workerBId, + ); + }, + { label: "worker B's own lease.granted republished onto the gateway's bus", timeout: 20_000 }, + ); + + held.kill("SIGTERM"); + await held.waitForExit(15_000); + + await workerB.cli(["daemon", "stop"]); + }); + + it("refuses an uplink whose token is not a worker join token", async () => { + const port = await freeLoopbackPort(); + const gateway = await withDaemon({ + configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, + driver: "none", + }); + // An operator token is a real credential that opens no uplink (ADR 0005 §25). The worker + // keeps retrying at its backoff cap rather than giving up, so what this asserts is the + // gateway's side: it never becomes a worker. + const operator = await gateway.cli(["token", "create", "--role", "operator"]); + const { secret } = operator.json as { secret: string }; + await withDaemon({ + configOverrides: { gateway: { token: secret, url: `ws://127.0.0.1:${port}` } }, + }); + + let rejected: { reason?: string; workerId?: string } | undefined; + await waitFor( + async () => { + const events = await gateway.events(); + rejected = events.find((event) => event.event === "worker.rejected")?.payload as + | { reason?: string; workerId?: string } + | undefined; + return rejected?.reason === "forbidden"; + }, + { label: "the gateway reported the refused uplink", timeout: 20_000 }, + ); + // M3: `workerId` is whatever the dial claimed in its headers over the real WebSocket + // adapter, not just the in-memory one the unit suite scripts -- an operator otherwise had + // no way to tell *which* machine's misconfigured worker keeps knocking. + expect(rejected?.workerId).toBeDefined(); + + expect(await listWorkers(gateway)).toEqual([]); + }); +}); diff --git a/e2e/helpers/env.ts b/e2e/helpers/env.ts index 5fc6ab798..0d861ebac 100644 --- a/e2e/helpers/env.ts +++ b/e2e/helpers/env.ts @@ -110,8 +110,11 @@ export interface WithDaemonOptions { * fake driver. "real" leaves driver discovery alone -- the daemon finds the real * iOS/Android drivers exactly as it would in production -- for the slow, real-SDK * lane; `driverScript`/`driverLog` are inert in that mode (nothing reads them). + * "none" wires no driver and seeds no driver-shaped config at all: what a + * `mode: "gateway"` daemon needs, since it starts no drivers and warns about every + * worker-only key it is given (ADR 0005 §2). */ - readonly driver?: "fake" | "real"; + readonly driver?: "fake" | "real" | "none"; } export interface TestEnv { @@ -169,7 +172,7 @@ export async function withDaemon(options: WithDaemonOptions = {}): Promise { * other test env on this machine is already using, and the alternative (a fixed port) fails * every parallel run rather than an unlucky one. */ -async function freeLoopbackPort(): Promise { +export async function freeLoopbackPort(): Promise { const server = createServer(); try { const port = await new Promise((resolve) => { diff --git a/e2e/helpers/index.ts b/e2e/helpers/index.ts index d53feab6c..50b25ce06 100644 --- a/e2e/helpers/index.ts +++ b/e2e/helpers/index.ts @@ -2,7 +2,7 @@ // through this barrel -- add an export here (from its owning helper module) the // moment a flow needs it, rather than pre-declaring the full internal surface, so an // unused re-export is always a real signal. -export { withDaemon } from "./env.js"; +export { freeLoopbackPort, withDaemon } from "./env.js"; // A flow that factors its own setup out of a test body needs to name what `withDaemon` hands // back; every other flow keeps it inferred. export type { TestEnv } from "./env.js"; diff --git a/package.json b/package.json index 31c3da1c1..4045b631c 100644 --- a/package.json +++ b/package.json @@ -58,11 +58,13 @@ "@hono/zod-validator": "^0.9.1", "@modelcontextprotocol/sdk": "1.29.0", "hono": "^4.13.5", + "ws": "8.18.3", "zod": "^3.25.76" }, "devDependencies": { "@release-it/conventional-changelog": "^11.0.1", "@types/node": "^26.1.1", + "@types/ws": "8.18.1", "fallow": "^3.6.0", "lefthook": "^2.1.10", "oxfmt": "^0.59.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 665bbb9db..56101d99e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1,202 +1,3 @@ ---- -lockfileVersion: '9.0' - -importers: - - .: - configDependencies: {} - packageManagerDependencies: - '@pnpm/exe': - specifier: ^11.9.0 - version: 11.22.0 - pnpm: - specifier: ^11.9.0 - version: 11.22.0 - -packages: - - '@pnpm/exe@11.22.0': - resolution: {integrity: sha512-B1SGeKm+v9pX9YkzMmrnO2FbgBd8TDwzZ3jSj6J6ThxdyGvI4TsOfMeHARW4Wb25visPpmMDfIXrU76EZdJM4g==} - hasBin: true - - '@pnpm/linux-arm64@11.22.0': - resolution: {integrity: sha512-xzzn3jYG9QaiFZPaHcWM3yX4Fm9UGz5E42mzpbvUEvXYf5O9fwNolenOhGLpRl2qS5u35fjZSvDZbWlOwHMcug==} - cpu: [arm64] - os: [linux] - - '@pnpm/linux-x64@11.22.0': - resolution: {integrity: sha512-isvaPctGinbsM2hsTtRsMarN8Sr5QhXDTNmn8Xv9Lp1PjincCvH2RBbhpo+xYIOxzgls1dtQSdgoORUbfRVALQ==} - cpu: [x64] - os: [linux] - - '@pnpm/linuxstatic-arm64@11.22.0': - resolution: {integrity: sha512-i4J+AQWW0T3JBdXaLsvxu8ZmMG1HLS6JZQESdOR9uBv8Zumb4yg8GYT83eWRLacr6ngVdhEBiC3W4eOG64MFbA==} - cpu: [arm64] - os: [linux] - libc: [musl] - - '@pnpm/linuxstatic-x64@11.22.0': - resolution: {integrity: sha512-QYzk8jhSuSbVthW/OxEOhU3f3zhjpw4HqgedrlwbVNb7btCWn5del2Hb5PsYYka2PbmKq5EtF5IzYN8Yp1CfxQ==} - cpu: [x64] - os: [linux] - libc: [musl] - - '@pnpm/macos-arm64@11.22.0': - resolution: {integrity: sha512-Io8Axk5kutPgMuAfOg1QGj3J0/KpLvH5iiPcmp7up8D4q7BNWT02ndQo3RyGWqrlkf5nwspM41GFpWTShrZ4Aw==} - cpu: [arm64] - os: [darwin] - - '@pnpm/win-arm64@11.22.0': - resolution: {integrity: sha512-QgaRuKGQKov7xW2utPCgDT83fn/PU5cD6HFgib48oTslz7wv26E89d4jMCxL4GRmEL2YCfkYuj5ITj1oVWg5WQ==} - cpu: [arm64] - os: [win32] - - '@pnpm/win-x64@11.22.0': - resolution: {integrity: sha512-iWYsiSwpgxqur+TwsnSoPdOQaEfd4ygB84mb5tJUOgim6PHr1xhKJBndaQzH+At/WkLxLdYN+K8dYc4M7naezg==} - cpu: [x64] - os: [win32] - - '@reflink/reflink-darwin-arm64@0.1.19': - resolution: {integrity: sha512-ruy44Lpepdk1FqDz38vExBY/PVUsjxZA+chd9wozjUH9JjuDT/HEaQYA6wYN9mf041l0yLVar6BCZuWABJvHSA==} - engines: {node: '>= 10'} - cpu: [arm64] - os: [darwin] - - '@reflink/reflink-darwin-x64@0.1.19': - resolution: {integrity: sha512-By85MSWrMZa+c26TcnAy8SDk0sTUkYlNnwknSchkhHpGXOtjNDUOxJE9oByBnGbeuIE1PiQsxDG3Ud+IVV9yuA==} - engines: {node: '>= 10'} - cpu: [x64] - os: [darwin] - - '@reflink/reflink-linux-arm64-gnu@0.1.19': - resolution: {integrity: sha512-7P+er8+rP9iNeN+bfmccM4hTAaLP6PQJPKWSA4iSk2bNvo6KU6RyPgYeHxXmzNKzPVRcypZQTpFgstHam6maVg==} - engines: {node: '>= 10'} - cpu: [arm64] - os: [linux] - libc: [glibc] - - '@reflink/reflink-linux-arm64-musl@0.1.19': - resolution: {integrity: sha512-37iO/Dp6m5DDaC2sf3zPtx/hl9FV3Xze4xoYidrxxS9bgP3S8ALroxRK6xBG/1TtfXKTvolvp+IjrUU6ujIGmA==} - engines: {node: '>= 10'} - cpu: [arm64] - os: [linux] - libc: [musl] - - '@reflink/reflink-linux-x64-gnu@0.1.19': - resolution: {integrity: sha512-jbI8jvuYCaA3MVUdu8vLoLAFqC+iNMpiSuLbxlAgg7x3K5bsS8nOpTRnkLF7vISJ+rVR8W+7ThXlXlUQ93ulkw==} - engines: {node: '>= 10'} - cpu: [x64] - os: [linux] - libc: [glibc] - - '@reflink/reflink-linux-x64-musl@0.1.19': - resolution: {integrity: sha512-e9FBWDe+lv7QKAwtKOt6A2W/fyy/aEEfr0g6j/hWzvQcrzHCsz07BNQYlNOjTfeytrtLU7k449H1PI95jA4OjQ==} - engines: {node: '>= 10'} - cpu: [x64] - os: [linux] - libc: [musl] - - '@reflink/reflink-win32-arm64-msvc@0.1.19': - resolution: {integrity: sha512-09PxnVIQcd+UOn4WAW73WU6PXL7DwGS6wPlkMhMg2zlHHG65F3vHepOw06HFCq+N42qkaNAc8AKIabWvtk6cIQ==} - engines: {node: '>= 10'} - cpu: [arm64] - os: [win32] - - '@reflink/reflink-win32-x64-msvc@0.1.19': - resolution: {integrity: sha512-E//yT4ni2SyhwP8JRjVGWr3cbnhWDiPLgnQ66qqaanjjnMiu3O/2tjCPQXlcGc/DEYofpDc9fvhv6tALQsMV9w==} - engines: {node: '>= 10'} - cpu: [x64] - os: [win32] - - '@reflink/reflink@0.1.19': - resolution: {integrity: sha512-DmCG8GzysnCZ15bres3N5AHCmwBwYgp0As6xjhQ47rAUTUXxJiK+lLUxaGsX3hd/30qUpVElh05PbGuxRPgJwA==} - engines: {node: '>= 10'} - - detect-libc@2.1.2: - resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} - engines: {node: '>=8'} - - pnpm@11.22.0: - resolution: {integrity: sha512-H/hwxMYTPf2I+yr8Rt0T1H8JyXlLQ4xv20fKmMrzvBY4HuC+k6CRuOOCTPAfiJ9G19niCRD7C+GrD7W6qA3WIQ==} - engines: {node: '>=22.13'} - hasBin: true - -snapshots: - - '@pnpm/exe@11.22.0': - dependencies: - '@reflink/reflink': 0.1.19 - detect-libc: 2.1.2 - optionalDependencies: - '@pnpm/linux-arm64': 11.22.0 - '@pnpm/linux-x64': 11.22.0 - '@pnpm/linuxstatic-arm64': 11.22.0 - '@pnpm/linuxstatic-x64': 11.22.0 - '@pnpm/macos-arm64': 11.22.0 - '@pnpm/win-arm64': 11.22.0 - '@pnpm/win-x64': 11.22.0 - - '@pnpm/linux-arm64@11.22.0': - optional: true - - '@pnpm/linux-x64@11.22.0': - optional: true - - '@pnpm/linuxstatic-arm64@11.22.0': - optional: true - - '@pnpm/linuxstatic-x64@11.22.0': - optional: true - - '@pnpm/macos-arm64@11.22.0': - optional: true - - '@pnpm/win-arm64@11.22.0': - optional: true - - '@pnpm/win-x64@11.22.0': - optional: true - - '@reflink/reflink-darwin-arm64@0.1.19': - optional: true - - '@reflink/reflink-darwin-x64@0.1.19': - optional: true - - '@reflink/reflink-linux-arm64-gnu@0.1.19': - optional: true - - '@reflink/reflink-linux-arm64-musl@0.1.19': - optional: true - - '@reflink/reflink-linux-x64-gnu@0.1.19': - optional: true - - '@reflink/reflink-linux-x64-musl@0.1.19': - optional: true - - '@reflink/reflink-win32-arm64-msvc@0.1.19': - optional: true - - '@reflink/reflink-win32-x64-msvc@0.1.19': - optional: true - - '@reflink/reflink@0.1.19': - optionalDependencies: - '@reflink/reflink-darwin-arm64': 0.1.19 - '@reflink/reflink-darwin-x64': 0.1.19 - '@reflink/reflink-linux-arm64-gnu': 0.1.19 - '@reflink/reflink-linux-arm64-musl': 0.1.19 - '@reflink/reflink-linux-x64-gnu': 0.1.19 - '@reflink/reflink-linux-x64-musl': 0.1.19 - '@reflink/reflink-win32-arm64-msvc': 0.1.19 - '@reflink/reflink-win32-x64-msvc': 0.1.19 - - detect-libc@2.1.2: {} - - pnpm@11.22.0: {} - ---- lockfileVersion: '9.0' settings: @@ -223,6 +24,9 @@ importers: hono: specifier: ^4.13.5 version: 4.13.5 + ws: + specifier: 8.18.3 + version: 8.18.3 zod: specifier: ^3.25.76 version: 3.25.76 @@ -233,6 +37,9 @@ importers: '@types/node': specifier: ^26.1.1 version: 26.1.1 + '@types/ws': + specifier: 8.18.1 + version: 8.18.1 fallow: specifier: ^3.6.0 version: 3.6.0 @@ -927,6 +734,9 @@ packages: resolution: {integrity: sha512-EULJ8LApcVEPbrfND0cRQqutIOdiIgJ1Mgrhpy755r14xMohPTEpkV/k28SJvuOs9bHRFW8x+KeDAEPiGQPB9Q==} deprecated: This is a stub types definition. parse-path provides its own type definitions, so you do not need this installed. + '@types/ws@8.18.1': + resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==} + '@typescript/typescript-aix-ppc64@7.0.2': resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==} engines: {node: '>=16.20.0'} @@ -2327,6 +2137,18 @@ packages: wrappy@1.0.2: resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} + ws@8.18.3: + resolution: {integrity: sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==} + engines: {node: '>=10.0.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: '>=5.0.2' + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + wsl-utils@0.3.1: resolution: {integrity: sha512-g/eziiSUNBSsdDJtCLB8bdYEUMj4jR7AGeUo96p/3dTafgjHhpF4RiCFPiRILwjQoDXx5MqkBr4fwWtR3Ky4Wg==} engines: {node: '>=20'} @@ -2837,6 +2659,10 @@ snapshots: dependencies: parse-path: 7.1.0 + '@types/ws@8.18.1': + dependencies: + '@types/node': 26.1.1 + '@typescript/typescript-aix-ppc64@7.0.2': optional: true @@ -4169,6 +3995,8 @@ snapshots: wrappy@1.0.2: {} + ws@8.18.3: {} + wsl-utils@0.3.1: dependencies: is-wsl: 3.1.1 diff --git a/src/admin/index.ts b/src/admin/index.ts index ca61841cf..5264c8ba8 100644 --- a/src/admin/index.ts +++ b/src/admin/index.ts @@ -57,6 +57,12 @@ export type { TokenListOutput, TokenRevokeInput, TokenRevokeOutput, + WorkerDrainInput, + WorkerDrainOutput, + WorkerListOutput, + WorkerRemoveOutput, + WorkerUndrainOutput, + WorkerView, } from "../simlock-client/client.js"; export { isSimlockError, SimlockError } from "../simlock-client/client.js"; diff --git a/src/bus/index.test.ts b/src/bus/index.test.ts index 4e2ed83e7..e23adf5e1 100644 --- a/src/bus/index.test.ts +++ b/src/bus/index.test.ts @@ -152,6 +152,12 @@ describe("EventBus", () => { | "doctor.reconciled" | "driver.root-rejected" | "driver.adb-server-rejected" + | "worker.connected" + | "worker.rejected" + | "worker.disconnected" + | "worker.removed" + | "worker.drain-started" + | "worker.drain-ended" >(); expectTypeOf().toMatchTypeOf>(); }); diff --git a/src/bus/index.ts b/src/bus/index.ts index 4e6e04526..4211f146c 100644 --- a/src/bus/index.ts +++ b/src/bus/index.ts @@ -170,6 +170,68 @@ export interface EventMap { readonly reason: string; }; "doctor.reconciled": { readonly driftFindings: unknown }; + // ---- gateway facts (ADR 0005 §22) --------------------------------------------------------- + // + // Emitted only by a daemon in gateway mode, about the workers connected to it. A worker's own + // events are *republished* on the gateway's bus under their original names with `workerId` + // added to the payload, so `simlock events` against a gateway shows the fleet; these six are + // the facts only the gateway can know. + /** A worker's uplink opened and its `hello` completed: the gateway can now drive it. An + * uplink that authenticated but negotiated no protocol emits nothing at all (ADR 0005 §31): + * it is in the registry as `incompatible`, which is where an operator finds it. */ + "worker.connected": { + readonly workerId: string; + readonly label?: string; + readonly version?: string; + }; + /** + * An uplink was turned away at the door, before any session existed (ADR 0005 §4/§22). + * Two reasons, and they are the same two the rest of the API tells apart: + * `unauthenticated` (`401`) is a missing or unrecognized join token -- a revoked or mistyped + * one lands here -- and `forbidden` (`403`) is a real token whose role is not `worker`. + * + * Version skew is deliberately *not* one of these: a worker whose `hello` finds no + * overlapping protocol range authenticated fine, so it enters the registry as + * `incompatible` and emits nothing (§31). This event is only ever about the door. + * + * Every field but `reason` is optional because a dial that fails authentication proves no + * identity: `workerId` and `label` are whatever the connection *claimed* in its headers, and + * may be absent entirely. + * + * P-2: `count`, present only when greater than one, is how many identical (reason, claimed + * id) refusals the *previous* coalescing window absorbed before it closed, reported on the + * next matching refusal rather than this event's own (always singular) occurrence. + * `GatewayService` coalesces a flood of these into one emission per window rather than one per + * dial, since every refusal here is unauthenticated by definition and the ring buffer they + * land in is bounded by count, not bytes (P3): without coalescing, a loop of refused dials can + * evict every other fact an operator comes to `simlock events` for, including the very + * `worker.connected`/`worker.disconnected` lines explaining whatever outage they are + * debugging. + */ + "worker.rejected": { + readonly reason: "forbidden" | "unauthenticated"; + readonly workerId?: string; + readonly label?: string; + readonly count?: number; + }; + /** A worker's uplink closed. `leaseCount` is what the view still shows it holding at that + * moment -- the number an operator needs to know how much is stranded, and the reason the + * view is not dropped immediately (§6). */ + "worker.disconnected": { + readonly workerId: string; + readonly label?: string; + readonly leaseCount: number; + }; + /** A disconnected worker's view was forgotten: by an operator (`worker.remove`) or because + * `gateway.disconnectedRetentionMs` elapsed. */ + "worker.removed": { + readonly workerId: string; + readonly label?: string; + readonly reason: "operator" | "retention"; + }; + /** ADR 0005 §9: the worker keeps its leases and receives no new dispatches from here on. */ + "worker.drain-started": { readonly workerId: string; readonly label?: string }; + "worker.drain-ended": { readonly workerId: string; readonly label?: string }; /** Payloads owned by the driver module that refused the root; see `DriverRejection`. */ "driver.root-rejected": { readonly platform: string; diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index c3bb0f098..dd963042b 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1618,6 +1618,265 @@ describe("CLI: token operations never write tokens.json directly", () => { }); }); +describe("CLI: worker commands (ADR 0005 §8/§23)", () => { + const connectedWorker = { + capacity: { + android: { + limit: 2, + maxRunning: 2, + overLimit: false, + reserved: 0, + running: 0, + used: 0, + warm: 0, + }, + global: { maxRunning: 4, overLimit: false, reserved: 0, running: 1, warm: 1 }, + ios: { limit: 2, maxRunning: 2, overLimit: false, reserved: 0, running: 1, used: 1, warm: 1 }, + }, + catalog: [], + connection: "connected" as const, + devices: [], + drained: false, + id: "wrk_1", + label: "mac-mini-1", + lastSeenAt: 1_000, + leases: [ + { + deviceId: "dev_1", + grantedAt: 1, + id: "lease_1", + lastRenewedAt: 1, + ownerId: "agent-1", + requesterId: "agent-1", + ttlDeadline: 2, + ttlMs: 1, + }, + ], + }; + + it("renders each worker's state, capacity and lease count", async () => { + const output = outputCapture(); + const environment = output.environmentWith({ + connectAdmin: async () => + fakeClient({ listWorkers: () => Promise.resolve({ workers: [connectedWorker] }) }), + }); + + await expect(runCli(["worker", "list"], environment)).resolves.toBe(0); + + expect(output.stdout).toContain("wrk_1 (mac-mini-1): connected"); + expect(output.stdout).toContain("ios 1/2"); + expect(output.stdout).toContain("1 lease(s)"); + }); + + it("says so plainly when no worker has ever connected", async () => { + const output = outputCapture(); + const environment = output.environmentWith({ connectAdmin: async () => fakeClient() }); + + await runCli(["worker", "list"], environment); + + expect(output.stdout).toContain("No workers have connected"); + }); + + it("names the protocol skew on an incompatible worker", async () => { + const output = outputCapture(); + const environment = output.environmentWith({ + connectAdmin: async () => + fakeClient({ + listWorkers: () => + Promise.resolve({ + workers: [ + { + ...connectedWorker, + connection: "incompatible" as const, + leases: [], + protocol: { gateway: { max: 5, min: 5 }, worker: { max: 4, min: 4 } }, + }, + ], + }), + }), + }); + + await runCli(["worker", "list"], environment); + + expect(output.stdout).toContain("incompatible"); + expect(output.stdout).toContain("protocol 4-4 vs gateway 5-5"); + }); + + it("emits the raw contract value under --json", async () => { + const output = outputCapture(); + const environment = output.environmentWith({ + connectAdmin: async () => + fakeClient({ listWorkers: () => Promise.resolve({ workers: [connectedWorker] }) }), + }); + + await runCli(["worker", "list", "--json"], environment); + + expect(JSON.parse(output.stdout)).toMatchObject({ workers: [{ id: "wrk_1" }] }); + }); + + it("drains, undrains and removes by id", async () => { + const calls: string[] = []; + const client = fakeClient({ + drainWorker: (input) => { + calls.push(`drain:${input.workerId}`); + return Promise.resolve({ drained: true as const, workerId: input.workerId }); + }, + removeWorker: (input) => { + calls.push(`remove:${input.workerId}`); + return Promise.resolve({ removed: true, workerId: input.workerId }); + }, + undrainWorker: (input) => { + calls.push(`undrain:${input.workerId}`); + return Promise.resolve({ drained: false as const, workerId: input.workerId }); + }, + }); + const environment = outputCapture().environmentWith({ connectAdmin: async () => client }); + + await expect(runCli(["worker", "drain", "wrk_1"], environment)).resolves.toBe(0); + await expect(runCli(["worker", "undrain", "wrk_1"], environment)).resolves.toBe(0); + await expect(runCli(["worker", "remove", "wrk_2"], environment)).resolves.toBe(0); + + expect(calls).toEqual(["drain:wrk_1", "undrain:wrk_1", "remove:wrk_2"]); + }); + + it("requires a worker id, and rejects an unknown subcommand", async () => { + const environment = outputCapture().environmentWith({ + connectAdmin: async () => fakeClient(), + }); + + await expect(runCli(["worker", "drain"], environment)).resolves.toBe(2); + await expect(runCli(["worker", "explode"], environment)).resolves.toBe(2); + }); + + it("prints usage without connecting to anything", async () => { + const output = outputCapture(); + let connected = false; + const environment = output.environmentWith({ + connectAdmin: async () => { + connected = true; + return fakeClient(); + }, + }); + + await expect(runCli(["worker"], environment)).resolves.toBe(0); + + expect(output.stdout).toContain("simlock worker list"); + expect(connected).toBe(false); + }); + + it("mints a worker join token (ADR 0005 §8)", async () => { + const roles: string[] = []; + const client = fakeClient({ + createToken: (input) => { + roles.push(input.role); + return Promise.resolve({ + secret: "sec_join", + token: { createdAt: 0, id: "tok_1", role: input.role }, + }); + }, + }); + const output = outputCapture(); + const environment = output.environmentWith({ connectAdmin: async () => client }); + + await expect(runCli(["token", "create", "--role", "worker"], environment)).resolves.toBe(0); + + expect(roles).toEqual(["worker"]); + expect(JSON.parse(output.stdout)).toMatchObject({ token: { role: "worker" } }); + }); + + it("still rejects a role that is not one of the three", async () => { + const environment = outputCapture().environmentWith({ + connectAdmin: async () => fakeClient(), + }); + + await expect(runCli(["token", "create", "--role", "root"], environment)).resolves.toBe(2); + }); +}); + +describe("CLI: status renders the fleet a gateway reports (ADR 0005 §20)", () => { + it("names the mode, each worker, and which worker a device and a lease live on", async () => { + const output = outputCapture(); + const status = { + capacity: { + android: { + limit: 0, + maxRunning: 0, + overLimit: false, + reserved: 0, + running: 0, + used: 0, + warm: 0, + }, + global: { maxRunning: 2, overLimit: false, reserved: 0, running: 1, warm: 0 }, + ios: { + limit: 2, + maxRunning: 2, + overLimit: false, + reserved: 0, + running: 1, + used: 1, + warm: 0, + }, + }, + daemon: { health: "running" as const, mode: "gateway" as const }, + devices: [ + { + id: "dev_1", + spec: { model: "iPhone 17", osVersion: "26.0", platform: "ios" as const }, + state: "leased" as const, + workerId: "wrk_1", + }, + ], + leases: [ + { + deviceId: "dev_1", + grantedAt: 1, + id: "lease_1", + lastRenewedAt: 1, + ownerId: "agent-1", + requesterId: "agent-1", + ttlDeadline: 2, + ttlMs: 1, + workerId: "wrk_1", + }, + ], + queueDepth: 0, + workers: [ + { + capacity: undefined, + catalog: [], + connection: "connected" as const, + devices: [], + drained: true, + id: "wrk_1", + lastSeenAt: 1, + leases: [], + }, + ], + }; + const environment = output.environmentWith({ + connectAdmin: async () => fakeClient({ getStatus: () => Promise.resolve(status) }), + }); + + await runCli(["status"], environment); + + expect(output.stdout).toContain("Daemon: running (gateway)"); + expect(output.stdout).toContain("wrk_1: connected, drained"); + expect(output.stdout).toContain("Device dev_1 on wrk_1: leased"); + expect(output.stdout).toContain("Lease lease_1: agent-1 on wrk_1"); + }); + + it("says worker on a worker, and leaves its devices and leases unqualified", async () => { + const output = outputCapture(); + const environment = output.environmentWith({ connectAdmin: async () => fakeClient() }); + + await runCli(["status"], environment); + + expect(output.stdout).toContain("Daemon: running (worker)"); + expect(output.stdout).not.toContain(" on wrk_"); + }); +}); + describe("CLI: lease pushes and exit codes (own logic, not the dispatcher's)", () => { it("exits 14 on a lost lease and does not attempt to re-release it", async () => { const output = outputCapture(); @@ -2784,6 +3043,11 @@ function fakeClient(overrides: Partial = {}): SimlockAdminCl }), listTokens: () => Promise.resolve(emptyTokenList), revokeToken: () => Promise.resolve({ revoked: true }), + listWorkers: () => Promise.resolve({ workers: [] }), + drainWorker: (input) => Promise.resolve({ drained: true as const, workerId: input.workerId }), + undrainWorker: (input) => + Promise.resolve({ drained: false as const, workerId: input.workerId }), + removeWorker: (input) => Promise.resolve({ removed: true, workerId: input.workerId }), ...overrides, }; return base; @@ -3042,6 +3306,7 @@ function testConfig(): Config { mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, + gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, drivers: {}, eventBuffer: { capacity: 100 }, health: { diff --git a/src/cli/index.ts b/src/cli/index.ts index 8d2558d5d..78421d34b 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -32,6 +32,7 @@ import { type LeaseGrant, type SimlockAdminClient, type StatusGetOutput, + type WorkerView, } from "../admin/index.js"; import type { Role } from "../contract/index.js"; import type { PassthroughCommand } from "../client/index.js"; @@ -49,6 +50,8 @@ const USAGE = `Usage: simlock [options] Commands: lease, release, status, list, catalog, cleanup, doctor, nuke, events, daemon, config, token + worker + Inspect and manage the workers of a gateway simctl Run xcrun simctl against Simlock's iOS device set adb Run adb against Simlock's adb server mcp Start the stdio MCP server @@ -543,6 +546,11 @@ function extractGlobalToken(argv: readonly string[]): { return { token, rest }; } +/** + * The command switch: one arm per published command, each one line handing off to that + * command's own function. + */ +// fallow-ignore-next-line complexity -- flat dispatch: the cyclomatic count is the number of commands Simlock publishes (cognitive complexity is 6, and every arm is a single delegation). `worker` is ADR 0005's addition to it; splitting the switch would hide the CLI's surface rather than simplify it. export async function runCli( argv: readonly string[], environment: CliEnvironment = defaultCliEnvironment(), @@ -578,6 +586,8 @@ export async function runCli( return await runConfig(rest.slice(1), environment, token); case "token": return await runToken(rest.slice(1), environment, token); + case "worker": + return await runWorker(rest.slice(1), environment, token); case "simctl": case "adb": // Named here rather than discovered from the drivers on purpose: these are @@ -1583,7 +1593,7 @@ async function runToken( const command = argv[0]; if (command === undefined || isHelp(command)) { environment.stdout.write( - "Usage: simlock token create --role [--label ]\n" + + "Usage: simlock token create --role [--label ]\n" + " simlock token list\n" + " simlock token revoke \n", ); @@ -1612,7 +1622,7 @@ async function runTokenCreate( }); if (values.help) { environment.stdout.write( - "Usage: simlock token create --role [--label ]\n", + "Usage: simlock token create --role [--label ]\n", ); return 0; } @@ -1655,12 +1665,118 @@ async function runTokenRevoke( return 0; } -function parseTokenRole(value: unknown): "agent" | "operator" { - if (value !== "agent" && value !== "operator") - throw new UsageError(withHelpHint("token create requires --role ")); +/** + * ADR 0005 §8 adds `worker`: a join token, minted on a gateway and put in a worker's + * `gateway.token`. It is deliberately mintable on either mode -- the CLI does not know which + * daemon it is talking to, and a token minted on a worker is simply a credential nothing will + * ever present to it, which is not worth a mode check the daemon would have to duplicate. + */ +function parseTokenRole(value: unknown): "agent" | "operator" | "worker" { + if (value !== "agent" && value !== "operator" && value !== "worker") + throw new UsageError(withHelpHint("token create requires --role ")); return value; } +/** + * 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. + */ +async function runWorker( + argv: readonly string[], + environment: CliEnvironment, + token: string | undefined, +): Promise { + const command = argv[0]; + if (command === undefined || isHelp(command)) { + environment.stdout.write( + "Usage: simlock worker list [--json]\n" + + " simlock worker drain \n" + + " simlock worker undrain \n" + + " simlock worker remove \n", + ); + return 0; + } + const client = await connectDaemonClient(environment, token); + try { + if (command === "list") return await runWorkerList(argv.slice(1), client, environment); + if (command === "drain" || command === "undrain" || command === "remove") { + return await runWorkerAction(command, argv.slice(1), client, environment); + } + throw new UsageError(withHelpHint(`Unknown worker command: ${command}`)); + } finally { + await client.close(); + } +} + +async function runWorkerList( + argv: readonly string[], + client: SimlockAdminClient, + environment: CliEnvironment, +): Promise { + const values = commandArgs(argv, { + help: { type: "boolean", short: "h" }, + json: { type: "boolean" }, + }); + if (values.help) { + environment.stdout.write("Usage: simlock worker list [--json]\n"); + return 0; + } + const result = await client.listWorkers(); + if (values.json) writeResult(environment, result); + else environment.stdout.write(`${formatWorkers(result.workers)}\n`); + return 0; +} + +async function runWorkerAction( + command: "drain" | "undrain" | "remove", + argv: readonly string[], + client: SimlockAdminClient, + environment: CliEnvironment, +): Promise { + const values = commandArgs(argv, { help: { type: "boolean", short: "h" } }); + if (values.help) { + environment.stdout.write(`Usage: simlock worker ${command} \n`); + return 0; + } + const workerId = requiredPositional(values.positionals, "worker-id"); + const result = + command === "drain" + ? await client.drainWorker({ workerId }) + : command === "undrain" + ? await client.undrainWorker({ workerId }) + : await client.removeWorker({ workerId }); + writeResult(environment, result); + return 0; +} + +/** + * One line per worker, in the shape an operator scans: state first (that is the question), then + * identity, then what it is carrying. `simlock worker list --json` is the machine-readable + * answer, so this stays a summary rather than a dump. + */ +function formatWorkers(workers: WorkerView[]): string { + if (workers.length === 0) return "No workers have connected to this gateway."; + return workers + .map((worker) => { + const label = worker.label === undefined ? worker.id : `${worker.id} (${worker.label})`; + const state = worker.drained ? `${worker.connection}, drained` : worker.connection; + const capacity = + worker.capacity === undefined + ? "capacity unknown" + : `ios ${worker.capacity.ios.running}/${worker.capacity.ios.limit}, ` + + `android ${worker.capacity.android.running}/${worker.capacity.android.limit}`; + const skew = + worker.protocol === undefined + ? "" + : ` protocol ${worker.protocol.worker.min}-${worker.protocol.worker.max}` + + ` vs gateway ${worker.protocol.gateway.min}-${worker.protocol.gateway.max}`; + return `${label}: ${state} -- ${capacity}, ${String(worker.leases.length)} lease(s)${skew}`; + }) + .join("\n"); +} + function commandArgs( argv: readonly string[], options: NonNullable[0]>["options"], @@ -1779,12 +1895,17 @@ function writeResult(environment: CliEnvironment, value: unknown): void { // fallow-ignore-next-line complexity -- stable human status rendering is intentionally a single formatter. function formatStatus(status: StatusGetOutput): string { - const { capacity, daemon, devices, leases, queueDepth } = status; + const { capacity, daemon, devices, leases, queueDepth, workers } = status; const globalLine = `Running global: ${capacity.global.running} + ${capacity.global.reserved} reserved/${capacity.global.maxRunning}, warm ${capacity.global.warm}${capacity.global.overLimit ? " (over limit)" : ""}`; const capacityLines = (["ios", "android"] as const).map((platform) => { const usage = capacity[platform]; return `Capacity ${platform}: managed ${usage.used}/${usage.limit}, running ${usage.running} + ${usage.reserved} reserved/${usage.maxRunning}, warm ${usage.warm}${usage.overLimit ? " (over limit)" : ""}`; }); + // ADR 0005 §20: on a gateway every device and lease names the worker it lives on, and the + // fleet itself is a block of its own above them. On a worker `workers` is absent and this is + // exactly the output it has always been. + const workerLines = + workers === undefined ? [] : [formatWorkers(workers), ""].filter((line) => line !== ""); const deviceLines = devices.map((device) => { const markers = [ device.foreignStateDetectedAt === undefined ? undefined : "foreign state change", @@ -1795,18 +1916,20 @@ function formatStatus(status: StatusGetOutput): string { : `mid-transition ${device.transitionAgeMs}ms`, ].filter((marker) => marker !== undefined); const suffix = markers.length === 0 ? "" : ` (${markers.join(", ")})`; - return `Device ${device.id}: ${device.state}${suffix}`; + const where = device.workerId === undefined ? "" : ` on ${device.workerId}`; + return `Device ${device.id}${where}: ${device.state}${suffix}`; }); // ADR 0004: `lastRenewedAt` is a stored field written at grant and on every renew, so unlike // the derived `lastHeartbeatAt` it replaces, every lease has one to render. const leaseLines = leases.map( (lease) => - `Lease ${lease.id}: ${lease.requesterId} since ${lease.grantedAt}, last renewed ${lease.lastRenewedAt}`, + `Lease ${lease.id}: ${lease.requesterId}${lease.workerId === undefined ? "" : ` on ${lease.workerId}`} since ${lease.grantedAt}, last renewed ${lease.lastRenewedAt}`, ); return [ `Daemon: ${daemon.health} (${daemon.mode})`, globalLine, ...capacityLines, + ...workerLines, ...deviceLines, ...leaseLines, `Queue depth: ${queueDepth}`, diff --git a/src/contract/errors.ts b/src/contract/errors.ts index 01e37643e..e625708d7 100644 --- a/src/contract/errors.ts +++ b/src/contract/errors.ts @@ -73,6 +73,40 @@ export interface ErrorDetailsMap { NUKE_UNAVAILABLE: Record; INTERNAL: Record; + // -- domain, gateway mode (ADR 0005) -- + /** + * ADR 0005 §34/§23: the operation exists in the contract, this daemon is a gateway, and a + * gateway is not the thing that can answer it. Two populations share the code, and + * `details.operation` is what tells them apart for a caller: + * + * - permanently, by design: `nuke.run`, `cleanup.run`, `doctor.run`, `driver.passthrough` -- + * operations that act on one machine's devices as a whole, which stay per-worker + * (§34: "a fleet-wide destructive command from one endpoint is not something v1 should + * offer", and a passthrough command string the client cannot run is worse than an error); + * - until #118: the lease family (`lease.request`, `lease.renew`, `lease.release`, + * `lease.cancel`, `lease.list`, `lease.release-all`) and `device.exec`, which the fleet + * queue and the forwarding path implement. + * + * It is not `UNKNOWN_REQUEST`: the operation is known, and the answer "ask a worker" is a + * different instruction from "that is not an operation". + */ + UNSUPPORTED_IN_GATEWAY_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 }; + /** `worker.drain`/`worker.undrain` naming a worker the gateway has no view of. (`worker.remove` + * answers `{removed: false}` instead: forgetting something already forgotten is done, not an + * error.) */ + UNKNOWN_WORKER: { readonly workerId: string }; + /** + * ADR 0005 §28: the worker that owns this lease (or would serve this request) has no open + * uplink. `kind: "transport"`, because it says the same thing `DAEMON_CONNECTION_LOST` says + * one hop further out -- the operation did not fail on its merits, the machine that would + * decide is unreachable. Declared here now, with the rest of the closed set; #118 is what + * throws it, once there is a lease to forward. + */ + WORKER_UNREACHABLE: { readonly workerId: string }; + /** ADR §7's forward-compatibility escape hatch: a code the client does not know (a newer * daemon) wraps as this instead of throwing a parse failure. Never sent by a daemon this * version of the contract can produce -- purely a client-side wrapping target. */ @@ -87,6 +121,53 @@ export interface ErrorDetailsMap { export type SimlockErrorCode = keyof ErrorDetailsMap; +/** The subset of `SimlockErrorCode` whose `ErrorDetailsMap` entry actually declares a field -- + * i.e. every code above except the `Record` ("no details") ones. Structural + * assignability to `Record`, not `keyof`: an index-signature-only type's `keyof` + * is `string`, not `never`, so a `keyof ... extends never` test would (wrongly) call every code + * "declared" -- only a shape whose every property-value-type is itself assignable to `never` + * (i.e. `Record` itself) is actually empty. */ +type CodeWithDeclaredDetails = { + [Code in SimlockErrorCode]: ErrorDetailsMap[Code] extends Record ? never : Code; +}[SimlockErrorCode]; + +/** + * Hardening: which error codes are declared, in `ErrorDetailsMap` above, to carry a `details` + * payload onto the wire -- read by `src/http/errors.ts`'s `mapError` so it forwards a + * `DispatchError`'s `.details` only for a code the contract actually documents as carrying one, + * rather than for any `DispatchError` whose `.details` happens to be object-shaped. `.details` + * is `unknown` on `DispatchError` (`dispatch.ts`) -- nothing stops a handler from attaching an + * object to a code that declares none, and without this gate `mapError` would put it on the + * wire anyway. + * + * Deliberately a `Record` rather than a plain array: TypeScript + * requires this object to have *exactly* `CodeWithDeclaredDetails`'s keys, no more and no + * fewer, so adding a details shape to `ErrorDetailsMap` without adding it here (or the reverse) + * is a compile error here -- the two cannot drift apart silently. + */ +const CODES_WITH_DECLARED_DETAILS_BY_CODE: Record = { + PROTOCOL_VERSION_UNSUPPORTED: true, + QUEUE_TIMEOUT: true, + REQUESTER_ALREADY_LEASED: true, + NO_DRIVER: true, + RUNTIME_MISSING: true, + UNKNOWN_MODEL: true, + INSUFFICIENT_DISK_SPACE: true, + LICENSE_NOT_ACCEPTED: true, + UNKNOWN_LEASE: true, + PASSTHROUGH_REFUSED: true, + UNKNOWN_PASSTHROUGH_TOOL: true, + UNSUPPORTED_IN_GATEWAY_MODE: true, + WORKER_CONNECTED: true, + UNKNOWN_WORKER: true, + WORKER_UNREACHABLE: true, + UNKNOWN_DAEMON_ERROR: true, +}; + +export const CODES_WITH_DECLARED_DETAILS: ReadonlySet = new Set( + Object.keys(CODES_WITH_DECLARED_DETAILS_BY_CODE) as CodeWithDeclaredDetails[], +); + export interface ErrorTableEntry { readonly code: Code; readonly kind: ErrorKind; @@ -188,6 +269,29 @@ export const ERROR_TABLE: { readonly [Code in SimlockErrorCode]: ErrorTableEntry }, NUKE_UNAVAILABLE: { code: "NUKE_UNAVAILABLE", kind: "domain", cliExitCode: 1, httpStatus: 503 }, INTERNAL: { code: "INTERNAL", kind: "domain", cliExitCode: 1, httpStatus: 500 }, + // 501, not 400/503: the request was well-formed and the daemon is healthy -- this endpoint + // simply does not implement that operation, which is exactly what "Not Implemented" says. + // `cliExitCode: 2` puts it with the other "you asked the wrong thing" outcomes. + UNSUPPORTED_IN_GATEWAY_MODE: { + code: "UNSUPPORTED_IN_GATEWAY_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 + // something that cannot apply, rather than hitting a state of the fleet. + WORKER_CONNECTED: { code: "WORKER_CONNECTED", kind: "domain", cliExitCode: 2, httpStatus: 409 }, + // Exit 12, beside `UNKNOWN_MODEL`: the "what you named does not exist" class, which a script + // branches on differently from "the fleet is busy" or "that cannot apply here". + UNKNOWN_WORKER: { code: "UNKNOWN_WORKER", kind: "domain", cliExitCode: 12, httpStatus: 404 }, + WORKER_UNREACHABLE: { + code: "WORKER_UNREACHABLE", + kind: "transport", + cliExitCode: 1, + httpStatus: 503, + }, UNKNOWN_DAEMON_ERROR: { code: "UNKNOWN_DAEMON_ERROR", kind: "protocol", diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index 36ac93d1e..314ba02da 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -58,6 +58,11 @@ const ROLE_MATRIX: ReadonlyArray<{ }, { name: "token.list", input: {}, role: "admin" }, { name: "token.revoke", input: { id: "tok_1" }, role: "admin" }, + // ADR 0005 §8/§23: gateway-only, admin throughout. + { name: "worker.list", input: {}, role: "admin" }, + { name: "worker.drain", input: { workerId: "wrk_1" }, role: "admin" }, + { name: "worker.undrain", input: { workerId: "wrk_1" }, role: "admin" }, + { name: "worker.remove", input: { workerId: "wrk_1" }, role: "admin" }, ]; describe("operation role matrix", () => { @@ -204,6 +209,112 @@ describe("operation input/output round trips", () => { expect(OPERATIONS["status.get"].output.parse(status)).toBeDefined(); }); + it("status.get: round-trips a gateway's aggregate, workers and all (ADR 0005 §20)", () => { + const capacityEntry = { + running: 1, + maxRunning: 2, + reserved: 0, + overLimit: false, + limit: 2, + warm: 0, + used: 1, + }; + const capacity = { + ios: capacityEntry, + android: capacityEntry, + global: { running: 1, maxRunning: 4, reserved: 0, overLimit: false, warm: 0 }, + }; + const lease = { + id: "lease_1", + deviceId: "dev_1", + requesterId: "agent-1", + ownerId: "agent-1", + grantedAt: 1, + ttlMs: 2, + ttlDeadline: 3, + lastRenewedAt: 1, + workerId: "wrk_1", + }; + const parsed = OPERATIONS["status.get"].output.parse({ + devices: [ + { + id: "dev_1", + spec: { platform: "ios", model: "iPhone 17", osVersion: "26.0" }, + state: "leased", + workerId: "wrk_1", + }, + ], + leases: [lease], + capacity, + daemon: { health: "running", mode: "gateway" }, + queueDepth: 0, + workers: [ + { + id: "wrk_1", + label: "mac-mini-1", + connection: "connected", + drained: false, + lastSeenAt: 10, + health: "running", + version: "0.3.0", + capacity, + queueDepth: 0, + leases: [lease], + devices: [], + catalog: [{ platform: "ios", models: ["iPhone 17"], runtimes: ["26.0"] }], + }, + { + id: "wrk_2", + connection: "incompatible", + drained: false, + lastSeenAt: 11, + protocol: { gateway: { min: 4, max: 4 }, worker: { min: 3, max: 3 } }, + leases: [], + devices: [], + catalog: [], + }, + ], + }); + expect(parsed.workers?.[1]?.protocol?.worker).toEqual({ min: 3, max: 3 }); + expect(parsed.devices[0]?.workerId).toBe("wrk_1"); + expect(parsed.leases[0]?.workerId).toBe("wrk_1"); + }); + + it("catalog.get: round-trips a gateway's per-entry worker annotations (ADR 0005 §21)", () => { + const parsed = OPERATIONS["catalog.get"].output.parse({ + platforms: [ + { + platform: "ios", + models: ["iPhone 17"], + runtimes: ["26.0"], + modelWorkers: { "iPhone 17": ["wrk_1", "wrk_2"] }, + runtimeWorkers: { "26.0": ["wrk_1"] }, + }, + ], + }); + expect(parsed.platforms[0]?.modelWorkers).toEqual({ "iPhone 17": ["wrk_1", "wrk_2"] }); + }); + + it("worker.remove reports whether there was a view to forget; drain never lies", () => { + // `remove` is idempotent: forgetting a worker the gateway has already forgotten is done, + // not an error -- so `false` is a legitimate outcome, the same shape `token.revoke` uses. + expect(OPERATIONS["worker.remove"].output.parse({ workerId: "wrk_1", removed: false })).toEqual( + { workerId: "wrk_1", removed: false }, + ); + // Drain and undrain each report the state they establish, and only that state: an + // `undrain` answering `drained: true` would be a contradiction rather than an outcome. + expect(OPERATIONS["worker.drain"].output.parse({ workerId: "wrk_1", drained: true })).toEqual({ + workerId: "wrk_1", + drained: true, + }); + expect(() => + OPERATIONS["worker.drain"].output.parse({ workerId: "wrk_1", drained: false }), + ).toThrow(); + expect(() => + OPERATIONS["worker.undrain"].output.parse({ workerId: "wrk_1", drained: true }), + ).toThrow(); + }); + it("list.get: accepts each kind's array shape", () => { expect(OPERATIONS["list.get"].output.parse([])).toEqual([]); expect(OPERATIONS["list.get"].output.parse([{ name: "idle-shutdown" }])).toEqual([ @@ -265,6 +376,8 @@ describe("operation input/output round trips", () => { it("config.get: round-trips a representative config", () => { const config = { + mode: "worker", + gateway: { disconnectedRetentionMs: 86_400_000, execTimeoutMs: 660_000 }, capacity: { strategy: "fixed", config: { maxRunning: 4 } }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_000 }, idle: { shutdownAfterMs: 1, deleteAfterMs: 2 }, diff --git a/src/contract/operations.ts b/src/contract/operations.ts index ba17de8b6..bc2ade499 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -14,6 +14,7 @@ import { cleanupRuleSummarySchema, configSchema, daemonHealthSchema, + daemonModeSchema, deviceRecordSchema, doctorReportSchema, eventEnvelopeSchema, @@ -26,8 +27,10 @@ import { proposalSchema, statusCapacitySchema, statusDeviceSchema, + statusLeaseSchema, tokenRecordSchema, tokenRoleSchema, + workerViewSchema, } from "./schemas.js"; export interface OperationDefinition< @@ -78,7 +81,7 @@ export const statusGet = defineOperation({ // `driverData` and reclamation/recovery bookkeeping off this response; see its doc comment // in schemas.ts. `list.get` (admin-only) is the operation that returns the full record. devices: z.array(statusDeviceSchema), - leases: z.array(leaseRecordSchema), + leases: z.array(statusLeaseSchema), capacity: statusCapacitySchema, /** * What this daemon *is*, as opposed to what it currently holds: its health, and its run @@ -89,8 +92,14 @@ export const statusGet = defineOperation({ * neither is a fact about a device; `health` moved in here from the top level with the * same protocol bump that added `mode`. */ - daemon: z.object({ health: daemonHealthSchema, mode: z.enum(["worker", "gateway"]) }), + daemon: z.object({ health: daemonHealthSchema, mode: daemonModeSchema }), queueDepth: z.number(), + /** + * ADR 0005 §20: one entry per worker view, additive and gateway-only. Absent (not empty) + * from a worker's answer -- a worker has no fleet, and an empty array would read as "a + * gateway with no workers". + */ + workers: z.array(workerViewSchema).optional(), }), }); @@ -332,12 +341,17 @@ export const deviceExec = defineOperation({ // ---- lease.list (new, ADR §9) ----------------------------------------------------------------- +/** + * ADR 0005 §20: the element carries an optional `workerId` -- absent from a worker's own + * answer, set by a gateway, which lists the leases its worker views report. Additive, so a + * client that never talks to a gateway sees exactly what it saw before. + */ // fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. export const leaseList = defineOperation({ name: "lease.list", role: "agent", input: z.object({}), - output: z.object({ leases: z.array(leaseRecordSchema) }), + output: z.object({ leases: z.array(statusLeaseSchema) }), }); // ---- doctor.run ------------------------------------------------------------------------------- @@ -386,6 +400,20 @@ export const leaseReleaseAll = defineOperation({ // ---- list.get ----------------------------------------------------------------------------- +/** + * The union has four arms because two kinds of daemon answer it (ADR 0005 §32): + * + * - a **worker** returns its own registry records -- the full `deviceRecordSchema`, which an + * operator inspecting one machine legitimately wants; + * - a **gateway** returns the fleet, and cannot return that shape: it has never held a + * `driverDeviceId` or a driver's private `driverData`, and fabricating either would be a + * lie about a device it does not own. It answers the narrower `statusDeviceSchema` (plus + * `workerId`) instead -- the same devices `status.get` reports. + * + * Arm order is load-bearing: a full record matches the first arm, so a worker's answer is + * unchanged. `rules` is per-machine cleanup configuration, so a gateway answers it with an + * empty list rather than inventing a fleet-wide rule set. + */ // fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. export const listGet = defineOperation({ name: "list.get", @@ -393,7 +421,8 @@ export const listGet = defineOperation({ input: z.object({ kind: z.enum(["devices", "leases", "rules"]).optional() }), output: z.union([ z.array(deviceRecordSchema), - z.array(leaseRecordSchema), + z.array(statusDeviceSchema), + z.array(statusLeaseSchema), z.array(cleanupRuleSummarySchema), ]), }); @@ -506,6 +535,71 @@ export const tokenRevoke = defineOperation({ output: z.object({ revoked: z.boolean() }), }); +// ---- 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. +// +// `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 +// operation at that role. + +// fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. +export const workerList = defineOperation({ + name: "worker.list", + role: "admin", + input: z.object({}), + output: z.object({ workers: z.array(workerViewSchema) }), +}); + +/** + * ADR 0005 §9: a drained worker keeps its existing leases and receives no new dispatches -- + * the operator's tool for taking a machine down without killing anyone's device. This PR + * records the flag (persisted, so it survives a worker reconnect and a gateway restart) and + * reports it; #118's dispatcher is what honours it, because this PR has no dispatch to skip. + * + * Idempotent: draining an already-drained worker succeeds and changes nothing. An id the + * gateway has no view of is `UNKNOWN_WORKER` -- draining a machine that is not in the fleet is + * a typo, and answering "done" would leave an operator believing a machine was taken out of + * service when nothing was. + */ +// fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. +export const workerDrain = defineOperation({ + name: "worker.drain", + role: "admin", + input: z.object({ workerId: z.string().min(1) }), + output: z.object({ workerId: z.string(), drained: z.literal(true) }), +}); + +// fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. +export const workerUndrain = defineOperation({ + name: "worker.undrain", + role: "admin", + input: z.object({ workerId: z.string().min(1) }), + output: z.object({ workerId: z.string(), drained: z.literal(false) }), +}); + +/** + * ADR 0005 §8: forgets a *disconnected* worker's view. A connected one is refused with + * `WORKER_CONNECTED` -- removing it would only make the gateway forget a machine that is about + * to announce itself again on its very next refresh, which is a confusing no-op rather than an + * operator action. + * + * `removed: false` is the answer for an id with no view: unlike drain, "forget this" is + * already true of something the gateway has never heard of or has already forgotten, so it is + * an outcome to report rather than an error to raise (the same shape `token.revoke` uses). + */ +// fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. +export const workerRemove = defineOperation({ + name: "worker.remove", + role: "admin", + input: z.object({ workerId: z.string().min(1) }), + output: z.object({ workerId: z.string(), removed: z.boolean() }), +}); + // ---- the full registry ---------------------------------------------------------------------- export const OPERATIONS = { @@ -531,6 +625,25 @@ export const OPERATIONS = { "token.create": tokenCreate, "token.list": tokenList, "token.revoke": tokenRevoke, + "worker.list": workerList, + "worker.drain": workerDrain, + "worker.undrain": workerUndrain, + "worker.remove": workerRemove, } 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", +] as const satisfies readonly OperationName[]; + +export type GatewayOnlyOperationName = (typeof GATEWAY_ONLY_OPERATIONS)[number]; + export type OperationName = keyof typeof OPERATIONS; diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index 5be9462fd..7b4c2e4f2 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -14,19 +14,23 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** - * The range this contract's daemon speaks. Both ends are 5, and both moves that got it there - * were breaking with no shim kept behind them, which is exactly when ADR 0003 §6's honesty + * The range this contract's daemon speaks. Both ends are 5, and every move that got it there + * was breaking with no shim kept behind them, which is exactly when ADR 0003 §6's honesty * rule says a range must *not* widen: ADR 0004 removed `lease.heartbeat` and `mode` from the - * wire (taking it to 4), and ADR 0005 adds `device.exec`, its `output` push family, and a - * `mode` field `status.get` now always carries (taking it to 5). A client from before either - * change simply does not overlap this daemon, and `hello` fails with - * `PROTOCOL_VERSION_UNSUPPORTED` naming both ranges; `daemon.stop` stays the frozen exception - * so the upgrade path (stop, then start the new daemon) exists at all. + * wire (taking it to 4), and ADR 0005 adds `device.exec` and its `output` push family, a + * `mode` field `status.get` now always carries, and the gateway surface -- `worker.*`, + * `workerId`, the `worker` token role -- on top (taking it to 5). It only ever widens once a + * second version is actually kept alive side by side with the first, which nothing here does. * - * `status.get`'s `mode` is the clearest reason this had to move rather than stay at 4: an - * older client parsing that response against a schema without the field is not a compatibility - * story anyone kept, so advertising 4 would be a claim to a compatibility path that does not - * exist. + * A client from before any of those changes simply does not overlap this daemon, and `hello` + * fails with `PROTOCOL_VERSION_UNSUPPORTED` naming both ranges; `daemon.stop` stays the frozen + * exception so the upgrade path (stop, then start the new daemon) exists at all. `status.get`'s + * `mode` is the clearest reason this had to move rather than stay at 4: an older client parsing + * that response against a schema without the field is not a compatibility story anyone kept, so + * advertising 4 would be a claim to a compatibility path that does not exist. + * + * The consequence ADR 0005 §31 names: a pre-0005 worker's uplink negotiates nothing, so its + * gateway marks it `incompatible` -- with both ranges on the view -- and never dispatches to it. */ export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 5, max: 5 }; diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index 1ac890031..27249dbad 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -106,6 +106,13 @@ export const statusDeviceSchema = z.object({ quarantineNextRetryAt: z.number().optional(), /** Decoration added by `status.get`; absent for a device not mid-transition. */ transitionAgeMs: z.number().optional(), + /** + * ADR 0005 §20: which worker this device lives on. Additive and gateway-only -- a worker + * answers `status.get` about its own devices and has no second machine to name, so it never + * sets this; a gateway sets it on every device in the aggregate, because "device dev_7" is + * ambiguous across a fleet in a way it never is on one host. + */ + workerId: z.string().optional(), }); /** @@ -243,6 +250,16 @@ export const platformCatalogSchema = z.object({ models: z.array(z.string()), runtimes: z.array(z.string()), defaultRuntime: z.string().optional(), + /** + * ADR 0005 §21: on a gateway, `models`/`runtimes` are the *union* over the fleet, and these + * two maps say which workers each entry came from (`{"iPhone 16": ["wrk_a", "wrk_b"]}`). + * Additive and gateway-only: a worker's own catalog needs no attribution, and a renderer + * that predates the fleet still reads `models`/`runtimes` unchanged. Kept as annotations + * beside the flat lists rather than as a change to their element type precisely so that + * stays true. + */ + modelWorkers: z.record(z.string(), z.array(z.string())).optional(), + runtimeWorkers: z.record(z.string(), z.array(z.string())).optional(), }); export const proposalSchema = z.object({ @@ -381,6 +398,10 @@ const capacityConfigSchema = z.discriminatedUnion("strategy", [ /** Mirrors `Config` (src/core/config.ts) field for field. */ export const configSchema = z.object({ + /** ADR 0005 §1. `config.get` is how a caller learns which mode the daemon it is talking to + * runs in without inferring it from behaviour; `status.get`'s `daemon.mode` is the + * agent-role answer to the same question. */ + mode: z.enum(["worker", "gateway"]), capacity: capacityConfigSchema, downloads: z.object({ policy: z.enum(["never", "on-request", "always"]), @@ -430,6 +451,16 @@ export const configSchema = z.object({ bootTimeoutMs: z.number(), }), }), + /** ADR 0005 §3/§6. `url`/`token`/`label` are the worker's half, `disconnectedRetentionMs` + * the gateway's; a daemon carries the whole block whichever mode it runs in, and simply + * reads the half that applies (see `Config["gateway"]`). */ + gateway: z.object({ + url: z.string().optional(), + token: z.string().optional(), + label: z.string().optional(), + disconnectedRetentionMs: z.number(), + execTimeoutMs: z.number(), + }), stalledTransition: z.object({ thresholdMultiplier: z.number(), minimumThresholdMs: z.number(), @@ -439,13 +470,20 @@ export const configSchema = z.object({ // ---- tokens ----------------------------------------------------------------------------------- /** - * `TokenRole` (agent/operator token store roles, src/http/token-store.ts) is a deliberately - * different vocabulary from the daemon session `Role` (agent/admin, see `roles.ts`) -- a - * `token.create --role operator` mints a credential that *resolves to* the admin session role - * at `hello` (ADR §5), it is not itself that role. Keeping the two enums textually distinct - * here (rather than reusing `roleSchema`) is deliberate, not an oversight. + * `TokenRole` (agent/operator/worker token store roles, src/http/token-store.ts) is a + * deliberately different vocabulary from the daemon session `Role` (agent/admin, see + * `roles.ts`) -- a `token.create --role operator` mints a credential that *resolves to* the + * admin session role at `hello` (ADR 0003 §5), it is not itself that role. Keeping the two + * enums textually distinct here (rather than reusing `roleSchema`) is deliberate, not an + * oversight. + * + * ADR 0005 §8/§25 adds `worker`: a join token, presented by a worker when it opens its uplink + * to a gateway. It resolves to no session role at all -- it can open an uplink and nothing + * else, and a `worker`-role token on a `/v1` route is `403` (see `src/http/auth.ts`). That is + * why it is a third value here rather than a reuse of `agent`: the whole point is a credential + * whose authority is a single transport, not a set of operations. */ -export const tokenRoleSchema = z.enum(["agent", "operator"]); +export const tokenRoleSchema = z.enum(["agent", "operator", "worker"]); export const tokenRecordSchema = z.object({ id: z.string(), @@ -453,3 +491,98 @@ export const tokenRecordSchema = z.object({ label: z.string().optional(), createdAt: z.number(), }); + +// ---- modes and worker views (ADR 0005) -------------------------------------------------------- + +/** + * Which mode a daemon runs in (ADR 0005 §1). A worker owns devices -- drivers, registry, + * capacity, leases -- and is what every simlock daemon has been until now, so it is the + * default. A gateway owns none of that and fronts the workers connected to it. One process, + * one mode. + */ +export const daemonModeSchema = z.enum(["worker", "gateway"]); + +/** Mirrors `ProtocolRange` (protocol.ts). Re-declared rather than imported so this file stays + * the one place a wire *shape* is written down; `protocol.ts` owns the negotiation logic. */ +const protocolRangeShapeSchema = z.object({ min: z.number().int(), max: z.number().int() }); + +/** + * ADR 0005 §6: the uplink is the reachability signal. `connected` means the worker's uplink is + * open and its session negotiated a protocol version; `disconnected` means it closed and the + * view is the last-known one (kept until `gateway.disconnectedRetentionMs` elapses or an + * operator removes it); `incompatible` means the uplink is open but `hello` found no + * overlapping protocol version (§31) -- the view then carries both ranges and nothing else the + * gateway would have had to ask for over a protocol it cannot speak. + */ +const workerConnectionStateSchema = z.enum(["connected", "disconnected", "incompatible"]); + +/** + * What the gateway currently knows about one worker (ADR 0005's vocabulary table, §7, §31). + * Rebuilt over the uplink, never persisted: a gateway restart re-derives every field from the + * workers that reconnect (§30). + * + * The optional fields are exactly the ones that come from a `status.get`/`catalog.get` round + * trip the gateway may not have been able to make: an `incompatible` worker is never asked + * 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. + */ +export const workerViewSchema = z.object({ + /** The worker's own instance identity (`instance.json`), ADR 0005 §3a: stable across + * restarts, unique by construction, opaque to clients. Never a host name or an address. */ + id: z.string(), + /** `gateway.label` from the worker's config -- display only, need not be unique, and never + * used to route (§13: "label is display-only"). */ + label: z.string().optional(), + connection: workerConnectionStateSchema, + /** ADR 0005 §9: a drained worker keeps its leases and receives no new dispatches. */ + drained: z.boolean(), + /** When the gateway last had this worker's uplink open, or last refreshed its view. */ + lastSeenAt: z.number(), + health: daemonHealthSchema.optional(), + /** The worker daemon's own version string, as reported by its `hello` reply. */ + version: z.string().optional(), + /** Set only for an `incompatible` worker (§31), naming both ranges so an operator can see + * which side to upgrade. */ + protocol: z + .object({ gateway: protocolRangeShapeSchema, worker: protocolRangeShapeSchema }) + .optional(), + capacity: statusCapacitySchema.optional(), + /** + * The worker's effective `downloads.policy`, read once with `config.get` when the uplink + * connects. It is on the view because it is a *routing input*, not decoration: ADR 0005 §13 + * says a request that would need a download is only eligible on a worker whose policy allows + * one, and #118's policy reads it from here rather than asking at dispatch time. Absent for + * a worker whose `config.get` the gateway could not read (an incompatible one, or a call + * that failed). + */ + downloads: z.object({ policy: z.enum(["never", "on-request", "always"]) }).optional(), + /** + * The worker's own `lease.maxTtlMs`, read once with `config.get` when the uplink connects + * (and again on the periodic backstop tick, alongside the catalog and `downloads.policy` + * above -- see `WorkerLink#rebuildView`). ADR 0005 §15: a fleet lease's width is decided at + * the gateway's own `lease.maxTtlMs`, but what the gateway dispatches is an ordinary + * `lease.request`, so a worker whose own cap is lower still refuses a request the gateway + * already accepted -- this field is what lets the gateway notice that at the worker, rather + * than only in the operator's documentation. Absent for a worker whose `config.get` the + * gateway could not read (an incompatible worker, a call that failed, or one older than this + * field). + */ + lease: z.object({ maxTtlMs: z.number() }).optional(), + /** The worker's *own* queue depth -- local agents on that machine. The gateway's fleet queue + * is reported separately by `status.get` and arrives with #118. */ + queueDepth: z.number().optional(), + leases: z.array(leaseRecordSchema), + devices: z.array(statusDeviceSchema), + catalog: z.array(platformCatalogSchema), +}); + +/** + * `status.get`'s lease shape. Identical to `leaseRecordSchema` plus the gateway's additive + * `workerId` (ADR 0005 §20) -- an extension rather than a change to `leaseRecordSchema` itself, + * so `lease.renew`/`lease.list`'s shapes are untouched by this PR. + */ +export const statusLeaseSchema = leaseRecordSchema.extend({ + /** Which worker holds this lease; absent on a worker's own answer, set by a gateway. */ + workerId: z.string().optional(), +}); diff --git a/src/core/acquisition-planner.test.ts b/src/core/acquisition-planner.test.ts index d3a06c05b..72e4e7d35 100644 --- a/src/core/acquisition-planner.test.ts +++ b/src/core/acquisition-planner.test.ts @@ -13,6 +13,7 @@ const config: Config = { mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, + gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, drivers: {}, eventBuffer: { capacity: 100 }, health: { diff --git a/src/core/cleanup/idle-destroy.test.ts b/src/core/cleanup/idle-destroy.test.ts index 2d2e28cd1..ca6b97b06 100644 --- a/src/core/cleanup/idle-destroy.test.ts +++ b/src/core/cleanup/idle-destroy.test.ts @@ -9,6 +9,7 @@ const config: Config = { mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 0 }, + gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, drivers: {}, eventBuffer: { capacity: 1 }, health: { diff --git a/src/core/cleanup/idle-shutdown.test.ts b/src/core/cleanup/idle-shutdown.test.ts index 4c24b03d7..ed332ab1c 100644 --- a/src/core/cleanup/idle-shutdown.test.ts +++ b/src/core/cleanup/idle-shutdown.test.ts @@ -7,6 +7,7 @@ const config: Config = { mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 0 }, + gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, drivers: {}, eventBuffer: { capacity: 1 }, health: { diff --git a/src/core/config.test.ts b/src/core/config.test.ts index 1b314be69..215e5cfc6 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -123,7 +123,7 @@ describe("loadConfig", () => { ).rejects.toThrow("mode"); }); - it("rejects mode: gateway with http.enabled: false at load", async () => { + it("defaults a gateway to http.enabled and rejects one that turns it off at load", async () => { // ADR 0005 §2: a gateway is the fleet's contact point over both HTTP and its unix socket, // so one with HTTP off is unreachable by any worker or agent -- a config with no safe // reading, rejected the same way a self-contradicting lease TTL pair is (naming the key, @@ -131,11 +131,14 @@ describe("loadConfig", () => { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/home/agent/.simlock"); - // The default is `http.enabled: false`, so naming only `mode` already triggers this. + // A gateway defaults `http.enabled` to true (it is the fleet's contact point), so naming + // only `mode` is a complete, valid gateway config rather than a rejected one. Only a + // config that says `false` out loud is refused -- a value the operator wrote and the + // daemon quietly inverted would be worse than a start that says why. await filesystem.writeFileAtomic(configPath, JSON.stringify({ mode: "gateway" })); await expect( loadConfig({ configPath, filesystem, systemStats: createStats() }), - ).rejects.toThrow("http.enabled"); + ).resolves.toMatchObject({ http: { enabled: true }, mode: "gateway" }); await filesystem.writeFileAtomic( configPath, @@ -976,6 +979,172 @@ describe("loadConfig legacy capacity keys", () => { }); }); +/** + * ADR 0005 §1/§2: `mode` selects what the daemon is, and a gateway reads only `mode`, `http.*`, + * `log.*`, `lease.*`, `eventBuffer.*` and `gateway.*`. + */ +describe("loadConfig modes (ADR 0005)", () => { + async function load( + contents: unknown, + options: { + readonly overrides?: Parameters[0]["overrides"]; + readonly warn?: (message: string) => void; + } = {}, + ) { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/agent/.simlock"); + await filesystem.writeFileAtomic(configPath, JSON.stringify(contents)); + return loadConfig({ + configPath, + filesystem, + systemStats: createStats(), + ...(options.overrides === undefined ? {} : { overrides: options.overrides }), + ...(options.warn === undefined ? {} : { warn: options.warn }), + }); + } + + it("defaults to worker mode, with HTTP off and a 24h disconnected-view retention", async () => { + const config = await load({}); + + expect(config.mode).toBe("worker"); + expect(config.http.enabled).toBe(false); + expect(config.gateway).toEqual({ + disconnectedRetentionMs: 24 * 60 * 60_000, + execTimeoutMs: 11 * 60_000, + }); + }); + + it("rejects a mode outside the two the ADR names", async () => { + await expect(load({ mode: "hybrid" })).rejects.toThrow("mode"); + }); + + it("turns HTTP on by default in gateway mode -- a gateway is the fleet's contact point", async () => { + const config = await load({ mode: "gateway" }); + + expect(config.http.enabled).toBe(true); + expect(config.http.port).toBe(4700); + }); + + it("refuses a gateway that switches HTTP off, naming the key", async () => { + await expect(load({ mode: "gateway", http: { enabled: false } })).rejects.toThrow( + "http.enabled", + ); + }); + + it("keeps an explicit gateway http host/port", async () => { + const config = await load({ mode: "gateway", http: { host: "0.0.0.0", port: 4800 } }); + + expect(config.http).toEqual({ enabled: true, host: "0.0.0.0", port: 4800 }); + }); + + it("warns about worker-only keys in a gateway's config and ignores them", async () => { + const warn = vi.fn(); + const config = await load( + { + mode: "gateway", + capacity: { strategy: "fixed", config: { maxRunning: 3 } }, + ios: { slim: { enabled: true } }, + lease: { defaultTtlMs: 60_000 }, + }, + { warn }, + ); + + expect(warn).toHaveBeenCalledWith(expect.stringContaining('Ignoring "capacity"')); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('Ignoring "ios"')); + // Ignored, not rejected: the file still loads, and the gateway-readable keys still apply. + expect(config.lease.defaultTtlMs).toBe(60_000); + // "Ignored" means "nothing in gateway mode reads it" -- the value is still parsed and + // merged, so a config file can be shared between a worker and a gateway with only `mode` + // differing. The warning is what makes that visible rather than silent. + expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('Ignoring "lease"')); + }); + + it("warns about the worker-side gateway.* keys on a gateway, but not the gateway's own", async () => { + const warn = vi.fn(); + const config = await load({ + mode: "gateway", + gateway: { + url: "ws://127.0.0.1:4700/v1/uplink", + token: "secret", + label: "ignored", + disconnectedRetentionMs: 60_000, + }, + }); + + expect(config.gateway.disconnectedRetentionMs).toBe(60_000); + + const warned = await load( + { mode: "gateway", gateway: { url: "ws://127.0.0.1:4700/v1/uplink" } }, + { warn }, + ); + expect(warned.mode).toBe("gateway"); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('Ignoring "gateway.url"')); + expect(warn).not.toHaveBeenCalledWith( + expect.stringContaining('Ignoring "gateway.disconnectedRetentionMs"'), + ); + }); + + it("says nothing about worker keys on a worker, which is every daemon today", async () => { + const warn = vi.fn(); + await load({ capacity: { strategy: "fixed", config: { maxRunning: 3 } } }, { warn }); + + expect(warn).not.toHaveBeenCalled(); + }); + + it("keeps a worker's gateway.url/token/label", async () => { + const config = await load({ + gateway: { url: "wss://fleet.example", token: "join-secret", label: "mac-1" }, + }); + + expect(config.gateway.url).toBe("wss://fleet.example"); + expect(config.gateway.token).toBe("join-secret"); + expect(config.gateway.label).toBe("mac-1"); + }); + + it("refuses a worker that names a gateway but no join token, and the reverse", async () => { + // Either alone is an operator half-finishing a join, and a worker that silently never + // joined looks exactly like one whose gateway is down -- so this fails the start instead. + await expect(load({ gateway: { url: "ws://fleet.example" } })).rejects.toThrow("gateway.token"); + await expect(load({ gateway: { token: "join-secret" } })).rejects.toThrow("gateway.url"); + }); + + it("does not pair those keys on a gateway, which reads neither", async () => { + const warn = vi.fn(); + await expect( + load({ mode: "gateway", gateway: { url: "ws://fleet.example" } }, { warn }), + ).resolves.toBeDefined(); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('Ignoring "gateway.url"')); + }); + + it.each(["http://fleet.example/v1/uplink", "fleet.example", "not a url"])( + "rejects a gateway.url that is not a WebSocket URL: %s", + async (url) => { + await expect(load({ gateway: { url } })).rejects.toThrow("gateway.url"); + }, + ); + + it("rejects a non-positive disconnected retention", async () => { + await expect(load({ gateway: { disconnectedRetentionMs: 0 } })).rejects.toThrow( + "gateway.disconnectedRetentionMs", + ); + }); + + it("defaults the gateway exec backstop above the worker's own ten minutes", async () => { + // ADR 0005 §19e: the worker's timeout is authoritative, so the gateway's must not fire + // first -- a gateway that timed out earlier would report a failure for a command still + // running on the machine that owns the device. #118 is what reads it. + const config = await load({ mode: "gateway" }); + expect(config.gateway.execTimeoutMs).toBe(11 * 60_000); + }); + + it("lets an override name the mode, like every other key", async () => { + const config = await load({}, { overrides: { mode: "gateway" } }); + + expect(config.mode).toBe("gateway"); + expect(config.http.enabled).toBe(true); + }); +}); + describe("effectiveAllowDownload", () => { it("grants downloads for every request under the always policy", () => { expect(effectiveAllowDownload("always", false)).toBe(true); diff --git a/src/core/config.ts b/src/core/config.ts index 1a1c3b369..834588f78 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -42,6 +42,13 @@ export const DEFAULT_LEASE_TTL_MS = 15 * 60_000; /** `lease.maxTtlMs`'s default: the largest TTL any request or renew may ask for. */ const DEFAULT_LEASE_MAX_TTL_MS = 4 * 60 * 60_000; +/** `gateway.disconnectedRetentionMs`'s default (ADR 0005 §6): 24 hours. */ +const DEFAULT_DISCONNECTED_RETENTION_MS = 24 * 60 * 60_000; + +/** `gateway.execTimeoutMs`'s default (ADR 0005 §19e): eleven minutes, one more than the + * worker's authoritative ten, so the worker's timeout is the one that fires. */ +const DEFAULT_GATEWAY_EXEC_TIMEOUT_MS = 11 * 60_000; + /** * `exec.timeoutMs`'s default (ADR 0005 §19e): how long a single `device.exec` command may run * on this worker before it is killed and the operation fails with `EXEC_TIMEOUT`. Ten minutes, @@ -69,7 +76,7 @@ export type DaemonMode = "worker" | "gateway"; export interface Config { /** See `DaemonMode`. Reported on `status.get`'s daemon block, which is how a client tells - * the two apart; the gateway behaviour itself lands with #117. */ + * the two apart. Default `"worker"`. */ readonly mode: DaemonMode; readonly capacity: CapacityConfig; /** @@ -144,6 +151,48 @@ export interface Config { readonly bootTimeoutMs: number; }; }; + /** + * ADR 0005 §3/§6. Both sides of the fleet live under one key, and which half is read depends + * on `mode`: + * + * - a **worker** reads `url`, `token`, and `label` -- the two keys that join a fleet, plus a + * display name. Absent `url`/`token` simply means "this worker has no gateway", which is + * every worker today. + * - a **gateway** reads `disconnectedRetentionMs` and ignores the other three with a + * warning (`loadConfig` reports every worker-only key it finds in a gateway's config). + * + * Kept as one block rather than `gateway.*` / `worker.*` blocks because both halves are + * facts about the same relationship, and a `worker.gateway.url` spelling reads worse than + * the thing it configures. + */ + readonly gateway: { + /** The gateway's uplink endpoint, `ws://host:port/v1/uplink` or `wss://...`. Worker-side. */ + readonly url?: string; + /** A join token minted on the gateway with `simlock token create --role worker`. + * Worker-side. It is a secret, and it sits in the daemon's config file like any other + * value there: `config.get` is admin-role and returns the config as written, so this key + * is exactly as sensitive as `config.json`'s file permissions make it. See + * docs/CONFIGURATION.md. */ + readonly token?: string; + /** Display-only name for this worker in the gateway's views (§3a, §13). Worker-side. */ + readonly label?: string; + /** + * How long a gateway keeps a disconnected worker's view before forgetting it (§6). + * Gateway-side. Default 24 hours: long enough that a machine rebooting overnight is still + * the same machine in the morning, short enough that a decommissioned one does not haunt + * `simlock status` forever. A view whose leases have not all expired is never dropped on + * this timer, however long it has been gone. + */ + readonly disconnectedRetentionMs: number; + /** + * Gateway-side backstop on a proxied `device.exec` (ADR 0005 §19e). Deliberately longer + * than the worker's own `exec.timeoutMs` (ten minutes): the worker's is authoritative and + * should be what kills a runaway command, so a gateway that timed out first would report + * a failure for a command still running on the machine that owns the device. Read by #118, + * which is what proxies `device.exec`; declared now so the key does not appear mid-series. + */ + readonly execTimeoutMs: number; + }; readonly stalledTransition: { /** * Applied to the driver's own estimate (`provision + boot` for `provisioning`, @@ -194,6 +243,10 @@ export async function loadConfig({ // defaulted: it decides which options block `capacity.config` is, and which // defaults the merge starts from. const strategy = resolveStrategyName([fromFile, fromOverrides]); + // Same reason as the strategy above: `mode` decides which keys are read at all, and what + // `http.enabled` defaults to, so it has to be known before anything is defaulted or warned + // about. + const mode = resolveMode([fromFile, fromOverrides]); const validators = configValidators(strategy); const fileConfig = normalizeLayer( @@ -208,11 +261,18 @@ export async function loadConfig({ ); const merged = mergeConfig( - mergeConfig(defaultConfig(systemStats, strategy), fileConfig), + mergeConfig(defaultConfig(systemStats, strategy, mode), fileConfig), overrideConfig, ) as unknown as Config; validateLeaseTtls(merged); - validateGatewayNeedsHttp(merged); + if (mode === "gateway") { + warnWorkerOnlyKeys([fromFile, fromOverrides], warn); + requireGatewayHttp(merged); + } else { + // Worker-side only: a gateway ignores these keys entirely (it dials nobody), so pairing + // them there would fail a start over a value nothing reads. + validateGatewayMembership(merged); + } return deepFreeze(merged); } @@ -244,22 +304,121 @@ function validateLeaseTtls(config: Config): void { } /** - * Cross-field check (ADR 0005 §2): a gateway is the fleet's contact point, over both HTTP and - * its unix socket, so `http.enabled: false` on a `gateway` daemon describes one nothing could - * ever reach -- no worker could open an uplink to it and no agent could lease through it. That - * has no safe reading to fall back on (unlike a `worker`, for which HTTP is genuinely - * optional), so it fails the daemon start naming the key rather than starting a gateway that - * can never do the one thing a gateway is for. `mode` itself decides which driver-starting, - * device-root-validating half of `gateway` mode actually runs (the rest of ADR 0005 §2, - * #117's scope) -- this check is purely a config-shape rule with no dependency on that, - * which is why it belongs here rather than waiting on it. + * The config keys a gateway reads (ADR 0005 §2). Everything else in a gateway's config is a + * worker-only key: it configures drivers, devices, capacity, or cleanup, none of which a + * gateway has. Listed here rather than derived from `Config`'s shape because the *set* is the + * decision -- adding a key to `Config` should not silently make it gateway-relevant. + */ +const GATEWAY_CONFIG_KEYS: readonly string[] = [ + "mode", + "http", + "log", + "lease", + "eventBuffer", + "gateway", +]; + +/** The `gateway.*` sub-keys a *worker* reads. A gateway ignores these three (it dials nobody); + * `disconnectedRetentionMs` and `execTimeoutMs` are the ones the gateway itself reads. */ +const WORKER_ONLY_GATEWAY_KEYS: readonly string[] = ["url", "token", "label"]; + +/** + * ADR 0005 §2: "worker-only keys in a gateway's config are ignored with a warning, as unknown + * keys are today". Warned per key the operator actually wrote (the file and override layers), + * never per defaulted key -- a gateway's own defaults contain the whole worker-side `Config` + * shape, and warning about those would fire on every start with nothing to fix. + * + * Ignoring rather than failing is the deliberate choice the ADR makes, and it is what lets one + * config file be copied between a worker and a gateway while only `mode` differs. + */ +function warnWorkerOnlyKeys(layers: readonly unknown[], warn: Warn): void { + for (const layer of layers) { + const object = requireObject(layer, "config"); + for (const key of Object.keys(object)) { + if (!GATEWAY_CONFIG_KEYS.includes(key)) { + warn(`Ignoring "${key}": it configures a worker, and this daemon runs in gateway mode.`); + } + } + const gateway = object["gateway"]; + if (gateway === undefined) continue; + for (const key of Object.keys(requireObject(gateway, "gateway"))) { + if (WORKER_ONLY_GATEWAY_KEYS.includes(key)) { + warn( + `Ignoring "gateway.${key}": it points a worker at its gateway, ` + + `and this daemon runs in gateway mode.`, + ); + } + } + } +} + +/** + * ADR 0005 §2: "a gateway always listens on HTTP (it is the fleet's contact point) and on its + * unix socket". HTTP is not optional for a gateway in a way it is for a worker: it is how + * every agent reaches the fleet *and* the transport the worker uplink upgrades from + * (`/v1/uplink`), so a gateway with `http.enabled: false` is a process nothing can reach and + * no worker can join. + * + * The default is flipped to `true` for a gateway (see `defaultConfig`), so this only ever + * fires for a config that says `false` out loud. That is refused rather than silently + * overridden, on the same reasoning as `lease.defaultTtlMs > lease.maxTtlMs`: a value the + * operator wrote and the daemon quietly inverted is worse than a start that says why. */ -function validateGatewayNeedsHttp(config: Config): void { - if (config.mode === "gateway" && !config.http.enabled) { - throw invalidValue("http.enabled", 'true when mode is "gateway"'); +function requireGatewayHttp(config: Config): void { + if (!config.http.enabled) { + throw invalidValue("http.enabled", "true in gateway mode (a gateway is reached over HTTP)"); } } +/** + * A worker's fleet membership, checked at load rather than at dial time so a typo fails the + * daemon start naming the key instead of surfacing as an endless reconnect loop hours later. + * + * `gateway.url` is the gateway's **base** URL (`ws://host:port`); the worker derives the + * uplink endpoint (`/v1/uplink`) from it, so nothing here inspects the path -- a URL that + * already carries one is accepted and the endpoint is resolved against it, which is what makes + * a reverse proxy on a sub-path work. + * + * The two keys are required together: a URL with no token cannot authenticate and a token with + * no URL has nowhere to go, and either alone is an operator half-finishing a join. Failing the + * start is right where ignoring would be wrong -- a worker that silently never joined would + * look identical to one whose gateway is down. + */ +function validateGatewayMembership(config: Config): void { + const { token, url } = config.gateway; + if (url !== undefined) { + let parsed: URL; + try { + parsed = new URL(url); + } catch { + throw invalidValue("gateway.url", "a ws:// or wss:// URL"); + } + if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") { + throw invalidValue("gateway.url", "a ws:// or wss:// URL"); + } + } + if (url !== undefined && token === undefined) { + throw invalidValue("gateway.token", "a join token, since gateway.url is set"); + } + if (token !== undefined && url === undefined) { + throw invalidValue("gateway.url", "a gateway URL, since gateway.token is set"); + } +} + +/** Last layer that names a mode wins; absent everywhere means `worker` (ADR 0005 §1). */ +function resolveMode(layers: readonly unknown[]): DaemonMode { + let resolved: DaemonMode = "worker"; + for (const layer of layers) { + const candidate = requireObject(layer, "config")["mode"]; + if (candidate === undefined) continue; + if (candidate !== "worker" && candidate !== "gateway") { + throw invalidValue("mode", 'one of "worker", "gateway"'); + } + resolved = candidate; + } + return resolved; +} + /** Last layer that names a strategy wins; absent everywhere means the default. */ function resolveStrategyName(layers: readonly unknown[]): CapacityStrategyName { let resolved: CapacityStrategyName = DEFAULT_CAPACITY_STRATEGY; @@ -332,9 +491,13 @@ function asObject(value: unknown): Layer { return isObject(value) ? value : {}; } -function defaultConfig(systemStats: SystemStats, strategy: CapacityStrategyName): Config { +function defaultConfig( + systemStats: SystemStats, + strategy: CapacityStrategyName, + mode: DaemonMode, +): Config { return { - mode: "worker", + mode, capacity: { strategy, config: defaultCapacityOptions(strategy, systemStats), @@ -365,7 +528,10 @@ function defaultConfig(systemStats: SystemStats, strategy: CapacityStrategyName) diskPressure: { freeBytesThreshold: 10 * 1024 ** 3 }, eventBuffer: { capacity: 1_000 }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, - http: { enabled: false, host: "127.0.0.1", port: 4700 }, + // ADR 0005 §2: a gateway always listens on HTTP, so that is its default rather than + // something every operator has to remember to switch on; a worker's HTTP gateway stays + // opt-in exactly as before. + http: { enabled: mode === "gateway", host: "127.0.0.1", port: 4700 }, health: { enabled: true, probeIntervalMs: 30_000, @@ -380,6 +546,10 @@ function defaultConfig(systemStats: SystemStats, strategy: CapacityStrategyName) bootTimeoutMs: 600_000, }, }, + gateway: { + disconnectedRetentionMs: DEFAULT_DISCONNECTED_RETENTION_MS, + execTimeoutMs: DEFAULT_GATEWAY_EXEC_TIMEOUT_MS, + }, stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000, @@ -428,8 +598,8 @@ function validateConfigLayer( } const LOG_LEVELS: readonly LogLevel[] = ["debug", "info", "warn", "error"]; -const DOWNLOAD_POLICIES: readonly DownloadPolicy[] = ["never", "on-request", "always"]; const DAEMON_MODES: readonly DaemonMode[] = ["worker", "gateway"]; +const DOWNLOAD_POLICIES: readonly DownloadPolicy[] = ["never", "on-request", "always"]; /** * The `capacity.config` validator is the selected strategy's own, so a strategy @@ -438,6 +608,13 @@ const DAEMON_MODES: readonly DaemonMode[] = ["worker", "gateway"]; function configValidators(strategy: CapacityStrategyName): Record { return { mode: stringUnion(DAEMON_MODES), + gateway: objectValidator({ + url: stringValue, + token: stringValue, + label: stringValue, + disconnectedRetentionMs: positiveNumber, + execTimeoutMs: positiveNumber, + }), capacity: objectValidator({ strategy: stringUnion(capacityStrategyNames), config: capacityStrategyValidator(strategy), diff --git a/src/core/doctor.test.ts b/src/core/doctor.test.ts index 8205a0beb..67bf39966 100644 --- a/src/core/doctor.test.ts +++ b/src/core/doctor.test.ts @@ -1854,6 +1854,7 @@ function config(stalledTransitionOverrides: Partial mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 1 }, + gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, drivers: {}, eventBuffer: { capacity: 10 }, health: { diff --git a/src/core/index.ts b/src/core/index.ts index c7cee6f37..a1d4bee80 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -1,6 +1,8 @@ export { type Config, type ConfigOverrides, + // fallow-ignore-next-line unused-type -- public Config surface (config.mode, ADR 0005 §1); every in-tree reader gets it structurally off `Config` + type DaemonMode, // fallow-ignore-next-line unused-type -- public Config surface (config.downloads.policy); no in-tree consumer names it directly yet type DownloadPolicy, effectiveAllowDownload, diff --git a/src/core/lease-acquisition-coordinator.test.ts b/src/core/lease-acquisition-coordinator.test.ts index 4903fee63..b681a4fd4 100644 --- a/src/core/lease-acquisition-coordinator.test.ts +++ b/src/core/lease-acquisition-coordinator.test.ts @@ -28,6 +28,7 @@ function config(maxDevices = 1): Config { mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, + gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, drivers: {}, downloads: { acceptAndroidLicenses: false, policy: "on-request", timeoutMs: 1_200_000 }, eventBuffer: { capacity: 100 }, diff --git a/src/core/lease-engine.test.ts b/src/core/lease-engine.test.ts index 61b179607..0b4297090 100644 --- a/src/core/lease-engine.test.ts +++ b/src/core/lease-engine.test.ts @@ -25,6 +25,7 @@ function config(overrides: Partial = {}): Config { mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, + gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, drivers: {}, downloads: { acceptAndroidLicenses: false, policy: "on-request", timeoutMs: 1_200_000 }, eventBuffer: { capacity: 100 }, diff --git a/src/core/lease-health-monitor.test.ts b/src/core/lease-health-monitor.test.ts index 98b49dd2c..be19002c0 100644 --- a/src/core/lease-health-monitor.test.ts +++ b/src/core/lease-health-monitor.test.ts @@ -20,6 +20,7 @@ function config(overrides: Partial = {}): Config { mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, + gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, drivers: {}, eventBuffer: { capacity: 100 }, warmPool: { diff --git a/src/core/nuke.test.ts b/src/core/nuke.test.ts index 229d94bd7..703abfcc5 100644 --- a/src/core/nuke.test.ts +++ b/src/core/nuke.test.ts @@ -148,6 +148,7 @@ function config(): Config { mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 1 }, + gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, drivers: {}, eventBuffer: { capacity: 10 }, health: { diff --git a/src/core/reaper.test.ts b/src/core/reaper.test.ts index 2b7f87f30..a8df99721 100644 --- a/src/core/reaper.test.ts +++ b/src/core/reaper.test.ts @@ -47,6 +47,7 @@ function config(): Config { mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, + gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, drivers: {}, eventBuffer: { capacity: 100 }, health: { diff --git a/src/core/warm-pool-coordinator.test.ts b/src/core/warm-pool-coordinator.test.ts index 0132878fd..7a6f34cc1 100644 --- a/src/core/warm-pool-coordinator.test.ts +++ b/src/core/warm-pool-coordinator.test.ts @@ -18,6 +18,7 @@ const config: Config = { mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, + gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, drivers: {}, eventBuffer: { capacity: 100 }, health: { diff --git a/src/daemon-protocol/index.test.ts b/src/daemon-protocol/index.test.ts index 9601ca6b3..8e128d67c 100644 --- a/src/daemon-protocol/index.test.ts +++ b/src/daemon-protocol/index.test.ts @@ -9,10 +9,11 @@ import { describe("daemon protocol", () => { it("keeps the current protocol version and newline framing", () => { - // ADR 0005: protocol 5, no compatibility shim -- `device.exec`, its `output` push family - // and `status.get`'s always-present `mode` land on the wire with nothing kept behind them, - // exactly as ADR 0004's removals took it to 4, so under ADR 0003 §6's honesty rule the - // range does not widen to keep speaking 4. + // ADR 0005: protocol 5, no compatibility shim -- `device.exec`, its `output` push family, + // `status.get`'s always-present `mode`, and the gateway surface (`worker.*`, `workerId`, + // the `worker` token role) all land on the wire with nothing kept behind them, exactly as + // ADR 0004's removals took it to 4, so under ADR 0003 §6's honesty rule the range does not + // widen to keep speaking 4. expect(DAEMON_PROTOCOL_VERSION).toBe(5); expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n'); }); diff --git a/src/daemon/dispatch.ts b/src/daemon/dispatch.ts new file mode 100644 index 000000000..5f8aee952 --- /dev/null +++ b/src/daemon/dispatch.ts @@ -0,0 +1,240 @@ +/** + * The transport-facing half of ADR 0003 §2's dispatcher: the session a transport hands to + * `dispatch()`, the rejection a dispatcher throws, and the `dispatch()` signature itself. + * + * These three declarations live in their own module -- rather than beside the worker's + * `Dispatcher` in `dispatcher.ts` -- because ADR 0005 §32 gives the contract a *second* + * implementation: `src/gateway/`'s handlers read worker views and forward over uplinks instead + * of calling `core`. Both implementations are reached by the same transports (the socket + * server, the HTTP app), so both need this vocabulary, and the gateway must be able to import + * it without importing `src/core` through the back door -- which is exactly what importing + * `dispatcher.ts` would do (see `src/gateway/boundary.test.ts`). + * + * Nothing here imports from `src/core`, `src/drivers`, or `src/http`; the contract module and + * its zod-inferred types are the whole dependency surface. + */ +import type { z } from "zod"; + +import { + describeSchemaIssues, + OPERATIONS, + type AuthorizeContext, + type OperationDefinition, + type OperationName, + type Role, + type leaseProgressSchema, +} from "../contract/index.js"; + +/** + * Request-scoped progress, as the contract declares it. Structurally identical to `core`'s own + * `LeaseProgress` (src/core/wait-queue.ts) -- the worker's dispatcher passes one straight + * through to the other -- but named from the contract here so this module stays core-free. + */ +export type DispatchProgress = z.infer; + +/** + * ADR 0003 §2's "session" argument to `dispatch`. Constructed fresh per call by the transport + * (`DaemonServer`, one per socket request; the HTTP app, one per HTTP request) from whatever + * longer-lived state it owns -- this type does not itself track anything across calls. + * + * `principal`/`role` are the ADR §4/§5 identity: fixed for the connection's lifetime once + * `hello` resolves them (see `session.ts`'s `SessionRoleResolver` seam). ADR 0004 removed the + * two connection-scoped fields that used to sit beside them (`heldLeaseIds`, + * `heartbeatCapability`): the daemon keeps no per-connection lease state at all any more. + * `onProgress` and `manageEventSubscription` are the two places a request-scoped or + * connection-scoped push actually reaches the wire -- `DaemonServer` supplies closures that + * write socket frames; an HTTP session can leave `onProgress` unset and no-op on + * `events.subscribe`, since HTTP has no open connection to push through even in principle + * (ADR §8's "the HTTP notice buffer stays"). + */ +export interface DispatchSession { + readonly principal: string; + readonly role: Role; + /** Called for each progress update while this specific `lease.request` call is in flight. + * Ignored by every other operation. */ + readonly onProgress?: (progress: DispatchProgress) => void; + /** + * Called for each chunk a `device.exec` command writes, as it writes it (ADR 0005 §19a's + * `output` push family). Ignored by every other operation, and left unset by a transport + * that has nowhere to put a chunk -- in which case the command still runs and still reports + * its exit code, and the output is simply not relayed. The same shape as `onProgress`, for + * the same reason: both are request-scoped pushes, and the dispatcher stays out of framing. + * + * **May return a promise**, and the command is stopped at its pipe until that resolves (see + * `ProcessStreamOptions.onChunk`). A transport returns one when placing a chunk is not + * instantaneous -- an SSE write, a socket frame -- so a client that reads slowly slows the + * command rather than filling this process with its output (§19e). + */ + readonly onOutput?: (stream: "stdout" | "stderr", chunk: string) => void | Promise; + /** + * Called once, for a `device.exec` call, the moment its process is running -- after every + * failure that can happen *before* one exists (a refused verb, an unknown tool, an unowned + * lease, a daemon still starting) and before any output. A transport that has to commit to + * a response shape uses it as the decision point: HTTP opens its event stream here, so a + * command that prints nothing for nine minutes still gets its `200` and its keepalives, and + * an `EXEC_TIMEOUT` always arrives as that stream's terminal event rather than as a status + * code the client cannot receive any more (ADR 0005 §19e). + */ + readonly onStarted?: () => void; + /** `events.subscribe`/`events.unsubscribe` stay push-shaped (ADR §2: "pushes" stay with the + * transport), so the dispatcher's handler for them does nothing but call this: `true` to + * (re)subscribe, returning the new subscription id; `false` to tear an existing one down. */ + readonly manageEventSubscription: (subscribe: boolean) => string | undefined; +} + +/** Thrown for a role/ownership rejection or a malformed request; `DaemonServer` maps this the + * same way it already maps its own protocol errors (see `errorCode` in `server.ts`), and + * `classifyError` trusts its `code` verbatim (see `error-code.ts`). */ +export class DispatchError extends Error { + constructor( + readonly code: string, + message: string, + readonly details?: unknown, + ) { + super(message); + this.name = "DispatchError"; + } +} + +/** + * What a transport needs from a dispatcher, and all it needs: one call that takes an operation + * name, a raw input, and a session. `Dispatcher` (worker, `dispatcher.ts`) and + * `GatewayDispatcher` (`src/gateway/dispatcher.ts`) both satisfy it, which is what lets + * `DaemonServer` serve either without knowing which mode it is running in (ADR 0005 §32: + * "the gateway is a second implementation of the daemon contract's handlers, not a second + * contract"). + */ +export interface ContractDispatcher { + dispatch( + operation: Op, + rawInput: unknown, + session: DispatchSession, + ): Promise>; +} + +// ---- the shared dispatch pipeline ------------------------------------------------------------ + +/** + * A handler, erased to `never` input so a lookup table can hold every operation's handler side + * by side. Each implementation keeps its own strongly-typed handler declarations (see + * `Dispatcher`'s `Handler` and the gateway's) and only the table erases them; `runDispatch` + * casts the already-schema-validated input back to `never` at the one call site that needs it. + */ +export type ErasedHandler = (input: never, session: DispatchSession) => Promise | unknown; + +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. */ + 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` + * for both lookups, which every hook treats as authorized on purpose, so the handler's own + * error surfaces instead of a misleading `FORBIDDEN`. */ + readonly authorizeLookups?: Pick< + AuthorizeContext, + "leaseRequesterId" | "ownerId" | "pendingRequestOwner" + >; + /** ADR 0003 §2 step 4: every operation but `status.get` parks here before its handler runs. + * Omitted when there is nothing to wait for. */ + readonly awaitReady?: () => Promise; + /** Called when a handler's result fails its contract output schema -- always a daemon-side + * bug, so both implementations log it before the caller sees a generic `INTERNAL`. */ + readonly onOutputMismatch?: (operation: string, issues: readonly unknown[]) => void; +} + +/** + * ADR 0003 §2's ordering, once, for both implementations of the contract: parse input, role + * check, `authorize` hook, park on startup readiness, call handler, parse output. Handlers + * never see a raw payload or run their own role/ownership check -- both already happened by + * the time a handler's body runs. + * + * Shared rather than copied because it *is* the contract's enforcement: a gateway that checked + * roles slightly differently from a worker would be a second contract wearing the first one's + * name (§32 says the gateway is a second set of handlers, and nothing else). + */ +export async function runDispatch( + operation: Op, + rawInput: unknown, + session: DispatchSession, + pipeline: DispatchPipeline, +): Promise> { + // "Generic-over-a-closed-union" cast: `OPERATIONS[operation]` for a generic `Op` collapses to + // a union across every operation, and TypeScript refuses to call a union of functions + // (`.role`, `.authorize`) with a generically-typed argument even though each concrete + // instantiation is sound. `OPERATIONS` is a closed, exhaustively-typed record validated by + // its own test suite -- this cast trusts that shape, not the runtime, unlike `input as never` + // below (which truly is unverified until `parseDispatchInput` runs). + const definition = OPERATIONS[operation] as unknown as OperationDefinition; + const handler = pipeline.handlers[operation]; + if (handler === undefined) { + throw new DispatchError("UNKNOWN_REQUEST", `Unknown request type: ${operation}`); + } + + const input = parseDispatchInput(definition.input, rawInput ?? {}); + const requiredRole: Role = + typeof definition.role === "function" ? definition.role(input) : definition.role; + if (!roleSatisfies(session.role, requiredRole)) { + throw new DispatchError( + "FORBIDDEN", + `Operation ${operation} requires role ${requiredRole}, session is ${session.role}`, + ); + } + if (definition.authorize !== undefined) { + const context: AuthorizeContext = { + leaseRequesterId: pipeline.authorizeLookups?.leaseRequesterId ?? (() => undefined), + ownerId: pipeline.authorizeLookups?.ownerId ?? (() => undefined), + pendingRequestOwner: pipeline.authorizeLookups?.pendingRequestOwner ?? (() => undefined), + principal: session.principal, + role: session.role, + }; + if (!definition.authorize(input, context)) { + throw new DispatchError("FORBIDDEN", `Not authorized for ${operation}`); + } + } + + if (operation !== "status.get") { + await pipeline.awaitReady?.(); + } + + const output = await handler(input as never, session); + return parseDispatchOutput( + definition.output, + output, + operation, + pipeline.onOutputMismatch, + ) as z.infer<(typeof OPERATIONS)[Op]["output"]>; +} + +function roleSatisfies(sessionRole: Role, required: Role): boolean { + return sessionRole === "admin" || required === "agent"; +} + +function parseDispatchInput(schema: z.ZodType, value: unknown): Output { + const result = schema.safeParse(value); + if (result.success) return result.data; + throw new DispatchError("BAD_REQUEST", describeSchemaIssues(result.error.issues)); +} + +/** + * Validates a handler's return value against its contract output schema before it goes on the + * wire. A mismatch is always a daemon-side bug (the schema or the mapping is wrong -- never + * loosen the schema to whatever happens to be emitted), so it is reported to + * `onOutputMismatch` and then thrown as a plain `Error`, which maps to `INTERNAL`. `.parse` + * is deliberately non-strict: an additive field a handler starts returning before its schema + * declares it is dropped, not a failure -- only a missing or mistyped *declared* field is a + * bug worth failing loudly over. + */ +function parseDispatchOutput( + schema: z.ZodType, + value: unknown, + operationName: string, + onMismatch?: (operation: string, issues: readonly unknown[]) => void, +): Output { + const result = schema.safeParse(value); + if (result.success) return result.data; + onMismatch?.(operationName, result.error.issues); + throw new Error( + `Internal: ${operationName} produced a response that does not match its contract output schema`, + ); +} diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 5512e729b..800612c6d 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -1253,6 +1253,7 @@ function testConfig( ): Config { return { mode: "worker", + gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, drivers: {}, exec: { timeoutMs: 600_000, ...execOverrides }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 4e03bdda9..c83d9a480 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -7,7 +7,6 @@ import { type DeviceRecord, type DeviceRequest, type Doctor, - type LeaseProgress, type Nuke, type Registry, effectiveAllowDownload, @@ -31,66 +30,26 @@ import type { } from "../ports/index.js"; import { exitCodeOf, NoopLogger } from "../ports/index.js"; import { - describeSchemaIssues, OPERATIONS, - type OperationDefinition, + type GatewayOnlyOperationName, type OperationName, - type AuthorizeContext, - type Role, } from "../contract/index.js"; import type { TokenStore } from "../http/token-store.js"; - -/** - * ADR 0003 §2's "session" argument to `dispatch`. Constructed fresh per call by the transport - * (today: `DaemonServer`, one per socket request) from whatever longer-lived state it owns -- - * this type does not itself track anything across calls. - * - * `principal`/`role` are the ADR §4/§5 identity: fixed for the connection's lifetime once - * `hello` resolves them (see `session.ts`'s `SessionRoleResolver` seam -- PR 2's credential - * handshake replaces how `role` is computed, not this shape). ADR 0004 removes the two - * connection-scoped fields that used to sit beside them (`heldLeaseIds`, - * `heartbeatCapability`): the daemon keeps no per-connection lease state at all any more, and - * the one operation that read them is gone. `onProgress` and `manageEventSubscription` are the - * two places a request-scoped or connection-scoped push actually reaches the wire -- `DaemonServer` supplies - * closures that write socket frames; an HTTP session (next PR) can leave `onProgress` unset and - * fail loudly (or no-op) on `events.subscribe`, since HTTP has no open connection to push - * through even in principle (ADR §8's "the HTTP notice buffer stays"). +import { + DispatchError, + runDispatch, + type DispatchSession, + type ErasedHandler, +} from "./dispatch.js"; + +export { DispatchError, type ContractDispatcher, type DispatchSession } from "./dispatch.js"; + +/* + * `DispatchSession`, `DispatchError`, and `ContractDispatcher` moved to `./dispatch.js` when + * ADR 0005 gave the contract a second dispatcher implementation (`src/gateway/`), which needs + * them without importing this file's `src/core` dependencies. They are re-exported above, so + * every existing `from "./dispatcher.js"` import keeps working. */ -export interface DispatchSession { - readonly principal: string; - readonly role: Role; - /** Called for each progress update while this specific `lease.request` call is in flight. - * Ignored by every other operation. */ - readonly onProgress?: (progress: LeaseProgress) => void; - /** - * Called for each chunk a `device.exec` command writes, as it writes it (ADR 0005 §19a's - * `output` push family). Ignored by every other operation, and left unset by a transport - * that has nowhere to put a chunk -- in which case the command still runs and still reports - * its exit code, and the output is simply not relayed. The same shape as `onProgress`, for - * the same reason: both are request-scoped pushes, and the dispatcher stays out of framing. - * - * **May return a promise**, and the command is stopped at its pipe until that resolves (see - * `ProcessStreamOptions.onChunk`). A transport returns one when placing a chunk is not - * instantaneous -- an SSE write, a socket frame -- so a client that reads slowly slows the - * command rather than filling this process with its output (§19e). - */ - readonly onOutput?: (stream: "stdout" | "stderr", chunk: string) => void | Promise; - /** - * Called once, for a `device.exec` call, the moment its process is running -- after every - * failure that can happen *before* one exists (a refused verb, an unknown tool, an unowned - * lease, a daemon still starting) and before any output. A transport that has to commit to - * a response shape uses it as the decision point: HTTP opens its event stream here, so a - * command that prints nothing for nine minutes still gets its `200` and its keepalives, and - * an `EXEC_TIMEOUT` always arrives as that stream's terminal event rather than as a status - * code the client cannot receive any more (ADR 0005 §19e). - */ - readonly onStarted?: () => void; - /** `events.subscribe`/`events.unsubscribe` stay push-shaped (ADR §2: "pushes" stay with the - * transport), so the dispatcher's handler for them does nothing but call this: `true` to - * (re)subscribe, returning the new subscription id; `false` to tear an existing one down. */ - readonly manageEventSubscription: (subscribe: boolean) => string | undefined; -} - /** * How long a timed-out `device.exec` child gets between SIGTERM and SIGKILL (ADR 0005 §19e). * Fixed rather than derived from `exec.timeoutMs`: it is a termination-cleanup budget, not a @@ -103,18 +62,6 @@ const EXEC_SIGKILL_GRACE_MS = 10_000; * it can never collide with something a `StreamingProcessHandle` could resolve with. */ const EXEC_EXPIRED = Symbol("exec-expired"); -/** Thrown for a role/ownership rejection or a malformed request; `DaemonServer` maps this the - * same way it already maps its own protocol errors (see `errorCode` in `server.ts`). */ -export class DispatchError extends Error { - constructor( - readonly code: string, - message: string, - ) { - super(message); - this.name = "DispatchError"; - } -} - export class DoctorUnavailableError extends Error { constructor() { super("Doctor is unavailable"); @@ -195,15 +142,10 @@ type Handler = ( session: DispatchSession, ) => Promise | unknown; -/** The type `#handlers` and `dispatch()` actually traffic in: a `Handler` for some - * particular `Op`, erased to `never` input so the lookup table can hold every operation's - * handler side by side (a function accepting a narrower/`never` input is a valid supertype - * target for one accepting a wider input, so every concrete `Handler` assigns into this). - * `dispatch()` casts its already-schema-validated `input` to `never` at the one call site that - * needs it -- the same "trust the runtime validation, not the type checker" boundary every - * other generic-over-a-closed-union dispatch table in this codebase (e.g. `OPERATIONS` itself) - * accepts. */ -type AnyHandler = (input: never, session: DispatchSession) => 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; /** * The transport-independent dispatcher (ADR 0003 §2). One `dispatch()` call does, in order: @@ -211,7 +153,8 @@ type AnyHandler = (input: never, session: DispatchSession) => Promise | * output. Handlers never see a raw payload or run their own role/ownership check -- both * already happened by the time a handler's function body runs. * - * Deliberately excludes `hello` (protocol-level, answered before a session exists) and + * Deliberately excludes `hello` (protocol-level, answered before a session exists), the + * gateway-only `worker.*` operations (ADR 0005 §23 -- see `#handlers`), and * `daemon.stop` (ADR §6's frozen exception -- scoped to the protocol-version gate only, so it * stays reachable across a version mismatch; still requires a completed handshake and the * `admin` role, checked in `DaemonServer#dispatchLine` itself) -- both stay in `DaemonServer`, @@ -220,12 +163,20 @@ type AnyHandler = (input: never, session: DispatchSession) => Promise | export class Dispatcher { readonly #logger: Logger; /** - * Total over every operation but `daemon.stop`. Deliberately *not* a partial map: a - * declared operation whose handler was never written is otherwise invisible to the - * compiler and only shows up as `UNKNOWN_REQUEST` at runtime -- which is exactly how + * Total over every operation but `daemon.stop` and the gateway-only ones. Deliberately *not* + * a partial map: a declared operation whose handler was never written is otherwise invisible + * to the compiler and only shows up as `UNKNOWN_REQUEST` at runtime -- which is exactly how * `driver.passthrough` came to be declared, dispatched, and unimplemented at once. + * + * `GATEWAY_ONLY_OPERATIONS` (ADR 0005 §23: `worker.list|drain|undrain|remove`) are excluded + * from the type rather than given handlers that throw. A worker daemon has no worker + * registry to answer them from, and the honest answer is the one `dispatch()`'s own + * missing-handler guard already gives -- `UNKNOWN_REQUEST`, "this daemon does not implement + * that operation". Excluding them here also means adding a gateway operation cannot silently + * acquire a meaningless worker-side implementation: it either lands in + * `GATEWAY_ONLY_OPERATIONS` or the compiler asks for a handler in this map. */ - readonly #handlers: Record, AnyHandler>; + readonly #handlers: Record; constructor(private readonly options: DispatcherOptions) { this.#logger = options.logger ?? new NoopLogger(); @@ -256,59 +207,31 @@ export class Dispatcher { }; } - async dispatch( + /** 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. */ + dispatch( operation: Op, rawInput: unknown, session: DispatchSession, ): Promise> { - // Same "generic-over-a-closed-union" cast `AnyHandler` needed above: `OPERATIONS[operation]` - // for a generic `Op` collapses to a union across every operation, and TypeScript refuses to - // call a union of functions (`.role`, `.authorize`) with a generically-typed argument even - // though each concrete instantiation is sound. `OPERATIONS` is a closed, exhaustively-typed - // record (see `operations.ts`) validated by its own test suite -- this cast trusts that - // shape, not the runtime, so it is not the same kind of escape hatch as `input as never` - // below (that one truly is unverified until `parseInput` runs). - const definition = OPERATIONS[operation] as unknown as OperationDefinition; - // `#handlers` is total over every operation but `daemon.stop`, so the only `Op` this - // lookup can miss is that one -- and `DaemonServer` intercepts it before `dispatch()`. - // The cast states that; the guard below still covers a caller that ignores the rule, - // since an absent handler must not become `undefined is not a function`. - const handler: AnyHandler | undefined = - this.#handlers[operation as Exclude]; - if (handler === undefined) { - throw new DispatchError("UNKNOWN_REQUEST", `Unknown request type: ${operation}`); - } - - const input = parseInput(definition.input, rawInput ?? {}); - const requiredRole: Role = - typeof definition.role === "function" ? definition.role(input) : definition.role; - if (!roleSatisfies(session.role, requiredRole)) { - throw new DispatchError( - "FORBIDDEN", - `Operation ${operation} requires role ${requiredRole}, session is ${session.role}`, - ); - } - if (definition.authorize !== undefined) { - const context: AuthorizeContext = { + return runDispatch(operation, rawInput, session, { + handlers: this.#handlers, + authorizeLookups: { ownerId: (leaseId) => this.options.registry.snapshot.leases.find((lease) => lease.id === leaseId)?.ownerId, leaseRequesterId: (leaseId) => this.options.registry.snapshot.leases.find((lease) => lease.id === leaseId)?.requesterId, pendingRequestOwner: (requesterId) => this.options.queue.pendingRequestOwner(requesterId), - principal: session.principal, - role: session.role, - }; - if (!definition.authorize(input, context)) { - throw new DispatchError("FORBIDDEN", `Not authorized for ${operation}`); - } - } - - if (operation !== "status.get") { - await this.options.awaitReady(); - } - - const output = await handler(input as never, session); - return this.#parseOutput(definition.output, output, operation); + }, + awaitReady: () => this.options.awaitReady(), + onOutputMismatch: (operationName, issues) => { + this.#logger.error("Operation output failed contract validation", { + operation: operationName, + issues, + }); + }, + }); } // ---- handlers --------------------------------------------------------------------------- @@ -652,18 +575,6 @@ export class Dispatcher { if (enteredAt === undefined) return device; return { ...device, transitionAgeMs: this.options.clock.now() - enteredAt }; } - - #parseOutput(schema: z.ZodType, value: unknown, operationName: string): Output { - const result = schema.safeParse(value); - if (result.success) return result.data; - this.#logger.error("Operation output failed contract validation", { - operation: operationName, - issues: result.error.issues, - }); - throw new Error( - `Internal: ${operationName} produced a response that does not match its contract output schema`, - ); - } } /** A child that exited between the timer firing and the signal landing is not an error worth @@ -675,13 +586,3 @@ function killQuietly(handle: StreamingProcessHandle, signal: NodeJS.Signals): vo // Already gone. } } - -function roleSatisfies(sessionRole: Role, required: Role): boolean { - return sessionRole === "admin" || required === "agent"; -} - -function parseInput(schema: z.ZodType, value: unknown): Output { - const result = schema.safeParse(value); - if (result.success) return result.data; - throw new DispatchError("BAD_REQUEST", describeSchemaIssues(result.error.issues)); -} diff --git a/src/daemon/gateway-uplink.test.ts b/src/daemon/gateway-uplink.test.ts new file mode 100644 index 000000000..7478bc22e --- /dev/null +++ b/src/daemon/gateway-uplink.test.ts @@ -0,0 +1,293 @@ +import { describe, expect, it, vi } from "vitest"; + +import { + createConnectionPair, + FakeClock, + MemoryUplinkTransport, + UplinkError, + type IpcConnection, + type UplinkConnector, + type UplinkDialOptions, +} from "../ports/index.js"; +import { GatewayUplink } from "./gateway-uplink.js"; + +/** A connector a test drives by hand: every dial is recorded, and each one either hands back a + * connection or fails with the scripted error. */ +class ScriptedConnector implements UplinkConnector { + readonly dials: UplinkDialOptions[] = []; + readonly connections: IpcConnection[] = []; + #outcomes: Array<"connect" | UplinkError> = []; + + script(...outcomes: Array<"connect" | UplinkError>): void { + this.#outcomes.push(...outcomes); + } + + async connect(options: UplinkDialOptions): Promise { + this.dials.push(options); + const outcome = this.#outcomes.shift() ?? "connect"; + if (outcome !== "connect") throw outcome; + const [workerEnd, gatewayEnd] = createConnectionPair(); + this.connections.push(gatewayEnd); + return workerEnd; + } +} + +function uplink( + connector: UplinkConnector, + overrides: Partial[0]> = {}, +) { + const clock = new FakeClock(1_000); + const accepted: IpcConnection[] = []; + const link = new GatewayUplink({ + accept: (connection) => accepted.push(connection), + clock, + connector, + // Pinned so the delays a test asserts are the schedule, not a coin flip. The real default + // is Math.random; jitter itself is asserted separately below. + random: () => 1, + token: "join-secret", + url: "ws://gateway.test", + workerId: "wrk_1", + ...overrides, + }); + return { accepted, clock, link }; +} + +describe("GatewayUplink", () => { + it("dials on start and hands the connection to the daemon", async () => { + const connector = new ScriptedConnector(); + const { accepted, link } = uplink(connector); + + link.start(); + await vi.waitFor(() => expect(accepted).toHaveLength(1)); + + // The base URL travels verbatim: deriving `/v1/uplink` is the adapter's job, so a test of + // the supervisor asserts what the operator configured. + expect(connector.dials).toEqual([ + { token: "join-secret", url: "ws://gateway.test", workerId: "wrk_1" }, + ]); + await link.stop(); + }); + + it("sends the label when the worker configured one", async () => { + const connector = new ScriptedConnector(); + const { link } = uplink(connector, { label: "mac-mini-1" }); + + link.start(); + await vi.waitFor(() => expect(connector.dials).toHaveLength(1)); + + expect(connector.dials[0]?.label).toBe("mac-mini-1"); + await link.stop(); + }); + + it("reconnects after the gateway drops the uplink", async () => { + const connector = new ScriptedConnector(); + const { accepted, clock, link } = uplink(connector); + link.start(); + await vi.waitFor(() => expect(accepted).toHaveLength(1)); + + // The gateway's end goes away -- a restart, a network drop, a revoked token being cut off. + await connector.connections[0]?.close(); + clock.advance(1_000); + await vi.waitFor(() => expect(accepted).toHaveLength(2)); + + await link.stop(); + }); + + it("backs off exponentially and stops growing at the cap", async () => { + const connector = new ScriptedConnector(); + const unreachable = () => new UplinkError("unreachable", "no gateway"); + connector.script(unreachable(), unreachable(), unreachable(), unreachable(), unreachable()); + const { clock, link } = uplink(connector, { + backoff: { initialMs: 1_000, maxMs: 4_000, multiplier: 2 }, + }); + + link.start(); + await vi.waitFor(() => expect(connector.dials).toHaveLength(1)); + + // 1s, then 2s, then 4s, then the cap holds at 4s. Each `advance` is one millisecond short + // of the next delay first, to prove the retry is actually scheduled rather than eager. + for (const delayMs of [1_000, 2_000, 4_000, 4_000]) { + const before = connector.dials.length; + clock.advance(delayMs - 1); + expect(connector.dials).toHaveLength(before); + clock.advance(1); + await vi.waitFor(() => expect(connector.dials).toHaveLength(before + 1)); + } + + await link.stop(); + }); + + // H1: `#attempt` used to reset to 0 the instant `connect()` resolved, regardless of how long + // the link actually stayed up -- so a gateway that accepts the connection and then immediately + // closes it (an accept-then-immediately-close loop: a proxy misconfiguration, a mismatched + // protocol version the gateway does not retry past) redialled at `backoff.initialMs` forever, + // never backing off. Every prior test scripts either an outright dial *failure* (which always + // incremented `#attempt` correctly) or a single successful connect; none closes a + // *successful* connection immediately, repeatedly, which is exactly the case that used to + // reset the counter every cycle. + it("keeps backing off through an accept-then-immediately-close loop, instead of resetting every cycle (H1)", async () => { + const connector = new ScriptedConnector(); + const { accepted, clock, link } = uplink(connector, { + backoff: { initialMs: 1_000, maxMs: 8_000, multiplier: 2 }, + minStableMs: 8_000, + }); + + link.start(); + await vi.waitFor(() => expect(accepted).toHaveLength(1)); + + // 1s, 2s, 4s, then the cap holds at 8s -- exactly the growing schedule a dial *failure* + // already gets, proving a connection that never survives `minStableMs` is treated the same + // way. Against the pre-fix code every one of these delays would instead be 1s: `#attempt` + // reset to 0 as soon as each connect resolved, before its immediate close ever ran. + for (const delayMs of [1_000, 2_000, 4_000, 8_000, 8_000]) { + const connectionsBefore = accepted.length; + await connector.connections[connectionsBefore - 1]?.close(); + clock.advance(delayMs - 1); + // Flushes the microtask queue before asserting nothing redialled yet: closing a + // connection triggers `#onClosed`'s scheduling synchronously, but a redial itself runs + // through an `await`, so a check made with no yield at all would not observe one that + // fired too early against a shorter, buggy delay -- exactly the gap the pre-fix code hid + // behind, since the assertion below would otherwise pass whether the real delay was + // `delayMs` or a flat `initialMs`. + await Promise.resolve(); + await Promise.resolve(); + expect(accepted).toHaveLength(connectionsBefore); + clock.advance(1); + await vi.waitFor(() => expect(accepted).toHaveLength(connectionsBefore + 1)); + } + + await link.stop(); + }); + + // H1's other half: every test above either never lets a connection survive `minStableMs` (the + // accept-then-close loop just above) or never grows `#attempt` past 1 before a stable success + // (every other passing case). Neither exercises the actual reset itself -- deleting + // `this.#attempt = 0` from the stable timer's callback fails none of them, since the very + // first reconnect after one success looks identical whether `#attempt` was reset to 0 or left + // at 1. This grows `#attempt` to 4 with real failures first, *then* lets a connection survive + // `minStableMs`, so the reset is the only thing that can explain the next delay being back at + // `initialMs` instead of the cap `#attempt` would otherwise still be sitting at. + it("resets the backoff once a connection has genuinely stayed up, not merely connected (H1)", async () => { + const connector = new ScriptedConnector(); + const unreachable = () => new UplinkError("unreachable", "no gateway"); + connector.script(unreachable(), unreachable(), unreachable()); + const { accepted, clock, link } = uplink(connector, { + backoff: { initialMs: 1_000, maxMs: 8_000, multiplier: 2 }, + minStableMs: 5_000, + }); + + link.start(); + await vi.waitFor(() => expect(connector.dials).toHaveLength(1)); + + // Three straight failures grow `#attempt` to 3 (delays 1s, 2s, 4s) before the 4th dial ever + // gets a chance to succeed. + for (const delayMs of [1_000, 2_000, 4_000]) { + const before = connector.dials.length; + clock.advance(delayMs); + await vi.waitFor(() => expect(connector.dials).toHaveLength(before + 1)); + } + await vi.waitFor(() => expect(accepted).toHaveLength(1)); + + // Stays up past `minStableMs`: the stable timer fires and, if the reset is intact, `#attempt` + // goes back to 0 here -- well before anything closes. + clock.advance(5_000); + + // Without the reset, `#attempt` is still 4 from the dial that succeeded, and the next delay + // would be the cap (`1000 * 2**3` = 8000, already at `maxMs`) rather than `initialMs`. + await connector.connections[0]?.close(); + const before = connector.dials.length; + clock.advance(999); + expect(connector.dials).toHaveLength(before); + clock.advance(1); + await vi.waitFor(() => expect(connector.dials).toHaveLength(before + 1)); + + await link.stop(); + }); + + it("keeps retrying at the cap when the gateway rejects the join token (ADR 0005 §8)", async () => { + const connector = new ScriptedConnector(); + const rejected = () => new UplinkError("rejected", "revoked"); + connector.script(rejected(), rejected(), rejected(), rejected(), rejected(), rejected()); + const { clock, link } = uplink(connector, { + backoff: { initialMs: 1_000, maxMs: 2_000, multiplier: 2 }, + }); + + link.start(); + await vi.waitFor(() => expect(connector.dials).toHaveLength(1)); + // A revoked token is not a reason to give up: an operator may mint a new one at any time, + // and a worker that stopped dialling would need a restart nobody would think to perform. + for (let index = 0; index < 4; index += 1) { + const before = connector.dials.length; + clock.advance(2_000); + await vi.waitFor(() => expect(connector.dials.length).toBeGreaterThan(before)); + } + + await link.stop(); + }); + + it("jitters the delay across the lower half of the window", async () => { + const connector = new ScriptedConnector(); + connector.script(new UplinkError("unreachable", "no gateway")); + const { clock, link } = uplink(connector, { + backoff: { initialMs: 1_000, maxMs: 1_000, multiplier: 2 }, + // Smallest possible jitter: half the window. + random: () => 0, + }); + + link.start(); + await vi.waitFor(() => expect(connector.dials).toHaveLength(1)); + clock.advance(499); + expect(connector.dials).toHaveLength(1); + clock.advance(1); + await vi.waitFor(() => expect(connector.dials).toHaveLength(2)); + + await link.stop(); + }); + + it("stops dialling and closes the uplink on stop", async () => { + const connector = new ScriptedConnector(); + const { accepted, clock, link } = uplink(connector); + link.start(); + await vi.waitFor(() => expect(accepted).toHaveLength(1)); + + await link.stop(); + + expect(accepted[0]?.closed).toBe(true); + // Neither the closed connection nor the passage of time redials after a stop. + clock.advance(60_000); + expect(connector.dials).toHaveLength(1); + }); + + it("closes a connection that lands after a stop rather than serving it", async () => { + let release: ((connection: IpcConnection) => void) | undefined; + const pending = new Promise((resolve) => { + release = resolve; + }); + const connector: UplinkConnector = { connect: async () => pending }; + const { accepted, link } = uplink(connector); + + link.start(); + await link.stop(); + const [workerEnd] = createConnectionPair(); + release?.(workerEnd); + await vi.waitFor(() => expect(workerEnd.closed).toBe(true)); + + expect(accepted).toEqual([]); + }); + + it("works against the in-memory transport end to end", async () => { + const transport = new MemoryUplinkTransport(); + const accepted: string[] = []; + await transport.listen({ + accept: (uplinkConnection) => accepted.push(uplinkConnection.workerId), + authenticate: async (token) => (token === "join-secret" ? "accept" : "unauthenticated"), + }); + const { link } = uplink(transport); + + link.start(); + await vi.waitFor(() => expect(accepted).toEqual(["wrk_1"])); + + await link.stop(); + }); +}); diff --git a/src/daemon/gateway-uplink.ts b/src/daemon/gateway-uplink.ts new file mode 100644 index 000000000..3d4787428 --- /dev/null +++ b/src/daemon/gateway-uplink.ts @@ -0,0 +1,201 @@ +/** + * The worker's half of the uplink (ADR 0005 §4): one outbound connection to `gateway.url`, + * redialled with capped, jittered exponential backoff after any disconnect, and handed to this + * daemon's own `DaemonServer` as one more connection to serve. + * + * It is a supervisor, not a protocol: everything about what travels over the link lives in + * `DaemonServer` (which serves it) and in the gateway (which drives it). All this class decides + * is *when to dial*. + */ +import type { Clock, IpcConnection, Logger, TimerHandle, UplinkConnector } from "../ports/index.js"; +import { NoopLogger, UplinkError } from "../ports/index.js"; + +export interface UplinkBackoff { + /** Delay before the first retry. */ + readonly initialMs: number; + /** Ceiling the delay grows to and stays at (ADR 0005 §4/§8: a worker whose token was revoked + * keeps retrying *at the cap* -- an operator may mint a new token at any time, and a worker + * that gave up would then need a restart nobody would think to perform). */ + readonly maxMs: number; + readonly multiplier: number; +} + +const DEFAULT_UPLINK_BACKOFF: UplinkBackoff = { + initialMs: 1_000, + maxMs: 30_000, + multiplier: 2, +}; + +export interface GatewayUplinkOptions { + readonly clock: Clock; + readonly connector: UplinkConnector; + /** `gateway.url` -- the gateway's base URL. The uplink endpoint (`/v1/uplink`) is derived + * from it by the connector, so this is exactly what the operator configured. */ + readonly url: string; + /** `gateway.token`, the join token this worker presents. */ + readonly token: string; + /** `gateway.label`, display-only (ADR 0005 §3a). */ + readonly label?: string; + /** This worker's instance id (`instance.json`) -- its fleet identity (§3a). */ + readonly workerId: string; + /** Hands an established uplink to whoever serves it (`DaemonServer#acceptUplink`). */ + readonly accept: (connection: IpcConnection) => void; + readonly logger?: Logger; + readonly backoff?: UplinkBackoff; + /** H1: how long a connection must stay up before `#attempt` resets to 0. Defaults to the + * backoff's own cap (`backoff.maxMs`) so a link that never survives that long never looks + * "recovered" -- an accept-then-immediately-close loop grows into, and stays at, the cap + * instead of redialling forever at `backoff.initialMs`. */ + readonly minStableMs?: number; + /** + * Jitter source, injected so a test gets a deterministic schedule. Defaults to `Math.random`. + * Jitter matters here for the same reason it does in any reconnect loop: a gateway restart + * disconnects every worker at once, and an unjittered fleet would redial in lockstep forever. + */ + readonly random?: () => number; +} + +export class GatewayUplink { + readonly #logger: Logger; + readonly #backoff: UplinkBackoff; + readonly #minStableMs: number; + readonly #random: () => number; + #attempt = 0; + #timer: TimerHandle | undefined; + #connection: IpcConnection | undefined; + #stopped = false; + /** Guards against two dials in flight at once -- a `close` arriving while a dial is pending + * would otherwise schedule a second one beside it. */ + #dialing = false; + /** + * H1: armed on a successful connect, cancelled on close. `#attempt` used to reset to 0 the + * moment `connect()` resolved, regardless of how long the link actually stayed up -- so a + * gateway that accepts the TCP/WebSocket upgrade and then immediately closes it (a proxy + * misconfiguration, a protocol-version mismatch the gateway itself does not retry past, a + * backend that flaps) never grew its delay past `backoff.initialMs`: every cycle looked like + * "back to full health" a moment before failing again, redialling at ~0.75s forever instead of + * backing off. `#attempt` now only resets once the link has stayed up long enough for this + * timer to fire -- if the close beats it, the timer is cancelled and `#attempt` carries over + * into the next delay calculation unchanged. + */ + #stableTimer: TimerHandle | undefined; + + constructor(private readonly options: GatewayUplinkOptions) { + this.#logger = options.logger ?? new NoopLogger(); + this.#backoff = options.backoff ?? DEFAULT_UPLINK_BACKOFF; + this.#minStableMs = options.minStableMs ?? this.#backoff.maxMs; + this.#random = options.random ?? Math.random; + } + + /** + * Dials now, and keeps redialling for the daemon's lifetime. Deliberately synchronous and + * fire-and-forget: a worker whose gateway is down must still come up and serve its local + * agents, so nothing in the daemon's startup path ever waits on this. + */ + start(): void { + if (this.#stopped) return; + void this.#dial(); + } + + /** Stops redialling and closes the current uplink, if any. */ + async stop(): Promise { + if (this.#stopped) return; + this.#stopped = true; + if (this.#timer !== undefined) { + this.options.clock.cancel(this.#timer); + this.#timer = undefined; + } + if (this.#stableTimer !== undefined) { + this.options.clock.cancel(this.#stableTimer); + this.#stableTimer = undefined; + } + const connection = this.#connection; + this.#connection = undefined; + await connection?.close(); + } + + async #dial(): Promise { + if (this.#stopped || this.#dialing || this.#connection !== undefined) return; + this.#dialing = true; + this.#attempt += 1; + try { + const connection = await this.options.connector.connect({ + url: this.options.url, + token: this.options.token, + workerId: this.options.workerId, + ...(this.options.label === undefined ? {} : { label: this.options.label }), + }); + if (this.#stopped) { + // A stop that landed while the dial was in flight: close what we just opened rather + // than handing a connection to a daemon that is shutting down. + await connection.close(); + return; + } + this.#connection = connection; + connection.onClose(() => this.#onClosed()); + this.#logger.info("Uplink to gateway established", { + url: this.options.url, + workerId: this.options.workerId, + }); + this.options.accept(connection); + // H1: `#attempt` resets only once this link has actually stayed up for `#minStableMs` -- + // not the instant `connect()` resolves. Cancelled in `#onClosed`/`stop` if the close + // beats it, which is exactly the accept-then-immediately-close case this guards against. + this.#stableTimer = this.options.clock.setTimer(this.#minStableMs, () => { + this.#stableTimer = undefined; + this.#attempt = 0; + }); + } catch (error: unknown) { + const delayMs = this.#nextDelayMs(); + // `warn`, not `error`: a gateway that is down is an expected state for a worker, which + // goes on serving its local agents throughout. The `reason` is what tells an operator a + // revoked token apart from an unreachable gateway -- both retry, only one is fixable by + // waiting. + this.#logger.warn("Uplink to gateway failed; retrying", { + url: this.options.url, + reason: error instanceof UplinkError ? error.code : "unknown", + message: error instanceof Error ? error.message : String(error), + retryInMs: delayMs, + }); + this.#scheduleRetry(delayMs); + } finally { + this.#dialing = false; + } + } + + #onClosed(): void { + this.#connection = undefined; + if (this.#stableTimer !== undefined) { + this.options.clock.cancel(this.#stableTimer); + this.#stableTimer = undefined; + } + if (this.#stopped) return; + const delayMs = this.#nextDelayMs(); + this.#logger.info("Uplink to gateway closed; reconnecting", { + url: this.options.url, + retryInMs: delayMs, + }); + this.#scheduleRetry(delayMs); + } + + #scheduleRetry(delayMs: number): void { + if (this.#stopped || this.#timer !== undefined) return; + this.#timer = this.options.clock.setTimer(delayMs, () => { + this.#timer = undefined; + void this.#dial(); + }); + } + + /** + * Exponential up to the cap, then jittered across the lower half of the resulting window + * (`[delay/2, delay]`). Half-window rather than full: a fleet redialling after a gateway + * restart must spread out, but a worker should not idle for a full cap's worth of seconds + * when the gateway is already back. + */ + #nextDelayMs(): number { + const exponential = + this.#backoff.initialMs * this.#backoff.multiplier ** Math.max(0, this.#attempt - 1); + const capped = Math.min(this.#backoff.maxMs, exponential); + return Math.round(capped * (0.5 + this.#random() * 0.5)); + } +} diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 35e071a45..44fafe97d 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -55,9 +55,20 @@ import { type ProcessSupervisor, type TcpProbe, } from "../ports/index.js"; +import { + FileDrainStore, + GatewayDispatcher, + GatewayService, + type GatewayServiceOptions, +} from "../gateway/index.js"; +import { + WebSocketUplinkConnector, + WebSocketUplinkListenerFactory, +} from "../ports/uplink-websocket.js"; import { DaemonServer } from "./server.js"; import { DaemonEndpointHost } from "./connection-host.js"; import { AdminSecretManager } from "./admin-secret.js"; +import { GatewayUplink } from "./gateway-uplink.js"; import { createCredentialRoleResolver } from "./session.js"; export interface StartDaemonOptions { @@ -116,6 +127,24 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise (await tokens.verify(secret))?.role === "operator", verifyAdminSecret: (secret) => adminSecret.verify(secret), }); - // Reassigned once the HTTP gateway actually starts, but must exist as a stable closure now: - // `stopAuxiliary` is fixed at `DaemonServer` construction time, before the gateway itself + /** + * ADR 0005 §3/§4: two config keys join a fleet. Undefined here means this worker has no + * gateway, which is every worker today -- and the daemon is otherwise completely unchanged + * either way, which is the point of the uplink being outbound. + */ + const gatewayUplink = + config.gateway.url === undefined || config.gateway.token === undefined + ? undefined + : new GatewayUplink({ + accept: (connection) => daemon.acceptUplink(connection), + clock, + connector: new WebSocketUplinkConnector(), + logger: logger.child("uplink"), + token: config.gateway.token, + url: config.gateway.url, + workerId: instanceId, + ...(config.gateway.label === undefined ? {} : { label: config.gateway.label }), + }); + // Reassigned once the HTTP frontend actually starts, but must exist as a stable closure now: + // `stopAuxiliary` is fixed at `DaemonServer` construction time, before the frontend itself // exists. let stopHttpGateway: (() => Promise) | undefined; // Settles once the HTTP gateway either finishes starting or fails to -- resolved/rejected from @@ -322,6 +369,11 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise { await gatewayStarted.catch(() => undefined); await stopHttpGateway?.(); + // Stopped with the other auxiliary frontends, and for the same reason: the uplink is a + // live connection into this daemon's dispatcher, so it must be shut before lease/queue + // teardown begins. Stopping it also stops the reconnect loop, so a shutting-down worker + // does not redial the gateway it just left. + await gatewayUplink?.stop(); }, // ADR 0003 §2: "an HTTP request during startup now waits like a socket request instead of // being refused". Firing the gateway's own `start()` from here (not after `daemon.start()` @@ -338,7 +390,7 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise resolveGatewayStarted?.(), (error: unknown) => { - logger.error("HTTP gateway failed to start", { message: errorMessage(error) }); + logger.error("HTTP frontend failed to start", { message: errorMessage(error) }); rejectGatewayStarted?.(error); }, ); @@ -347,6 +399,12 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise { const httpLogger = logger.child("http"); const app = createHttpApp({ @@ -406,6 +464,202 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise { + const { clock, config, dataDirectory, eventBus, filesystem, idGenerator, logger } = options; + // The gateway's own identity, used to namespace the principal it announces to each worker + // (ADR 0005 §27's shape) so a worker's logs attribute what the gateway did to the gateway. + const instanceId = await loadInstanceId({ + filesystem, + idGenerator, + path: join(dataDirectory, "instance.json"), + }); + // ADR 0005 §24: a gateway has its own token store and mints its own credentials. A gateway + // token is never valid on a worker and vice versa -- they are different stores on different + // machines, which is what makes that true without any code enforcing it. + const tokens = new TokenStore({ + clock, + filesystem, + idGenerator, + path: join(dataDirectory, "tokens.json"), + secrets: new CryptoTokenSecrets(), + }); + const adminSecret = new AdminSecretManager({ + filesystem, + secrets: new CryptoTokenSecrets(), + path: join(dataDirectory, "admin.token"), + }); + const resolveRole = createCredentialRoleResolver({ + verifyOperatorToken: async (secret) => (await tokens.verify(secret))?.role === "operator", + verifyAdminSecret: (secret) => adminSecret.verify(secret), + }); + + const uplinks = new WebSocketUplinkListenerFactory(); + const gatewayService = new GatewayService({ + // ADR 0005 §4/§25: only a `worker`-role token opens an uplink. A token of another role is + // real and simply has no authority here (403); anything else is unauthenticated (401). + // C-2: the accepted case names the token's own id, so `token.revoke` can later find and + // close every uplink it authorized (`GatewayService#closeLinksForToken`, wired below). + authenticate: async (credential) => { + if (credential === undefined) return "unauthenticated"; + const identity = await tokens.verify(credential); + if (identity === undefined) return "unauthenticated"; + if (identity.role !== "worker") return "forbidden"; + return { outcome: "accept", tokenId: identity.requesterId }; + }, + clock, + drainStore: new FileDrainStore({ + filesystem, + logger: logger.child("gateway"), + path: join(dataDirectory, "workers.json"), + }), + eventBus, + // ADR 0005 §15: this gateway's own cap, compared against every connected worker's own + // reported one so the registry can warn when a worker's is lower. + leaseMaxTtlMs: config.lease.maxTtlMs, + logger: logger.child("gateway"), + principal: `gw:${instanceId}`, + retentionMs: config.gateway.disconnectedRetentionMs, + uplinks, + } satisfies GatewayServiceOptions); + + let stopHttpGateway: (() => Promise) | undefined; + let resolveHttpStarted: (() => void) | undefined; + let rejectHttpStarted: ((error: unknown) => void) | undefined; + let socketClaimed = false; + const httpStarted = new Promise((resolveStarted, rejectStarted) => { + resolveHttpStarted = resolveStarted; + rejectHttpStarted = rejectStarted; + }); + + const daemon = new DaemonServer({ + adminSecret, + clock, + config, + defaultRequesterId: process.env.SIMLOCK_AGENT_ID ?? String(process.pid), + // ADR 0005 §32: the contract's second implementation, serving the same transport. + dispatcher: new GatewayDispatcher({ + awaitReady: () => Promise.resolve(), + // C-2: makes `token.revoke` actually close the uplink it names (ADR 0005 §8), rather than + // only writing the store and waiting for that worker's next reconnect. + closeUplinksForToken: (tokenId) => gatewayService.closeLinksForToken(tokenId), + config, + eventBus, + health: () => daemon.health, + logger: logger.child("gateway"), + tokens, + workers: gatewayService.workers, + }), + eventBus, + host: new DaemonEndpointHost({ + connector: options.ipc, + endpoint: options.socketPath, + filesystem, + listenerFactory: options.ipc, + logger: logger.child("connection-host"), + }), + logger: logger.child("server"), + resolveRole, + version: options.version, + // A gateway's "convergence" is starting to accept uplinks and arming the refresh tick. + // Running it here rather than before `start()` keeps one lifecycle: a listener that cannot + // start fails the daemon start, and `status.get` answers throughout (a fleet with no views + // yet is a true answer, not an unready one). A worker that dials in the window before this + // resolves is refused and redials on its own backoff. + converge: async () => { + await gatewayService.start(); + }, + dispose: async () => { + await gatewayService.stop(); + }, + stopAuxiliary: async () => { + await httpStarted.catch(() => undefined); + await stopHttpGateway?.(); + }, + onSocketClaimed: () => { + socketClaimed = true; + void startHttpFrontend().then( + () => resolveHttpStarted?.(), + (error: unknown) => { + logger.error("HTTP frontend failed to start", { message: errorMessage(error) }); + rejectHttpStarted?.(error); + }, + ); + }, + }); + + async function startHttpFrontend(): Promise { + const httpLogger = logger.child("http"); + const app = createHttpApp({ + clock, + config, + dispatch: (operation, input, session) => daemon.dispatch(operation, input, session), + eventBus, + idGenerator, + logger: httpLogger, + // Inert in gateway mode: the gateway issues no leases of its own in this PR, so there + // are no owner-routed facts to buffer (see `DaemonServer`'s constructor). + ownerRoutedFacts: daemon.ownerRoutedFacts, + // A gateway owns no devices, so there is no registry to read one from. The routes that + // decorate a response with a device record are lease routes, which answer + // `UNSUPPORTED_IN_GATEWAY_MODE` here anyway; the fleet's devices come from `status.get`. + registry: { snapshot: { devices: [] } }, + tokens, + }); + const gateway = new HttpGateway(app, { + host: config.http.host, + logger: httpLogger, + // ADR 0005 §4: the uplink upgrades on this same listener, so the fleet has one inbound + // port. The factory only needs the server's `upgrade` event, which is all it is given. + onServerCreated: (server) => uplinks.attach(server), + port: config.http.port, + }); + await gateway.start(); + stopHttpGateway = async () => { + await gateway.stop(); + app.dispose(); + }; + } + + const daemonStarted = daemon.start().finally(() => { + if (!socketClaimed) resolveHttpStarted?.(); + }); + const [daemonResult, httpResult] = await Promise.allSettled([daemonStarted, httpStarted]); + if (httpResult.status === "rejected" && daemonResult.status === "fulfilled") { + // The gateway itself came up but its HTTP listener never bound -- which for a gateway means + // no agent can reach it and no worker can join it. Tear it down, after the start is a + // settled fact so `daemon.stopping` cannot precede `daemon.started`. + await daemon.stop("http-start-failed").catch(() => undefined); + } + if (daemonResult.status === "rejected") throw daemonResult.reason; + if (httpResult.status === "rejected") throw httpResult.reason; + return daemon; +} + function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); } diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 644bb01d5..2ad89674b 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -19,6 +19,7 @@ import { import { PROTOCOL_VERSION_RANGE } from "../contract/index.js"; import { AndroidLicenseNotAcceptedError } from "../drivers/android/index.js"; import { + createConnectionPair, CryptoTokenSecrets, FakeClock, FakeSystemStats, @@ -53,8 +54,8 @@ interface Client { } interface ServerFrame { - readonly error?: { readonly code: string; readonly message: string }; - readonly id?: string | null; + readonly error?: { readonly code: string; readonly message: string; readonly details?: unknown }; + readonly id?: string | number | null; readonly ok?: boolean; readonly payload?: unknown; readonly push?: @@ -2489,8 +2490,100 @@ describe("DaemonServer roles and ownership (ADR 0003 §2-4)", () => { await requester.close(); await observer.close(); }); + + /** + * ADR 0005 §5: over the uplink the gateway is the protocol client, and the worker grants that + * session `admin` because *it* opened the connection to the gateway named in its own config. + * The harness resolves every ordinary session to `agent` here, so the contrast is the point: + * the same `hello`, with no credential at all, is agent over the socket and admin over the + * uplink. + */ + it("grants an accepted uplink the admin role without a credential (ADR 0005 §5)", async () => { + const harness = await createHarness({ resolveRole: { resolve: () => "agent" } }); + const [workerEnd, gatewayEnd] = createConnectionPair(); + harness.daemon.acceptUplink(workerEnd); + const gateway = driveConnection(gatewayEnd); + + const reply = await gateway.request("hello", { + clientVersion: "gateway", + protocolVersion: DAEMON_PROTOCOL_VERSION, + principal: "gw:instance-1", + }); + + expect(reply).toMatchObject({ ok: true, payload: { role: "admin" } }); + // ...and the role is real, not cosmetic: an admin-only operation answers. + await expect(gateway.request("list.get", { kind: "devices" })).resolves.toMatchObject({ + ok: true, + }); + + // Meanwhile a plain socket connection on the same daemon is still an agent. + const local = await createClient(harness.socketPath); + await local.request("hello", { + clientVersion: "test", + protocolVersion: DAEMON_PROTOCOL_VERSION, + }); + await expect(local.request("list.get", {})).resolves.toMatchObject({ + error: { code: "FORBIDDEN" }, + }); + await local.close(); + }); + + it("negotiates the protocol range over an uplink exactly as over the socket (ADR 0005 §31)", async () => { + const harness = await createHarness({ resolveRole: { resolve: () => "agent" } }); + const [workerEnd, gatewayEnd] = createConnectionPair(); + harness.daemon.acceptUplink(workerEnd); + const gateway = driveConnection(gatewayEnd); + + const reply = await gateway.request("hello", { + clientVersion: "gateway", + protocolRange: { min: 99, max: 99 }, + }); + + expect(reply).toMatchObject({ + ok: false, + error: { code: "PROTOCOL_VERSION_UNSUPPORTED" }, + }); + // Both ranges travel, which is what a gateway puts on an `incompatible` worker view. + expect(reply.error).toMatchObject({ + details: { client: { min: 99, max: 99 }, daemon: PROTOCOL_VERSION_RANGE }, + }); + }); }); +/** Drives an in-memory `IpcConnection` the way `createClient` drives a real socket -- enough to + * send request frames and await their replies. Used for uplink tests, where there is no socket + * at all: the connection is the one a worker dialled out and handed to its own daemon. */ +function driveConnection(connection: IpcConnection): { + request(type: string, payload: unknown): Promise; +} { + let buffer = ""; + let nextId = 1; + const waiters = new Map void>(); + connection.onData((chunk) => { + buffer += chunk; + for (;;) { + const newline = buffer.indexOf("\n"); + if (newline < 0) return; + const line = buffer.slice(0, newline); + buffer = buffer.slice(newline + 1); + if (line.trim() === "") continue; + const frame = JSON.parse(line) as ServerFrame; + if (typeof frame.id !== "number") continue; + const waiter = waiters.get(frame.id); + waiters.delete(frame.id); + waiter?.(frame); + } + }); + return { + request: async (type, payload) => { + const id = nextId++; + const settled = new Promise((resolve) => waiters.set(id, resolve)); + await connection.write(`${JSON.stringify({ id, payload, type })}\n`); + return settled; + }, + }; +} + async function helloAs( client: Client, principal: string, @@ -2888,6 +2981,7 @@ function testConfig( mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, + gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, drivers: {}, eventBuffer: { capacity: 100 }, health: { diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 77a127c4c..e6c267123 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -40,7 +40,12 @@ import { } from "../contract/index.js"; import type { ConnectionHost } from "./connection-host.js"; import type { TokenStore } from "../http/token-store.js"; -import { Dispatcher, DispatchError, type DispatchSession } from "./dispatcher.js"; +import { + Dispatcher, + DispatchError, + type ContractDispatcher, + type DispatchSession, +} from "./dispatcher.js"; import { resolveAgentRole, type SessionRoleResolver } from "./session.js"; import type { AdminSecretManager } from "./admin-secret.js"; import { OwnerRoutedFactBus, type OwnerRoutedFacts } from "./owner-routed-facts.js"; @@ -68,6 +73,14 @@ interface Connection { * the seam PR 2's credential handshake replaces -- see `session.ts`. */ principal: string; role: Role; + /** + * Set only for a connection accepted through `acceptUplink` (ADR 0005 §5): the role that + * connection gets, decided by *how it was accepted* rather than by anything in its `hello`. + * `#handleHello` uses it in place of `#resolveRole`, so no credential is consulted and none + * is required. See `acceptUplink`'s own comment for why that is the correct trust model + * here and nowhere else. + */ + readonly forcedRole: Role | undefined; /** * Lease ids this connection is *currently* explicitly releasing (`lease.release`/ * `lease.release-all`), added right before the dispatched call and consumed by @@ -96,26 +109,24 @@ interface Connection { subscriptionId: string | undefined; } -export interface DaemonServerOptions { +/** + * The worker engine `DaemonServer` builds its `Dispatcher` from, and the few things it touches + * around that dispatcher (the registry snapshot a `lease.release-all` reads to suppress its own + * pushes, the queue a closing connection detaches progress from, the reaper and health monitor + * a stop disposes). + * + * Separate from the common options because ADR 0005 §32 gives the contract a second + * implementation: a **gateway** passes `dispatcher` instead of all of this, and has none of it + * to pass -- no registry, no capacity, no lifecycle (§33). Keeping the split in the *type* + * rather than making every field optional is what preserves the compile-time guarantee for + * worker mode: omitting `queue` from a worker's options is still an error, not a runtime + * surprise. + */ +export interface DaemonServerEngineOptions { readonly capacity: CapacityReader; readonly catalog: CatalogReader; - readonly clock: Clock; - readonly config: Config; readonly doctor?: Doctor; - readonly defaultRequesterId: string; - /** - * Platforms whose driver refused to start. The daemon serves without them rather than - * refusing to come up (safety rule 9), so the refusal has to be visible somewhere: one - * event each lands in the ring buffer here, and `Doctor` reports the same list. - */ - readonly driverRejections?: readonly DriverRejection[]; - readonly eventBus: EventBus; - readonly host: ConnectionHost; readonly leases: LeaseCommands; - readonly logger?: Logger; - /** Overrides the daemon's advertised protocol range (ADR 0003 §6); defaults to - * `PROTOCOL_VERSION_RANGE`. A bare number is normalized to `{n, n}`, same as a client's. */ - readonly protocolVersion?: number | ProtocolRange; readonly queue: QueueControl; readonly reaper: CleanupReaper; readonly healthMonitor?: LeaseHealthMonitor; @@ -130,6 +141,24 @@ export interface DaemonServerOptions { readonly registry: Registry; /** ADR 0003 §11: threaded straight into the `Dispatcher` for `token.create|list|revoke`. */ readonly tokens?: TokenStore; +} + +export interface DaemonServerCommonOptions { + readonly clock: Clock; + readonly config: Config; + readonly defaultRequesterId: string; + /** + * Platforms whose driver refused to start. The daemon serves without them rather than + * refusing to come up (safety rule 9), so the refusal has to be visible somewhere: one + * event each lands in the ring buffer here, and `Doctor` reports the same list. + */ + readonly driverRejections?: readonly DriverRejection[]; + readonly eventBus: EventBus; + readonly host: ConnectionHost; + readonly logger?: Logger; + /** Overrides the daemon's advertised protocol range (ADR 0003 §6); defaults to + * `PROTOCOL_VERSION_RANGE`. A bare number is normalized to `{n, n}`, same as a client's. */ + readonly protocolVersion?: number | ProtocolRange; readonly version: string; /** ADR §5's seam (see `session.ts`): resolves a session's role from `hello`'s payload. * Defaults to `resolveAgentRole` (every session is "agent") -- PR 2's credential handshake @@ -184,6 +213,19 @@ export interface DaemonServerOptions { readonly onSocketClaimed?: () => void; } +/** + * ADR 0005 §32: one transport, two dispatchers. A worker passes its engine and gets the + * `Dispatcher` built for it; a gateway passes a ready-made `dispatcher` (its own handlers, over + * worker views and uplinks) and no engine at all. The union -- rather than one interface with + * everything optional -- is what keeps each mode's requirements checked at compile time. + */ +export type DaemonServerOptions = + | (DaemonServerCommonOptions & DaemonServerEngineOptions & { readonly dispatcher?: undefined }) + | (DaemonServerCommonOptions & { + /** The contract implementation this daemon serves. See `src/gateway/dispatcher.ts`. */ + readonly dispatcher: ContractDispatcher; + }); + type DaemonHealth = "starting" | "running" | "failed"; /** @@ -195,7 +237,7 @@ type DaemonHealth = "starting" | "running" | "failed"; * the server's own live state are passed in rather than reached for. */ function buildDispatcher( - options: DaemonServerOptions, + options: DaemonServerCommonOptions & DaemonServerEngineOptions, hooks: { readonly awaitReady: () => Promise; readonly health: () => DaemonHealth; @@ -241,9 +283,16 @@ export class DaemonServer { * `start()`. */ readonly #parkedDispatches = new Set>(); - readonly #dispatcher: Dispatcher; + readonly #dispatcher: ContractDispatcher; readonly #resolveRole: SessionRoleResolver; - readonly #ownerRoutedFacts: OwnerRoutedFactBus; + /** + * The worker engine, or `undefined` in gateway mode (ADR 0005 §33: a gateway has no + * registry, capacity or lifecycle to hold). Every engine touchpoint below is written + * against this rather than `this.options`, so "what a gateway does not have" is one + * `?.` at each site instead of a mode flag threaded through the class. + */ + readonly #engine: DaemonServerEngineOptions | undefined; + readonly #ownerRoutedFacts: OwnerRoutedFacts & { dispose(): void }; constructor(private readonly options: DaemonServerOptions) { this.#protocolRange = @@ -256,11 +305,29 @@ export class DaemonServer { // `#notifyDeviceRecovered` below route from is what the HTTP gateway's `LeaseNoticeBuffer` // consumes too (see `ownerRoutedFacts` getter and `main.ts`) -- one bus subscription // per raw event, not one per consumer. - this.#ownerRoutedFacts = new OwnerRoutedFactBus(options.eventBus, options.registry); - this.#dispatcher = buildDispatcher(options, { - awaitReady: () => this.#awaitReady(), - health: () => this.#health, - }); + if (options.dispatcher === undefined) { + // Worker mode: build the engine-backed `Dispatcher` exactly as before. `options` narrows + // to the engine arm of the union here, so every field it needs is still required at + // compile time. + const engine: DaemonServerEngineOptions = options; + this.#engine = engine; + this.#ownerRoutedFacts = new OwnerRoutedFactBus(options.eventBus, engine.registry); + this.#dispatcher = buildDispatcher(options, { + awaitReady: () => this.#awaitReady(), + health: () => this.#health, + }); + } 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 + // its own in this PR, and a worker's republished `lease.expired` names *that worker's* + // owner, not a gateway client's principal -- routing one to a gateway connection would + // push another machine's fact at the wrong holder. #118/#119 relay lease-scoped pushes, + // with the gateway's own lease index to route them by; until then this is inert rather + // than wrong. + this.#engine = undefined; + this.#dispatcher = options.dispatcher; + this.#ownerRoutedFacts = inertOwnerRoutedFacts(); + } } // fallow-ignore-next-line unused-class-member -- retained as a daemon compatibility facade. @@ -268,8 +335,9 @@ export class DaemonServer { return this.options.host.endpoint; } - /** Public read of `#health`, kept for tests and any future auxiliary frontend that needs it without becoming a privileged internal itself. */ - // fallow-ignore-next-line unused-class-member -- public surface exercised directly by server.test.ts; `status.get` itself reads `#health` through the dispatcher's own `health()` closure, not this getter. + /** Public read of `#health`. A gateway's dispatcher reads it through here (`main.ts` passes + * `() => daemon.health` as its `health` hook), which is what keeps `status.get` on a gateway + * reporting the same daemon health a worker does without the gateway holding a second copy. */ get health(): DaemonHealth { return this.#health; } @@ -438,7 +506,7 @@ export class DaemonServer { // also what keeps the subscriptions above safe -- nothing can emit // device.crash-detected during the startup window, because the only emitter is // this monitor. - this.options.healthMonitor?.start(); + this.#engine?.healthMonitor?.start(); } async #converge(): Promise { @@ -484,8 +552,8 @@ export class DaemonServer { this.options.eventBus.emit("daemon.stopping", { reason }, "daemon"); for (const unsubscribe of this.#unsubscribeLeaseLost.splice(0)) unsubscribe(); this.#ownerRoutedFacts.dispose(); - this.options.reaper.dispose(); - this.options.healthMonitor?.dispose(); + this.#engine?.reaper.dispose(); + this.#engine?.healthMonitor?.dispose(); // ADR 0004 §3: a stop releases nothing. Every lease persists with its deadline, and the // next daemon restores its timer from that deadline (`StartupConverger`); one whose // deadline passed in between expires as soon as a daemon is there to expire it. What is @@ -507,7 +575,30 @@ export class DaemonServer { this.#logger.info("Daemon stopped", { reason }); } - #accept(socket: IpcConnection): void { + /** + * ADR 0005 §5: accepts a worker's *outbound* uplink as one more connection on this daemon's + * own protocol, and grants that session the `admin` role. + * + * The grant is not a hole in ADR 0003 §5 ("admin authority comes from a credential in the + * handshake, never from the socket") -- it is the same rule applied one layer out. §5's + * prohibition is on inferring authority from a *transport this daemon merely accepted*: a + * local unix socket proves nothing about who connected. Here the daemon is not accepting + * anything; it *dialled out*, to the `gateway.url` in its own configuration, presenting the + * `gateway.token` from that same file, and the gateway verified that token before this + * connection existed (ADR 0005 §4). The credential in this handshake is that join token, + * checked by the peer; the trust runs from this worker's own config, which is exactly the + * kind of statement §5 says admin authority may come from. An operator who does not want a + * gateway administering this machine removes two config keys. + * + * Everything else about the session is unchanged: `hello` still negotiates the protocol + * range (§31, ADR 0003 §6), the dispatcher still runs every role and ownership check, and a + * mismatched range still refuses every operation but `daemon.stop`. + */ + acceptUplink(connection: IpcConnection): void { + this.#accept(connection, "admin"); + } + + #accept(socket: IpcConnection, forcedRole?: Role): void { if (this.#stopping) { void socket.close(); return; @@ -515,6 +606,7 @@ export class DaemonServer { const connection: Connection = { buffer: "", closed: false, + forcedRole, helloReceived: false, // Overwritten by `#handleHello` before any dispatched request can read them -- every // path that reaches `#handleRequest` has `connection.helloReceived === true` by @@ -660,7 +752,16 @@ export class DaemonServer { } else { this.#logger.debug("Handled request error", { code, type: frame.type }); } - await this.#respondError(connection.socket, frame.id, code, this.#describeError(error)); + // 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`), + // so a socket client can narrow on them exactly as an HTTP one does. + await this.#respondError( + connection.socket, + frame.id, + code, + this.#describeError(error), + error instanceof DispatchError ? error.details : undefined, + ); } } @@ -730,10 +831,16 @@ export class DaemonServer { // whether the versions would otherwise have matched. let role: Role; try { - role = await this.#resolveRole.resolve({ - ...(payload.principal === undefined ? {} : { principal: payload.principal }), - ...(payload.credential === undefined ? {} : { credential: payload.credential }), - }); + // ADR 0005 §5: an uplink connection's role comes from how it was accepted (this daemon + // dialled the gateway named in its own config), so no credential is consulted -- see + // `acceptUplink`. Every other connection resolves its role from `hello` exactly as + // before. + role = + connection.forcedRole ?? + (await this.#resolveRole.resolve({ + ...(payload.principal === undefined ? {} : { principal: payload.principal }), + ...(payload.credential === undefined ? {} : { credential: payload.credential }), + })); } catch (error: unknown) { await this.#respondError(connection.socket, frame.id, errorCode(error), errorMessage(error)); await connection.socket.close(); @@ -840,7 +947,7 @@ export class DaemonServer { // and one granted inside the window is not suppressed, so its holder gets the push it // would have got for any other force-release. Neither can suppress a push for a lease // this principal does not own, which is the property that matters. - const releasing = this.options.registry.snapshot.leases + const releasing = (this.#engine?.registry.snapshot.leases ?? []) .filter((lease) => connection.role === "admin" || lease.ownerId === connection.principal) .map((lease) => lease.id); for (const leaseId of releasing) connection.selfInitiatedReleases.add(leaseId); @@ -951,6 +1058,27 @@ 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. + case "worker.list": + return this.#dispatcher.dispatch( + "worker.list", + frame.payload ?? {}, + this.#session(connection), + ); + case "worker.drain": + return this.#dispatcher.dispatch("worker.drain", frame.payload, this.#session(connection)); + case "worker.undrain": + return this.#dispatcher.dispatch( + "worker.undrain", + frame.payload, + this.#session(connection), + ); + case "worker.remove": + return this.#dispatcher.dispatch("worker.remove", frame.payload, this.#session(connection)); // "daemon.stop" is deliberately absent from this switch: `#dispatchLine` intercepts it // itself, ahead of the protocol-mismatch and `#stopping` gates (ADR §6's frozen exception, // scoped to protocol version only -- still gated on a completed handshake and the `admin` @@ -1271,7 +1399,7 @@ export class DaemonServer { } connection.progressDisposers.clear(); for (const requesterId of connection.progressRequesters) { - void this.options.queue.detachQueuedProgress(requesterId); + void this.#engine?.queue.detachQueuedProgress(requesterId); } connection.progressRequesters.clear(); this.#connections.delete(connection); @@ -1280,6 +1408,18 @@ export class DaemonServer { } } +/** + * An `OwnerRoutedFacts` that never emits -- what a gateway gets, since it has no local leases + * to report facts about (see the constructor's comment). A named function rather than an inline + * object literal so the intent reads at the one place that would otherwise be a bare `{}`. + */ +function inertOwnerRoutedFacts(): OwnerRoutedFacts & { dispose(): void } { + return { + subscribe: () => () => {}, + dispose: () => {}, + }; +} + class ProtocolError extends Error { constructor( readonly code: string, diff --git a/src/gateway/aggregate.test.ts b/src/gateway/aggregate.test.ts new file mode 100644 index 000000000..d1a00bd2e --- /dev/null +++ b/src/gateway/aggregate.test.ts @@ -0,0 +1,220 @@ +import { describe, expect, it } from "vitest"; + +import { OPERATIONS } from "../contract/index.js"; +import { aggregateCatalog, aggregateStatus } from "./aggregate.js"; +import { deviceFixture, leaseFixture } from "./test-support.js"; +import type { WorkerView } from "./worker-registry.js"; + +function capacity(running: number, limit: number) { + return { + android: { + limit, + maxRunning: limit, + overLimit: false, + reserved: 0, + running: 0, + used: 0, + warm: 0, + }, + global: { maxRunning: limit * 2, overLimit: false, reserved: 0, running, warm: 1 }, + ios: { + limit, + maxRunning: limit, + overLimit: false, + reserved: 0, + running, + used: running, + warm: 1, + }, + }; +} + +function view(overrides: Partial & { readonly id: string }): WorkerView { + return { + catalog: [], + connection: "connected", + devices: [], + drained: false, + lastSeenAt: 1_000, + leases: [], + ...overrides, + }; +} + +describe("aggregateStatus", () => { + it("returns the same shape a worker returns, with the gateway named in the daemon block", () => { + const status = aggregateStatus([], { health: "running", queueDepth: 0 }); + + // The contract is the arbiter: a gateway's answer parses as `status.get`'s output or it is + // not the same shape. + expect(() => OPERATIONS["status.get"].output.parse(status)).not.toThrow(); + expect(status.daemon.mode).toBe("gateway"); + expect(status.workers).toEqual([]); + }); + + it("sums capacity across connected workers", () => { + const status = aggregateStatus( + [ + view({ capacity: capacity(1, 2), id: "wrk_a" }), + view({ capacity: capacity(2, 4), id: "wrk_b" }), + ], + { health: "running", queueDepth: 0 }, + ); + + expect(status.capacity.ios).toMatchObject({ limit: 6, running: 3, used: 3, warm: 2 }); + expect(status.capacity.global).toMatchObject({ maxRunning: 12, running: 3, warm: 2 }); + }); + + it("leaves a disconnected worker's capacity out of the sum", () => { + // Free slots on a machine nobody can reach are not capacity: counting them would tell an + // operator the fleet can take work it cannot. + const status = aggregateStatus( + [ + view({ capacity: capacity(1, 2), id: "wrk_a" }), + view({ capacity: capacity(9, 9), connection: "disconnected", id: "wrk_b" }), + ], + { health: "running", queueDepth: 0 }, + ); + + expect(status.capacity.ios).toMatchObject({ limit: 2, running: 1 }); + }); + + it("counts a worker over its own limit as the fleet being over one", () => { + const overLimit = capacity(3, 2); + const status = aggregateStatus( + [ + view({ capacity: capacity(0, 2), id: "wrk_a" }), + view({ + capacity: { ...overLimit, ios: { ...overLimit.ios, overLimit: true } }, + id: "wrk_b", + }), + ], + { health: "running", queueDepth: 0 }, + ); + + expect(status.capacity.ios.overLimit).toBe(true); + }); + + it("stamps every device and lease with the worker it lives on", () => { + const status = aggregateStatus( + [ + view({ + devices: [deviceFixture("dev_1", "leased")], + id: "wrk_a", + leases: [leaseFixture("lease_1", "dev_1")], + }), + view({ devices: [deviceFixture("dev_2")], id: "wrk_b" }), + ], + { health: "running", queueDepth: 0 }, + ); + + expect(status.devices).toEqual([ + expect.objectContaining({ id: "dev_1", workerId: "wrk_a" }), + expect.objectContaining({ id: "dev_2", workerId: "wrk_b" }), + ]); + expect(status.leases).toEqual([expect.objectContaining({ id: "lease_1", workerId: "wrk_a" })]); + }); + + it("keeps a disconnected worker's leases in the aggregate", () => { + // The opposite call from capacity, and deliberately so: a lease on a machine that dropped + // off is still holding a device, which is exactly what an operator needs to see. + const status = aggregateStatus( + [ + view({ + connection: "disconnected", + id: "wrk_a", + leases: [leaseFixture("lease_1", "dev_1")], + }), + ], + { health: "running", queueDepth: 0 }, + ); + + expect(status.leases).toEqual([expect.objectContaining({ id: "lease_1", workerId: "wrk_a" })]); + }); + + it("reports the gateway's own queue depth and health, not any worker's", () => { + const status = aggregateStatus([view({ health: "failed", id: "wrk_a", queueDepth: 7 })], { + health: "starting", + queueDepth: 0, + }); + + expect(status).toMatchObject({ daemon: { health: "starting" }, queueDepth: 0 }); + expect(status.workers?.[0]).toMatchObject({ health: "failed", queueDepth: 7 }); + }); +}); + +describe("aggregateCatalog", () => { + const iosOnA = { + defaultRuntime: "26.0", + models: ["iPhone 17"], + platform: "ios" as const, + runtimes: ["26.0"], + }; + const iosOnB = { + defaultRuntime: "26.0", + models: ["iPhone 17", "iPad Pro"], + platform: "ios" as const, + runtimes: ["26.0", "25.4"], + }; + + it("unions the connected workers' catalogs and annotates every entry", () => { + const catalog = aggregateCatalog([ + view({ catalog: [iosOnA], id: "wrk_a" }), + view({ catalog: [iosOnB], id: "wrk_b" }), + ]); + + expect(() => OPERATIONS["catalog.get"].output.parse(catalog)).not.toThrow(); + expect(catalog.platforms).toHaveLength(1); + expect(catalog.platforms[0]).toMatchObject({ + models: ["iPad Pro", "iPhone 17"], + modelWorkers: { "iPad Pro": ["wrk_b"], "iPhone 17": ["wrk_a", "wrk_b"] }, + platform: "ios", + runtimes: ["25.4", "26.0"], + runtimeWorkers: { "25.4": ["wrk_b"], "26.0": ["wrk_a", "wrk_b"] }, + }); + }); + + it("keeps a default runtime only when every worker agrees on it", () => { + const agreed = aggregateCatalog([ + view({ catalog: [iosOnA], id: "wrk_a" }), + view({ catalog: [iosOnB], id: "wrk_b" }), + ]); + expect(agreed.platforms[0]?.defaultRuntime).toBe("26.0"); + + const disagreed = aggregateCatalog([ + view({ catalog: [iosOnA], id: "wrk_a" }), + view({ catalog: [{ ...iosOnB, defaultRuntime: "25.4" }], id: "wrk_b" }), + ]); + // Picking one at random would make `simlock lease` non-deterministic across an unchanged + // fleet, so a fleet that disagrees has no default. + expect(disagreed.platforms[0]?.defaultRuntime).toBeUndefined(); + }); + + it("ignores a disconnected worker: a machine nobody can reach can lease nothing", () => { + const catalog = aggregateCatalog([ + view({ catalog: [iosOnA], connection: "disconnected", id: "wrk_a" }), + ]); + + expect(catalog.platforms).toEqual([]); + }); + + it("keeps a drained worker, whose models are still installed", () => { + const catalog = aggregateCatalog([view({ catalog: [iosOnA], drained: true, id: "wrk_a" })]); + + expect(catalog.platforms[0]?.models).toEqual(["iPhone 17"]); + }); + + it("filters to one platform when asked", () => { + const catalog = aggregateCatalog( + [ + view({ + catalog: [iosOnA, { models: ["Pixel 9"], platform: "android", runtimes: ["35"] }], + id: "wrk_a", + }), + ], + "android", + ); + + expect(catalog.platforms.map((entry) => entry.platform)).toEqual(["android"]); + }); +}); diff --git a/src/gateway/aggregate.ts b/src/gateway/aggregate.ts new file mode 100644 index 000000000..65294f16f --- /dev/null +++ b/src/gateway/aggregate.ts @@ -0,0 +1,189 @@ +/** + * The fleet, expressed in the same shapes one machine uses (ADR 0005 §20/§21): pure functions + * over worker views, with no clock, no I/O and no state of their own, so what a gateway + * reports is a function of what it currently knows and nothing else. + */ +import type { z } from "zod"; + +import { OPERATIONS, type Platform } from "../contract/index.js"; +import type { WorkerView } from "./worker-registry.js"; + +type StatusOutput = z.infer<(typeof OPERATIONS)["status.get"]["output"]>; +type CatalogOutput = z.infer<(typeof OPERATIONS)["catalog.get"]["output"]>; +type StatusCapacity = StatusOutput["capacity"]; +type PlatformCatalog = CatalogOutput["platforms"][number]; + +const PLATFORMS: readonly Platform[] = ["ios", "android"]; + +const EMPTY_PLATFORM_CAPACITY = { + limit: 0, + maxRunning: 0, + overLimit: false, + reserved: 0, + running: 0, + used: 0, + warm: 0, +}; + +const EMPTY_GLOBAL_CAPACITY = { + maxRunning: 0, + overLimit: false, + reserved: 0, + running: 0, + warm: 0, +}; + +export interface AggregateStatusOptions { + /** The *gateway's* own health, not any worker's. */ + readonly health: StatusOutput["daemon"]["health"]; + /** The gateway's fleet queue depth -- 0 until #118 gives it a queue. */ + readonly queueDepth: number; +} + +/** + * ADR 0005 §20: "the same shape a worker returns -- capacity summed across connected workers, + * all leases and devices, the gateway queue's depth -- plus an additive `workers` array". + * + * Two deliberate asymmetries in what is included: + * + * - **Capacity sums connected workers only.** An unreachable machine's last-known free slots + * are not capacity; reporting them would tell an operator the fleet can take work it cannot. + * - **Devices and leases include every view, connected or not.** A lease on a machine that + * dropped off is precisely what an operator needs to see (it is still holding a device, and + * its worker's TTL is still counting down), so hiding it would be the more misleading + * choice. Each entry carries `workerId`, and that worker's view says whether it is live. + */ +export function aggregateStatus( + views: readonly WorkerView[], + options: AggregateStatusOptions, +): StatusOutput { + return { + capacity: sumCapacity(views.filter((view) => view.connection === "connected")), + daemon: { health: options.health, mode: "gateway" }, + devices: views.flatMap((view) => + view.devices.map((device) => ({ ...device, workerId: view.id })), + ), + leases: views.flatMap((view) => view.leases.map((lease) => ({ ...lease, workerId: view.id }))), + queueDepth: options.queueDepth, + workers: [...views], + }; +} + +function sumCapacity(views: readonly WorkerView[]): StatusCapacity { + const capacity: StatusCapacity = { + android: { ...EMPTY_PLATFORM_CAPACITY }, + global: { ...EMPTY_GLOBAL_CAPACITY }, + ios: { ...EMPTY_PLATFORM_CAPACITY }, + }; + for (const view of views) { + const reported = view.capacity; + if (reported === undefined) continue; + for (const platform of PLATFORMS) { + capacity[platform] = { + limit: capacity[platform].limit + reported[platform].limit, + maxRunning: capacity[platform].maxRunning + reported[platform].maxRunning, + // True if *any* worker is over its own limit: the fleet has a machine in trouble, and + // summing booleans any other way would hide it behind the ones that are fine. + overLimit: capacity[platform].overLimit || reported[platform].overLimit, + reserved: capacity[platform].reserved + reported[platform].reserved, + running: capacity[platform].running + reported[platform].running, + used: capacity[platform].used + reported[platform].used, + warm: capacity[platform].warm + reported[platform].warm, + }; + } + capacity.global = { + maxRunning: capacity.global.maxRunning + reported.global.maxRunning, + overLimit: capacity.global.overLimit || reported.global.overLimit, + reserved: capacity.global.reserved + reported.global.reserved, + running: capacity.global.running + reported.global.running, + warm: capacity.global.warm + reported.global.warm, + }; + } + return capacity; +} + +/** + * ADR 0005 §21: the union of the connected workers' catalogs, each model and runtime annotated + * with the workers that have it. + * + * Connected workers only: a catalog answers "what can this fleet give me", and a machine whose + * uplink is closed can give nothing. `incompatible` workers are excluded for the same reason + * (the gateway never even read their catalog). A drained worker *is* included -- draining stops + * new dispatches, but it is a temporary operator state, and a catalog that shrank while a + * machine was drained would read as models having been uninstalled. + * + * `defaultRuntime` survives only when every worker offering that platform names the same one. + * A fleet whose machines default differently has no single default, and picking one at random + * would make `simlock lease` non-deterministic across an unchanged fleet. + */ +export function aggregateCatalog(views: readonly WorkerView[], platform?: Platform): CatalogOutput { + const byPlatform = indexCatalogs(views, platform); + const platforms: PlatformCatalog[] = []; + // Iterated over `PLATFORMS` rather than the map's own keys so the answer is ordered the same + // way a worker's own `catalog.get` orders it, whichever worker happened to connect first. + for (const candidate of PLATFORMS) { + const bucket = byPlatform.get(candidate); + if (bucket !== undefined) platforms.push(renderPlatform(candidate, bucket)); + } + return { platforms }; +} + +/** One platform's models and runtimes, each mapped to the workers that reported it, plus every + * `defaultRuntime` seen for it -- which is what makes disagreement visible to `renderPlatform` + * rather than resolved silently at insertion. */ +interface CatalogBucket { + readonly models: Map; + readonly runtimes: Map; + readonly defaults: Set; +} + +function indexCatalogs( + views: readonly WorkerView[], + platform: Platform | undefined, +): Map { + const byPlatform = new Map(); + for (const view of views) { + if (view.connection !== "connected") continue; + for (const entry of view.catalog) { + if (platform === undefined || entry.platform === platform) { + addCatalogEntry(byPlatform, entry, view.id); + } + } + } + return byPlatform; +} + +/** Folds one worker's catalog entry for one platform into that platform's bucket. */ +function addCatalogEntry( + byPlatform: Map, + entry: PlatformCatalog, + workerId: string, +): void { + const bucket = byPlatform.get(entry.platform) ?? { + defaults: new Set(), + models: new Map(), + runtimes: new Map(), + }; + byPlatform.set(entry.platform, bucket); + for (const model of entry.models) annotate(bucket.models, model, workerId); + for (const runtime of entry.runtimes) annotate(bucket.runtimes, runtime, workerId); + bucket.defaults.add(entry.defaultRuntime); +} + +function renderPlatform(platform: Platform, bucket: CatalogBucket): PlatformCatalog { + const agreedDefault = bucket.defaults.size === 1 ? [...bucket.defaults][0] : undefined; + return { + models: [...bucket.models.keys()].sort(), + modelWorkers: Object.fromEntries(bucket.models), + platform, + runtimes: [...bucket.runtimes.keys()].sort(), + runtimeWorkers: Object.fromEntries(bucket.runtimes), + ...(agreedDefault === undefined ? {} : { defaultRuntime: agreedDefault }), + }; +} + +function annotate(index: Map, key: string, workerId: string): void { + const workers = index.get(key) ?? []; + if (!workers.includes(workerId)) workers.push(workerId); + index.set(key, workers); +} diff --git a/src/gateway/boundary.test.ts b/src/gateway/boundary.test.ts new file mode 100644 index 000000000..cb8c8611d --- /dev/null +++ b/src/gateway/boundary.test.ts @@ -0,0 +1,242 @@ +import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, posix } from "node:path"; +import { fileURLToPath } from "node:url"; + +import { describe, expect, it } from "vitest"; + +const gatewayDir = dirname(fileURLToPath(import.meta.url)); +const srcDir = dirname(gatewayDir); +const daemonDir = join(srcDir, "daemon"); + +/** + * ADR 0005 §33: "`src/gateway/` imports nothing from `drivers`, and from `core` only the + * platform-agnostic queue and bus modules it reuses; never the registry, capacity, or lifecycle + * modules (enforced like `src/contract/boundary.test.ts`)." + * + * In this PR the gateway reuses nothing from `core` at all -- the fleet queue arrives with #118 + * -- so the allowance is written as an explicit list rather than a blanket "core is fine": a + * gateway that starts importing `core/registry.js` should fail here, and a later PR adding + * `core/wait-queue.js` should have to say so in this list rather than silently widening the + * boundary. `src/http` is off limits for the same reason (`GatewayTokenStore` is a structural + * interface precisely so the token store need not be imported), as are `src/cli`, `src/mcp` and + * `src/drivers`. + * + * Named as top-level directories under `src/`, matched against a specifier normalised relative + * to `src/` (see `normalizeSpecifier`) rather than against the raw text of the specifier -- a + * literal `"../core"` prefix check (C2) only catches an import written from a file directly + * under `src/gateway/`; a nested module (`src/gateway/routing/policy.ts`, which #118 adds) + * reaches core as `"../../core/registry.js"`, which does not start with `"../core"`, so the + * check silently stopped applying to exactly the files a subdirectory newly reaches. + */ +const FORBIDDEN_IMPORT_DIRS = ["core", "drivers", "http", "cli", "mcp"]; + +/** + * The only `src/daemon` module the gateway may import: the transport-facing dispatch contract + * (`DispatchSession`, `DispatchError`, `runDispatch`). It is core-free by construction -- see + * the second test below, which asserts exactly that, so this allowance cannot become a back + * door into the worker's engine. Written normalised (relative to `src/`) for the same reason as + * `FORBIDDEN_IMPORT_DIRS` above. + */ +const ALLOWED_DAEMON_IMPORTS = ["daemon/dispatch.js"]; + +/** + * A relative import specifier, resolved against the directory of the file that wrote it and + * expressed relative to `src/` -- e.g. `"../../core/registry.js"` from + * `src/gateway/routing/policy.ts` becomes `"core/registry.js"`, exactly like + * `"../core/registry.js"` from `src/gateway/policy.ts` does. A non-relative specifier (an npm + * package, a `node:` built-in) is returned unchanged: it can never resolve inside `src/`, so no + * prefix check below will ever match it. + */ +function normalizeSpecifier(fileDir: string, specifier: string): string { + if (!specifier.startsWith(".")) return specifier; + const resolved = posix.normalize(posix.join(fileDir, specifier)); + return posix.relative(srcDir, resolved); +} + +/** Whether a normalised specifier names a module inside the top-level `src/` directory `dir` -- + * `dir` itself (an import of its barrel, `"core"` with no further path) or anything under it. */ +function isUnder(normalized: string, dir: string): boolean { + return normalized === dir || normalized.startsWith(`${dir}/`); +} + +/** + * Recursive and by relative path (M4): a flat, non-recursive listing let a future subdirectory + * under `src/gateway/` skip this test's notice entirely, silently, the moment one was added -- + * exactly the kind of gap that should fail loudly instead. `recursive: true` is Node 20+; the + * repo requires Node 22. + */ +function sourceFilesRecursive(dir: string): string[] { + return readdirSync(dir, { recursive: true, withFileTypes: true }) + .filter( + (entry) => entry.isFile() && entry.name.endsWith(".ts") && !entry.name.endsWith(".test.ts"), + ) + .map((entry) => join(entry.parentPath, entry.name)); +} + +describe("gateway module boundary", () => { + const sourceFiles = sourceFilesRecursive(gatewayDir); + + it("found the gateway's own source files", () => { + expect(sourceFiles.length).toBeGreaterThan(0); + }); + + it.each(sourceFiles.map((path) => [path.slice(gatewayDir.length + 1), path] as const))( + "%s imports no engine module", + (relativePath, filePath) => { + const contents = readFileSync(filePath, "utf8"); + const fileDir = dirname(filePath); + + for (const specifier of importSpecifiers(stripComments(contents))) { + const normalized = normalizeSpecifier(fileDir, specifier); + for (const forbidden of FORBIDDEN_IMPORT_DIRS) { + expect({ + fileName: relativePath, + normalized, + specifier, + matchesForbiddenDir: isUnder(normalized, forbidden), + }).toEqual({ + fileName: relativePath, + normalized, + specifier, + matchesForbiddenDir: false, + }); + } + if (isUnder(normalized, "daemon")) { + expect(ALLOWED_DAEMON_IMPORTS).toContain(normalized); + } + } + }, + ); + + it("the one daemon module the gateway imports is itself free of core", () => { + const contents = stripComments(readFileSync(join(daemonDir, "dispatch.ts"), "utf8")); + + for (const specifier of importSpecifiers(contents)) { + const normalized = normalizeSpecifier(daemonDir, specifier); + expect(isUnder(normalized, "core")).toBe(false); + expect(isUnder(normalized, "drivers")).toBe(false); + expect(isUnder(normalized, "http")).toBe(false); + } + }); +}); + +describe("sourceFilesRecursive", () => { + // M4: the other half of the gap -- a flat `readdirSync` never looked inside a subdirectory at + // all, so a module placed under one skipped this whole suite silently rather than failing it. + it("descends into a subdirectory, and still skips test files there", () => { + const dir = mkdtempSync(join(tmpdir(), "simlock-boundary-test-")); + try { + mkdirSync(join(dir, "nested")); + writeFileSync(join(dir, "top.ts"), "export {};"); + writeFileSync(join(dir, "nested", "deep.ts"), "export {};"); + writeFileSync(join(dir, "nested", "deep.test.ts"), "export {};"); + + const found = sourceFilesRecursive(dir) + .map((path) => path.slice(dir.length + 1)) + .sort(); + + expect(found).toEqual(["nested/deep.ts", "top.ts"]); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); + +describe("normalizeSpecifier / isUnder", () => { + // C2: the round's title/body tell -- the old check compared the raw specifier text to a + // literal `"../core"` prefix, which is only ever true for a file directly under + // `src/gateway/`. `src/gateway/routing/policy.ts` (a subdirectory #118 adds) reaches the same + // module as `"../../core/registry.js"`, one `..` longer, and a bare `startsWith` check does + // not know the two name the same forbidden module. Resolving both against the file's own + // directory into a path relative to `src/` is what makes them compare equal. + it("resolves a nested file's longer relative path to the same normalized module as a top-level one", () => { + const topLevel = normalizeSpecifier(gatewayDir, "../core/registry.js"); + const nested = normalizeSpecifier(join(gatewayDir, "routing"), "../../core/registry.js"); + + expect(nested).toBe(topLevel); + expect(nested).toBe("core/registry.js"); + expect(isUnder(nested, "core")).toBe(true); + }); + + it("leaves a non-relative specifier (a package, a node: built-in) unchanged", () => { + expect(normalizeSpecifier(gatewayDir, "zod")).toBe("zod"); + expect(normalizeSpecifier(gatewayDir, "node:fs")).toBe("node:fs"); + }); + + it("does not flag a same-directory or sibling-module import as forbidden", () => { + const normalized = normalizeSpecifier(gatewayDir, "./worker-registry.js"); + expect(isUnder(normalized, "core")).toBe(false); + }); +}); + +describe("gateway module boundary regression fixtures", () => { + // C2, made concrete: this is exactly the file #118 adds, reduced to the one line that matters. + // Against the pre-fix `specifier.startsWith("../core")` check, this import passes silently -- + // `"../../core/registry.js"` does not start with `"../core"` -- even though it reaches the + // exact module the boundary exists to keep out. + it("catches a nested module importing core through a longer relative path", () => { + const nestedDir = join(gatewayDir, "routing"); + const specifier = "../../core/registry.js"; + const normalized = normalizeSpecifier(nestedDir, specifier); + + expect(FORBIDDEN_IMPORT_DIRS.some((forbidden) => isUnder(normalized, forbidden))).toBe(true); + }); + + // And the matching allowlist gap: `"../../daemon/dispatcher.js"` does not start with + // `"../daemon"` either, so the pre-fix allowlist branch was never entered for a nested file -- + // it would neither pass as allowed nor fail as forbidden, just vanish from the check entirely. + it("still recognizes a nested module's daemon import as a daemon import to check against the allowlist", () => { + const nestedDir = join(gatewayDir, "routing"); + const normalized = normalizeSpecifier(nestedDir, "../../daemon/dispatcher.js"); + + expect(isUnder(normalized, "daemon")).toBe(true); + expect(ALLOWED_DAEMON_IMPORTS).not.toContain(normalized); + }); +}); + +describe("importSpecifiers", () => { + // M4: the gap the first review round found -- a dynamic `await import(...)` routed around + // every check above without either of these. + it("catches a dynamic import, not just a static `from`", () => { + expect(importSpecifiers('const mod = await import("../core/registry.js");')).toContain( + "../core/registry.js", + ); + }); + + it("catches a bare side-effect import with no `from` clause", () => { + expect(importSpecifiers('import "../core/registry.js";')).toContain("../core/registry.js"); + }); + + it("still catches an ordinary static import exactly once", () => { + expect(importSpecifiers('import { x } from "../core/registry.js";')).toEqual([ + "../core/registry.js", + ]); + }); +}); + +/** Strips block and line comments so a specifier that appears only in prose (a doc comment + * naming a forbidden import, as several in this module do) is never mistaken for a real one. */ +function stripComments(source: string): string { + return source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/.*$/gm, ""); +} + +/** + * Every module specifier a static `import ... from "…"`, a bare side-effect `import "…"`, a + * re-export (`export ... from "…"`), or a dynamic `await import("…")` names, in the + * (comment-stripped) text. Formatter-wrapped multi-line static imports are still caught because + * the `from "…"` clause always lands on one line; the dynamic form is its own pattern (M4) -- + * without it, a boundary this test enforces on every static import could be routed around with + * one `await import("../core/registry.js")` and this suite would stay green. + */ +function importSpecifiers(contents: string): string[] { + const specifiers: string[] = []; + const patterns = [/(?:from|import)\s*["']([^"']+)["']/g, /import\s*\(\s*["']([^"']+)["']/g]; + for (const pattern of patterns) { + for (const match of contents.matchAll(pattern)) { + const specifier = match[1]; + if (specifier !== undefined) specifiers.push(specifier); + } + } + return specifiers; +} diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts new file mode 100644 index 000000000..f55a0dfa9 --- /dev/null +++ b/src/gateway/dispatcher.test.ts @@ -0,0 +1,374 @@ +import { describe, expect, it } from "vitest"; + +import { EventBus } from "../bus/index.js"; +import { OPERATIONS, type OperationName } from "../contract/index.js"; +import type { DispatchSession } from "../daemon/dispatch.js"; +import { FakeClock } from "../ports/index.js"; +import { GatewayDispatcher, type GatewayTokenStore } from "./dispatcher.js"; +import { MemoryDrainStore } from "./drain-store.js"; +import { deviceFixture, leaseFixture, statusFixture } from "./test-support.js"; +import { WorkerRegistry } from "./worker-registry.js"; + +const gatewayConfig = { + capacity: { strategy: "fixed" as const, config: { maxRunning: 4 } }, + diskPressure: { freeBytesThreshold: 1 }, + downloads: { acceptAndroidLicenses: false, policy: "on-request" as const, timeoutMs: 1 }, + eventBuffer: { capacity: 100 }, + exec: { timeoutMs: 600_000 }, + gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, + health: { + enabled: false, + maxConcurrentRecoveries: 1, + maxRecoveryAttempts: 1, + probeIntervalMs: 1, + recoveryBackoffMs: 1, + stableObservations: 1, + }, + http: { enabled: true, host: "127.0.0.1", port: 4700 }, + idle: { deleteAfterMs: 1, shutdownAfterMs: 1 }, + ios: { slim: { bootTimeoutMs: 1, enabled: false } }, + lease: { defaultTtlMs: 900_000, maxTtlMs: 3_600_000 }, + log: { level: "info" as const, rotateBytes: 1 }, + mode: "gateway" as const, + stalledTransition: { minimumThresholdMs: 1, thresholdMultiplier: 1 }, + warmPool: { + quarantine: { + maxRetries: 1, + maxRetryBackoffMs: 1, + retryBackoffMs: 1, + retryBackoffMultiplier: 1, + }, + }, +}; + +class FakeTokens implements GatewayTokenStore { + readonly created: string[] = []; + readonly revoked: string[] = []; + + async create(role: "agent" | "operator" | "worker", label?: string) { + this.created.push(role); + return { + record: { createdAt: 1, id: "tok_1", role, ...(label === undefined ? {} : { label }) }, + secret: "slk_secret", + }; + } + + async list() { + return [{ createdAt: 1, id: "tok_1", role: "worker" as const }]; + } + + async revoke(id: string) { + this.revoked.push(id); + // Only "tok_1" is ever actually minted by this fake -- anything else is the "already gone, + // or never real" case C-2's test below needs a real `false` for. + return id === "tok_1"; + } +} + +function harness() { + const clock = new FakeClock(1_000); + const eventBus = new EventBus(clock); + const workers = new WorkerRegistry({ + clock, + drainStore: new MemoryDrainStore(), + eventBus, + leaseMaxTtlMs: gatewayConfig.lease.maxTtlMs, + retentionMs: 24 * 60 * 60_000, + }); + const tokens = new FakeTokens(); + /** C-2: every id `closeUplinksForToken` was actually called with, in call order. */ + const closedUplinkTokens: string[] = []; + const dispatcher = new GatewayDispatcher({ + awaitReady: async () => {}, + closeUplinksForToken: async (tokenId) => { + closedUplinkTokens.push(tokenId); + }, + config: gatewayConfig, + eventBus, + health: () => "running", + tokens, + workers, + }); + return { clock, closedUplinkTokens, dispatcher, eventBus, tokens, workers }; +} + +function session(overrides: Partial = {}): DispatchSession { + return { + manageEventSubscription: () => "sub_1", + principal: "operator-1", + role: "admin", + ...overrides, + }; +} + +/** Every operation the contract declares, minus `daemon.stop` (the transport answers it). */ +const EVERY_OPERATION = (Object.keys(OPERATIONS) as OperationName[]).filter( + (name) => name !== "daemon.stop", +); + +describe("GatewayDispatcher", () => { + it("answers status.get from the fleet", async () => { + const { dispatcher, workers } = harness(); + workers.connected("wrk_1", "mac-mini-1", "0.3.0"); + workers.refresh("wrk_1", { + capacity: statusFixture().capacity, + devices: [deviceFixture("dev_1", "leased")], + health: "running", + leases: [leaseFixture("lease_1", "dev_1")], + queueDepth: 0, + }); + + const status = await dispatcher.dispatch("status.get", {}, session()); + + expect(status.daemon.mode).toBe("gateway"); + expect(status.workers).toHaveLength(1); + expect(status.devices).toEqual([expect.objectContaining({ workerId: "wrk_1" })]); + expect(status.leases).toEqual([expect.objectContaining({ workerId: "wrk_1" })]); + }); + + it("answers catalog.get as the union of the fleet's catalogs", async () => { + const { dispatcher, workers } = harness(); + workers.connected("wrk_1", undefined, undefined); + workers.refresh("wrk_1", { + catalog: [{ models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }], + }); + + const catalog = await dispatcher.dispatch("catalog.get", {}, session()); + + expect(catalog.platforms[0]?.modelWorkers).toEqual({ "iPhone 17": ["wrk_1"] }); + }); + + it("answers config.get with the gateway's own config", async () => { + const { dispatcher } = harness(); + + await expect(dispatcher.dispatch("config.get", {}, session())).resolves.toMatchObject({ + mode: "gateway", + }); + }); + + it("lists workers, and drains, undrains and removes one", async () => { + const { dispatcher, workers } = harness(); + workers.connected("wrk_1", "mac-mini-1", "0.3.0"); + + await expect(dispatcher.dispatch("worker.list", {}, session())).resolves.toMatchObject({ + workers: [{ connection: "connected", id: "wrk_1", label: "mac-mini-1" }], + }); + + await expect( + dispatcher.dispatch("worker.drain", { workerId: "wrk_1" }, session()), + ).resolves.toEqual({ drained: true, workerId: "wrk_1" }); + expect(workers.view("wrk_1")?.drained).toBe(true); + + await expect( + dispatcher.dispatch("worker.undrain", { workerId: "wrk_1" }, session()), + ).resolves.toEqual({ drained: false, workerId: "wrk_1" }); + + workers.disconnected("wrk_1"); + await expect( + dispatcher.dispatch("worker.remove", { workerId: "wrk_1" }, session()), + ).resolves.toEqual({ removed: true, workerId: "wrk_1" }); + }); + + it("refuses to remove a connected worker with WORKER_CONNECTED, naming it", async () => { + const { dispatcher, workers } = harness(); + workers.connected("wrk_1", undefined, undefined); + + await expect( + dispatcher.dispatch("worker.remove", { workerId: "wrk_1" }, session()), + ).rejects.toMatchObject({ code: "WORKER_CONNECTED", details: { workerId: "wrk_1" } }); + }); + + it("reports removed: false for a worker it has never heard of", async () => { + const { dispatcher } = harness(); + + await expect( + dispatcher.dispatch("worker.remove", { workerId: "wrk_ghost" }, session()), + ).resolves.toEqual({ removed: false, workerId: "wrk_ghost" }); + }); + + it("answers UNKNOWN_WORKER when asked to drain a worker it has no view of", async () => { + const { dispatcher } = harness(); + + await expect( + dispatcher.dispatch("worker.drain", { workerId: "wrk_ghost" }, session()), + ).rejects.toMatchObject({ code: "UNKNOWN_WORKER", details: { workerId: "wrk_ghost" } }); + }); + + it("keeps worker.* admin-only", async () => { + const { dispatcher } = harness(); + + await expect( + dispatcher.dispatch("worker.list", {}, session({ role: "agent" })), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + }); + + it("lists the fleet's leases and devices, each naming its worker", async () => { + const { dispatcher, workers } = harness(); + workers.connected("wrk_1", undefined, undefined); + workers.refresh("wrk_1", { + devices: [deviceFixture("dev_1", "leased")], + leases: [leaseFixture("lease_1", "dev_1")], + }); + + await expect(dispatcher.dispatch("lease.list", {}, session())).resolves.toEqual({ + leases: [expect.objectContaining({ id: "lease_1", workerId: "wrk_1" })], + }); + await expect(dispatcher.dispatch("list.get", { kind: "devices" }, session())).resolves.toEqual([ + expect.objectContaining({ id: "dev_1", workerId: "wrk_1" }), + ]); + // Cleanup rules are a machine's own configuration, and a gateway runs no reaper. + await expect(dispatcher.dispatch("list.get", { kind: "rules" }, session())).resolves.toEqual( + [], + ); + }); + + // P-1 (third review round): the previous version of `#leaseList` compared a namespaced form + // of the session's own principal to each lease's `ownerId` -- a comparison that was false by + // construction (see `#leaseList`'s own comment) and so, in practice, indistinguishable from + // simply returning `[]`. This asserts the actual, current contract: a non-admin session sees + // no fleet leases at all, whatever its principal, until #118's own `FleetLeaseIndex` replaces + // this handler. + it("shows a non-admin session no fleet leases at all, regardless of its principal", async () => { + const { dispatcher, workers } = harness(); + workers.connected("wrk_1", undefined, undefined); + // `leaseFixture`'s ownerId ("agent-1") is a worker-local principal; this session's own + // principal is deliberately the exact same string, since a principal collision -- not just + // a mismatch -- is the case worth a session leaking a machine's own local lease. + workers.refresh("wrk_1", { leases: [leaseFixture("lease_1", "dev_1")] }); + + await expect( + dispatcher.dispatch("lease.list", {}, session({ principal: "agent-1", role: "agent" })), + ).resolves.toEqual({ leases: [] }); + }); + + // The behavior this round's fix actually changes: the deleted comparison, when fed the one + // input that made it succeed (a lease whose `ownerId` is that session's principal namespaced + // with the gateway's own `gw::` prefix -- the shape a real gateway-issued lease + // would carry once #118 lands, but nothing in this PR ever produces), used to return that + // lease to a non-admin session. This asserts the deliberate regression: `#leaseList` no + // longer has any code path that returns a lease to a non-admin session, matching or not, + // until #118 replaces it with `FleetLeaseIndex`'s real filter. + it("does not resurrect visibility through a namespaced ownerId nothing in this PR can produce", async () => { + const { dispatcher, workers } = harness(); + workers.connected("wrk_1", undefined, undefined); + const lease = { ...leaseFixture("lease_1", "dev_1"), ownerId: "gw:instance-1:agent-1" }; + workers.refresh("wrk_1", { leases: [lease] }); + + await expect( + dispatcher.dispatch("lease.list", {}, session({ principal: "agent-1", role: "agent" })), + ).resolves.toEqual({ leases: [] }); + }); + + it("replays and subscribes to its own bus, which carries the fleet's events", async () => { + const { dispatcher, eventBus } = harness(); + eventBus.emit("lease.granted", { deviceId: "dev_1", leaseId: "l1", requester: "a" }, "worker"); + + await expect(dispatcher.dispatch("events.replay", {}, session())).resolves.toEqual([ + expect.objectContaining({ event: "lease.granted" }), + ]); + await expect(dispatcher.dispatch("events.subscribe", {}, session())).resolves.toEqual({ + subscribed: true, + subscriptionId: "sub_1", + }); + }); + + it("mints and revokes its own tokens, worker join tokens included", async () => { + const { dispatcher, tokens } = harness(); + + await expect( + dispatcher.dispatch("token.create", { role: "worker", label: "mac-mini-1" }, session()), + ).resolves.toMatchObject({ secret: "slk_secret", token: { role: "worker" } }); + expect(tokens.created).toEqual(["worker"]); + + await expect(dispatcher.dispatch("token.revoke", { id: "tok_1" }, session())).resolves.toEqual({ + revoked: true, + }); + }); + + // C-2, ADR 0005 §8 ("revoking closes the uplink"): `#tokenRevoke` used to only write the + // store -- the join token was checked once, at upgrade, and nothing ever re-verified a live + // link, so revoking a worker's token had no observable effect until that worker happened to + // reconnect on its own, possibly never. This asserts the actual wiring `main.ts` depends on: + // a successful revoke calls `closeUplinksForToken` with exactly the revoked id. + it("closes the uplink a revoked token authorized, not merely the store entry (C-2)", async () => { + const { closedUplinkTokens, dispatcher } = harness(); + + await expect(dispatcher.dispatch("token.revoke", { id: "tok_1" }, session())).resolves.toEqual({ + revoked: true, + }); + + expect(closedUplinkTokens).toEqual(["tok_1"]); + }); + + // The other half of the same wiring: revoking an id the store never had is not a live link to + // close either, and must not call the hook with a token id that authorized nothing. + it("does not try to close an uplink for a token id that was never real (C-2)", async () => { + const { closedUplinkTokens, dispatcher } = harness(); + + await expect( + dispatcher.dispatch("token.revoke", { id: "tok_unknown" }, session()), + ).resolves.toEqual({ revoked: false }); + + expect(closedUplinkTokens).toEqual([]); + }); + + describe("UNSUPPORTED_IN_GATEWAY_MODE", () => { + it.each(["nuke.run", "cleanup.run", "doctor.run", "driver.passthrough"] as const)( + "%s stays per-worker, permanently", + async (operation) => { + const { dispatcher } = harness(); + const input = + operation === "driver.passthrough" ? { args: ["devices"], tool: "adb" } : { fix: true }; + + await expect(dispatcher.dispatch(operation, input, session())).rejects.toMatchObject({ + code: "UNSUPPORTED_IN_GATEWAY_MODE", + details: { operation }, + }); + }, + ); + + it.each([ + ["lease.request", { model: "iPhone 17", platform: "ios" }], + ["lease.renew", { leaseId: "lease_1" }], + ["lease.release", { leaseId: "lease_1" }], + ["lease.cancel", {}], + ["lease.release-all", {}], + ["device.exec", { leaseId: "lease_1", tool: "adb", args: ["devices"] }], + ] as const)("%s waits for fleet routing", async (operation, input) => { + const { dispatcher } = harness(); + + await expect( + dispatcher.dispatch(operation as OperationName, input, session()), + ).rejects.toMatchObject({ code: "UNSUPPORTED_IN_GATEWAY_MODE", details: { operation } }); + }); + }); + + it("has an answer for every operation the contract declares", async () => { + // Not one operation may fall through to `UNKNOWN_REQUEST` on a gateway: the contract is the + // same one every frontend renders, so "the gateway forgot about this operation" must be a + // failing test rather than a runtime surprise. Inputs here are only shaped well enough to + // reach the handler. + const inputs: Partial> = { + "driver.passthrough": { args: [], tool: "adb" }, + "lease.release": { leaseId: "lease_1" }, + "lease.renew": { leaseId: "lease_1" }, + "lease.request": { model: "iPhone 17", platform: "ios" }, + "token.create": { role: "agent" }, + "token.revoke": { id: "tok_1" }, + "worker.drain": { workerId: "wrk_1" }, + "worker.remove": { workerId: "wrk_1" }, + "worker.undrain": { workerId: "wrk_1" }, + }; + const { dispatcher, workers } = harness(); + workers.connected("wrk_1", undefined, undefined); + workers.disconnected("wrk_1"); + + for (const operation of EVERY_OPERATION) { + const outcome = await dispatcher.dispatch(operation, inputs[operation] ?? {}, session()).then( + () => "answered", + (error: unknown) => (error as { code?: string }).code ?? "threw", + ); + expect({ operation, outcome }).not.toEqual({ operation, outcome: "UNKNOWN_REQUEST" }); + } + }); +}); diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts new file mode 100644 index 000000000..086792a40 --- /dev/null +++ b/src/gateway/dispatcher.ts @@ -0,0 +1,303 @@ +/** + * The gateway's implementation of the daemon contract (ADR 0005 §32): "a second implementation + * of the daemon contract's handlers, not a second contract". Same `runDispatch` pipeline, same + * operation declarations, same role checks -- only the handlers differ, reading worker views + * instead of a registry and a lease engine. + * + * Three populations of operations live in the table below: + * + * 1. **Answered from the fleet**: `status.get` and `catalog.get` (aggregated, §20/§21), + * `worker.*` (§8/§23), `events.*` (the gateway's own bus, which carries every worker's + * republished events, §22), `config.get` (the gateway's own config, §34), `token.*` (a + * gateway mints its own credentials, §24). + * 2. **Refused permanently** (`unsupportedByDesign`): `nuke.run`, `cleanup.run`, `doctor.run` + * and `driver.passthrough` (§34) -- operations that act on one machine's devices as a whole. + * 3. **Refused until #118** (`unsupportedUntilRouting`): the lease *lifecycle* -- + * `lease.request`, `renew`, `release`, `cancel`, `release-all` -- and `device.exec`, which + * a gateway proxies to the worker that owns the device (§19b). The fleet queue, routing and + * forwarding are that PR's; this one deliberately makes the fleet visible before it is + * routable. + * + * The read-only members of the lease family -- `lease.list` and `list.get` -- are in the first + * population, not the third: they are the fleet made *visible*, which is this PR's whole point, + * and answering them needs nothing but the views. They read what workers report rather than + * forwarding anything, so #118 replaces their implementation (with its own lease index) without + * changing what a caller sees. + * + * The last two answer `UNSUPPORTED_IN_GATEWAY_MODE`; `details.operation` and the message say + * which population an answer came from. The table is typed total over the contract minus + * `daemon.stop`, so a newly declared operation is a compile error here until someone decides + * which of the three it belongs to. + */ +import type { z } from "zod"; + +import type { EventBus } from "../bus/index.js"; +import { OPERATIONS, type OperationName, type tokenRecordSchema } from "../contract/index.js"; +import { + DispatchError, + runDispatch, + type DispatchSession, + type ErasedHandler, +} from "../daemon/dispatch.js"; +import type { Logger } from "../ports/index.js"; +import { NoopLogger } from "../ports/index.js"; +import { aggregateCatalog, aggregateStatus } from "./aggregate.js"; +import type { WorkerRegistry } from "./worker-registry.js"; + +type Handler = ( + input: z.infer<(typeof OPERATIONS)[Op]["input"]>, + session: DispatchSession, +) => Promise | unknown; + +type TokenRecord = z.infer; + +type DeepReadonly = Value extends (infer Item)[] + ? readonly DeepReadonly[] + : Value extends object + ? { readonly [Key in keyof Value]: DeepReadonly } + : Value; + +/** + * The config `config.get` answers with, as this module sees it: the contract's own shape, made + * deeply readonly so `src/core`'s `Config` (which is) assigns into it. Declared this way rather + * than by importing `Config` because `src/gateway` imports nothing from `core` (ADR 0005 §33), + * and the gateway has no business with the type's *meaning* anyway -- it stores this value and + * hands it back. + */ +export type GatewayConfig = DeepReadonly>; + +/** + * The token store, structurally. Narrower than importing `TokenStore` itself (which lives under + * `src/http` for historical reasons): the gateway needs three methods, and depending on the + * shape rather than the class is what keeps `src/gateway` from importing a frontend. + */ +export interface GatewayTokenStore { + create( + role: "agent" | "operator" | "worker", + label?: string, + ): Promise<{ record: TokenRecord; secret: string }>; + list(): Promise; + revoke(id: string): Promise; +} + +export interface GatewayDispatcherOptions { + /** The gateway's own config -- what `config.get` returns (ADR 0005 §34). */ + readonly config: GatewayConfig; + readonly eventBus: EventBus; + readonly workers: WorkerRegistry; + readonly tokens?: GatewayTokenStore; + /** + * C-2, ADR 0005 §8: "revoking closes the uplink". Called after a successful `token.revoke` + * with the revoked token's id, so any uplink that token authenticated is closed immediately + * rather than only at that worker's next reconnect (uplinks are long-lived, so without this a + * revoked worker token has no observable effect until the worker happens to redial). Optional + * so a test exercising `token.revoke` in isolation, with no `GatewayService` behind it, need + * not supply one -- revocation still writes the store either way. + */ + readonly closeUplinksForToken?: (tokenId: string) => Promise; + readonly logger?: Logger; + /** The gateway's own health, for `status.get`. */ + readonly health: () => "starting" | "running" | "failed"; + readonly awaitReady: () => Promise; +} + +export class GatewayDispatcher { + readonly #logger: Logger; + readonly #handlers: Record, ErasedHandler>; + + constructor(private readonly options: GatewayDispatcherOptions) { + this.#logger = options.logger ?? new NoopLogger(); + this.#handlers = { + "catalog.get": this.#catalogGet, + "status.get": this.#statusGet, + "config.get": this.#configGet, + "events.replay": this.#eventsReplay, + "events.subscribe": this.#eventsSubscribe, + "events.unsubscribe": this.#eventsUnsubscribe, + "token.create": this.#tokenCreate, + "token.list": this.#tokenList, + "token.revoke": this.#tokenRevoke, + "worker.list": this.#workerList, + "worker.drain": this.#workerDrain, + "worker.undrain": this.#workerUndrain, + "worker.remove": this.#workerRemove, + "lease.list": this.#leaseList, + "list.get": this.#listGet, + + "nuke.run": unsupportedByDesign("nuke.run"), + "cleanup.run": unsupportedByDesign("cleanup.run"), + "doctor.run": unsupportedByDesign("doctor.run"), + "driver.passthrough": unsupportedByDesign("driver.passthrough"), + + "lease.request": unsupportedUntilRouting("lease.request"), + "lease.renew": unsupportedUntilRouting("lease.renew"), + "lease.release": unsupportedUntilRouting("lease.release"), + "lease.cancel": unsupportedUntilRouting("lease.cancel"), + "lease.release-all": unsupportedUntilRouting("lease.release-all"), + "device.exec": unsupportedUntilRouting("device.exec"), + // "daemon.stop" is absent for the same reason it is absent from the worker's table: the + // transport intercepts it ahead of any dispatch (ADR 0003 §6's frozen exception). + }; + } + + dispatch( + operation: Op, + rawInput: unknown, + session: DispatchSession, + ): Promise> { + return runDispatch(operation, rawInput, session, { + handlers: this.#handlers, + // No `authorizeLookups`: the gateway holds no leases and no pending requests of its own + // in this PR, so both lookups answer `undefined`, which every `authorize` hook treats as + // authorized -- and every operation carrying one is refused here anyway. #118 supplies + // the real lookups along with the lease index they read. + awaitReady: () => this.options.awaitReady(), + onOutputMismatch: (operationName, issues) => { + this.#logger.error("Operation output failed contract validation", { + operation: operationName, + issues, + }); + }, + }); + } + + // ---- handlers ----------------------------------------------------------------------------- + + #statusGet: Handler<"status.get"> = () => + aggregateStatus(this.options.workers.views(), { + health: this.options.health(), + // ADR 0005 §20: the *gateway's* queue depth. It has no queue until #118, and 0 is the + // honest answer for a queue that cannot hold anything -- not a placeholder. + queueDepth: 0, + }); + + #catalogGet: Handler<"catalog.get"> = (input) => + aggregateCatalog(this.options.workers.views(), input.platform); + + #configGet: Handler<"config.get"> = () => this.options.config; + + #eventsReplay: Handler<"events.replay"> = (input) => + this.options.eventBus.replay(input.sinceTs === undefined ? {} : { sinceTs: input.sinceTs }); + + #eventsSubscribe: Handler<"events.subscribe"> = (_input, session) => { + const subscriptionId = session.manageEventSubscription(true); + if (subscriptionId === undefined) { + throw new DispatchError("INTERNAL", "Transport did not provide a subscription id"); + } + return { subscribed: true, subscriptionId }; + }; + + #eventsUnsubscribe: Handler<"events.unsubscribe"> = (_input, session) => { + session.manageEventSubscription(false); + return { subscribed: false }; + }; + + #tokenCreate: Handler<"token.create"> = async (input) => { + const { record, secret } = await this.#requireTokens().create(input.role, input.label); + return { secret, token: record }; + }; + + #tokenList: Handler<"token.list"> = async () => ({ tokens: await this.#requireTokens().list() }); + + #tokenRevoke: Handler<"token.revoke"> = async (input) => { + const revoked = await this.#requireTokens().revoke(input.id); + // C-2: only a token that actually existed can have opened an uplink -- revoking an unknown + // id (already-gone, or never real) has nothing to close, same as it has nothing to forget + // in the store. + if (revoked) await this.options.closeUplinksForToken?.(input.id); + return { revoked }; + }; + + #workerList: Handler<"worker.list"> = () => ({ workers: this.options.workers.views() }); + + #workerDrain: Handler<"worker.drain"> = async (input) => { + await this.options.workers.setDrained(input.workerId, true); + return { drained: true, workerId: input.workerId }; + }; + + #workerUndrain: Handler<"worker.undrain"> = async (input) => { + await this.options.workers.setDrained(input.workerId, false); + return { drained: false, workerId: input.workerId }; + }; + + #workerRemove: Handler<"worker.remove"> = async (input) => ({ + removed: await this.options.workers.remove(input.workerId), + workerId: input.workerId, + }); + + /** + * Every lease the fleet's views report, each carrying its `workerId` (ADR 0005 §20), for an + * admin session. A non-admin session sees none of them. + * + * P-1 (third review round): P2's version of this handler compared a namespaced form of the + * session's own principal (`gatewayRequesterPrefix` + `session.principal`) against each + * lease's `ownerId` -- but on a worker, `ownerId` is the *raw*, un-namespaced local principal + * (`daemon/dispatcher.ts`'s own `lease.list`), and the gateway's own principal at `hello` is + * `gw:` with no `:` suffix (`GatewayService`). A string ending in + * `:` can therefore never equal `gw:`, so that comparison returned + * `[]` for every non-admin session *by construction* -- not "until #118", as its comment + * claimed -- and nothing exercised it except a test that hand-built an `ownerId` no code path + * actually produces. #118 replaces this handler outright with its own `FleetLeaseIndex`, + * filtered by `ownerId` for the real, routed case; this handler is deliberately left inert + * rather than growing a second, competing namespacing scheme #118 would then have to undo. + * Same observable behavior as before (`[]`), no comparison pretending to be live. + */ + #leaseList: Handler<"lease.list"> = (_input, session) => ({ + leases: session.role === "admin" ? this.#fleetLeases() : [], + }); + + /** + * The admin inspection of the fleet. `devices` and `leases` are the aggregate with + * `workerId`; `rules` is empty, because cleanup rules are a machine's own configuration and a + * gateway runs no reaper (ADR 0005 §2) -- an empty list says "this endpoint has none", which + * is true, where a refusal would suggest the question was wrong. + */ + #listGet: Handler<"list.get"> = (input) => { + switch (input.kind) { + case "leases": + return this.#fleetLeases(); + case "rules": + return []; + case "devices": + case undefined: + return this.options.workers + .views() + .flatMap((view) => view.devices.map((device) => ({ ...device, workerId: view.id }))); + } + }; + + #fleetLeases() { + return this.options.workers + .views() + .flatMap((view) => view.leases.map((lease) => ({ ...lease, workerId: view.id }))); + } + + #requireTokens(): GatewayTokenStore { + if (this.options.tokens === undefined) { + throw new DispatchError("INTERNAL", "Token store is unavailable"); + } + return this.options.tokens; + } +} + +/** ADR 0005 §34: stays per-worker, permanently. */ +function unsupportedByDesign(operation: OperationName): ErasedHandler { + return () => { + throw new DispatchError( + "UNSUPPORTED_IN_GATEWAY_MODE", + `${operation} acts on one machine's devices; run it against a worker`, + { operation }, + ); + }; +} + +/** Answered once #118 gives the gateway a queue, a routing policy, and lease forwarding. */ +function unsupportedUntilRouting(operation: OperationName): ErasedHandler { + return () => { + throw new DispatchError( + "UNSUPPORTED_IN_GATEWAY_MODE", + `${operation} is not available on a gateway yet; fleet routing implements it`, + { operation }, + ); + }; +} diff --git a/src/gateway/drain-store.ts b/src/gateway/drain-store.ts new file mode 100644 index 000000000..c02ee8752 --- /dev/null +++ b/src/gateway/drain-store.ts @@ -0,0 +1,93 @@ +/** + * The one thing a gateway persists (ADR 0005, Decision 3: the worker registry is gateway + * state): which workers an operator has drained. + * + * Everything else on a view is rebuilt from the workers themselves on reconnect, which is why + * this file holds ids and nothing else. Drain cannot be rebuilt that way -- it is an operator's + * decision about a machine, not a fact the machine reports -- and losing it is the one failure + * mode that matters: a gateway restart, or a worker reconnecting after a reboot, would silently + * put a machine that was taken out of service back into rotation. + */ +import { dirname } from "node:path"; + +import type { Filesystem, Logger } from "../ports/index.js"; +import { NoopLogger } from "../ports/index.js"; + +/** Owner-only, like every other file the daemon keeps under `SIMLOCK_HOME` (`tokens.json`, + * `admin.token`, `state.json`): the trust boundary is the OS user. */ +const WORKERS_FILE_MODE = 0o600; + +export interface DrainStore { + load(): Promise; + save(drainedWorkerIds: readonly string[]): Promise; +} + +export interface FileDrainStoreOptions { + readonly filesystem: Filesystem; + /** `workers.json` under the gateway's data directory. */ + readonly path: string; + readonly logger?: Logger; +} + +/** + * A tiny JSON file: `{"drained": ["wrk_a", "wrk_b"]}`. + * + * Read errors never stop a gateway starting. A corrupt or unreadable file means the gateway + * forgets which workers were drained -- bad, and logged loudly -- but refusing to start would + * take a whole fleet's *routing* offline to protect a flag on some of it, which is the worse + * trade. Write errors are logged and swallowed for the same reason: the drain is already in + * effect in memory, and failing the operator's `worker.drain` call after it took effect would + * be a lie in the other direction. + */ +export class FileDrainStore implements DrainStore { + readonly #logger: Logger; + + constructor(private readonly options: FileDrainStoreOptions) { + this.#logger = options.logger ?? new NoopLogger(); + } + + async load(): Promise { + if (!(await this.options.filesystem.exists(this.options.path))) return []; + try { + const parsed: unknown = JSON.parse(await this.options.filesystem.readFile(this.options.path)); + const drained = (parsed as { readonly drained?: unknown } | null)?.drained; + if (!Array.isArray(drained)) throw new Error("`drained` is not an array"); + return drained.filter((id): id is string => typeof id === "string"); + } catch (error: unknown) { + this.#logger.error("Could not read the gateway's worker registry; drains are forgotten", { + path: this.options.path, + message: error instanceof Error ? error.message : String(error), + }); + return []; + } + } + + async save(drainedWorkerIds: readonly string[]): Promise { + try { + await this.options.filesystem.mkdirp(dirname(this.options.path)); + await this.options.filesystem.writeFileAtomic( + this.options.path, + `${JSON.stringify({ drained: [...drainedWorkerIds] }, null, 2)}\n`, + { mode: WORKERS_FILE_MODE }, + ); + } catch (error: unknown) { + this.#logger.error("Could not persist the gateway's worker registry", { + path: this.options.path, + message: error instanceof Error ? error.message : String(error), + }); + } + } +} + +/** For tests and for a gateway with nowhere to write: remembers nothing across a restart. */ +export class MemoryDrainStore implements DrainStore { + #drained: readonly string[] = []; + + async load(): Promise { + return this.#drained; + } + + async save(drainedWorkerIds: readonly string[]): Promise { + this.#drained = [...drainedWorkerIds]; + } +} diff --git a/src/gateway/fleet-ports.ts b/src/gateway/fleet-ports.ts new file mode 100644 index 000000000..d0f6d3f86 --- /dev/null +++ b/src/gateway/fleet-ports.ts @@ -0,0 +1,56 @@ +/** + * `src/gateway/fleet-ports.ts` -- the seam #118 (fleet queue, routing, forwarding) codes + * against, declared here so that PR can be written while this one's internals are still + * being revised. + * + * Nothing here has an implementation of its own: `WorkerLink`, `WorkerRegistry` and + * `GatewayService` satisfy these shapes, and the point is that #118 never imports those + * classes directly -- so a change *behind* one of these shapes (a call timeout, the + * drain-flag split, a truncation guard) is not a change #118 has to see. + * + * Declared before its consumer exists, so `fallow` is told that is deliberate -- the same + * annotation `DrainStore` already carries in `index.ts`. #118 owns these shapes once it + * lands: if one is wrong, that PR changes it rather than working around it. + */ +import type { SimlockAdminClient } from "../admin/index.js"; +import type { WorkerView } from "./worker-registry.js"; + +/** + * One worker, addressed for dispatch. `WorkerLink` satisfies this. + * + * `client()` is the gateway's own admin session on that worker -- the same one the link uses + * for its refresh round trips -- because every call #118 forwards (`lease.request`, + * `lease.renew`, `lease.release`, `lease.cancel`, `device.exec`, and `lease.list` for the + * reconnect rebuild) is one that session can already make. It returns `undefined` before + * `start()` has completed or after `close()`. #118 may narrow this to purpose-built methods + * if the wider shape proves too permissive for `boundary.test.ts`. + * + * `reachable` is false once the uplink is closing or closed. Answering a forwarded call for + * an unreachable worker is #119's `WORKER_UNREACHABLE`, not this PR's concern. + */ +export interface WorkerDispatchTarget { + readonly workerId: string; + readonly reachable: boolean; + client(): SimlockAdminClient | undefined; +} + +/** Resolves a worker id to its live link. `GatewayService` satisfies this. */ +// fallow-ignore-next-line unused-type -- #118's seam; declared before its consumer exists. +export interface WorkerDirectory { + target(workerId: string): WorkerDispatchTarget | undefined; +} + +/** + * The fleet's views, plus the signal that one changed. `WorkerRegistry` satisfies this. + * + * `onViewsChanged` is what makes ADR §11's "dispatch runs whenever the queue or any worker + * view changes" implementable without #118 reaching into the registry's internals or polling + * it. Listeners are called *after* the change is committed (and after the corresponding event + * is emitted), per `events.md`'s post-commit rule; the returned function unsubscribes. + */ +// fallow-ignore-next-line unused-type -- #118's seam; declared before its consumer exists. +export interface FleetViews { + views(): readonly WorkerView[]; + view(workerId: string): WorkerView | undefined; + onViewsChanged(listener: () => void): () => void; +} diff --git a/src/gateway/index.ts b/src/gateway/index.ts new file mode 100644 index 000000000..0ae9c86a8 --- /dev/null +++ b/src/gateway/index.ts @@ -0,0 +1,27 @@ +/** + * `src/gateway` -- the second implementation of the daemon contract (ADR 0005 §32), for a + * daemon that owns no devices and fronts the workers connected to it. + * + * Boundaries (§33, enforced by `boundary.test.ts`): nothing here imports `src/drivers`, and + * from `src/core` nothing at all in this PR -- no registry, no capacity, no lifecycle. The only + * daemon-side import is `daemon/dispatch.js`, the transport-facing dispatch contract, which is + * itself core-free. + * + * The barrel is what the daemon entrypoint assembles a gateway out of, not a mirror of every + * module here: `WorkerRegistry`, `WorkerLink` and the aggregation functions are wired together + * *by* `GatewayService` and `GatewayDispatcher`, so nothing outside builds one directly, and + * their own tests import their modules. + */ +export { FileDrainStore } from "./drain-store.js"; +// fallow-ignore-next-line unused-type -- public port shape for anyone supplying their own store. +export type { DrainStore } from "./drain-store.js"; +export { GatewayDispatcher } from "./dispatcher.js"; +// fallow-ignore-next-line unused-type -- public option shape for anyone composing a gateway; `main.ts` builds one inline. +export type { GatewayTokenStore } from "./dispatcher.js"; +export { GatewayService, type GatewayServiceOptions } from "./service.js"; +// fallow-ignore-next-line unused-type -- #118's seam; declared before its consumer exists. +export type { FleetViews } from "./fleet-ports.js"; +// fallow-ignore-next-line unused-type -- #118's seam; declared before its consumer exists. +export type { WorkerDirectory } from "./fleet-ports.js"; +// fallow-ignore-next-line unused-type -- #118's seam; declared before its consumer exists. +export type { WorkerDispatchTarget } from "./fleet-ports.js"; diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts new file mode 100644 index 000000000..ae447e6b1 --- /dev/null +++ b/src/gateway/service.test.ts @@ -0,0 +1,928 @@ +import { describe, expect, it, vi } from "vitest"; + +import { EventBus, type EventEnvelope } from "../bus/index.js"; +import { PROTOCOL_VERSION_RANGE } from "../contract/index.js"; +import { + FakeClock, + MemoryUplinkTransport, + type Logger, + type UplinkAuthOutcome, + type UplinkAuthResult, +} from "../ports/index.js"; +import { MemoryDrainStore } from "./drain-store.js"; +import { GatewayService, REJECTION_COALESCE_WINDOW_MS } from "./service.js"; +import { + catalogFixture, + deviceFixture, + leaseFixture, + protocolMismatchError, + ScriptedWorkerClient, + statusFixture, +} from "./test-support.js"; +import { MAX_CONSECUTIVE_REFRESH_TIMEOUTS, WORKER_CALL_TIMEOUT_MS } from "./worker-link.js"; + +const RETENTION_MS = 24 * 60 * 60_000; +const REFRESH_MS = 30_000; +/** Matches `core/config.ts`'s own default (ADR 0005 §15's own cap). */ +const DEFAULT_LEASE_MAX_TTL_MS = 4 * 60 * 60_000; + +/** H4: records every line at `warn` and `error` (the levels a link's own failure paths use), so + * a test can assert what a failure was actually logged *as* -- not just that something failed. */ +class RecordingLogger implements Logger { + readonly warnings: Array<{ message: string; fields?: Record }> = []; + + debug(): void {} + info(): void {} + warn(message: string, fields?: Record): void { + this.warnings.push(fields === undefined ? { message } : { fields, message }); + } + error(): void {} + child(): Logger { + return this; + } +} + +function fleet( + options: { + readonly authenticate?: ( + credential: string | undefined, + ) => UplinkAuthOutcome | UplinkAuthResult; + readonly leaseMaxTtlMs?: number; + readonly logger?: Logger; + readonly refreshIntervalMs?: number; + } = {}, +) { + const clock = new FakeClock(1_000); + const eventBus = new EventBus(clock); + const events: EventEnvelope[] = []; + eventBus.subscribeAll((envelope) => events.push(envelope)); + const transport = new MemoryUplinkTransport(); + /** The scripted worker each uplink resolves to, keyed by the principal-free order they join. */ + const clients: ScriptedWorkerClient[] = []; + // C3: set to make the *next* `connect()` -- the `hello` round trip itself -- never resolve, + // the way a peer that completes the WebSocket upgrade and then falls silent would. + const connectState = { hangNext: false }; + const service = new GatewayService({ + authenticate: async (credential) => options.authenticate?.(credential) ?? "accept", + clock, + connect: async () => { + if (connectState.hangNext) { + connectState.hangNext = false; + return new Promise(() => {}); + } + const client = clients.at(-1); + if (client === undefined) throw new Error("no scripted worker was queued for this uplink"); + return client.asClient(); + }, + drainStore: new MemoryDrainStore(), + eventBus, + leaseMaxTtlMs: options.leaseMaxTtlMs ?? DEFAULT_LEASE_MAX_TTL_MS, + ...(options.logger === undefined ? {} : { logger: options.logger }), + principal: "gw:instance-1", + refreshIntervalMs: options.refreshIntervalMs ?? REFRESH_MS, + retentionMs: RETENTION_MS, + uplinks: transport, + }); + return { + clients, + clock, + events, + service, + transport, + /** Queues the worker the next uplink resolves to, then dials it. `token` defaults to the + * fixed secret every other test relies on; C-2's test overrides it per worker so a custom + * `authenticate` can hand back a distinct `tokenId` for each. */ + join: async ( + workerId: string, + client: ScriptedWorkerClient, + label?: string, + token = "join-secret", + ) => { + clients.push(client); + return transport.connect({ + token, + url: "ws://gateway.test", + workerId, + ...(label === undefined ? {} : { label }), + }); + }, + /** Dials an uplink whose `hello` never answers -- no `ScriptedWorkerClient` is ever built, + * since C3's whole point is that the handshake itself must not be able to hang forever. */ + joinSilent: async (workerId: string, label?: string) => { + connectState.hangNext = true; + return transport.connect({ + token: "join-secret", + url: "ws://gateway.test", + workerId, + ...(label === undefined ? {} : { label }), + }); + }, + }; +} + +function eventNames(events: readonly EventEnvelope[]): string[] { + return events.map((event) => event.event); +} + +describe("GatewayService", () => { + it("builds a view from the four calls ADR 0005 §7 prescribes", async () => { + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + worker.status = statusFixture({ leases: [leaseFixture("lease_1", "dev_1")], queueDepth: 1 }); + worker.devices = [deviceFixture("dev_1", "leased")]; + worker.catalog = catalogFixture([ + { models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }, + ]); + + await harness.join("wrk_1", worker, "mac-mini-1"); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.capacity).toBeDefined()); + + expect(worker.calls).toContain("status.get"); + expect(worker.calls).toContain("list.get:devices"); + expect(worker.calls).toContain("catalog.get"); + expect(worker.calls).toContain("events.subscribe"); + expect(harness.service.workers.view("wrk_1")).toMatchObject({ + catalog: [{ models: ["iPhone 17"] }], + connection: "connected", + devices: [{ id: "dev_1" }], + downloads: { policy: "on-request" }, + id: "wrk_1", + label: "mac-mini-1", + leases: [{ id: "lease_1" }], + queueDepth: 1, + version: "0.3.0", + }); + expect(eventNames(harness.events)).toContain("worker.connected"); + + 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(); + const worker = new ScriptedWorkerClient(); + worker.devices = [ + { + ...deviceFixture("dev_1"), + createdAt: 1, + driverData: { secret: "a driver's private blob" }, + driverDeviceId: "UDID-1", + }, + ]; + + await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.devices).toHaveLength(1)); + + const device = harness.service.workers.view("wrk_1")?.devices[0]; + expect(device).toMatchObject({ id: "dev_1", state: "ready" }); + expect(device).not.toHaveProperty("driverData"); + expect(device).not.toHaveProperty("driverDeviceId"); + + await harness.service.stop(); + }); + + it("republishes a worker's events with its workerId, into its own ring buffer", async () => { + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(worker.subscribed).toBe(true)); + + worker.pushEvent({ + event: "lease.granted", + module: "lease-engine", + payload: { deviceId: "dev_1", leaseId: "lease_1", requester: "agent-1" }, + }); + + const republished = harness.events.find((event) => event.event === "lease.granted"); + expect(republished).toMatchObject({ + // The name and the emitting module travel unchanged -- the fact happened in that + // worker's lease engine, and `workerId` is what says which machine. + module: "lease-engine", + payload: { deviceId: "dev_1", leaseId: "lease_1", workerId: "wrk_1" }, + }); + + await harness.service.stop(); + }); + + // Hardening: a worker's event name is taken on faith from its own `events.subscribe` push -- + // `workerId` is merged in last so it cannot be spoofed, but nothing about the protocol proves + // the *name* is genuinely the worker's own. Without a guard, a worker (or anything speaking + // its admin protocol) could forge one of the six subjects `docs/EVENTS.md` calls "the + // gateway's own" -- e.g. `worker.drain-ended` -- straight into the operator's audit trail. + it("refuses to republish a worker's event under a name reserved for the gateway itself", async () => { + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(worker.subscribed).toBe(true)); + + worker.pushEvent({ + event: "worker.drain-ended", + module: "gateway", + payload: { workerId: "wrk_forged", label: "not-this-worker" }, + }); + // A genuine event from the same worker still goes through -- the guard is on the six names, + // not on this link entirely. + worker.pushEvent({ + event: "lease.granted", + module: "lease-engine", + payload: { deviceId: "dev_1", leaseId: "lease_1", requester: "agent-1" }, + }); + await vi.waitFor(() => + expect(harness.events.some((event) => event.event === "lease.granted")).toBe(true), + ); + + const forged = harness.events.filter((event) => event.event === "worker.drain-ended"); + // Never forwarded, and never with the forged `workerId` a real gateway-authored + // `worker.drain-ended` for a *different* worker would otherwise be indistinguishable from. + expect(forged).toEqual([]); + + await harness.service.stop(); + }); + + it("refreshes the view on a worker event that changes capacity or leases", async () => { + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(worker.subscribed).toBe(true)); + const callsBefore = worker.calls.length; + worker.status = statusFixture({ leases: [leaseFixture("lease_9", "dev_9")] }); + + worker.pushEvent({ event: "lease.granted" }); + + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.leases).toEqual([ + expect.objectContaining({ id: "lease_9" }), + ]), + ); + expect(worker.calls.length).toBeGreaterThan(callsBefore); + + await harness.service.stop(); + }); + + it("does not re-read the fleet for an event that changes neither", async () => { + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(worker.subscribed).toBe(true)); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.capacity).toBeDefined()); + const callsBefore = worker.calls.length; + + worker.pushEvent({ event: "doctor.reconciled" }); + // Still republished -- every worker fact reaches the gateway's buffer -- just not a reason + // to re-read anything. + await vi.waitFor(() => expect(eventNames(harness.events)).toContain("doctor.reconciled")); + + expect(worker.calls).toHaveLength(callsBefore); + + await harness.service.stop(); + }); + + it("refreshes every view on the periodic tick, catalog included", async () => { + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.capacity).toBeDefined()); + worker.catalog = catalogFixture([ + { models: ["iPhone 17", "iPad Pro"], platform: "ios", runtimes: ["26.0"] }, + ]); + + harness.clock.advance(REFRESH_MS); + + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.catalog[0]?.models).toEqual([ + "iPhone 17", + "iPad Pro", + ]), + ); + + await harness.service.stop(); + }); + + describe("warning on a worker's lower lease.maxTtlMs (ADR 0005 §15)", () => { + it("warns once the joining worker's own config.get reports a lower cap", async () => { + const logger = new RecordingLogger(); + const harness = fleet({ leaseMaxTtlMs: 3_600_000, logger }); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + worker.leaseMaxTtlMs = 1_800_000; + + await harness.join("wrk_1", worker, "mac-mini-1"); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.lease).toBeDefined()); + + const warning = logger.warnings.find((entry) => entry.fields?.workerId === "wrk_1"); + expect(warning?.fields).toMatchObject({ + gatewayMaxTtlMs: 3_600_000, + label: "mac-mini-1", + workerMaxTtlMs: 1_800_000, + }); + + await harness.service.stop(); + }); + + it("does not warn when the joining worker's own cap is at or above the gateway's", async () => { + const logger = new RecordingLogger(); + const harness = fleet({ leaseMaxTtlMs: 3_600_000, logger }); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + worker.leaseMaxTtlMs = 3_600_000; + + await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.lease).toBeDefined()); + + expect(logger.warnings.some((entry) => entry.fields?.workerId === "wrk_1")).toBe(false); + + await harness.service.stop(); + }); + + it("does not repeat the warning on the periodic tick's re-read of an unchanged cap", async () => { + const logger = new RecordingLogger(); + const harness = fleet({ leaseMaxTtlMs: 3_600_000, logger }); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + worker.leaseMaxTtlMs = 1_800_000; + + await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.lease).toBeDefined()); + const warningsAfterJoin = logger.warnings.filter( + (entry) => entry.fields?.workerId === "wrk_1", + ).length; + expect(warningsAfterJoin).toBe(1); + + // The periodic backstop tick re-reads config.get alongside the catalog + // (`#runTick` -> `link.refresh({ includeCatalog: true })`) -- the worker's cap has not + // moved, so this must not warn again. + const callsBefore = worker.calls.filter((call) => call === "config.get").length; + harness.clock.advance(REFRESH_MS); + await vi.waitFor(() => + expect(worker.calls.filter((call) => call === "config.get").length).toBeGreaterThan( + callsBefore, + ), + ); + + expect(logger.warnings.filter((entry) => entry.fields?.workerId === "wrk_1").length).toBe( + warningsAfterJoin, + ); + + await harness.service.stop(); + }); + }); + + it("marks a worker incompatible when hello finds no overlapping range, and asks it nothing else", async () => { + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + // What `connectSimlockAdmin`'s degraded client does after a failed negotiation: every call + // rejects with the captured error, carrying both ranges. + worker.failWith = protocolMismatchError({ min: 4, max: 4 }); + + await harness.join("wrk_1", worker); + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.connection).toBe("incompatible"), + ); + + expect(harness.service.workers.view("wrk_1")).toMatchObject({ + protocol: { gateway: PROTOCOL_VERSION_RANGE, worker: { min: 4, max: 4 } }, + }); + expect(worker.calls).toEqual(["status.get"]); + expect(worker.subscribed).toBe(false); + // ADR 0005 §31: that uplink authenticated, so it is not a `worker.rejected` -- and there + // is no `worker.connected` either, because nothing usable connected. + expect(eventNames(harness.events)).not.toContain("worker.rejected"); + expect(eventNames(harness.events)).not.toContain("worker.connected"); + + await harness.service.stop(); + }); + + it("flips a view to disconnected the moment its uplink closes -- no polling", async () => { + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + const workerEnd = await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.capacity).toBeDefined()); + + await workerEnd.close(); + + // Not on the next tick: the uplink is the reachability signal (ADR 0005 §6). + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.connection).toBe("disconnected"), + ); + expect(eventNames(harness.events)).toContain("worker.disconnected"); + + await harness.service.stop(); + }); + + // D1: `WorkerRegistry` is keyed by worker id, not by link, and a stale link's own close used + // to call `registry.disconnected` with no check at all -- so a socket the OS had not yet + // reported dead could mark the *live* successor's view disconnected, permanently (`refresh()` + // never touches `connection`). Against the code before this fix, no test joined the same + // worker id twice against a live service; this is that test. + it("does not let a stale link's late close mark a reconnected worker disconnected (D1)", async () => { + const harness = fleet(); + await harness.service.start(); + + const clientA = new ScriptedWorkerClient("admin", "0.1.0"); + const workerEndA = await harness.join("wrk_1", clientA); + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.connection).toBe("connected"), + ); + + // A's own close, once the reconnect below triggers it, must never actually complete during + // this test: a hung `events.unsubscribe` (D2) is exactly what stretches a stale link's close + // from microseconds to minutes in the wild, and here it lets the test control precisely + // when A's connection actually goes away. + clientA.hangUnsubscribe = true; + + // The same worker id redials with a new connection -- a restart, or a new TCP path after a + // NAT rebind. The service replaces the link; A's old one is asked to close but (per above) + // never gets there. + const clientB = new ScriptedWorkerClient("admin", "9.9.9"); + await harness.join("wrk_1", clientB); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.version).toBe("9.9.9")); + + // Only now does the OS finally report the stale socket dead. Closing the worker's own end + // fires the connection's real close event directly, bypassing A's still-stuck `close()` + // chain -- exactly what a genuinely half-open socket closing on its own would do. + await workerEndA.close(); + + expect(harness.service.workers.view("wrk_1")?.connection).toBe("connected"); + expect(harness.service.workers.view("wrk_1")?.version).toBe("9.9.9"); + expect(eventNames(harness.events)).not.toContain("worker.disconnected"); + + await harness.service.stop(); + }); + + // D2: `close()` awaited `events.unsubscribe` -- a real round trip -- with nothing bounding it. + // On a half-open socket that promise never settled, so `close()` never reached + // `connection.close()` and the link (and its WebSocket) leaked for the life of the process. + it("does not hang close() forever behind an events.unsubscribe that never answers (D2)", async () => { + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(worker.subscribed).toBe(true)); + worker.hangUnsubscribe = true; + + const stopped = harness.service.stop(); + // `stop()` is now blocked inside `link.close()`, awaiting the bounded wrapper around the + // hung unsubscribe -- wait for that timer to actually be armed before advancing past it. + await vi.waitFor(() => expect(harness.clock.pendingTimerCount).toBeGreaterThan(0)); + harness.clock.advance(WORKER_CALL_TIMEOUT_MS); + + await expect(stopped).resolves.toBeUndefined(); + expect(worker.closed).toBe(true); + }); + + // D3: a hung round trip inside `#rebuildView` used to latch `#refreshing` forever, since it + // was cleared only in a `finally` on a promise that never settled -- freezing the view while + // it still reported `connected`. + it("does not latch refreshing forever when a round trip hangs, and recovers past the timeout (D3)", async () => { + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.capacity).toBeDefined()); + + worker.hangingCalls.add("status.get"); + worker.status = statusFixture({ leases: [leaseFixture("lease_9", "dev_9")] }); + worker.pushEvent({ event: "lease.granted" }); + + // The refresh this event triggered is now stuck inside `#rebuildView`'s bounded wait. + await vi.waitFor(() => expect(harness.clock.pendingTimerCount).toBeGreaterThan(0)); + harness.clock.advance(WORKER_CALL_TIMEOUT_MS); + + // Once the hung refresh times out and un-latches `#refreshing`, a later event must still be + // able to trigger a real one -- proving the latch did not stay stuck. + worker.hangingCalls.delete("status.get"); + worker.pushEvent({ event: "lease.granted" }); + + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.leases).toEqual([ + expect.objectContaining({ id: "lease_9" }), + ]), + ); + + await harness.service.stop(); + }); + + // H2: the same asymmetry D1 fixed in `#handleClosed`, one write later -- `#rebuildView` wrote + // to `registry.refresh` after its own `await` with no re-check of `#closed` or + // `isCurrentLink`. A stale link's in-flight refresh, started before a reconnect replaced it, + // could land after its successor's fresher one and overwrite it with stale data for up to + // `WORKER_CALL_TIMEOUT_MS`. + it("does not let a stale link's late-arriving refresh overwrite its successor's fresher view (H2)", async () => { + const harness = fleet(); + await harness.service.start(); + + const clientA = new ScriptedWorkerClient("admin", "0.1.0"); + await harness.join("wrk_1", clientA); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.version).toBe("0.1.0")); + + // A's refresh, triggered by a worker event, is in flight but held open by hand -- long + // enough for a reconnect to fully replace this link before it ever answers. + let resolveStatus: ((status: ReturnType) => void) | undefined; + clientA.getStatus = () => + new Promise((resolve) => { + resolveStatus = resolve; + }); + clientA.pushEvent({ event: "lease.granted" }); + await vi.waitFor(() => expect(resolveStatus).toBeDefined()); + + // The same worker id redials with a new connection -- service.ts replaces A's link with B's, + // which builds its own, current view. + const clientB = new ScriptedWorkerClient("admin", "9.9.9"); + await harness.join("wrk_1", clientB); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.version).toBe("9.9.9")); + + // Only now does A's stale round trip finally answer -- exactly what a slow or half-open path + // answering late would do, well after B has already built the current view. + resolveStatus?.(statusFixture()); + // A few real event-loop turns for A's now-resolved promise chain to run to completion (or, + // with the fix, to stop itself before writing) -- nothing here is clock-scheduled, so there + // is no fake-clock timer to advance instead. + await new Promise((resolve) => setTimeout(resolve, 20)); + + expect(harness.service.workers.view("wrk_1")?.version).toBe("9.9.9"); + + await harness.service.stop(); + }); + + // H4: a timed-out `events.subscribe` used to be logged exactly like a rejection ("Worker + // refused an event subscription"), asserting something this code cannot know -- the worker may + // never have answered at all, or may have subscribed successfully with the reply just arriving + // too late to matter. The two are worth telling apart in a log an operator reads. + it("logs a timed-out event subscription as a timeout, not a refusal (H4)", async () => { + const logger = new RecordingLogger(); + const harness = fleet({ logger }); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + // Never resolves, unlike a real rejection -- the exact shape of a subscribe call that just + // never gets an answer within `WORKER_CALL_TIMEOUT_MS`. Tracked by hand rather than via + // `pendingTimerCount` alone: the service's own periodic tick timer is already pending from + // `service.start()`, so that check alone cannot tell "the subscribe call's own timeout timer + // is now armed" apart from "some timer, possibly the unrelated tick, exists". + let subscribeCalled = false; + worker.subscribeEvents = (): Promise => { + subscribeCalled = true; + return new Promise(() => {}); + }; + + await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(subscribeCalled).toBe(true)); + harness.clock.advance(WORKER_CALL_TIMEOUT_MS); + + await vi.waitFor(() => + expect(logger.warnings.some((entry) => entry.message.includes("did not answer"))).toBe(true), + ); + expect(logger.warnings.some((entry) => entry.message.includes("refused"))).toBe(false); + + await harness.service.stop(); + }); + + // P1: a refresh timeout used to be swallowed into a debug log with nothing acting on it, so a + // half-open uplink (NAT rebind, cable pull, kernel panic -- no FIN) had `connection` report + // `connected` forever with a `lastSeenAt` that never moved again. One timeout recovering on + // the very next attempt (D3, above) must still not disconnect a worker -- that is a real, slow + // response, not a dead link -- but the same failure MAX_CONSECUTIVE_REFRESH_TIMEOUTS times in a + // row, with nothing in between, must make the gateway give up and close the uplink. + it("closes the uplink once refreshes keep timing out, so a half-open worker stops reporting connected (P1)", async () => { + expect(MAX_CONSECUTIVE_REFRESH_TIMEOUTS).toBeGreaterThan(1); + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.capacity).toBeDefined()); + + // Never un-hung, unlike D3's test: this is the half-open case, not a briefly slow one. + worker.hangingCalls.add("status.get"); + + for (let attempt = 1; attempt < MAX_CONSECUTIVE_REFRESH_TIMEOUTS; attempt++) { + harness.clock.advance(REFRESH_MS); + await vi.waitFor(() => expect(harness.clock.pendingTimerCount).toBeGreaterThan(0)); + harness.clock.advance(WORKER_CALL_TIMEOUT_MS); + // Wait for the *next* tick to actually be armed, not just for the (already, trivially + // true) `connected` check to pass -- that value never changes on a timeout, so checking + // it alone would resolve before the tick's own promise chain (refresh's catch, then + // `pruneExpired`, then rescheduling) has actually finished, and the next iteration's + // `advance(REFRESH_MS)` would fast-forward the clock past a timer that has not been + // registered yet -- silently skipping a whole tick instead of exercising it. + await vi.waitFor(() => expect(harness.clock.pendingTimerCount).toBeGreaterThan(0)); + // Below the threshold, the view must still say `connected` -- exactly D3's guarantee, + // repeated for every attempt short of the last one. + expect(harness.service.workers.view("wrk_1")?.connection).toBe("connected"); + } + + // The attempt that crosses the threshold. + harness.clock.advance(REFRESH_MS); + await vi.waitFor(() => expect(harness.clock.pendingTimerCount).toBeGreaterThan(0)); + harness.clock.advance(WORKER_CALL_TIMEOUT_MS); + + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.connection).toBe("disconnected"), + ); + expect(eventNames(harness.events)).toContain("worker.disconnected"); + + await harness.service.stop(); + }); + + // C-1: P1's counter used to be driven by the whole bundled refresh timing out, which conflated + // a dead transport with a merely busy dispatcher -- on a worker mid-`converge`, `runDispatch` + // parks every call except `status.get` behind the startup-readiness gate, so `list.get` can + // legitimately hang for tens of seconds while the socket is completely healthy. Reproduces the + // reviewer's repro: `status.get` keeps answering, `list.get` never does, for well more than + // `MAX_CONSECUTIVE_REFRESH_TIMEOUTS` refresh cycles in a row. A gateway that still infers + // transport death from this would flip the link to `disconnected` long before this loop ends. + it("does not close the link when status.get keeps answering but the dispatcher is busy (C-1)", async () => { + // A refreshIntervalMs far outside this test's clock advances: `#runTick` only reschedules + // its own timer once a refresh settles (`service.ts`'s `.finally(() => this.#scheduleTick())`), + // so on a link whose refresh keeps timing out the tick's real cadence drifts to roughly + // `refreshIntervalMs + WORKER_CALL_TIMEOUT_MS` per cycle -- exercising this via event-driven + // refreshes instead (as D3 and H2 above do) keeps the periodic tick out of the picture + // entirely, rather than fighting its drift with hand-tuned clock advances. + const harness = fleet({ refreshIntervalMs: 10_000_000 }); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.capacity).toBeDefined()); + + // Unlike P1's test (which hangs `status.get` itself), the worker answers `status.get` on + // every single call -- only the readiness-gated `list.get` never returns, exactly what a + // worker stuck in a long `converge` looks like from the gateway's side. + worker.hangingCalls.add("list.get:devices"); + + for (let attempt = 1; attempt <= MAX_CONSECUTIVE_REFRESH_TIMEOUTS + 2; attempt++) { + const listCallsBefore = worker.calls.filter((call) => call === "list.get:devices").length; + // A worker event, not the tick, triggers each refresh here -- `#onWorkerEvent` calls + // `refresh()` directly, with none of the tick's own scheduling drift. + worker.pushEvent({ event: "lease.granted" }); + // Waits for `list.get` to have actually been called -- proof `status.get`'s real promise + // was given a genuine chance to settle and `#rebuildView` moved on to the hung batch. + // Waiting on `pendingTimerCount` instead would be a false positive: `status.get`'s own + // bounded wait registers a timer *synchronously*, before its real response has had any + // chance to arrive, so a bare "a timer exists" check can pass and race the fake clock's + // `advance` below against `status.get`'s still-pending real resolution -- timing out the + // liveness call itself instead of the batch behind it, which is exactly the distinction + // this fix exists to preserve. + await vi.waitFor(() => + expect(worker.calls.filter((call) => call === "list.get:devices").length).toBeGreaterThan( + listCallsBefore, + ), + ); + harness.clock.advance(WORKER_CALL_TIMEOUT_MS); + // Real microtask turns for the timeout rejection to propagate through `#rebuildView` and + // `refresh()`'s catch/finally -- nothing here is clock-scheduled once the timer fires. + await new Promise((resolve) => setTimeout(resolve, 20)); + // `status.get` answered this round, so liveness holds no matter how many cycles the + // dispatcher stays busy -- unlike P1's test, this must stay true past the threshold. + expect(harness.service.workers.view("wrk_1")?.connection).toBe("connected"); + } + expect(eventNames(harness.events)).not.toContain("worker.disconnected"); + + await harness.service.stop(); + }); + + // C-2, ADR 0005 §8 ("revoking closes the uplink"): a join token was checked once, at upgrade, + // and nothing ever re-verified a live link -- so revoking a worker's token used to have no + // observable effect on an already-open uplink at all. `closeLinksForToken` is what + // `GatewayDispatcher#tokenRevoke` calls after a successful revoke; this exercises it end to + // end against real `WorkerLink`s, matched by the exact token each authenticated with, so a + // shared or reused credential (however unlikely) cannot silently take out an unrelated worker. + it("closes exactly the link a token authorized, and leaves every other link alone (C-2)", async () => { + const harness = fleet({ + // Mirrors `main.ts`'s real `authenticate`: `accept` names the token id that authorized + // it, which is the whole plumbing this fix adds. + authenticate: (credential) => + credential === undefined + ? "unauthenticated" + : { outcome: "accept" as const, tokenId: credential }, + }); + await harness.service.start(); + + const workerA = new ScriptedWorkerClient(); + await harness.join("wrk_a", workerA, undefined, "tok_a"); + const workerB = new ScriptedWorkerClient(); + await harness.join("wrk_b", workerB, undefined, "tok_b"); + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_a")?.connection).toBe("connected"), + ); + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_b")?.connection).toBe("connected"), + ); + + await harness.service.closeLinksForToken("tok_a"); + + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_a")?.connection).toBe("disconnected"), + ); + // B authenticated with a different token entirely -- revoking A's must not touch it. + expect(harness.service.workers.view("wrk_b")?.connection).toBe("connected"); + expect(eventNames(harness.events)).toEqual( + expect.arrayContaining(["worker.connected", "worker.connected", "worker.disconnected"]), + ); + + await harness.service.stop(); + }); + + // C3: `hello` -- inside `connect()`, the first round trip `start()` makes -- had no timeout + // at all, unlike every call after it. A peer that completes the WebSocket upgrade with a + // valid join token and then never answers `hello` (a half-open TCP right after upgrade, or a + // deliberately silent client) used to hang `start()` forever: the link stayed in `#links` + // (registered before `start()` even runs), holding an open socket and no view, invisible in + // `simlock worker list` while consuming a slot -- D2's exact failure mode, one call earlier. + it("does not hang the handshake forever when hello itself never answers (C3)", async () => { + const harness = fleet(); + await harness.service.start(); + + const workerEnd = await harness.joinSilent("wrk_1", "mac-mini-1"); + await vi.waitFor(() => expect(harness.clock.pendingTimerCount).toBeGreaterThan(0)); + harness.clock.advance(WORKER_CALL_TIMEOUT_MS); + + // The decisive check: a timed-out hello must make the link actually give up and close its + // end of the socket -- closing either end of an in-memory pair closes both, so this is only + // true once the gateway's side has been closed. Against the unbounded `connect()` this + // never happens: nothing ever times out, so nothing ever closes, and this assertion is what + // tells the two apart (a looser "no view was built" check passes either way, since a + // permanently-hung connect() also never builds one). + await vi.waitFor(() => expect(workerEnd.closed).toBe(true)); + + // Timing out must not fabricate a view for a worker the gateway never actually spoke to. + expect(eventNames(harness.events)).not.toContain("worker.connected"); + expect(harness.service.workers.view("wrk_1")).toBeUndefined(); + + // And the slot must actually be freed: the same worker id reconnecting for real (a client + // that does answer) must build a normal view rather than being shut out by a link that + // leaked past its timeout. + const worker = new ScriptedWorkerClient(); + await harness.join("wrk_1", worker); + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.connection).toBe("connected"), + ); + + await harness.service.stop(); + }); + + it("sweeps a retired view on the tick, once retention has passed", async () => { + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + const workerEnd = await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.capacity).toBeDefined()); + await workerEnd.close(); + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.connection).toBe("disconnected"), + ); + + harness.clock.advance(RETENTION_MS + REFRESH_MS); + + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")).toBeUndefined()); + expect(eventNames(harness.events)).toContain("worker.removed"); + + await harness.service.stop(); + }); + + // The two refusals reach the event stream apart, because they point at different fixes: + // the join token itself, or the role it was minted with (ADR 0005 §4). + it.each(["unauthenticated", "forbidden"] as const)( + "reports a %s uplink it turned away, without inventing a worker for it", + async (reason) => { + const harness = fleet({ authenticate: () => reason }); + await harness.service.start(); + + await expect( + harness.join("wrk_1", new ScriptedWorkerClient(), "mac-mini-1"), + ).rejects.toMatchObject({ + code: "rejected", + }); + + expect(harness.service.workers.views()).toEqual([]); + // M3: `workerId`/`label` are whatever the dial *claimed* in its headers -- never verified + // (a refused peer proves no identity), but still worth an operator's while, and something + // this event used to always report as `undefined` regardless of what the dial sent. + expect(harness.events.at(-1)).toMatchObject({ + event: "worker.rejected", + payload: { label: "mac-mini-1", reason, workerId: "wrk_1" }, + }); + + await harness.service.stop(); + }, + ); + + // P-2: `GET /v1/uplink` needs no credential to reach `authenticate`, and before this fix every + // refusal emitted its own `worker.rejected` -- so a flood of refused dials (deliberate, or a + // misconfigured worker retrying fast) could fill the event bus's ring buffer, bounded by count + // and not bytes, with nothing but refusals, evicting everything else in it. No test dialed + // twice before this round. This asserts the coalescing itself: two dials with the same claimed + // id and reason inside one window produce exactly one event, and the first dial after the + // window closes reports the closed window's total as `count`. + it("coalesces a flood of identical refusals into one event per window, with a count (P-2)", async () => { + const harness = fleet({ authenticate: () => "unauthenticated" }); + await harness.service.start(); + const rejectedEvents = () => + harness.events.filter((event) => event.event === "worker.rejected"); + + await expect( + harness.join("wrk_flood", new ScriptedWorkerClient(), "mac-mini-1"), + ).rejects.toMatchObject({ code: "rejected" }); + await expect( + harness.join("wrk_flood", new ScriptedWorkerClient(), "mac-mini-1"), + ).rejects.toMatchObject({ code: "rejected" }); + + // Both refusals were real (each dial above genuinely rejected), but only the first became + // an event -- and it carries no `count` at all, the exact pre-P-2 payload shape. + expect(rejectedEvents()).toHaveLength(1); + expect(rejectedEvents()[0]?.payload).toMatchObject({ workerId: "wrk_flood" }); + expect(rejectedEvents()[0]?.payload).not.toHaveProperty("count"); + + // Past the window: the next matching refusal is reported on its own, carrying the tally the + // just-closed window absorbed (both dials above). + harness.clock.advance(REJECTION_COALESCE_WINDOW_MS); + await expect( + harness.join("wrk_flood", new ScriptedWorkerClient(), "mac-mini-1"), + ).rejects.toMatchObject({ code: "rejected" }); + + expect(rejectedEvents()).toHaveLength(2); + expect(rejectedEvents()[1]?.payload).toMatchObject({ count: 2, workerId: "wrk_flood" }); + + // A different claimed id is its own window from the start -- coalescing must not blend + // unrelated identities together into one gate. + await expect( + harness.join("wrk_other", new ScriptedWorkerClient(), "mac-mini-2"), + ).rejects.toMatchObject({ code: "rejected" }); + expect(rejectedEvents()).toHaveLength(3); + expect(rejectedEvents()[2]?.payload).not.toHaveProperty("count"); + + await harness.service.stop(); + }); + + it("closes the uplink when a worker does not grant the gateway admin", async () => { + const harness = fleet(); + await harness.service.start(); + // A worker older than #117, or one that resolved the session some other way: nothing the + // gateway asks would be answered, so there is no view worth keeping. + const worker = new ScriptedWorkerClient("agent"); + + const workerEnd = await harness.join("wrk_1", worker); + + await vi.waitFor(() => expect(worker.closed).toBe(true)); + expect(workerEnd.closed).toBe(true); + expect(harness.service.workers.views()).toEqual([]); + + await harness.service.stop(); + }); + + it("stops the tick and closes every link on stop", async () => { + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.capacity).toBeDefined()); + + await harness.service.stop(); + + expect(worker.closed).toBe(true); + const callsAfterStop = worker.calls.length; + harness.clock.advance(10 * REFRESH_MS); + expect(worker.calls).toHaveLength(callsAfterStop); + }); + + // `./fleet-ports.ts`'s WorkerDispatchTarget#client -- #118's seam. Both halves of the + // contract: undefined before start() has completed the handshake, and undefined again once + // the link has closed. + describe("target() / WorkerDispatchTarget (fleet-ports)", () => { + it("has no client before the handshake completes", async () => { + const harness = fleet(); + await harness.service.start(); + + await harness.joinSilent("wrk_1"); + const target = harness.service.target("wrk_1"); + + expect(target).toBeDefined(); + expect(target?.reachable).toBe(true); + expect(target?.client()).toBeUndefined(); + + await harness.service.stop(); + }); + + it("has no client once the link has closed", async () => { + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.capacity).toBeDefined()); + + const target = harness.service.target("wrk_1"); + expect(target?.client()).toBeDefined(); + expect(target?.reachable).toBe(true); + + await harness.service.stop(); + + expect(target?.reachable).toBe(false); + expect(target?.client()).toBeUndefined(); + }); + }); +}); diff --git a/src/gateway/service.ts b/src/gateway/service.ts new file mode 100644 index 000000000..a87c2a149 --- /dev/null +++ b/src/gateway/service.ts @@ -0,0 +1,277 @@ +/** + * The gateway's moving parts, wired together: the uplink listener, one `WorkerLink` per + * connected worker, the worker registry those links write into, and the slow periodic tick that + * backstops event-driven refreshes and sweeps expired views (ADR 0005 §6, §7). + * + * Everything here is lifecycle. What an operation *answers* lives in `GatewayDispatcher`, and + * what a view *is* lives in `WorkerRegistry`; this class only makes sure both are fed. + */ +import type { EventBus } from "../bus/index.js"; +import type { + AcceptedUplink, + Clock, + Logger, + TimerHandle, + UplinkAuthResult, + UplinkListener, + UplinkListenerFactory, +} from "../ports/index.js"; +import { NoopLogger, uplinkOutcome } from "../ports/index.js"; +import type { DrainStore } from "./drain-store.js"; +import { WorkerLink, type WorkerClientFactory } from "./worker-link.js"; +import { WorkerRegistry } from "./worker-registry.js"; + +/** + * How often the gateway refreshes every worker view and sweeps expired ones, absent an + * override. ADR 0005 §7 asks for "a slow periodic tick as a backstop" -- slow because the + * uplink's event stream is the real signal and this only catches what it missed (an event lost + * to a refresh that failed, a worker whose `events.subscribe` was refused). Thirty seconds is + * 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; + +/** + * P-2: how long a coalescing window for repeated `worker.rejected` refusals stays open. + * `GET /v1/uplink` needs no credential to reach `authenticate` (P3), so a loop of refused dials + * -- deliberate or a genuinely misconfigured worker retrying fast -- would otherwise emit one + * `worker.rejected` per attempt, and the event bus's ring buffer is bounded by count, not bytes: + * enough of them evicts every other fact an operator comes to `simlock events` for. One second + * is short enough that a legitimate operator watching `simlock events --follow` still sees a + * refusal essentially the moment it happens, and long enough to collapse a tight retry loop + * (a worker's backoff floor, per `docs/known-pitfalls.md`, is measured in seconds) to about one + * event per second regardless of how fast the dials themselves arrive. + */ +export const REJECTION_COALESCE_WINDOW_MS = 1_000; + +/** + * P-2: bounds `#recentRejections` itself. Coalescing keys on the claimed worker id, which is + * attacker-controlled (P3) -- without a cap, a flood that varies its claimed id every dial would + * trade one unbounded structure (the event bus's ring buffer) for another (this map) rather than + * actually fixing anything. Evicting the oldest window on overflow means a wide-enough flood + * degrades back to "one event per refusal" for the ids that get evicted, which is only ever as + * bad as this fix's baseline (pre-P-2) behavior -- never worse. + */ +const MAX_TRACKED_REJECTION_WINDOWS = 1_000; + +export interface GatewayServiceOptions { + readonly clock: Clock; + readonly eventBus: EventBus; + readonly uplinks: UplinkListenerFactory; + /** + * Verifies a join token presented at upgrade (ADR 0005 §4/§25): `accept` only for a token the + * gateway's own store holds with role `worker`; `forbidden` for a real token of another role; + * `unauthenticated` for anything else. Injected rather than taking a token store, so this + * module never learns what a token *is* -- except its id, which an `accept` may optionally + * carry (`UplinkAuthResult`) so `closeLinksForToken` (C-2) can later find the link it opened. + */ + readonly authenticate: (credential: string | undefined) => Promise; + /** `gateway.disconnectedRetentionMs` (§6). */ + readonly retentionMs: number; + /** This gateway's own `lease.maxTtlMs` (§15) -- threaded straight into the registry, which + * warns when a connected worker's own reported cap is lower. */ + readonly leaseMaxTtlMs: number; + /** Where drained worker ids survive a restart (Decision 3). */ + readonly drainStore?: DrainStore; + /** The principal the gateway announces to each worker at `hello`. */ + readonly principal: string; + readonly logger?: Logger; + readonly refreshIntervalMs?: number; + /** Injected in tests to script a worker without a real daemon behind the uplink. */ + readonly connect?: WorkerClientFactory; +} + +export class GatewayService { + readonly #registry: WorkerRegistry; + readonly #links = new Map(); + readonly #logger: Logger; + readonly #refreshIntervalMs: number; + #listener: UplinkListener | undefined; + #tick: TimerHandle | undefined; + #stopped = false; + /** P-2: open coalescing windows for `worker.rejected`, keyed by `${reason}:${claimed id}`. + * Insertion order is what makes the overflow eviction in `#recordRejection` an LRU-ish + * "drop the oldest key" rather than an arbitrary one -- `Map` preserves it. */ + readonly #recentRejections = new Map(); + + constructor(private readonly options: GatewayServiceOptions) { + this.#logger = options.logger ?? new NoopLogger(); + this.#refreshIntervalMs = options.refreshIntervalMs ?? DEFAULT_WORKER_REFRESH_INTERVAL_MS; + this.#registry = new WorkerRegistry({ + clock: options.clock, + eventBus: options.eventBus, + // ADR 0005 §14's own-lease prefix, reused for §6's retention hold (M2): `principal` is + // exactly `gw:`, the same shape requirement 27 stamps on + // every requester id this gateway forwards, just without the trailing `:`. + gatewayRequesterPrefix: `${options.principal}:`, + leaseMaxTtlMs: options.leaseMaxTtlMs, + logger: this.#logger, + retentionMs: options.retentionMs, + ...(options.drainStore === undefined ? {} : { drainStore: options.drainStore }), + }); + } + + /** The views every gateway handler reads. */ + get workers(): WorkerRegistry { + return this.#registry; + } + + /** `./fleet-ports.ts`'s `WorkerDirectory#target` -- #118's way to resolve a worker id to its + * live link without importing `WorkerLink` or reaching into `#links` itself. */ + target(workerId: string): WorkerLink | undefined { + return this.#links.get(workerId); + } + + /** + * C-2, ADR 0005 §8: "revoking closes the uplink". Closes every currently-open link that + * authenticated with join token `tokenId` -- ordinarily at most one, but a token is a + * credential, not a worker id, so nothing stops the same secret from having opened more than + * one uplink before it was revoked. `link.close()` runs the same teardown a worker-initiated + * disconnect does (`registry.disconnected`, `#links` eviction via `onClosed`), so a revoked + * worker is indistinguishable in the fleet's view and its event history from one that simply + * hung up. Links that never got a `tokenId` (every uplink opened before this fix's `main.ts` + * wiring, or a test `authenticate` that returns the bare outcome string) are never matched by + * a real token id, so this is a no-op for them rather than a false positive. + */ + async closeLinksForToken(tokenId: string): Promise { + const matches = [...this.#links.values()].filter((link) => link.tokenId === tokenId); + await Promise.all(matches.map((link) => link.close())); + } + + async start(): Promise { + // Before the listener, not after: a worker that reconnects in the first millisecond must + // find its drain state already restored, or it would be dispatched to once (#118) before + // the flag landed. + await this.#registry.load(); + this.#listener = await this.options.uplinks.listen({ + accept: (uplink) => this.#accept(uplink), + authenticate: async (credential, claimed) => { + const result = await this.options.authenticate(credential); + const outcome = uplinkOutcome(result); + // ADR 0005 §22's fleet audit trail includes the joins that failed: a revoked token + // retrying at its backoff cap is invisible on the gateway otherwise, and "why is that + // machine not in the fleet" is exactly the question an operator brings to + // `simlock events`. Which of the two refusals it was travels with the fact -- the + // event carries the same 401/403 distinction the upgrade answered with. `workerId` and + // `label` are only what the dial *claimed* in its headers, never verified -- a refused + // uplink proves no identity, but the claim is still worth an operator's while. + // P-2: coalesced rather than emitted one-per-dial -- see `#recordRejection`. + if (outcome !== "accept") this.#recordRejection(outcome, claimed.workerId, claimed.label); + return result; + }, + }); + this.#scheduleTick(); + } + + /** + * P-2: emits `worker.rejected` for the first refusal of a given (reason, claimed id) in a + * window and merely counts every one after it, until the window elapses -- rather than one + * event per dial, which an unauthenticated flood against `GET /v1/uplink` could otherwise use + * to pin the event bus's ring buffer full of refusals and evict everything else in it (P3). + * The next dial after the window closes carries the closed window's total as `count`, so an + * operator watching `simlock events` still learns *that* a flood happened and *how big* it + * was -- just not once per attempt. + */ + #recordRejection( + reason: "forbidden" | "unauthenticated", + workerId: string | undefined, + label: string | undefined, + ): void { + const key = `${reason}:${workerId ?? ""}`; + const now = this.options.clock.now(); + const existing = this.#recentRejections.get(key); + if (existing !== undefined && now - existing.windowStart < REJECTION_COALESCE_WINDOW_MS) { + existing.count += 1; + return; + } + // A new window: either this key has never been seen, or its last one has aged out. Either + // way, this dial itself is reported immediately -- `count` names how many total refusals + // (including this one) the just-closed window absorbed, so a lone refusal keeps the exact + // pre-P-2 payload shape (no `count` field at all) rather than gaining a redundant `count: 1`. + const previousTotal = existing?.count; + if (this.#recentRejections.size >= MAX_TRACKED_REJECTION_WINDOWS) { + // Oldest insertion first, per `Map`'s iteration order -- a flood that varies its claimed + // id every dial must not grow this map without bound either (see the constant's doc). + const oldestKey = this.#recentRejections.keys().next().value; + if (oldestKey !== undefined) this.#recentRejections.delete(oldestKey); + } + this.#recentRejections.set(key, { count: 1, windowStart: now }); + this.#registry.rejected(reason, workerId, label, previousTotal); + } + + async stop(): Promise { + if (this.#stopped) return; + this.#stopped = true; + if (this.#tick !== undefined) { + this.options.clock.cancel(this.#tick); + this.#tick = undefined; + } + await this.#listener?.close(); + this.#listener = undefined; + const links = [...this.#links.values()]; + this.#links.clear(); + await Promise.all(links.map((link) => link.close())); + } + + #accept(uplink: AcceptedUplink): void { + if (this.#stopped) { + void uplink.connection.close(); + return; + } + // A worker that reconnects while the gateway still holds its previous link (a half-open + // socket the OS has not reported dead) replaces it: the id is the worker's identity, and + // the newest uplink is the one that can actually be driven. The old link is closed rather + // than left to fight the new one over the same view. + const previous = this.#links.get(uplink.workerId); + if (previous !== undefined) { + this.#logger.info("Worker reconnected while an uplink was still open; replacing it", { + workerId: uplink.workerId, + }); + void previous.close(); + } + const link = new WorkerLink({ + clock: this.options.clock, + eventBus: this.options.eventBus, + // The same "is this still the current link" test as `onClosed` below, reused for D1: a + // stale link's late close (the OS finally reporting a half-open socket dead, well after a + // reconnect already replaced it) must not mark the registry's *current* entry + // disconnected. One predicate, read from the same map, keeps both guards from drifting + // apart. + isCurrentLink: () => this.#links.get(uplink.workerId) === link, + logger: this.#logger, + onClosed: (workerId) => { + // Only forget the link if it is still the current one: a replaced link's late close + // must not evict its successor. + if (this.#links.get(workerId) === link) this.#links.delete(workerId); + }, + principal: this.options.principal, + registry: this.#registry, + uplink, + ...(this.options.connect === undefined ? {} : { connect: this.options.connect }), + }); + this.#links.set(uplink.workerId, link); + void link.start(); + } + + /** + * One timer, rearmed after each run rather than a repeating interval, so a slow round of + * refreshes can never overlap itself. Failures inside a refresh are the link's to log; this + * loop only guarantees the next tick happens. + */ + #scheduleTick(): void { + if (this.#stopped) return; + this.#tick = this.options.clock.setTimer(this.#refreshIntervalMs, () => { + this.#tick = undefined; + void this.#runTick().finally(() => this.#scheduleTick()); + }); + } + + async #runTick(): Promise { + // Catalogs are re-read on the tick, not on every lease event: models and runtimes change + // when someone installs an SDK, which is exactly the kind of slow change a backstop is for. + await Promise.all( + [...this.#links.values()].map((link) => link.refresh({ includeCatalog: true })), + ); + await this.#registry.pruneExpired(); + } +} diff --git a/src/gateway/test-support.ts b/src/gateway/test-support.ts new file mode 100644 index 000000000..d5e01a460 --- /dev/null +++ b/src/gateway/test-support.ts @@ -0,0 +1,210 @@ +/** + * Doubles the gateway's own suites share: a scripted worker (the `SimlockAdminClient` a + * `WorkerLink` drives, with no daemon behind it) and the small fixtures every view needs. + * + * The scripted client is deliberately shaped like the real one -- it answers `status.get`, + * `list.get`, `catalog.get` and `events.subscribe`, and can be told to fail a call or push an + * event -- so a test drives the same code path a real worker would, minus the socket. + */ +import type { z } from "zod"; + +import type { SimlockAdminClient, StatusGetOutput } from "../admin/index.js"; +import { SimlockError } from "../admin/index.js"; +import { PROTOCOL_VERSION_RANGE } from "../contract/index.js"; +import type { OPERATIONS, platformCatalogSchema } from "../contract/index.js"; + +type CatalogOutput = z.infer<(typeof OPERATIONS)["catalog.get"]["output"]>; +type PlatformCatalog = z.infer; +type EventEnvelope = z.infer<(typeof OPERATIONS)["events.replay"]["output"]>[number]; + +const emptyPlatformCapacity = { + limit: 2, + maxRunning: 2, + overLimit: false, + reserved: 0, + running: 0, + used: 0, + warm: 0, +}; + +export function statusFixture(overrides: Partial = {}): StatusGetOutput { + return { + capacity: { + android: { ...emptyPlatformCapacity }, + global: { maxRunning: 4, overLimit: false, reserved: 0, running: 0, warm: 0 }, + ios: { ...emptyPlatformCapacity }, + }, + daemon: { health: "running", mode: "worker" }, + devices: [], + leases: [], + queueDepth: 0, + ...overrides, + }; +} + +export function leaseFixture(id: string, deviceId: string) { + return { + deviceId, + grantedAt: 1, + id, + lastRenewedAt: 1, + ownerId: "agent-1", + requesterId: "agent-1", + ttlDeadline: 900_001, + ttlMs: 900_000, + }; +} + +export function deviceFixture(id: string, state: "ready" | "leased" = "ready") { + return { + id, + spec: { model: "iPhone 17", osVersion: "26.0", platform: "ios" as const }, + state, + }; +} + +export function catalogFixture(entries: readonly PlatformCatalog[]): CatalogOutput { + return { platforms: [...entries] }; +} + +type DownloadPolicy = "never" | "on-request" | "always"; + +/** + * A `SimlockAdminClient` with only the methods a `WorkerLink` actually calls. Everything else + * rejects loudly rather than returning a plausible-looking empty value: if the link starts + * calling something new, the test that notices should be the one that says so. + */ +export class ScriptedWorkerClient { + status: StatusGetOutput = statusFixture(); + devices: unknown[] = []; + catalog: CatalogOutput = catalogFixture([]); + /** What `config.get` reports; the view carries it as a routing input (ADR 0005 §13). */ + downloadPolicy: DownloadPolicy = "on-request"; + /** What `config.get` reports for `lease.maxTtlMs` (ADR 0005 §15) -- the routing-adjacent + * counterpart to `downloadPolicy` above. Defaults comfortably above every gateway cap this + * suite's fixtures use, so a test that never sets it cannot accidentally trip the new warning; + * a test exercising §15 sets it explicitly. `config.get` always answers with a real + * `lease.maxTtlMs` when it answers at all (the field predates this change and is not + * optional on `Config`), so unlike `downloadPolicy` there is no "unset" state to script here + * -- the workerViewSchema field's own optionality is `config === undefined`, exercised at + * `WorkerRegistry`'s own level in `worker-registry.test.ts`, not through this fake. */ + leaseMaxTtlMs = 24 * 60 * 60_000; + readonly calls: string[] = []; + /** Set to reject every call with this error -- e.g. a protocol mismatch. */ + failWith: unknown; + closed = false; + /** + * Names of calls (`"status.get"`, `"list.get:devices"`, `"catalog.get"`, `"config.get"`) that + * should hang forever instead of answering -- for exercising `WorkerLink`'s own per-call + * timeout (D2/D3) rather than a rejection, which `SimlockWire` already handles fine. A call + * still lands in `calls` before it hangs, so a test can tell it was attempted. + */ + readonly hangingCalls = new Set(); + /** Makes the closure `subscribeEvents` returns hang forever instead of resolving -- the exact + * shape of D2's `events.unsubscribe` round trip that never answers. Read at call time, not + * captured when the closure is created, so a test can flip this after the worker is already + * connected and subscribed. */ + hangUnsubscribe = false; + #eventListener: ((push: { event: EventEnvelope }) => void) | undefined; + + constructor( + readonly role: "admin" | "agent" = "admin", + readonly daemonVersion = "0.3.0", + ) {} + + /** Delivers one event to the gateway exactly as a worker's `events.subscribe` push would. */ + pushEvent(envelope: Partial & { readonly event: string }): void { + this.#eventListener?.({ + event: { + module: "test", + payload: {}, + seq: 1, + timestamp: 1, + ...envelope, + } as EventEnvelope, + }); + } + + get subscribed(): boolean { + return this.#eventListener !== undefined; + } + + asClient(): SimlockAdminClient { + // The cast is the point of this double: a `WorkerLink` only ever touches the members below, + // and fabricating the other twenty would say less about what it depends on, not more. + return this as unknown as SimlockAdminClient; + } + + // fallow-ignore-next-line unused-class-member -- reached structurally through the `SimlockAdminClient` the cast in `asClient()` produces; the audit cannot follow a member access through that. + async getStatus(): Promise { + this.calls.push("status.get"); + if (this.hangingCalls.has("status.get")) return new Promise(() => {}); + this.#throwIfFailing(); + return this.status; + } + + // fallow-ignore-next-line unused-class-member -- reached structurally through the `SimlockAdminClient` the cast in `asClient()` produces; the audit cannot follow a member access through that. + async list(input: { readonly kind?: string }): Promise { + const name = `list.get:${input.kind ?? "devices"}`; + this.calls.push(name); + if (this.hangingCalls.has(name)) return new Promise(() => {}); + this.#throwIfFailing(); + return this.devices; + } + + // fallow-ignore-next-line unused-class-member -- reached structurally through the `SimlockAdminClient` the cast in `asClient()` produces; the audit cannot follow a member access through that. + async getCatalog(): Promise { + this.calls.push("catalog.get"); + if (this.hangingCalls.has("catalog.get")) return new Promise(() => {}); + this.#throwIfFailing(); + return this.catalog; + } + + // fallow-ignore-next-line unused-class-member -- reached structurally through the `SimlockAdminClient` the cast in `asClient()` produces; the audit cannot follow a member access through that. + async getConfig(): Promise<{ + readonly downloads: { readonly policy: DownloadPolicy }; + readonly lease: { readonly maxTtlMs: number }; + }> { + this.calls.push("config.get"); + if (this.hangingCalls.has("config.get")) return new Promise(() => {}); + this.#throwIfFailing(); + return { downloads: { policy: this.downloadPolicy }, lease: { maxTtlMs: this.leaseMaxTtlMs } }; + } + + // fallow-ignore-next-line unused-class-member -- reached structurally through the `SimlockAdminClient` the cast in `asClient()` produces; the audit cannot follow a member access through that. + async subscribeEvents( + listener: (push: { event: EventEnvelope }) => void, + ): Promise<() => Promise> { + this.calls.push("events.subscribe"); + this.#throwIfFailing(); + this.#eventListener = listener; + return async () => { + if (this.hangUnsubscribe) return new Promise(() => {}); + this.#eventListener = undefined; + }; + } + + // fallow-ignore-next-line unused-class-member -- reached structurally through the `SimlockAdminClient` the cast in `asClient()` produces; the audit cannot follow a member access through that. + async close(): Promise { + this.closed = true; + } + + #throwIfFailing(): void { + if (this.failWith !== undefined) throw this.failWith; + } +} + +/** The rejection `connectSimlockAdmin`'s degraded client throws for every call when `hello` + * found no overlapping protocol version (ADR 0003 §6) -- what marks a view `incompatible`. */ +export function protocolMismatchError( + worker: { readonly min: number; readonly max: number }, + gateway: { readonly min: number; readonly max: number } = PROTOCOL_VERSION_RANGE, + daemonVersion = "0.2.0", +): SimlockError<"PROTOCOL_VERSION_UNSUPPORTED"> { + return new SimlockError( + "PROTOCOL_VERSION_UNSUPPORTED", + "protocol", + "No overlapping protocol version", + { client: gateway, daemon: worker, daemonVersion }, + ); +} diff --git a/src/gateway/worker-link.ts b/src/gateway/worker-link.ts new file mode 100644 index 000000000..b214ab57a --- /dev/null +++ b/src/gateway/worker-link.ts @@ -0,0 +1,512 @@ +/** + * One worker's uplink, from the gateway's side (ADR 0005 §5, §7, §22, §31). + * + * Over the uplink the gateway is the protocol *client*: this class drives the worker's own + * dispatcher with the same typed admin client a supervisor process uses over a unix socket + * (`connectSimlockAdmin`), which is the whole reason the fleet needs no second API. What it + * does with that client is exactly what §7 prescribes -- `status.get`, `list.get`, + * `catalog.get` and `events.subscribe` on connect, a refresh on every worker event that can + * change capacity or leases, and a periodic refresh as a backstop -- plus §22's republishing of + * those events onto the gateway's own bus with `workerId` added. + * + * One call §7 does not name is here too: `config.get`, read once per session for the worker's + * `downloads.policy`. It is a routing input rather than decoration (§13: a request needing a + * download is only eligible on a worker whose policy allows one), it never changes without a + * worker restart -- which is a new session anyway -- and the uplink session is admin, so the + * gateway may read it. + */ +import { z } from "zod"; + +import type { EventBus, EventName } from "../bus/index.js"; +import { isSimlockError, statusDeviceSchema } 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 { WorkerRegistry } from "./worker-registry.js"; + +/** + * How long the gateway waits for one round trip to a worker before giving up on it. + * `SimlockWire` keeps no per-call timeout of its own (ADR 0003 leaves that to the caller), so a + * call on a half-open socket the OS has not yet reported dead can otherwise hang forever. Two + * findings from #117's first review round share this one root cause: a hung `events.unsubscribe` + * stalls `close()` behind an RPC that will never answer, which is what widens a stale link's + * window from microseconds to minutes before its `onClose` ever fires (the D1 reconnect bug); + * and a hung refresh round trip latches `#refreshing` forever, freezing a view that still claims + * to be `connected`. Ten seconds is far above any real round trip and far below the kind of gap + * that turns "briefly stale" into "silently wrong". + */ +export const WORKER_CALL_TIMEOUT_MS = 10_000; + +/** + * P1/C-1: how many consecutive *transport-liveness* failures are allowed before the gateway + * gives up on this link and closes it -- specifically, `status.get` itself timing out, not the + * batch of calls behind it. `runDispatch` (`dispatch.ts`) parks every operation except + * `status.get` behind the worker's startup-readiness gate, so on a worker mid-`converge` (a + * per-device shell-out plus capacity shutdowns, routinely tens of seconds) `list.get`, + * `catalog.get`, `config.get` and `events.subscribe` can all be genuinely, harmlessly slow while + * the transport itself is fine. `#rebuildView` awaits `status.get` on its own, ahead of the rest + * of the refresh, and resets `#consecutiveRefreshTimeouts` to zero the instant it answers -- so a + * worker that is merely busy converging never counts against this limit at all, no matter how + * long its startup gate stays shut. Only `status.get` itself failing to answer counts. + * + * One is not enough -- D3's single hung `status.get` recovering on its very next attempt is a + * real, common case (a worker briefly slow, not a half-open socket) and must not tear the link + * down for it. But nothing was acting on a *repeated* timeout either: a half-open uplink (NAT + * rebind, a cable pull, a kernel panic -- no FIN) has every `status.get` time out forever while + * `connection` keeps reporting `connected` with a `lastSeenAt` that never moves again. Two in a + * row means two consecutive refresh attempts each got no answer to `status.get` at all -- and + * since a refresh is triggered either by a worker event (immediately) or by the periodic tick + * backstop (`refreshIntervalMs`, 30s by default), the wall-clock gap between those two failures + * can be anywhere from milliseconds (events firing on an already-dead link) up to roughly two + * tick intervals, not a fixed "one minute" -- that figure assumed a single bundled timeout per + * tick, which is exactly the bundling this fix removes. + */ +export const MAX_CONSECUTIVE_REFRESH_TIMEOUTS = 2; + +class WorkerCallTimeoutError extends Error { + constructor(what: string) { + super(`Timed out waiting for the worker's ${what}`); + this.name = "WorkerCallTimeoutError"; + } +} + +/** How the gateway turns an accepted uplink into a driven session. Injected so a test can + * script a worker without a `DaemonServer` behind it. */ +export type WorkerClientFactory = ( + connection: IpcConnection, + principal: string, +) => Promise; + +export interface WorkerLinkOptions { + readonly uplink: AcceptedUplink; + readonly registry: WorkerRegistry; + readonly eventBus: EventBus; + readonly clock: Clock; + /** The principal the gateway announces at `hello`, namespaced by its own instance id, so a + * worker's logs attribute what the gateway did to the gateway (ADR 0005 §27's shape). */ + readonly principal: string; + readonly logger?: Logger; + readonly connect?: WorkerClientFactory; + /** Called once, when this uplink closes for any reason. */ + readonly onClosed?: (workerId: string) => void; + /** + * Whether the owning `GatewayService` still considers this link the current one for its + * worker id. A worker's uplink is keyed by worker id, not by link, so a reconnect that + * replaces this link with a newer one leaves this one to close on its own time -- a stale + * TCP path can take minutes to be reported dead (D1). Without this guard that late close + * would call `registry.disconnected` on a worker id a newer, live link now owns, and nothing + * would ever correct it: `refresh()` never touches `connection`. Defaults to "yes" so a + * caller that never replaces links (every test that does not exercise a reconnect) need not + * supply one. + */ + 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); + +export class WorkerLink { + readonly workerId: string; + readonly #logger: Logger; + #client: SimlockAdminClient | undefined; + #unsubscribeEvents: (() => Promise) | undefined; + #closed = false; + #refreshing = false; + #refreshQueued = false; + /** P1/C-1: consecutive `status.get` timeouts, reset to 0 the instant any `status.get` answers + * (inside `#rebuildView`) rather than only once a whole refresh completes -- see + * `MAX_CONSECUTIVE_REFRESH_TIMEOUTS`'s comment for why liveness is judged on that one call. */ + #consecutiveRefreshTimeouts = 0; + + constructor(private readonly options: WorkerLinkOptions) { + this.workerId = options.uplink.workerId; + this.#logger = options.logger ?? new NoopLogger(); + } + + /** `./fleet-ports.ts`'s `WorkerDispatchTarget#reachable` -- false once this link is closing or + * closed (`close()`/`#handleClosed` both set `#closed` before anything else). */ + // fallow-ignore-next-line unused-class-member -- #118's seam (WorkerDispatchTarget); nothing in this PR calls it yet. + get reachable(): boolean { + return !this.#closed; + } + + /** C-2: the join token record id that authenticated this uplink at upgrade, or `undefined` + * when `authenticate` returned the bare outcome string rather than naming one. Read by + * `GatewayService#closeLinksForToken` so a revoked token can find every link it opened. */ + get tokenId(): string | undefined { + return this.options.uplink.tokenId; + } + + /** `./fleet-ports.ts`'s `WorkerDispatchTarget#client` -- the gateway's own admin session on + * this worker, the same one `#rebuildView`'s refresh round trips use. `undefined` before + * `start()` has assigned it or after `close()`/`#handleClosed` has run -- neither clears + * `#client` itself, so this mirrors `reachable` rather than checking it separately. */ + // fallow-ignore-next-line unused-class-member -- #118's seam (WorkerDispatchTarget); nothing in this PR calls it yet. + client(): SimlockAdminClient | undefined { + return this.#closed ? undefined : this.#client; + } + + /** + * Completes the handshake and builds the first view. Never throws: a worker that cannot be + * driven is a fact about the fleet, reported in its view and its log line, not an error the + * gateway's accept path has to survive. + */ + async start(): Promise { + this.options.uplink.connection.onClose(() => this.#handleClosed()); + const connect = this.options.connect ?? defaultConnect; + let client: SimlockAdminClient; + try { + // C3: bounded like every other call this class makes (see `WORKER_CALL_TIMEOUT_MS`) -- + // `hello` is a round trip too, and a peer that completes the WebSocket upgrade with a + // valid join token and then never answers it would otherwise hang `start()` forever, + // holding an open socket and a slot in `#links` with no view to show for it (D2's failure + // mode, one call earlier in this same method). + client = await this.#withTimeout( + connect(this.options.uplink.connection, this.options.principal), + "hello", + ); + } catch (error: unknown) { + // A `hello` that failed for any reason other than version negotiation (see below): there + // is no session to drive, so there is nothing to put in a view either. + this.#logger.warn("Worker uplink handshake failed", { + workerId: this.workerId, + message: errorMessage(error), + }); + await this.close(); + return; + } + this.#client = client; + + // ADR 0003 §6's degraded client is how a version mismatch surfaces: `connectSimlockAdmin` + // keeps the connection open and every call rejects with the captured + // `PROTOCOL_VERSION_UNSUPPORTED`, carrying both ranges. One call is therefore the probe + // *and* the first `status.get` -- so a compatible worker pays nothing for the check. + try { + // The result is deliberately discarded: this call exists to *fail* on a mismatched + // protocol, and the view is built by the full refresh below rather than from half a + // snapshot taken before the event subscription exists. Bounded like every other call this + // class makes (see `WORKER_CALL_TIMEOUT_MS`): a worker that never answers `status.get` at + // all must not hang the handshake forever. + await this.#withTimeout(client.getStatus(), "status.get"); + } catch (error: unknown) { + if (isSimlockError(error) && error.code === "PROTOCOL_VERSION_UNSUPPORTED") { + // ADR 0005 §31: marked `incompatible`, with both ranges, and never asked anything else. + // The uplink stays open on purpose -- the worker is running and will reconnect on its + // own schedule after an upgrade; closing it here would just make it redial. + this.options.registry.incompatible( + this.workerId, + this.options.uplink.label, + { gateway: error.details.client, worker: error.details.daemon }, + error.details.daemonVersion, + ); + this.#logger.warn("Worker speaks no protocol version this gateway supports", { + workerId: this.workerId, + worker: error.details.daemon, + gateway: error.details.client, + }); + return; + } + this.#logger.warn("Worker uplink failed its first status call", { + workerId: this.workerId, + message: errorMessage(error), + }); + await this.close(); + return; + } + + if (client.role !== "admin") { + // ADR 0005 §5 says the worker grants this session `admin` because it dialled the gateway + // named in its own config. A worker that did not is either older than #117 or + // misconfigured; either way the gateway can read nothing useful from it, and pretending + // otherwise would produce a view full of `FORBIDDEN`s. + this.#logger.error("Worker did not grant the gateway an admin session; closing the uplink", { + workerId: this.workerId, + role: client.role, + }); + await this.close(); + return; + } + + this.options.registry.connected(this.workerId, this.options.uplink.label, client.daemonVersion); + // Subscribed before the first full refresh, not after: an event that fires while the + // refresh is in flight then queues another one, instead of falling in a gap between the + // two calls. It costs one extra `status.get` per connect, which is the cheapest call the + // worker has. + try { + this.#unsubscribeEvents = await this.#withTimeout( + client.subscribeEvents((push) => { + this.#onWorkerEvent(push.event); + }), + "events.subscribe", + ); + } catch (error: unknown) { + // H4: a `WorkerCallTimeoutError` here is not a refusal -- the worker was never asked and + // said no, its answer just did not arrive within `WORKER_CALL_TIMEOUT_MS`. Logging it as + // "refused" asserts something this code cannot know: the RPC may yet land, or may already + // have subscribed the worker on its end with no unsubscribe handle this link ever + // receives -- there is no way to unsubscribe that short of closing the whole link. + // Distinguishing the two in the log is this method's job even though neither path can (or + // needs to, for `refresh` below) retry the subscription itself; the tick still covers it. + if (error instanceof WorkerCallTimeoutError) { + this.#logger.warn( + "Worker did not answer an event subscription in time; falling back to the tick", + { workerId: this.workerId }, + ); + } else { + this.#logger.warn("Worker refused an event subscription; falling back to the tick", { + workerId: this.workerId, + message: errorMessage(error), + }); + } + } + await this.refresh({ includeCatalog: true }); + } + + /** + * Rebuilds this worker's view. Concurrent calls coalesce into one in-flight refresh plus at + * most one queued follow-up: a burst of worker events (a lease granted, its device leased, + * its capacity changed) must not become a burst of round trips, but the *last* event in a + * burst must still be reflected. + */ + async refresh(options: { readonly includeCatalog?: boolean } = {}): Promise { + const client = this.#client; + if (client === undefined || this.#closed) return; + if (this.#refreshing) { + this.#refreshQueued = true; + return; + } + this.#refreshing = true; + try { + // No reset here on success: `#rebuildView` already reset `#consecutiveRefreshTimeouts` to + // 0 the moment its `status.get` answered (C-1), which is a strictly earlier point than + // this `await` ever returning -- reaching here without throwing is only possible once + // that has already happened, which is what makes a second reset here dead code rather + // than defense in depth. + await this.#rebuildView(client, options.includeCatalog === true); + } catch (error: unknown) { + // A refresh that fails because the uplink died needs no handling here: `onClose` has + // already marked the view disconnected. Anything else is worth a line, and the next tick + // will try again. + this.#logger.debug("Worker view refresh failed", { + workerId: this.workerId, + message: errorMessage(error), + }); + // P1: a `WorkerCallTimeoutError` here is not "anything else" -- it is the one failure this + // class already knows means "the socket is not answering", and it used to mean nothing + // happened at all: `registry.refresh` was never reached, so `connection` stayed + // `connected` and `lastSeenAt` stayed stale, forever, on a half-open uplink. After + // `MAX_CONSECUTIVE_REFRESH_TIMEOUTS` in a row, close the link -- which routes through + // `#handleClosed` into `registry.disconnected` -- rather than let it keep confidently + // reporting a machine nothing can reach. `close()` is fire-and-forget here on purpose: it + // flips `#closed` synchronously before its own first `await`, which is what the `finally` + // block below needs to skip queuing another refresh behind a link that is on its way out. + if (error instanceof WorkerCallTimeoutError) { + this.#consecutiveRefreshTimeouts += 1; + if (this.#consecutiveRefreshTimeouts >= MAX_CONSECUTIVE_REFRESH_TIMEOUTS) { + this.#logger.warn("Worker stopped answering; closing its uplink", { + workerId: this.workerId, + consecutiveTimeouts: this.#consecutiveRefreshTimeouts, + }); + void this.close(); + } + } + } finally { + this.#refreshing = false; + if (this.#refreshQueued && !this.#closed) { + this.#refreshQueued = false; + void this.refresh(); + } + } + } + + /** The round trips one refresh makes, and what they become in the view. Split out of + * `refresh` so that method is only the coalescing rule and this one is only the reads. + * Bounded as one unit per call (D3): a worker that never answers one of these calls must not + * latch `#refreshing` forever and freeze the view mid-flight while it still reports + * `connected`. `status.get` is awaited on its own, ahead of the rest, and its arrival resets + * `#consecutiveRefreshTimeouts` immediately (C-1): it is the one call `runDispatch` never + * parks behind the worker's startup-readiness gate, so it answering is proof the transport is + * alive even while the other three are genuinely, harmlessly queued behind a slow `converge` + * -- application latency, not transport death, and P1's counter must not confuse the two. */ + async #rebuildView(client: SimlockAdminClient, includeCatalog: boolean): Promise { + const status = await this.#withTimeout(client.getStatus(), "status.get"); + this.#consecutiveRefreshTimeouts = 0; + + const [devices, catalog, config] = await this.#withTimeout( + Promise.all([ + client.list({ kind: "devices" }), + includeCatalog ? client.getCatalog() : undefined, + // Read on the same pass as the catalog: both are session-lifetime facts, and pairing + // them keeps the per-event refresh down to the two calls that actually go stale. + includeCatalog ? client.getConfig() : undefined, + ]), + "view refresh", + ); + // H2: the same asymmetry D1 fixed in `#handleClosed`, one write later. This link's own + // `close()`/`#handleClosed` may have run while the round trips above were in flight -- a + // reconnect that replaced this link with a newer one, or an explicit `stop()` -- and without + // this re-check the write below would land after the successor's own, more recent refresh, + // overwriting a fresh view with a stale one for up to `WORKER_CALL_TIMEOUT_MS`. + if (this.#closed || (this.options.isCurrentLink?.() ?? true) === false) return; + this.options.registry.refresh(this.workerId, { + capacity: status.capacity, + devices: viewDevicesSchema.parse(devices), + health: status.daemon.health, + leases: status.leases, + queueDepth: status.queueDepth, + version: client.daemonVersion, + ...(catalog === undefined ? {} : { catalog: catalog.platforms }), + ...(config === undefined + ? {} + : { + downloads: { policy: config.downloads.policy }, + // ADR 0005 §15: the one other field this gateway keeps out of a worker's config, + // alongside `downloads.policy` above -- `WorkerRegistry#refresh` is where it is + // compared against the gateway's own `lease.maxTtlMs` and warned about. + lease: { maxTtlMs: config.lease.maxTtlMs }, + }), + }); + } + + async close(): Promise { + if (this.#closed) return; + this.#closed = true; + const unsubscribe = this.#unsubscribeEvents; + this.#unsubscribeEvents = undefined; + // Best-effort throughout: the connection may already be gone, which is the common case + // here. The client and the connection are both closed -- closing the client is what tears + // down its own bookkeeping, and closing the connection is what guarantees the socket is + // gone even if the client never opened one (or failed on its way out). + // + // `unsubscribe` is a real `events.unsubscribe` round trip (D2): on a half-open socket it can + // otherwise hang forever, since `.catch(() => undefined)` only swallows a *rejection* and + // never fires on a promise that just never settles -- which is exactly what widened D1's + // reconnect window from microseconds to minutes. Bounding it here is what lets `close()` + // always reach `connection.close()`. + await this.#withTimeout(unsubscribe?.() ?? Promise.resolve(), "events.unsubscribe").catch( + () => undefined, + ); + await this.#client?.close().catch(() => undefined); + await this.options.uplink.connection.close().catch(() => undefined); + } + + #handleClosed(): void { + this.#closed = true; + // ADR 0005 §6: the uplink is keyed by worker id, not by this link, so a worker that + // reconnects while this link's socket is still (half-)open replaces it in the gateway's + // bookkeeping well before the old socket is ever reported dead (D1). Marking the registry + // disconnected here regardless would flip the *live* successor's view -- permanently, + // since `refresh()` never touches `connection` -- so a late close only counts when this is + // still the link the service considers current for its worker id. + if (this.options.isCurrentLink?.() ?? true) this.options.registry.disconnected(this.workerId); + this.options.onClosed?.(this.workerId); + } + + /** Bounds one round trip to the worker (D2/D3): races `promise` against a timer and rejects + * with `WorkerCallTimeoutError` if the timer wins. The timer is always cancelled once + * `promise` settles, so a slow-but-eventually-successful call leaves nothing pending. */ + #withTimeout(promise: Promise, what: string): Promise { + return new Promise((resolve, reject) => { + let settled = false; + const timer = this.options.clock.setTimer(WORKER_CALL_TIMEOUT_MS, () => { + if (settled) return; + settled = true; + reject(new WorkerCallTimeoutError(what)); + }); + promise.then( + (value) => { + if (settled) return; + settled = true; + this.options.clock.cancel(timer); + resolve(value); + }, + (error: unknown) => { + if (settled) return; + settled = true; + this.options.clock.cancel(timer); + reject(error instanceof Error ? error : new Error(String(error))); + }, + ); + }); + } + + /** + * ADR 0005 §22: a worker's business events are republished on the gateway's bus with + * `workerId` added, so they land in its ring buffer and `simlock events --follow` against a + * gateway shows the fleet. The name and the emitting module travel unchanged -- the fact came + * from that worker's reaper or lease engine, and rewriting either would make the audit trail + * lie about where it happened; `workerId` is what says which machine. + * + * Hardening: `envelope.event` is whatever string a worker's own `events.subscribe` push sends + * -- a client of this same admin protocol, on a machine this gateway does not otherwise + * control -- and `workerId` is merged in last, so it cannot be spoofed, but the *name* is + * taken on faith. Refusing the six subjects `docs/EVENTS.md` calls "the gateway's own" + * (`GATEWAY_OWN_EVENTS`) keeps a worker from forging `worker.drain-ended`, `worker.removed`, + * etc. into the operator's audit trail -- facts this gateway itself is supposed to be the only + * author of. Every other name still forwards unchanged, including ones this gateway's own + * `EventMap` has never heard of (a newer worker's own vocabulary). + */ + #onWorkerEvent(envelope: { + readonly event: string; + readonly payload?: unknown; + readonly module: string; + }): void { + if (GATEWAY_OWN_EVENTS.has(envelope.event)) { + this.#logger.warn("Worker sent an event name reserved for the gateway itself; dropping it", { + workerId: this.workerId, + event: envelope.event, + }); + return; + } + const payload = isRecord(envelope.payload) + ? { ...envelope.payload, workerId: this.workerId } + : { workerId: this.workerId }; + // The one cast in this file: a worker's event name is a string on the wire (see + // `eventEnvelopeSchema`), and a *newer* worker may legitimately send a name this gateway's + // `EventMap` has never heard of. Forwarding it is better than dropping it -- the envelope + // is what `events.replay` returns, and a consumer that knows the name gets it either way. + this.options.eventBus.emit(envelope.event as EventName, payload as never, envelope.module); + if (changesCapacityOrLeases(envelope.event)) void this.refresh(); + } +} + +/** + * ADR 0005 §22 / `docs/EVENTS.md`: the six facts only a gateway itself ever emits, about the + * workers connected to it. Never forwarded from a worker's own event stream (see + * `#onWorkerEvent`) -- a worker is a client of the same admin protocol, and nothing about + * `events.subscribe` proves the name it pushes is genuinely its own. + */ +const GATEWAY_OWN_EVENTS: ReadonlySet = new Set([ + "worker.connected", + "worker.rejected", + "worker.disconnected", + "worker.removed", + "worker.drain-started", + "worker.drain-ended", +]); + +/** + * Which worker events make a view stale (ADR 0005 §7: "every worker event that changes capacity + * or leases"). Matched by subject prefix rather than an explicit list of names: every event + * about a lease or a device is, by construction, about something a view reports -- and a list + * would silently miss the next one added to `EventMap`. The cost of being generous is one + * coalesced round trip; the cost of missing one is a view that stays wrong until the next tick. + */ +function changesCapacityOrLeases(event: string): boolean { + return event.startsWith("lease.") || event.startsWith("device."); +} + +const defaultConnect: WorkerClientFactory = (connection, principal) => + connectSimlockAdmin({ connection, principal }); + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} diff --git a/src/gateway/worker-registry.test.ts b/src/gateway/worker-registry.test.ts new file mode 100644 index 000000000..c2ada5887 --- /dev/null +++ b/src/gateway/worker-registry.test.ts @@ -0,0 +1,681 @@ +import { describe, expect, it } from "vitest"; + +import { EventBus, type EventEnvelope } from "../bus/index.js"; +import { PROTOCOL_VERSION_RANGE } from "../contract/index.js"; +import { FakeClock, type Logger } from "../ports/index.js"; +import { MemoryDrainStore } from "./drain-store.js"; +import { leaseFixture } from "./test-support.js"; +import { WorkerRegistry } from "./worker-registry.js"; + +const RETENTION_MS = 24 * 60 * 60_000; +/** Matches `core/config.ts`'s own default, so a test that does not care about ADR 0005 §15's + * warning gets a cap no fixture's `ttlMs` ever comes near. */ +const DEFAULT_LEASE_MAX_TTL_MS = 4 * 60 * 60_000; +/** Matches `service.test.ts`'s `principal: "gw:instance-1"` -- ADR 0005 §14/§27's own-lease + * prefix is that principal plus a trailing `:`. */ +const GATEWAY_REQUESTER_PREFIX = "gw:instance-1:"; + +/** Records every `warn` call, the same shape `service.test.ts`'s own `RecordingLogger` uses -- + * §15's warning is asserted on directly rather than only on the view it leaves behind. */ +class RecordingLogger implements Logger { + readonly warnings: Array<{ message: string; fields?: Record }> = []; + + debug(): void {} + info(): void {} + warn(message: string, fields?: Record): void { + this.warnings.push(fields === undefined ? { message } : { fields, message }); + } + error(): void {} + child(): Logger { + return this; + } +} + +function registry( + options: { + readonly drainStore?: MemoryDrainStore; + /** Omit to get the default fixture prefix; pass `null` explicitly (H3) to build a registry + * with no `gatewayRequesterPrefix` at all, the way `dispatcher.test.ts`'s harness does. */ + readonly gatewayRequesterPrefix?: string | null; + /** ADR 0005 §15's own cap. Defaults to `core/config.ts`'s own default so a test that never + * reports a worker `lease.maxTtlMs` cannot accidentally trip the new warning. */ + readonly leaseMaxTtlMs?: number; + readonly logger?: Logger; + } = {}, +) { + const clock = new FakeClock(1_000); + const eventBus = new EventBus(clock); + const events: EventEnvelope[] = []; + eventBus.subscribeAll((envelope) => events.push(envelope)); + const gatewayRequesterPrefix = + options.gatewayRequesterPrefix === null + ? undefined + : (options.gatewayRequesterPrefix ?? GATEWAY_REQUESTER_PREFIX); + const workers = new WorkerRegistry({ + clock, + eventBus, + leaseMaxTtlMs: options.leaseMaxTtlMs ?? DEFAULT_LEASE_MAX_TTL_MS, + retentionMs: RETENTION_MS, + ...(gatewayRequesterPrefix === undefined ? {} : { gatewayRequesterPrefix }), + ...(options.drainStore === undefined ? {} : { drainStore: options.drainStore }), + ...(options.logger === undefined ? {} : { logger: options.logger }), + }); + return { clock, events, workers }; +} + +/** A gateway-issued lease's `requesterId` (ADR 0005 §14/§27): the fixed prefix `pruneExpired` + * scopes its retention hold to, so a fixture built with it exercises the real branch rather than + * one that happens to pass because no scoping exists yet. */ +function gatewayLeaseFixture(id: string, deviceId: string) { + return { ...leaseFixture(id, deviceId), requesterId: `${GATEWAY_REQUESTER_PREFIX}agent-1` }; +} + +function names(events: readonly EventEnvelope[]): string[] { + return events.map((event) => event.event); +} + +describe("WorkerRegistry", () => { + it("builds a view on connect and emits the fact", () => { + const { events, workers } = registry(); + + const view = workers.connected("wrk_1", "mac-mini-1", "0.3.0"); + + expect(view).toMatchObject({ + catalog: [], + connection: "connected", + devices: [], + drained: false, + id: "wrk_1", + label: "mac-mini-1", + lastSeenAt: 1_000, + leases: [], + version: "0.3.0", + }); + expect(events).toHaveLength(1); + expect(events[0]).toMatchObject({ + event: "worker.connected", + payload: { label: "mac-mini-1", version: "0.3.0", workerId: "wrk_1" }, + }); + }); + + it("refreshes what a worker reports and leaves the rest alone", () => { + const { clock, workers } = registry(); + workers.connected("wrk_1", undefined, "0.3.0"); + + clock.advance(5_000); + workers.refresh("wrk_1", { health: "running", queueDepth: 2, leases: [] }); + + expect(workers.view("wrk_1")).toMatchObject({ + connection: "connected", + health: "running", + lastSeenAt: 6_000, + queueDepth: 2, + }); + }); + + it("keeps an absent key's previous value, so an event-driven refresh does not blank the catalog", () => { + const { workers } = registry(); + workers.connected("wrk_1", undefined, "0.3.0"); + workers.refresh("wrk_1", { + catalog: [{ models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }], + }); + + workers.refresh("wrk_1", { queueDepth: 1 }); + + expect(workers.view("wrk_1")?.catalog).toEqual([ + { models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }, + ]); + }); + + it("drops a refresh for a view that has been removed", async () => { + const { workers } = registry(); + workers.connected("wrk_1", undefined, "0.3.0"); + workers.disconnected("wrk_1"); + await workers.remove("wrk_1"); + + workers.refresh("wrk_1", { queueDepth: 9 }); + + expect(workers.view("wrk_1")).toBeUndefined(); + }); + + describe("warning on a worker's lower lease.maxTtlMs (ADR 0005 §15)", () => { + it("warns once a worker's own cap is refreshed in below the gateway's", () => { + const logger = new RecordingLogger(); + const { workers } = registry({ leaseMaxTtlMs: 3_600_000, logger }); + workers.connected("wrk_1", "mac-mini-1", "0.3.0"); + + workers.refresh("wrk_1", { lease: { maxTtlMs: 1_800_000 } }); + + expect(logger.warnings).toHaveLength(1); + expect(logger.warnings[0]).toMatchObject({ + fields: { + gatewayMaxTtlMs: 3_600_000, + label: "mac-mini-1", + workerId: "wrk_1", + workerMaxTtlMs: 1_800_000, + }, + }); + }); + + it("does not warn when a worker's own cap is at or above the gateway's", () => { + const logger = new RecordingLogger(); + const { workers } = registry({ leaseMaxTtlMs: 3_600_000, logger }); + workers.connected("wrk_1", undefined, "0.3.0"); + + // Exactly equal, and then strictly above -- neither is "below". + workers.refresh("wrk_1", { lease: { maxTtlMs: 3_600_000 } }); + workers.refresh("wrk_1", { lease: { maxTtlMs: 7_200_000 } }); + + expect(logger.warnings).toEqual([]); + }); + + it("does not warn, and does not crash, when a worker reports no cap at all", () => { + const logger = new RecordingLogger(); + const { workers } = registry({ leaseMaxTtlMs: 3_600_000, logger }); + workers.connected("wrk_1", undefined, "0.3.0"); + + // No `lease` key on the snapshot: exactly what an event-driven refresh sends today + // (`config.get` is only read alongside the catalog), and what an incompatible or + // config.get-failed worker's view carries forever. + expect(() => workers.refresh("wrk_1", { queueDepth: 1 })).not.toThrow(); + + expect(workers.view("wrk_1")?.lease).toBeUndefined(); + expect(logger.warnings).toEqual([]); + }); + + it("does not repeat the warning on a later refresh reporting the same lower cap", () => { + const logger = new RecordingLogger(); + const { workers } = registry({ leaseMaxTtlMs: 3_600_000, logger }); + workers.connected("wrk_1", undefined, "0.3.0"); + + // The periodic backstop tick re-reads config.get (and so `lease.maxTtlMs`) on every + // refresh alongside the catalog (`WorkerLink#rebuildView`) -- an unchanged report must + // not turn into a warning every `refreshIntervalMs`. + workers.refresh("wrk_1", { lease: { maxTtlMs: 1_800_000 } }); + workers.refresh("wrk_1", { lease: { maxTtlMs: 1_800_000 } }); + workers.refresh("wrk_1", { lease: { maxTtlMs: 1_800_000 } }); + + expect(logger.warnings).toHaveLength(1); + }); + + it("warns again if the cap drops further while already below the gateway's", () => { + const logger = new RecordingLogger(); + const { workers } = registry({ leaseMaxTtlMs: 3_600_000, logger }); + workers.connected("wrk_1", undefined, "0.3.0"); + + workers.refresh("wrk_1", { lease: { maxTtlMs: 1_800_000 } }); + workers.refresh("wrk_1", { lease: { maxTtlMs: 900_000 } }); + + expect(logger.warnings).toHaveLength(2); + expect(logger.warnings[1]?.fields).toMatchObject({ workerMaxTtlMs: 900_000 }); + }); + }); + + it("marks a version-mismatched worker incompatible with both ranges, and rejects it", () => { + const { events, workers } = registry(); + + const view = workers.incompatible( + "wrk_1", + "old-mac", + { gateway: PROTOCOL_VERSION_RANGE, worker: { min: 4, max: 4 } }, + "0.2.0", + ); + + expect(view).toMatchObject({ + connection: "incompatible", + protocol: { gateway: PROTOCOL_VERSION_RANGE, worker: { min: 4, max: 4 } }, + version: "0.2.0", + }); + // ADR 0005 §31: no event at all. Not `worker.connected`, because nothing usable + // connected, and not `worker.rejected` either -- that uplink authenticated. The view is + // the fact. + expect(events).toEqual([]); + }); + + it("clears the protocol ranges when an upgraded worker reconnects", () => { + const { workers } = registry(); + workers.incompatible( + "wrk_1", + undefined, + { gateway: PROTOCOL_VERSION_RANGE, worker: { min: 4, max: 4 } }, + "0.2.0", + ); + + const view = workers.connected("wrk_1", undefined, "0.3.0"); + + expect(view.connection).toBe("connected"); + expect(view.protocol).toBeUndefined(); + }); + + it.each(["unauthenticated", "forbidden"] as const)( + "reports a %s uplink without inventing a view for it", + (reason) => { + const { events, workers } = registry(); + + workers.rejected(reason, undefined, undefined); + + expect(workers.views()).toEqual([]); + expect(events[0]).toMatchObject({ event: "worker.rejected", payload: { reason } }); + }, + ); + + it("keeps a disconnected view with everything it last reported", () => { + const { clock, events, workers } = registry(); + workers.connected("wrk_1", "mac-mini-1", "0.3.0"); + workers.refresh("wrk_1", { leases: [leaseFixture("lease_1", "dev_1")] }); + + clock.advance(1_000); + workers.disconnected("wrk_1"); + + expect(workers.view("wrk_1")).toMatchObject({ + connection: "disconnected", + lastSeenAt: 2_000, + leases: [{ id: "lease_1" }], + }); + expect(events.at(-1)).toMatchObject({ + event: "worker.disconnected", + payload: { leaseCount: 1, label: "mac-mini-1", workerId: "wrk_1" }, + }); + }); + + it("says nothing when a view that is already disconnected disconnects again", () => { + const { events, workers } = registry(); + workers.connected("wrk_1", undefined, undefined); + workers.disconnected("wrk_1"); + const before = events.length; + + workers.disconnected("wrk_1"); + + expect(events).toHaveLength(before); + }); + + describe("retention", () => { + it("forgets a disconnected view once the retention window passes", async () => { + const { clock, events, workers } = registry(); + workers.connected("wrk_1", undefined, undefined); + workers.disconnected("wrk_1"); + + clock.advance(RETENTION_MS - 1); + await workers.pruneExpired(); + expect(workers.view("wrk_1")).toBeDefined(); + + clock.advance(1); + await workers.pruneExpired(); + + expect(workers.view("wrk_1")).toBeUndefined(); + expect(events.at(-1)).toMatchObject({ + event: "worker.removed", + payload: { reason: "retention", workerId: "wrk_1" }, + }); + }); + + it("never forgets a worker whose gateway-issued leases are still live, however long it has been gone", async () => { + const { clock, workers } = registry(); + workers.connected("wrk_1", undefined, undefined); + const lease = { ...gatewayLeaseFixture("lease_1", "dev_1"), ttlDeadline: 10 * RETENTION_MS }; + workers.refresh("wrk_1", { leases: [lease] }); + workers.disconnected("wrk_1"); + + clock.advance(5 * RETENTION_MS); + await workers.pruneExpired(); + + // A device is still held on a machine nobody can reach: that is exactly what an operator + // must be able to see. + expect(workers.view("wrk_1")).toBeDefined(); + }); + + // ADR 0005 §6/§14 (M2): the retention hold is scoped to leases *this gateway* issued. A + // worker's own local lease -- an agent on that machine, never routed through the gateway -- + // is none of the gateway's business to keep a view alive for. + // H3: a registry with no `gatewayRequesterPrefix` cannot tell a gateway-issued lease apart + // from a worker-local one, so per `safety.md`'s fails-closed instinct it must not guess "none + // of these are mine" and prune anyway. `GatewayService` always supplies the prefix, but the + // class is exported and `dispatcher.test.ts`'s harness constructs one without it. + it("holds a view with a live lease when built with no gatewayRequesterPrefix at all", async () => { + const { clock, workers } = registry({ gatewayRequesterPrefix: null }); + workers.connected("wrk_1", undefined, undefined); + const lease = { ...leaseFixture("lease_1", "dev_1"), ttlDeadline: 10 * RETENTION_MS }; + workers.refresh("wrk_1", { leases: [lease] }); + workers.disconnected("wrk_1"); + + clock.advance(5 * RETENTION_MS); + await workers.pruneExpired(); + + expect(workers.view("wrk_1")).toBeDefined(); + }); + + it("forgets a worker whose only live lease is a local one, not the gateway's own", async () => { + const { clock, workers } = registry(); + workers.connected("wrk_1", undefined, undefined); + const localLease = { ...leaseFixture("lease_1", "dev_1"), ttlDeadline: 10 * RETENTION_MS }; + workers.refresh("wrk_1", { leases: [localLease] }); + workers.disconnected("wrk_1"); + + clock.advance(RETENTION_MS + 1); + await workers.pruneExpired(); + + expect(workers.view("wrk_1")).toBeUndefined(); + }); + + it("forgets it once the last lease deadline has passed and retention has elapsed", async () => { + const { clock, workers } = registry(); + workers.connected("wrk_1", undefined, undefined); + workers.refresh("wrk_1", { + leases: [{ ...gatewayLeaseFixture("lease_1", "dev_1"), ttlDeadline: 2_000 }], + }); + workers.disconnected("wrk_1"); + + clock.advance(RETENTION_MS); + await workers.pruneExpired(); + + expect(workers.view("wrk_1")).toBeUndefined(); + }); + + it("leaves a connected view alone no matter how long it has been connected", async () => { + const { clock, workers } = registry(); + workers.connected("wrk_1", undefined, undefined); + + clock.advance(10 * RETENTION_MS); + await workers.pruneExpired(); + + expect(workers.view("wrk_1")).toBeDefined(); + }); + + // C1: a regression in the M1 fix above -- `pruneExpired` reused `#forget`, which also + // cleared the drain flag. Retention is not an operator action (ADR 0005 §9: "only `undrain` + // ends it"; §8a: the drained set is the gateway's own record, kept separate from the + // observed view precisely so a drain outlives it). An operator who drains a machine for + // maintenance and leaves it off over a retention window must find it still drained when it + // reconnects, exactly like the reconnect and restart cases above -- this crosses drain with + // retention, which neither of those tests do. + it("keeps the drain flag when retention forgets the view, unlike an operator remove", async () => { + const store = new MemoryDrainStore(); + const { clock, workers } = registry({ drainStore: store }); + workers.connected("wrk_1", undefined, undefined); + await workers.setDrained("wrk_1", true); + workers.disconnected("wrk_1"); + + clock.advance(RETENTION_MS + 1); + await workers.pruneExpired(); + + expect(workers.view("wrk_1")).toBeUndefined(); + expect(workers.connected("wrk_1", undefined, undefined).drained).toBe(true); + }); + + // Hardening: the C1 test above is correct that retention must not clear a drain flag -- but + // once a view is gone, neither `setDrained` nor `undrain` can reach that flag either + // (`UNKNOWN_WORKER`, no view to require). Before this fix, nothing could ever clear it + // again: `remove` returned early on a missing view before touching `#drained`, leaving + // `workers.json` growing a permanent `true` for a worker that no longer exists -- M1's + // "unbounded file" relocated, not closed. `remove` on that same id is the one command + // already documented as a no-op-but-not-an-error for a forgotten worker; it must also be + // the one that can still clear a flag stranded behind it. + it("lets remove() clear a drain flag stranded by retention, with no view to answer removed: true", async () => { + const store = new MemoryDrainStore(); + const { clock, workers } = registry({ drainStore: store }); + workers.connected("wrk_1", undefined, undefined); + await workers.setDrained("wrk_1", true); + workers.disconnected("wrk_1"); + + clock.advance(RETENTION_MS + 1); + await workers.pruneExpired(); + expect(workers.view("wrk_1")).toBeUndefined(); + + // No view left to remove, so this is still "already forgotten" -- but the flag itself + // must actually clear, and the store must actually persist that. + await expect(workers.remove("wrk_1")).resolves.toBe(false); + await expect(store.load()).resolves.not.toContain("wrk_1"); + + // The real proof: a later reconnect under the same id is no longer drained. + expect(workers.connected("wrk_1", undefined, undefined).drained).toBe(false); + }); + }); + + describe("drain", () => { + it("flags the view and emits the fact, once", async () => { + const { events, workers } = registry(); + workers.connected("wrk_1", "mac-mini-1", undefined); + + const view = await workers.setDrained("wrk_1", true); + expect(view.drained).toBe(true); + expect(events.at(-1)).toMatchObject({ + event: "worker.drain-started", + payload: { label: "mac-mini-1", workerId: "wrk_1" }, + }); + + // Idempotent: draining again is not an error and is not a second fact. + const before = events.length; + await workers.setDrained("wrk_1", true); + expect(events).toHaveLength(before); + }); + + it("undrains", async () => { + const { events, workers } = registry(); + workers.connected("wrk_1", undefined, undefined); + await workers.setDrained("wrk_1", true); + + await workers.setDrained("wrk_1", false); + + expect(workers.view("wrk_1")?.drained).toBe(false); + expect(names(events)).toContain("worker.drain-ended"); + }); + + it("refuses an id it has no view of", async () => { + const { workers } = registry(); + + await expect(workers.setDrained("wrk_missing", true)).rejects.toMatchObject({ + code: "UNKNOWN_WORKER", + }); + }); + + it("survives a reconnect", async () => { + const { workers } = registry(); + workers.connected("wrk_1", undefined, undefined); + await workers.setDrained("wrk_1", true); + workers.disconnected("wrk_1"); + + expect(workers.connected("wrk_1", undefined, undefined).drained).toBe(true); + }); + + it("survives a gateway restart, which is the point of persisting it", async () => { + const store = new MemoryDrainStore(); + const first = registry({ drainStore: store }); + first.workers.connected("wrk_1", undefined, undefined); + await first.workers.setDrained("wrk_1", true); + + // A second gateway, with nothing in memory and the same file. + const second = registry({ drainStore: store }); + await second.workers.load(); + + // The worker has not even connected yet, and is already drained when it does. + expect(second.workers.connected("wrk_1", undefined, undefined).drained).toBe(true); + }); + + it("stops persisting a worker that has been undrained", async () => { + const store = new MemoryDrainStore(); + const first = registry({ drainStore: store }); + first.workers.connected("wrk_1", undefined, undefined); + await first.workers.setDrained("wrk_1", true); + await first.workers.setDrained("wrk_1", false); + + const second = registry({ drainStore: store }); + await second.workers.load(); + + expect(second.workers.connected("wrk_1", undefined, undefined).drained).toBe(false); + }); + }); + + describe("remove", () => { + it("forgets a disconnected view", async () => { + const { events, workers } = registry(); + workers.connected("wrk_1", "mac-mini-1", undefined); + workers.disconnected("wrk_1"); + + await expect(workers.remove("wrk_1")).resolves.toBe(true); + + expect(workers.view("wrk_1")).toBeUndefined(); + expect(events.at(-1)).toMatchObject({ + event: "worker.removed", + payload: { reason: "operator", workerId: "wrk_1" }, + }); + }); + + it("refuses a connected one", async () => { + const { workers } = registry(); + workers.connected("wrk_1", undefined, undefined); + + await expect(workers.remove("wrk_1")).rejects.toMatchObject({ code: "WORKER_CONNECTED" }); + expect(workers.view("wrk_1")).toBeDefined(); + }); + + it("refuses an incompatible one too -- its uplink is open", async () => { + const { workers } = registry(); + workers.incompatible( + "wrk_1", + undefined, + { gateway: PROTOCOL_VERSION_RANGE, worker: { min: 4, max: 4 } }, + undefined, + ); + + await expect(workers.remove("wrk_1")).rejects.toMatchObject({ code: "WORKER_CONNECTED" }); + }); + + it("reports `false` for an id it has never heard of, rather than failing", async () => { + const { events, workers } = registry(); + + await expect(workers.remove("wrk_missing")).resolves.toBe(false); + expect(names(events)).not.toContain("worker.removed"); + }); + + // M1: `#forget` used to delete the view and leave the drain flag standing forever -- + // `workers.json` grew without bound, and a worker whose id was ever seen again would come + // back silently drained with no way to `undrain` it (there is no view to undrain). + it("clears a removed worker's drain flag too, and persists that", async () => { + const store = new MemoryDrainStore(); + const first = registry({ drainStore: store }); + first.workers.connected("wrk_1", undefined, undefined); + await first.workers.setDrained("wrk_1", true); + first.workers.disconnected("wrk_1"); + + await expect(first.workers.remove("wrk_1")).resolves.toBe(true); + + // Reconnecting the same id, on the same registry, must not come back drained: the flag + // was cleared in memory... + expect(first.workers.connected("wrk_1", undefined, undefined).drained).toBe(false); + first.workers.disconnected("wrk_1"); + await first.workers.remove("wrk_1"); + + // ...and on disk, so a second gateway reading the same store does not resurrect it either. + const second = registry({ drainStore: store }); + await second.workers.load(); + expect(second.workers.connected("wrk_1", undefined, undefined).drained).toBe(false); + }); + + it("undrain fails UNKNOWN_WORKER for a worker removed while drained -- there is no view left", async () => { + const { workers } = registry(); + workers.connected("wrk_1", undefined, undefined); + await workers.setDrained("wrk_1", true); + workers.disconnected("wrk_1"); + await workers.remove("wrk_1"); + + await expect(workers.setDrained("wrk_1", false)).rejects.toMatchObject({ + code: "UNKNOWN_WORKER", + }); + }); + }); + + it("orders views by id, so two reads agree", () => { + const { workers } = registry(); + workers.connected("wrk_c", undefined, undefined); + workers.connected("wrk_a", undefined, undefined); + workers.connected("wrk_b", undefined, undefined); + + expect(workers.views().map((view) => view.id)).toEqual(["wrk_a", "wrk_b", "wrk_c"]); + }); + + // `./fleet-ports.ts`'s `FleetViews#onViewsChanged` -- #118's seam. This registry has no + // listeners of its own; these tests are the notifier's whole contract. + describe("onViewsChanged", () => { + it("fires once per committed change, after the view is committed", () => { + const { workers } = registry(); + const seen: Array = []; + workers.onViewsChanged(() => seen.push(workers.view("wrk_1")?.connection)); + + workers.connected("wrk_1", undefined, undefined); + + expect(seen).toEqual(["connected"]); + }); + + it("does not fire for a call that changes nothing", async () => { + const { workers } = registry(); + workers.connected("wrk_1", undefined, undefined); + let fired = 0; + workers.onViewsChanged(() => { + fired += 1; + }); + + // Draining an already-undrained-to-false worker: `setDrained` no-ops. + await workers.setDrained("wrk_1", false); + // A refresh for a worker with no view: dropped. + workers.refresh("wrk_missing", { queueDepth: 1 }); + // Disconnecting an already-disconnected view: no-op. + workers.disconnected("wrk_1"); + workers.disconnected("wrk_1"); + + expect(fired).toBe(1); // only the first `disconnected()` -- the second is the no-op repeat. + }); + + it("stops firing once unsubscribed", () => { + const { workers } = registry(); + let fired = 0; + const unsubscribe = workers.onViewsChanged(() => { + fired += 1; + }); + + workers.connected("wrk_1", undefined, undefined); + unsubscribe(); + workers.disconnected("wrk_1"); + + expect(fired).toBe(1); + }); + + it("does not let a throwing listener break the mutation or starve the other listeners", () => { + const { workers } = registry(); + let afterFired = 0; + workers.onViewsChanged(() => { + throw new Error("a subscriber's own bug"); + }); + workers.onViewsChanged(() => { + afterFired += 1; + }); + + expect(() => workers.connected("wrk_1", undefined, undefined)).not.toThrow(); + + // The mutation itself committed... + expect(workers.view("wrk_1")?.connection).toBe("connected"); + // ...and the listener registered after the throwing one still ran. + expect(afterFired).toBe(1); + }); + + it("fires for remove() and pruneExpired(), each forgetting a view through #forget", async () => { + const { clock, workers } = registry(); + let fired = 0; + workers.onViewsChanged(() => { + fired += 1; + }); + + workers.connected("wrk_1", undefined, undefined); // 1 + workers.disconnected("wrk_1"); // 2 + await workers.remove("wrk_1"); // 3 + + workers.connected("wrk_2", undefined, undefined); // 4 + workers.disconnected("wrk_2"); // 5 + clock.advance(RETENTION_MS + 1); + await workers.pruneExpired(); // 6 + + expect(fired).toBe(6); + expect(workers.view("wrk_1")).toBeUndefined(); + expect(workers.view("wrk_2")).toBeUndefined(); + }); + }); +}); diff --git a/src/gateway/worker-registry.ts b/src/gateway/worker-registry.ts new file mode 100644 index 000000000..c2d801501 --- /dev/null +++ b/src/gateway/worker-registry.ts @@ -0,0 +1,467 @@ +/** + * The gateway's picture of its fleet: one `WorkerView` per worker it has seen, and the facts it + * emits as those views change (ADR 0005 §6, §8, §9, §22). + * + * Views are rebuilt over the uplink (§30: a gateway restart re-derives everything from the + * workers that reconnect). Exactly one thing on them is persisted -- the drained set, which no + * worker reports and which must survive both a worker reconnect and a gateway restart (Decision + * 3, see `./drain-store.ts`). This class owns *what a view is and when it changes*; `WorkerLink` + * owns the uplink that supplies the facts, and `GatewayDispatcher` owns answering operations + * from them. + */ +import type { z } from "zod"; + +import type { EventBus } from "../bus/index.js"; +import { workerViewSchema, type ProtocolRange } from "../contract/index.js"; +import { DispatchError } from "../daemon/dispatch.js"; +import type { Clock, Logger } from "../ports/index.js"; +import { NoopLogger } from "../ports/index.js"; +import type { DrainStore } from "./drain-store.js"; + +export type WorkerView = z.infer; + +/** The fields a refresh over the uplink replaces. Everything else on a view -- identity, drain + * state, connection state -- is this registry's own bookkeeping, never a worker's to report. */ +export type WorkerViewSnapshot = Pick< + WorkerView, + | "capacity" + | "catalog" + | "devices" + | "downloads" + | "health" + | "lease" + | "leases" + | "queueDepth" + | "version" +>; + +export interface WorkerRegistryOptions { + readonly clock: Clock; + readonly eventBus: EventBus; + /** `gateway.disconnectedRetentionMs` (ADR 0005 §6). */ + readonly retentionMs: number; + /** + * Where the drained set is kept across restarts (ADR 0005, Decision 3). Optional so a test + * that does not care about persistence need not fabricate one; a gateway always has one. + */ + readonly drainStore?: DrainStore; + /** + * `gw::` (ADR 0005 §14/§27) -- what marks a lease as *this* + * gateway's own, rather than another gateway's or a worker's local one. Scopes the retention + * hold (§6) to leases this gateway issued: a worker's own local lease is none of this + * gateway's business to keep a view alive for, and holding one anyway would mean a machine + * with only local traffic never leaves an operator's `simlock worker remove` after it + * disconnects (M2). Optional so a test exercising nothing lease-shaped need not supply one; + * a real gateway always does. + */ + readonly gatewayRequesterPrefix?: string; + /** + * This gateway's own `lease.maxTtlMs` (ADR 0005 §15) -- what every view's reported + * `lease.maxTtlMs` is compared against on `refresh()` to warn when a worker's own cap is + * lower. Not optional: a real gateway always has this value (it is `config.lease.maxTtlMs`, + * which always defaults to something), and there is no safe placeholder to compare against + * in its absence. + */ + readonly leaseMaxTtlMs: number; + readonly logger?: Logger; +} + +export class WorkerRegistry { + readonly #workers = new Map(); + /** + * Drained worker ids, including ids with no view yet. Kept beside the views rather than only + * on them because drain outlives a view: an operator drains a machine, the machine is turned + * off (its view eventually retired), and when it comes back it must still be drained. This + * set is what `load()` restores and what `setDrained` writes back. + */ + readonly #drained = new Set(); + /** `./fleet-ports.ts`'s `FleetViews#onViewsChanged` -- see that method's own doc comment. */ + readonly #viewsChangedListeners = new Set<() => void>(); + readonly #logger: Logger; + + constructor(private readonly options: WorkerRegistryOptions) { + this.#logger = options.logger ?? new NoopLogger(); + } + + /** Restores the persisted drain set. Called once, before the uplink listener starts, so a + * worker that reconnects in the first second is already drained when its view is built. */ + async load(): Promise { + for (const workerId of (await this.options.drainStore?.load()) ?? []) { + this.#drained.add(workerId); + } + } + + /** Every view, ordered by id so two calls in a row -- and two gateways -- agree. */ + views(): readonly WorkerView[] { + return [...this.#workers.values()].sort((left, right) => left.id.localeCompare(right.id)); + } + + view(workerId: string): WorkerView | undefined { + return this.#workers.get(workerId); + } + + /** + * `./fleet-ports.ts`'s `FleetViews#onViewsChanged` -- #118's seam for running dispatch + * whenever the fleet's queue or any worker view changes (ADR 0005 §11), without reaching into + * this registry's internals or polling it. Called once per mutation this registry actually + * commits (`connected`, `incompatible`, `refresh`, `disconnected`, `setDrained`, `remove`, + * `pruneExpired`) -- never for a call that finds nothing to change (an unknown worker, a + * refresh dropped for a view already gone, draining an already-drained worker) -- and always + * *after* the commit and after the corresponding event, if any, is emitted (`events.md`'s + * post-commit rule). Returns the unsubscribe function. + * + * A listener that throws is logged at debug and does not stop the mutation that triggered it + * or any other listener: this registry's own correctness must never depend on what a + * subscriber does with the notification. + */ + onViewsChanged(listener: () => void): () => void { + this.#viewsChangedListeners.add(listener); + return () => { + this.#viewsChangedListeners.delete(listener); + }; + } + + #notifyViewsChanged(): void { + for (const listener of this.#viewsChangedListeners) { + try { + listener(); + } catch (error: unknown) { + this.#logger.debug("A worker-views-changed listener threw", { + message: error instanceof Error ? error.message : String(error), + }); + } + } + } + + /** + * A worker's uplink is open. A view that already exists keeps its drain state -- draining is + * an operator's decision about a *machine*, and a worker that reconnects (a restart, a + * flapping network) has not undone it. Everything the worker itself reports is left for the + * first refresh; until then the view says `connected` and carries whatever the last session + * saw, which is more useful to a console than an empty one. + */ + connected(workerId: string, label: string | undefined, version: string | undefined): WorkerView { + const existing = this.#workers.get(workerId); + const view: WorkerView = { + ...(existing ?? { catalog: [], devices: [], leases: [] }), + connection: "connected", + // Read from the persisted set, not from the previous view: a worker connecting for the + // first time after a gateway restart has no previous view, and must still be drained. + drained: this.#drained.has(workerId), + id: workerId, + lastSeenAt: this.options.clock.now(), + ...(label === undefined ? {} : { label }), + ...(version === undefined ? {} : { version }), + }; + // A reconnect after an `incompatible` session must not keep the old ranges around. + const { protocol: _dropped, ...withoutProtocol } = view; + this.#workers.set(workerId, withoutProtocol); + this.options.eventBus.emit( + "worker.connected", + { + workerId, + ...(label === undefined ? {} : { label }), + ...(version === undefined ? {} : { version }), + }, + "gateway", + ); + this.#notifyViewsChanged(); + return withoutProtocol; + } + + /** + * ADR 0005 §31: the uplink is open but `hello` found no overlapping protocol version. The + * view records both ranges and nothing else -- the gateway asked the worker nothing, because + * it cannot. + * + * No event either way, deliberately. Not `worker.connected`, because nothing usable + * connected; and not `worker.rejected`, because that one is about the door (§22) and this + * uplink authenticated fine. What an operator needs here is the *standing* fact "this + * machine is too old to drive", and that is the view -- which `simlock worker list` shows + * until the machine is upgraded, rather than a line that scrolls out of the ring buffer + * while the worker keeps redialling. + */ + incompatible( + workerId: string, + label: string | undefined, + protocol: { readonly gateway: ProtocolRange; readonly worker: ProtocolRange }, + version: string | undefined, + ): WorkerView { + const existing = this.#workers.get(workerId); + const view: WorkerView = { + ...(existing ?? { catalog: [], devices: [], leases: [] }), + connection: "incompatible", + drained: this.#drained.has(workerId), + id: workerId, + lastSeenAt: this.options.clock.now(), + protocol, + ...(label === undefined ? {} : { label }), + ...(version === undefined ? {} : { version }), + }; + this.#workers.set(workerId, view); + this.#notifyViewsChanged(); + return view; + } + + /** + * An uplink the gateway turned away at the upgrade (ADR 0005 §4/§22). The reason is the + * outcome the token check produced, kept apart here for the same reason it is kept apart on + * the wire: `unauthenticated` (`401`) is "no token, or one I do not know" and points at the + * join token, while `forbidden` (`403`) is "a real credential without this authority" and + * points at its role -- two different things for an operator to go and fix. + * + * There is no view to build: the peer never became a worker, so this is a fact and nothing + * else, and `workerId` is only ever what the connection claimed in its header. + * + * P-2: `count`, when given, is how many identical (reason, claimed id) refusals the *previous* + * coalescing window absorbed before it closed -- not a count of this event's own occurrence, + * which is always exactly one. `GatewayService` reports it on the next matching refusal after + * a window ages out, since every refusal here is unauthenticated by definition and the ring + * buffer this lands in is bounded by count, not bytes (P3): without coalescing, a loop of + * refused dials could otherwise emit one event per attempt and evict everything else in it. + * Omitted (not zero or one) outside a flood, so the payload is unchanged from before this fix + * in the overwhelmingly common case of an isolated refusal. + */ + rejected( + reason: "forbidden" | "unauthenticated", + workerId: string | undefined, + label: string | undefined, + count?: number, + ): void { + this.options.eventBus.emit( + "worker.rejected", + { + reason, + ...(workerId === undefined ? {} : { workerId }), + ...(label === undefined ? {} : { label }), + ...(count === undefined ? {} : { count }), + }, + "gateway", + ); + } + + /** + * Replaces what the worker reports. Partial on purpose: a refresh triggered by a lease event + * re-reads status and devices but not the catalog (§7), and an absent key must leave the + * previous value standing rather than blank it. A refresh for a worker whose view is gone + * (removed while a status call was in flight) is dropped rather than resurrecting it. + */ + refresh(workerId: string, snapshot: Partial): void { + const existing = this.#workers.get(workerId); + if (existing === undefined) return; + const next: WorkerView = { + ...existing, + ...snapshot, + lastSeenAt: this.options.clock.now(), + }; + this.#workers.set(workerId, next); + this.#warnOnLowerMaxTtl(existing, next); + this.#notifyViewsChanged(); + } + + /** + * ADR 0005 §15: the gateway's own `lease.maxTtlMs` decides a fleet lease's width at + * admission, before any worker is chosen -- but what the gateway dispatches is an ordinary + * `lease.request`, so a worker whose own cap is lower still refuses a request the gateway + * already accepted. That mismatch becomes visible the moment this worker's `config.get` + * answer lands in its view (`WorkerLink#rebuildView`), which is exactly where it is reported + * here -- as a log line, not a bus event: an operator configuration warning is not a business + * fact about the fleet (`docs/agent-rules/events.md`), the same reasoning `core/config.ts` + * already applies to a worker-only key left in a gateway's config. + * + * Warned on the transition into the mismatched state (or a change while inside it), never on + * an unchanged refresh: `config.get` is re-read on every periodic backstop tick alongside the + * catalog, and a worker whose reported cap has not moved must not repeat this warning every + * `refreshIntervalMs`. Comparing the incoming cap against the *previous* view's own gives that + * for free, with no extra state to track: a worker's first refresh after connecting has no + * previous `lease.maxTtlMs` to match, so it warns the moment a low cap is first reported; a + * later refresh reporting the identical cap finds `previous.lease?.maxTtlMs` already equal to + * it and says nothing new. + */ + #warnOnLowerMaxTtl(previous: WorkerView, next: WorkerView): void { + const workerMaxTtlMs = next.lease?.maxTtlMs; + // No cap reported (an incompatible worker, a failed config.get, or one older than this + // field) is not a fact to warn about -- there is nothing to compare. + if (workerMaxTtlMs === undefined || workerMaxTtlMs >= this.options.leaseMaxTtlMs) return; + if (previous.lease?.maxTtlMs === workerMaxTtlMs) return; + this.#logger.warn( + "Worker's lease.maxTtlMs is below this gateway's own cap; requests the gateway accepts up to its own cap will be refused by this worker", + { + gatewayMaxTtlMs: this.options.leaseMaxTtlMs, + workerId: next.id, + workerMaxTtlMs, + ...(next.label === undefined ? {} : { label: next.label }), + }, + ); + } + + /** + * ADR 0005 §6: the uplink is the reachability signal, and a closed one does not delete + * anything. The view keeps its last-known state -- capacity, devices, and above all the + * leases the worker still holds -- until retention elapses or an operator removes it. + */ + disconnected(workerId: string): void { + const existing = this.#workers.get(workerId); + if (existing === undefined || existing.connection === "disconnected") return; + this.#workers.set(workerId, { + ...existing, + connection: "disconnected", + lastSeenAt: this.options.clock.now(), + }); + this.options.eventBus.emit( + "worker.disconnected", + { + leaseCount: existing.leases.length, + workerId, + ...(existing.label === undefined ? {} : { label: existing.label }), + }, + "gateway", + ); + this.#notifyViewsChanged(); + } + + /** + * ADR 0005 §9. Idempotent by design: draining an already-drained worker succeeds and emits + * nothing, because nothing changed and an event is a fact about a change. An operator + * re-running a command should not have to care, and neither should a script. + * + * Persisted before it returns (Decision 3): the point of drain is that a machine stays out of + * rotation across the reconnect an operator is about to cause by working on it. + */ + async setDrained(workerId: string, drained: boolean): Promise { + const existing = this.#requireView(workerId); + if (existing.drained === drained) return existing; + const view: WorkerView = { ...existing, drained }; + this.#workers.set(workerId, view); + if (drained) this.#drained.add(workerId); + else this.#drained.delete(workerId); + await this.options.drainStore?.save([...this.#drained]); + this.options.eventBus.emit( + drained ? "worker.drain-started" : "worker.drain-ended", + { workerId, ...(existing.label === undefined ? {} : { label: existing.label }) }, + "gateway", + ); + this.#notifyViewsChanged(); + return view; + } + + /** + * ADR 0005 §8: forgets a disconnected worker's view. A connected one is refused -- + * `worker.remove` on a live worker would forget a machine that announces itself again on its + * very next frame, which is a confusing no-op rather than an operator action. An + * `incompatible` worker counts as connected for this rule: its uplink is open, and removing + * it would do just as little. + * + * Hardening: a drain flag can outlive its view -- `pruneExpired`'s retention sweep + * deliberately does not clear it (C1: only an explicit `undrain` should end a drain), so a + * worker that drops off and ages out of retention while still drained leaves `#drained` + * holding an id with nothing left to view. Neither `setDrained` nor `undrain` can reach it at + * that point (`#requireView` throws `UNKNOWN_WORKER`), which is exactly M1's "unbounded file" + * relocated rather than closed: nothing could ever clear that flag again, short of editing + * `workers.json` by hand. `remove` on that same id is the one command already documented as + * "no view to forget is fine" (`removed: false`) -- letting it also clear a leftover flag, + * still answering `removed: false`, is what actually closes the file rather than moving the + * leak. + */ + async remove(workerId: string): Promise { + const existing = this.#workers.get(workerId); + if (existing === undefined) { + if (this.#drained.delete(workerId)) { + await this.options.drainStore?.save([...this.#drained]); + } + // Unlike drain, an id with no view is not an error: "forget this worker" is already true + // of one the gateway has never heard of or has already retired, so it is an outcome to + // report (`removed: false`) rather than a failure to raise. + return false; + } + if (existing.connection !== "disconnected") { + throw new DispatchError( + "WORKER_CONNECTED", + `Worker ${workerId} is still connected; drain it and wait for it to disconnect, or stop it first`, + { workerId }, + ); + } + await this.#forget(existing, "operator", { clearDrain: true }); + return true; + } + + /** + * ADR 0005 §6's retention sweep, run from the gateway's periodic tick. Two conditions, both + * required: + * + * 1. every *gateway-issued* lease the view still shows has passed its deadline -- a lease + * this gateway granted with time left on it is a device still held on a machine that went + * away, which is exactly what an operator must be able to see, however long ago it went. + * Once the last deadline passes, the worker's own TTL has reclaimed everything (or will + * the moment it comes back), so the view is only history. A worker's own *local* lease is + * none of this gateway's business (§14): scoping by the `gw::` prefix it + * stamps on everything it forwards is what keeps a machine serving only local agents from + * being held here forever (M2) -- without it, `remove` on such a worker would still work + * (it only checks `connection`), but this sweep would never volunteer to do the same; + * 2. and the view has been disconnected for longer than + * `gateway.disconnectedRetentionMs`. + * + * Deadlines, not just "any lease": a worker that dropped off months ago with leases recorded + * would otherwise be kept forever by leases that expired minutes after it left. + * + * H3, `safety.md`'s fails-closed instinct: a registry built with no `gatewayRequesterPrefix` + * cannot tell a gateway-issued lease from a worker-local one, so it must not guess "none of + * these are mine" -- that would prune a view out from under live gateway leases just because + * the option was left off. Treat a missing prefix as "every unexpired lease counts", i.e. + * hold the view, rather than as "no lease counts". + */ + async pruneExpired(): Promise { + const now = this.options.clock.now(); + const cutoff = now - this.options.retentionMs; + const prefix = this.options.gatewayRequesterPrefix; + const expired = this.views().filter( + (view) => + view.connection === "disconnected" && + view.lastSeenAt <= cutoff && + !view.leases.some( + (lease) => + lease.ttlDeadline > now && + (prefix === undefined || lease.requesterId.startsWith(prefix)), + ), + ); + for (const view of expired) await this.#forget(view, "retention", { clearDrain: false }); + } + + /** + * M1: on an operator `remove`, also clears this worker's drain flag and re-saves the store, if + * it had one. Without this, a removed worker's `true` survives in `workers.json` forever -- an + * unbounded file that silently re-drains the machine if its id is ever seen again, with + * `undrain` unable to clear it in the meantime (`UNKNOWN_WORKER`, since there is no view to + * undrain). "Forgotten" has to mean forgotten, not "forgotten except the one flag that matters + * most." + * + * C1: the retention sweep must NOT clear the drain flag. Retention forgetting the *view* is + * not an operator action -- ADR 0005 §9 says only `undrain` ends a drain, and §8a keeps + * `#drained` a separate record from the observed view precisely so a drain outlives it. A + * drained worker that goes quiet past `disconnectedRetentionMs` must still rejoin drained. + */ + async #forget( + view: WorkerView, + reason: "operator" | "retention", + { clearDrain }: { clearDrain: boolean }, + ): Promise { + this.#workers.delete(view.id); + if (clearDrain && this.#drained.delete(view.id)) { + await this.options.drainStore?.save([...this.#drained]); + } + this.options.eventBus.emit( + "worker.removed", + { reason, workerId: view.id, ...(view.label === undefined ? {} : { label: view.label }) }, + "gateway", + ); + this.#notifyViewsChanged(); + } + + #requireView(workerId: string): WorkerView { + const view = this.#workers.get(workerId); + if (view === undefined) { + throw new DispatchError("UNKNOWN_WORKER", `Unknown worker: ${workerId}`, { workerId }); + } + return view; + } +} diff --git a/src/http/app.test.ts b/src/http/app.test.ts index 8ea29a5e7..a750ccb37 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -1154,3 +1154,132 @@ describe("hardening from review", () => { expect(body.lease.ttlMs).toBe(123_000); }); }); + +/** + * 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. + */ +describe("worker routes (gateway mode)", () => { + 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 }); + + // 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); + }); + + it("GET /v1/workers returns the views", async () => { + const { app, dispatcher } = gatewayHarness(); + dispatcher.handlers["worker.list"] = () => ({ + workers: [ + { + catalog: [], + connection: "connected", + devices: [], + drained: false, + id: "wrk_1", + lastSeenAt: 1, + leases: [], + }, + ], + }); + + const response = await app.request("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/v1/workers", { headers: operatorAuth }); + + expect(response.status).toBe(200); + expect(await response.json()).toMatchObject({ workers: [{ id: "wrk_1" }] }); + }); + + it("maps drain, undrain and remove onto their operations, with the id from the path", async () => { + const { app, dispatcher } = gatewayHarness(); + dispatcher.handlers["worker.drain"] = (input: never) => ({ + drained: true, + workerId: (input as { workerId: string }).workerId, + }); + dispatcher.handlers["worker.undrain"] = (input: never) => ({ + drained: false, + workerId: (input as { workerId: string }).workerId, + }); + dispatcher.handlers["worker.remove"] = (input: never) => ({ + removed: true, + workerId: (input as { workerId: string }).workerId, + }); + + const drained = await app.request("/v1/workers/wrk_1/drain", { + headers: operatorAuth, + method: "POST", + }); + expect(await drained.json()).toEqual({ drained: true, workerId: "wrk_1" }); + const undrained = await app.request("/v1/workers/wrk_1/drain", { + headers: operatorAuth, + method: "DELETE", + }); + expect(await undrained.json()).toEqual({ drained: false, workerId: "wrk_1" }); + const removed = await app.request("/v1/workers/wrk_2", { + headers: operatorAuth, + method: "DELETE", + }); + expect(await removed.json()).toEqual({ removed: true, workerId: "wrk_2" }); + + expect(dispatcher.calls.map((call) => call.operation)).toEqual([ + "worker.drain", + "worker.undrain", + "worker.remove", + ]); + }); + + it("leaves the role check to the shared dispatcher, which 403s an agent token", async () => { + const { app, dispatcher } = gatewayHarness(); + dispatcher.handlers["worker.list"] = () => { + throw new DispatchError("FORBIDDEN", "Operation worker.list requires role admin"); + }; + + const response = await app.request("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/v1/workers", { headers: agentAuth }); + + expect(response.status).toBe(403); + }); + + it("puts a refusal's typed details in the body, so a client need not parse prose", async () => { + const { app, dispatcher } = gatewayHarness(); + dispatcher.handlers["worker.remove"] = () => { + throw new DispatchError("WORKER_CONNECTED", "Worker wrk_1 is still connected", { + workerId: "wrk_1", + }); + }; + + const response = await app.request("/v1/workers/wrk_1", { + headers: operatorAuth, + method: "DELETE", + }); + + expect(response.status).toBe(409); + expect(await response.json()).toEqual({ + error: { code: "WORKER_CONNECTED", message: expect.any(String), workerId: "wrk_1" }, + }); + }); + + it("answers 501 for an operation a gateway does not implement", async () => { + const { app, dispatcher } = gatewayHarness(); + dispatcher.handlers["lease.request"] = () => { + throw new DispatchError( + "UNSUPPORTED_IN_GATEWAY_MODE", + "lease.request is not available on a gateway yet", + { operation: "lease.request" }, + ); + }; + + const response = await postLeaseRequest(app, defaultBody); + + expect(response.status).toBe(501); + expect(await response.json()).toMatchObject({ + error: { code: "UNSUPPORTED_IN_GATEWAY_MODE", operation: "lease.request" }, + }); + }); +}); diff --git a/src/http/app.ts b/src/http/app.ts index 8caf15e6e..e98239901 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -496,6 +496,48 @@ 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")))), + ); + + 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", 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"); const sinceTs = since === undefined ? undefined : deps.clock.now() - parseDuration(since); diff --git a/src/http/auth.test.ts b/src/http/auth.test.ts index 21e7972ce..5d2f40d35 100644 --- a/src/http/auth.test.ts +++ b/src/http/auth.test.ts @@ -70,4 +70,17 @@ describe("requireAuth", () => { identity: { requesterId: "tok_op", role: "operator" }, }); }); + + it("403s a worker join token: it can open an uplink and nothing else (ADR 0005 §25)", async () => { + const tokens = new FakeTokens(); + tokens.register("slk_join", { requesterId: "tok_join", role: "worker" }); + const response = await appWithAuth(tokens).request("/resource", { + headers: { authorization: "Bearer slk_join" }, + }); + // 403, not 401: the token is real and was recognized, it just has no authority here. + expect(response.status).toBe(403); + expect(await response.json()).toEqual({ + error: { code: "FORBIDDEN", message: expect.any(String) }, + }); + }); }); diff --git a/src/http/auth.ts b/src/http/auth.ts index 893aec6dc..b354cccd8 100644 --- a/src/http/auth.ts +++ b/src/http/auth.ts @@ -1,6 +1,6 @@ import type { Context, MiddlewareHandler, Next } from "hono"; -import { unauthenticated } from "./errors.js"; +import { forbidden, unauthenticated } from "./errors.js"; import type { TokenIdentity } from "./token-store.js"; export interface AuthEnv { @@ -30,6 +30,15 @@ function extractSecret(header: string | undefined): string | undefined { * `Dispatcher`'s role check and `authorize` hook (see `dispatcher-session.ts`) -- the same * checks the socket path runs, not a second HTTP-only copy. A route still needs *an* identity * to build the `DispatchSession` `dispatch()` takes, which is what this middleware supplies. + * + * The one role decision that *does* live here is ADR 0005 §25's: a `worker`-role join token is + * `403` on every `/v1` route. It is not a role gate of the kind that moved to the dispatcher -- + * those compare an operation's required role to a session's. This is narrower and belongs at + * the transport: a join token authorizes one transport (the uplink upgrade, see + * `src/ports/uplink.ts`) and no operation at all, so there is no session to build from it and + * nothing further down the stack could tell the difference between it and an agent token. + * Refusing it here, before a `DispatchSession` exists, is what makes "it can open an uplink and + * nothing else" true rather than aspirational. */ export function requireAuth(tokens: TokenVerifier): MiddlewareHandler { return async (c: Context, next: Next) => { @@ -38,6 +47,11 @@ export function requireAuth(tokens: TokenVerifier): MiddlewareHandler { const identity = await tokens.verify(secret); if (identity === undefined) throw unauthenticated("Unknown bearer token"); + // 403, not 401: the token is real and was recognized -- it simply has no authority here + // (ADR 0005 §25). + if (identity.role === "worker") { + throw forbidden("A worker join token can only open an uplink, not call the HTTP API"); + } c.set("identity", identity); await next(); diff --git a/src/http/errors.test.ts b/src/http/errors.test.ts index 56226d3d8..6bfbce23b 100644 --- a/src/http/errors.test.ts +++ b/src/http/errors.test.ts @@ -12,7 +12,11 @@ import { UnknownModelError, } from "../core/index.js"; import { classifyError, StartupFailedError } from "../daemon/error-code.js"; -import { DoctorUnavailableError, NukeUnavailableError } from "../daemon/dispatcher.js"; +import { + DispatchError, + DoctorUnavailableError, + NukeUnavailableError, +} from "../daemon/dispatcher.js"; import { ERROR_TABLE } from "../contract/index.js"; import { ExecOutputDeliveryStalledError } from "../ports/index.js"; import { @@ -112,6 +116,28 @@ describe("mapError", () => { it("collapses a non-Error thrown value the same way", () => { expect(mapError("boom")).toEqual({ code: "INTERNAL", message: "Internal error", status: 500 }); }); + + it("forwards a DispatchError's details for a code the contract declares one for", () => { + const mapped = mapError( + new DispatchError("WORKER_CONNECTED", "already connected", { + workerId: "wrk_1", + }), + ); + expect(mapped).toMatchObject({ code: "WORKER_CONNECTED", extra: { workerId: "wrk_1" } }); + }); + + // Hardening: `DispatchError.details` is `unknown` -- nothing at the type level stops a + // handler from attaching an object to a code `ErrorDetailsMap` declares as + // `Record` (no details at all). Before this fix, `mapError`'s only gate was + // "is `.details` object-shaped", which this would have passed straight through onto the + // wire; `CODES_WITH_DECLARED_DETAILS` is what `BAD_REQUEST` is deliberately absent from. + it("does not forward a DispatchError's details for a code the contract declares none for", () => { + const mapped = mapError( + new DispatchError("BAD_REQUEST", "malformed", { internal: "should never reach the wire" }), + ); + expect(mapped).toEqual({ code: "BAD_REQUEST", message: "malformed", status: 400 }); + expect(mapped).not.toHaveProperty("extra"); + }); }); describe("errorResponse", () => { diff --git a/src/http/errors.ts b/src/http/errors.ts index 9f6c0a8fe..8a44fd4d5 100644 --- a/src/http/errors.ts +++ b/src/http/errors.ts @@ -3,13 +3,19 @@ import type { Context } from "hono"; import { RequestCancelledError, RequesterAlreadyLeasedError } from "../core/index.js"; import { classifyError } from "../daemon/error-code.js"; import { DispatchError } from "../daemon/dispatcher.js"; -import { ERROR_TABLE, type SimlockErrorCode } from "../contract/index.js"; +import { + CODES_WITH_DECLARED_DETAILS, + ERROR_TABLE, + type SimlockErrorCode, +} from "../contract/index.js"; -/** Every status this gateway ever answers with; keeps `mapError` exhaustive by construction. - * 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 gateway was waiting on never - * finished, which is exactly what a gateway timeout says. */ -export type HttpStatus = 400 | 401 | 403 | 404 | 409 | 422 | 500 | 503 | 504; +/** 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 + * `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. */ +export type HttpStatus = 400 | 401 | 403 | 404 | 409 | 422 | 500 | 501 | 503 | 504; /** * Uniform `{status, code}` pair a route or middleware raises directly (auth, ownership, @@ -131,7 +137,16 @@ export function mapError(error: unknown): MappedError { const extra = error instanceof RequesterAlreadyLeasedError && error.existingLeaseId !== undefined ? { existingLeaseId: error.existingLeaseId } - : undefined; + : // ADR 0003 §7: `details` are contract, message text is not -- so a `DispatchError` + // carrying them (`WORKER_CONNECTED`'s `workerId`, + // `UNSUPPORTED_IN_GATEWAY_MODE`'s `operation`) puts them in the response body, where a + // client can branch on them instead of parsing prose. Hardening: gated on `code` being + // one `ErrorDetailsMap` actually declares a shape for, not merely on `.details` being + // object-shaped -- `DispatchError.details` is `unknown`, so nothing before this stopped + // a handler from attaching an object to a code the contract says carries none. + CODES_WITH_DECLARED_DETAILS.has(code) && isDetailsObject(error) + ? error.details + : undefined; return { status: entry.httpStatus as HttpStatus, code: entry.code, @@ -140,6 +155,18 @@ export function mapError(error: unknown): MappedError { }; } +/** A `DispatchError` whose `details` are a plain object worth putting on the wire. */ +function isDetailsObject(error: unknown): error is DispatchError & { + readonly details: Record; +} { + return ( + error instanceof DispatchError && + typeof error.details === "object" && + error.details !== null && + !Array.isArray(error.details) + ); +} + /** Writes `mapError`'s result as the standard `{"error":{...}}` body, plus `Retry-After` for NO_CAPACITY. */ export function errorResponse(c: Context, error: unknown): Response { const mapped = mapError(error); diff --git a/src/http/server.ts b/src/http/server.ts index f54d95807..7c10ee9bc 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -9,6 +9,15 @@ export interface HttpGatewayOptions { readonly host: string; readonly port: number; readonly logger: Logger; + /** + * Called once, with the Node HTTP server, as soon as it exists (before it is listening). + * ADR 0005 §4 puts the worker uplink on this same listener -- upgraded on `/v1/uplink` -- so + * that the whole fleet has exactly one inbound port. The uplink adapter needs the server's + * `upgrade` event to do that, and this is the only thing it needs; handing it the server + * here keeps `HttpGateway` from growing any knowledge of WebSockets, uplinks, or workers. + * Undefined on a worker, which upgrades nothing. + */ + readonly onServerCreated?: (server: Server) => void; } /** @@ -42,6 +51,7 @@ export class HttpGateway { readonly #port: number; readonly #logger: Logger; readonly #sockets = new Set(); + readonly #onServerCreated: ((server: Server) => void) | undefined; #server: Server | undefined; constructor(app: FetchApp, options: HttpGatewayOptions) { @@ -49,6 +59,7 @@ export class HttpGateway { this.#host = options.host; this.#port = options.port; this.#logger = options.logger; + this.#onServerCreated = options.onServerCreated; } /** Resolves once listening, with the actual bound port (matches the configured one in v1, since port 0 is never used here). */ @@ -76,6 +87,10 @@ export class HttpGateway { socket.once("close", () => this.#sockets.delete(socket)); }); this.#server = server; + // Before `listening` fires deliberately: an upgrade cannot arrive until the server is + // listening, and wiring it here means there is no window where a connection is accepted + // with no `upgrade` handler attached. + this.#onServerCreated?.(server); }); } diff --git a/src/http/test-fakes.ts b/src/http/test-fakes.ts index 491e8bf60..68fadb5c7 100644 --- a/src/http/test-fakes.ts +++ b/src/http/test-fakes.ts @@ -8,9 +8,13 @@ import type { TokenIdentity } from "./token-store.js"; const gibibyte = 1024 * 1024 * 1024; /** Shared config fixture; every field `Config` currently declares (see `src/core/config.ts`). */ -export function testConfig(overrides: Partial = {}): Config { +export function testConfig( + overrides: Partial = {}, + mode: Config["mode"] = "worker", +): Config { return { - mode: "worker", + mode, + gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, drivers: {}, capacity: { strategy: "resource", diff --git a/src/http/token-store.ts b/src/http/token-store.ts index 13f16afc4..d5e489c80 100644 --- a/src/http/token-store.ts +++ b/src/http/token-store.ts @@ -2,7 +2,21 @@ import { dirname } from "node:path"; import type { Clock, Filesystem, IdGenerator, TokenSecrets } from "../ports/index.js"; -export type TokenRole = "agent" | "operator"; +/** + * ADR 0003 §5 (`agent`, `operator`) plus ADR 0005 §8/§25's `worker`: a *join token*, minted on + * a gateway with `simlock token create --role worker` and presented by a worker when it opens + * its uplink. It authorizes exactly one thing -- opening an uplink -- and nothing else: the + * HTTP bearer adapter answers `403` for a `worker` token on any `/v1` route (`auth.ts`), and + * it resolves to no daemon session role at all. Revoking it closes the uplink (ADR 0005 §8): + * `GatewayDispatcher#tokenRevoke` closes every link the revoked token authenticated + * (`GatewayService#closeLinksForToken`), so the effect is immediate rather than waiting on that + * worker's next reconnect. + */ +export type TokenRole = "agent" | "operator" | "worker"; + +/** The same three values as a list, for `isTokenRole`'s membership check -- one branch there + * instead of one per role. Module-private: `TokenRole` is the exported vocabulary. */ +const TOKEN_ROLES: readonly TokenRole[] = ["agent", "operator", "worker"]; export interface TokenRecord { readonly id: string; @@ -53,6 +67,7 @@ export class TokenStore { this.#path = options.path; } + // fallow-ignore-next-line unused-class-member -- called by `Dispatcher`'s `token.create` handler through `#requireTokens()`'s return value (src/daemon/dispatcher.ts); the audit does not follow a member access on a method's result. async create(role: TokenRole, label?: string): Promise<{ record: TokenRecord; secret: string }> { const secret = this.#secrets.generateSecret(); const record: TokenRecord = { @@ -74,6 +89,7 @@ export class TokenStore { return this.#readAll(); } + // fallow-ignore-next-line unused-class-member -- same as `create` above: reached through `#requireTokens()`'s return value. async revoke(id: string): Promise { const records = await this.#readAll(); const index = records.findIndex((record) => record.id === id); @@ -130,12 +146,16 @@ function isTokenRecord(value: unknown): value is TokenRecord { return ( typeof record.id === "string" && typeof record.hash === "string" && - (record.role === "agent" || record.role === "operator") && + isTokenRole(record.role) && (record.label === undefined || typeof record.label === "string") && typeof record.createdAt === "number" ); } +function isTokenRole(value: unknown): value is TokenRole { + return typeof value === "string" && (TOKEN_ROLES as readonly string[]).includes(value); +} + function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); } diff --git a/src/ports/index.ts b/src/ports/index.ts index 91b6190a7..0932b902f 100644 --- a/src/ports/index.ts +++ b/src/ports/index.ts @@ -20,6 +20,27 @@ export type { IpcErrorCode } from "./ipc.js"; // fallow-ignore-next-line unused-type -- public listener lifecycle contract. export type { IpcListener } from "./ipc.js"; export { type Clock, FakeClock, SystemClock, type TimerHandle } from "./clock.js"; +/** + * ADR 0005 §33's uplink port and its in-memory adapter. The WebSocket adapters are + * deliberately *not* re-exported here: they live in `./uplink-websocket.js`, the one module + * that imports `ws`, and only the daemon entrypoint needs them -- so the CLI and the MCP + * server, which import this barrel, never load a WebSocket implementation they never use. + */ +export { + createConnectionPair, + MemoryUplinkTransport, + uplinkOutcome, + UplinkError, + type AcceptedUplink, + type UplinkAuthOutcome, + type UplinkAuthResult, + type UplinkConnector, + type UplinkDialOptions, + type UplinkListener, + type UplinkListenerFactory, +} from "./uplink.js"; +// fallow-ignore-next-line unused-type -- public port contract for consumers that branch on why a dial failed. +export type { UplinkErrorCode } from "./uplink.js"; export { JsonLinesLogger, type LogLevel, diff --git a/src/ports/ipc.ts b/src/ports/ipc.ts index 965049f98..cfc73074f 100644 --- a/src/ports/ipc.ts +++ b/src/ports/ipc.ts @@ -189,6 +189,27 @@ export class MemoryIpcTransport implements IpcConnector, IpcListenerFactory { } } +/** + * Adds `listener` to `listeners` and returns the unsubscribe every `on*` method on + * `IpcConnection` hands back. + * + * Three lines, but written out per event per implementation it was nine copies of the same + * add-then-delete dance across the in-memory transport, the paired connection behind the + * uplink port, and the WebSocket adapter -- and the dance is all they shared, since what + * differs between those classes is what *emits*, never how one subscribes. Set-backed + * implementations only: `NodeIpcConnection` above delegates to the socket's own + * `EventEmitter`, which already owns this bookkeeping. + */ +export function subscribeListener( + listeners: Set, + listener: Listener, +): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + class MemoryIpcConnection implements IpcConnection { readonly #closeListeners = new Set<() => void>(); readonly #dataListeners = new Set<(chunk: string) => void>(); @@ -205,18 +226,15 @@ class MemoryIpcConnection implements IpcConnection { } onData(listener: (chunk: string) => void): () => void { - this.#dataListeners.add(listener); - return () => this.#dataListeners.delete(listener); + return subscribeListener(this.#dataListeners, listener); } onClose(listener: () => void): () => void { - this.#closeListeners.add(listener); - return () => this.#closeListeners.delete(listener); + return subscribeListener(this.#closeListeners, listener); } onError(listener: (error: Error) => void): () => void { - this.#errorListeners.add(listener); - return () => this.#errorListeners.delete(listener); + return subscribeListener(this.#errorListeners, listener); } async write(contents: string): Promise { diff --git a/src/ports/uplink-websocket.test.ts b/src/ports/uplink-websocket.test.ts new file mode 100644 index 000000000..3f4880fac --- /dev/null +++ b/src/ports/uplink-websocket.test.ts @@ -0,0 +1,107 @@ +/** + * P3: `WebSocketUplinkListenerFactory#handleUpgrade` reads `x-simlock-worker-id` and the + * URI-decoded `x-simlock-worker-label` *before* `authenticate` runs -- so anyone who can reach + * the gateway's HTTP port, with no credential at all, can make it claim an arbitrary worker id + * and a label up to Node's header budget (~16 KB). Both reach `authenticate`'s `claimed` + * argument regardless of the outcome, and a refusal still emits `worker.rejected` on the + * gateway's bus with them attached (`GatewayService`/`WorkerRegistry`, exercised elsewhere) -- + * this file is the one place that can drive a real HTTP upgrade with attacker-shaped headers and + * observe what actually reaches that boundary, unauthenticated. + * + * A real `http.Server` and the real `ws` library on both ends, not a hand-built + * `IncomingMessage` -- `#handleUpgrade` is private, and a header this large or this shaped is + * exactly the kind of thing worth proving survives an actual HTTP round trip rather than a + * fabricated request object. + */ +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; + +import { afterEach, describe, expect, it } from "vitest"; + +import type { ClaimedUplinkIdentity, UplinkAuthOutcome } from "./uplink.js"; +import { WebSocketUplinkConnector, WebSocketUplinkListenerFactory } from "./uplink-websocket.js"; + +let server: Server | undefined; + +afterEach(async () => { + if (server === undefined) return; + await new Promise((resolve) => server?.close(() => resolve())); + server = undefined; +}); + +/** Starts a real gateway-side listener whose `authenticate` always refuses (recording every + * `claimed` it was handed) and returns the base URL to dial it at. */ +async function startRefusingGateway(): Promise<{ + url: string; + claims: ClaimedUplinkIdentity[]; +}> { + const claims: ClaimedUplinkIdentity[] = []; + const factory = new WebSocketUplinkListenerFactory(); + await factory.listen({ + authenticate: (_credential, claimed): Promise => { + claims.push(claimed); + return Promise.resolve("unauthenticated"); + }, + accept: () => { + throw new Error("this gateway never accepts"); + }, + }); + server = createServer((_request, response) => { + response.writeHead(404).end(); + }); + factory.attach(server); + await new Promise((resolve) => server?.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as AddressInfo; + return { claims, url: `ws://127.0.0.1:${port}` }; +} + +/** Dials with no credential the gateway will accept, and swallows the resulting refusal -- every + * test here is about what `authenticate` was handed, not about the connection succeeding. */ +async function dialAndIgnoreRefusal(url: string, workerId: string, label?: string): Promise { + await new WebSocketUplinkConnector() + .connect({ token: "irrelevant", url, workerId, ...(label === undefined ? {} : { label }) }) + .catch(() => undefined); +} + +describe("WebSocketUplinkListenerFactory / P3", () => { + it("truncates an over-long claimed workerId before authenticate ever sees it", async () => { + const { claims, url } = await startRefusingGateway(); + const longId = "w".repeat(10_000); + + await dialAndIgnoreRefusal(url, longId); + + expect(claims).toHaveLength(1); + expect(claims[0]?.workerId).toHaveLength(128); + expect(claims[0]?.workerId).toBe(longId.slice(0, 128)); + }); + + it("truncates an over-long claimed label the same way", async () => { + const { claims, url } = await startRefusingGateway(); + const longLabel = "mac-mini-".repeat(100); + + await dialAndIgnoreRefusal(url, "wrk_1", longLabel); + + expect(claims).toHaveLength(1); + expect(claims[0]?.label).toHaveLength(128); + expect(claims[0]?.label).toBe(longLabel.slice(0, 128)); + }); + + it("drops a claimed label containing a control character instead of passing it through", async () => { + const { claims, url } = await startRefusingGateway(); + + // A worker's own label never contains one; an attacker's header can claim anything. + await dialAndIgnoreRefusal(url, "wrk_1", "mac-mini-evil\ntitle"); + + expect(claims).toHaveLength(1); + expect(claims[0]?.label).toBeUndefined(); + }); + + it("still accepts an ordinary short, printable label unchanged", async () => { + const { claims, url } = await startRefusingGateway(); + + await dialAndIgnoreRefusal(url, "wrk_1", "mac-mini-1"); + + expect(claims).toHaveLength(1); + expect(claims[0]).toEqual({ label: "mac-mini-1", workerId: "wrk_1" }); + }); +}); diff --git a/src/ports/uplink-websocket.ts b/src/ports/uplink-websocket.ts new file mode 100644 index 000000000..d84f87c32 --- /dev/null +++ b/src/ports/uplink-websocket.ts @@ -0,0 +1,369 @@ +/** + * The WebSocket adapters behind the uplink port (`./uplink.ts`) -- the one file in the tree + * that imports `ws`, kept out of the ports barrel so processes that never open an uplink (the + * CLI, the MCP server) never load it. + * + * Why `ws` at all: Node 22 ships a WebSocket *client* and no server, and its client cannot set + * request headers -- and the join token and the worker id both travel in headers at upgrade + * time (ADR 0005 §4). Both halves therefore use `ws`, pinned to an exact version in + * package.json. + * + * The gateway's half is deliberately `noServer: true`: the uplink lives on the gateway's + * *existing* HTTP listener, upgraded on `/v1/uplink`, so the whole fleet still has exactly one + * inbound port (ADR 0005 decision 1). Authentication happens at upgrade, before any WebSocket + * exists -- a request without a recognized `worker`-role bearer token gets a plain `401` and + * its socket destroyed, so an unauthenticated peer never reaches the daemon protocol. + */ +import type { IncomingMessage, Server } from "node:http"; +import type { Duplex } from "node:stream"; + +import { WebSocket, WebSocketServer, type RawData } from "ws"; + +import { subscribeListener, type IpcConnection } from "./ipc.js"; +import { + resolveUplinkUrl, + uplinkOutcome, + uplinkTokenId, + UPLINK_PATH, + UplinkError, + WORKER_ID_HEADER, + WORKER_LABEL_HEADER, + type UplinkConnector, + type UplinkDialOptions, + type UplinkHandlers, + type UplinkListener, + type UplinkListenerFactory, +} from "./uplink.js"; + +/** + * Wraps one WebSocket as the `IpcConnection` the daemon protocol expects. Each protocol frame + * is sent as its own text message; frames are already newline-terminated by `serializeFrame` + * and every reader buffers by newline, so a message boundary that does not line up with a + * frame boundary is harmless either way. + */ +class WebSocketUplinkConnection implements IpcConnection { + readonly #socket: WebSocket; + readonly #dataListeners = new Set<(chunk: string) => void>(); + readonly #closeListeners = new Set<() => void>(); + readonly #errorListeners = new Set<(error: Error) => void>(); + /** + * Frames that arrived before anything subscribed. A real socket buffers what is sent to it + * until someone reads; `ws` does not -- it emits `message` events, and one emitted with no + * listener attached is simply gone. + * + * That gap is not theoretical here, it is the normal case: over the uplink the *gateway* + * speaks first (ADR 0005 §5), so its `hello` can be delivered in the same tick as the + * WebSocket's `open` -- before the worker's `DaemonServer` has been handed the connection and + * subscribed. Losing it deadlocks the link: the gateway waits forever for a reply to a frame + * the worker never saw. Buffering until the first `onData` makes this adapter behave the way + * every other `IpcConnection` in the tree already does. + */ + readonly #pending: string[] = []; + #closed = false; + + constructor(socket: WebSocket) { + this.#socket = socket; + socket.on("message", (data: RawData, isBinary: boolean) => { + // Binary frames are not part of this protocol. Ignoring one is the same treatment + // `SimlockWire` gives a malformed line: a peer's bad frame is not this side's crash. + if (isBinary) return; + const chunk = Array.isArray(data) + ? Buffer.concat(data).toString("utf8") + : Buffer.isBuffer(data) + ? data.toString("utf8") + : Buffer.from(data as ArrayBuffer).toString("utf8"); + if (this.#dataListeners.size === 0) { + this.#pending.push(chunk); + return; + } + for (const listener of this.#dataListeners) listener(chunk); + }); + socket.on("close", () => this.#markClosed()); + socket.on("error", (error: Error) => { + for (const listener of this.#errorListeners) listener(error); + this.#markClosed(); + }); + } + + get closed(): boolean { + return this.#closed; + } + + onData(listener: (chunk: string) => void): () => void { + const unsubscribe = subscribeListener(this.#dataListeners, listener); + // Whatever arrived before anyone was listening is delivered to the first subscriber, in + // order, before it sees anything new -- see `#pending`. + if (this.#pending.length > 0) { + const buffered = this.#pending.splice(0); + for (const chunk of buffered) listener(chunk); + } + return unsubscribe; + } + + onClose(listener: () => void): () => void { + if (this.#closed) { + listener(); + return () => {}; + } + return subscribeListener(this.#closeListeners, listener); + } + + onError(listener: (error: Error) => void): () => void { + return subscribeListener(this.#errorListeners, listener); + } + + async write(contents: string): Promise { + if (this.#closed || this.#socket.readyState !== WebSocket.OPEN) return; + await new Promise((resolve) => { + // Resolving on the send callback (rather than fire-and-forget) keeps `write`'s contract + // the same as the unix-socket adapter's: the caller may await a frame actually leaving. + // A send error is not rethrown -- the `error` event above already reports it to every + // listener, and a rejected `write` would tear down a caller that has nothing to do + // about it. + this.#socket.send(contents, () => resolve()); + }); + } + + async close(): Promise { + if (this.#closed) return; + this.#socket.close(); + this.#markClosed(); + } + + #markClosed(): void { + if (this.#closed) return; + this.#closed = true; + for (const listener of this.#closeListeners) listener(); + } +} + +/** + * The gateway's half. `listen()` records the handlers; `attach(server)` wires the HTTP + * server's `upgrade` event. The split exists because the HTTP server is created after this + * factory (see `src/daemon/main.ts`), and a listener that silently did nothing until some + * other call arrived would be a worse contract than one that names the call that wires it. + */ +export class WebSocketUplinkListenerFactory implements UplinkListenerFactory { + readonly #server = new WebSocketServer({ noServer: true }); + #handlers: UplinkHandlers | undefined; + #detach: (() => void) | undefined; + + async listen(handlers: UplinkHandlers): Promise { + this.#handlers = handlers; + return { + close: async () => { + this.#handlers = undefined; + this.#detach?.(); + this.#detach = undefined; + await new Promise((resolve) => this.#server.close(() => resolve())); + }, + }; + } + + /** Wires this factory to a Node HTTP server's `upgrade` event. */ + attach(server: Server): void { + const onUpgrade = (request: IncomingMessage, socket: Duplex, head: Buffer) => { + void this.#handleUpgrade(request, socket, head); + }; + server.on("upgrade", onUpgrade); + this.#detach = () => { + server.off("upgrade", onUpgrade); + }; + } + + async #handleUpgrade(request: IncomingMessage, socket: Duplex, head: Buffer): Promise { + const handlers = this.#handlers; + if (handlers === undefined) { + // Nothing is listening for uplinks (a daemon mid-shutdown): refuse rather than leave the + // socket hanging half-upgraded. + respondAndDestroy(socket, 404, "Not Found"); + return; + } + if (!isUplinkPath(request.url)) { + // The gateway upgrades exactly one path. Anything else is a client that guessed, or an + // HTTP route someone tried to upgrade; either way it is not an uplink. + respondAndDestroy(socket, 404, "Not Found"); + return; + } + const rawWorkerId = headerValue(request, WORKER_ID_HEADER); + if (rawWorkerId === undefined) { + respondAndDestroy(socket, 400, "Bad Request"); + return; + } + // P3: truncated before anything else touches it, which bounds the *size* of a flood -- one + // claimed id or label, up to Node's header budget (~16 KB), times the ring buffer's capacity + // -- not the flood itself. Both fields below reach the gateway's event bus (`worker.rejected` + // on the refusal path below, and a real `worker.connected` past authentication) *before* any + // credential has been proven -- `GET /v1/uplink` needs no token to supply either -- and the + // bus does no payload validation of its own. The other half of the harm this guards against + // -- a loop of refused dials evicting every real fact an operator comes to `simlock events` + // for, including the very `worker.connected`/`worker.disconnected` lines explaining the + // outage they are debugging, since the buffer is bounded by count, not bytes -- is P-2's: + // `GatewayService#recordRejection` coalesces repeated refusals into one event per window. + const workerId = rawWorkerId.slice(0, MAX_CLAIMED_FIELD_LENGTH); + // Decoded before authentication, not after: a dial that fails the credential check still + // claimed this identity in its headers, and ADR 0005 §22's `worker.rejected` reports + // whatever a refused peer claimed rather than nothing at all. + const label = decodeLabel(headerValue(request, WORKER_LABEL_HEADER)); + const claimed = { workerId, ...(label === undefined ? {} : { label }) }; + let result: Awaited>; + try { + result = await handlers.authenticate(bearerToken(request), claimed); + } catch { + // A token store that cannot be read is not an authenticated peer. + result = "unauthenticated"; + } + const outcome = uplinkOutcome(result); + if (outcome !== "accept") { + // 403 for a real token of the wrong role, 401 for one the gateway does not know + // (ADR 0005 §25) -- the same distinction the HTTP frontend draws for a `worker` token on + // an ordinary `/v1` route, in the opposite direction. + if (outcome === "forbidden") respondAndDestroy(socket, 403, "Forbidden"); + else respondAndDestroy(socket, 401, "Unauthorized"); + return; + } + // C-2: the token record id that authorized this uplink, carried onto `AcceptedUplink` so a + // later `token.revoke` of it can find and close this exact link (ADR 0005 §8). + const tokenId = uplinkTokenId(result); + this.#server.handleUpgrade(request, socket, head, (client) => { + handlers.accept({ + connection: new WebSocketUplinkConnection(client), + workerId, + ...(label === undefined ? {} : { label }), + ...(tokenId === undefined ? {} : { tokenId }), + }); + }); + } +} + +/** The worker's half: dials `gateway.url` with the join token and its instance id. */ +export class WebSocketUplinkConnector implements UplinkConnector { + async connect(options: UplinkDialOptions): Promise { + // `options.url` is `gateway.url`, the gateway's base URL; the endpoint is this worker's to + // derive (ADR 0005 §4), so an operator configures one URL and never an internal path. + const socket = new WebSocket(resolveUplinkUrl(options.url), { + headers: { + authorization: `Bearer ${options.token}`, + [WORKER_ID_HEADER]: options.workerId, + ...(options.label === undefined + ? {} + : { [WORKER_LABEL_HEADER]: encodeURIComponent(options.label) }), + }, + }); + // Wrapped *before* awaiting `open`, not after: the gateway speaks first over an uplink, and + // its `hello` can be emitted in the same tick the socket opens. The wrapper's `message` + // listener has to be attached by then, or that frame is lost and the link deadlocks (see + // `WebSocketUplinkConnection#pending`). + const connection = new WebSocketUplinkConnection(socket); + try { + await waitForOpen(socket); + } catch (error: unknown) { + socket.terminate(); + throw error; + } + return connection; + } +} + +function waitForOpen(socket: WebSocket): Promise { + return new Promise((resolve, reject) => { + const onOpen = () => { + cleanup(); + resolve(); + }; + const onError = (error: Error) => { + cleanup(); + reject(toUplinkError(error)); + }; + // `ws` emits this instead of `error` when the handshake gets an HTTP response -- which is + // exactly what a refused join token looks like (401). Without it, a revoked token would be + // indistinguishable from an unreachable gateway in the worker's log. + const onUnexpectedResponse = (_request: unknown, response: IncomingMessage) => { + cleanup(); + const status = response.statusCode ?? 0; + reject( + new UplinkError( + status === 401 || status === 403 ? "rejected" : "unknown", + `The gateway refused the uplink with HTTP ${String(status)}`, + ), + ); + }; + const cleanup = () => { + socket.off("open", onOpen); + socket.off("error", onError); + socket.off("unexpected-response", onUnexpectedResponse); + }; + socket.on("open", onOpen); + socket.on("error", onError); + socket.on("unexpected-response", onUnexpectedResponse); + }); +} + +function toUplinkError(error: unknown): UplinkError { + if (error instanceof UplinkError) return error; + const code = (error as { code?: unknown } | undefined)?.code; + const unreachable = + code === "ECONNREFUSED" || + code === "ENOTFOUND" || + code === "EHOSTUNREACH" || + code === "ETIMEDOUT"; + return new UplinkError( + unreachable ? "unreachable" : "unknown", + error instanceof Error ? error.message : String(error), + error, + ); +} + +/** The upgrade request's path, compared without its query string. A request with no `url` at + * all (which Node's typings allow) is not the uplink. */ +function isUplinkPath(url: string | undefined): boolean { + if (url === undefined) return false; + const [path] = url.split("?"); + return path === UPLINK_PATH; +} + +function headerValue(request: IncomingMessage, name: string): string | undefined { + const value = request.headers[name]; + const first = Array.isArray(value) ? value[0] : value; + return first === undefined || first === "" ? undefined : first; +} + +function bearerToken(request: IncomingMessage): string | undefined { + const header = headerValue(request, "authorization"); + if (header === undefined || !header.startsWith("Bearer ")) return undefined; + const secret = header.slice("Bearer ".length).trim(); + return secret === "" ? undefined : secret; +} + +/** P3: how long a claimed `workerId` or decoded label is allowed to be before either reaches + * anything -- the event bus (`worker.rejected`, `worker.connected`), a view, or `workers.json`. + * Comfortably longer than any real hostname or label an operator would set, far short of the + * ~16 KB a raw header can carry. */ +const MAX_CLAIMED_FIELD_LENGTH = 128; + +/** Control characters (C0 and DEL), the one thing worth rejecting a label outright for rather + * than just truncating -- a raw header value the gateway's own JSON logging already renders + * safely (`writeResult` JSON-encodes; terminal escapes are not the concern here), but a + * multi-line or unreadable "machine name" in `simlock worker list` and `simlock events` is not + * something worth keeping even truncated. */ +// oxlint-disable-next-line no-control-regex -- matching control characters is the whole point. +const NON_PRINTABLE = /[\u0000-\u001f\u007f]/; + +function decodeLabel(value: string | undefined): string | undefined { + if (value === undefined) return undefined; + try { + const decoded = decodeURIComponent(value); + if (decoded === "" || NON_PRINTABLE.test(decoded)) return undefined; + // P3: truncated like `workerId` above, before it reaches the bus or a view -- see + // `MAX_CLAIMED_FIELD_LENGTH`'s comment for why. + return decoded.slice(0, MAX_CLAIMED_FIELD_LENGTH); + } catch { + // A label is cosmetic; a malformed encoding drops it rather than refusing the uplink. + return undefined; + } +} + +function respondAndDestroy(socket: Duplex, status: number, reason: string): void { + socket.write(`HTTP/1.1 ${String(status)} ${reason}\r\nConnection: close\r\n\r\n`); + socket.destroy(); +} diff --git a/src/ports/uplink.test.ts b/src/ports/uplink.test.ts new file mode 100644 index 000000000..22e01d0ff --- /dev/null +++ b/src/ports/uplink.test.ts @@ -0,0 +1,200 @@ +import { describe, expect, it, vi } from "vitest"; + +import { + createConnectionPair, + MemoryUplinkTransport, + resolveUplinkUrl, + UplinkError, +} from "./uplink.js"; +import type { AcceptedUplink } from "./uplink.js"; + +describe("createConnectionPair", () => { + it("delivers what one end writes to the other end's data listeners", async () => { + const [left, right] = createConnectionPair(); + const received: string[] = []; + right.onData((chunk) => received.push(chunk)); + + await left.write('{"id":1,"type":"hello"}\n'); + + expect(received).toEqual(['{"id":1,"type":"hello"}\n']); + }); + + it("closes both ends, whichever one is closed", async () => { + const [left, right] = createConnectionPair(); + const closed = vi.fn(); + right.onClose(closed); + + await left.close(); + + expect(left.closed).toBe(true); + expect(right.closed).toBe(true); + expect(closed).toHaveBeenCalledTimes(1); + }); + + it("fires an onClose listener attached after the close, rather than losing it", () => { + const [left, right] = createConnectionPair(); + void left.close(); + const closed = vi.fn(); + + right.onClose(closed); + + expect(closed).toHaveBeenCalledTimes(1); + }); + + it("buffers what is written before anyone is listening, then delivers it in order", async () => { + // A real socket buffers; this pair must too, or the uplink's very first frame is lost -- + // over an uplink the *gateway* speaks first, before the worker has handed the connection + // to its own server (ADR 0005 §5). + const [left, right] = createConnectionPair(); + await left.write("first\n"); + await left.write("second\n"); + + const received: string[] = []; + right.onData((chunk) => received.push(chunk)); + + expect(received).toEqual(["first\n", "second\n"]); + }); + + it("delivers the buffer only once, to the first reader", async () => { + const [left, right] = createConnectionPair(); + await left.write("first\n"); + const firstReader: string[] = []; + const secondReader: string[] = []; + + right.onData((chunk) => firstReader.push(chunk)); + right.onData((chunk) => secondReader.push(chunk)); + + expect(firstReader).toEqual(["first\n"]); + expect(secondReader).toEqual([]); + }); + + it("drops a write to a closed peer instead of throwing", async () => { + const [left, right] = createConnectionPair(); + const received: string[] = []; + right.onData((chunk) => received.push(chunk)); + await right.close(); + + await expect(left.write("frame\n")).resolves.toBeUndefined(); + expect(received).toEqual([]); + }); +}); + +describe("MemoryUplinkTransport", () => { + function transportWithListener( + authenticate: (token: string | undefined) => "accept" | "unauthenticated" | "forbidden", + ) { + const transport = new MemoryUplinkTransport(); + const accepted: AcceptedUplink[] = []; + return { + transport, + accepted, + listen: () => + transport.listen({ + accept: (uplink) => accepted.push(uplink), + authenticate: async (credential) => authenticate(credential), + }), + }; + } + + it("refuses to dial when no gateway is listening", async () => { + const transport = new MemoryUplinkTransport(); + + await expect( + transport.connect({ url: "ws://gateway/v1/uplink", token: "t", workerId: "wrk_1" }), + ).rejects.toMatchObject({ code: "unreachable" }); + }); + + it("hands the listener an accepted uplink carrying the worker id and label", async () => { + const harness = transportWithListener(() => "accept"); + await harness.listen(); + + const workerEnd = await harness.transport.connect({ + url: "ws://gateway/v1/uplink", + token: "join", + workerId: "wrk_1", + label: "mac-mini-1", + }); + + expect(harness.accepted).toHaveLength(1); + expect(harness.accepted[0]?.workerId).toBe("wrk_1"); + expect(harness.accepted[0]?.label).toBe("mac-mini-1"); + + // The two ends are wired to each other: the gateway sees what the worker writes. + const received: string[] = []; + harness.accepted[0]?.connection.onData((chunk) => received.push(chunk)); + await workerEnd.write("frame\n"); + expect(received).toEqual(["frame\n"]); + }); + + it("rejects a token the gateway does not recognize, and accepts nothing", async () => { + const harness = transportWithListener((token) => + token === "good" ? "accept" : "unauthenticated", + ); + await harness.listen(); + + await expect( + harness.transport.connect({ + url: "ws://gateway/v1/uplink", + token: "revoked", + workerId: "wrk_1", + }), + ).rejects.toMatchObject({ code: "rejected" }); + expect(harness.accepted).toEqual([]); + }); + + // M3: `worker.rejected`'s `workerId`/`label` are "whatever the connection claimed in its + // headers" (ADR 0005 §22) -- a rejected dial still claims an identity, even though nothing + // verifies it, and the gateway needs that claim passed through to report it. + it("passes what the dial claimed to authenticate, even when it is refused", async () => { + const transport = new MemoryUplinkTransport(); + const claims: Array<{ readonly workerId?: string; readonly label?: string }> = []; + await transport.listen({ + accept: () => { + throw new Error("must not accept a rejected dial"); + }, + authenticate: async (_credential, claimed) => { + claims.push(claimed); + return "unauthenticated"; + }, + }); + + await expect( + transport.connect({ + url: "ws://gateway/v1/uplink", + token: "bad", + workerId: "wrk_1", + label: "mac-mini-1", + }), + ).rejects.toMatchObject({ code: "rejected" }); + + expect(claims).toEqual([{ workerId: "wrk_1", label: "mac-mini-1" }]); + }); + + it("stops accepting once the listener is closed", async () => { + const harness = transportWithListener(() => "accept"); + const listener = await harness.listen(); + await listener.close(); + + await expect( + harness.transport.connect({ url: "ws://gateway/v1/uplink", token: "t", workerId: "wrk_1" }), + ).rejects.toBeInstanceOf(UplinkError); + }); +}); + +describe("resolveUplinkUrl", () => { + it("derives the uplink endpoint from a gateway's base URL", () => { + expect(resolveUplinkUrl("ws://127.0.0.1:4700")).toBe("ws://127.0.0.1:4700/v1/uplink"); + expect(resolveUplinkUrl("ws://127.0.0.1:4700/")).toBe("ws://127.0.0.1:4700/v1/uplink"); + }); + + it("leaves a URL that already names the endpoint alone", () => { + expect(resolveUplinkUrl("ws://127.0.0.1:4700/v1/uplink")).toBe("ws://127.0.0.1:4700/v1/uplink"); + }); + + it("keeps a sub-path a reverse proxy publishes the gateway under", () => { + expect(resolveUplinkUrl("wss://ci.example/simlock/")).toBe( + "wss://ci.example/simlock/v1/uplink", + ); + expect(resolveUplinkUrl("wss://ci.example/simlock")).toBe("wss://ci.example/simlock/v1/uplink"); + }); +}); diff --git a/src/ports/uplink.ts b/src/ports/uplink.ts new file mode 100644 index 000000000..985d0b36a --- /dev/null +++ b/src/ports/uplink.ts @@ -0,0 +1,304 @@ +/** + * The worker uplink, as a port (architecture rule 9; ADR 0005 §33: "the uplink is a port + * (`UplinkListenerFactory` on the gateway, `UplinkConnector` on the worker) with a WebSocket + * adapter, so tests script it in memory"). + * + * Two halves of one link: + * + * - **`UplinkConnector`** (worker side) dials `gateway.url` with the join token and the + * worker's instance id, and hands back a connection. + * - **`UplinkListenerFactory`** (gateway side) accepts an authenticated uplink and hands the + * daemon that same abstract connection. + * + * What travels over it is the existing daemon protocol -- the newline-delimited JSON frames + * `DaemonServer` and `SimlockWire` already speak -- which is why both halves traffic in + * `IpcConnection` rather than a WebSocket type of their own. That is the point of ADR 0005's + * decision 2 ("the uplink carries the existing contract"): the worker's own `DaemonServer` + * accepts the uplink as one more connection, and the gateway drives it with the same typed + * client a supervisor process uses over a unix socket. Neither end has a second vocabulary to + * learn, and an operation added to the contract works over the uplink for free. + * + * The direction is deliberately inverted relative to what the names suggest: the *worker* + * dials (so no worker needs an inbound port -- ADR 0005 decision 1), and over the resulting + * connection the *gateway* is the protocol client (§5). So `UplinkConnector.connect` returns + * the connection a `DaemonServer` will serve, and `UplinkListenerFactory.listen`'s `accept` + * hands out the connection a client will drive. + * + * This module holds the port and its in-memory adapter only. The WebSocket adapters live in + * `./uplink-websocket.ts`, which is the one file that imports `ws` -- kept out of the ports + * barrel so the CLI and the MCP server, which never open an uplink, never load it. + */ +import { subscribeListener, type IpcConnection } from "./ipc.js"; + +/** Header carrying the worker's instance identity (`instance.json`) at upgrade (ADR 0005 §3a, + * §4). A header rather than a query parameter so the id stays out of proxy access logs. */ +export const WORKER_ID_HEADER = "x-simlock-worker-id"; +/** Header carrying `gateway.label`, URI-encoded (it is free text and may be non-ASCII). */ +export const WORKER_LABEL_HEADER = "x-simlock-worker-label"; +/** + * The one route a `worker`-role join token may use (ADR 0005 §25), and the only path a gateway + * upgrades an uplink on: `GET /v1/uplink`. A worker's `gateway.url` is the gateway's *base* + * URL and this is derived from it -- see `resolveUplinkUrl` -- so an operator configures one + * URL rather than remembering an endpoint. + */ +export const UPLINK_PATH = "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/v1/uplink"; + +/** + * Derives the uplink endpoint from `gateway.url`. Resolved against the base rather than + * concatenated, so a gateway published under a sub-path by a reverse proxy + * (`wss://ci.example/simlock/`) lands on `wss://ci.example/simlock/v1/uplink` rather than at + * the host root. A base URL that already names the uplink path resolves to itself. + */ +export function resolveUplinkUrl(baseUrl: string): string { + if (new URL(baseUrl).pathname.endsWith(UPLINK_PATH)) return baseUrl; + const base = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`; + return new URL(UPLINK_PATH.slice(1), base).toString(); +} + +/** One accepted uplink: who opened it, and the frames it carries. */ +export interface AcceptedUplink { + /** The worker's instance id, from `WORKER_ID_HEADER`. */ + readonly workerId: string; + /** `gateway.label`, when the worker sent one. Display only. */ + readonly label?: string; + readonly connection: IpcConnection; + /** + * The join token record's own id, when `authenticate` reported one alongside `accept` + * (C-2, ADR 0005 §8: "revoking closes the uplink"). Recorded here so `GatewayService` can + * find every link opened with a given token and close it the moment `token.revoke` runs, + * rather than only at that worker's next reconnect. `undefined` for a caller that returns + * the bare `UplinkAuthOutcome` string -- every test that never exercises revocation. + */ + readonly tokenId?: string; +} + +export interface UplinkListener { + close(): Promise; +} + +/** + * What the gateway makes of the credential presented at upgrade (ADR 0005 §4/§25). Three + * outcomes, not two, because the difference is the difference between "who are you" and "you + * are not allowed here": + * + * - `accept` -- a token the gateway holds with role `worker`. + * - `unauthenticated` (`401`) -- no token, or one the gateway does not know. A revoked join + * token lands here, which is what closes an uplink after `simlock token revoke`. + * - `forbidden` (`403`) -- a real token of the wrong role. An `agent` or `operator` token is + * valid elsewhere and carries no authority here, exactly as a `worker` token carries none on + * any other `/v1` route. + */ +export type UplinkAuthOutcome = "accept" | "unauthenticated" | "forbidden"; + +/** + * `authenticate`'s actual return type: the bare outcome, or -- only on acceptance -- an object + * naming the token record that authorized it. The object form exists solely to carry `tokenId` + * to `AcceptedUplink` (C-2); a discriminated *addition* to the bare string rather than a new + * required shape, so every `authenticate` that has no token store to consult (every uplink test + * in the tree) keeps returning the plain string it always has. Read with `uplinkOutcome` and + * `uplinkTokenId` rather than switching on `typeof` at each call site. + */ +export type UplinkAuthResult = + | UplinkAuthOutcome + | { readonly outcome: "accept"; readonly tokenId: string }; + +/** The outcome out of an `UplinkAuthResult`, whichever form `authenticate` returned. */ +export function uplinkOutcome(result: UplinkAuthResult): UplinkAuthOutcome { + return typeof result === "string" ? result : result.outcome; +} + +/** The token id out of an `UplinkAuthResult`, or `undefined` when `authenticate` returned the + * bare outcome string (including every refusal, which never carries one). */ +export function uplinkTokenId(result: UplinkAuthResult): string | undefined { + return typeof result === "string" ? undefined : result.tokenId; +} + +/** What the dial *claims* about itself before authentication has run -- the worker id and label + * headers, present or not, regardless of whether the credential checks out. Passed to + * `authenticate` so a rejection can still name the peer it turned away (ADR 0005 §22: + * `worker.rejected`'s `workerId`/`label` are "whatever the connection claimed in its headers"). */ +export interface ClaimedUplinkIdentity { + readonly workerId?: string; + readonly label?: string; +} + +export interface UplinkHandlers { + /** + * Verifies the join token presented in the `Authorization: Bearer` header at upgrade time. + * Anything but `accept` answers its HTTP status and destroys the socket without ever + * completing the upgrade -- an unauthorized peer never reaches the daemon protocol at all. + * `claimed` is never itself trusted for anything but attribution on a refusal: a rejected + * dial proves no identity, so this is only what it *said*, not what it is. + */ + authenticate( + credential: string | undefined, + claimed: ClaimedUplinkIdentity, + ): Promise; + /** Called once per accepted uplink. */ + accept(uplink: AcceptedUplink): void; +} + +export interface UplinkListenerFactory { + listen(handlers: UplinkHandlers): Promise; +} + +export interface UplinkDialOptions { + /** `gateway.url`: the gateway's **base** URL (`ws://host:port`, or `wss://...`). The adapter + * derives the uplink endpoint from it -- see `resolveUplinkUrl`. */ + readonly url: string; + /** The join token, sent as `Authorization: Bearer `. */ + readonly token: string; + /** This worker's instance id (`instance.json`). */ + readonly workerId: string; + readonly label?: string; +} + +export interface UplinkConnector { + connect(options: UplinkDialOptions): Promise; +} + +/** + * Why a dial failure is its own error class: the worker's reconnect supervisor backs off on + * *any* failure, but an operator reading the log needs to tell "the gateway is not up yet" + * (`unreachable`) from "the gateway refused this token" (`rejected` -- a revoked or mistyped + * join token, which retrying alone never fixes). ADR 0005 §4/§8: a revoked token closes the + * uplink and the worker keeps retrying at the cap, which is right (an operator may mint a new + * token at any moment) but should be obvious in the log rather than a silent loop. + */ +export type UplinkErrorCode = "unreachable" | "rejected" | "unknown"; + +export class UplinkError extends Error { + constructor( + readonly code: UplinkErrorCode, + message: string, + readonly cause?: unknown, + ) { + super(message, { cause }); + this.name = "UplinkError"; + } +} + +/** + * Deterministic in-process uplink, for tests that script a fleet without a socket (ADR 0005 + * §33/§35). `connect()` runs the same authentication the WebSocket adapter does, hands the + * dialer one end and the listener's `accept` the other, and rejects with the same + * `UplinkError` codes -- so a test that exercises a revoked token exercises the real branch. + */ +export class MemoryUplinkTransport implements UplinkListenerFactory, UplinkConnector { + #handlers: UplinkHandlers | undefined; + + async listen(handlers: UplinkHandlers): Promise { + if (this.#handlers !== undefined) { + throw new UplinkError("unknown", "This memory uplink transport is already listening"); + } + this.#handlers = handlers; + return { + close: async () => { + this.#handlers = undefined; + }, + }; + } + + async connect(options: UplinkDialOptions): Promise { + const handlers = this.#handlers; + if (handlers === undefined) { + throw new UplinkError("unreachable", `No gateway is listening at ${options.url}`); + } + const result = await handlers.authenticate(options.token, { + workerId: options.workerId, + ...(options.label === undefined ? {} : { label: options.label }), + }); + const outcome = uplinkOutcome(result); + if (outcome !== "accept") { + throw new UplinkError("rejected", `The gateway rejected this join token: ${outcome}`); + } + const tokenId = uplinkTokenId(result); + const [workerEnd, gatewayEnd] = createConnectionPair(); + handlers.accept({ + connection: gatewayEnd, + workerId: options.workerId, + ...(options.label === undefined ? {} : { label: options.label }), + ...(tokenId === undefined ? {} : { tokenId }), + }); + return workerEnd; + } +} + +/** + * Two `IpcConnection`s wired to each other: what one writes, the other's `onData` listeners + * receive; closing either closes both. Used by `MemoryUplinkTransport`, and exported so a test + * that needs a bare pair (a scripted worker on one end, a real `DaemonServer` on the other) + * does not have to build one. + */ +export function createConnectionPair(): [IpcConnection, IpcConnection] { + const left = new PairedConnection(); + const right = new PairedConnection(); + left.pair(right); + right.pair(left); + return [left, right]; +} + +class PairedConnection implements IpcConnection { + readonly #closeListeners = new Set<() => void>(); + readonly #dataListeners = new Set<(chunk: string) => void>(); + /** Buffered until the first `onData`, exactly as the WebSocket adapter does and as a real + * socket does: the peer may write before this end has been handed to whoever reads it. */ + readonly #pending: string[] = []; + #peer: PairedConnection | undefined; + #closed = false; + + get closed(): boolean { + return this.#closed; + } + + pair(peer: PairedConnection): void { + this.#peer = peer; + } + + onData(listener: (chunk: string) => void): () => void { + const unsubscribe = subscribeListener(this.#dataListeners, listener); + if (this.#pending.length > 0) { + const buffered = this.#pending.splice(0); + for (const chunk of buffered) listener(chunk); + } + return unsubscribe; + } + + onClose(listener: () => void): () => void { + if (this.#closed) { + // A listener attached after the close would otherwise never fire, and consumers attach + // `onClose` after construction -- an in-memory pair can close in between. + listener(); + return () => {}; + } + return subscribeListener(this.#closeListeners, listener); + } + + onError(): () => void { + // An in-memory pair has no transport to fail; nothing ever emits here. Returning an inert + // unsubscriber keeps the port's shape honest rather than pretending errors are possible. + return () => {}; + } + + async write(contents: string): Promise { + const peer = this.#peer; + if (this.#closed || peer === undefined || peer.#closed) return; + if (peer.#dataListeners.size === 0) { + peer.#pending.push(contents); + return; + } + for (const listener of peer.#dataListeners) listener(contents); + } + + async close(): Promise { + this.#close(); + const peer = this.#peer; + if (peer !== undefined) peer.#close(); + } + + #close(): void { + if (this.#closed) return; + this.#closed = true; + for (const listener of this.#closeListeners) listener(); + } +} diff --git a/src/simlock-client/client.ts b/src/simlock-client/client.ts index 97d550b4b..e55df483f 100644 --- a/src/simlock-client/client.ts +++ b/src/simlock-client/client.ts @@ -69,6 +69,11 @@ import type { TokenListOutput, TokenRevokeInput, TokenRevokeOutput, + WorkerDrainInput, + WorkerDrainOutput, + WorkerListOutput, + WorkerRemoveOutput, + WorkerUndrainOutput, } from "./types.js"; export type { @@ -116,6 +121,12 @@ export type { TokenListOutput, TokenRevokeInput, TokenRevokeOutput, + WorkerDrainInput, + WorkerDrainOutput, + WorkerListOutput, + WorkerRemoveOutput, + WorkerUndrainOutput, + WorkerView, } from "./types.js"; export { isSimlockError, @@ -205,6 +216,12 @@ export interface SimlockAdminClient extends SimlockClient { createToken(input: TokenCreateInput): Promise; listTokens(): Promise; revokeToken(input: TokenRevokeInput): Promise; + + /** ADR 0005 §23. Gateway-only: a worker answers `UNKNOWN_REQUEST`, since it has no fleet. */ + listWorkers(): Promise; + drainWorker(input: WorkerDrainInput): Promise; + undrainWorker(input: WorkerDrainInput): Promise; + removeWorker(input: WorkerDrainInput): Promise; } /** Internal: builds either client. `admin` toggles only which methods the returned object @@ -327,6 +344,10 @@ function buildDegradedClient( createToken: () => rejected(), listTokens: () => rejected(), revokeToken: () => rejected(), + listWorkers: () => rejected(), + drainWorker: () => rejected(), + undrainWorker: () => rejected(), + removeWorker: () => rejected(), }; return client; } @@ -517,6 +538,22 @@ class SimlockClientImpl { return this.#call("token.revoke", input); } + listWorkers(): Promise { + return this.#call("worker.list", {}); + } + + drainWorker(input: WorkerDrainInput): Promise { + return this.#call("worker.drain", input); + } + + undrainWorker(input: WorkerDrainInput): Promise { + return this.#call("worker.undrain", input); + } + + removeWorker(input: WorkerDrainInput): Promise { + return this.#call("worker.remove", input); + } + // ---- abort (ADR §10) ------------------------------------------------------------------------ /** diff --git a/src/simlock-client/types.ts b/src/simlock-client/types.ts index c28a58738..969380678 100644 --- a/src/simlock-client/types.ts +++ b/src/simlock-client/types.ts @@ -63,6 +63,21 @@ export type TokenListOutput = OpOutput<"token.list">; export type TokenRevokeInput = OpInput<"token.revoke">; export type TokenRevokeOutput = OpOutput<"token.revoke">; +// ---- gateway-only 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. + +export type WorkerListOutput = OpOutput<"worker.list">; +/** One worker as the gateway currently sees it -- the shape `simlock worker list` renders. */ +export type WorkerView = WorkerListOutput["workers"][number]; +export type WorkerDrainInput = OpInput<"worker.drain">; +export type WorkerDrainOutput = OpOutput<"worker.drain">; +export type WorkerUndrainOutput = OpOutput<"worker.undrain">; +export type WorkerRemoveOutput = OpOutput<"worker.remove">; + // ---- pushes --------------------------------------------------------------------------------- export type LeaseProgress = z.infer;