diff --git a/docs/CLI.md b/docs/CLI.md index 6930c3c51..bdc926499 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -72,6 +72,7 @@ command starts it again) to bring the platform up. | 10 | `EXEC_TIMEOUT` | a `simctl`/`adb` command run through `device.exec` outlived `exec.timeoutMs` and was killed | | 10 | `DOWNLOAD_TIMEOUT` | a runtime download, including the time spent waiting for another download on the same platform, outlived `downloads.timeoutMs` | | 11 | `NO_CAPACITY` | capacity reached and `--no-wait` was set | +| 11 | `COMPONENT_BUSY` | `component remove` while a component install or removal runs or waits on that platform; try again once it ends | | 12 | `NO_DRIVER` | no driver registered for the requested platform | | 12 | `RUNTIME_MISSING` | runtime not installed and no `--allow-download` | | 12 | `UNKNOWN_MODEL` | unknown device model for the platform | @@ -79,6 +80,8 @@ command starts it again) to bring the platform up. | 12 | `LICENSE_NOT_ACCEPTED` | a required license (e.g. an Android SDK license) is not accepted | | 12 | `UNKNOWN_WORKER` | `worker drain`/`undrain` or `component install --worker` naming a worker the gateway does not know | | 12 | `DOWNLOADS_DISABLED` | `component install` on a machine whose `downloads.policy` is `"never"` | +| 12 | `COMPONENT_NOT_OWNED` | `component remove` of a component Simlock did not install, or one that changed on disk since | +| 12 | `COMPONENT_IN_USE` | `component remove` of a component a device uses, Simlock's or your own | | 13 | `REQUESTER_ALREADY_LEASED` | requester already holds a lease or has a pending request — one lease per agent in v1; release the named lease first | | 14 | — | `lease` without `--detach` only: the daemon ended the lease without the holder asking (TTL expiry, operator `release`, or an unrecoverable device) | | 15 | — | `component install --worker`/`--all-workers` on a gateway only: at least one worker did not end `installed` or `already-installed` (it refused, failed, was skipped, or its result is unknown) | @@ -107,10 +110,11 @@ implement them: means for `USAGE` and `BAD_REQUEST`. Neither is retryable as written: the fix is a different command, or the same command against a different daemon. `UNSUPPORTED_IN_GATEWAY_MODE` in particular is permanent, not provisional: - `nuke`, `cleanup`, `doctor`, `driver.passthrough` and `component list` - stay per-worker operations rather than waiting on some later fleet-wide - version. `component install` without a worker flag answers it too; with - `--worker` or `--all-workers` it installs on the workers you name. + `nuke`, `cleanup`, `doctor`, `driver.passthrough`, `component list` and + `component remove` stay per-worker operations rather than waiting on some + later fleet-wide version. `component install` without a worker flag answers + it too; with `--worker` or `--all-workers` it installs on the workers you + name. - `UNKNOWN_WORKER` takes `12`, the number the table already gives to "the thing you named cannot be resolved" (`UNKNOWN_MODEL`, `NO_DRIVER`), because that is what it is: a worker id the gateway has no record of. @@ -495,10 +499,10 @@ Refused, all exit 2 with `USAGE` and a message naming what to run instead: - `shutdown all` — it stops every device in the set, for every agent, and each interrupted lease spends its recovery budget rebooting; one that runs out ends as `lease_lost`. `shutdown ` of a single device is allowed. -- `runtime delete` — it deletes a runtime shared with Xcode. - It does not free the disk the runtime's download - takes either (see `doctor`'s `runtime-cache-unreclaimable` finding). Delete - it through Xcode if that is what you mean. +- `runtime delete` — it deletes a runtime shared with Xcode. To remove a + runtime Simlock installed, use + [`simlock component remove ios `](#simlock-component-remove-iosandroid-version---dry-run---yes), + which refuses while any simulator uses it. Delete any other through Xcode. - `--set` and `--profiles`, wherever they appear *before* the subcommand and however they are spelled (`-set`, `--set `, `--set=`) — `simlock simctl` supplies the device set itself. A caller-supplied one would @@ -1371,6 +1375,75 @@ still listed. A gateway answers `UNSUPPORTED_IN_GATEWAY_MODE`; run the command against the worker. A platform other than `ios` or `android`, or a positional argument, is a usage error (exit 2). +## `simlock component remove [--dry-run] [--yes]` + +Removes an iOS simulator runtime or Android system image that Simlock +installed, to get its disk back. Admin only: an agent session gets +`FORBIDDEN`. + +```sh +simlock component remove ios 26.4 --dry-run # what would go, and how much disk it frees +simlock component remove ios 26.4 # asks first +simlock component remove android 35 --yes # no question, for scripts +``` + +Without `--dry-run` the command asks for confirmation. Where it cannot ask, +because there is no terminal, it refuses with a usage error (exit 2) unless +you pass `--yes`. `--dry-run` never asks. + +The result is one JSON line on stdout: + +```text +{"platform":"ios","version":"26.4","outcome":"removed","sizeBytes":9103456789} +``` + +`outcome` is `removed`, or `would-remove` for a dry run. `sizeBytes` is the +disk the component took, left out when it could not be read. A removed +component leaves `simlock catalog` and `simlock component list` at once. + +Simlock removes a component only when all of these hold. A dry run checks +every one of them and removes nothing. + +- **Simlock installed it.** It was installed with `component install` or by + a lease with `--allow-download`, and it is still the same one on disk: + `installedBySimlock` is `true` in `simlock component list`. Otherwise the + command fails with `COMPONENT_NOT_OWNED` (exit 12). A component that was on + the machine before, or that was deleted and installed again some other + way, is never removed, and there is no flag to force it. +- **No device uses it.** None of Simlock's own devices of that platform and + version, in any state, leased ones included, and none of yours: a + simulator in Xcode's default device set or an AVD in your own AVD home, + booted or not. Otherwise it fails with `COMPONENT_IN_USE` (exit 12), and + the error says how many of each use it. Delete those devices first. +- **Nothing else is installing or removing on that platform.** Otherwise it + fails with `COMPONENT_BUSY` (exit 11). Run it again once that ends. A + `component install` or lease download that arrives while a removal runs + waits for it, and no new Simlock device is created on the component being + removed: a lease request for it fails with `RUNTIME_MISSING`. + +An iOS runtime is removed with `simctl runtime delete`. macOS can keep the +runtime's download in its own asset store afterwards. When it does, the +result carries `residue`, a sentence that says so and how to get the space +back: remove the platform in Xcode's Settings, under Platforms. Simlock never +deletes files there itself. An Android image is removed with +`sdkmanager --uninstall`. + +```text +{"platform":"ios","version":"26.4","outcome":"removed","sizeBytes":9103456789,"residue":"The download of iOS 26.4 (23E244) ..."} +``` + +Every removal emits `component.removed`, naming the component and who asked; +see [EVENTS.md](EVENTS.md#components). Nothing removes a component on its +own: no cleanup rule, idle timer or low-disk reaction does. Stopping the +daemon ends a removal that is running; nothing resumes it. A gateway answers +`UNSUPPORTED_IN_GATEWAY_MODE`; run the command against the worker. A missing +or extra argument, or a platform other than `ios` or `android`, is a usage +error (exit 2). + +Simlock counts only the devices it can see. A device you create while a +removal runs, or a device of another Simlock instance on the same machine, +is not counted. + ## `simlock cleanup [--dry-run] [--rule ]` Run the cleanup reconciliation immediately. `--dry-run` prints the actions diff --git a/docs/CLIENT.md b/docs/CLIENT.md index ecee64687..19ea776ba 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -16,7 +16,7 @@ import { connectSimlockAdmin } from "simlock/admin"; // agent + admin role `connectSimlockAdmin` returns a superset of `connectSimlock`'s client — every agent-role method plus the admin-role ones (`list`, `runCleanup`, `runNuke`, `getConfig`, `stopDaemon`, `replayEvents`/`subscribeEvents`, -`createToken`/`listTokens`/`revokeToken`, `installComponent`). The split exists so +`createToken`/`listTokens`/`revokeToken`, `installComponent`, `removeComponent`). The split exists so `simlock/client` doesn't even show admin methods in a caller's editor; the daemon's own role check is what actually stops an agent-role session from calling one — this is a discoverability choice, not the @@ -355,6 +355,43 @@ const { components } = await client.listComponents({ platform: "android" }); own AVD home. - A gateway rejects it with `UNSUPPORTED_IN_GATEWAY_MODE`. +## Removing a runtime: `removeComponent` + +`removeComponent({ platform, version, dryRun? })` on the admin client removes +one iOS simulator runtime or Android system image that Simlock installed — +the call behind `simlock component remove`. It does not ask for +confirmation; that is the caller's to do. `dryRun: true` runs every check a +removal runs and removes nothing. + +```ts +const result = await admin.removeComponent({ platform: "ios", version: "26.4" }); +// { platform: "ios", version: "26.4", outcome: "removed", sizeBytes: 9103456789 } +``` + +- `outcome` is `removed`, or `would-remove` for a dry run. `sizeBytes` is + absent when it could not be read. The catalog stops listing the component + at once. +- `residue`, when present, says what stayed on disk and how to reclaim it: + on iOS, macOS can keep the runtime's download in its asset store, which + Xcode's Settings, under Platforms, removes. +- It rejects, removing nothing, with `COMPONENT_NOT_OWNED` when Simlock did + not install the component or it changed on disk since, + `COMPONENT_IN_USE` when a device uses it, Simlock's or not (`details` + carries `devices` and `foreignDevices`), and `COMPONENT_BUSY` while an + install or removal runs or waits on that platform. Other rejections: + `FORBIDDEN` for an agent session, `NO_DRIVER`, and + `UNSUPPORTED_IN_GATEWAY_MODE` from a gateway. + +```ts +try { + await admin.removeComponent({ platform: "ios", version: "26.4" }); +} catch (error) { + if (isSimlockError(error) && error.code === "COMPONENT_IN_USE") { + console.error(`${error.details.devices} Simlock and ${error.details.foreignDevices} other devices use it`); + } +} +``` + ## What machine answered: `getStatus().host` `getStatus()` carries a `host` block beside `daemon`: the machine the daemon diff --git a/docs/EVENTS.md b/docs/EVENTS.md index b73ab5bdd..a522d0566 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -61,12 +61,16 @@ putting in front of every event-bus consumer. | `component.install-started` | platform, component id (the string the install was asked for: an iOS runtime version, `latest`, or a bare major; an Android API level), requester id (of the request that started the install, when known: a lease request's requester, or the principal that ran `component install`) | once per install, after the free-disk check passed and disk was set aside, just before `xcodebuild -downloadPlatform` / `sdkmanager --install` runs | component-installer | implemented | | `component.installed` | platform, component id, version (the exact version now installed), already present (`true` when the installer ran and found the component already there), duration, requester id | once per install, when the installer finished **and** a fresh read confirmed the component — never on a bare exit 0 | component-installer | implemented | | `component.install-failed` | platform, component id, duration, stable error summary, requester id | once per install, when it failed: the installer failed (a license retry included), it ran out of `downloads.timeoutMs`, the daemon stopped, the installer exited 0 but a fresh read could not confirm the component, or the component installed but its record could not be stored | component-installer | implemented | +| `component.removed` | platform, component id (the version the removal was asked for), version (the exact version removed), size in bytes (when it could be read), residue (when something stayed on disk: what, and how to reclaim it), requester id (the admin principal that ran `component remove`) | once per removal, after the platform's own removal (`simctl runtime delete` / `sdkmanager --uninstall`) finished, a fresh read confirmed the component is gone, and Simlock's record of installing it was deleted — never for a dry run or a refused removal | component-installer | implemented | These fire once per install, however many requests joined it. A request that needs no install emits none: one whose component turned out to be installed already, one another install made unnecessary while it waited, or one refused for lack of disk before anything started. +`component.removed` fires once per removal. A removal that is refused, or +that fails, emits nothing, and the component stays installed. + ## System | Event | Payload (key fields) | Emitted when | Emitter | Status | diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 6d2ddd60b..f131c8a6f 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -116,8 +116,9 @@ Routes, status codes, and every other field are unchanged. Gateway/worker fleet mode is purely additive on top of that: the same routes answer identically whether the daemon behind them is a worker or a **gateway** fronting a fleet of workers (except -`POST /v1/components/install` and `GET /v1/components`, which only a worker -serves; a gateway answers `501 UNSUPPORTED_IN_GATEWAY_MODE`), and what it adds are new +`POST /v1/components/install`, `GET /v1/components` and +`DELETE /v1/components/{platform}/{version}`, which only a worker serves; a +gateway answers `501 UNSUPPORTED_IN_GATEWAY_MODE`), and what it adds are new routes (`/v1/uplink`, `/v1/workers*`, `POST /v1/leases/{id}/exec`), new fields (`mode` on status, `workers[]`, `workerId`, `worker` on the lease), and new error codes. Nothing existing changes shape, and a client that @@ -815,6 +816,54 @@ A platform whose tools cannot answer is left out. `400 BAD_REQUEST` for a `platform` other than `ios` or `android`; `501 UNSUPPORTED_IN_GATEWAY_MODE` from a gateway, which owns no components — ask the worker. +### `DELETE /v1/components/{platform}/{version}` + +Role: `operator`. Removes one iOS simulator runtime or Android system image +that Simlock installed on this machine, to get its disk back — the same +operation as `simlock component remove`. `?dryRun=true` runs every check a +removal runs and removes nothing. + +``` +DELETE /v1/components/ios/26.4 +DELETE /v1/components/ios/26.4?dryRun=true +``` + +The answer is one JSON body, not a stream: + +```json +{ "platform": "ios", "version": "26.4", "outcome": "removed", "sizeBytes": 9103456789 } +``` + +`outcome` is `removed`, or `would-remove` for a dry run. `sizeBytes` is the +disk the component took, left out when it could not be read. `residue` +appears when something stayed on disk after the removal: on iOS, macOS can +keep the runtime's download in its own asset store, and `residue` says so and +how to reclaim it (remove the platform in Xcode's Settings, under Platforms). +A removed component leaves `GET /v1/catalog` and `GET /v1/components` at once, +and the removal is reported as a `component.removed` event naming who asked. + +A component is removed only when Simlock installed it and it is still the same +one on disk, no device uses it, and nothing else installs or removes on that +platform. Each refusal removes nothing: + +- `409 COMPONENT_NOT_OWNED` — Simlock did not install it, or it changed on + disk since. There is no way to force it. +- `409 COMPONENT_IN_USE` — a device uses it: one of Simlock's, in any state, + leased ones included, or one outside Simlock (a simulator in Xcode's + default device set, an AVD in the user's own AVD home). The body carries + `devices` and `foreignDevices`, how many of each. +- `409 COMPONENT_BUSY` — an install or removal runs or waits on that + platform; try again once it ends. +- `403 FORBIDDEN` — an `agent` token. +- `400 BAD_REQUEST` — a platform other than `ios` or `android`, a malformed + version, or a `dryRun` other than `true` or `false`. +- `501 UNSUPPORTED_IN_GATEWAY_MODE` — the daemon is a gateway, which owns no + components; ask the worker. + +```json +{ "error": { "code": "COMPONENT_IN_USE", "message": "...", "devices": 1, "foreignDevices": 2 } } +``` + ### `DELETE /v1/leases/{id}` Role: `agent` (own lease); `operator` may release any lease. @@ -1042,9 +1091,9 @@ Every failure is the same shape the daemon protocol uses: | 401 | `UNAUTHENTICATED` (missing or unrecognized token) | | 403 | `FORBIDDEN` (role doesn't permit the route — including a `worker` token on any `/v1` route other than `/v1/uplink`, and an `agent`/`operator` token at `/v1/uplink`; a `/v1/lease-requests/*` route whose request another token sent; or `POST /v1/leases/{id}/renew`/`DELETE /v1/leases/{id}`/`POST /v1/leases/{id}/exec` naming another requester's still-live lease), `DOWNLOADS_DISABLED` (`POST /v1/components/install` under `downloads.policy: "never"`) | | 404 | `UNKNOWN_WORKER` (`POST`/`DELETE /v1/workers/{id}/drain` naming a worker the gateway does not know), `UNKNOWN_LEASE_REQUEST` (unknown request id), `UNKNOWN_LEASE` (unknown lease id, expired/released, **or `GET /v1/leases/{id}`/`GET /v1/leases/{id}/events` naming another requester's lease** — see [`GET /v1/leases/{id}`](#get-v1leasesid)) | -| 409 | `REQUESTER_ALREADY_LEASED` (body names the existing lease id; fleet-wide on a gateway), `IDEMPOTENCY_CONFLICT` (an `Idempotency-Key` repeated with a different device), `REQUEST_NOT_CANCELLABLE` (body names the lease id if the request had already been granted), `WORKER_CONNECTED` (`DELETE /v1/workers/{id}` while its uplink is open) | +| 409 | `REQUESTER_ALREADY_LEASED` (body names the existing lease id; fleet-wide on a gateway), `IDEMPOTENCY_CONFLICT` (an `Idempotency-Key` repeated with a different device), `REQUEST_NOT_CANCELLABLE` (body names the lease id if the request had already been granted), `WORKER_CONNECTED` (`DELETE /v1/workers/{id}` while its uplink is open), `COMPONENT_NOT_OWNED`, `COMPONENT_IN_USE` (body carries `devices` and `foreignDevices`), `COMPONENT_BUSY` (the three refusals of `DELETE /v1/components/{platform}/{version}`) | | 422 | `UNKNOWN_MODEL`, `RUNTIME_MISSING`, `NO_DRIVER`, `PASSTHROUGH_REFUSED` (a refused `exec` verb, a caller-supplied `--set`/`-P`, a bare `adb shell`), `UNKNOWN_PASSTHROUGH_TOOL` | -| 501 | `UNSUPPORTED_IN_GATEWAY_MODE` (an operation that acts on one machine, asked of a gateway: `POST /v1/components/install`, `GET /v1/components`) | +| 501 | `UNSUPPORTED_IN_GATEWAY_MODE` (an operation that acts on one machine, asked of a gateway: `POST /v1/components/install`, `GET /v1/components`, `DELETE /v1/components/{platform}/{version}`) | | 503 | `NO_CAPACITY` (only with `noWait: true`; response carries `Retry-After`), `WORKER_UNREACHABLE` (a gateway could not reach the worker holding this lease or request) | | 504 | `EXEC_TIMEOUT` (a `device.exec` command outlived `exec.timeoutMs`), `DOWNLOAD_TIMEOUT` (a runtime download, waiting for another download included, outlived `downloads.timeoutMs`) | @@ -1058,18 +1107,19 @@ behind this is not reachable right now" is the same answer in all four cases, and a client with one retry rule for `transport` should not need a second one because the unreachable thing happened to be a worker. -`UNSUPPORTED_IN_GATEWAY_MODE` comes from two routes in this version, -`POST /v1/components/install` without `workers` and `GET /v1/components` -asked of a gateway — `nuke`, `cleanup`, and +`UNSUPPORTED_IN_GATEWAY_MODE` comes from three routes in this version, +`POST /v1/components/install` without `workers`, `GET /v1/components` and +`DELETE /v1/components/{platform}/{version}` asked of a gateway — `nuke`, +`cleanup`, and `doctor` are absent from the HTTP surface (see [Not implemented](#not-implemented)), and the status is fixed so adding `POST /v1/doctor` or `POST /v1/cleanup` later is additive rather than a fresh decision. `501` is the honest status for it: this is not a temporary condition to retry past, it is an operation this daemon will never perform, and `nuke`/`cleanup`/`doctor`/`driver.passthrough` and component listings -stay per-worker permanently rather than pending some later fan-out. A -component install through a gateway is a different request, one that names -its workers. +and removals stay per-worker permanently rather than pending some later +fan-out. A component install through a gateway is a different request, one +that names its workers. `EXEC_TIMEOUT`'s `504` is documented for completeness rather than for the exec route: `POST /v1/leases/{id}/exec` has already answered `200` and begun diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index e534e151a..083da39d1 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -177,8 +177,8 @@ agent / console ──token auth──> │ HTTP frontend + unix socket 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`, - `driver.passthrough`, `component.install` and `component.list` answer - `UNSUPPORTED_IN_GATEWAY_MODE` permanently: they act on one machine's devices + `driver.passthrough`, `component.install`, `component.list` and + `component.remove` answer `UNSUPPORTED_IN_GATEWAY_MODE` permanently: they act on one machine's devices or components, and stay per-worker. Installing through a gateway is its own gateway-only operation, `worker.install-component`, which names the workers (see "Through a gateway" under Components). The lease lifecycle @@ -1395,7 +1395,8 @@ install components; they do not decide when. `resolveSpec` never downloads: when a download could satisfy a request it throws `RuntimeMissingError` with `downloadable: true` and `component`, the string to install — a version, or a driver's word for "newest" (`latest` on iOS; the bare major of a model's upper -bound when the model has one). A driver offers two verbs and an estimate: +bound when the model has one). For installs a driver offers two verbs and an +estimate (`listComponents` and `removeComponent` are below): - `findComponent(component)` — a read: the installed version and its receipt, or nothing. A string that is not a version answers nothing. @@ -1500,12 +1501,70 @@ registry: `installedBySimlock` is true when a `ComponentRecord` of that platform has a receipt equal (`sameReceipt`) to the entry's, and `installedAt` is that record's time — the record is the only proof (ADR 0010 §5, safety rule 8). `devices` counts registry devices of that platform and -version in any state but `deleted`; the core cannot tell variants apart, so +version in any state but `deleted`, plus every device `DeviceProvisioner` has +claimed and not registered yet (below); the core cannot tell variants apart, so two variants of one version show the same count. A driver whose listing rejects is left out and logged, and the other platform is still listed. Entries are ordered by platform, then version, then variant. A gateway answers `UNSUPPORTED_IN_GATEWAY_MODE`. +Removal is `component.remove` (ADR 0010 §8), an admin operation with input +`{ platform, version, dryRun? }`, behind `simlock component remove` (which +confirms or requires `--yes`, safety rule 5), `removeComponent` on the admin +client and `DELETE /v1/components/{platform}/{version}` (`?dryRun=true`, one +JSON answer). The dispatcher passes the session principal as `requesterId` +and turns `ComponentInUseError` into `COMPONENT_IN_USE` with its two counts +as details. `ComponentInstaller.remove` is the only caller of +`Driver.removeComponent`: + +1. **Prove ownership.** The registry's `ComponentRecord` of that platform and + version, and an entry of the driver's listing — the same `#listDriver` + `list` answers from (architecture rule 10) — whose receipt equals the + record's. Either missing is `ComponentNotOwnedError` + (`COMPONENT_NOT_OWNED`). A listing that rejects rejects the removal: an + unreadable foreign count is never "no users". +2. **Refuse users.** `devices` or `foreignDevices` above zero is + `ComponentInUseError` (`COMPONENT_IN_USE`). +3. **Refuse a busy platform.** Anything in the platform's install queue, or a + removal already holding its turn, is `ComponentBusyError` + (`COMPONENT_BUSY`). A dry run stops here with `would-remove` and the + listed size; it has run every check. +4. **Take the turn.** Checked and taken with no `await` between them; while + a removal holds it, `#pump` starts no install on that platform, and an + install that arrives is told it waits. +5. **Mark, inside the decision gate.** It counts Simlock's devices again and + marks the platform and version as being removed. Device records are + created in one place, `DeviceProvisioner.provision`, which first calls + `ComponentInstaller.claimProvision(spec)` inside the gate: a marked + component refuses with `ComponentBeingRemovedError` (a + `RuntimeMissingError`, so `RUNTIME_MISSING`) before the driver creates + anything, and the lease path rejects the request instead of retrying. An + unmarked one counts the claim as a Simlock device until the device's + record is committed, in the same gate section, or the provision fails. So + the gate orders every new device against every removal: either the + removal's count sees it, or it sees the mark. +6. **Remove.** `driver.removeComponent(receipt, { signal })`, then delete the + record inside the gate, then emit `component.removed`. A failure is logged + with who asked, keeps the record, and rethrows. The mark and the turn live + in one record, `#removals`, which every exit clears. `close()` aborts a + running removal through its signal, which answers `DAEMON_STOPPING`, and + resolves once the driver call has returned. + +Every driver's `removeComponent` is `removeListedComponent` (`src/core/driver.ts`) +over its own listing: prove the receipt again, refuse a foreign user again, +run the platform step under `COMPONENT_REMOVAL_TIMEOUT_MS` (five minutes) and +the signal, and list again to verify the component is gone. Both platform +steps run through `runBoundedProcess` (`src/drivers/installer-process.ts`), +which ends the process `SIGTERM` then `SIGKILL` and answers only once it has +exited. iOS runs `simctl --set runtime delete ` without +`--keep-asset` (the `--set` from `#scopedSimctlArgv`, like every scoped call), +then reads the asset store (#79) and reports `residue` when the build's +download is still there; `simlock simctl runtime delete` stays refused and +points at `simlock component remove`. Android runs +`sdkmanager --uninstall `. A second +Simlock instance's devices and a foreign device created after the driver's +last count are not seen; see KNOWN-PITFALLS.md. + #### Through a gateway `worker.install-component` (ADR 0010 §7) is gateway-only: it is in diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index ea8f2bb5f..d01b561e7 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -85,6 +85,7 @@ consumer, just operator diagnostics, so it's a `warn` log line (`daemon.driver-d | `component.install-started` | platform, component id (the string the install was asked for: an iOS runtime version, `latest`, or a bare major; an Android API level), requester id (of the request that started the install, when known: a lease request's requester, or the principal that ran `component install`) | once per install, after the free-disk check passed and disk was set aside, just before `xcodebuild -downloadPlatform` / `sdkmanager --install` runs | component-installer | implemented | | `component.installed` | platform, component id, version (the exact version now installed), already present (`true` when the installer ran and found the component already there), duration, requester id | once per install, when the installer finished **and** a fresh read confirmed the component — never on a bare exit 0 | component-installer | implemented | | `component.install-failed` | platform, component id, duration, stable error summary, requester id | once per install, when it failed: the installer failed (a license retry included), it ran out of `downloads.timeoutMs`, the daemon stopped, the installer exited 0 but a fresh read could not confirm the component, or the component installed but its record could not be stored | component-installer | implemented | +| `component.removed` | platform, component id (the version the removal was asked for), version (the exact version removed), size in bytes (when it could be read), residue (when something stayed on disk: what, and how to reclaim it), requester id (the admin principal that ran `component remove`) | once per removal, after the platform's own removal (`simctl runtime delete` / `sdkmanager --uninstall`) finished, a fresh read confirmed the component is gone, and Simlock's record of installing it was deleted — never for a dry run or a refused removal | component-installer | implemented | `ComponentInstaller` (`src/core/component-installer.ts`) is the only emitter (ADR 0010 §3): drivers install but never emit (architecture rule 5). The events fire once per install, not @@ -97,6 +98,14 @@ install. See "Device requests" in [ARCHITECTURE.md](ARCHITECTURE.md) for how a m component gets to this point. The requester hears the install through its own `downloading` progress stage, a direct call chain from the installer, not these events (architecture rule 5). +`component.removed` has the same single emitter (ADR 0010 §8). `ComponentInstaller.remove` +emits it after the driver's `removeComponent` returned and the component record was deleted +from the registry (events rule 3); a dry run, a refusal (`COMPONENT_NOT_OWNED`, +`COMPONENT_IN_USE`, `COMPONENT_BUSY`) and a driver failure emit nothing, and a failure keeps the +record. `requesterId` is the admin session's principal, never a caller-supplied id (safety rule +6). `residue` is the driver's sentence, carried unread: on iOS it names the asset-store download +`simctl runtime delete` left behind (#79). + ## System | Event | Payload (key fields) | Emitted when | Emitter | Status | diff --git a/docs/internal/KNOWN-PITFALLS.md b/docs/internal/KNOWN-PITFALLS.md index eeee9ee23..33780ef5e 100644 --- a/docs/internal/KNOWN-PITFALLS.md +++ b/docs/internal/KNOWN-PITFALLS.md @@ -355,9 +355,46 @@ tens of gigabytes on every `doctor` run — and stays silent when the store is absent or unreadable, which is the normal state on a machine that has never downloaded a runtime. +**What `component remove` reports:** `simlock component remove ios ` +runs `simctl runtime delete` without `--keep-asset`, so CoreSimulator is asked +to let go of the download too, then reads the store the same way the advisory +does. When a bundle of the removed image's build (or, for an image with no +build, its version) is still there, the result and `component.removed` carry +`residue`: a sentence naming the store and Xcode's Settings → Platforms as the +way to reclaim it. The removal itself succeeded either way, and Simlock still +never deletes a file in the store (ADR 0010 §8). + **The knob:** `downloads.policy` decides whether the host downloads runtimes at all; short of that, the reclaim is manual and periodic, driven by what -`doctor` reports. +`doctor` and `component remove` report. + +## `component remove` counts only the devices this instance can see (ADR 0010 §8) + +`simlock component remove` refuses while a device uses the component: every +device in this instance's registry, in any state but `deleted` (and every +device being provisioned that has no record yet), plus the devices the driver +counts outside Simlock — simulators in the machine's default device set, +AVDs in the user's own AVD home. + +**The pitfall:** two kinds of device are not counted. + +- A **second Simlock instance** on the same machine keeps its devices in its + own root, which this instance cannot see and must not read. Removing a + component that instance uses breaks its devices until the component is + installed again. +- A **foreign device created after the driver's last count** — the count runs + once in the removal's checks and once more in the driver, just before the + platform's own removal. A simulator or AVD the user creates between that + count and the end of `simctl runtime delete` / `sdkmanager --uninstall` is + not seen. A new *Simlock* device cannot slip in the same way: the removal + marks the component inside the decision gate, and `DeviceProvisioner` + refuses every device on a marked component until the removal settles. + +**Why it is accepted:** both need knowledge Simlock does not have without +reaching outside what it owns. The ADR accepts them (Consequences, and §8's +"a foreign device created after the driver's last count is not seen"), and +removal is never automatic: an operator runs it, after reading +`simlock component list`. ## True cancellation during provisioning is not implemented (ADR 0003 §10) diff --git a/docs/internal/agent-rules/safety.md b/docs/internal/agent-rules/safety.md index 3798d8aa2..7fcce79a2 100644 --- a/docs/internal/agent-rules/safety.md +++ b/docs/internal/agent-rules/safety.md @@ -9,6 +9,19 @@ never enforce them only inside an individual rule or driver. (i.e. that simlock created). Everything else on the machine is strictly read-only. This includes `doctor --fix` and `nuke`. + A component (an iOS simulator runtime or an Android system image) is + removed only through its record: `ComponentInstaller.remove`, from an + admin's explicit `component.remove`, and only when a component record's + receipt equals the receipt of what is installed now + ([ADR 0010](../adr/0010-components-have-one-owner-in-the-core.md) §5, §8). + It is never removed while any device uses it, Simlock's own in any state + but `deleted` or a foreign one, booted or not; and nothing removes one on + its own — no cleanup rule, idle tier or disk-pressure reaction. To count + foreign devices a driver may read the platform's default device locations + (the machine's default simulator set, the user's own AVD home), and never + writes there. Simlock never deletes a file in the macOS asset store: it + asks `simctl` to delete the runtime and reports what `simctl` left. + There is exactly one exception, and it is opt-in: `doctor --purge-orphans` may destroy a device that sits inside a *validly-marked Simlock device root* but has no registry record (see diff --git a/e2e/component-remove.test.ts b/e2e/component-remove.test.ts new file mode 100644 index 000000000..1cfc602da --- /dev/null +++ b/e2e/component-remove.test.ts @@ -0,0 +1,149 @@ +import { describe, expect, it } from "vitest"; + +import { events, type TestEnv, withDaemon } from "./helpers/index.js"; + +async function removeCalls(env: TestEnv): Promise { + return (await env.driverLog.calls()) + .filter((call) => call.operation === "removeComponent") + .map((call) => call.arguments); +} + +/** A daemon whose iOS driver has 18.4 on the machine and 19.0 installed by Simlock. */ +async function withSimlockInstall(): Promise { + const env = await withDaemon(); + await env.driverScript.set({ + ios: { + availableOsVersions: ["18.4"], + componentSizes: { "19.0": 9_000_000_000 }, + knownModels: ["iPhone 16"], + }, + }); + const install = await env.cli(["component", "install", "ios", "19.0"]); + expect(install.code, install.stderr).toBe(0); + await env.driverLog.clear(); + return env; +} + +describe("simlock component remove", () => { + it("removes a component Simlock installed: the catalog and component list no longer show it, and component.removed names who asked", async () => { + const env = await withSimlockInstall(); + + const removed = await env.cli(["component", "remove", "ios", "19.0", "--yes"], { + env: { SIMLOCK_AGENT_ID: "operator-221" }, + }); + + expect(removed.code, removed.stderr).toBe(0); + expect(removed.json).toEqual({ + outcome: "removed", + platform: "ios", + sizeBytes: 9_000_000_000, + version: "19.0", + }); + expect(await removeCalls(env)).toHaveLength(1); + const catalog = await env.cli(["catalog", "--platform", "ios", "--json"]); + expect(catalog.json).toMatchObject({ platforms: [{ runtimes: ["18.4"] }] }); + const listed = await env.cli(["component", "list", "--platform", "ios"]); + expect(listed.json).toMatchObject({ components: [{ version: "18.4" }] }); + expect((listed.json as { components: unknown[] }).components).toHaveLength(1); + const removedEvents = (await events(env.env)).filter( + (entry) => entry.event === "component.removed", + ); + expect(removedEvents).toHaveLength(1); + expect(removedEvents[0]?.payload).toMatchObject({ + componentId: "19.0", + platform: "ios", + requesterId: "operator-221", + sizeBytes: 9_000_000_000, + version: "19.0", + }); + }); + + it("answers a dry run with would-remove and the size, and removes nothing", async () => { + const env = await withSimlockInstall(); + + const dryRun = await env.cli(["component", "remove", "ios", "19.0", "--dry-run"]); + + expect(dryRun.code, dryRun.stderr).toBe(0); + expect(dryRun.json).toEqual({ + outcome: "would-remove", + platform: "ios", + sizeBytes: 9_000_000_000, + version: "19.0", + }); + expect(await removeCalls(env)).toEqual([]); + const listed = await env.cli(["component", "list", "--platform", "ios"]); + expect(listed.json).toMatchObject({ + components: [{ version: "18.4" }, { installedBySimlock: true, version: "19.0" }], + }); + }); + + it("refuses a component Simlock did not install with COMPONENT_NOT_OWNED and exit 12, removing nothing", async () => { + const env = await withSimlockInstall(); + + const result = await env.cli(["component", "remove", "ios", "18.4", "--yes"]); + + expect(result.code, result.stderr).toBe(12); + expect(result.stdout).toBe(""); + expect(result.error?.code).toBe("COMPONENT_NOT_OWNED"); + expect(await removeCalls(env)).toEqual([]); + }); + + it("refuses a component a leased device uses with COMPONENT_IN_USE and exit 12, removing nothing", async () => { + const env = await withSimlockInstall(); + const lease = await env.cli([ + "lease", + "--platform", + "ios", + "--device", + "iPhone 16", + "--os", + "19.0", + "--agent-id", + "agent-a", + "--detach", + ]); + expect(lease.code, lease.stderr).toBe(0); + + const result = await env.cli(["component", "remove", "ios", "19.0", "--yes"]); + + expect(result.code, result.stderr).toBe(12); + expect(result.error?.code).toBe("COMPONENT_IN_USE"); + expect(await removeCalls(env)).toEqual([]); + }); + + it("refuses a component a foreign device uses with COMPONENT_IN_USE, removing nothing", async () => { + const env = await withSimlockInstall(); + await env.driverScript.set({ + ios: { + availableOsVersions: ["18.4"], + foreignDevices: { "19.0": 1 }, + knownModels: ["iPhone 16"], + }, + }); + + const result = await env.cli(["component", "remove", "ios", "19.0", "--yes"]); + + expect(result.code, result.stderr).toBe(12); + expect(result.error?.code).toBe("COMPONENT_IN_USE"); + expect(await removeCalls(env)).toEqual([]); + }); + + it("refuses an agent session with FORBIDDEN, removing nothing", async () => { + const env = await withSimlockInstall(); + + // A credential the daemon rejects falls back to an agent session (with a notice). + const result = await env.cli([ + "--token", + "not-an-admin-credential", + "component", + "remove", + "ios", + "19.0", + "--yes", + ]); + + expect(result.code, result.stderr).toBe(1); + expect(result.error?.code).toBe("FORBIDDEN"); + expect(await removeCalls(env)).toEqual([]); + }); +}); diff --git a/e2e/fake-driver/fake-driver.ts b/e2e/fake-driver/fake-driver.ts index 65a1512da..1fdc1e1ae 100644 --- a/e2e/fake-driver/fake-driver.ts +++ b/e2e/fake-driver/fake-driver.ts @@ -6,6 +6,8 @@ import { BootTimeoutError, type ComponentInstallProgress, type ComponentInstallResult, + type ComponentReceipt, + type ComponentRemoval, DriverCrashError, type InstalledComponent, RuntimeMissingError, @@ -23,6 +25,7 @@ import { type PassthroughCommand, type PassthroughContext, PassthroughRefusedError, + removeListedComponent, } from "../../dist/core/driver.js"; import type { DeviceSpec, Platform } from "../../dist/core/domain.js"; import type { @@ -297,6 +300,33 @@ export class OutOfProcessFakeDriver implements Driver { */ async listComponents(): Promise { const script = await this.#beforeCall("listComponents", []); + return this.#listed(script); + } + + /** + * Removes an installed version through the steps every driver takes (`removeListedComponent`), + * reading the listing `listComponents` answers. Scripted by `latencyMs.removeComponent`, + * `failures.removeComponent` and `removalResidue` like any call. Only a version an install put + * in place goes: a scripted one stays in `availableOsVersions`, as the user's own would. + */ + async removeComponent( + receipt: ComponentReceipt, + options: { readonly signal: AbortSignal }, + ): Promise { + const script = await this.#beforeCall("removeComponent", [receipt]); + if (options.signal.aborted) throw new DriverCrashError("Fake removal aborted"); + return removeListedComponent({ + list: async () => this.#listed(script), + platform: this.platform, + receipt, + remove: async ({ version }) => { + this.#installed.delete(version); + return script.removalResidue === undefined ? {} : { residue: script.removalResidue }; + }, + }); + } + + #listed(script: FakeDriverPlatformScript): DriverComponent[] { return this.#available(script).flatMap((version): DriverComponent[] => { const found = this.#find(version, script); if (found === undefined) return []; diff --git a/e2e/fake-driver/types.ts b/e2e/fake-driver/types.ts index a976689d2..7fef24628 100644 --- a/e2e/fake-driver/types.ts +++ b/e2e/fake-driver/types.ts @@ -19,6 +19,7 @@ export type FakeDriverOperation = | "listManaged" | "listCatalog" | "listComponents" + | "removeComponent" /** The root re-proof `doctor --purge-orphans` takes before its first destroy. */ | "revalidateRoot"; @@ -102,6 +103,8 @@ export interface FakeDriverPlatformScript { readonly componentSizes?: Readonly>; /** What `listComponents` reports as each version's foreign devices; 0 for one left out. */ readonly foreignDevices?: Readonly>; + /** What every `removeComponent` reports as left on disk; nothing unless set. */ + readonly removalResidue?: string; readonly latencyMs?: Partial>; readonly estimateMs?: Partial>; readonly reclaimResult?: "ready" | "shutdown"; diff --git a/src/admin/index.ts b/src/admin/index.ts index 2e18b9381..0b74a4869 100644 --- a/src/admin/index.ts +++ b/src/admin/index.ts @@ -17,6 +17,8 @@ export type { CatalogGetOutput, ComponentListInput, ComponentListOutput, + ComponentRemoveInput, + ComponentRemoveOutput, CleanupRunInput, CleanupRunOutput, ComponentInstallInput, diff --git a/src/bus/index.test.ts b/src/bus/index.test.ts index 59924d889..eead0bd8e 100644 --- a/src/bus/index.test.ts +++ b/src/bus/index.test.ts @@ -141,6 +141,7 @@ describe("EventBus", () => { | "component.install-started" | "component.installed" | "component.install-failed" + | "component.removed" | "device.foreign-state-detected" | "device.foreign-provenance-detected" | "device.stalled-transition-detected" diff --git a/src/bus/index.ts b/src/bus/index.ts index 5135ebe10..871dfa07a 100644 --- a/src/bus/index.ts +++ b/src/bus/index.ts @@ -151,6 +151,19 @@ export interface EventMap { readonly error: string; readonly requesterId?: string; }; + "component.removed": { + readonly platform: string; + /** The component string the removal was asked for: the version, as the catalog lists it. */ + readonly componentId: string; + /** The exact version removed: the version of Simlock's record of installing it. */ + readonly version: string; + /** The component's size as listed just before it was removed, when the driver could read it. */ + readonly sizeBytes?: number; + /** What stayed on disk after the removal, and how to reclaim it, when something did. */ + readonly residue?: string; + /** The principal of the admin session that asked. */ + readonly requesterId: string; + }; "daemon.started": { readonly version: string; readonly configSnapshot: unknown }; "daemon.stopping": { readonly reason: string }; "disk.pressure-detected": { readonly freeBytes: number; readonly threshold: number }; diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 8a4e62585..073a781ec 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1426,6 +1426,170 @@ describe("CLI: daemon status (ADR 0003 §11)", () => { }); }); +describe("CLI: component remove (ADR 0010 §8)", () => { + /** A client that records every removal it is asked for and answers it. */ + function removingClient(asked: unknown[]) { + return fakeClient({ + removeComponent: async (input) => { + asked.push(input); + return { + outcome: input.dryRun === true ? "would-remove" : "removed", + platform: input.platform, + sizeBytes: 7_000_000_000, + version: input.version, + }; + }, + }); + } + + it("removes with --yes and prints the daemon's answer as one JSON line on stdout", async () => { + const output = outputCapture(); + const asked: unknown[] = []; + + await expect( + runCli( + ["component", "remove", "ios", "26.4", "--yes"], + output.environmentWith({ + confirm: async () => { + throw new Error("--yes must not ask"); + }, + connectAdmin: async () => removingClient(asked), + }), + ), + ).resolves.toBe(0); + + expect(asked).toEqual([{ platform: "ios", version: "26.4" }]); + expect(output.stdout.trim().split("\n")).toHaveLength(1); + expect(JSON.parse(output.stdout)).toEqual({ + outcome: "removed", + platform: "ios", + sizeBytes: 7_000_000_000, + version: "26.4", + }); + }); + + it("asks for confirmation without --yes, and removes once it is given", async () => { + const output = outputCapture(); + const asked: unknown[] = []; + const questions: string[] = []; + + await expect( + runCli( + ["component", "remove", "android", "35"], + output.environmentWith({ + confirm: async (question) => { + questions.push(question); + return true; + }, + connectAdmin: async () => removingClient(asked), + }), + ), + ).resolves.toBe(0); + + expect(questions).toEqual(["Remove android 35? [y/N] "]); + expect(asked).toEqual([{ platform: "android", version: "35" }]); + }); + + it.each([ + ["declined", async () => false], + // No terminal to ask on: the CLI's own `confirmTerminal` is not installed, so this is the + // no-terminal case rather than the default. + ["unavailable", undefined], + ] as const)( + "refuses without --yes when confirmation is %s, and contacts nobody", + async (_case, confirm) => { + const output = outputCapture(); + let connected = false; + + await expect( + runCli( + ["component", "remove", "ios", "26.4"], + output.environmentWith({ + ...(confirm === undefined ? { confirm: undefined } : { confirm }), + connectAdmin: async () => { + connected = true; + return fakeClient(); + }, + }), + ), + ).resolves.toBe(2); + + expect(connected).toBe(false); + expect(JSON.parse(output.stderr)).toEqual({ + error: { code: "USAGE", message: expect.stringContaining("--yes") }, + }); + }, + ); + + it("does not ask under --dry-run, and asks the daemon for a dry run", async () => { + const output = outputCapture(); + const asked: unknown[] = []; + + await expect( + runCli( + ["component", "remove", "ios", "26.4", "--dry-run"], + output.environmentWith({ + confirm: async () => { + throw new Error("--dry-run must not ask"); + }, + connectAdmin: async () => removingClient(asked), + }), + ), + ).resolves.toBe(0); + + expect(asked).toEqual([{ dryRun: true, platform: "ios", version: "26.4" }]); + expect(JSON.parse(output.stdout)).toMatchObject({ outcome: "would-remove" }); + }); + + it.each([ + ["COMPONENT_NOT_OWNED", {}, 12], + ["COMPONENT_IN_USE", { devices: 1, foreignDevices: 2 }, 12], + ["COMPONENT_BUSY", {}, 11], + ] as const)( + "exits with the table's code when the daemon refuses with %s", + async (code, details, exit) => { + const output = outputCapture(); + const client = fakeClient({ + removeComponent: () => + Promise.reject(new SimlockError(code, "domain", "refused", details as never)), + }); + + await expect( + runCli( + ["component", "remove", "ios", "26.4", "--yes"], + output.environmentWith({ connectAdmin: async () => client }), + ), + ).resolves.toBe(exit); + expect(output.stdout).toBe(""); + expect(JSON.parse(output.stderr.trim().split("\n").at(-1) ?? "")).toMatchObject({ + error: { code }, + }); + }, + ); + + it.each([ + ["no version", ["component", "remove", "ios"]], + ["an unknown platform", ["component", "remove", "tvos", "1.0", "--yes"]], + ["an extra argument", ["component", "remove", "ios", "26.4", "extra", "--yes"]], + ])("exits 2 with USAGE for %s, without asking the daemon", async (_label, argv) => { + const output = outputCapture(); + let connected = false; + + await expect( + runCli( + argv, + output.environmentWith({ + connectAdmin: async () => { + connected = true; + return fakeClient(); + }, + }), + ), + ).resolves.toBe(2); + expect(connected).toBe(false); + }); +}); + describe("CLI: config set validates before writing (ADR 0003 §11)", () => { it("rejects an invalid merged config without writing the file", async () => { const output = outputCapture(); @@ -1934,7 +2098,7 @@ describe("CLI: component install (ADR 0010 §6)", () => { ["an extra argument", ["component", "install", "ios", "26.4", "26.5"]], ["an unknown platform", ["component", "install", "tvos", "26.4"]], ["--json", ["component", "install", "ios", "26.4", "--json"]], - ["an unknown subcommand", ["component", "remove", "ios", "26.4"]], + ["an unknown subcommand", ["component", "uninstall", "ios", "26.4"]], ])("exits 2 with USAGE for %s, without asking the daemon", async (_label, argv) => { const output = outputCapture(); let installs = 0; @@ -1973,7 +2137,8 @@ describe("CLI: component install (ADR 0010 §6)", () => { ).resolves.toBe(0); expect(output.stdout).toBe( "Usage: simlock component install [--worker ... | --all-workers]\n" + - " simlock component list [--platform ]\n", + " simlock component list [--platform ]\n" + + " simlock component remove [--dry-run] [--yes]\n", ); expect(connected).toBe(false); }, @@ -4260,6 +4425,12 @@ function fakeClient(overrides: Partial = {}): SimlockAdminCl version: input.version, }), installComponentOnWorkers: () => Promise.resolve({ results: [] }), + removeComponent: (input) => + Promise.resolve({ + outcome: input.dryRun === true ? ("would-remove" as const) : ("removed" as const), + platform: input.platform, + version: input.version, + }), ...overrides, }; return base; diff --git a/src/cli/index.ts b/src/cli/index.ts index 78331525e..4a617d90c 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -61,6 +61,8 @@ Commands: Install a simulator runtime or system image component list [--platform ] List installed runtimes and system images + component remove [--dry-run] [--yes] + Remove a runtime or system image Simlock installed simctl Run xcrun simctl against Simlock's iOS device set adb Run adb against Simlock's adb server mcp Start the stdio MCP server @@ -1865,7 +1867,8 @@ async function runWorkerAction( const COMPONENT_USAGE = "Usage: simlock component install [--worker ... | --all-workers]\n" + - " simlock component list [--platform ]\n"; + " simlock component list [--platform ]\n" + + " simlock component remove [--dry-run] [--yes]\n"; /** * ADR 0010 §6: installs one component through the daemon's `component.install`. Argument @@ -1888,6 +1891,7 @@ async function runComponent( return 0; } if (command === "list") return runComponentList(argv.slice(1), environment, token); + if (command === "remove") return runComponentRemove(argv.slice(1), environment, token); if (command !== "install") { throw new UsageError(withHelpHint(`Unknown component command: ${command}`)); } @@ -1956,6 +1960,67 @@ async function runComponentList( } } +/** + * ADR 0010 §8: `component remove` renders the daemon's `component.remove` as one JSON line on + * stdout. Destructive, so without `--dry-run` it confirms or requires `--yes`, exactly as + * `release --all` does (safety rule 5); a dry run removes nothing and asks nothing. Whether the + * component may go is the daemon's answer. + */ +async function runComponentRemove( + argv: readonly string[], + environment: CliEnvironment, + token: string | undefined, +): Promise { + const parsed = parseComponentRemoveArgs(argv); + if (parsed === "help") { + environment.stdout.write(COMPONENT_USAGE); + return 0; + } + const { dryRun, platform, version } = parsed; + if (!dryRun) { + const confirmed = + parsed.yes || (await environment.confirm?.(`Remove ${platform} ${version}? [y/N] `)); + if (confirmed !== true) { + throw new UsageError("component remove requires confirmation or --yes"); + } + } + const client = await connectDaemonClient(environment, token); + try { + writeResult( + environment, + await client.removeComponent({ platform, version, ...(dryRun ? { dryRun } : {}) }), + ); + return 0; + } finally { + await client.close(); + } +} + +/** `component remove`'s arguments: exactly a platform and a version and its flags, or `--help`. */ +function parseComponentRemoveArgs(argv: readonly string[]): + | { + readonly platform: "ios" | "android"; + readonly version: string; + readonly dryRun: boolean; + readonly yes: boolean; + } + | "help" { + const values = commandArgs(argv, { + "dry-run": { type: "boolean" }, + help: { type: "boolean", short: "h" }, + yes: { type: "boolean" }, + }); + if (values.help) return "help"; + const [platform, version, ...extra] = values.positionals; + if (platform === undefined || version === undefined || extra.length > 0) { + throw new UsageError(withHelpHint("Expected ")); + } + if (platform !== "ios" && platform !== "android") { + throw new UsageError("component remove must be ios or android"); + } + return { dryRun: values["dry-run"] === true, platform, version, yes: values.yes === true }; +} + /** `component install`'s arguments: exactly a platform and a version, optionally the workers to * install on (`--worker`, repeatable, or `--all-workers`, never both), or `--help`. */ function parseComponentInstallArgs(argv: readonly string[]): diff --git a/src/contract/errors.ts b/src/contract/errors.ts index 9a168093b..05f2b0d58 100644 --- a/src/contract/errors.ts +++ b/src/contract/errors.ts @@ -72,6 +72,18 @@ export interface ErrorDetailsMap { * no operation overrides that policy, so the install never starts. */ DOWNLOADS_DISABLED: { readonly policy: "never" }; + /** + * ADR 0010 §5/§8: a `component.remove` for a component Simlock did not install -- no record of + * installing it, or what is installed now is not what the record names. Nothing was removed. + */ + COMPONENT_NOT_OWNED: Record; + /** + * ADR 0010 §8: a `component.remove` for a component a device uses: `devices` of Simlock's own, + * in any state but deleted, and `foreignDevices` outside Simlock. Nothing was removed. + */ + COMPONENT_IN_USE: { readonly devices: number; readonly foreignDevices: number }; + /** ADR 0010 §8: a `component.remove` while an install or removal runs or waits on the platform. */ + COMPONENT_BUSY: Record; UNKNOWN_LEASE: { readonly leaseId: string }; /** A `simlock ` verb the owning driver will not proxy (ADR 0001, decision 7). Carries * the tool so a caller can say which wrapper refused without re-parsing the message. */ @@ -173,6 +185,7 @@ const CODES_WITH_DECLARED_DETAILS_BY_CODE: Record LICENSE_NOT_ACCEPTED: true, DOWNLOAD_TIMEOUT: true, DOWNLOADS_DISABLED: true, + COMPONENT_IN_USE: true, UNKNOWN_LEASE: true, PASSTHROUGH_REFUSED: true, UNKNOWN_PASSTHROUGH_TOOL: true, @@ -303,6 +316,22 @@ export const ERROR_TABLE: { readonly [Code in SimlockErrorCode]: ErrorTableEntry cliExitCode: 12, httpStatus: 403, }, + // A refused removal: 409, the component is not in a state that allows it. 12 for the two that + // a retry does not change on its own (not Simlock's; in use until its devices are deleted), + // 11 for the one that passes once the platform's install or removal ends, like `NO_CAPACITY`. + COMPONENT_NOT_OWNED: { + code: "COMPONENT_NOT_OWNED", + kind: "domain", + cliExitCode: 12, + httpStatus: 409, + }, + COMPONENT_IN_USE: { + code: "COMPONENT_IN_USE", + kind: "domain", + cliExitCode: 12, + httpStatus: 409, + }, + COMPONENT_BUSY: { code: "COMPONENT_BUSY", kind: "domain", cliExitCode: 11, httpStatus: 409 }, DOCTOR_UNAVAILABLE: { code: "DOCTOR_UNAVAILABLE", kind: "domain", diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index 630982e85..e11739dee 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -73,6 +73,8 @@ const ROLE_MATRIX: ReadonlyArray<{ input: { platform: "ios", version: "26.4", workers: "all" }, role: "admin", }, + // ADR 0010 §8: removal is destructive, so admin-only. + { name: "component.remove", input: { platform: "ios", version: "26.4" }, role: "admin" }, ]; describe("operation role matrix", () => { @@ -143,6 +145,7 @@ const EFFECT_MATRIX: ReadonlyArray<{ input: { platform: "ios", version: "26.4", workers: "all" }, effect: "write", }, + { name: "component.remove", input: { platform: "ios", version: "26.4" }, effect: "write" }, ]; function resolvedEffect(name: OperationName, input: unknown): unknown { diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 822eb0839..0be831778 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -803,6 +803,35 @@ export const workerInstallComponent = defineOperation({ output: z.object({ results: z.array(workerInstallResultSchema) }), }); +// ---- component.remove (ADR 0010 §8) --------------------------------------------------------- + +/** + * Removes one component Simlock installed: refused with `COMPONENT_NOT_OWNED` when Simlock has + * no record of installing exactly what is installed now, `COMPONENT_IN_USE` while any device + * uses it, Simlock's or not, and `COMPONENT_BUSY` while an install or removal runs or waits on + * that platform. `dryRun` runs every one of those checks and removes nothing, answering + * `would-remove`. Admin-only. `sizeBytes` is the component's size as listed, when known; + * `residue` says what stayed on disk after a removal and how to reclaim it. + */ +// fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. +export const componentRemove = defineOperation({ + name: "component.remove", + role: "admin", + effect: "write", + input: z.object({ + platform: platformSchema, + version: componentVersionSchema, + dryRun: z.boolean().optional(), + }), + output: z.object({ + platform: platformSchema, + version: z.string(), + outcome: z.enum(["removed", "would-remove"]), + sizeBytes: z.number().int().nonnegative().optional(), + residue: z.string().optional(), + }), +}); + // ---- the full registry ---------------------------------------------------------------------- export const OPERATIONS = { @@ -835,6 +864,7 @@ export const OPERATIONS = { "component.install": componentInstall, "component.list": componentList, "worker.install-component": workerInstallComponent, + "component.remove": componentRemove, } as const; /** diff --git a/src/core/component-installer.test.ts b/src/core/component-installer.test.ts index 73d63c89a..36c1138a8 100644 --- a/src/core/component-installer.test.ts +++ b/src/core/component-installer.test.ts @@ -9,13 +9,17 @@ import { type TimerHandle, } from "../ports/index.js"; import { + ComponentBeingRemovedError, ComponentInstaller, ComponentInstallerClosedError, type ComponentInstallerProgress, type ComponentInstallRequest, } from "./component-installer.js"; import { + ComponentBusyError, + ComponentInUseError, ComponentInstallTimeoutError, + ComponentNotOwnedError, DiskSpaceGuard, type DriverComponent, DriverCrashError, @@ -23,6 +27,7 @@ import { } from "./driver.js"; import { DriverCatalog } from "./driver-catalog.js"; import { FakeDriver } from "./fake-driver.js"; +import type { DeviceRecord } from "./domain.js"; import { Registry } from "./registry.js"; import { SerializedDecision } from "./serialized-decision.js"; @@ -1284,3 +1289,490 @@ describe("ComponentInstaller.list", () => { expect(harness.events).toEqual([]); }); }); + +describe("ComponentInstaller.remove", () => { + /** A harness whose iOS driver starts with nothing installed, then has `27.0` installed by Simlock. */ + async function withSimlockInstall( + options: { + readonly componentSizes?: Record; + readonly foreignDevices?: Record; + } = {}, + ) { + const harness = await createHarness({ + drivers: (clock) => [ + new FakeDriver({ availableOsVersions: [], clock, platform: "ios", ...options }), + ], + }); + await harness.installer.install(ios("27.0")); + harness.events.length = 0; + return harness; + } + + function removals(driver: FakeDriver): readonly unknown[] { + return driver.calls + .filter((call) => call.operation === "removeComponent") + .map((call) => call.arguments[0]); + } + + const removeIos = (version: string, extra: { readonly dryRun?: boolean } = {}) => ({ + platform: "ios" as const, + requesterId: "tok_admin", + version, + ...extra, + }); + + it("removes a component with a record and no users, deletes its record, and list no longer shows it", async () => { + const harness = await withSimlockInstall({ componentSizes: { "27.0": 7_000_000_000 } }); + const [record] = harness.registry.snapshot.components; + + await expect(harness.installer.remove(removeIos("27.0"))).resolves.toEqual({ + outcome: "removed", + sizeBytes: 7_000_000_000, + }); + + expect(removals(harness.ios)).toEqual([record?.receipt]); + expect(harness.registry.snapshot.components).toEqual([]); + expect(await harness.installer.list()).toEqual([]); + expect(harness.events).toEqual([ + { + event: "component.removed", + payload: { + componentId: "27.0", + platform: "ios", + requesterId: "tok_admin", + sizeBytes: 7_000_000_000, + version: "27.0", + }, + }, + ]); + }); + + it("carries the driver's residue into the answer and the event", async () => { + const harness = await createHarness({ + drivers: (clock) => [ + new FakeDriver({ + availableOsVersions: [], + clock, + platform: "ios", + removalResidue: "the download stays", + }), + ], + }); + await harness.installer.install(ios("27.0")); + + await expect(harness.installer.remove(removeIos("27.0"))).resolves.toEqual({ + outcome: "removed", + residue: "the download stays", + }); + expect(harness.events.at(-1)).toMatchObject({ + event: "component.removed", + payload: { residue: "the download stays" }, + }); + }); + + it("refuses a component with no record with ComponentNotOwnedError and never calls removeComponent", async () => { + // 26.5 is on the machine, but Simlock did not install it. + const harness = await createHarness(); + + await expect(harness.installer.remove(removeIos("26.5"))).rejects.toBeInstanceOf( + ComponentNotOwnedError, + ); + expect(removals(harness.ios)).toEqual([]); + expect(await harness.installer.list()).toMatchObject([{ version: "26.5" }]); + }); + + it("refuses a record whose receipt no longer matches what is installed with ComponentNotOwnedError and never calls removeComponent", async () => { + const harness = await createHarness(); + await harness.registry.recordComponent({ + installedAt: 1_000, + platform: "ios", + receipt: { install: "1", version: "26.5" }, + version: "26.5", + }); + + await expect(harness.installer.remove(removeIos("26.5"))).rejects.toBeInstanceOf( + ComponentNotOwnedError, + ); + expect(removals(harness.ios)).toEqual([]); + expect(harness.registry.snapshot.components).toHaveLength(1); + }); + + it.each(["provisioning", "ready", "leased", "reclaiming", "quarantined", "shutdown"] as const)( + "refuses a component a %s registry device uses with ComponentInUseError naming the count, and never calls removeComponent", + async (state) => { + const device: DeviceRecord = { + createdAt: 0, + driverData: {}, + driverDeviceId: "udid-1", + id: "dev_1", + mode: "full", + spec: { model: "Phone", osVersion: "27.0", platform: "ios" }, + state, + }; + const harness = await withSimlockInstall(); + // The same installer's view, with one device of that version in the registry. + const installer = new ComponentInstaller({ + clock: harness.clock, + decisions: new SerializedDecision(), + diskSpace: new DiskSpaceGuard(), + drivers: new DriverCatalog(harness.drivers), + eventBus: harness.bus, + filesystem: new MemoryFilesystem(), + registry: { + deleteComponent: (platform, version) => + harness.registry.deleteComponent(platform, version), + recordComponent: (record) => harness.registry.recordComponent(record), + get snapshot() { + return { ...harness.registry.snapshot, devices: [device] }; + }, + }, + timeoutMs, + }); + + const error = await installer.remove(removeIos("27.0")).catch((e: unknown) => e); + + expect(error).toBeInstanceOf(ComponentInUseError); + expect(error).toMatchObject({ devices: 1, foreignDevices: 0 }); + expect(removals(harness.ios)).toEqual([]); + expect(harness.registry.snapshot.components).toHaveLength(1); + }, + ); + + it("refuses a component a foreign device uses with ComponentInUseError naming the count, and never calls removeComponent", async () => { + const harness = await withSimlockInstall({ foreignDevices: { "27.0": 2 } }); + + const error = await harness.installer.remove(removeIos("27.0")).catch((e: unknown) => e); + + expect(error).toBeInstanceOf(ComponentInUseError); + expect(error).toMatchObject({ devices: 0, foreignDevices: 2 }); + expect(removals(harness.ios)).toEqual([]); + }); + + it("refuses, and never calls removeComponent, when the driver's listing rejects", async () => { + const harness = await withSimlockInstall(); + harness.ios.failOn("listComponents", 1, new DriverCrashError("default set unreadable")); + + await expect(harness.installer.remove(removeIos("27.0"))).rejects.toThrow( + "default set unreadable", + ); + expect(removals(harness.ios)).toEqual([]); + expect(harness.registry.snapshot.components).toHaveLength(1); + }); + + it("refuses with ComponentInUseError while a device is being provisioned on it and has no record yet", async () => { + const harness = await withSimlockInstall(); + const release = harness.installer.claimProvision({ osVersion: "27.0", platform: "ios" }); + + await expect(harness.installer.remove(removeIos("27.0"))).rejects.toMatchObject({ + devices: 1, + foreignDevices: 0, + }); + expect(removals(harness.ios)).toEqual([]); + + release(); + await expect(harness.installer.remove(removeIos("27.0"))).resolves.toMatchObject({ + outcome: "removed", + }); + }); + + it("answers a dry run with would-remove and the size, calls no driver verb that changes anything, and keeps the record", async () => { + const harness = await withSimlockInstall({ componentSizes: { "27.0": 7_000_000_000 } }); + const before = harness.ios.calls.length; + + await expect(harness.installer.remove(removeIos("27.0", { dryRun: true }))).resolves.toEqual({ + outcome: "would-remove", + sizeBytes: 7_000_000_000, + }); + + expect(harness.ios.calls.slice(before).map((call) => call.operation)).toEqual([ + "listComponents", + ]); + expect(harness.registry.snapshot.components).toHaveLength(1); + expect(harness.events).toEqual([]); + expect(await harness.installer.list()).toMatchObject([ + { installedBySimlock: true, version: "27.0" }, + ]); + }); + + it.each([false, true])( + "refuses with ComponentBusyError while an install is running on that platform (dry run: %s)", + async (dryRun) => { + const harness = await withSimlockInstall(); + harness.ios.holdInstalls(); + const install = track(harness.installer.install(ios("28.0"))); + await flush(); + expect(installs(harness.ios)).toEqual(["27.0", "28.0"]); + + await expect(harness.installer.remove(removeIos("27.0", { dryRun }))).rejects.toBeInstanceOf( + ComponentBusyError, + ); + expect(removals(harness.ios)).toEqual([]); + + harness.ios.releaseInstalls(); + await flush(); + expect(install.result()).toMatchObject({ outcome: "installed" }); + }, + ); + + it("refuses with ComponentBusyError while an install waits on that platform, before its driver runs", async () => { + const harness = await withSimlockInstall(); + // At the front of the queue, still checking whether it is needed: waiting, not downloading. + void harness.installer + .install(ios("28.0", { stillNeeded: () => new Promise(() => undefined) })) + .catch(() => undefined); + await flush(); + expect(harness.installer.inProgress()).toMatchObject([{ component: "28.0", state: "waiting" }]); + expect(installs(harness.ios)).toEqual(["27.0"]); + + await expect(harness.installer.remove(removeIos("27.0"))).rejects.toBeInstanceOf( + ComponentBusyError, + ); + expect(removals(harness.ios)).toEqual([]); + }); + + it("counts Simlock's devices again inside the decision gate, and refuses one claimed after the listing", async () => { + const decisions = new SerializedDecision(); + const harness = await createHarness({ + decisions, + drivers: (clock) => [new FakeDriver({ availableOsVersions: [], clock, platform: "ios" })], + }); + await harness.installer.install(ios("27.0")); + // Something else holds the gate, so the removal's listing and first count pass before it + // gets its turn there. + let releaseGate!: () => void; + void decisions.run( + () => + new Promise((resolve) => { + releaseGate = resolve; + }), + ); + const removal = track(harness.installer.remove(removeIos("27.0"))); + await flush(); + expect(harness.ios.calls.filter((call) => call.operation === "listComponents")).toHaveLength(1); + expect(removal.settled()).toBe(false); + + harness.installer.claimProvision({ osVersion: "27.0", platform: "ios" }); + releaseGate(); + await flush(); + + expect(removal.error()).toBeInstanceOf(ComponentInUseError); + expect(removal.error()).toMatchObject({ devices: 1 }); + expect(removals(harness.ios)).toEqual([]); + }); + + it("starts an install that arrives during a removal only after the removal has ended", async () => { + const harness = await withSimlockInstall(); + harness.ios.holdRemovals(); + const removal = track(harness.installer.remove(removeIos("27.0"))); + await flush(); + expect(removals(harness.ios)).toHaveLength(1); + + const progress: ComponentInstallerProgress[] = []; + const install = track( + harness.installer.install(ios("28.0", { onProgress: (heard) => progress.push(heard) })), + ); + await flush(); + expect(progress).toEqual([{ stage: "waiting" }]); + expect(installs(harness.ios)).toEqual(["27.0"]); + expect(harness.ios.calls.filter((call) => call.operation === "findComponent")).toHaveLength(1); + expect(harness.installer.inProgress()).toMatchObject([{ component: "28.0", state: "waiting" }]); + + harness.ios.releaseRemovals(); + await flush(); + + expect(removal.result()).toMatchObject({ outcome: "removed" }); + expect(installs(harness.ios)).toEqual(["27.0", "28.0"]); + expect(install.result()).toMatchObject({ outcome: "installed", version: "28.0" }); + }); + + it("refuses a second removal on the platform while one runs with ComponentBusyError", async () => { + const harness = await createHarness({ + drivers: (clock) => [new FakeDriver({ availableOsVersions: [], clock, platform: "ios" })], + }); + await harness.installer.install(ios("27.0")); + await harness.installer.install(ios("28.0")); + harness.ios.holdRemovals(); + const first = track(harness.installer.remove(removeIos("27.0"))); + await flush(); + + await expect(harness.installer.remove(removeIos("28.0"))).rejects.toBeInstanceOf( + ComponentBusyError, + ); + + harness.ios.releaseRemovals(); + await flush(); + expect(first.result()).toMatchObject({ outcome: "removed" }); + }); + + it("refuses every device claimed on the component while it is being removed, and none once the removal has settled", async () => { + const harness = await withSimlockInstall(); + harness.ios.holdRemovals(); + const removal = track(harness.installer.remove(removeIos("27.0"))); + await flush(); + + expect(() => harness.installer.claimProvision({ osVersion: "27.0", platform: "ios" })).toThrow( + ComponentBeingRemovedError, + ); + // Another version is not being removed. + expect(() => + harness.installer.claimProvision({ osVersion: "26.0", platform: "ios" }), + ).not.toThrow(); + + harness.ios.releaseRemovals(); + await flush(); + expect(removal.settled()).toBe(true); + expect(() => + harness.installer.claimProvision({ osVersion: "27.0", platform: "ios" }), + ).not.toThrow(); + }); + + it("keeps the record, clears the mark and emits no component.removed when the driver fails the removal", async () => { + const harness = await withSimlockInstall(); + harness.ios.failOn("removeComponent", 1, new DriverCrashError("simctl runtime delete failed")); + + await expect(harness.installer.remove(removeIos("27.0"))).rejects.toThrow( + "simctl runtime delete failed", + ); + + expect(harness.registry.snapshot.components).toMatchObject([{ version: "27.0" }]); + expect(harness.events).toEqual([]); + expect(() => + harness.installer.claimProvision({ osVersion: "27.0", platform: "ios" }), + ).not.toThrow(); + // The turn is back: an install on the platform starts. + await expect(harness.installer.install(ios("28.0"))).resolves.toMatchObject({ + outcome: "installed", + }); + }); + + it("refuses with ComponentInstallerClosedError, removing nothing, when the daemon stops while the listing is read", async () => { + const harness = await createHarness({ + drivers: (clock) => [ + new FakeDriver({ + availableOsVersions: [], + clock, + latencyMs: { listComponents: 10 }, + platform: "ios", + }), + ], + }); + await harness.installer.install(ios("27.0")); + const removal = track(harness.installer.remove(removeIos("27.0"))); + await flush(); + expect(harness.ios.calls.filter((call) => call.operation === "listComponents")).toHaveLength(1); + + await harness.installer.close(); + harness.clock.advance(10); + await flush(); + + expect(removal.error()).toBeInstanceOf(ComponentInstallerClosedError); + expect(removals(harness.ios)).toEqual([]); + expect(harness.registry.snapshot.components).toHaveLength(1); + }); + + it("ends one claim per release however often that release is called", async () => { + const harness = await withSimlockInstall(); + const first = harness.installer.claimProvision({ osVersion: "27.0", platform: "ios" }); + harness.installer.claimProvision({ osVersion: "27.0", platform: "ios" }); + + first(); + first(); + + expect(await harness.installer.list()).toMatchObject([{ devices: 1, version: "27.0" }]); + }); + + it("refuses a dry run with ComponentInUseError when a Simlock device uses the component", async () => { + const harness = await withSimlockInstall(); + harness.installer.claimProvision({ osVersion: "27.0", platform: "ios" }); + + await expect( + harness.installer.remove(removeIos("27.0", { dryRun: true })), + ).rejects.toMatchObject({ devices: 1, foreignDevices: 0, name: "ComponentInUseError" }); + }); + + it("refuses with ComponentInstallerClosedError once the daemon has stopped, without reading the listing", async () => { + const harness = await withSimlockInstall(); + await harness.installer.close(); + const before = harness.ios.calls.length; + + await expect(harness.installer.remove(removeIos("27.0"))).rejects.toBeInstanceOf( + ComponentInstallerClosedError, + ); + expect(harness.ios.calls.slice(before)).toEqual([]); + }); + + it("resolves close only once a running removal's driver call has returned", async () => { + const harness = await createHarness({ + drivers: (clock) => [ + new FakeDriver({ + availableOsVersions: [], + clock, + // A delay the abort does not cut short, as a platform tool that is slow to exit. + latencyMs: { removeComponent: 10 }, + platform: "ios", + }), + ], + }); + await harness.installer.install(ios("27.0")); + void harness.installer.remove(removeIos("27.0")).catch(() => undefined); + await flush(); + expect(removals(harness.ios)).toHaveLength(1); + + const closing = track(harness.installer.close()); + await flush(); + expect(closing.settled()).toBe(false); + + harness.clock.advance(10); + await flush(); + expect(closing.settled()).toBe(true); + }); + + it("logs a failed removal with who asked, after the driver was called", async () => { + const warnings: { readonly message: string; readonly fields: unknown }[] = []; + const logger: Logger = { + child: () => logger, + debug: () => {}, + error: () => {}, + info: () => {}, + warn: (message, fields) => { + warnings.push({ fields, message }); + }, + }; + const harness = await createHarness({ + drivers: (clock) => [new FakeDriver({ availableOsVersions: [], clock, platform: "ios" })], + logger, + }); + await harness.installer.install(ios("27.0")); + harness.ios.failOn("removeComponent", 1, new DriverCrashError("simctl runtime delete failed")); + + await expect(harness.installer.remove(removeIos("27.0"))).rejects.toThrow( + "simctl runtime delete failed", + ); + + expect(warnings).toEqual([ + { + fields: { + error: "DriverCrashError: simctl runtime delete failed", + platform: "ios", + requesterId: "tok_admin", + version: "27.0", + }, + message: "A component removal failed; Simlock's record of it is kept", + }, + ]); + }); + + it("ends a running removal on close with ComponentInstallerClosedError, and keeps the record", async () => { + const harness = await withSimlockInstall(); + harness.ios.holdRemovals(); + const removal = track(harness.installer.remove(removeIos("27.0"))); + await flush(); + + await harness.installer.close(); + await flush(); + + expect(removal.error()).toBeInstanceOf(ComponentInstallerClosedError); + expect(harness.registry.snapshot.components).toHaveLength(1); + expect(harness.events).toEqual([]); + }); +}); diff --git a/src/core/component-installer.ts b/src/core/component-installer.ts index f70712614..b4152f306 100644 --- a/src/core/component-installer.ts +++ b/src/core/component-installer.ts @@ -6,14 +6,20 @@ import { NoopLogger, type TimerHandle, } from "../ports/index.js"; -import type { Platform } from "./domain.js"; +import type { DeviceSpec, Platform } from "./domain.js"; import { + ComponentBusyError, + ComponentInUseError, type ComponentInstallProgress, type ComponentInstallResult, ComponentInstallTimeoutError, + ComponentNotOwnedError, + type ComponentReceipt, + type ComponentRemoval, type DiskSpaceGuard, type Driver, type DriverComponent, + RuntimeMissingError, sameReceipt, } from "./driver.js"; import type { DriverCatalog } from "./driver-catalog.js"; @@ -70,7 +76,7 @@ export interface ComponentInstallerOptions { readonly filesystem: Pick; /** Hears a driver whose `listComponents` rejects; `list` leaves that driver out. */ readonly logger?: Logger; - readonly registry: Pick; + readonly registry: Pick; /** `downloads.timeoutMs`: one budget per call, from the moment `install` is called. */ readonly timeoutMs: number; } @@ -109,13 +115,50 @@ export interface InstalledComponentListing { readonly foreignDevices: number; } +export interface ComponentRemoveRequest { + readonly platform: Platform; + /** The version as the catalog lists it, which names Simlock's record of installing it. */ + readonly version: string; + /** Run every check a removal runs, and remove nothing. */ + readonly dryRun?: boolean; + /** Who asked, for `component.removed` (safety rule 6). */ + readonly requesterId: string; +} + +export interface ComponentRemoveOutcome { + readonly outcome: "removed" | "would-remove"; + /** The component's size as listed, when the driver could read it. */ + readonly sizeBytes?: number; + /** What stayed on disk after a removal, and how to reclaim it; never on a dry run. */ + readonly residue?: string; +} + +/** + * A device request that resolved to a component being removed (ADR 0010 §8). A + * `RuntimeMissingError`, so a lease request that hits it is rejected with `RUNTIME_MISSING`. + */ +export class ComponentBeingRemovedError extends RuntimeMissingError { + constructor(platform: Platform, version: string) { + super(platform, version); + this.message = `${platform} ${version} is being removed; no new device is created on it`; + this.name = "ComponentBeingRemovedError"; + } +} + +/** One running removal; see `ComponentInstaller.#removals`. */ +interface Removal { + readonly abort: AbortController; + readonly version: string; + marked: boolean; +} + /** `inProgress()` lists at most this many installs, the oldest first. */ const MAX_LISTED_INSTALLS = 16; /** Every call still open when the daemon stops rejects with this; nothing is resumed. */ export class ComponentInstallerClosedError extends Error { - constructor() { - super("The daemon is stopping; the component install was ended"); + constructor(operation: "install" | "removal" = "install") { + super(`The daemon is stopping; the component ${operation} was ended`); this.name = "ComponentInstallerClosedError"; } } @@ -164,11 +207,23 @@ interface InstallCall { * install's error, `ComponentInstallTimeoutError` when its budget runs out, or * `ComponentInstallerClosedError` on `close()`. Settling removes it from its install, cancels its * timer and fires its promise, in one place (`#settle`). + * + * Also the only caller of `Driver.removeComponent` (ADR 0010 §8): a removal holds its platform's + * turn like an install, and `claimProvision` is how device creation learns what is being removed. */ export class ComponentInstaller { readonly #queues = new Map(); readonly #runs = new Set>(); #closed = false; + /** + * The one record of each running removal (architecture rule 12), by the platform whose turn it + * holds: while a platform is here no install on it starts (`#pump`). `marked` is set inside the + * decision gate; from then until the removal leaves this map, on every exit, `claimProvision` + * refuses every device of `version`. `abort` ends the removal on `close()`. + */ + readonly #removals = new Map(); + /** Per `componentKey`, the provisions that have claimed it and not yet registered a device. */ + readonly #provisioning = new Map(); readonly #logger: Logger; @@ -206,8 +261,9 @@ export class ComponentInstaller { } catch { // An observer, like `onProgress`: a throw there must not reach the install. } - if (queue[0] !== install) notify(call, { stage: "waiting" }); - else if (install.latest !== undefined) notify(call, install.latest); + if (queue[0] !== install || this.#removals.has(request.platform)) { + notify(call, { stage: "waiting" }); + } else if (install.latest !== undefined) notify(call, install.latest); this.#pump(request.platform); }); } @@ -250,50 +306,231 @@ export class ComponentInstaller { const listed = await Promise.all( this.options.drivers.select(platform).map(async (driver) => { try { - return { components: await driver.listComponents(), platform: driver.platform }; + return await this.#listDriver(driver); } catch (error: unknown) { this.#logger.warn("A driver could not list its installed components", { error: stableError(error), platform: driver.platform, }); - return { components: [], platform: driver.platform }; + return []; } }), ); - const { components: records, devices } = this.options.registry.snapshot; return listed - .flatMap(({ components, platform: listedPlatform }) => - components.map((component): InstalledComponentListing => { - const record = records.find( - (candidate) => - candidate.platform === listedPlatform && - sameReceipt(candidate.receipt, component.receipt), - ); - return { - devices: devices.filter( - (device) => - device.state !== "deleted" && - device.spec.platform === listedPlatform && - device.spec.osVersion === component.version, - ).length, - foreignDevices: component.foreignDevices, - installedBySimlock: record !== undefined, - platform: listedPlatform, - version: component.version, - ...(record === undefined ? {} : { installedAt: record.installedAt }), - ...optionalFields(component), - }; - }), - ) + .flat() + .map(({ listing }) => listing) .sort(compareListings); } + /** + * Removes a component Simlock installed (ADR 0010 §8), or with `dryRun` runs every check a + * removal runs and stops. Refused, before anything changes, with `ComponentNotOwnedError` when + * Simlock has no record of it or what is installed now is not what the record names, + * `ComponentInUseError` when `list` counts a device of Simlock's or a foreign one on it, and + * `ComponentBusyError` while an install or another removal is running or waiting on the + * platform. A listing that rejects rejects the removal: an unreadable count is never "no users". + * + * A removal holds the platform's turn, so an install that arrives waits behind it. Inside the + * decision gate it counts Simlock's devices again and marks the component as being removed; + * from then until it settles `claimProvision` refuses every device on it. The driver removes + * it; then the record is deleted and `component.removed` emitted. A failure is logged, keeps + * the record, and rethrows. Every exit clears the mark and gives the turn back. + */ + async remove(request: ComponentRemoveRequest): Promise { + if (this.#closed) throw new ComponentInstallerClosedError("removal"); + const { platform, version } = request; + const driver = this.options.drivers.get(platform); + const { receipt, sizeBytes } = await this.#removable(driver, version); + if (this.#closed) throw new ComponentInstallerClosedError("removal"); + // Checked and taken with no `await` between them, so nothing can start on the platform in + // between. `#removals` is the one record of the turn (architecture rule 12). + if (this.#queue(platform).length > 0 || this.#removals.has(platform)) { + throw new ComponentBusyError(platform, version); + } + if (request.dryRun === true) { + return { outcome: "would-remove", ...(sizeBytes === undefined ? {} : { sizeBytes }) }; + } + + const removal: Removal = { abort: new AbortController(), marked: false, version }; + this.#removals.set(platform, removal); + const run = this.#removeHoldingTurn(driver, request, receipt, removal); + const settled = run.then( + () => undefined, + () => undefined, + ); + this.#runs.add(settled); + try { + return await run; + } finally { + // Every exit, a throw included, clears the mark and gives the turn back. + this.#runs.delete(settled); + this.#removals.delete(platform); + this.#pump(platform); + } + } + + /** + * The checks a removal and a dry run share, from `list` (architecture rule 10): Simlock's + * record of this version, a listed component whose receipt equals the record's, and no device + * of Simlock's or a foreign one on it. Answers the receipt to remove and the listed size. + */ + async #removable( + driver: Driver, + version: string, + ): Promise<{ readonly receipt: ComponentReceipt; readonly sizeBytes?: number }> { + const { platform } = driver; + const record = this.options.registry.snapshot.components.find( + (candidate) => candidate.platform === platform && candidate.version === version, + ); + if (record === undefined) { + throw new ComponentNotOwnedError( + platform, + `Simlock has no record of installing ${platform} ${version}, so it will not remove it`, + ); + } + const listed = (await this.#listDriver(driver)).find((entry) => + sameReceipt(entry.receipt, record.receipt), + ); + if (listed === undefined) { + throw new ComponentNotOwnedError( + platform, + `The ${platform} ${version} installed now is not the one Simlock installed, so Simlock ` + + "will not remove it", + ); + } + const { devices, foreignDevices, sizeBytes } = listed.listing; + if (devices > 0 || foreignDevices > 0) { + throw new ComponentInUseError(platform, version, { devices, foreignDevices }); + } + return { receipt: record.receipt, ...(sizeBytes === undefined ? {} : { sizeBytes }) }; + } + + async #removeHoldingTurn( + driver: Driver, + request: ComponentRemoveRequest, + receipt: ComponentReceipt, + removal: Removal, + ): Promise { + const { signal } = removal.abort; + const { platform, version } = request; + await this.options.decisions.run(() => { + const devices = this.#simlockDevices(platform, version); + if (devices > 0) { + throw new ComponentInUseError(platform, version, { devices, foreignDevices: 0 }); + } + removal.marked = true; + }); + let removed: ComponentRemoval; + try { + removed = await driver.removeComponent(receipt, { signal }); + // Committed before `component.removed` is emitted (events rule 3). + await this.options.decisions.run(() => + this.options.registry.deleteComponent(platform, version), + ); + } catch (error: unknown) { + // The driver may have removed it before the failure: who asked and what failed is logged + // (safety rule 6), and the record stands, claiming nothing once its receipt is gone. + this.#logger.warn("A component removal failed; Simlock's record of it is kept", { + error: stableError(error), + platform, + requesterId: request.requesterId, + version, + }); + if (signal.aborted) throw new ComponentInstallerClosedError("removal"); + throw error; + } + const outcome = { + ...(removed.sizeBytes === undefined ? {} : { sizeBytes: removed.sizeBytes }), + ...(removed.residue === undefined ? {} : { residue: removed.residue }), + }; + this.options.eventBus.emit( + "component.removed", + { componentId: version, platform, requesterId: request.requesterId, version, ...outcome }, + "component-installer", + ); + return { outcome: "removed", ...outcome }; + } + + /** + * Claims a device about to be provisioned on `spec`'s platform and version, and answers the + * release that ends the claim. Call it inside the decision gate, before the driver creates + * the device, and release once the device's record is committed or the provision failed. A + * component being removed refuses it with `ComponentBeingRemovedError`; a claim counts as a + * Simlock device in `list` and in a removal's checks, so a removal cannot start under a + * device the registry does not hold yet (ADR 0010 §8). + */ + // fallow-ignore-next-line unused-class-member -- reached through DeviceProvisioner's `components` option, typed as a Pick of this class. + claimProvision(spec: Pick): () => void { + const key = componentKey(spec.platform, spec.osVersion); + const removal = this.#removals.get(spec.platform); + if (removal?.marked === true && removal.version === spec.osVersion) { + throw new ComponentBeingRemovedError(spec.platform, spec.osVersion); + } + this.#provisioning.set(key, (this.#provisioning.get(key) ?? 0) + 1); + let released = false; + return () => { + if (released) return; + released = true; + const remaining = (this.#provisioning.get(key) ?? 0) - 1; + if (remaining > 0) this.#provisioning.set(key, remaining); + else this.#provisioning.delete(key); + }; + } + + /** + * One driver's components, each as `list` reports it and with its receipt. Rejects when the + * driver's listing does: `list` leaves that driver out, and `remove` refuses. + */ + async #listDriver( + driver: Driver, + ): Promise< + { readonly listing: InstalledComponentListing; readonly receipt: ComponentReceipt }[] + > { + const components = await driver.listComponents(); + const records = this.options.registry.snapshot.components; + return components.map((component) => { + const record = records.find( + (candidate) => + candidate.platform === driver.platform && + sameReceipt(candidate.receipt, component.receipt), + ); + return { + listing: { + devices: this.#simlockDevices(driver.platform, component.version), + foreignDevices: component.foreignDevices, + installedBySimlock: record !== undefined, + platform: driver.platform, + version: component.version, + ...(record === undefined ? {} : { installedAt: record.installedAt }), + ...optionalFields(component), + }, + receipt: component.receipt, + }; + }); + } + + /** + * Simlock's own devices of this platform and version: every registry device in any state but + * `deleted`, and every provision that has claimed one and not registered it yet. The one count + * `list` reports and a removal refuses on. + */ + #simlockDevices(platform: Platform, version: string): number { + const registered = this.options.registry.snapshot.devices.filter( + (device) => + device.state !== "deleted" && + device.spec.platform === platform && + device.spec.osVersion === version, + ).length; + return registered + (this.#provisioning.get(componentKey(platform, version)) ?? 0); + } + /** * Ends the running installs through their `AbortSignal`, rejects every open call, and resolves * once each driver run has returned. Nothing is resumed after a restart. */ async close(): Promise { this.#closed = true; + for (const removal of this.#removals.values()) removal.abort.abort(); const error = new ComponentInstallerClosedError(); for (const queue of this.#queues.values()) { for (const install of queue) { @@ -336,7 +573,7 @@ export class ComponentInstaller { #pump(platform: Platform): void { // A waiting install whose calls all left still goes to the front, finds none, and ends. const front = this.#queue(platform)[0]; - if (front === undefined || front.state !== "waiting") return; + if (front === undefined || front.state !== "waiting" || this.#removals.has(platform)) return; front.state = "front"; const run = this.#run(front).finally(() => { this.#runs.delete(run); @@ -537,6 +774,11 @@ function notify(call: InstallCall, progress: ComponentInstallerProgress): void { } } +/** One component's key in `#provisioning`: its platform and version. */ +function componentKey(platform: Platform, version: string): string { + return JSON.stringify([platform, version]); +} + function optionalFields( component: DriverComponent, ): Pick { diff --git a/src/core/device-provisioner.test.ts b/src/core/device-provisioner.test.ts index 1b7e864c4..340aff423 100644 --- a/src/core/device-provisioner.test.ts +++ b/src/core/device-provisioner.test.ts @@ -1,3 +1,7 @@ +import { readdirSync, readFileSync } from "node:fs"; +import { dirname, join, relative } from "node:path"; +import { fileURLToPath } from "node:url"; + import { describe, expect, it, vi } from "vitest"; import { EventBus } from "../bus/index.js"; @@ -9,10 +13,11 @@ import { MemoryLogSink, } from "../ports/index.js"; import { type CapacityReservation } from "./capacity/index.js"; +import { ComponentBeingRemovedError, ComponentInstaller } from "./component-installer.js"; import { DeviceOperationClaims } from "./device-operation-claims.js"; import { DeviceProvisioner } from "./device-provisioner.js"; import { DriverCatalog } from "./driver-catalog.js"; -import { DriverCrashError, BootTimeoutError } from "./driver.js"; +import { DriverCrashError, BootTimeoutError, DiskSpaceGuard } from "./driver.js"; import { FakeDriver } from "./fake-driver.js"; import { ManagedDeviceLifecycle } from "./managed-device-lifecycle.js"; import { Registry } from "./registry.js"; @@ -57,15 +62,26 @@ async function createHarness( new DeviceOperationClaims(), clock, ); + const components = new ComponentInstaller({ + clock, + decisions, + diskSpace: new DiskSpaceGuard(), + drivers: new DriverCatalog([driver]), + eventBus, + filesystem: new MemoryFilesystem(), + registry, + timeoutMs: 1_200_000, + }); const provisioner = new DeviceProvisioner({ catalog: new DriverCatalog([driver]), clock, + components, decisions, lifecycle, ...(logger === undefined ? {} : { logger }), registry, }); - return { clock, driver, eventBus, lifecycle, provisioner, registry }; + return { clock, components, decisions, driver, eventBus, lifecycle, provisioner, registry }; } describe("DeviceProvisioner", () => { @@ -73,6 +89,10 @@ describe("DeviceProvisioner", () => { const harness = await createHarness({ makeReady: 7, provision: 11 }); const pending = harness.provisioner.provision(spec, { reservation: reservation() }); + // The provision is claimed in the decision gate first; the driver's call starts after that. + await vi.waitFor(() => + expect(harness.driver.calls.filter((call) => call.operation === "provision")).toHaveLength(1), + ); harness.clock.advance(11); await vi.waitFor(() => expect(harness.driver.calls.filter((call) => call.operation === "makeReady")).toHaveLength(1), @@ -223,6 +243,7 @@ describe("DeviceProvisioner", () => { const provisioner = new DeviceProvisioner({ catalog: new DriverCatalog([harness.driver]), clock: harness.clock, + components: harness.components, decisions: new SerializedDecision(), lifecycle: harness.lifecycle, registry: { @@ -239,3 +260,111 @@ describe("DeviceProvisioner", () => { expect(harness.driver.calls.filter((call) => call.operation === "destroy")).toEqual([]); }); }); + +describe("DeviceProvisioner and a component removal (ADR 0010 §8)", () => { + const removal = { platform: "ios" as const, requesterId: "tok_admin", version: "26.5" }; + + /** A harness whose 26.5 runtime was installed by Simlock, so it can be removed. */ + async function withSimlockRuntime(latencyMs?: { readonly provision?: number }) { + const harness = await createHarness(latencyMs); + await harness.components.install({ component: "26.5", platform: "ios" }); + return harness; + } + + function driverCalls(harness: { readonly driver: FakeDriver }, operation: string): number { + return harness.driver.calls.filter((call) => call.operation === operation).length; + } + + it("refuses a device on a version being removed before the driver creates it, registers nothing and releases the reservation", async () => { + const harness = await withSimlockRuntime(); + harness.driver.holdRemovals(); + const removing = harness.components.remove(removal); + await vi.waitFor(() => expect(driverCalls(harness, "removeComponent")).toBe(1)); + const reserved = reservation(); + + await expect(harness.provisioner.provision(spec, { reservation: reserved })).rejects.toThrow( + ComponentBeingRemovedError, + ); + + expect(driverCalls(harness, "provision")).toBe(0); + expect(harness.registry.snapshot.devices).toEqual([]); + expect(reserved.releaseCount()).toBe(1); + harness.driver.releaseRemovals(); + await expect(removing).resolves.toMatchObject({ outcome: "removed" }); + }); + + it("counts a device the driver is still creating as in use, so a removal started meanwhile is refused", async () => { + const harness = await withSimlockRuntime({ provision: 50 }); + const provisioning = harness.provisioner.provision(spec, { reservation: reservation() }); + await vi.waitFor(() => expect(driverCalls(harness, "provision")).toBe(1)); + expect(harness.registry.snapshot.devices).toEqual([]); + + await expect(harness.components.remove(removal)).rejects.toMatchObject({ + devices: 1, + foreignDevices: 0, + name: "ComponentInUseError", + }); + expect(driverCalls(harness, "removeComponent")).toBe(0); + + harness.clock.advance(50); + await provisioning; + // Once registered the device is counted by the registry alone, not twice. + const listed = await harness.components.list("ios"); + expect(listed.find((component) => component.version === "26.5")).toMatchObject({ + devices: 1, + }); + }); + + it("is the only code in src that asks a driver to provision or registers a device", () => { + const srcRoot = join(dirname(fileURLToPath(import.meta.url)), ".."); + const sources = (readdirSync(srcRoot, { recursive: true }) as string[]) + .filter((file) => file.endsWith(".ts") && !file.endsWith(".test.ts")) + .map((file) => join(srcRoot, file)); + // Every production source file is read, not a chosen few (testing rule 4). + expect(sources.length).toBeGreaterThan(100); + + const creators = (pattern: RegExp) => + sources + .filter((file) => pattern.test(readFileSync(file, "utf8"))) + .map((file) => relative(srcRoot, file)); + + expect(creators(/\.registerDevice\(/)).toEqual([join("core", "device-provisioner.ts")]); + expect(creators(/driver\.provision\(/)).toEqual([join("core", "device-provisioner.ts")]); + }); + + it("takes its claim inside the decision gate, so the driver creates nothing while another decision holds it", async () => { + const harness = await withSimlockRuntime(); + let releaseGate!: () => void; + void harness.decisions.run( + () => + new Promise((resolve) => { + releaseGate = resolve; + }), + ); + + const provisioning = harness.provisioner.provision(spec, { reservation: reservation() }); + for (let count = 0; count < 100; count += 1) await Promise.resolve(); + + expect(driverCalls(harness, "provision")).toBe(0); + const listed = await harness.components.list("ios"); + expect(listed.find((component) => component.version === "26.5")).toMatchObject({ + devices: 0, + }); + releaseGate(); + await provisioning; + expect(driverCalls(harness, "provision")).toBe(1); + }); + + it("ends its claim when the driver cannot provision, so the component can be removed", async () => { + const harness = await withSimlockRuntime(); + harness.driver.failOn("provision", 1, new DriverCrashError("simctl create failed")); + + await expect( + harness.provisioner.provision(spec, { reservation: reservation() }), + ).rejects.toThrow("simctl create failed"); + + await expect(harness.components.remove(removal)).resolves.toMatchObject({ + outcome: "removed", + }); + }); +}); diff --git a/src/core/device-provisioner.ts b/src/core/device-provisioner.ts index 97e5adb52..830ea4563 100644 --- a/src/core/device-provisioner.ts +++ b/src/core/device-provisioner.ts @@ -1,6 +1,7 @@ import { type Clock, type Logger, NoopLogger } from "../ports/index.js"; import { stableError } from "./stable-error.js"; import type { CapacityReservation } from "./capacity/index.js"; +import type { ComponentInstaller } from "./component-installer.js"; import type { DeviceRecord, DeviceSpec } from "./domain.js"; import { BootTimeoutError, type DriverDevice } from "./driver.js"; import { DriverCatalog } from "./driver-catalog.js"; @@ -25,6 +26,11 @@ export interface DeviceProvisionerRegistry { export interface DeviceProvisionerOptions { readonly catalog: DriverCatalog; readonly clock: Clock; + /** + * The one installer (ADR 0010 §8). Every device record is created here, so this is where a + * component being removed refuses a new device, on every path that provisions one. + */ + readonly components: Pick; readonly decisions: SerializedDecision; readonly lifecycle: Pick; readonly registry: DeviceProvisionerRegistry; @@ -46,6 +52,17 @@ export class DeviceProvisioner { async provision(spec: DeviceSpec, options: ProvisionDeviceOptions): Promise { const driver = this.options.catalog.get(spec.platform); + // Claimed inside the gate, so a removal's own count in the gate sees this device before the + // driver creates it, or this claim sees the removal's mark and refuses. + let releaseClaim: () => void; + try { + releaseClaim = await this.options.decisions.run(() => + this.options.components.claimProvision(spec), + ); + } catch (error: unknown) { + options.reservation.release(); + throw error; + } const startedAt = this.options.clock.now(); let driverDevice: DriverDevice; try { @@ -55,20 +72,27 @@ export class DeviceProvisioner { }); driverDevice = await driver.provision(spec); } catch (error: unknown) { + releaseClaim(); options.reservation.release(); throw error; } let device: DeviceRecord; try { - device = await this.options.decisions.run(() => - this.options.registry.registerDevice({ - driverData: driverDevice.driverData, - driverDeviceId: driverDevice.deviceId, - provisionDuration: this.options.clock.now() - startedAt, - spec, - }), - ); + // The claim ends in the section that commits the record, so the device is counted by one + // of the two at every moment. + device = await this.options.decisions.run(async () => { + try { + return await this.options.registry.registerDevice({ + driverData: driverDevice.driverData, + driverDeviceId: driverDevice.deviceId, + provisionDuration: this.options.clock.now() - startedAt, + spec, + }); + } finally { + releaseClaim(); + } + }); } catch (error: unknown) { options.reservation.release(); throw error; diff --git a/src/core/driver.ts b/src/core/driver.ts index 6b8a912a1..ef514943f 100644 --- a/src/core/driver.ts +++ b/src/core/driver.ts @@ -265,6 +265,19 @@ export interface Driver { * it reads them and never writes there (safety rule 1). */ listComponents(): Promise; + /** + * Removes the installed component whose receipt equals `receipt` (ADR 0010 §8), through + * `removeListedComponent`: it proves the receipt against a fresh listing + * (`ComponentNotOwnedError` when nothing matches), refuses when a foreign device uses it + * (`ComponentInUseError`), runs the platform's own removal bounded by + * `COMPONENT_REMOVAL_TIMEOUT_MS` and ended by `signal`, and lists again to verify it is gone. + * `ComponentInstaller` is its only caller, and calls it only for a component it has a record + * of and no Simlock device uses. + */ + removeComponent( + receipt: ComponentReceipt, + options: { readonly signal: AbortSignal }, + ): Promise; provision(spec: DeviceSpec): Promise; /** * Boots the device and returns it with a freshly read `address`. Never trust the address a @@ -521,6 +534,116 @@ export interface ComponentInstallResult extends InstalledComponent { readonly outcome: "installed" | "already-installed"; } +/** + * What one `removeComponent` freed and left. `sizeBytes` is the component's size as listed just + * before it was removed, absent when the driver could not read it. `residue` is a sentence for + * the operator when something stays on disk after the removal, and how to reclaim it. + */ +export interface ComponentRemoval { + readonly sizeBytes?: number; + readonly residue?: string; +} + +/** How long one platform removal (`simctl runtime delete`, `sdkmanager --uninstall`) may run. */ +export const COMPONENT_REMOVAL_TIMEOUT_MS = 5 * 60_000; + +/** + * The one shape of `Driver.removeComponent`, for every driver alike (ADR 0010 §8): + * + * 1. find the listed component whose receipt equals `receipt`; none is `ComponentNotOwnedError`; + * 2. a foreign device that uses it is `ComponentInUseError`; + * 3. `remove` it, the driver's own platform step; + * 4. list again, and fail when a component with that receipt is still there. + * + * `list` is the driver's listing, the same one `listComponents` answers from, so the "in use" + * answer here and in `component.list` cannot differ. A listing that rejects rejects the removal. + */ +export async function removeListedComponent(options: { + readonly platform: Platform; + readonly receipt: ComponentReceipt; + readonly list: () => Promise; + readonly remove: (component: Listed) => Promise<{ readonly residue?: string }>; +}): Promise { + const { platform, receipt } = options; + const target = (await options.list()).find((listed) => sameReceipt(listed.receipt, receipt)); + if (target === undefined) { + throw new ComponentNotOwnedError( + platform, + `The ${platform} component Simlock installed is no longer installed as Simlock installed ` + + "it, so Simlock will not remove anything", + ); + } + if (target.foreignDevices > 0) { + throw new ComponentInUseError(platform, target.version, { + devices: 0, + foreignDevices: target.foreignDevices, + }); + } + const { residue } = await options.remove(target); + if ((await options.list()).some((listed) => sameReceipt(listed.receipt, receipt))) { + throw new DriverCrashError( + `${platform} ${target.version} is still installed after it was removed`, + ); + } + return { + ...(target.sizeBytes === undefined ? {} : { sizeBytes: target.sizeBytes }), + ...(residue === undefined ? {} : { residue }), + }; +} + +/** + * A removal Simlock refuses because the component is not Simlock's (ADR 0010 §5): there is no + * record of installing it, or what is installed now is not what the record names. + */ +export class ComponentNotOwnedError extends Error { + constructor( + readonly platform: Platform, + message: string, + ) { + super(message); + this.name = "ComponentNotOwnedError"; + } +} + +/** + * A removal Simlock refuses because a device uses the component (ADR 0010 §8): `devices` of + * Simlock's own, in any state but deleted, and `foreignDevices` outside Simlock. + */ +export class ComponentInUseError extends Error { + readonly devices: number; + readonly foreignDevices: number; + + constructor( + readonly platform: Platform, + readonly version: string, + counts: { readonly devices: number; readonly foreignDevices: number }, + ) { + super( + `${platform} ${version} is in use by ${String(counts.devices)} Simlock ` + + `${counts.devices === 1 ? "device" : "devices"} and ${String(counts.foreignDevices)} ` + + `other ${counts.foreignDevices === 1 ? "device" : "devices"}; delete ` + + `${counts.devices + counts.foreignDevices === 1 ? "it" : "them"} before removing it`, + ); + this.name = "ComponentInUseError"; + this.devices = counts.devices; + this.foreignDevices = counts.foreignDevices; + } +} + +/** A removal refused because an install, or another removal, is running or waiting on the platform. */ +export class ComponentBusyError extends Error { + constructor( + readonly platform: Platform, + readonly version: string, + ) { + super( + `Cannot remove ${platform} ${version} while a ${platform} component is being installed or ` + + "removed; try again when it has finished", + ); + this.name = "ComponentBusyError"; + } +} + /** A driver's progress report while it installs: the percentage its installer printed. */ export interface ComponentInstallProgress { readonly stage: "downloading"; diff --git a/src/core/fake-driver.ts b/src/core/fake-driver.ts index 2a7c6bb6a..bc6f0ff52 100644 --- a/src/core/fake-driver.ts +++ b/src/core/fake-driver.ts @@ -4,6 +4,7 @@ import { type ComponentInstallProgress, type ComponentInstallResult, type ComponentReceipt, + type ComponentRemoval, type DeviceRequest, type Driver, type DriverCatalogEntry, @@ -18,6 +19,7 @@ import { type PassthroughCommand, PassthroughRefusedError, type PassthroughContext, + removeListedComponent, RuntimeMissingError, UnknownModelError, } from "./driver.js"; @@ -34,6 +36,7 @@ export type FakeDriverOperation = | "listManaged" | "listCatalog" | "listComponents" + | "removeComponent" /** Recorded like every other call, so a test can pin that it precedes the first destroy. */ | "revalidateRoot" | "findLegacy" @@ -57,6 +60,8 @@ export interface FakeDriverOptions { readonly componentSizes?: Readonly>; /** What `listComponents` reports as each version's foreign devices; 0 for one left out. */ readonly foreignDevices?: Readonly>; + /** What every `removeComponent` reports as left on disk; nothing unless set. */ + readonly removalResidue?: string; /** Stands in for a real driver's owned root; nothing here validates or creates it. */ readonly deviceRoot?: string; readonly estimateMs?: Partial>; @@ -134,10 +139,16 @@ export class FakeDriver implements Driver { #installCount = 0; readonly #install: Pick< FakeDriverOptions, - "componentFootprint" | "componentSizes" | "foreignDevices" | "installProgress" + | "componentFootprint" + | "componentSizes" + | "foreignDevices" + | "installProgress" + | "removalResidue" >; #holdInstalls = false; readonly #pendingInstalls: (() => void)[] = []; + #holdRemovals = false; + readonly #pendingRemovals: (() => void)[] = []; readonly #callCounts = new Map(); readonly #calls: FakeDriverCall[] = []; readonly #clock: Clock; @@ -271,7 +282,7 @@ export class FakeDriver implements Driver { for (const percent of this.#install.installProgress ?? []) { options.onProgress({ percent, stage: "downloading" }); } - if (this.#holdInstalls) await this.#heldInstall(options.signal); + if (this.#holdInstalls) await this.#held(this.#pendingInstalls, options.signal); const version = component === "latest" ? (newestVersion(this.#availableOsVersions) ?? component) : component; const existing = this.#installed(version); @@ -289,6 +300,44 @@ export class FakeDriver implements Driver { */ async listComponents(): Promise { await this.#beforeCall("listComponents"); + return this.#listedComponents(); + } + + /** + * Removes the available version whose receipt this is, through the same steps every driver + * takes (`removeListedComponent`), reading the same listing `listComponents` answers. Scripted + * through `failOn("removeComponent", n, error)`, `holdRemovals()` (it then waits for + * `releaseRemovals()` or its signal) and the `removalResidue` option. + */ + async removeComponent( + receipt: ComponentReceipt, + options: { readonly signal: AbortSignal }, + ): Promise { + await this.#beforeCall("removeComponent", receipt); + return removeListedComponent({ + list: async () => this.#listedComponents(), + platform: this.platform, + receipt, + remove: async ({ version }) => { + if (this.#holdRemovals) await this.#held(this.#pendingRemovals, options.signal); + this.#availableOsVersions.delete(version); + this.#receipts.delete(version); + const residue = this.#install.removalResidue; + return residue === undefined ? {} : { residue }; + }, + }); + } + + holdRemovals(): void { + this.#holdRemovals = true; + } + + releaseRemovals(): void { + this.#holdRemovals = false; + for (const resolve of this.#pendingRemovals.splice(0)) resolve(); + } + + #listedComponents(): readonly DriverComponent[] { return [...this.#availableOsVersions].flatMap((version): DriverComponent[] => { const installed = this.#installed(version); if (installed === undefined) return []; @@ -319,13 +368,13 @@ export class FakeDriver implements Driver { : undefined; } - #heldInstall(signal: AbortSignal): Promise { + #held(pending: (() => void)[], signal: AbortSignal): Promise { return new Promise((resolve, reject) => { if (signal.aborted) { reject(abortReason(signal)); return; } - this.#pendingInstalls.push(resolve); + pending.push(resolve); signal.addEventListener("abort", () => reject(abortReason(signal)), { once: true }); }); } diff --git a/src/core/index.ts b/src/core/index.ts index 4d502151f..40088e7bd 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -23,10 +23,15 @@ export { automaticCleanupRules } from "./cleanup/rules.js"; export { CleanupReaper } from "./reaper.js"; export { BootTimeoutError, + ComponentBusyError, + ComponentInUseError, type ComponentInstallProgress, type ComponentInstallResult, ComponentInstallTimeoutError, + ComponentNotOwnedError, type ComponentReceipt, + type ComponentRemoval, + COMPONENT_REMOVAL_TIMEOUT_MS, type DeviceRequest, DiskSpaceGuard, type Driver, @@ -48,6 +53,7 @@ export { type PassthroughCommand, type PrerequisiteCheck, PassthroughRefusedError, + removeListedComponent, RuntimeMissingError, sameReceipt, UnknownModelError, diff --git a/src/core/lease-acquisition-coordinator.test.ts b/src/core/lease-acquisition-coordinator.test.ts index bb11ed0e1..a5c9253c4 100644 --- a/src/core/lease-acquisition-coordinator.test.ts +++ b/src/core/lease-acquisition-coordinator.test.ts @@ -141,7 +141,15 @@ async function createHarness( ), ); const lifecycle = new ManagedDeviceLifecycle(catalog, registry, decisions, claims, clock); - const provisioner = new DeviceProvisioner({ catalog, clock, decisions, lifecycle, registry }); + const provisioner = new DeviceProvisioner({ + catalog, + clock, + // Never refuses: what a removal does to provisioning is `DeviceProvisioner`'s own test. + components: { claimProvision: () => () => undefined }, + decisions, + lifecycle, + registry, + }); const expiry = new LeaseExpiryScheduler(clock, async () => undefined); const leases = new LeaseLifecycle({ clock, diff --git a/src/core/lease-acquisition-coordinator.ts b/src/core/lease-acquisition-coordinator.ts index 7a43c971f..fc0d616cd 100644 --- a/src/core/lease-acquisition-coordinator.ts +++ b/src/core/lease-acquisition-coordinator.ts @@ -16,7 +16,11 @@ import { type Platform, sameSpec, } from "./domain.js"; -import type { ComponentInstaller, ComponentInstallerProgress } from "./component-installer.js"; +import { + ComponentBeingRemovedError, + type ComponentInstaller, + type ComponentInstallerProgress, +} from "./component-installer.js"; import { BootTimeoutError, type DeviceRequest, @@ -430,6 +434,15 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { this.#wakeQueue(); return; } + // The spec resolved to a component being removed (ADR 0010 §8): no device was created, + // and none will be on it, so the request ends as `RUNTIME_MISSING` rather than retrying. + if (error instanceof ComponentBeingRemovedError) { + await this.options.decisions.run(async () => { + if (waiter.state !== "rejected") this.#reject(waiter, error, "unresolvable-spec"); + }); + this.#wakeQueue(); + return; + } const retry = await this.options.decisions.run(async () => { if (waiter.state === "rejected") return false; waiter.failures += 1; diff --git a/src/core/lease-engine.test.ts b/src/core/lease-engine.test.ts index 3836caa3b..ff70416b8 100644 --- a/src/core/lease-engine.test.ts +++ b/src/core/lease-engine.test.ts @@ -109,7 +109,7 @@ function withCapacity( async function createHarness( options: { /** Stands in for the installer, when a test needs to see whether it was reached at all. */ - readonly components?: Pick; + readonly components?: Pick; readonly driver?: FakeDriver; readonly drivers?: readonly FakeDriver[]; /** The state directory of an earlier harness: loading it again is a daemon restart. */ @@ -236,6 +236,7 @@ describe("LeaseEngine", () => { const asked: unknown[] = []; const harness = await createHarness({ components: { + claimProvision: () => () => undefined, install: async (call) => { asked.push(call); return { outcome: "installed", version: "26.5" }; diff --git a/src/core/lease-engine.ts b/src/core/lease-engine.ts index 790de06f1..7f4fc64c6 100644 --- a/src/core/lease-engine.ts +++ b/src/core/lease-engine.ts @@ -43,10 +43,11 @@ export interface LeaseEngineOptions { readonly clock: Clock; /** * The daemon's one `ComponentInstaller`, built and closed by the composition root. Only the - * lease path reaches it: warm-pool provisioning and startup convergence never do (safety - * rule 4). + * lease path installs through it: warm-pool provisioning and startup convergence never do + * (safety rule 4). Every device provisioned is claimed through it, so none is created on a + * component being removed (ADR 0010 §8). */ - readonly components: Pick; + readonly components: Pick; readonly config: Config; /** * The one decision gate every registry write runs inside. Passed in rather than built here @@ -138,6 +139,7 @@ export class LeaseEngine { this.#provisioner = new DeviceProvisioner({ catalog: this.#drivers, clock: options.clock, + components: options.components, decisions: this.#decisions, lifecycle: this.#deviceLifecycle, ...(options.logger === undefined ? {} : { logger: options.logger }), diff --git a/src/core/registry.test.ts b/src/core/registry.test.ts index 9187e06d7..472a8887a 100644 --- a/src/core/registry.test.ts +++ b/src/core/registry.test.ts @@ -57,6 +57,27 @@ describe("Registry: component records", () => { ]); }); + it("deletes the record of one platform and version, keeps the others, and the deletion survives a reload", async () => { + const filesystem = new MemoryFilesystem(); + const registry = await load(filesystem); + for (const [platform, version] of [ + ["ios", "26.4"], + ["ios", "27.0"], + ["android", "26.4"], + ] as const) { + await registry.recordComponent({ installedAt: 1, platform, receipt: { version }, version }); + } + + await registry.deleteComponent("ios", "26.4"); + + const kept = [ + { installedAt: 1, platform: "ios", receipt: { version: "27.0" }, version: "27.0" }, + { installedAt: 1, platform: "android", receipt: { version: "26.4" }, version: "26.4" }, + ]; + expect(registry.snapshot.components).toEqual(kept); + expect((await load(filesystem)).snapshot.components).toEqual(kept); + }); + it("drops a stored component record whose receipt is not all strings, and keeps the others", async () => { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/home/agent/.simlock"); diff --git a/src/core/registry.ts b/src/core/registry.ts index 5c552ebd0..83a4c1e69 100644 --- a/src/core/registry.ts +++ b/src/core/registry.ts @@ -195,6 +195,20 @@ export class Registry implements LeaseRequestStore { await this.#commit(this.#devices, this.#leases, this.#leaseRequests, components); } + /** + * Deletes the record of the component of this platform and version (ADR 0010 §8). + * `ComponentInstaller` calls it once the driver removed the component, before it emits + * `component.removed`. Deleting a record that is not there commits nothing. + */ + // fallow-ignore-next-line unused-class-member -- called through ComponentInstaller's registry port. + async deleteComponent(platform: Platform, version: string): Promise { + const components = this.#components.filter( + (existing) => existing.platform !== platform || existing.version !== version, + ); + if (components.length === this.#components.length) return; + await this.#commit(this.#devices, this.#leases, this.#leaseRequests, components); + } + async registerDevice({ driverData, driverDeviceId, diff --git a/src/core/test-wiring.ts b/src/core/test-wiring.ts index bae7d0294..455ad16cb 100644 --- a/src/core/test-wiring.ts +++ b/src/core/test-wiring.ts @@ -13,12 +13,12 @@ import { SerializedDecision } from "./serialized-decision.js"; * that passes its own `components` gets the gate alone. */ export function testComponentWiring< - Components extends Pick = ComponentInstaller, + Components extends Pick = ComponentInstaller, >(options: { readonly clock: Clock; readonly drivers: readonly Driver[]; readonly eventBus: Pick; - readonly registry: Pick; + readonly registry: Pick; /** Stands in for the installer, when a test needs to see whether it was reached at all. */ readonly components?: Components | undefined; }): { diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 903beeece..08fc5a5e3 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -149,7 +149,10 @@ async function buildDispatcher( readonly capacity?: Config["capacity"]; /** Stands in for the component installer: a test that needs to see whether it was reached, * or one that reads `status.get`'s installs from an installer of its own. */ - readonly components?: Pick; + readonly components?: Pick< + ComponentInstaller, + "claimProvision" | "inProgress" | "install" | "list" | "remove" + >; } = {}, ) { const clock = overrides.clock ?? new FakeClock(1_000); @@ -1037,6 +1040,7 @@ describe("Dispatcher: status.get installs in progress", () => { eventBus: new EventBus(clock), filesystem: new MemoryFilesystem(), registry: { + deleteComponent: () => Promise.resolve(), recordComponent: () => Promise.resolve(), snapshot: { components: [], devices: [], leases: [] }, }, @@ -1134,7 +1138,13 @@ describe("Dispatcher: component.install", () => { const install = vi.fn(() => Promise.resolve({ outcome: "installed" as const, version: "unreachable" }), ); - return { inProgress: () => [], install, list: () => Promise.resolve([]) }; + return { + claimProvision: () => () => undefined, + inProgress: () => [], + install, + list: () => Promise.resolve([]), + remove: vi.fn(() => Promise.reject(new Error("unreachable"))), + }; } function installCalls(driver: FakeDriver): unknown[] { @@ -2193,3 +2203,173 @@ function testConfig( }, }; } + +describe("Dispatcher: component.remove", () => { + const admin = (overrides: Partial = {}) => + session({ principal: "tok_operator", role: "admin", ...overrides }); + + function driverCalls(driver: FakeDriver, operation: string): number { + return driver.calls.filter((call) => call.operation === operation).length; + } + + /** A dispatcher over a real engine and installer, with iOS 27.0 installed by Simlock. */ + async function withSimlockInstall() { + const built = await buildDispatcher({ + driverOptions: { componentSizes: { "27.0": 7_000_000_000 }, knownModels: ["iPhone 17 Pro"] }, + }); + await built.dispatcher.dispatch( + "component.install", + { platform: "ios", version: "27.0" }, + admin(), + ); + return built; + } + + it("removes a component Simlock installed and emits component.removed with the admin principal as requesterId", async () => { + const { dispatcher, eventBus } = await withSimlockInstall(); + + await expect( + dispatcher.dispatch( + "component.remove", + { platform: "ios", version: "27.0" }, + admin({ principal: "tok_remover" }), + ), + ).resolves.toEqual({ + outcome: "removed", + platform: "ios", + sizeBytes: 7_000_000_000, + version: "27.0", + }); + expect( + eventBus + .replay() + .filter((envelope) => envelope.event === "component.removed") + .map((envelope) => envelope.payload), + ).toEqual([ + { + componentId: "27.0", + platform: "ios", + requesterId: "tok_remover", + sizeBytes: 7_000_000_000, + version: "27.0", + }, + ]); + }); + + it("answers a dry run with would-remove and removes nothing", async () => { + const { dispatcher, driver } = await withSimlockInstall(); + + await expect( + dispatcher.dispatch( + "component.remove", + { dryRun: true, platform: "ios", version: "27.0" }, + admin(), + ), + ).resolves.toEqual({ + outcome: "would-remove", + platform: "ios", + sizeBytes: 7_000_000_000, + version: "27.0", + }); + expect(driverCalls(driver, "removeComponent")).toBe(0); + }); + + it("refuses an agent session with FORBIDDEN and never reaches the installer", async () => { + const { components, dispatcher } = await withSimlockInstall(); + const removals = vi.spyOn(components, "remove"); + + await expect( + dispatcher.dispatch("component.remove", { platform: "ios", version: "27.0" }, session()), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + expect(removals).not.toHaveBeenCalled(); + }); + + it("refuses a component Simlock did not install with COMPONENT_NOT_OWNED", async () => { + const { dispatcher, driver } = await buildDispatcher(); + + const error = await dispatcher + .dispatch("component.remove", { platform: "ios", version: "26.5" }, admin()) + .catch((caught: unknown) => caught); + + expect(classifyError(error)).toBe("COMPONENT_NOT_OWNED"); + expect(driverCalls(driver, "removeComponent")).toBe(0); + }); + + it("refuses a component a leased device uses with COMPONENT_IN_USE, carrying both counts as details", async () => { + const { dispatcher, driver, registry } = await withSimlockInstall(); + await dispatcher.dispatch( + "lease.request", + { model: "iPhone 17 Pro", osVersion: "27.0", platform: "ios" }, + session(), + ); + expect(registry.snapshot.devices.map((device) => device.state)).toEqual(["leased"]); + + const error = await dispatcher + .dispatch("component.remove", { platform: "ios", version: "27.0" }, admin()) + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(DispatchError); + expect(error).toMatchObject({ + code: "COMPONENT_IN_USE", + details: { devices: 1, foreignDevices: 0 }, + }); + expect(classifyError(error)).toBe("COMPONENT_IN_USE"); + expect(driverCalls(driver, "removeComponent")).toBe(0); + }); + + it("refuses with COMPONENT_BUSY while an install runs on that platform", async () => { + const { dispatcher, driver } = await withSimlockInstall(); + driver.holdInstalls(); + const install = dispatcher.dispatch( + "component.install", + { platform: "ios", version: "28.0" }, + admin(), + ); + await vi.waitFor(() => expect(driverCalls(driver, "installComponent")).toBe(2)); + + const error = await dispatcher + .dispatch("component.remove", { platform: "ios", version: "27.0" }, admin()) + .catch((caught: unknown) => caught); + + expect(classifyError(error)).toBe("COMPONENT_BUSY"); + driver.releaseInstalls(); + await install; + }); + + it("rejects a lease request that resolves to the version being removed with RUNTIME_MISSING, and creates no device record", async () => { + const { dispatcher, driver, registry } = await withSimlockInstall(); + driver.holdRemovals(); + const removal = dispatcher.dispatch( + "component.remove", + { platform: "ios", version: "27.0" }, + admin(), + ); + await vi.waitFor(() => expect(driverCalls(driver, "removeComponent")).toBe(1)); + + let leaseError: unknown; + let leaseSettled = false; + void dispatcher + .dispatch( + "lease.request", + { model: "iPhone 17 Pro", osVersion: "27.0", platform: "ios" }, + session(), + ) + .then( + () => undefined, + (caught: unknown) => { + leaseError = caught; + }, + ) + .finally(() => { + leaseSettled = true; + }); + // Rejected while the removal is still running, not queued until it ends. + await vi.waitFor(() => expect(leaseSettled).toBe(true)); + + expect(classifyError(leaseError)).toBe("RUNTIME_MISSING"); + expect(registry.snapshot.devices).toEqual([]); + expect(driverCalls(driver, "provision")).toBe(0); + driver.releaseRemovals(); + await expect(removal).resolves.toMatchObject({ outcome: "removed" }); + }); +}); diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index a501f3c87..b740409ed 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -3,6 +3,7 @@ import { z } from "zod"; import type { EventHistory } from "../bus/index.js"; import { type CleanupReaper, + ComponentInUseError, type ComponentInstaller, type ComponentInstallerProgress, type Config, @@ -88,9 +89,9 @@ export interface DispatcherOptions { /** * The one installer (ADR 0010 §3), shared with the lease path so `component.install` and a * lease request's download join one install, and read for `status.get`'s installs in progress - * and for `component.list`. + * and for `component.list`. `component.remove` goes through it too (ADR 0010 §8). */ - readonly components: Pick; + readonly components: Pick; readonly config: Config; readonly doctor?: Doctor; /** Answers `events.replay`: the ring, or the event file for a `sinceTs`. */ @@ -223,6 +224,7 @@ export class Dispatcher { "token.revoke": this.#tokenRevoke, "component.install": this.#componentInstall, "component.list": this.#componentList, + "component.remove": this.#componentRemove, // "daemon.stop" deliberately absent -- see the class comment; `DaemonServer` never calls // `dispatch()` for a frame type this map has no entry for. }; @@ -647,6 +649,31 @@ export class Dispatcher { components: await this.options.components.list(input.platform), }); + /** + * ADR 0010 §8: an operator's removal of a component Simlock installed. Every check and the + * removal itself are the installer's; this names the admin principal for `component.removed` + * (safety rule 6) and puts the in-use counts on the wire as `COMPONENT_IN_USE`'s details. + */ + #componentRemove: Handler<"component.remove"> = async (input, session) => { + try { + const result = await this.options.components.remove({ + platform: input.platform, + requesterId: session.principal, + version: input.version, + ...(input.dryRun === undefined ? {} : { dryRun: input.dryRun }), + }); + return { platform: input.platform, version: input.version, ...result }; + } catch (error: unknown) { + if (error instanceof ComponentInUseError) { + throw new DispatchError("COMPONENT_IN_USE", error.message, { + devices: error.devices, + foreignDevices: error.foreignDevices, + }); + } + throw error; + } + }; + /** * ADR §11: the daemon is the only owner of `tokens.json` -- `TokenStore.create` never * persists the plaintext `secret`, only its hash, exactly as it did when the CLI called it diff --git a/src/daemon/error-code.ts b/src/daemon/error-code.ts index 48b22b25d..6045eedee 100644 --- a/src/daemon/error-code.ts +++ b/src/daemon/error-code.ts @@ -20,8 +20,10 @@ * dispatcher, so it never reaches HTTP either) -- that stays local to `server.ts`. */ import { + ComponentBusyError, ComponentInstallerClosedError, ComponentInstallTimeoutError, + ComponentNotOwnedError, IdempotencyConflictError, InsufficientDiskSpaceError, LeaseRequestForbiddenError, @@ -136,6 +138,14 @@ export function classifyError(error: unknown): SimlockErrorCode | undefined { if (error instanceof ComponentInstallerClosedError) { return "DAEMON_STOPPING"; } + // ADR 0010 §8's refused removals. `COMPONENT_IN_USE` carries its counts as details, so the + // dispatcher's `component.remove` handler raises it as a `DispatchError` (above). + if (error instanceof ComponentNotOwnedError) { + return "COMPONENT_NOT_OWNED"; + } + if (error instanceof ComponentBusyError) { + return "COMPONENT_BUSY"; + } if (error instanceof UnknownLeaseError) { return "UNKNOWN_LEASE"; } diff --git a/src/daemon/server.ts b/src/daemon/server.ts index f23006539..8343f3a2a 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -139,9 +139,9 @@ export interface DaemonServerEngineOptions { readonly capacity: CapacityReader; readonly catalog: CatalogReader; /** The one component installer (ADR 0010 §3), threaded into the `Dispatcher` for - * `component.install`, `component.list` and `status.get`'s installs; the same instance the lease engine - * downloads through. */ - readonly components: Pick; + * `component.install`, `component.list`, `component.remove` and `status.get`'s installs; the same + * instance the lease engine downloads through. */ + readonly components: Pick; readonly doctor?: Doctor; /** What `events.replay` answers from; see `EventHistory`. */ readonly eventHistory: Pick; @@ -1147,6 +1147,12 @@ export class DaemonServer { frame.payload ?? {}, this.#session(connection), ); + case "component.remove": + return this.#dispatcher.dispatch( + "component.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` diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index 060213760..ba81133ab 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -5,6 +5,8 @@ import { describe, expect, it, vi } from "vitest"; import type { Driver } from "../../core/driver.js"; import { + ComponentInUseError, + ComponentNotOwnedError, OWNED_ROOT_MARKER_FILE, OwnedRootError, PassthroughRefusedError, @@ -2760,8 +2762,159 @@ describe("AndroidDriver listComponents()", () => { ); expect(runner.calls).toHaveLength(callsBeforeListing); }); + + describe("removeComponent()", () => { + const packageName = "system-images;android-35;google_apis;arm64-v8a"; + const signal = () => new AbortController().signal; + + it("removes the image the receipt names with sdkmanager --uninstall and its package, and verifies it is gone", async () => { + const filesystem = await androidFilesystem({ + images: [ + ["35", "google_apis", "arm64-v8a"], + ["35", "default", "arm64-v8a"], + ], + }); + await filesystem.writeFileAtomic(`${googleApis}/system.img`, "0123456789"); + const runner = new InstallReflectingProcessRunner( + [processResult(binaries.sdkmanager, ["--uninstall", packageName])], + filesystem, + ); + const driver = await createDriver(filesystem, runner); + const target = (await driver.listComponents()).find( + (component) => component.variant === "google_apis/arm64-v8a", + ); + + await expect( + driver.removeComponent(target?.receipt ?? {}, { signal: signal() }), + ).resolves.toEqual({ sizeBytes: 10 }); + + expect(runner.calls.map((call) => [call.command, ...call.args])).toEqual([ + [binaries.sdkmanager, "--uninstall", packageName], + ]); + expect((await driver.listComponents()).map(({ variant }) => variant)).toEqual([ + "default/arm64-v8a", + ]); + }); + + it("refuses with ComponentInUseError when an AVD in the user's AVD home names the image, and uninstalls nothing", async () => { + const filesystem = await androidFilesystem({ images: [["35", "google_apis", "arm64-v8a"]] }); + await userAvd(filesystem, "Pixel_8", "system-images/android-35/google_apis/arm64-v8a/"); + // The scripted runner fails any call it was not given, so an uninstall would fail this test. + const runner = new ScriptedProcessRunner([]); + const driver = await createDriver(filesystem, runner); + const [target] = await driver.listComponents(); + + const error = await driver + .removeComponent(target?.receipt ?? {}, { signal: signal() }) + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ComponentInUseError); + expect(error).toMatchObject({ foreignDevices: 1 }); + expect(runner.calls).toEqual([]); + }); + + it("refuses with ComponentNotOwnedError when no installed image has the receipt, and uninstalls nothing", async () => { + const filesystem = await androidFilesystem({ images: [["35", "google_apis", "arm64-v8a"]] }); + const runner = new ScriptedProcessRunner([]); + const driver = await createDriver(filesystem, runner); + + await expect( + driver.removeComponent( + { package: packageName, revision: "1", stamp: "elsewhere@0" }, + { signal: signal() }, + ), + ).rejects.toBeInstanceOf(ComponentNotOwnedError); + expect(runner.calls).toEqual([]); + }); + + it("fails with sdkmanager's output when the uninstall exits non-zero", async () => { + const filesystem = await androidFilesystem({ images: [["35", "google_apis", "arm64-v8a"]] }); + const runner = new ScriptedProcessRunner([ + { + match: { args: ["--uninstall", packageName], command: binaries.sdkmanager }, + result: { code: 1, stderr: "Failed to find package", stdout: "" }, + }, + ]); + const driver = await createDriver(filesystem, runner); + const [target] = await driver.listComponents(); + + await expect( + driver.removeComponent(target?.receipt ?? {}, { signal: signal() }), + ).rejects.toThrow("Failed to find package"); + }); + + it("ends sdkmanager --uninstall when its signal fires", async () => { + const filesystem = await androidFilesystem({ images: [["35", "google_apis", "arm64-v8a"]] }); + const runner = new ScriptedProcessRunner([ + { + hangs: true, + match: { args: ["--uninstall", packageName], command: binaries.sdkmanager }, + }, + ]); + const driver = await createDriver(filesystem, runner); + const [target] = await driver.listComponents(); + const abort = new AbortController(); + + const removal = driver + .removeComponent(target?.receipt ?? {}, { signal: abort.signal }) + .catch((caught: unknown) => caught); + await vi.waitFor(() => expect(runner.calls).toHaveLength(1)); + abort.abort(); + + expect(await settledValue(removal)).toMatchObject({ + message: expect.stringMatching(/was ended before it finished/), + }); + }); + + it("ends sdkmanager --uninstall after five minutes, SIGTERM then SIGKILL, and answers only once it has exited", async () => { + const filesystem = await androidFilesystem({ images: [["35", "google_apis", "arm64-v8a"]] }); + const clock = new FakeClock(); + const runner = new ScriptedProcessRunner([ + { + // Ignores SIGTERM: only the SIGKILL ten seconds later ends it. + hangs: true, + ignoresSigterm: true, + match: { args: ["--uninstall", packageName], command: binaries.sdkmanager }, + }, + ]); + const driver = await createDriver(filesystem, runner, { clock }); + const [target] = await driver.listComponents(); + + let settled = false; + const removal = driver + .removeComponent(target?.receipt ?? {}, { signal: signal() }) + .catch((caught: unknown) => caught) + .finally(() => { + settled = true; + }); + await vi.waitFor(() => expect(runner.calls).toHaveLength(1)); + clock.advance(5 * 60_000); + for (let count = 0; count < 100; count += 1) await Promise.resolve(); + expect(settled).toBe(false); + clock.advance(10_000); + + expect(await settledValue(removal)).toMatchObject({ + message: expect.stringMatching(/timed out after 300000ms/), + }); + }); + }); }); +/** + * What a promise settled with, once it has: a promise still open fails a named assertion rather + * than the test's own timeout, so a deadline that never ends anything reads as that. + */ +async function settledValue(promise: Promise): Promise { + const state: { done: boolean; value: unknown } = { done: false, value: undefined }; + const settle = (value: unknown): void => { + state.done = true; + state.value = value; + }; + void promise.then(settle, settle); + await vi.waitFor(() => expect(state.done).toBe(true)); + return state.value; +} + function bootProbes(runner: ScriptedProcessRunner): number { return runner.calls.filter((call) => call.args.includes("sys.boot_completed")).length; } @@ -3247,6 +3400,12 @@ class InstallReflectingProcessRunner extends ScriptedProcessRunner { options: ProcessRunOptions = {}, ): ProcessHandle { const handle = super.spawn(command, args, options); + const uninstalled = args[0] === "--uninstall" ? imageDirectory(args[1]) : undefined; + if (uninstalled !== undefined) { + void handle.wait().then(async (result) => { + if (result.code === 0) await this.#filesystem.rm(uninstalled); + }); + } if (args[0] === "--install" && typeof args[1] === "string") { const packageName = args[1]; void handle.wait().then((result) => { @@ -3286,6 +3445,14 @@ function installFor( }); } +/** Where sdkmanager puts a `system-images;android-;;` package. */ +function imageDirectory(packageName: string | undefined): string | undefined { + const match = /^system-images;android-(.+);(.+);(.+)$/.exec(packageName ?? ""); + if (match === null) return undefined; + const [, api, tag, abi] = match; + return `${sdk}/system-images/android-${api ?? ""}/${tag ?? ""}/${abi ?? ""}`; +} + function processResult(command: string, args: readonly (string | RegExp)[], stdout = "") { return { match: { args, command }, diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index 7b32a0c22..b0bf6b935 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -6,6 +6,8 @@ import { type ComponentInstallProgress, type ComponentInstallResult, type ComponentReceipt, + type ComponentRemoval, + COMPONENT_REMOVAL_TIMEOUT_MS, type DeviceRequest, type Driver, type DriverCatalogEntry, @@ -24,6 +26,7 @@ import { PassthroughRefusedError, type PassthroughContext, type ReclaimResult, + removeListedComponent, RuntimeMissingError, sameReceipt, } from "../../core/driver.js"; @@ -33,7 +36,7 @@ import { type LegacyDevice, OwnedRootError, } from "../../core/index.js"; -import { runInstallerProcess } from "../installer-process.js"; +import { runBoundedProcess, runInstallerProcess } from "../installer-process.js"; import { isMissingPathError, type Clock, @@ -1210,16 +1213,71 @@ export class AndroidDriver implements Driver { * home whose `config.ini` names the image's directory; that home is only read. */ async listComponents(): Promise { + return (await this.#listedImages()).map(({ image: _image, ...component }) => component); + } + + /** + * Removes the system image whose receipt this is with `sdkmanager --uninstall `, + * through the steps every driver takes (`removeListedComponent`): refused when an AVD in the + * user's own AVD home names it, verified gone afterwards. + */ + async removeComponent( + receipt: ComponentReceipt, + options: { readonly signal: AbortSignal }, + ): Promise { + return removeListedComponent({ + list: () => this.#listedImages(), + platform: this.platform, + receipt, + remove: async ({ image }) => { + await this.#uninstall(systemImagePackage(image.apiLevel, image.tag, image.abi), options); + return {}; + }, + }); + } + + async #uninstall(packageName: string, options: { readonly signal: AbortSignal }): Promise { + const command = `${this.#sdk.sdkmanager} --uninstall ${packageName}`; + let outcome; + try { + outcome = await runBoundedProcess( + this.#processRunner, + this.#clock, + this.#sdk.sdkmanager, + ["--uninstall", packageName], + { signal: options.signal, timeoutMs: COMPONENT_REMOVAL_TIMEOUT_MS }, + ); + } catch (error: unknown) { + throw new DriverCrashError( + `${command} failed: ${error instanceof Error ? error.message : String(error)}`, + ); + } + if (outcome.timedOut) { + throw new DriverCrashError( + `${command} timed out after ${String(COMPONENT_REMOVAL_TIMEOUT_MS)}ms`, + ); + } + if (outcome.stopped) throw new DriverCrashError(`${command} was ended before it finished`); + if (outcome.result.code !== 0) { + throw new DriverCrashError( + `${command} failed: ${outcome.result.stderr || outcome.result.stdout}`, + ); + } + } + + /** `listComponents`' entries, each with the system image it describes. */ + async #listedImages(): Promise<(DriverComponent & { readonly image: SystemImage })[]> { const [images, foreignAvds] = await Promise.all([ this.#installedImages(), this.#foreignAvdImageDirectories(), ]); return Promise.all( - images.map(async (image): Promise => { + images.map(async (image): Promise => { const sizeBytes = await this.#filesystem.directorySize(image.path).catch(() => undefined); const directories = [image.path, relativeImageDirectory(image)]; return { ...(await this.#installedComponent(image)), + image, foreignDevices: foreignAvds.filter((named) => named.some((directory) => directories.includes(directory)), ).length, diff --git a/src/drivers/installer-process.ts b/src/drivers/installer-process.ts index d8b18cad6..a7141cbc6 100644 --- a/src/drivers/installer-process.ts +++ b/src/drivers/installer-process.ts @@ -106,3 +106,38 @@ function killQuietly(handle: ProcessHandle, signal: NodeJS.Signals): void { // Already exited. } } + +/** + * Runs one platform removal (`sdkmanager --uninstall`) like `runInstallerProcess`, with a + * deadline of its own as well as `signal`: whichever comes first ends the process, `SIGTERM` + * then `SIGKILL`. `timedOut` says the deadline did it. + */ +export async function runBoundedProcess( + runner: ProcessRunner, + clock: Clock, + command: string, + args: readonly string[], + options: { readonly signal: AbortSignal; readonly timeoutMs: number }, +): Promise { + const bounded = new AbortController(); + let timedOut = false; + const timer = clock.setTimer(options.timeoutMs, () => { + timedOut = true; + bounded.abort(); + }); + const forward = (): void => { + bounded.abort(); + }; + if (options.signal.aborted) bounded.abort(); + else options.signal.addEventListener("abort", forward, { once: true }); + try { + const outcome = await runInstallerProcess(runner, clock, command, args, { + onProgress: () => undefined, + signal: bounded.signal, + }); + return { ...outcome, timedOut }; + } finally { + clock.cancel(timer); + options.signal.removeEventListener("abort", forward); + } +} diff --git a/src/drivers/ios/index.test.ts b/src/drivers/ios/index.test.ts index 50d15b2b8..a0f8a1504 100644 --- a/src/drivers/ios/index.test.ts +++ b/src/drivers/ios/index.test.ts @@ -6,6 +6,8 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { BootTimeoutError, + ComponentInUseError, + ComponentNotOwnedError, DriverCrashError, OwnedRootError, OWNED_ROOT_MARKER_FILE, @@ -1584,6 +1586,14 @@ describe("IosSimctlDriver", () => { expect(message).not.toMatch(/download|install/i); }); + it("points the runtime delete refusal at simlock component remove", async () => { + const driver = await createDriver(new ScriptedProcessRunner([])); + + expect(() => driver.passthrough(["runtime", "delete", "26.5"])).toThrow( + /use `simlock component remove ios `/, + ); + }); + it("still proxies the runtime operations that only read", async () => { const driver = await createDriver(new ScriptedProcessRunner([])); @@ -3384,8 +3394,206 @@ describe("IosSimctlDriver listComponents()", () => { await expect(driver.listComponents()).rejects.toBeInstanceOf(DriverCrashError); }); + + describe("removeComponent()", () => { + const target = image("26.4", "23E244", { sizeBytes: 7_000_000_000 }); + const other = image("18.4", "22E238"); + const receipt = { build: "23E244", image: "IMG-26.4-23E244" }; + const deleteInvocation = simctl("runtime", "delete", "IMG-26.4-23E244"); + const deleted = { match: deleteInvocation, result: { code: 0, stderr: "", stdout: "" } }; + const signal = () => new AbortController().signal; + + async function assetStore(builds: readonly (readonly [string, string])[]): Promise { + const filesystem = new MemoryFilesystem(); + for (const [index, [version, build]] of builds.entries()) { + const bundle = `${IOS_RUNTIME_ASSET_ROOT}/bundle-${String(index)}.asset`; + await filesystem.mkdirp(bundle); + await filesystem.writeFileAtomic(`${bundle}/Info.plist`, assetInfoPlist(version, build)); + } + return filesystem; + } + + it("deletes the image the receipt names with simctl runtime delete and no --keep-asset, and reports no residue when its download is gone", async () => { + const runner = new ScriptedProcessRunner([ + imagesListed([target, other]), + defaultSetListed({}), + deleted, + imagesListed([other]), + defaultSetListed({}), + ]); + // Other builds' downloads are in the store, one of them of the same version; this one's + // is not. + const filesystem = await assetStore([ + ["18.4", "22E238"], + ["26.4", "23E200"], + ]); + const driver = await createDriver(runner, new FakeClock(), filesystem); + + await expect(driver.removeComponent(receipt, { signal: signal() })).resolves.toEqual({ + sizeBytes: 7_000_000_000, + }); + expect(runner.calls[2]?.args).toEqual(deleteInvocation.args); + }); + + it("reports residue naming Xcode's Settings -> Platforms when the build's download is still in the asset store", async () => { + const runner = new ScriptedProcessRunner([ + imagesListed([target]), + defaultSetListed({}), + deleted, + imagesListed([]), + defaultSetListed({}), + ]); + const filesystem = await assetStore([["26.4", "23E244"]]); + const driver = await createDriver(runner, new FakeClock(), filesystem); + + const removal = await driver.removeComponent(receipt, { signal: signal() }); + + expect(removal.residue).toContain("26.4 (23E244)"); + expect(removal.residue).toContain(IOS_RUNTIME_ASSET_ROOT); + expect(removal.residue).toContain("Xcode's Settings -> Platforms"); + // Read only: the bundle is still there. + await expect(filesystem.exists(`${IOS_RUNTIME_ASSET_ROOT}/bundle-0.asset`)).resolves.toBe( + true, + ); + }); + + it("fails with simctl's own error when runtime delete exits non-zero", async () => { + // No listing after the failure: the scripted runner fails any call it was not given. + const runner = new ScriptedProcessRunner([ + imagesListed([target]), + defaultSetListed({}), + { + match: deleteInvocation, + result: { code: 1, stderr: "Unable to delete runtime: in use", stdout: "" }, + }, + ]); + const driver = await createDriver(runner); + + await expect(driver.removeComponent(receipt, { signal: signal() })).rejects.toThrow( + "Unable to delete runtime: in use", + ); + expect(runner.calls).toHaveLength(3); + }); + + it("refuses with ComponentInUseError when a device in the default device set uses the runtime, and deletes nothing", async () => { + // The scripted runner fails any call it was not given, so a delete would fail this test. + const runner = new ScriptedProcessRunner([ + imagesListed([target]), + defaultSetListed({ [target.runtime]: 1 }), + ]); + const driver = await createDriver(runner); + + const error = await driver + .removeComponent(receipt, { signal: signal() }) + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ComponentInUseError); + expect(error).toMatchObject({ foreignDevices: 1 }); + expect(runner.calls).toHaveLength(2); + }); + + it("refuses with ComponentNotOwnedError when no listed image has the receipt, and deletes nothing", async () => { + const runner = new ScriptedProcessRunner([imagesListed([target]), defaultSetListed({})]); + const driver = await createDriver(runner); + + await expect( + driver.removeComponent({ build: "23E244", image: "IMG-OTHER" }, { signal: signal() }), + ).rejects.toBeInstanceOf(ComponentNotOwnedError); + expect(runner.calls).toHaveLength(2); + }); + + it("fails when the image is still listed after simctl answered", async () => { + const runner = new ScriptedProcessRunner([ + imagesListed([target]), + defaultSetListed({}), + deleted, + imagesListed([target]), + defaultSetListed({}), + ]); + const driver = await createDriver(runner); + + await expect(driver.removeComponent(receipt, { signal: signal() })).rejects.toThrow( + "ios 26.4 is still installed after it was removed", + ); + }); + + it("ends simctl runtime delete after five minutes, SIGTERM then SIGKILL, and answers only once it has exited", async () => { + // Ignores SIGTERM: only the SIGKILL ten seconds later ends it. + const stubborn = { hangs: true, ignoresSigterm: true, match: deleteInvocation }; + const clock = new FakeClock(); + const runner = new ScriptedProcessRunner([ + imagesListed([target]), + defaultSetListed({}), + stubborn, + ]); + const driver = await createDriver(runner, clock); + let settled = false; + const removal = driver + .removeComponent(receipt, { signal: signal() }) + .catch((caught: unknown) => caught) + .finally(() => { + settled = true; + }); + await vi.waitFor(() => expect(runner.calls).toHaveLength(3)); + + clock.advance(5 * 60_000); + await flushMicrotasks221(); + expect(settled).toBe(false); + clock.advance(10_000); + + expect(await settledValue(removal)).toMatchObject({ + message: expect.stringMatching(/timed out after 300000ms/), + }); + }); + + it("ends simctl runtime delete when its signal fires, and starts none when it already has", async () => { + const abort = new AbortController(); + const runner = new ScriptedProcessRunner([ + imagesListed([target]), + defaultSetListed({}), + { hangs: true, match: deleteInvocation }, + ]); + const driver = await createDriver(runner); + const aborted = driver + .removeComponent(receipt, { signal: abort.signal }) + .catch((caught: unknown) => caught); + await vi.waitFor(() => expect(runner.calls).toHaveLength(3)); + abort.abort(); + expect(await settledValue(aborted)).toMatchObject({ + message: expect.stringMatching(/was ended before it finished/), + }); + + // The scripted runner fails any call it was not given, so a delete would fail this. + const lateRunner = new ScriptedProcessRunner([imagesListed([target]), defaultSetListed({})]); + const lateDriver = await createDriver(lateRunner); + await expect( + lateDriver.removeComponent(receipt, { signal: AbortSignal.abort() }), + ).rejects.toThrow(/was ended before it finished/); + expect(lateRunner.calls).toHaveLength(2); + }); + }); }); +/** Lets queued continuations run, so a test can see that something has not happened yet. */ +async function flushMicrotasks221(): Promise { + for (let count = 0; count < 100; count += 1) await Promise.resolve(); +} + +/** + * What a promise settled with, once it has: a promise still open fails a named assertion rather + * than the test's own timeout, so a deadline that never ends anything reads as that. + */ +async function settledValue(promise: Promise): Promise { + const state: { done: boolean; value: unknown } = { done: false, value: undefined }; + const settle = (value: unknown): void => { + state.done = true; + state.value = value; + }; + void promise.then(settle, settle); + await vi.waitFor(() => expect(state.done).toBe(true)); + return state.value; +} + describe("IosSimctlDriver toolVersions()", () => { it("reports the Xcode version and build that xcodebuild -version prints", async () => { const runner = new ScriptedProcessRunner([ diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index 220ae7143..177f16d35 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -5,6 +5,8 @@ import { type ComponentInstallProgress, type ComponentInstallResult, type ComponentReceipt, + type ComponentRemoval, + COMPONENT_REMOVAL_TIMEOUT_MS, type DeviceRequest, type Driver, type DriverAdvisory, @@ -24,6 +26,7 @@ import { type PassthroughCommand, PassthroughRefusedError, type ObservedRunState, + removeListedComponent, RuntimeMissingError, sameReceipt, UnknownModelError, @@ -37,7 +40,7 @@ import type { ProcessResult, ProcessRunner, } from "../../ports/index.js"; -import { runInstallerProcess } from "../installer-process.js"; +import { runBoundedProcess, runInstallerProcess } from "../installer-process.js"; import { labelsFor, resolveSlimCategories, slimSignature } from "./slim-labels.js"; const COMMAND_TIMEOUT_MS = 30_000; @@ -532,6 +535,81 @@ export class IosSimctlDriver implements Driver { * An image that reports no version names no component and is left out. */ async listComponents(): Promise { + return (await this.#listedImages()).map(({ image: _image, ...component }) => component); + } + + /** + * Removes the runtime image whose receipt this is with `simctl runtime delete ` -- no + * `--keep-asset`, so CoreSimulator is asked to let go of its download too -- through the steps + * every driver takes (`removeListedComponent`): refused when a device in the machine's default + * set uses it, verified gone afterwards. When the download is still in the macOS asset store + * afterwards (#79), `residue` says so and how to reclaim it; Simlock never deletes a file there. + */ + async removeComponent( + receipt: ComponentReceipt, + options: { readonly signal: AbortSignal }, + ): Promise { + return removeListedComponent({ + list: () => this.#listedImages(), + platform: this.platform, + receipt, + remove: async ({ image, version }) => { + await this.#deleteRuntimeImage(image.identifier, options.signal); + return this.#downloadResidue(image, version); + }, + }); + } + + /** + * `simctl runtime delete `, scoped like every other call, through the same bounded + * runner the Android removal uses: it ends at `COMPONENT_REMOVAL_TIMEOUT_MS` or when `signal` + * fires, `SIGTERM` then `SIGKILL`, and answers only once the process has exited. + */ + async #deleteRuntimeImage(identifier: string, signal: AbortSignal): Promise { + const args = ["runtime", "delete", identifier]; + const command = `simctl ${args.join(" ")}`; + let outcome; + try { + outcome = await runBoundedProcess( + this.#processRunner, + this.#clock, + "xcrun", + this.#scopedSimctlArgv(args), + { signal, timeoutMs: COMPONENT_REMOVAL_TIMEOUT_MS }, + ); + } catch (error: unknown) { + throw new DriverCrashError(`${command} failed: ${errorMessage(error)}`); + } + if (outcome.timedOut) { + throw new DriverCrashError( + `${command} timed out after ${String(COMPONENT_REMOVAL_TIMEOUT_MS)}ms`, + ); + } + if (outcome.stopped) throw new DriverCrashError(`${command} was ended before it finished`); + this.#assertSuccessful(args, outcome.result); + } + + /** + * What `removeComponent` reports when the removed image's download is still in the asset + * store: matched by build, or by version for an image that names no build. + */ + async #downloadResidue(image: RuntimeImage, version: string): Promise<{ residue?: string }> { + const left = (await this.#downloadedRuntimeAssets()).some((asset) => + image.build === undefined ? asset.version === version : asset.build === image.build, + ); + if (!left) return {}; + const label = image.build === undefined ? version : `${version} (${image.build})`; + return { + residue: + `The download of iOS ${label} (${IOS_RUNTIME_ASSET_APPROX_SIZE}) is still in ` + + `${IOS_RUNTIME_ASSET_ROOT}; \`simctl runtime delete\` did not reclaim it and Simlock ` + + "does not delete files there -- remove the platform in Xcode's Settings -> Platforms " + + "to get the space back", + }; + } + + /** `listComponents`' entries, each with the runtime image it describes. */ + async #listedImages(): Promise<(DriverComponent & { readonly image: RuntimeImage })[]> { const [images, defaultSet] = await Promise.all([ this.#loadRuntimeImages(), this.#legacySimctl(["list", "-j", "devices"], COMMAND_TIMEOUT_MS), @@ -543,19 +621,22 @@ export class IosSimctlDriver implements Driver { if (error instanceof DriverCrashError) throw error; throw new DriverCrashError(`Could not parse simctl device list: ${errorMessage(error)}`); } - return images.filter(isIosImage).flatMap((image): DriverComponent[] => - image.version === undefined - ? [] - : [ - { - foreignDevices: foreign.get(image.runtimeIdentifier) ?? 0, - receipt: imageReceipt(image), - version: image.version, - ...(image.build === undefined ? {} : { variant: image.build }), - ...(image.sizeBytes === undefined ? {} : { sizeBytes: image.sizeBytes }), - }, - ], - ); + return images + .filter(isIosImage) + .flatMap((image): (DriverComponent & { readonly image: RuntimeImage })[] => + image.version === undefined + ? [] + : [ + { + foreignDevices: foreign.get(image.runtimeIdentifier) ?? 0, + image, + receipt: imageReceipt(image), + version: image.version, + ...(image.build === undefined ? {} : { variant: image.build }), + ...(image.sizeBytes === undefined ? {} : { sizeBytes: image.sizeBytes }), + }, + ], + ); } /** The receipt of every runtime installed right now, before an installer run. */ @@ -1334,7 +1415,7 @@ export class IosSimctlDriver implements Driver { if (verb === "runtime" && operands.find((operand) => !operand.startsWith("-")) === "delete") { this.#refuse( "runtime delete", - "it deletes a runtime shared with Xcode and other tools. Delete it through Xcode if that is really what you meant.", + "it deletes a runtime shared with Xcode and other tools. To remove a runtime Simlock added, use `simlock component remove ios `; delete any other through Xcode.", ); } } @@ -1552,12 +1633,16 @@ export class IosSimctlDriver implements Driver { /** * The single insertion point for `--set`, which scopes every subcommand to the root this * driver owns and must therefore precede the subcommand. Every call in this file is - * spawned through here or through `#invokeLegacySimctl`, and nothing else: a scoped call - * that slipped past both would address the machine's default set, where Simlock can prove - * nothing about what it touches. + * spawned with these arguments or through `#invokeLegacySimctl`, and nothing else: a scoped + * call that slipped past both would address the machine's default set, where Simlock can + * prove nothing about what it touches. */ + #scopedSimctlArgv(args: readonly string[]): string[] { + return ["simctl", "--set", this.#deviceRoot, ...args]; + } + async #invokeSimctl(args: readonly string[], timeoutMs: number): Promise { - return this.#invokeXcrun(["simctl", "--set", this.#deviceRoot, ...args], timeoutMs); + return this.#invokeXcrun(this.#scopedSimctlArgv(args), timeoutMs); } /** diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index 0e4977add..249b1a082 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -669,6 +669,22 @@ describe("GatewayDispatcher", () => { message: "component.list lists one machine's components; run it against a worker", }); }); + + it("component.remove answers UNSUPPORTED_IN_GATEWAY_MODE to an admin session, saying it removes from one machine (ADR 0010 §8)", async () => { + const { dispatcher } = harness(); + + await expect( + dispatcher.dispatch( + "component.remove", + { platform: "ios", version: "26.4" }, + session({ role: "admin" }), + ), + ).rejects.toMatchObject({ + code: "UNSUPPORTED_IN_GATEWAY_MODE", + details: { operation: "component.remove" }, + message: "component.remove removes a component from one machine; run it against a worker", + }); + }); }); describe("lease lifecycle and device.exec (#118)", () => { diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts index 4ac70d251..e0d8c057b 100644 --- a/src/gateway/dispatcher.ts +++ b/src/gateway/dispatcher.ts @@ -16,7 +16,8 @@ * 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 -- * and `component.install` (ADR 0010 §7), which installs on one machine; its message points at - * `worker.install-component`, which names the workers to install on. + * `worker.install-component`, which names the workers to install on. `component.list` and + * `component.remove` (§8) list and remove one machine's components. * 3. *(Formerly "refused until #118" -- the fleet queue, routing, and lease/exec forwarding this * module now implements. Nothing is left in this population; the type below still enforces * that every operation but `daemon.stop` is accounted for.)* @@ -182,6 +183,10 @@ export class GatewayDispatcher { "component.list", "component.list lists one machine's components; run it against a worker", ), + "component.remove": unsupportedByDesign( + "component.remove", + "component.remove removes a component from one machine; run it against a worker", + ), "lease.request": this.#leaseRequest, "lease.renew": this.#leaseRenew, diff --git a/src/http/app.test.ts b/src/http/app.test.ts index a870ec32b..1d1a5e595 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -317,6 +317,83 @@ describe("GET /v1/components", () => { }); }); +describe("DELETE /v1/components/{platform}/{version}", () => { + it("dispatches component.remove with the path's platform and version, and answers its result as JSON", async () => { + const { app, dispatcher } = buildHarness(); + const answer = { outcome: "removed", platform: "ios", sizeBytes: 7, version: "26.4" }; + dispatcher.handlers["component.remove"] = (input) => { + expect(input).toEqual({ platform: "ios", version: "26.4" }); + return answer; + }; + + const response = await app.request("/v1/components/ios/26.4", { + headers: operatorAuth, + method: "DELETE", + }); + + expect(response.status).toBe(200); + expect(response.headers.get("content-type")).toMatch(/application\/json/); + expect(await response.json()).toEqual(answer); + }); + + it.each([ + ["true", true], + ["false", false], + ])("passes ?dryRun=%s through as dryRun", async (query, dryRun) => { + const { app, dispatcher } = buildHarness(); + dispatcher.handlers["component.remove"] = (input) => { + expect(input).toEqual({ dryRun, platform: "android", version: "35" }); + return { outcome: "would-remove", platform: "android", version: "35" }; + }; + + const response = await app.request(`/v1/components/android/35?dryRun=${query}`, { + headers: operatorAuth, + method: "DELETE", + }); + + expect(response.status).toBe(200); + }); + + it("400s a dryRun that is not true or false, before ever dispatching", async () => { + const { app, dispatcher } = buildHarness(); + dispatcher.handlers["component.remove"] = () => { + throw new Error("should not be called"); + }; + + const response = await app.request("/v1/components/ios/26.4?dryRun=yes", { + headers: operatorAuth, + method: "DELETE", + }); + + expect(response.status).toBe(400); + }); + + it("answers COMPONENT_IN_USE with 409 and both counts in the body", async () => { + const { app, dispatcher } = buildHarness(); + dispatcher.handlers["component.remove"] = () => { + throw new DispatchError("COMPONENT_IN_USE", "ios 26.4 is in use", { + devices: 1, + foreignDevices: 2, + }); + }; + + const response = await app.request("/v1/components/ios/26.4", { + headers: operatorAuth, + method: "DELETE", + }); + + expect(response.status).toBe(409); + expect(await response.json()).toEqual({ + error: { + code: "COMPONENT_IN_USE", + devices: 1, + foreignDevices: 2, + message: "ios 26.4 is in use", + }, + }); + }); +}); + describe("POST /v1/lease-requests", () => { it("creates a request resource, 201 with a Location header", async () => { const { app, dispatcher } = buildHarness(); diff --git a/src/http/app.ts b/src/http/app.ts index eab136fc8..25d5599e9 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -234,6 +234,25 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa return c.json(result); }); + // ADR 0010 §8: an admin removal, answered as one JSON body. Which platforms and versions are + // valid, and who may remove, are `component.remove`'s own answers through the dispatcher. + app.delete("/v1/components/:platform/:version", agentAuth, async (c) => { + const dryRun = c.req.query("dryRun"); + if (dryRun !== undefined && dryRun !== "true" && dryRun !== "false") { + throw badRequest("dryRun must be true or false"); + } + const result = await deps.dispatch( + "component.remove", + { + platform: c.req.param("platform"), + version: c.req.param("version"), + ...(dryRun === undefined ? {} : { dryRun: dryRun === "true" }), + }, + buildHttpSession(c.get("identity")), + ); + return c.json(result); + }); + app.post("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/v1/lease-requests", agentAuth, jsonBody(leaseRequestBodySchema), async (c) => { const identity = c.get("identity"); const body = c.req.valid("json"); diff --git a/src/simlock-client/client.test.ts b/src/simlock-client/client.test.ts index 16470133c..0db0b7504 100644 --- a/src/simlock-client/client.test.ts +++ b/src/simlock-client/client.test.ts @@ -195,6 +195,23 @@ describe("connectSimlock: handshake", () => { await expect(callPromise).resolves.toEqual(answer); }); + it("removes a component from an admin client with component.remove, sending the input and returning the daemon's answer", async () => { + const connection = new ScriptedConnection(); + const connectPromise = connectSimlockAdmin({ connection, credential: "operator-secret" }); + await flushMicrotasks(); + completeHello(connection, { role: "admin" }); + const client = await connectPromise; + const answer = { outcome: "would-remove", platform: "ios", sizeBytes: 7, version: "26.4" }; + + const callPromise = client.removeComponent({ dryRun: true, platform: "ios", version: "26.4" }); + await flushMicrotasks(); + const call = connection.lastSentOf("component.remove")!; + expect(call.payload).toEqual({ dryRun: true, platform: "ios", version: "26.4" }); + connection.reply(call.id, answer); + + await expect(callPromise).resolves.toEqual(answer); + }); + it("wraps a malformed daemon response instead of throwing a raw parse failure", async () => { const connection = new ScriptedConnection(); const connectPromise = connectSimlock({ connection }); diff --git a/src/simlock-client/client.ts b/src/simlock-client/client.ts index ae2c135de..2d4a83dbb 100644 --- a/src/simlock-client/client.ts +++ b/src/simlock-client/client.ts @@ -35,6 +35,8 @@ import type { ComponentInstallOutput, ComponentListInput, ComponentListOutput, + ComponentRemoveInput, + ComponentRemoveOutput, DaemonStopOutput, DeviceRecoveredPush, DeviceUnhealthyPush, @@ -92,6 +94,8 @@ export type { ComponentInstallProgress, ComponentListInput, ComponentListOutput, + ComponentRemoveInput, + ComponentRemoveOutput, DaemonStopOutput, DeviceRecoveredPush, DeviceUnhealthyPush, @@ -265,6 +269,13 @@ export interface SimlockAdminClient extends SimlockClient { input: WorkerInstallComponentInput, options?: InstallComponentOnWorkersOptions, ): Promise; + + /** + * ADR 0010 §8: removes one component Simlock installed, or with `dryRun: true` runs every + * check and removes nothing. Refused with `COMPONENT_NOT_OWNED`, `COMPONENT_IN_USE` (with the + * counts as details) or `COMPONENT_BUSY`. + */ + removeComponent(input: ComponentRemoveInput): Promise; } /** Internal: builds either client. `admin` toggles only which methods the returned object @@ -394,6 +405,7 @@ function buildDegradedClient( removeWorker: () => rejected(), installComponent: () => rejected(), installComponentOnWorkers: () => rejected(), + removeComponent: () => rejected(), }; return client; } @@ -636,6 +648,10 @@ class SimlockClientImpl { return this.#call("worker.remove", input); } + removeComponent(input: ComponentRemoveInput): Promise { + return this.#call("component.remove", input); + } + // ---- abort (ADR §10) ------------------------------------------------------------------------ /** diff --git a/src/simlock-client/types.ts b/src/simlock-client/types.ts index 6163c46e0..feb36ad12 100644 --- a/src/simlock-client/types.ts +++ b/src/simlock-client/types.ts @@ -86,6 +86,8 @@ export type ComponentListInput = OpInput<"component.list">; export type ComponentListOutput = OpOutput<"component.list">; export type WorkerInstallComponentInput = OpInput<"worker.install-component">; export type WorkerInstallComponentOutput = OpOutput<"worker.install-component">; +export type ComponentRemoveInput = OpInput<"component.remove">; +export type ComponentRemoveOutput = OpOutput<"component.remove">; // ---- pushes ---------------------------------------------------------------------------------