diff --git a/docs/CLI.md b/docs/CLI.md index 6ab8ddf2a..a1aafd95b 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -2606,6 +2606,37 @@ as a contract. Growth is bounded: once the file passes `log.rotateBytes` it is rotated to `daemon.log.1` (replacing any previous generation), so `logs` always shows the current file with the immediately preceding one prepended. +### Breaking: state moves to state.db + +A worker keeps its devices, leases, lease requests and installed components in +`state.db` in its data directory (`~/.simlock`), one row per record, instead of +in `state.json`. A change writes only the rows it touches, so a renew writes +one lease row however many lease requests are stored. Nothing is imported from +`state.json`. The upgrade therefore loses the record of which components +Simlock installed, so `simlock component remove` refuses a component +installed before it (`Simlock has no record of installing …`). + +A daemon whose folder still holds `state.json` does not start. To upgrade: + +1. With the older Simlock, release every lease and run + `simlock nuke --delete-devices`, so no simulator, emulator or lease is left + that the new Simlock would not know about. +2. Remove `state.json`. +3. Start the new Simlock, then add physical devices again with + `simlock device add`. + +A daemon also does not start when `state.db` is damaged, when another Simlock +daemon holds it locked for more than five seconds, or when it was written by a +newer Simlock (the message names the file and what to do). The reason is +logged as `Daemon failed to start` and exits `1`; read it with +`simlock daemon logs`, which works with no daemon up. A damaged `state.db` is +never repaired or deleted for you: move it away to start with empty state, and +know that every device and lease it held is forgotten. + +To go back to an older Simlock, release every lease and run +`simlock nuke --delete-devices` first: the older Simlock does not read +`state.db`. + ## `simlock worker ` The operator's view of a fleet. Every subcommand is an admin diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index a0322b6e2..6073b5d0c 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -26,7 +26,7 @@ worker daemon ── uplink (WebSocket to /v1/uplink, worker dials) ──┘ dispatcher in process, never through the socket. - A gateway is a second set of handlers for the same contract. Every frontend works against either mode unchanged. -- State lives on the worker (`state.json`, written only by core's +- State lives on the worker (`state.db`, its registry tables written only by core's `Registry`). A gateway keeps only its tokens, its instance id and its drained-worker set on disk; everything else is rebuilt from the workers that reconnect. @@ -56,6 +56,7 @@ worker daemon ── uplink (WebSocket to /v1/uplink, worker dials) ──┘ | simlock-client, client, admin | The typed programmatic client (`simlock/client`, `simlock/admin`) | [simlock-client](../../src/simlock-client/AGENTS.md) · [client](../../src/client/AGENTS.md) · [admin](../../src/admin/AGENTS.md) | | lease-policy | Client-side renew timer | [lease-policy](../../src/lease-policy/AGENTS.md) | | bus | Post-commit business events and their in-memory ring | [bus](../../src/bus/AGENTS.md) | +| state | `state.db`: opens it, refuses an old file, damage and a newer version, migrates each owner's tables | [state](../../src/state/AGENTS.md) | | history | The durable event history: `history.db`, prune, set-aside, projections (usage: request, minute and device fact rows) | [history](../../src/history/AGENTS.md) | | ports | Every external API behind an interface, with a fake | [ports](../../src/ports/AGENTS.md) | | host-load | CPU, memory and disk load samples | [host-load](../../src/host-load/AGENTS.md) | diff --git a/docs/internal/flows/startup.md b/docs/internal/flows/startup.md index 06b2d6ec6..493899bf9 100644 --- a/docs/internal/flows/startup.md +++ b/docs/internal/flows/startup.md @@ -9,12 +9,18 @@ Entry: `src/daemon/main.ts` `startDaemon` → `DaemonServer.start` (`src/daemon/ 2. `Logger` → `daemon.log`. At `log.level: debug` the `ProcessRunner` is wrapped. 3. Host info read once (`sw_vers` on macOS); bounded, never throws. 4. `EventBus` → the event history is created (`createEventHistory`). It touches no file yet. + `refuseWhenDaemonAnswers` (`src/daemon/main.ts:241`) first connects to the socket: a daemon + that answers makes this one fail with `DaemonAlreadyRunningError`, before any `state.db` is opened. + `openStateDatabase` then opens the role's `state.db` (both roles) in this order, each failure + being the daemon's start error: an old file of the role's former state refuses, then + `node:sqlite` missing, the open and its pragmas, `quick_check`, and in one `BEGIN IMMEDIATE` + transaction each owner's version (a newer one, or a migration that throws, refuses). `createAuth` then builds the token store and the admin secret (hash in memory), once, for both modes. 5. Started with `--gateway` (role `gateway`, data directory `/gateway`) → the gateway section. Otherwise go on. ## Worker: build (before the claim) -6. `Registry.load` — `state.json`. +6. `Registry.load` — the `registry` and device-data tables of `state.db`. 7. Instance identity — `loadInstanceId`, `instance.json`. Written once per home, never regenerated. 8. Root validation — `discoverDrivers`: each driver checks its owned root against @@ -43,7 +49,7 @@ Entry: `src/daemon/main.ts` `startDaemon` → `DaemonServer.start` (`src/daemon/ Converge (`src/daemon/main.ts` `convergeStartup`), one step after another. Once a stop reaches its settle step, the steps after the read are skipped. Before step 16 it -removes the `....tmp` files and `....staging` directories of dead writers beside `state.json`, beside each device root and in +removes the `....tmp` files and `....staging` directories of dead writers beside each device root and in the data directory (`sweepWriteLeftovers`). 16. Settle open requests — `leasing.settleRequests`: every `open` request fails @@ -122,7 +128,7 @@ platform runs the deferred reclaim (step 21.2). 7. Close connections, remove `admin.token`, release the socket (released even when the removal fails). A gateway's stop: agent-device edge and HTTP, then `FleetLeaseCoordinator` and -`GatewayService` are disposed, then the event history stops. +`GatewayService` are disposed, then the event history stops and `state.db` closes. -A stop releases nothing. Leases stay in `state.json` with their deadlines; the +A stop releases nothing. Leases stay in `state.db` with their deadlines; the next start re-arms or ends them (steps 19–20). diff --git a/e2e/daemon-folders.test.ts b/e2e/daemon-folders.test.ts index 762cf2da4..b01629d8b 100644 --- a/e2e/daemon-folders.test.ts +++ b/e2e/daemon-folders.test.ts @@ -3,6 +3,7 @@ import { existsSync } from "node:fs"; import { readFile, writeFile } from "node:fs/promises"; import { createServer } from "node:net"; import { join } from "node:path"; +import { DatabaseSync } from "node:sqlite"; import { describe, expect, it } from "vitest"; import { freeLoopbackPort, REPO_ROOT, type TestEnv, waitFor, withDaemon } from "./helpers/index.js"; @@ -108,7 +109,15 @@ describe("daemon folders (ADR 0034)", () => { const workerInstance = await readFile(join(env.home, "instance.json"), "utf8"); const gatewayInstance = await readFile(join(gatewayFolder(env), "instance.json"), "utf8"); expect(gatewayInstance).not.toBe(workerInstance); - expect(existsSync(join(gatewayFolder(env), "state.json"))).toBe(false); + const gatewayState = new DatabaseSync(join(gatewayFolder(env), "state.db")); + try { + const devicesTables = gatewayState + .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'devices'") + .all(); + expect(devicesTables).toEqual([]); + } finally { + gatewayState.close(); + } } finally { await stopGateway(env); } @@ -185,6 +194,30 @@ describe("daemon folders (ADR 0034)", () => { ); }); + it("the daemon entry run in a folder that still holds state.json exits 1, logs the upgrade instructions as its last line and creates no state.db", async () => { + const env = await withDaemon({ mode: "auto" }); + await writeFile(join(env.home, "state.json"), "{}\n", "utf8"); + + const code = await new Promise((resolve, reject) => { + const child = spawn(process.execPath, [join(REPO_ROOT, "dist/daemon/main.js")], { + env: env.env, + stdio: "ignore", + }); + child.once("error", reject); + child.once("close", resolve); + }); + + expect(code).toBe(1); + const lines = (await readFile(join(env.home, "daemon.log"), "utf8")).trim().split("\n"); + expect(JSON.parse(lines.at(-1) ?? "{}")).toMatchObject({ + fields: { + message: `Found ${join(env.home, "state.json")}, which this Simlock no longer reads. To upgrade: with the older Simlock, release every lease and run \`simlock nuke --delete-devices\`; then remove ${join(env.home, "state.json")} and start again. See "Breaking: state moves to state.db" in docs/CLI.md.`, + }, + message: "Daemon failed to start", + }); + expect(existsSync(join(env.home, "state.db"))).toBe(false); + }); + it("on a machine with only a present gateway, plain daemon start and plain status reach the gateway and start no worker", async () => { const env = await withDaemon({ mode: "auto" }); diff --git a/e2e/fake-driver/device-data.test.ts b/e2e/fake-driver/device-data.test.ts new file mode 100644 index 000000000..ddcece644 --- /dev/null +++ b/e2e/fake-driver/device-data.test.ts @@ -0,0 +1,30 @@ +import { DatabaseSync } from "node:sqlite"; +import { describe, expect, it } from "vitest"; +import { e2eFakeDeviceDataTable } from "./device-data.js"; + +function openTable(): DatabaseSync { + const database = new DatabaseSync(":memory:"); + for (const statement of e2eFakeDeviceDataTable.migrations) database.exec(statement); + return database; +} + +describe("e2e fake device data table", () => { + it("writes and reads back its one key", () => { + const database = openTable(); + + e2eFakeDeviceDataTable.write(database, "dev_1", { fakeDeviceId: "fk-1" }); + + expect(e2eFakeDeviceDataTable.read(database, "dev_1")).toEqual({ fakeDeviceId: "fk-1" }); + }); + + it("refuses data with a key besides fakeDeviceId, and stores nothing", () => { + const database = openTable(); + + expect(() => + e2eFakeDeviceDataTable.write(database, "dev_1", { extra: 1, fakeDeviceId: "fk-1" }), + ).toThrow("Invalid fake driver data for device dev_1"); + expect(() => e2eFakeDeviceDataTable.read(database, "dev_1")).toThrow( + "No fake driver data for device dev_1", + ); + }); +}); diff --git a/e2e/fake-driver/device-data.ts b/e2e/fake-driver/device-data.ts new file mode 100644 index 000000000..ad4d14cbf --- /dev/null +++ b/e2e/fake-driver/device-data.ts @@ -0,0 +1,30 @@ +import type { DeviceDataTable } from "../../dist/core/index.js"; + +// why: e2e may enter the project only through dist//index.js, so the e2e fake driver keeps its own table beside src/core's fakeDeviceDataTable. +export const e2eFakeDeviceDataTable: DeviceDataTable = { + migrations: [ + "CREATE TABLE e2e_fake_device_data (device_id TEXT PRIMARY KEY, fake_device_id TEXT NOT NULL) STRICT", + ], + name: "e2e-fake-device-data", + read(database, deviceId) { + const row = database + .prepare("SELECT fake_device_id FROM e2e_fake_device_data WHERE device_id = ?") + .get(deviceId); + if (row === undefined) throw new Error(`No fake driver data for device ${deviceId}`); + return { fakeDeviceId: row["fake_device_id"] }; + }, + version: 1, + write(database, deviceId, driverData) { + const data = driverData as Record | null | undefined; + const fakeDeviceId = data?.["fakeDeviceId"]; + if (typeof fakeDeviceId !== "string" || Object.keys(data ?? {}).length !== 1) { + throw new Error(`Invalid fake driver data for device ${deviceId}`); + } + database + .prepare( + `INSERT INTO e2e_fake_device_data (device_id, fake_device_id) VALUES (?, ?) + ON CONFLICT (device_id) DO UPDATE SET fake_device_id = excluded.fake_device_id`, + ) + .run(deviceId, fakeDeviceId); + }, +}; diff --git a/e2e/fake-driver/index.ts b/e2e/fake-driver/index.ts index bf7de4378..d34d4e8e8 100644 --- a/e2e/fake-driver/index.ts +++ b/e2e/fake-driver/index.ts @@ -1,4 +1,5 @@ -import type { Driver, PrerequisiteCheck } from "../../dist/core/index.js"; +import type { DeviceDataTable, Driver, PrerequisiteCheck } from "../../dist/core/index.js"; +import { e2eFakeDeviceDataTable } from "./device-data.js"; import { OutOfProcessFakeDriver, readPlatformScript, type FakeDriverClock } from "./fake-driver.js"; import { DEFAULT_LOG_ENV, DEFAULT_PLATFORMS_ENV, DEFAULT_SCRIPT_ENV } from "./types.js"; @@ -36,3 +37,8 @@ export const prerequisiteChecks: readonly PrerequisiteCheck[] = (["ios", "androi platform, }), ); + +export const deviceDataTables: ReadonlyMap<"ios" | "android", DeviceDataTable> = new Map([ + ["ios", e2eFakeDeviceDataTable], + ["android", e2eFakeDeviceDataTable], +]); diff --git a/e2e/helpers/physical-presence.ts b/e2e/helpers/physical-presence.ts index a7c4e678a..e9281508d 100644 --- a/e2e/helpers/physical-presence.ts +++ b/e2e/helpers/physical-presence.ts @@ -1,6 +1,3 @@ -import { readFile, writeFile } from "node:fs/promises"; -import { join } from "node:path"; - import { expect } from "vitest"; import type { FakeDriverErrorSpec, FakeDriverPlatformScript } from "../fake-driver/types.js"; @@ -14,6 +11,7 @@ import { type PhysicalSeed, type SeededLease, } from "./physical-state.js"; +import { patchPhysicalRows, readPhysicalRecords } from "./state-db.js"; import { waitFor } from "./wait.js"; export const ENROLLED = ["com.example.mail", "com.example.maps"] as const; @@ -167,21 +165,13 @@ export async function patchPhysicalRecords( env: Pick, patch: (record: Record) => Record, ): Promise { - const path = join(env.home, "state.json"); - const state = JSON.parse(await readFile(path, "utf8")) as { - physicalDevices: Record[]; - }; - state.physicalDevices = state.physicalDevices.map(patch); - await writeFile(path, JSON.stringify(state, null, 2), "utf8"); + patchPhysicalRows(env, patch); } export async function physicalRecords( env: Pick, ): Promise[]> { - const state = JSON.parse(await readFile(join(env.home, "state.json"), "utf8")) as { - physicalDevices: Record[]; - }; - return state.physicalDevices; + return readPhysicalRecords(env); } export interface DeviceRow { diff --git a/e2e/helpers/physical-state.ts b/e2e/helpers/physical-state.ts index 2e595d826..ca22554b5 100644 --- a/e2e/helpers/physical-state.ts +++ b/e2e/helpers/physical-state.ts @@ -1,7 +1,5 @@ -import { writeFile } from "node:fs/promises"; -import { join } from "node:path"; - import type { TestEnv } from "./env.js"; +import { openSeedDatabase } from "./state-db.js"; import { waitFor } from "./wait.js"; /** The one iPhone every physical-device flow enrols: an iPhone 15 Pro on iOS 18.4, class phone. */ @@ -59,11 +57,6 @@ export const HELD_LEASE = (deadlineInMs: number): SeededLease => ({ id: "lse_pheld", }); -/** - * Writes `state.json` into the env's home with these physical records in their own list, the - * way an enrolment would leave it. Call it before the daemon starts (`withDaemon({ mode: - * "auto" })`). - */ export async function seedPhysicalState( env: Pick, physical: readonly PhysicalSeed[], @@ -71,52 +64,73 @@ export async function seedPhysicalState( simulators: readonly ShutdownSimulatorSeed[] = [], ): Promise { const now = Date.now(); - const state = { - components: [], - devices: simulators.map((simulator) => ({ - createdAt: now - 2 * DAY_MS, - driverData: {}, - driverDeviceId: simulator.driverDeviceId, - id: simulator.id, - mode: "full", - shutdownAt: now - DAY_MS, - spec: { model: PHYSICAL_MODEL, osVersion: PHYSICAL_OS, platform: "ios" }, - state: "shutdown", - })), - leaseRequests: [], - leases: leases.map((lease) => ({ - deviceId: lease.deviceId, - grantedAt: now - 60_000, - id: lease.id, - idChosenByRequester: false, - lastRenewedAt: now - 60_000, - ownerId: PHYSICAL_AGENT, - requesterId: PHYSICAL_AGENT, - ttlDeadline: now + lease.deadlineInMs, - ttlMs: 600_000, - })), - physicalDevices: physical.map((seed) => ({ - address: seed.driverDeviceId, - createdAt: now - 2 * DAY_MS, - driverData: {}, - driverDeviceId: seed.driverDeviceId, - enrolledApps: seed.enrolledApps ?? [], - id: seed.id, - lastLeaseEndedAt: - seed.lastLeaseEndedAt ?? now - (seed.state === "reclaiming" ? DAY_MS : 3_600_000), - physical: true, - readyAt: now - 2 * DAY_MS, - spec: { - class: "phone", - model: PHYSICAL_MODEL, - osVersion: PHYSICAL_OS, - physical: true, - platform: "ios", - }, - state: seed.state, - })), - }; - await writeFile(join(env.home, "state.json"), `${JSON.stringify(state, null, 2)}\n`, "utf8"); + const state = await openSeedDatabase(env); + try { + state.transaction(() => { + const { database } = state; + for (const simulator of simulators) { + database + .prepare( + `INSERT INTO devices (id, platform, physical, driver_device_id, state, model, os_version, + mode, created_at, shutdown_at) VALUES (?, 'ios', 0, ?, 'shutdown', ?, ?, 'full', ?, ?)`, + ) + .run( + simulator.id, + simulator.driverDeviceId, + PHYSICAL_MODEL, + PHYSICAL_OS, + now - 2 * DAY_MS, + now - DAY_MS, + ); + database + .prepare("INSERT INTO e2e_fake_device_data (device_id, fake_device_id) VALUES (?, ?)") + .run(simulator.id, simulator.driverDeviceId); + } + for (const seed of physical) { + database + .prepare( + `INSERT INTO devices (id, platform, physical, driver_device_id, state, model, os_version, + class, created_at, last_lease_ended_at, ready_at, address) + VALUES (?, 'ios', 1, ?, ?, ?, ?, 'phone', ?, ?, ?, ?)`, + ) + .run( + seed.id, + seed.driverDeviceId, + seed.state, + PHYSICAL_MODEL, + PHYSICAL_OS, + now - 2 * DAY_MS, + seed.lastLeaseEndedAt ?? now - (seed.state === "reclaiming" ? DAY_MS : 3_600_000), + now - 2 * DAY_MS, + seed.driverDeviceId, + ); + (seed.enrolledApps ?? []).forEach((app, position) => { + database + .prepare("INSERT INTO device_enrolled_apps (device_id, position, app) VALUES (?, ?, ?)") + .run(seed.id, position, app); + }); + } + for (const lease of leases) { + database + .prepare( + `INSERT INTO leases (id, device_id, requester_id, owner_id, granted_at, ttl_ms, + ttl_deadline, last_renewed_at, id_chosen_by_requester) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0)`, + ) + .run( + lease.id, + lease.deviceId, + PHYSICAL_AGENT, + PHYSICAL_AGENT, + now - 60_000, + 600_000, + now + lease.deadlineInMs, + now - 60_000, + ); + } + }); + } finally { + state.close(); + } } /** The fake driver's operations on calls whose arguments name any of these driver device IDs. */ diff --git a/e2e/helpers/state-db.ts b/e2e/helpers/state-db.ts new file mode 100644 index 000000000..84ec23d12 --- /dev/null +++ b/e2e/helpers/state-db.ts @@ -0,0 +1,109 @@ +import { join } from "node:path"; +import { DatabaseSync } from "node:sqlite"; + +import { e2eFakeDeviceDataTable } from "../fake-driver/device-data.js"; +import type { TestEnv } from "./env.js"; + +const PHYSICAL_COLUMNS = { + absentReason: "absent_reason", + address: "address", + class: "class", + createdAt: "created_at", + deferredReclaimLeaseId: "deferred_reclaim_lease_id", + driverDeviceId: "driver_device_id", + foreignProvenanceDetectedAt: "foreign_provenance_detected_at", + foreignStateDetectedAt: "foreign_state_detected_at", + lastLeaseEndedAt: "last_lease_ended_at", + model: "model", + osVersion: "os_version", + quarantineAttempts: "quarantine_attempts", + quarantineCauseKind: "quarantine_cause_kind", + quarantineCauseMessage: "quarantine_cause_message", + quarantineCauseStalledState: "quarantine_cause_stalled_state", + quarantineNextRetryAt: "quarantine_next_retry_at", + quarantinedAt: "quarantined_at", + readyAt: "ready_at", + reclaimingSince: "reclaiming_since", + recoveringSince: "recovering_since", + recoveryAttempts: "recovery_attempts", + shutdownAt: "shutdown_at", + state: "state", +} as const; + +export async function openSeedDatabase(env: Pick) { + const { openStateDatabase } = await import("../../dist/state/index.js"); + const { NoopLogger, NodeFilesystem, NodeSqliteOpener } = + await import("../../dist/ports/index.js"); + const { registryOwner } = await import("../../dist/core/index.js"); + return openStateDatabase({ + dataDirectory: env.home, + filesystem: new NodeFilesystem(), + logger: new NoopLogger(), + oldFiles: [], + owners: [registryOwner, e2eFakeDeviceDataTable], + sqlite: new NodeSqliteOpener(), + upgradeStep: "", + }); +} + +function withDatabase(env: Pick, work: (database: DatabaseSync) => T): T { + const database = new DatabaseSync(join(env.home, "state.db")); + try { + database.exec("PRAGMA busy_timeout=5000"); + return work(database); + } finally { + database.close(); + } +} + +export function readPhysicalRecords(env: Pick): Record[] { + return withDatabase(env, (database) => { + const rows = database.prepare("SELECT * FROM devices WHERE physical = 1 ORDER BY id").all(); + return rows.map((row) => { + const record: Record = { id: row["id"], physical: true }; + for (const [key, column] of Object.entries(PHYSICAL_COLUMNS)) { + if (row[column] !== null && row[column] !== undefined) record[key] = row[column]; + } + record["enrolledApps"] = database + .prepare("SELECT app FROM device_enrolled_apps WHERE device_id = ? ORDER BY position") + .all(String(row["id"])) + .map((app) => app["app"]); + return record; + }); + }); +} + +export function patchPhysicalRows( + env: Pick, + patch: (record: Record) => Record, +): void { + const records = readPhysicalRecords(env); + withDatabase(env, (database) => { + database.exec("BEGIN IMMEDIATE"); + for (const record of records) { + const patched = patch(record); + const assignments = Object.entries(PHYSICAL_COLUMNS).map(([, column]) => `${column} = ?`); + const values = Object.keys(PHYSICAL_COLUMNS).map((key) => { + const value = patched[key]; + return value === undefined ? null : (value as string | number); + }); + database + .prepare(`UPDATE devices SET ${assignments.join(", ")} WHERE id = ?`) + .run(...values, String(record["id"])); + database + .prepare("DELETE FROM device_enrolled_apps WHERE device_id = ?") + .run(String(record["id"])); + const apps = (patched["enrolledApps"] as readonly string[] | undefined) ?? []; + apps.forEach((app, position) => { + database + .prepare("INSERT INTO device_enrolled_apps (device_id, position, app) VALUES (?, ?, ?)") + .run(String(record["id"]), position, app); + }); + } + database.exec("COMMIT"); + }); +} + +export function readEnrolledApps(env: Pick): string[][] { + return readPhysicalRecords(env).map((record) => record["enrolledApps"] as string[]); +} diff --git a/e2e/physical-devices-core.test.ts b/e2e/physical-devices-core.test.ts index 81cc628fa..403511e9e 100644 --- a/e2e/physical-devices-core.test.ts +++ b/e2e/physical-devices-core.test.ts @@ -18,8 +18,8 @@ import { } from "./helpers/physical-state.js"; /** - * The core knows a device record may be physical (ADR 0022): a physical record is written into - * `state.json`'s `physicalDevices` by hand, as the tests below do, and every path that acts on + * why: the core knows a device record may be physical (ADR 0022): a physical record is written into + * `state.db`'s `devices` table by hand, as the tests below do, and every path that acts on * simulators and emulators leaves it alone. "No driver call names it" means the fake driver's * call log has no call whose arguments carry the record's `driverDeviceId`. */ diff --git a/e2e/physical-enrollment.test.ts b/e2e/physical-enrollment.test.ts index 957e0e8e1..1b2dc20b3 100644 --- a/e2e/physical-enrollment.test.ts +++ b/e2e/physical-enrollment.test.ts @@ -1,6 +1,3 @@ -import { readFile } from "node:fs/promises"; -import { join } from "node:path"; - import { describe, expect, it } from "vitest"; import { PROTOCOL_VERSION_RANGE } from "../src/contract/index.js"; @@ -8,6 +5,7 @@ import { NodeIpcTransport } from "../src/ports/index.js"; import { SimlockWire, WireCallError } from "../src/simlock-client/wire.js"; import type { FakeDriverRefusalReason, ScriptedPhysicalDevice } from "./fake-driver/types.js"; import { type TestEnv, waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js"; +import { readEnrolledApps } from "./helpers/state-db.js"; const UDID = "00008110-001A2B3C4D5E"; const ALIAS = "7A1C0E52-6B7D-4F1E-9C1A-2D3E4F5A6B7C"; @@ -666,11 +664,6 @@ describe("android enrolment", () => { expect(result.stdout).toBe( "Enrolled Pixel 9 (Android 15) as R58M123ABC, 1 user app recorded.\n", ); - const state = JSON.parse(await readFile(join(env.home, "state.json"), "utf8")) as { - physicalDevices: { driverDeviceId: string; enrolledApps: string[] }[]; - }; - expect(state.physicalDevices.map((record) => record.enrolledApps)).toEqual([ - ["com.example.mail"], - ]); + expect(readEnrolledApps(env)).toEqual([["com.example.mail"]]); }); }); diff --git a/e2e/physical-presence-loss-recovery.test.ts b/e2e/physical-presence-loss-recovery.test.ts index 71799bc3d..d9b79f9f4 100644 --- a/e2e/physical-presence-loss-recovery.test.ts +++ b/e2e/physical-presence-loss-recovery.test.ts @@ -166,7 +166,7 @@ describe("a daemon restart alone never ends a physical lease", () => { expect(readsBefore.length).toBeGreaterThanOrEqual(3); }); - it("a daemon restarted with an absent and a quarantined physical device in state.json keeps both states while they are not present", async () => { + it("a daemon restarted with an absent and a quarantined physical device in state.db keeps both states while they are not present", async () => { const env = await startPresence( [ { @@ -196,7 +196,7 @@ describe("a daemon restart alone never ends a physical lease", () => { } }); - it("a physical device left reclaiming in state.json stays reclaiming while not present, and is reclaimed to ready once present", async () => { + it("a physical device left reclaiming in state.db stays reclaiming while not present, and is reclaimed to ready once present", async () => { const env = await startPresence( [{ script: { installed: INSTALLED, present: false }, seed: RECLAIMING }], { config: SLOW_RETRY }, diff --git a/e2e/physical-reclaim.test.ts b/e2e/physical-reclaim.test.ts index 874a64c19..91a28d703 100644 --- a/e2e/physical-reclaim.test.ts +++ b/e2e/physical-reclaim.test.ts @@ -1,6 +1,3 @@ -import { readFile, writeFile } from "node:fs/promises"; -import { join } from "node:path"; - import { describe, expect, it } from "vitest"; import type { @@ -23,6 +20,7 @@ import { type PhysicalSeed, type SeededLease, } from "./helpers/physical-state.js"; +import { patchPhysicalRecords } from "./helpers/physical-presence.js"; const ENROLLED = ["com.example.mail", "com.example.maps"] as const; const AGENT_APPS = ["com.agent.one", "com.agent.two"] as const; @@ -82,24 +80,12 @@ async function startWith( mode: "auto", }); await seedPhysicalState(env, [seed], options.leases ?? []); - if (options.patchState !== undefined) await patchPhysicalRecord(env, options.patchState); + if (options.patchState !== undefined) await patchPhysicalRecords(env, options.patchState); const started = await env.startDaemon(); expect(started.code, started.stderr).toBe(0); return env; } -async function patchPhysicalRecord( - env: TestEnv, - patch: (device: Record) => Record, -): Promise { - const path = join(env.home, "state.json"); - const state = JSON.parse(await readFile(path, "utf8")) as { - physicalDevices: Record[]; - }; - state.physicalDevices = state.physicalDevices.map(patch); - await writeFile(path, JSON.stringify(state, null, 2), "utf8"); -} - async function setScript( env: TestEnv, physical: PhysicalSeed, @@ -307,7 +293,7 @@ describe("a physical reclaim that fails quarantines the device", () => { }); describe("a physical device that was mid-reclaim or quarantined when the daemon stopped", () => { - it("a physical device left reclaiming in state.json that is not present stays reclaiming after a daemon start; doctor --fix past its estimate quarantines it, and it is retried after retryBackoffMs once present", async () => { + it("a physical device left reclaiming in state.db that is not present stays reclaiming after a daemon start; doctor --fix past its estimate quarantines it, and it is retried after retryBackoffMs once present", async () => { const env = await startWith(RECLAIMING, { config: { warmPool: { quarantine: { retryBackoffMs: 1_500 } } }, script: { installed: [...ENROLLED, ...AGENT_APPS], present: false }, @@ -330,7 +316,7 @@ describe("a physical device that was mid-reclaim or quarantined when the daemon ]); }); - it("a daemon restarted with a quarantined physical device in state.json retries it after its quarantineNextRetryAt", async () => { + it("a daemon restarted with a quarantined physical device in state.db retries it after its quarantineNextRetryAt", async () => { const nextRetryAt = Date.now() + 2_500; const env = await startWith( { ...READY, state: "quarantined" }, diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 663b7ef0c..1749ec4f1 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -5,7 +5,8 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; -import { FakeDriver } from "../core/testing.js"; +import { FakeDriver, fakeDeviceDataTables } from "../core/testing.js"; +import { NodeSqliteOpener } from "../ports/index.js"; import { startDaemon, type StartDaemonOptions } from "../daemon/main.js"; import type { DaemonServer } from "../daemon/server.js"; import { @@ -88,7 +89,7 @@ interface Rig { readonly filesystem: MemoryFilesystem; readonly logs: MemoryLogSink; readonly origin: string; - readonly statePath: string; + readonly stateDbPath: string; readonly started: Promise; readonly restart: (between?: () => void) => Promise; } @@ -164,7 +165,7 @@ async function setUp(options: SetUpOptions = {}): Promise { const port = await freeLoopbackPort(); const fake = options.upstream ?? new FakeAgentDevice(); const drivers = options.drivers?.(clock) ?? [iosDriver(clock)]; - const statePath = join(directory, "state.json"); + const stateDbPath = join(directory, "state.db"); const logs = new MemoryLogSink(); const launch = () => startDaemon({ @@ -192,11 +193,11 @@ async function setUp(options: SetUpOptions = {}): Promise { }, ...(options.gatewayMode === true ? { role: "gateway" as const } : {}), dataDirectory: directory, + deviceDataTables: fakeDeviceDataTables, drivers, filesystem, logger: new JsonLinesLogger({ clock, level: "debug", sink: logs }), optionalModules: [agentDeviceModuleWith({ upstream: fake })], - statePath, version: "1.2.3", } as StartDaemonOptions).then((daemon) => { runningDaemons.push(daemon); @@ -216,7 +217,7 @@ async function setUp(options: SetUpOptions = {}): Promise { origin, restart: () => Promise.reject(new Error("restart needs a started daemon")), started, - statePath, + stateDbPath, }; } const rigFor = (daemon: DaemonServer, running: Promise): Rig => ({ @@ -234,7 +235,7 @@ async function setUp(options: SetUpOptions = {}): Promise { return rigFor(next, Promise.resolve(next)); }, started: running, - statePath, + stateDbPath, }); return rigFor(await started, started); } @@ -1032,7 +1033,7 @@ describe("the agent-device front, through the whole worker daemon", () => { expect(await waiting(rig)).toEqual([]); }); - it("stopping the daemon while an allocate waits ends with no simlock lease, and the lease request it waited on is cancelled, not open, in state.json", async () => { + it("stopping the daemon while an allocate waits ends with no simlock lease, and the lease request it waited on is cancelled, not open, in state.db", async () => { const rig = await setUp({ maxRunning: 1 }); await granted(rig, 1, {}, { token: secrets.two }); const second = track(allocate(rig, 2)); @@ -1041,16 +1042,19 @@ describe("the agent-device front, through the whole worker daemon", () => { await rig.daemon.stop("test"); await second.promise.catch(() => undefined); - const state = await rig.filesystem.readFile(rig.statePath); - expect(second.done()).toBe(true); - expect(state).toContain(hex(1)); - const records = JSON.parse(state ?? "{}") as { - leaseRequests?: readonly { leaseId?: string; state: string }[]; - }; - expect(records.leaseRequests?.filter((record) => record.leaseId === hex(2))).toEqual([ - expect.objectContaining({ state: "cancelled" }), - ]); - expect(records.leaseRequests?.some((record) => record.state === "open")).toBe(false); + const database = await new NodeSqliteOpener().open(rig.stateDbPath, { readOnly: true }); + try { + const leaseIds = database.prepare("SELECT id FROM leases").all(); + const requests = database.prepare("SELECT lease_id, state FROM lease_requests").all(); + expect(second.done()).toBe(true); + expect(leaseIds).toEqual([{ id: hex(1) }]); + expect(requests.filter((row) => row.lease_id === hex(2))).toEqual([ + expect.objectContaining({ state: "cancelled" }), + ]); + expect(requests.some((row) => row.state === "open")).toBe(false); + } finally { + database.close(); + } }); it("an allocate still waiting 330 s after the front admitted it answers `timed out waiting for a device; nothing was leased`, and simlock's queue is empty", async () => { diff --git a/src/agent-device/gateway-front.test.ts b/src/agent-device/gateway-front.test.ts index d838edd4f..dec790330 100644 --- a/src/agent-device/gateway-front.test.ts +++ b/src/agent-device/gateway-front.test.ts @@ -5,7 +5,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { FakeDriver } from "../core/testing.js"; +import { FakeDriver, fakeDeviceDataTables } from "../core/testing.js"; import { startDaemon, type StartDaemonOptions } from "../daemon/main.js"; import { DispatchError } from "../daemon/dispatch.js"; import { readHistoryEvents } from "../history/testing.js"; @@ -242,7 +242,6 @@ async function setUp(options: SetUpOptions = {}): Promise { }, logger: new JsonLinesLogger({ clock, level: "debug", sink: logs }), optionalModules: [agentDeviceModuleWith({})], - statePath: join(directory, "state.json"), version: "1.2.3", } as StartDaemonOptions); runningDaemons.push(started); @@ -285,6 +284,7 @@ async function setUp(options: SetUpOptions = {}): Promise { lease: { defaultTtlMs, maxTtlMs: workerMaxTtlMs }, }, dataDirectory: workerDirectory, + deviceDataTables: fakeDeviceDataTables, drivers: [driver], filesystem: workerFilesystem, logger: new JsonLinesLogger({ @@ -293,7 +293,6 @@ async function setUp(options: SetUpOptions = {}): Promise { sink: new MemoryLogSink(), }), optionalModules: [agentDeviceModuleWith({ upstream: fake })], - statePath: join(workerDirectory, "state.json"), version: "1.2.3", } as StartDaemonOptions).then((daemon) => { runningDaemons.push(daemon); diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index b237ce6e0..653b2f75e 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -10,8 +10,8 @@ import { testComponentWiring } from "../core/testing.js"; import { EventBus } from "../bus/index.js"; import { ringEventHistory, seedHistory } from "../history/testing.js"; -import { CleanupReaper, type Config, Registry } from "../core/index.js"; -import { FakeDriver } from "../core/testing.js"; +import { CleanupReaper, type Config } from "../core/index.js"; +import { FakeDriver, loadTestRegistry } from "../core/testing.js"; import { CryptoTokenSecrets, FakeClock, @@ -7134,12 +7134,10 @@ async function startTestDaemon(): Promise<{ socketPath: string; daemon: DaemonSe const clock = new FakeClock(1_000); const eventBus = new EventBus(clock); const filesystem = new MemoryFilesystem(); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem, idGenerator: sequence(), - statePath: "/state.json", }); const driver = new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }); const config = testConfig(); @@ -7247,12 +7245,10 @@ async function startInMemoryDaemon(options: { const { adminTokenPath, filesystem, ipcTransport, socketPath } = options; const clock = new FakeClock(1_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem, idGenerator: sequence(), - statePath: "/state.json", }); const driver = new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }); const config = testConfig(); diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index d1b5bbcc6..148a03e1b 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -123,7 +123,7 @@ const deviceSpecSchema = z.object({ const QUARANTINE_MESSAGE_MAX = 300; -export const quarantineCauseSchema = z +const quarantineCauseSchema = z .object({ kind: z.enum(["purge-failed", "shutdown-failed", "delete-failed", "stalled"]), stalledState: z.enum(["provisioning", "reclaiming"]).optional(), @@ -263,10 +263,9 @@ export const grantedDeviceSchema = z driverDeviceId: z.string(), spec: deviceSpecSchema, /** - * The driver-reported address (see `DriverDevice.address`), current as of this device's + * why: The driver-reported address (see `DriverDevice.address`), current as of this device's * last `ready` transition. Undefined for a device still `provisioning` (never made ready - * yet) and, as an upgrade path, for a record written by a pre-address daemon -- `state.json` - * from before this field existed loads without one rather than failing to start. It becomes + * yet) and for a device that was shut down, which has no address to reach. It becomes * defined the next time the device is made ready (`bootForLease`/`readyProvisionedForLease`); * nothing here ever guesses at a value it wasn't told. */ diff --git a/src/core/AGENTS.md b/src/core/AGENTS.md index 4e7b8aafa..6c16ae5d7 100644 --- a/src/core/AGENTS.md +++ b/src/core/AGENTS.md @@ -9,35 +9,35 @@ See also: [leasing](../leasing/AGENTS.md) (lease flow, when reclaim runs), [warm ## Files -| File | Role | -| ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Wiring and state** | | -| `create-core.ts`, `core-ports.ts` | `createCore`, `Core`, `CorePorts`; read ports (`CapacityReader`, `WarmPoolReader`, …) | -| `registry.ts` | `Registry`: the one writer of `state.json` | -| `domain.ts` | Records, specs, `transition`, `fits`, `mayBeGranted`, `sameSpec` | -| `serialized-decision.ts`, `device-operation-claims.ts` | The lock; one in-memory claim per device | -| `config.ts`, `validation.ts` | `loadConfig({ role })` (the role comes from the daemon, never a config key; a `mode` key is refused; with the optional modules' `ModuleConfigEntry` list: `capabilities.` sections, `enabled` owned here), defaults, validators, `redactConfig`, `effectiveAllowDownload` | -| `lease-request-store.ts` | Pure lease-request record helpers, shared with leasing | -| **Device verbs** | | -| `managed-device-lifecycle.ts` | `ManagedDeviceLifecycle`: every driver verb on a registered device | -| `device-provisioner.ts` | `DeviceProvisioner`: the one place a device record is created | -| `reclaim-coordinator.ts` | `ReclaimCoordinator`: wipe after a lease, spent delete, interrupted reclaim | -| `quarantine-coordinator.ts` | `QuarantineCoordinator`: entry, retry on backoff, give up | -| `nuke-service.ts`, `nuke.ts` | `NukeService` (operator reset); `Nuke` (command facade) | -| `idle-order.ts` | LRU order and eviction victim choice | -| **Background** | | -| `warm-pool/`, `capacity/` | What stays warm; limits, RAM budget, reservations (own manuals) | -| `reaper.ts`, `cleanup/`, `cleanup-executor.ts` | `CleanupReaper`, pure rules, `CleanupExecutor` | -| **Startup, health, drivers** | | -| `startup-read.ts`, `startup-converger.ts` | `readStartup`; `StartupConverger`, the device half of startup | -| `write-leftovers.ts` | `sweepWriteLeftovers`: removes dead writers' `.tmp` files and the `.staging` dirs of the device roots it is given; logs pid-less legacy ones, never deletes them | -| `doctor.ts`, `host-facts.ts` | `Doctor` findings and fixes; `HostFactsReader` for status | -| `driver.ts`, `driver-catalog.ts`, `screen.ts` | `Driver`, errors, `DiskSpaceGuard`; `DriverCatalog`; `ScreenCapture`, frame tags | -| `catalog-match.ts` | Model name, class and paired runtimes against a catalog entry | -| `component-installer.ts` | `ComponentInstaller`: install, list, remove | -| `physical-enrollment.ts`, `physical-presence.ts` | `device add`/`remove`; every presence read, `latestPresence` | -| `device-root.ts`, `instance-identity.ts` | `ensureOwnedRoot`; `loadInstanceId` | -| `stable-error.ts`, `testing.ts`, `fake-driver.ts` | `stableError`; test-only wiring and `FakeDriver` | +| File | Role | +| ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Wiring and state** | | +| `create-core.ts`, `core-ports.ts` | `createCore`, `Core`, `CorePorts`; read ports (`CapacityReader`, `WarmPoolReader`, …) | +| `registry.ts`, `registry-rows.ts`, `registry-schema.ts` | `Registry`: the one writer of the registry tables of `state.db`; the rows, the `registry` schema owner | +| `domain.ts` | Records, specs, `transition`, `fits`, `mayBeGranted`, `sameSpec` | +| `serialized-decision.ts`, `device-operation-claims.ts` | The lock; one in-memory claim per device | +| `config.ts`, `validation.ts` | `loadConfig({ role })` (the role comes from the daemon, never a config key; a `mode` key is refused; with the optional modules' `ModuleConfigEntry` list: `capabilities.` sections, `enabled` owned here), defaults, validators, `redactConfig`, `effectiveAllowDownload` | +| `lease-request-store.ts` | Pure lease-request record helpers, shared with leasing | +| **Device verbs** | | +| `managed-device-lifecycle.ts` | `ManagedDeviceLifecycle`: every driver verb on a registered device | +| `device-provisioner.ts` | `DeviceProvisioner`: the one place a device record is created | +| `reclaim-coordinator.ts` | `ReclaimCoordinator`: wipe after a lease, spent delete, interrupted reclaim | +| `quarantine-coordinator.ts` | `QuarantineCoordinator`: entry, retry on backoff, give up | +| `nuke-service.ts`, `nuke.ts` | `NukeService` (operator reset); `Nuke` (command facade) | +| `idle-order.ts` | LRU order and eviction victim choice | +| **Background** | | +| `warm-pool/`, `capacity/` | What stays warm; limits, RAM budget, reservations (own manuals) | +| `reaper.ts`, `cleanup/`, `cleanup-executor.ts` | `CleanupReaper`, pure rules, `CleanupExecutor` | +| **Startup, health, drivers** | | +| `startup-read.ts`, `startup-converger.ts` | `readStartup`; `StartupConverger`, the device half of startup | +| `write-leftovers.ts` | `sweepWriteLeftovers`: removes dead writers' `.tmp` files and the `.staging` dirs of the device roots it is given; logs pid-less legacy ones, never deletes them | +| `doctor.ts`, `host-facts.ts` | `Doctor` findings and fixes; `HostFactsReader` for status | +| `driver.ts`, `driver-catalog.ts`, `screen.ts` | `Driver`, errors, `DiskSpaceGuard`; `DriverCatalog`; `ScreenCapture`, frame tags | +| `catalog-match.ts` | Model name, class and paired runtimes against a catalog entry | +| `component-installer.ts` | `ComponentInstaller`: install, list, remove | +| `physical-enrollment.ts`, `physical-presence.ts` | `device add`/`remove`; every presence read, `latestPresence` | +| `device-root.ts`, `instance-identity.ts` | `ensureOwnedRoot`; `loadInstanceId` | +| `stable-error.ts`, `testing.ts`, `fake-driver.ts` | `stableError`; test-only wiring and `FakeDriver` | ## Wiring @@ -51,7 +51,7 @@ See also: [leasing](../leasing/AGENTS.md) (lease flow, when reclaim runs), [warm 4. Claims: one per device, memory only. Kinds: `boot`, `eviction`, `cleanup`, `nuke`, `recovery`, `reclaim`, `enrollment`, `grant`; optional `owner`. 5. Every verb: claim + revalidate (lock) → driver (no lock) → revalidate + commit (lock) → release. -6. Commit: whole `state.json` via `writeFileAtomic` → memory → `onCommit` → event. A transition +6. Commit: one `state.db` transaction that writes the rows whose record changed (and a device's device-data row) → memory → `onCommit` → event; a throw rolls back and leaves memory as it was. A transition without the one event its edge calls for throws `RegistryEventError`. ## Device state machine @@ -127,11 +127,11 @@ Events: → `absent` `device.absence-detected`; `absent` → `reclaiming` `devic | Removal, startup read per platform | 5 min, 60 s | `COMPONENT_REMOVAL_TIMEOUT_MS`, `STARTUP_READ_LIMIT_MS` | | Host facts max age, tool read | 60 s, 30 s | none | -`state.json`: `devices`, `physicalDevices`, `leases`, `leaseRequests`, `components`; unknown keys kept. +`state.db`, owner `registry`: `devices` (a physical device is `physical = 1`, its apps in `device_enrolled_apps`), `leases`, `lease_requests`, `lease_grants` with `lease_grant_environment`, `components` with `component_receipt`. A driver keeps its own `DeviceDataTable` (`driver.ts`) for a virtual device's `driverData`; a physical device has none. A granted request's `grant.device` is read as the device is now. ## Rules -- Only `Registry` writes `state.json`, inside `SerializedDecision.run`, mode `0600`. Events after the commit. +- Only `Registry` writes the `registry` tables, inside `SerializedDecision.run`. Events after the commit. - Destroy only what the registry holds. One exception: `doctor --purge-orphans`, opt-in. - Nothing in core acts on a leased device, except `recoverLeased`, under the lease. - Grant paths select by exact state; `mayBeGranted` keeps a spent `fresh` device out. diff --git a/src/core/cleanup-executor.test.ts b/src/core/cleanup-executor.test.ts index a03dbe5d8..29ee100d0 100644 --- a/src/core/cleanup-executor.test.ts +++ b/src/core/cleanup-executor.test.ts @@ -1,29 +1,25 @@ import { describe, expect, it, vi } from "vitest"; import { EventBus } from "../bus/index.js"; -import { FakeClock, MemoryFilesystem } from "../ports/index.js"; +import { FakeClock } from "../ports/index.js"; import { CleanupExecutor } from "./cleanup-executor.js"; import { DeviceOperationClaims } from "./device-operation-claims.js"; import { DriverCatalog } from "./driver-catalog.js"; import { FakeDriver } from "./fake-driver.js"; import { ManagedDeviceLifecycle } from "./managed-device-lifecycle.js"; -import { Registry } from "./registry.js"; +import { loadTestRegistry } from "./testing.js"; import { SerializedDecision } from "./serialized-decision.js"; -const statePath = "/home/agent/.simlock/state.json"; const spec = { physical: false, model: "iPhone 16", osVersion: "26.5", platform: "ios" } as const; async function createHarness() { const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); const eventBus = new EventBus(clock); const driver = new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem, idGenerator: { generate: () => "1" }, - statePath, }); const claims = new DeviceOperationClaims(); const decisions = new SerializedDecision(); diff --git a/src/core/component-installer.test.ts b/src/core/component-installer.test.ts index 691d0822a..65f5e9ee5 100644 --- a/src/core/component-installer.test.ts +++ b/src/core/component-installer.test.ts @@ -28,11 +28,11 @@ import { import { DriverCatalog } from "./driver-catalog.js"; import { FakeDriver } from "./fake-driver.js"; import type { DeviceRecord } from "./domain.js"; -import { Registry } from "./registry.js"; +import type { Registry } from "./registry.js"; +import { loadTestRegistry, openTestState } from "./testing.js"; import { SerializedDecision } from "./serialized-decision.js"; const gibibyte = 1024 ** 3; -const statePath = "/home/agent/.simlock/state.json"; const timeoutMs = 60_000; /** A clock whose timers fire only when a test fires them, one at a time, by creation order. */ @@ -78,14 +78,13 @@ async function createHarness( const drivers = options.drivers?.(clock) ?? [ new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }), ]; - const stateFilesystem = new MemoryFilesystem(); + const state = await openTestState(); let nextId = 0; - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: bus, - filesystem: stateFilesystem, idGenerator: { generate: () => `id${String((nextId += 1))}` }, - statePath, + state, }); // Every reservation the installer takes, and whether it gave it back. const guard = new DiskSpaceGuard(); @@ -121,7 +120,7 @@ async function createHarness( ios, registry, reservations, - stateFilesystem, + state, }; } @@ -639,12 +638,11 @@ describe("ComponentInstaller", () => { harness.clock.advance(2_000); await harness.installer.install(ios("27.0")); - const reloaded = await Registry.load({ + const reloaded = await loadTestRegistry({ clock: harness.clock, eventBus: harness.bus, - filesystem: harness.stateFilesystem, idGenerator: { generate: () => "id" }, - statePath, + state: harness.state, }); const expected = [ @@ -1149,9 +1147,10 @@ async function addDevice( platform: "ios" | "android", osVersion: string, ): Promise { + const driverDeviceId = `${platform}-${osVersion}-${String(registry.snapshot.devices.length)}`; const device = await registry.registerDevice({ - driverData: {}, - driverDeviceId: `${platform}-${osVersion}-${String(registry.snapshot.devices.length)}`, + driverData: { fakeDeviceId: driverDeviceId }, + driverDeviceId, provisionDuration: 0, spec: { physical: false, model: "Phone", osVersion, platform }, }); diff --git a/src/core/create-core.test.ts b/src/core/create-core.test.ts index 1c3dc4920..c4f818d09 100644 --- a/src/core/create-core.test.ts +++ b/src/core/create-core.test.ts @@ -18,11 +18,10 @@ import { DriverCrashError, loadConfig, type PrerequisiteCheck, - Registry, } from "./index.js"; import { type FakePhysicalDevice } from "./fake-driver.js"; import { ReclaimCoordinator } from "./reclaim-coordinator.js"; -import { FakeDriver, testComponentWiring } from "./testing.js"; +import { FakeDriver, loadTestRegistry, testComponentWiring } from "./testing.js"; import { WarmPool } from "./warm-pool/index.js"; async function build( @@ -55,15 +54,13 @@ async function build( const filesystem = new MemoryFilesystem(); const systemStats = new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * 1024 ** 3 }); let next = 1; - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem, idGenerator: { generate: () => `${next++}` }, ...(options.fresh === true ? { leaseIdentity: { android: "fresh", ios: "fresh" } as const } : {}), - statePath: "/state.json", }); const core = createCore({ clock, @@ -615,7 +612,7 @@ describe("createCore", () => { rig.core.connect(ports()); const ghost = await rig.registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "ghost-android" }, driverDeviceId: "ghost-android", provisionDuration: 0, spec: { model: "Pixel 8", osVersion: "35", physical: false, platform: "android" }, diff --git a/src/core/device-data-table.test.ts b/src/core/device-data-table.test.ts new file mode 100644 index 000000000..aa4484f88 --- /dev/null +++ b/src/core/device-data-table.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from "vitest"; + +import { describeDeviceDataTable, fakeDeviceDataTable, openTestState } from "./testing.js"; + +describeDeviceDataTable("fakeDeviceDataTable", fakeDeviceDataTable, [ + { fakeDeviceId: "fake-ios-1" }, + { fakeDeviceId: "fake-android-2" }, +]); + +describe("fakeDeviceDataTable", () => { + it("refuses driver data that is not { fakeDeviceId: string }, naming the device", async () => { + const state = await openTestState(); + for (const invalid of [ + {}, + { fakeDeviceId: 3 }, + { fakeDeviceId: "a", extra: 1 }, + null, + undefined, + "fk", + ]) { + expect(() => fakeDeviceDataTable.write(state.database, "dev_bad", invalid)).toThrow( + "Invalid fake driver data for device dev_bad", + ); + } + expect(state.database.prepare("SELECT COUNT(*) AS n FROM fake_device_data").get()).toEqual({ + n: 0, + }); + state.close(); + }); +}); diff --git a/src/core/device-provisioner.test.ts b/src/core/device-provisioner.test.ts index c158bd17d..0ef89b87a 100644 --- a/src/core/device-provisioner.test.ts +++ b/src/core/device-provisioner.test.ts @@ -20,10 +20,9 @@ import { DriverCatalog } from "./driver-catalog.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"; +import { loadTestRegistry } from "./testing.js"; import { SerializedDecision } from "./serialized-decision.js"; -const statePath = "/home/agent/.simlock/state.json"; const spec = { physical: false, model: "iPhone 16", osVersion: "26.5", platform: "ios" } as const; function reservation(): CapacityReservation & { readonly releaseCount: () => number } { @@ -47,12 +46,10 @@ async function createHarness( ...(latencyMs === undefined ? {} : { latencyMs }), }); let nextId = 0; - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => `${nextId++}` }, - statePath, }); const decisions = new SerializedDecision(); const claims = new DeviceOperationClaims(); diff --git a/src/core/doctor.test.ts b/src/core/doctor.test.ts index 337f204a4..9626432b3 100644 --- a/src/core/doctor.test.ts +++ b/src/core/doctor.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from "vitest"; import { EventBus } from "../bus/index.js"; -import { FakeClock, JsonLinesLogger, MemoryFilesystem, MemoryLogSink } from "../ports/index.js"; +import { FakeClock, JsonLinesLogger, MemoryLogSink } from "../ports/index.js"; import { FakeSystemStats } from "../ports/index.js"; import type { Config } from "./config.js"; import { DeviceOperationClaims } from "./device-operation-claims.js"; @@ -16,22 +16,20 @@ import { DriverCatalog } from "./driver-catalog.js"; import type { DriverRejection, PrerequisiteCheck } from "./driver.js"; import { FakeDriver } from "./fake-driver.js"; import { QuarantineCoordinator } from "./quarantine-coordinator.js"; -import { Registry } from "./registry.js"; +import type { Registry } from "./registry.js"; import { SerializedDecision } from "./serialized-decision.js"; import { StartupRead } from "./startup-read.js"; -import { HeldWritesFilesystem, testComponentWiring } from "./testing.js"; +import { loadTestRegistry, openTestState, testComponentWiring } from "./testing.js"; import { createTestEngine } from "../leasing/testing.js"; describe("Doctor", () => { it("reports all reconciliation drift classes without changing state", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const registered = await registry.registerDevice({ driverData: { fakeDeviceId: "missing" }, @@ -91,31 +89,22 @@ describe("Doctor", () => { it("reports but does not correct a leased-state device with no lease record", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const filesystem = new MemoryFilesystem(); - await filesystem.writeFileAtomic( - "/state.json", - JSON.stringify({ - devices: [ - { - physical: false, - createdAt: 1, - driverData: { fakeDeviceId: "simlock-stale" }, - driverDeviceId: "simlock-stale", - id: "dev_1", - spec: { physical: false, model: "Phone", osVersion: "1", platform: "ios" }, - state: "leased", - }, - ], - leases: [], - }), - ); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem, idGenerator: sequence(), - statePath: "/state.json", }); + const stale = await registry.registerDevice({ + driverData: { fakeDeviceId: "simlock-stale" }, + driverDeviceId: "simlock-stale", + provisionDuration: 0, + spec: { physical: false, model: "Phone", osVersion: "1", platform: "ios" }, + }); + await registry.transitionDevice(stale.id, "ready", { + event: "device.ready", + payload: { bootDuration: 0, deviceId: stale.id }, + }); + await registry.transitionDevice(stale.id, "leased"); const driver = new FakeDriver({ clock, platform: "ios" }); driver.setManagedReality({ devices: [ @@ -149,12 +138,10 @@ describe("Doctor", () => { it("keeps the first-detected timestamp when drift persists across ticks", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const device = await registry.registerDevice({ driverData: { fakeDeviceId: "simlock-drift" }, @@ -221,15 +208,13 @@ describe("Doctor", () => { for (const { detail, mark } of cases) { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "simlock-marked" }, driverDeviceId: "simlock-marked", provisionDuration: 0, spec: { physical: false, model: "Phone", osVersion: "1", platform: "ios" }, @@ -288,15 +273,13 @@ describe("Doctor", () => { it("flags both a foreign state change and a foreign provenance change on a device that shows both", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "simlock-both" }, driverDeviceId: "simlock-both", provisionDuration: 0, spec: { physical: false, model: "Phone", osVersion: "1", platform: "ios" }, @@ -341,15 +324,13 @@ describe("Doctor", () => { it("ignores provenance marks while Simlock is itself erasing the device", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "simlock-reclaiming" }, driverDeviceId: "simlock-reclaiming", provisionDuration: 0, spec: { physical: false, model: "Phone", osVersion: "1", platform: "ios" }, @@ -397,12 +378,10 @@ describe("Doctor", () => { it("fixes registry-attributable drift and leaves unregistered reality report-only", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const missing = await registry.registerDevice({ driverData: { fakeDeviceId: "missing" }, @@ -468,12 +447,10 @@ describe("Doctor", () => { it("--fix marks a missing device deleted although another device holds a lease", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const spec = { physical: false, model: "Phone", osVersion: "1", platform: "ios" } as const; const ids: string[] = []; @@ -522,95 +499,13 @@ describe("Doctor", () => { expect(registry.snapshot.devices.map((device) => device.state)).toEqual(["leased", "deleted"]); }); - it.each([ - { - name: "--fix marking a missing device deleted", - observedDrifted: undefined, - before: undefined, - fix: true, - expected: { state: "deleted" }, - }, - { - name: "--fix shutting down a device observed stopped", - observedDrifted: observed("drifted", "stopped"), - before: { fix: false }, - fix: true, - expected: { state: "shutdown" }, - }, - { - name: "a run flagging a device observed stopped", - observedDrifted: observed("drifted", "stopped"), - before: undefined, - fix: false, - expected: { foreignStateDetectedAt: 10_000, state: "ready" }, - }, - { - name: "a run flagging a device whose erasable mark is gone", - observedDrifted: { - ...observed("drifted", "running"), - mark: { durable: "tok", erasable: undefined, erasableReadable: true }, - }, - before: undefined, - fix: false, - expected: { foreignProvenanceDetectedAt: 10_000, state: "ready" }, - }, - ])( - "$name keeps its write, and another device's transition committed in the decision section while that write is in flight keeps its own", - async ({ before, expected, fix, observedDrifted }) => { - const clock = new FakeClock(10_000); - const eventBus = new EventBus(clock); - const filesystem = new HeldWritesFilesystem(); - const registry = await Registry.load({ - clock, - eventBus, - filesystem, - idGenerator: sequence(), - statePath: "/state.json", - }); - const drifted = await readyDevice(registry, "drifted", "ios"); - const warm = await shutdownDevice(registry, "warm", "ios"); - const driver = new FakeDriver({ clock, platform: "ios" }); - driver.setManagedReality({ - devices: [observed("warm", "stopped"), ...(observedDrifted ? [observedDrifted] : [])], - processes: [], - }); - const decisions = new SerializedDecision(); - const doctor = new Doctor({ - clock, - config: config(), - decisions, - drivers: [driver], - eventBus, - registry, - }); - if (before !== undefined) await doctor.reconcile(before); - - filesystem.holding = true; - const reconciling = doctor.reconcile({ fix }); - await filesystem.held(1); - const booting = decisions.run(() => - registry.transitionDevice(warm.id, "ready", { - event: "device.ready", - payload: { bootDuration: 0, deviceId: warm.id }, - }), - ); - await filesystem.releaseUntil(Promise.all([reconciling, booting])); - - const record = (id: string) => registry.snapshot.devices.find((d) => d.id === id); - expect(record(drifted.id)).toMatchObject(expected); - expect(record(warm.id)?.state).toBe("ready"); - }, - ); - it("expires an overdue live lease through leasing when fixing", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const device = await registry.registerDevice({ driverData: { fakeDeviceId: "live" }, @@ -674,12 +569,10 @@ describe("Doctor", () => { it("reports foreign-state-change for a device booted outside Simlock, on both platforms", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const iosDevice = await shutdownDevice(registry, "simlock-ios-1", "ios"); const androidDevice = await shutdownDevice(registry, "simlock_android-1", "android"); @@ -739,12 +632,10 @@ describe("Doctor", () => { it("does not report foreign-state-change for a device this daemon holds an operation claim on", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); // A lease-path boot from `shutdown` runs `makeReady` while the committed record still // says `shutdown` -- observed reality goes `running` before that boot's own transition @@ -786,12 +677,10 @@ describe("Doctor", () => { it("reports foreign-state-change for a device shut down outside Simlock, on both platforms", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const iosDevice = await readyDevice(registry, "simlock-ios-2", "ios"); const androidDevice = await readyDevice(registry, "simlock_android-2", "android"); @@ -851,12 +740,10 @@ describe("Doctor", () => { it("never reports drift when the observed state is transitioning", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); await readyDevice(registry, "simlock-transition", "ios"); @@ -890,15 +777,13 @@ describe("Doctor", () => { it("never reports drift for provisioning or reclaiming registry devices", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "simlock-provisioning" }, driverDeviceId: "simlock-provisioning", provisionDuration: 0, spec: { physical: false, model: "Phone", osVersion: "1", platform: "ios" }, @@ -956,7 +841,7 @@ describe("Doctor", () => { platform: "ios", }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "simlock-stuck" }, driverDeviceId: "simlock-stuck", provisionDuration: 0, spec: { physical: false, model: "Phone", osVersion: "1", platform: "ios" }, @@ -1030,7 +915,7 @@ describe("Doctor", () => { platform: "ios", }); const provisioning = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "simlock-stuck" }, driverDeviceId: "simlock-stuck", provisionDuration: 0, spec: { physical: false, model: "Phone", osVersion: "1", platform: "ios" }, @@ -1089,12 +974,10 @@ describe("Doctor", () => { it("reports a stalled-transition finding for a provisioning device past its driver-derived threshold", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const driver = new FakeDriver({ clock, @@ -1102,7 +985,7 @@ describe("Doctor", () => { platform: "ios", }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "simlock-stuck" }, driverDeviceId: "simlock-stuck", provisionDuration: 0, spec: { physical: false, model: "Phone", osVersion: "1", platform: "ios" }, @@ -1135,12 +1018,10 @@ describe("Doctor", () => { // healthy reclaim is reported as a stall and `--fix` quarantines it. const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const driver = new FakeDriver({ clock, @@ -1148,7 +1029,7 @@ describe("Doctor", () => { platform: "ios", }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "simlock-claimed" }, driverDeviceId: "simlock-claimed", provisionDuration: 0, spec: { physical: false, model: "Phone", osVersion: "1", platform: "ios" }, @@ -1192,12 +1073,10 @@ describe("Doctor", () => { it("does not report a stalled-transition finding for a device still legitimately in-flight", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const driver = new FakeDriver({ clock, @@ -1205,7 +1084,7 @@ describe("Doctor", () => { platform: "ios", }); await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "simlock-slow" }, driverDeviceId: "simlock-slow", provisionDuration: 0, spec: { physical: false, model: "Phone", osVersion: "1", platform: "ios" }, @@ -1229,12 +1108,10 @@ describe("Doctor", () => { it("reports a stalled-transition finding for a reclaiming device whose emulator was killed out from under the daemon", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const driver = new FakeDriver({ clock, estimateMs: { reclaim: 2_000 }, platform: "ios" }); const device = await readyDevice(registry, "simlock-killed", "ios"); @@ -1271,12 +1148,10 @@ describe("Doctor", () => { it("holds a reclaiming device to the slower clean level's estimate", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); // A record in `reclaiming` does not say which clean level started it, so the threshold // has to clear the slower of the two: pricing it at `standard` would call a healthy @@ -1324,12 +1199,10 @@ describe("Doctor", () => { it("emits device.stalled-transition-detected from the doctor, once, for a stalled device and not for other findings", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const driver = new FakeDriver({ clock, @@ -1337,7 +1210,7 @@ describe("Doctor", () => { platform: "ios", }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "simlock-stuck" }, driverDeviceId: "simlock-stuck", provisionDuration: 0, spec: { physical: false, model: "Phone", osVersion: "1", platform: "ios" }, @@ -1369,12 +1242,10 @@ describe("Doctor", () => { it("--fix quarantines a stalled provisioning device through QuarantineCoordinator", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const driver = new FakeDriver({ clock, @@ -1382,7 +1253,7 @@ describe("Doctor", () => { platform: "ios", }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "simlock-stuck" }, driverDeviceId: "simlock-stuck", provisionDuration: 0, spec: { physical: false, model: "Phone", osVersion: "1", platform: "ios" }, @@ -1437,41 +1308,39 @@ describe("Doctor", () => { it("--fix never quarantines a device that (inconsistently) still carries a lease", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const filesystem = new MemoryFilesystem(); - await filesystem.writeFileAtomic( - "/state.json", - JSON.stringify({ - devices: [ - { - physical: false, - createdAt: 1, - driverData: {}, - driverDeviceId: "simlock-stuck", - id: "dev_1", - lastLeaseEndedAt: 1, - spec: { physical: false, model: "Phone", osVersion: "1", platform: "ios" }, - state: "reclaiming", - }, - ], - leases: [ - { - deviceId: "dev_1", - grantedAt: 1, - id: "lse_1", - requesterId: "agent", - ownerId: "agent", - ttlDeadline: 999_999, - }, - ], - }), - ); - const registry = await Registry.load({ + const state = await openTestState(); + let registry = await loadTestRegistry({ clock, eventBus, - filesystem, idGenerator: sequence(), - statePath: "/state.json", + state, }); + const device = await registry.registerDevice({ + driverData: { fakeDeviceId: "simlock-stuck" }, + driverDeviceId: "simlock-stuck", + provisionDuration: 0, + spec: { physical: false, model: "Phone", osVersion: "1", platform: "ios" }, + }); + await registry.transitionDevice(device.id, "ready", { + event: "device.ready", + payload: { bootDuration: 0, deviceId: device.id }, + }); + const first = await registry.createLease({ + deviceId: device.id, + ownerId: "agent", + requesterId: "agent", + ttlDeadline: 9_999_999, + ttlMs: 60_000, + }); + await registry.beginRelease(first.id); + // why: the registry never grants a lease on a reclaiming device, so the inconsistent row goes in directly. + state.database + .prepare( + "INSERT INTO leases (id, device_id, requester_id, owner_id, granted_at, ttl_ms, ttl_deadline, last_renewed_at, id_chosen_by_requester) VALUES ('lse_stray', ?, 'agent', 'agent', 1, 60000, 9999999, 1, 0)", + ) + .run(device.id); + registry = await loadTestRegistry({ clock, eventBus, idGenerator: sequence(), state }); + clock.advance(100_000); const driver = new FakeDriver({ clock, estimateMs: { reclaim: 2_000 }, platform: "ios" }); const quarantine = { enterFromStalledTransition: vi.fn() }; @@ -1486,7 +1355,7 @@ describe("Doctor", () => { }).reconcile({ fix: true }); expect(report.findings).toContainEqual( - expect.objectContaining({ deviceId: "dev_1", kind: "stalled-transition" }), + expect.objectContaining({ deviceId: device.id, kind: "stalled-transition" }), ); expect(quarantine.enterFromStalledTransition).not.toHaveBeenCalled(); expect(registry.snapshot.devices[0]?.state).toBe("reclaiming"); @@ -1496,12 +1365,10 @@ describe("Doctor", () => { it("reports no live-drift finding for a quarantined simulator while its retry runs, and registry-device-missing once the fake no longer lists it", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const device = await readyDevice(registry, "simlock-quarantined", "ios"); const lease = await registry.createLease({ @@ -1586,12 +1453,10 @@ describe("Doctor", () => { it("--fix reconciles an unleased device's state to observed reality in both directions", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const bootedOutside = await shutdownDevice(registry, "simlock-booted", "ios"); const shutdownOutside = await readyDevice(registry, "simlock-shutdown", "ios"); @@ -1638,16 +1503,14 @@ describe("Doctor", () => { it("--fix keeps a spent fresh device shutdown when it is observed running, so its delete still finds it", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), leaseIdentity: { android: "reusable", ios: "fresh" }, - statePath: "/state.json", }); const spent = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "simlock-spent" }, driverDeviceId: "simlock-spent", provisionDuration: 0, spec: { physical: false, model: "iPhone 16", osVersion: "26.5", platform: "ios" }, @@ -1697,12 +1560,10 @@ describe("Doctor", () => { it("--fix leaves a leased device untouched while still reporting the finding", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const device = await readyDevice(registry, "simlock-leased", "ios"); await registry.createLease({ @@ -1755,12 +1616,10 @@ describe("Doctor", () => { it("emits device.foreign-state-detected once per finding, post-commit", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const bootedOutside = await shutdownDevice(registry, "simlock-booted", "ios"); const shutdownOutside = await readyDevice(registry, "simlock-shutdown", "ios"); @@ -1834,12 +1693,10 @@ describe("Doctor", () => { async function setup() { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const registered = await registry.registerDevice({ driverData: { fakeDeviceId: "gone" }, @@ -1896,12 +1753,10 @@ describe("Doctor", () => { it("reports a platform whose driver refused to start, with the reason it refused", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const report = await new Doctor({ @@ -1933,12 +1788,10 @@ describe("Doctor", () => { it("leaves a refused driver alone under --fix, since adopting it is the refusal's point", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const report = await new Doctor({ @@ -1959,12 +1812,10 @@ describe("Doctor", () => { it("collects driver-advisory findings from a driver that implements advisories()", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const driver = withAdvisories(new FakeDriver({ clock, platform: "ios" }), [ { code: "slim-runtime-unsupported", message: "iOS 17.0 predates the 18.5 floor" }, @@ -1992,12 +1843,10 @@ describe("Doctor", () => { it("contributes nothing from a driver that has no advisories() method", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const driver = new FakeDriver({ clock, platform: "ios" }); @@ -2016,12 +1865,10 @@ describe("Doctor", () => { it("tolerates a rejecting advisories() without failing the rest of reconcile", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const registered = await registry.registerDevice({ driverData: { fakeDeviceId: "missing" }, @@ -2053,12 +1900,10 @@ describe("Doctor", () => { it("--fix never acts on a driver-advisory finding", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const driver = withAdvisories(new FakeDriver({ clock, platform: "ios" }), [ { code: "slim-runtime-unsupported", message: "detail" }, @@ -2087,12 +1932,10 @@ describe("Doctor", () => { it("excludes driver-advisory findings from the doctor.reconciled event's driftFindings", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const driver = withAdvisories(new FakeDriver({ clock, platform: "ios" }), [ { code: "slim-runtime-unsupported", message: "detail" }, @@ -2555,53 +2398,6 @@ describe("Doctor with a platform it cannot observe", () => { expect(registry.snapshot.devices[0]?.state).toBe("deleted"); }); - it("records a destroyed legacy device missing in the decision section, keeping a transition committed while that write is in flight", async () => { - const clock = new FakeClock(10_000); - const eventBus = new EventBus(clock); - const filesystem = new HeldWritesFilesystem(); - const registry = await Registry.load({ - clock, - eventBus, - filesystem, - idGenerator: sequence(), - statePath: "/state.json", - }); - const stranded = await readyDevice(registry, "stranded", "ios"); - const warm = await shutdownDevice(registry, "warm", "ios"); - const driver = new FakeDriver({ - clock, - legacyDevices: { - stranded: { device: driverDevice("stranded"), path: "/Library/Devices/stranded" }, - }, - platform: "ios", - }); - driver.setManagedReality({ devices: [observed("warm", "stopped")], processes: [] }); - const decisions = new SerializedDecision(); - const doctor = new Doctor({ - clock, - config: config(), - decisions, - drivers: [driver], - eventBus, - registry, - }); - - filesystem.holding = true; - const reconciling = doctor.reconcile({ fix: true }); - await filesystem.held(1); - const booting = decisions.run(() => - registry.transitionDevice(warm.id, "ready", { - event: "device.ready", - payload: { bootDuration: 0, deviceId: warm.id }, - }), - ); - await filesystem.releaseUntil(Promise.all([reconciling, booting])); - - const record = (id: string) => registry.snapshot.devices.find((d) => d.id === id); - expect(record(stranded.id)?.state).toBe("deleted"); - expect(record(warm.id)?.state).toBe("ready"); - }); - it("never destroys a legacy device that a lease still references", async () => { const { clock, driver, eventBus, registry } = await legacyDeviceSetup(); const device = registry.snapshot.devices[0]!; @@ -2858,12 +2654,10 @@ async function legacyDeviceSetup() { } function loadRegistry(clock: FakeClock, eventBus: EventBus): Promise { - return Registry.load({ + return loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); } @@ -2884,12 +2678,10 @@ function observed(deviceId: string, runState: "running" | "stopped") { async function readyIosDevice() { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const registered = await registry.registerDevice({ driverData: { fakeDeviceId: "device-1" }, @@ -2920,7 +2712,7 @@ async function readyDevice( platform: "ios" | "android", ) { const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: driverDeviceId }, driverDeviceId, provisionDuration: 0, spec: { physical: false, model: "Phone", osVersion: "1", platform }, @@ -2949,65 +2741,45 @@ async function shutdownDevice( } describe("Doctor and physical devices (ADR 0022 §4)", () => { - const physical = (state: "ready" | "leased" | "reclaiming", extra: object = {}) => ({ - createdAt: 1, - driverData: {}, - driverDeviceId: `00008110-${state}`, - enrolledApps: [], - id: `dev_${state}`, - physical: true, - spec: { - class: "phone", - model: "iPhone 15 Pro", - osVersion: "18.4", - physical: true, - platform: "ios", - }, - state, - ...extra, - }); - - async function physicalHarness(records: readonly object[], leases: readonly object[] = []) { - const clock = new FakeClock(100_000); + async function physicalHarness(states: readonly ("ready" | "leased" | "reclaiming")[]) { + const clock = new FakeClock(1_000); const eventBus = new EventBus(clock); - const filesystem = new MemoryFilesystem(); - await filesystem.writeFileAtomic( - "/state.json", - JSON.stringify({ devices: [], leases, physicalDevices: records }), - ); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem, idGenerator: sequence(), - statePath: "/state.json", }); + for (const state of states) { + const device = await registry.enrollPhysical({ + apps: [], + class: "phone", + driverDeviceId: `00008110-${state}`, + model: "iPhone 15 Pro", + osVersion: "18.4", + platform: "ios", + }); + if (state === "ready") continue; + const lease = await registry.createLease({ + deviceId: device.id, + ownerId: "agent", + requesterId: "agent", + ttlDeadline: 10_000_000, + ttlMs: 60_000, + }); + if (state === "reclaiming") await registry.beginRelease(lease.id); + } + clock.advance(99_000); const driver = new FakeDriver({ clock, estimateMs: { boot: 2_000, provision: 1_000, reclaim: 1_000 }, platform: "ios", }); driver.setManagedReality({ devices: [], processes: [] }); - return { clock, driver, eventBus, filesystem, registry }; + return { clock, driver, eventBus, registry }; } - const heldLease = { - deviceId: "dev_leased", - grantedAt: 1, - id: "lse_held", - idChosenByRequester: false, - lastRenewedAt: 1, - ownerId: "agent", - requesterId: "agent", - ttlDeadline: 10_000_000, - ttlMs: 60_000, - }; - it("raises no drift finding for a ready or a leased physical record that no root holds, and --fix leaves both as they are", async () => { - const { clock, driver, eventBus, registry } = await physicalHarness( - [physical("ready"), physical("leased")], - [heldLease], - ); + const { clock, driver, eventBus, registry } = await physicalHarness(["ready", "leased"]); const destroy = vi.spyOn(driver, "destroy"); const shutdown = vi.spyOn(driver, "shutdown"); @@ -3027,7 +2799,7 @@ describe("Doctor and physical devices (ADR 0022 §4)", () => { }); it("does not report as an orphan the ID a physical record holds, and a purge destroys only the orphan, as a virtual driver device", async () => { - const { clock, driver, eventBus, registry } = await physicalHarness([physical("ready")]); + const { clock, driver, eventBus, registry } = await physicalHarness(["ready"]); driver.setManagedReality({ devices: [ { @@ -3059,9 +2831,7 @@ describe("Doctor and physical devices (ADR 0022 §4)", () => { }); it("reports stalled-transition for a reclaiming physical record past its threshold, priced at the physical reclaim estimate, and --fix quarantines it", async () => { - const { clock, driver, eventBus, registry } = await physicalHarness([ - physical("reclaiming", { lastLeaseEndedAt: 1_000 }), - ]); + const { clock, driver, eventBus, registry } = await physicalHarness(["reclaiming"]); const quarantine = new QuarantineCoordinator({ claims: new DeviceOperationClaims(), clock, @@ -3091,7 +2861,7 @@ describe("Doctor and physical devices (ADR 0022 §4)", () => { expect(report.findings).toEqual([ expect.objectContaining({ - deviceId: "dev_reclaiming", + deviceId: registry.snapshot.devices[0]?.id, kind: "stalled-transition", thresholdMs: 90_000, }), @@ -3102,38 +2872,13 @@ describe("Doctor and physical devices (ADR 0022 §4)", () => { }); describe("Doctor and a physical reclaim in flight (ADR 0022 §7, §8)", () => { - const reclaimingRecord = (id: string, extra: object = {}) => ({ - createdAt: 1, - driverData: {}, - driverDeviceId: `00008110-${id}`, - enrolledApps: [], - id, - physical: true, - spec: { - class: "phone", - model: "iPhone 15 Pro", - osVersion: "18.4", - physical: true, - platform: "ios", - }, - state: "reclaiming", - ...extra, - }); - - async function harness(records: readonly object[]) { - const clock = new FakeClock(100_000); + async function harness() { + const clock = new FakeClock(1_000); const eventBus = new EventBus(clock); - const filesystem = new MemoryFilesystem(); - await filesystem.writeFileAtomic( - "/state.json", - JSON.stringify({ devices: [], leases: [], physicalDevices: records }), - ); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem, idGenerator: sequence(), - statePath: "/state.json", }); const driver = new FakeDriver({ clock, @@ -3167,14 +2912,48 @@ describe("Doctor and a physical reclaim in flight (ADR 0022 §7, §8)", () => { quarantine, registry, }); - return { claims, clock, doctor, eventBus, filesystem, quarantine, registry }; + return { claims, clock, doctor, eventBus, quarantine, registry }; + } + + async function enrollReclaiming(registry: Registry, name: string) { + const device = await registry.enrollPhysical({ + apps: [], + class: "phone", + driverDeviceId: `00008110-${name}`, + model: "iPhone 15 Pro", + osVersion: "18.4", + platform: "ios", + }); + const lease = await registry.createLease({ + deviceId: device.id, + ownerId: "agent", + requesterId: "agent", + ttlDeadline: 10_000_000, + ttlMs: 60_000, + }); + await registry.beginRelease(lease.id); + return device; } it("a physical reclaim interrupted by a killed daemon is aged from reclaimingSince by stalled-transition", async () => { - const { doctor, quarantine } = await harness([ - reclaimingRecord("dev_old_start", { lastLeaseEndedAt: 99_000, reclaimingSince: 1_000 }), - reclaimingRecord("dev_new_start", { lastLeaseEndedAt: 1_000, reclaimingSince: 99_000 }), - ]); + const { clock, doctor, quarantine, registry } = await harness(); + const oldStart = await enrollReclaiming(registry, "old_start"); + const newStart = await enrollReclaiming(registry, "new_start"); + await registry.transitionDevice( + newStart.id, + "absent", + { + event: "device.absence-detected", + payload: { absentReason: "locked", deviceId: newStart.id, previousState: "reclaiming" }, + }, + { absentReason: "locked" }, + ); + clock.advance(98_000); + await registry.transitionDevice(newStart.id, "reclaiming", { + event: "device.returned", + payload: { deviceId: newStart.id, osVersion: "18.4" }, + }); + clock.advance(1_000); const report = await doctor.reconcile(); @@ -3182,28 +2961,31 @@ describe("Doctor and a physical reclaim in flight (ADR 0022 §7, §8)", () => { report.findings .filter((finding) => finding.kind === "stalled-transition") .map((finding) => finding.deviceId), - ).toEqual(["dev_old_start"]); + ).toEqual([oldStart.id]); quarantine.dispose(); }); it("doctor --fix on a stalled reclaiming device that is claimed by the time the fix runs writes nothing, emits no device.quarantined and arms no retry", async () => { - const { claims, clock, doctor, eventBus, filesystem, quarantine, registry } = await harness([ - reclaimingRecord("dev_stalled", { lastLeaseEndedAt: 1_000, reclaimingSince: 1_000 }), - ]); - const before = await filesystem.readFile("/state.json"); + const { claims, clock, doctor, eventBus, quarantine, registry } = await harness(); + const stalled = await enrollReclaiming(registry, "stalled"); + clock.advance(99_000); + let commits = 0; + registry.onCommit(() => { + commits += 1; + }); let claimTaken = false; eventBus.subscribe("device.stalled-transition-detected", () => { - claimTaken = claims.tryClaim("dev_stalled", "reclaim") !== undefined; + claimTaken = claims.tryClaim(stalled.id, "reclaim") !== undefined; }); const report = await doctor.reconcile({ fix: true }); expect(report.findings).toContainEqual( - expect.objectContaining({ deviceId: "dev_stalled", kind: "stalled-transition" }), + expect.objectContaining({ deviceId: stalled.id, kind: "stalled-transition" }), ); expect(claimTaken).toBe(true); expect(registry.snapshot.devices[0]?.state).toBe("reclaiming"); - expect(await filesystem.readFile("/state.json")).toBe(before); + expect(commits).toBe(0); expect(eventBus.replay().filter((event) => event.event === "device.quarantined")).toEqual([]); expect(clock.pendingTimerCount).toBe(0); quarantine.dispose(); diff --git a/src/core/domain.ts b/src/core/domain.ts index 59dd49033..76199f8eb 100644 --- a/src/core/domain.ts +++ b/src/core/domain.ts @@ -22,9 +22,8 @@ export type DeviceClass = (typeof DEVICE_CLASSES)[number]; export type DeviceMode = "slim" | "full"; /** - * A simulator's or emulator's spec. `physical` is always `false` here, in memory and on every - * spec a driver resolves; a spec read from `devices` in `state.json` has none on disk and gains it - * on load. + * why: A simulator's or emulator's spec. `physical` is always `false` here, in memory and on every + * spec a driver resolves; the `devices` row stores it as 0 for a virtual device. */ export interface VirtualSpec { readonly physical: false; @@ -233,10 +232,9 @@ interface DeviceRecordFields { readonly quarantineNextRetryAt?: number; readonly quarantineCause?: QuarantineCause; /** - * The driver-reported address (see `DriverDevice.address`), current as of this device's + * why: The driver-reported address (see `DriverDevice.address`), current as of this device's * last `ready` transition. Undefined for a device still `provisioning` (never made ready - * yet) and, as an upgrade path, for a record written by a pre-address daemon -- `state.json` - * from before this field existed loads without one rather than failing to start. It becomes + * yet) and for a device that was shut down, which has no address to reach. It becomes * defined the next time the device is made ready (`bootForLease`/`readyProvisionedForLease`); * nothing here ever guesses at a value it wasn't told. */ @@ -298,20 +296,18 @@ export interface LeaseRecord { readonly deviceId: string; readonly requesterId: string; /** - * The session principal (ADR 0003 §4) that requested this lease -- the identity `renew`, + * why: The session principal (ADR 0003 §4) that requested this lease -- the identity `renew`, * `release`, and `list` compare against, not `requesterId` (which is attribution, defaults to * the principal, but a connection may set it to something else per request so one connection - * can hold many leases). A record written before this field existed loads with `ownerId` equal - * to `requesterId` -- see `parseLease` in `registry.ts`. + * can hold many leases). A request without a separate owner stores `requesterId` here. */ readonly ownerId: string; readonly grantedAt: number; /** - * The width this lease was granted with, or last renewed with when a renew named one (ADR + * why: The width this lease was granted with, or last renewed with when a renew named one (ADR * 0004 §4). Stored, not derived: a `lease.renew` carrying no `ttlMs` re-applies exactly this, * rather than falling back to `lease.defaultTtlMs`, so a lease granted for four hours does - * not shrink to fifteen minutes the first time something renews it. A record written before - * ADR 0004 loads with `lease.defaultTtlMs` here -- see `parseLease` in `registry.ts`. + * not shrink to fifteen minutes the first time something renews it. */ readonly ttlMs: number; readonly ttlDeadline: number; diff --git a/src/core/driver.ts b/src/core/driver.ts index 82a622a9d..b317fdc29 100644 --- a/src/core/driver.ts +++ b/src/core/driver.ts @@ -1,5 +1,5 @@ import type { EventMap } from "../bus/index.js"; -import type { Filesystem } from "../ports/index.js"; +import type { Filesystem, SqliteDatabase, SqliteSchemaOwner } from "../ports/index.js"; import type { RootRejectionReason } from "./device-root.js"; import type { ScreenCapture } from "./screen.js"; import type { @@ -16,6 +16,11 @@ import type { VirtualSpec, } from "./domain.js"; +export interface DeviceDataTable extends SqliteSchemaOwner { + write(database: SqliteDatabase, deviceId: string, driverData: unknown): void; + read(database: SqliteDatabase, deviceId: string): unknown; +} + export interface ExactDeviceRequest { readonly platform: Platform; readonly model: string; diff --git a/src/core/fake-driver.ts b/src/core/fake-driver.ts index d291927ad..4cee1743d 100644 --- a/src/core/fake-driver.ts +++ b/src/core/fake-driver.ts @@ -13,6 +13,7 @@ import { type ComponentReceipt, type ComponentRemoval, type ExactDeviceRequest, + type DeviceDataTable, type Driver, type DriverCatalogEntry, type DriverCatalogImage, @@ -823,3 +824,31 @@ function readPhysical(device: FakePhysicalDevice, id: string): PhysicalInspectio osVersion: device.osVersion ?? "1.0", }; } + +export const fakeDeviceDataTable: DeviceDataTable = { + migrations: [ + "CREATE TABLE fake_device_data (device_id TEXT PRIMARY KEY, fake_device_id TEXT NOT NULL) STRICT", + ], + name: "fake-device-data", + read(database, deviceId) { + const row = database + .prepare("SELECT fake_device_id FROM fake_device_data WHERE device_id = ?") + .get(deviceId); + if (row === undefined) throw new Error(`No fake driver data for device ${deviceId}`); + return { fakeDeviceId: row.fake_device_id }; + }, + version: 1, + write(database, deviceId, driverData) { + const data = driverData as Record | null | undefined; + const fakeDeviceId = data?.fakeDeviceId; + if (typeof fakeDeviceId !== "string" || Object.keys(data ?? {}).length !== 1) { + throw new Error(`Invalid fake driver data for device ${deviceId}`); + } + database + .prepare( + `INSERT INTO fake_device_data (device_id, fake_device_id) VALUES (?, ?) + ON CONFLICT (device_id) DO UPDATE SET fake_device_id = excluded.fake_device_id`, + ) + .run(deviceId, fakeDeviceId); + }, +}; diff --git a/src/core/index.ts b/src/core/index.ts index cb09ef9d1..fc0301501 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -6,7 +6,6 @@ export { type AlertFormatName, type Config, type ConfigOverrides, - // fallow-ignore-next-line unused-type -- public Config surface (config.mode, ADR 0005 §1); every in-tree reader gets it structurally off `Config` type DaemonMode, // fallow-ignore-next-line unused-type -- public Config surface (config.downloads.policy); no in-tree consumer names it directly yet type DownloadPolicy, @@ -23,6 +22,7 @@ export { type DeviceMode, type DeviceRecord, type DeviceSpec, + type DeviceTransitionUpdate, type LeaseRecord, type LeaseRequestFailure, type PhysicalClass, @@ -64,6 +64,7 @@ export { type DriverCatalogEntry, type DriverComponent, DriverCrashError, + type DeviceDataTable, type DriverDevice, type DriverEstimate, type DriverReality, @@ -131,6 +132,8 @@ export { InstanceIdentityError, loadInstanceId } from "./instance-identity.js"; export type { InstanceIdentityOptions } from "./instance-identity.js"; export { Nuke } from "./nuke.js"; export { type NukeExecutor } from "./core-ports.js"; +export { registryOwner } from "./registry-schema.js"; +export { RegistryLoadError } from "./registry-rows.js"; export { Registry, RegistryEventError, UnknownDeviceError, UnknownLeaseError } from "./registry.js"; export { ComponentInstaller, diff --git a/src/core/instance-identity.ts b/src/core/instance-identity.ts index 65193e919..2482af77f 100644 --- a/src/core/instance-identity.ts +++ b/src/core/instance-identity.ts @@ -3,7 +3,7 @@ import { dirname } from "node:path"; import type { Filesystem, IdGenerator } from "../ports/index.js"; /** why: Owner-only, like the other files that hold secrets or state (`config.json`, - * `state.json`, `tokens.json`, `admin.token`): the trust boundary is the OS user, and the id this + * `state.db`, `tokens.json`, `admin.token`): the trust boundary is the OS user, and the id this * file holds is what every device root's ownership marker is checked against. */ const INSTANCE_FILE_MODE = 0o600; @@ -25,13 +25,13 @@ export class InstanceIdentityError extends Error { } /** - * Reads this Simlock installation's identity, generating it exactly once. + * why: Reads this Simlock installation's identity, generating it exactly once. * * The identity is what every device root's ownership marker is checked against, so losing * it is not a recoverable inconvenience: a regenerated id strands every device already in * the root behind `wrong-instance`, with no way back short of deleting tens of gigabytes * by hand. That is why an unreadable or malformed file is a hard failure rather than a - * reason to write a fresh one, and why the id lives here instead of in `state.json` -- a + * reason to write a fresh one, and why the id lives here instead of in `state.db` -- a * corrupt registry is precisely the situation in which someone rebuilds state, and the * identity has to survive that (ADR 0001, decision 2). */ diff --git a/src/core/lease-request-store.ts b/src/core/lease-request-store.ts index afed157c4..8c59571b1 100644 --- a/src/core/lease-request-store.ts +++ b/src/core/lease-request-store.ts @@ -30,7 +30,7 @@ export type LeaseRequestOutcome = | { readonly state: "cancelled" }; /** - * Where lease-request records live. The daemon's `Registry` keeps them in `state.json`; a + * why: Where lease-request records live. The daemon's `Registry` keeps them in `state.db`; a * gateway keeps them in memory (`InMemoryLeaseRequestStore`). Both apply retention, the record * cap, and settlement through the functions below, so the two cannot disagree about them. */ diff --git a/src/core/managed-device-lifecycle.test.ts b/src/core/managed-device-lifecycle.test.ts index 5f435ed54..ef671aaaf 100644 --- a/src/core/managed-device-lifecycle.test.ts +++ b/src/core/managed-device-lifecycle.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from "vitest"; import { EventBus } from "../bus/index.js"; -import { FakeClock, MemoryFilesystem } from "../ports/index.js"; +import { FakeClock } from "../ports/index.js"; import { promiseState } from "../test-support/promise-state.js"; import { DeviceOperationClaims } from "./device-operation-claims.js"; import { @@ -14,11 +14,10 @@ import { DriverCatalog } from "./driver-catalog.js"; import { DriverCrashError } from "./driver.js"; import { FakeDriver } from "./fake-driver.js"; import { ManagedDeviceLifecycle } from "./managed-device-lifecycle.js"; -import { Registry } from "./registry.js"; +import type { Registry } from "./registry.js"; +import { loadTestRegistry, openTestState } from "./testing.js"; import { SerializedDecision } from "./serialized-decision.js"; -const statePath = "/home/agent/.simlock/state.json"; - /** The registry's transition, narrowed to the virtual device every test here acts on. */ async function transitionVirtual( registry: Registry, @@ -35,12 +34,10 @@ async function createHarness() { const eventBus = new EventBus(clock); const driver = new FakeDriver({ clock, platform: "ios" }); let nextId = 0; - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => `${nextId++}` }, - statePath, }); const claims = new DeviceOperationClaims(); const lifecycle = new ManagedDeviceLifecycle( @@ -486,12 +483,10 @@ describe("ManagedDeviceLifecycle", () => { const eventBus = new EventBus(clock); const driver = new FakeDriver({ clock, mode: "slim", platform: "ios" }); let nextId = 0; - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => `${nextId++}` }, - statePath, }); const claims = new DeviceOperationClaims(); const lifecycle = new ManagedDeviceLifecycle( @@ -555,8 +550,8 @@ describe("ManagedDeviceLifecycle", () => { }); it("readyProvisionedForLease stores full, replacing a stored slim, when the driver reports no mode (#makeReadyForLease, provisioning path)", async () => { - // A device can't naturally re-enter "provisioning" once it leaves, so the persisted state is - // seeded directly (as a restarted daemon would load it from disk) to exercise the same + // why: a device can't naturally re-enter "provisioning" once it leaves, so the persisted state is + // seeded directly in the database (as a restarted daemon would load it) to exercise the same // provisioning-branch code path the "shutdown" test above covers for the other branch. const clock = new FakeClock(1_000); const eventBus = new EventBus(clock); @@ -567,32 +562,25 @@ describe("ManagedDeviceLifecycle", () => { osVersion: "26.5", platform: "ios", }); - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [ - { - physical: false, - createdAt: 0, - driverData: driverDevice.driverData, - driverDeviceId: driverDevice.deviceId, - mode: "slim", - id: "dev_stale_2", - spec: { physical: false, model: "iPhone 16", osVersion: "26.5", platform: "ios" }, - state: "provisioning", - }, - ], - leases: [], - }), - ); - const registry = await Registry.load({ + const state = await openTestState(); + const seeding = await loadTestRegistry({ + clock, + eventBus, + idGenerator: { generate: () => "stale_2" }, + state, + }); + await seeding.registerDevice({ + driverData: driverDevice.driverData, + driverDeviceId: driverDevice.deviceId, + provisionDuration: 0, + spec: { physical: false, model: "iPhone 16", osVersion: "26.5", platform: "ios" }, + }); + state.database.prepare("UPDATE devices SET mode = 'slim'").run(); + const registry = await loadTestRegistry({ clock, eventBus, - filesystem, idGenerator: { generate: () => "unused" }, - statePath, + state, }); const lifecycle = new ManagedDeviceLifecycle( new DriverCatalog([driver]), @@ -624,12 +612,10 @@ describe("ManagedDeviceLifecycle", () => { const eventBus = new EventBus(clock); const driver = new FakeDriver({ clock, platform: "ios", slimmableOsVersions: ["26.5"] }); let nextId = 0; - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => `${nextId++}` }, - statePath, }); const claims = new DeviceOperationClaims(); const lifecycle = new ManagedDeviceLifecycle( diff --git a/src/core/nuke-service.test.ts b/src/core/nuke-service.test.ts index c77aadac1..3038cd318 100644 --- a/src/core/nuke-service.test.ts +++ b/src/core/nuke-service.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from "vitest"; import { EventBus } from "../bus/index.js"; -import { FakeClock, JsonLinesLogger, MemoryFilesystem, MemoryLogSink } from "../ports/index.js"; -import { Registry } from "./index.js"; +import { FakeClock, JsonLinesLogger, MemoryLogSink } from "../ports/index.js"; +import { loadTestRegistry } from "./testing.js"; import type { VirtualDevice, LeaseRecord } from "./domain.js"; import { FakeDriver } from "./fake-driver.js"; import { DeviceOperationClaims } from "./device-operation-claims.js"; @@ -255,12 +255,10 @@ describe("NukeService", () => { const eventBus = new EventBus(clock); const driver = new FakeDriver({ availableOsVersions: ["1"], clock, platform: "ios" }); let nextId = 1; - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => `${nextId++}` }, - statePath: "/state.json", }); const lifecycle = new ManagedDeviceLifecycle( new DriverCatalog([driver]), @@ -310,14 +308,22 @@ describe("NukeService", () => { } as const; const ios = { physical: false, model: "Phone", osVersion: "1", platform: "ios" } as const; - const ghostReady = await register(android, {}, "ghost-ready-android"); + const ghostReady = await register( + android, + { fakeDeviceId: "ghost-ready-android" }, + "ghost-ready-android", + ); const provisionedReady = await driver.provision(ios); const healthyReady = await register( ios, provisionedReady.driverData, provisionedReady.deviceId, ); - const ghostShutdown = await register(android, {}, "ghost-shutdown-android"); + const ghostShutdown = await register( + android, + { fakeDeviceId: "ghost-shutdown-android" }, + "ghost-shutdown-android", + ); await registry.transitionDevice(ghostShutdown.id, "shutdown", { event: "device.shutdown", payload: { deviceId: ghostShutdown.id, initiator: "test" }, diff --git a/src/core/nuke.test.ts b/src/core/nuke.test.ts index 3ed914bd8..c748cad92 100644 --- a/src/core/nuke.test.ts +++ b/src/core/nuke.test.ts @@ -1,24 +1,21 @@ import { describe, expect, it } from "vitest"; -import { testComponentWiring } from "./testing.js"; +import { loadTestRegistry, testComponentWiring } from "./testing.js"; import { EventBus } from "../bus/index.js"; -import { FakeClock, FakeSystemStats, MemoryFilesystem } from "../ports/index.js"; +import { FakeClock, FakeSystemStats } from "../ports/index.js"; import type { Config } from "./config.js"; import { FakeDriver } from "./fake-driver.js"; import { Nuke } from "./nuke.js"; -import { Registry } from "./registry.js"; import { createTestEngine } from "../leasing/testing.js"; describe("Nuke", () => { it("destroys every registry device and never targets a foreign device", async () => { const clock = new FakeClock(1_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const driver = new FakeDriver({ clock, platform: "ios" }); driver.setManagedReality({ @@ -81,12 +78,10 @@ describe("Nuke", () => { it("waits for a blocked reclaim before deleting the registry-owned device", async () => { const clock = new FakeClock(1_000); const eventBus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: sequence(), - statePath: "/state.json", }); const driver = new FakeDriver({ availableOsVersions: ["1"], diff --git a/src/core/physical-enrollment.test.ts b/src/core/physical-enrollment.test.ts index 7272f3dfa..49af0b412 100644 --- a/src/core/physical-enrollment.test.ts +++ b/src/core/physical-enrollment.test.ts @@ -4,9 +4,9 @@ import { EventBus } from "../bus/index.js"; import { FakeClock, FakeSystemStats, MemoryFilesystem } from "../ports/index.js"; import { type FakePhysicalDevice } from "./fake-driver.js"; import type { PhysicalDevice } from "./domain.js"; -import { createCore, loadConfig, Registry } from "./index.js"; +import { createCore, loadConfig } from "./index.js"; import { PhysicalEnrollment } from "./physical-enrollment.js"; -import { FakeDriver, testComponentWiring } from "./testing.js"; +import { FakeDriver, loadTestRegistry, testComponentWiring } from "./testing.js"; const UDID = "00008110-001A2B3C4D5E"; const ALIAS = "7A1C0E52-6B7D-4F1E-9C1A-2D3E4F5A6B7C"; @@ -26,12 +26,10 @@ async function build(physicalDevices: readonly FakePhysicalDevice[] = [IPHONE]) const filesystem = new MemoryFilesystem(); const systemStats = new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * 1024 ** 3 }); let next = 1; - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem, idGenerator: { generate: () => `${next++}` }, - statePath: "/state.json", }); const core = createCore({ clock, diff --git a/src/core/quarantine-coordinator.test.ts b/src/core/quarantine-coordinator.test.ts index 869b3b7f2..8c0a883ec 100644 --- a/src/core/quarantine-coordinator.test.ts +++ b/src/core/quarantine-coordinator.test.ts @@ -13,14 +13,13 @@ import { DeviceOperationClaims } from "./device-operation-claims.js"; import { DriverCatalog } from "./driver-catalog.js"; import type { VirtualDevice, VirtualSpec } from "./domain.js"; import { type FakePhysicalDevice } from "./fake-driver.js"; -import { FakeDriver, testComponentWiring } from "./testing.js"; +import { FakeDriver, loadTestRegistry, openTestState, testComponentWiring } from "./testing.js"; import { createCore, loadConfig } from "./index.js"; import { QuarantineCoordinator, type QuarantineRegistry, type QuarantineRetryConfig, } from "./quarantine-coordinator.js"; -import { Registry } from "./registry.js"; import type { PhysicalDevice } from "./domain.js"; import { SerializedDecision } from "./serialized-decision.js"; @@ -533,7 +532,7 @@ describe("QuarantineCoordinator", () => { leaseId: "lease-1", }); vi.spyOn(harness.registry, "recordQuarantineRetryFailure").mockRejectedValue( - new Error("state.json unwritable"), + new Error("state unwritable"), ); harness.clock.advance(retryConfig.retryBackoffMs); @@ -544,7 +543,7 @@ describe("QuarantineCoordinator", () => { module: "daemon.quarantine-coordinator", fields: { deviceId: harness.target.id, - error: "Error: state.json unwritable", + error: "Error: state unwritable", step: "retry", }, }), @@ -700,45 +699,38 @@ async function flush(): Promise { } describe("QuarantineCoordinator for a physical device (ADR 0022 §4)", () => { - const physicalRecord = { - createdAt: 600, - driverData: {}, - driverDeviceId: "00008110-001A2B3C4D5E", - enrolledApps: [], - id: "dev_physical", - lastLeaseEndedAt: 700, - physical: true, - spec: { - class: "phone", - model: "iPhone 15 Pro", - osVersion: "18.4", - physical: true, - platform: "ios", - }, - state: "reclaiming", - }; + const physicalRecord = { driverDeviceId: "00008110-001A2B3C4D5E" }; - async function physicalHarness(state: "reclaiming" | "quarantined") { + async function physicalHarness(stateName: "reclaiming" | "quarantined") { const clock = new FakeClock(1_000); const bus = new EventBus(clock); const driver = new FakeDriver({ clock, platform: "ios", reclaimResult: "ready" }); driver.setPhysicalPresence(physicalRecord.driverDeviceId, true); - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic( - "/home/agent/.simlock/state.json", - JSON.stringify({ - devices: [], - leases: [], - physicalDevices: [{ ...physicalRecord, quarantineNextRetryAt: 1_500, state }], - }), - ); - const registry = await Registry.load({ + const state = await openTestState(); + const seeding = await loadTestRegistry({ + clock, + eventBus: new EventBus(clock), + idGenerator: { generate: () => "physical" }, + state, + }); + await seeding.enrollPhysical({ + apps: [], + class: "phone", + driverDeviceId: physicalRecord.driverDeviceId, + model: "iPhone 15 Pro", + osVersion: "18.4", + platform: "ios", + }); + state.database + .prepare( + "UPDATE devices SET created_at = 600, last_lease_ended_at = 700, ready_at = NULL, state = ?, quarantine_next_retry_at = 1500", + ) + .run(stateName); + const registry = await loadTestRegistry({ clock, eventBus: bus, - filesystem, idGenerator: { generate: () => "id" }, - statePath: "/home/agent/.simlock/state.json", + state, }); // `decisionRuns` counts this device's own retry, which the shared clock's timer count does not. const decisions = new SerializedDecision(); @@ -1021,12 +1013,10 @@ describe("QuarantineCoordinator and enrollment of a quarantined physical device const filesystem = new MemoryFilesystem(); const systemStats = new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * 1024 ** 3 }); let next = 1; - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem, idGenerator: { generate: () => `${next++}` }, - statePath: "/state.json", }); const config = await loadConfig({ filesystem, systemStats }); const core = createCore({ @@ -1191,12 +1181,10 @@ describe("QuarantineCoordinator retry of a physical device that is not present ( const filesystem = new MemoryFilesystem(); const systemStats = new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * 1024 ** 3 }); let next = 1; - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem, idGenerator: { generate: () => `${next++}` }, - statePath: "/state.json", }); const config = await loadConfig({ filesystem, @@ -1451,60 +1439,52 @@ describe("QuarantineCoordinator quarantine cause", () => { const bus = new EventBus(clock); const driver = new FakeDriver({ clock, platform, reclaimResult: "ready" }); const state = options.state ?? "reclaiming"; - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); + const testState = await openTestState(); + const seeding = await loadTestRegistry({ + clock, + eventBus: new EventBus(clock), + idGenerator: { generate: () => (options.physical === true ? "physical" : "virtual") }, + state: testState, + }); let id: string; - let record: Record; if (options.physical === true) { driver.setPhysicalPresence(PHYSICAL_ID, true); id = "dev_physical"; - record = { - createdAt: 600, - driverData: {}, + await seeding.enrollPhysical({ + apps: [], + class: "phone", driverDeviceId: PHYSICAL_ID, - enrolledApps: [], - id, - lastLeaseEndedAt: 700, - physical: true, - spec: { - class: "phone", - model: "iPhone 15 Pro", - osVersion: "18.4", - physical: true, - platform: "ios", - }, - state, - }; + model: "iPhone 15 Pro", + osVersion: "18.4", + platform: "ios", + }); + testState.database + .prepare( + "UPDATE devices SET created_at = 600, last_lease_ended_at = 700, ready_at = NULL, state = ?", + ) + .run(state); } else { const virtualSpec = platform === "android" ? androidSpec : spec; const provisioned = await driver.provision(virtualSpec); id = "dev_virtual"; - record = { - createdAt: 1, - driverData: {}, + await seeding.registerDevice({ + driverData: provisioned.driverData, driverDeviceId: provisioned.deviceId, - id, - mode: "full", - physical: false, + provisionDuration: 0, spec: virtualSpec, - state, - ...(options.fresh === true ? { lastLeaseEndedAt: 900, leaseIdentity: "fresh" } : {}), - }; + }); + testState.database.prepare("UPDATE devices SET created_at = 1, state = ?").run(state); + if (options.fresh === true) { + testState.database + .prepare("UPDATE devices SET last_lease_ended_at = 900, lease_identity = 'fresh'") + .run(); + } } - await filesystem.writeFileAtomic( - "/home/agent/.simlock/state.json", - JSON.stringify( - options.physical === true - ? { devices: [], leases: [], physicalDevices: [record] } - : { devices: [record], leases: [] }, - ), - ); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: bus, - filesystem, idGenerator: { generate: () => "id" }, - statePath: "/home/agent/.simlock/state.json", + state: testState, }); const claims = new DeviceOperationClaims(); const coordinator = new QuarantineCoordinator({ diff --git a/src/core/reaper.test.ts b/src/core/reaper.test.ts index 3ac190876..986883791 100644 --- a/src/core/reaper.test.ts +++ b/src/core/reaper.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from "vitest"; -import { testComponentWiring } from "./testing.js"; +import { loadTestRegistry, testComponentWiring } from "./testing.js"; import { EventBus } from "../bus/index.js"; import { @@ -10,13 +10,7 @@ import { MemoryFilesystem, MemoryLogSink, } from "../ports/index.js"; -import { - automaticCleanupRules, - CleanupReaper, - type CleanupRule, - type Config, - Registry, -} from "./index.js"; +import { automaticCleanupRules, CleanupReaper, type CleanupRule, type Config } from "./index.js"; import { FakeDriver } from "./fake-driver.js"; import { CleanupExecutor } from "./cleanup-executor.js"; import { DeviceOperationClaims } from "./device-operation-claims.js"; @@ -26,7 +20,6 @@ import { SerializedDecision } from "./serialized-decision.js"; import { createTestEngine } from "../leasing/testing.js"; const gibibyte = 1024 ** 3; -const statePath = "/home/agent/.simlock/state.json"; const spec = { physical: false, model: "iPhone 16", osVersion: "26.5", platform: "ios" } as const; /** @@ -145,12 +138,10 @@ async function createHarness( platform: "ios", }); let nextId = 1; - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem, idGenerator: { generate: () => `${nextId++}` }, - statePath, }); const cleanupConfig = options.cleanupConfig ?? config(); const engine = createTestEngine({ @@ -567,7 +558,7 @@ describe("CleanupReaper", () => { // discovery refused. The ready one exercises the shutdown path, the shut-down one the // destroy path; a healthy device follows each. const ghostReady = await harness.registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "ghost-ready-android" }, driverDeviceId: "ghost-ready-android", provisionDuration: 0, spec: { model: "Pixel 8", osVersion: "35", physical: false, platform: "android" }, @@ -590,7 +581,7 @@ describe("CleanupReaper", () => { }); const idleReady = await seedReleased(harness, "ready"); const ghostShutdown = await harness.registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "ghost-shutdown-android" }, driverDeviceId: "ghost-shutdown-android", provisionDuration: 0, spec: { model: "Pixel 8", osVersion: "35", physical: false, platform: "android" }, diff --git a/src/core/reclaim-coordinator.test.ts b/src/core/reclaim-coordinator.test.ts index 9434a496f..f922d7cf6 100644 --- a/src/core/reclaim-coordinator.test.ts +++ b/src/core/reclaim-coordinator.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from "vitest"; import { EventBus } from "../bus/index.js"; -import { FakeClock, type Logger, MemoryFilesystem } from "../ports/index.js"; +import { FakeClock, type Logger } from "../ports/index.js"; import { DeviceOperationClaims } from "./device-operation-claims.js"; import type { DeviceRecord, @@ -14,7 +14,8 @@ import type { import { FakeDriver } from "./fake-driver.js"; import { DriverCatalog, NoDriverError } from "./driver-catalog.js"; import { QuarantineCoordinator, type QuarantinePurgeFailure } from "./quarantine-coordinator.js"; -import { Registry, type ReleasedLease } from "./registry.js"; +import type { ReleasedLease } from "./registry.js"; +import { loadTestRegistry, openTestState } from "./testing.js"; import { SerializedDecision } from "./serialized-decision.js"; import { ReclaimCoordinator, @@ -625,45 +626,32 @@ describe("ReclaimCoordinator for a physical device the platform no longer lists platform: "ios", reclaimResult: "ready", }); - const filesystem = new MemoryFilesystem(); - await filesystem.writeFileAtomic( - "/state.json", - JSON.stringify({ - devices: [], - leases: [], - physicalDevices: [ - { - createdAt: 1, - driverData: {}, - driverDeviceId: PHYSICAL_ID, - enrolledApps: [], - id: "dev_physical", - lastLeaseEndedAt: 900, - physical: true, - spec: { - class: "phone", - model: "iPhone 15 Pro", - osVersion: "18.4", - physical: true, - platform: "ios", - }, - state, - ...(state === "absent" ? { absentReason: "not-present" } : {}), - }, - ], - }), - ); - const loaded = await Registry.load({ + const testState = await openTestState(); + const seeding = await loadTestRegistry({ + clock, + eventBus: new EventBus(clock), + idGenerator: { generate: () => "physical" }, + state: testState, + }); + await seeding.enrollPhysical({ + apps: [], + class: "phone", + driverDeviceId: PHYSICAL_ID, + model: "iPhone 15 Pro", + osVersion: "18.4", + platform: "ios", + }); + testState.database + .prepare( + "UPDATE devices SET created_at = 1, last_lease_ended_at = 900, ready_at = NULL, state = ?, absent_reason = ?", + ) + .run(state, state === "absent" ? "not-present" : null); + const registry = await loadTestRegistry({ clock, eventBus: bus, - filesystem, idGenerator: { generate: () => "id" }, - statePath: "/state.json", - }).catch((error: unknown) => error); - expect(loaded, `a state.json holding a physical device in state ${state} loads`).toBeInstanceOf( - Registry, - ); - const registry = loaded as Registry; + state: testState, + }); const drivers = options.drivers?.(driver) ?? new DriverCatalog([driver]); const claims = new DeviceOperationClaims(); const decisions = new SerializedDecision(); diff --git a/src/core/registry-rows.ts b/src/core/registry-rows.ts new file mode 100644 index 000000000..6f97e3b07 --- /dev/null +++ b/src/core/registry-rows.ts @@ -0,0 +1,668 @@ +import type { SqliteDatabase, SqliteValue } from "../ports/index.js"; +import { + type AbsentReason, + DEVICE_CLASSES, + type DeviceClass, + type DeviceMode, + type DeviceRecord, + type LeaseGrant, + type LeaseIdentity, + type LeaseRecord, + type LeaseRequestRecord, + type LeaseRequestState, + type LeaseTiming, + type PhysicalClass, + type PhysicalState, + type Platform, + type QuarantineCause, + type VirtualDevice, + type VirtualState, +} from "./domain.js"; +import type { DeviceDataTable, DeviceRequest } from "./driver.js"; +import type { ComponentRecord } from "./registry.js"; + +type Row = Record; + +export class RegistryLoadError extends Error { + constructor(message: string) { + super(message); + this.name = "RegistryLoadError"; + } +} + +const PLATFORMS: readonly Platform[] = ["ios", "android"]; +const VIRTUAL_STATES: readonly VirtualState[] = [ + "provisioning", + "ready", + "leased", + "reclaiming", + "quarantined", + "shutdown", + "deleted", +]; +const PHYSICAL_STATES: readonly PhysicalState[] = [ + "ready", + "absent", + "leased", + "reclaiming", + "quarantined", + "deleted", +]; +const ABSENT_REASONS: readonly AbsentReason[] = ["locked", "untrusted", "not-present"]; +const PHYSICAL_CLASSES: readonly PhysicalClass[] = ["phone", "tablet"]; +const DEVICE_MODES: readonly DeviceMode[] = ["slim", "full"]; +const LEASE_IDENTITIES: readonly LeaseIdentity[] = ["reusable", "fresh"]; +const LEASE_REQUEST_STATES: readonly LeaseRequestState[] = [ + "open", + "granted", + "failed", + "cancelled", +]; +const QUARANTINE_KINDS: readonly QuarantineCause["kind"][] = [ + "purge-failed", + "shutdown-failed", + "delete-failed", + "stalled", +]; +const STALLED_STATES: readonly NonNullable[] = [ + "provisioning", + "reclaiming", +]; + +class RowReader { + constructor( + private readonly table: string, + private readonly key: string, + private readonly row: Row, + ) {} + + #fail(column: string): never { + throw new RegistryLoadError(`Invalid ${this.table} row ${this.key}: bad value in ${column}`); + } + + #present(column: string): unknown { + const value = this.row[column]; + return value === null || value === undefined ? undefined : value; + } + + text(column: string): string { + return this.optText(column) ?? this.#fail(column); + } + + optText(column: string): string | undefined { + const value = this.#present(column); + if (value !== undefined && typeof value !== "string") this.#fail(column); + return value; + } + + int(column: string): number { + return this.optInt(column) ?? this.#fail(column); + } + + optInt(column: string): number | undefined { + const value = this.#present(column); + if (value !== undefined && typeof value !== "number") this.#fail(column); + return value; + } + + flag(column: string): boolean { + return this.optFlag(column) ?? this.#fail(column); + } + + optFlag(column: string): boolean | undefined { + const value = this.#present(column); + if (value === undefined) return undefined; + if (value !== 0 && value !== 1) this.#fail(column); + return value === 1; + } + + oneOf(column: string, allowed: readonly T[]): T { + return this.optOneOf(column, allowed) ?? this.#fail(column); + } + + optOneOf(column: string, allowed: readonly T[]): T | undefined { + const value = this.optText(column); + if (value !== undefined && !allowed.some((candidate) => candidate === value)) { + this.#fail(column); + } + return value as T | undefined; + } +} + +function present(key: K, value: V | undefined): { [P in K]?: V } { + return (value === undefined ? {} : { [key]: value }) as { [P in K]?: V }; +} + +const DEVICE_OPTIONAL_NUMBERS = [ + ["lastLeaseEndedAt", "last_lease_ended_at"], + ["readyAt", "ready_at"], + ["shutdownAt", "shutdown_at"], + ["foreignStateDetectedAt", "foreign_state_detected_at"], + ["foreignProvenanceDetectedAt", "foreign_provenance_detected_at"], + ["recoveringSince", "recovering_since"], + ["recoveryAttempts", "recovery_attempts"], + ["quarantinedAt", "quarantined_at"], + ["quarantineAttempts", "quarantine_attempts"], + ["quarantineNextRetryAt", "quarantine_next_retry_at"], +] as const; + +const DEVICE_COLUMNS = [ + "id", + "platform", + "physical", + "driver_device_id", + "state", + "model", + "os_version", + "spec_mode", + "image_tag", + "class", + "mode", + "lease_identity", + "created_at", + ...DEVICE_OPTIONAL_NUMBERS.map(([, column]) => column), + "deferred_reclaim_lease_id", + "quarantine_cause_kind", + "quarantine_cause_stalled_state", + "quarantine_cause_message", + "address", + "reclaiming_since", + "absent_reason", +] as const; + +const LEASE_COLUMNS = [ + "id", + "device_id", + "requester_id", + "owner_id", + "granted_at", + "ttl_ms", + "ttl_deadline", + "last_renewed_at", + "id_chosen_by_requester", +] as const; + +const REQUEST_COLUMNS = [ + "id", + "requester_id", + "owner_id", + "idempotency_key", + "lease_id", + "fleet_request_id", + "platform", + "model", + "os_version", + "mode", + "image_tag", + "class", + "physical", + "created_at", + "state", + "settled_at", + "failure_code", + "failure_message", +] as const; + +const GRANT_COLUMNS = [ + "request_id", + "device_id", + "lease_id", + "requester_id", + "owner_id", + "granted_at", + "ttl_ms", + "ttl_deadline", + "last_renewed_at", + "id_chosen_by_requester", + "estimated_provision_ms", + "estimated_boot_ms", + "estimated_reclaim_ms", + "estimated_ready_ms", +] as const; + +function upsertSql(table: string, columns: readonly string[], key: string): string { + const updates = columns + .filter((column) => column !== key) + .map((column) => `${column} = excluded.${column}`) + .join(", "); + return `INSERT INTO ${table} (${columns.join(", ")}) VALUES (${columns.map(() => "?").join(", ")}) + ON CONFLICT (${key}) DO UPDATE SET ${updates}`; +} + +function flagValue(value: boolean | undefined): number | null { + return value === undefined ? null : value ? 1 : 0; +} + +function specColumns(device: DeviceRecord): SqliteValue[] { + if (device.physical) return [null, null, device.spec.class]; + return [device.spec.mode ?? null, device.spec.imageTag ?? null, null]; +} + +function causeColumns(cause: QuarantineCause | undefined): SqliteValue[] { + return [cause?.kind ?? null, cause?.stalledState ?? null, cause?.message ?? null]; +} + +function physicalColumns(device: DeviceRecord): SqliteValue[] { + if (!device.physical) return [null, null]; + return [device.reclaimingSince ?? null, device.absentReason ?? null]; +} + +function deviceValues(device: DeviceRecord): SqliteValue[] { + return [ + device.id, + device.spec.platform, + flagValue(device.physical), + device.driverDeviceId, + device.state, + device.spec.model, + device.spec.osVersion, + ...specColumns(device), + device.mode ?? null, + device.leaseIdentity ?? null, + device.createdAt, + ...DEVICE_OPTIONAL_NUMBERS.map(([property]) => device[property] ?? null), + device.deferredReclaimLeaseId ?? null, + ...causeColumns(device.quarantineCause), + device.address ?? null, + ...physicalColumns(device), + ]; +} + +const UPSERT_DEVICE = upsertSql("devices", DEVICE_COLUMNS, "id"); +const UPSERT_LEASE = upsertSql("leases", LEASE_COLUMNS, "id"); +const UPSERT_REQUEST = upsertSql("lease_requests", REQUEST_COLUMNS, "id"); +const UPSERT_GRANT = upsertSql("lease_grants", GRANT_COLUMNS, "request_id"); + +export function writeDevice( + database: SqliteDatabase, + device: DeviceRecord, + deviceData: ReadonlyMap, +): void { + database.prepare(UPSERT_DEVICE).run(...deviceValues(device)); + if (device.physical) { + database.prepare("DELETE FROM device_enrolled_apps WHERE device_id = ?").run(device.id); + device.enrolledApps.forEach((app, position) => { + database + .prepare("INSERT INTO device_enrolled_apps (device_id, position, app) VALUES (?, ?, ?)") + .run(device.id, position, app); + }); + return; + } + const table = deviceData.get(device.spec.platform); + if (table === undefined) { + throw new Error(`No device-data table for platform ${device.spec.platform}`); + } + table.write(database, device.id, device.driverData); +} + +function leaseValues(lease: LeaseRecord): SqliteValue[] { + return [ + lease.id, + lease.deviceId, + lease.requesterId, + lease.ownerId, + lease.grantedAt, + lease.ttlMs, + lease.ttlDeadline, + lease.lastRenewedAt, + flagValue(lease.idChosenByRequester), + ]; +} + +export function writeLease(database: SqliteDatabase, lease: LeaseRecord): void { + database.prepare(UPSERT_LEASE).run(...leaseValues(lease)); +} + +export function deleteLease(database: SqliteDatabase, id: string): void { + database.prepare("DELETE FROM leases WHERE id = ?").run(id); +} + +export function writeLeaseRequest(database: SqliteDatabase, record: LeaseRequestRecord): void { + const { request } = record; + database + .prepare(UPSERT_REQUEST) + .run( + record.id, + record.requesterId, + record.ownerId, + record.idempotencyKey ?? null, + record.leaseId ?? null, + record.fleetRequestId ?? null, + request.platform, + request.model ?? null, + request.osVersion ?? null, + request.mode ?? null, + request.imageTag ?? null, + request.class ?? null, + flagValue(request.physical), + record.createdAt, + record.state, + record.settledAt ?? null, + record.failure?.code ?? null, + record.failure?.message ?? null, + ); + if (record.grant === undefined) return; + const { grant } = record; + const { lease } = grant; + database + .prepare(UPSERT_GRANT) + .run( + record.id, + grant.device.id, + lease.id, + lease.requesterId, + lease.ownerId, + lease.grantedAt, + lease.ttlMs, + lease.ttlDeadline, + lease.lastRenewedAt, + flagValue(lease.idChosenByRequester), + grant.timing.estimatedProvisionMs, + grant.timing.estimatedBootMs, + grant.timing.estimatedReclaimMs, + grant.timing.estimatedReadyMs, + ); + database.prepare("DELETE FROM lease_grant_environment WHERE request_id = ?").run(record.id); + for (const [name, value] of Object.entries(grant.environment)) { + database + .prepare("INSERT INTO lease_grant_environment (request_id, name, value) VALUES (?, ?, ?)") + .run(record.id, name, value); + } +} + +export function deleteLeaseRequest(database: SqliteDatabase, id: string): void { + database.prepare("DELETE FROM lease_grant_environment WHERE request_id = ?").run(id); + database.prepare("DELETE FROM lease_grants WHERE request_id = ?").run(id); + database.prepare("DELETE FROM lease_requests WHERE id = ?").run(id); +} + +export function writeComponent(database: SqliteDatabase, record: ComponentRecord): void { + deleteComponentRows(database, record.platform, record.version); + database + .prepare("INSERT INTO components (platform, version, installed_at) VALUES (?, ?, ?)") + .run(record.platform, record.version, record.installedAt); + for (const [key, value] of Object.entries(record.receipt)) { + database + .prepare("INSERT INTO component_receipt (platform, version, key, value) VALUES (?, ?, ?, ?)") + .run(record.platform, record.version, key, value); + } +} + +export function deleteComponentRows( + database: SqliteDatabase, + platform: Platform, + version: string, +): void { + database + .prepare("DELETE FROM component_receipt WHERE platform = ? AND version = ?") + .run(platform, version); + database + .prepare("DELETE FROM components WHERE platform = ? AND version = ?") + .run(platform, version); +} + +export interface LoadedRegistry { + readonly devices: DeviceRecord[]; + readonly leases: LeaseRecord[]; + readonly leaseRequests: LeaseRequestRecord[]; + readonly components: ComponentRecord[]; +} + +export function loadRegistryRows( + database: SqliteDatabase, + deviceData: ReadonlyMap, +): LoadedRegistry { + const appsByDevice = new Map(); + for (const row of database + .prepare("SELECT device_id, app FROM device_enrolled_apps ORDER BY device_id, position") + .all()) { + const reader = new RowReader("device_enrolled_apps", String(row.device_id), row); + const apps = appsByDevice.get(reader.text("device_id")) ?? []; + apps.push(reader.text("app")); + appsByDevice.set(reader.text("device_id"), apps); + } + const devices = database + .prepare("SELECT * FROM devices ORDER BY rowid") + .all() + .map((row) => deviceFromRow(database, row, appsByDevice, deviceData)); + const leases = database + .prepare("SELECT * FROM leases ORDER BY rowid") + .all() + .map((row) => leaseFromRow("leases", String(row.id), row, "id")); + const byId = new Map(devices.map((device) => [device.id, device])); + return { + components: loadComponents(database), + devices, + leaseRequests: loadLeaseRequests(database, byId), + leases, + }; +} + +function deviceFromRow( + database: SqliteDatabase, + row: Row, + appsByDevice: ReadonlyMap, + deviceData: ReadonlyMap, +): DeviceRecord { + const reader = new RowReader("devices", String(row.id), row); + const id = reader.text("id"); + const platform = reader.oneOf("platform", PLATFORMS); + const physical = reader.flag("physical"); + const shared = { + createdAt: reader.int("created_at"), + driverDeviceId: reader.text("driver_device_id"), + id, + ...Object.fromEntries( + DEVICE_OPTIONAL_NUMBERS.flatMap(([property, column]) => { + const value = reader.optInt(column); + return value === undefined ? [] : [[property, value]]; + }), + ), + ...present("address", reader.optText("address")), + ...present("deferredReclaimLeaseId", reader.optText("deferred_reclaim_lease_id")), + ...present("quarantineCause", quarantineCause(reader)), + }; + const model = reader.text("model"); + const osVersion = reader.text("os_version"); + if (physical) { + return { + ...shared, + driverData: {}, + enrolledApps: appsByDevice.get(id) ?? [], + physical: true, + ...present("reclaimingSince", reader.optInt("reclaiming_since")), + ...present("absentReason", reader.optOneOf("absent_reason", ABSENT_REASONS)), + spec: { + class: reader.oneOf("class", PHYSICAL_CLASSES), + model, + osVersion, + physical: true, + platform, + }, + state: reader.oneOf("state", PHYSICAL_STATES), + }; + } + const virtual: VirtualDevice = { + ...shared, + driverData: readDeviceData(database, deviceData, platform, id), + ...present("leaseIdentity", reader.optOneOf("lease_identity", LEASE_IDENTITIES)), + mode: reader.oneOf("mode", DEVICE_MODES), + physical: false, + spec: { + ...present("imageTag", reader.optText("image_tag")), + ...present("mode", reader.optOneOf("spec_mode", ["slim"] as const)), + model, + osVersion, + physical: false, + platform, + }, + state: reader.oneOf("state", VIRTUAL_STATES), + }; + return virtual; +} + +function quarantineCause(reader: RowReader): QuarantineCause | undefined { + const kind = reader.optOneOf("quarantine_cause_kind", QUARANTINE_KINDS); + if (kind === undefined) return undefined; + return { + kind, + ...present("stalledState", reader.optOneOf("quarantine_cause_stalled_state", STALLED_STATES)), + ...present("message", reader.optText("quarantine_cause_message")), + }; +} + +function readDeviceData( + database: SqliteDatabase, + deviceData: ReadonlyMap, + platform: Platform, + id: string, +): unknown { + const table = deviceData.get(platform); + if (table === undefined) { + throw new RegistryLoadError(`Invalid devices row ${id}: no device-data table for ${platform}`); + } + try { + return table.read(database, id); + } catch (error: unknown) { + throw new RegistryLoadError( + `Invalid devices row ${id}: no row in ${table.name}: ${error instanceof Error ? error.message : String(error)}`, + ); + } +} + +function leaseFromRow(table: string, key: string, row: Row, idColumn: string): LeaseRecord { + const reader = new RowReader(table, key, row); + return { + deviceId: reader.text("device_id"), + grantedAt: reader.int("granted_at"), + id: reader.text(idColumn), + idChosenByRequester: reader.flag("id_chosen_by_requester"), + lastRenewedAt: reader.int("last_renewed_at"), + ownerId: reader.text("owner_id"), + requesterId: reader.text("requester_id"), + ttlDeadline: reader.int("ttl_deadline"), + ttlMs: reader.int("ttl_ms"), + }; +} + +function loadLeaseRequests( + database: SqliteDatabase, + devices: ReadonlyMap, +): LeaseRequestRecord[] { + const environments = new Map>(); + for (const row of database.prepare("SELECT * FROM lease_grant_environment").all()) { + const reader = new RowReader("lease_grant_environment", String(row.request_id), row); + const environment = environments.get(reader.text("request_id")) ?? {}; + environment[reader.text("name")] = reader.text("value"); + environments.set(reader.text("request_id"), environment); + } + const grants = new Map(); + for (const row of database.prepare("SELECT * FROM lease_grants").all()) { + grants.set(String(row.request_id), row); + } + return database + .prepare("SELECT * FROM lease_requests ORDER BY rowid") + .all() + .map((row) => { + const reader = new RowReader("lease_requests", String(row.id), row); + const id = reader.text("id"); + const state = reader.oneOf("state", LEASE_REQUEST_STATES); + const grantRow = grants.get(id); + if ((state === "granted") !== (grantRow !== undefined)) { + throw new RegistryLoadError( + `Invalid lease_requests row ${id}: state ${state} and its grant disagree`, + ); + } + const failureCode = reader.optText("failure_code"); + return { + createdAt: reader.int("created_at"), + id, + ...present("idempotencyKey", reader.optText("idempotency_key")), + ...present("leaseId", reader.optText("lease_id")), + ...present("fleetRequestId", reader.optText("fleet_request_id")), + ownerId: reader.text("owner_id"), + request: requestFromRow(reader), + requesterId: reader.text("requester_id"), + state, + ...present("settledAt", reader.optInt("settled_at")), + ...(failureCode === undefined + ? {} + : { failure: { code: failureCode, message: reader.text("failure_message") } }), + ...(grantRow === undefined + ? {} + : { grant: grantFromRow(id, grantRow, devices, environments.get(id) ?? {}) }), + }; + }); +} + +function requestFromRow(reader: RowReader): DeviceRequest { + return { + platform: reader.oneOf("platform", PLATFORMS), + ...present("model", reader.optText("model")), + ...present("osVersion", reader.optText("os_version")), + ...present("mode", reader.optOneOf("mode", DEVICE_MODES)), + ...present("imageTag", reader.optText("image_tag")), + ...present("class", reader.optOneOf("class", DEVICE_CLASSES)), + ...present("physical", reader.optFlag("physical")), + }; +} + +function grantFromRow( + requestId: string, + row: Row, + devices: ReadonlyMap, + environment: Record, +): LeaseGrant { + const reader = new RowReader("lease_grants", requestId, row); + const device = devices.get(reader.text("device_id")); + if (device === undefined) { + throw new RegistryLoadError( + `Invalid lease_grants row ${requestId}: no device ${reader.text("device_id")}`, + ); + } + const timing: LeaseTiming = { + estimatedBootMs: reader.int("estimated_boot_ms"), + estimatedProvisionMs: reader.int("estimated_provision_ms"), + estimatedReadyMs: reader.int("estimated_ready_ms"), + estimatedReclaimMs: reader.int("estimated_reclaim_ms"), + }; + return { + device, + environment, + lease: leaseFromRow("lease_grants", requestId, { ...row, id: row.lease_id }, "id"), + timing, + }; +} + +function loadComponents(database: SqliteDatabase): ComponentRecord[] { + const receipts = new Map>(); + for (const row of database.prepare("SELECT * FROM component_receipt").all()) { + const reader = new RowReader( + "component_receipt", + `${String(row.platform)}/${String(row.version)}`, + row, + ); + const identity = `${reader.text("platform")}\0${reader.text("version")}`; + const receipt = receipts.get(identity) ?? {}; + receipt[reader.text("key")] = reader.text("value"); + receipts.set(identity, receipt); + } + return database + .prepare("SELECT * FROM components ORDER BY rowid") + .all() + .map((row) => { + const reader = new RowReader( + "components", + `${String(row.platform)}/${String(row.version)}`, + row, + ); + const platform = reader.oneOf("platform", PLATFORMS); + const version = reader.text("version"); + return { + installedAt: reader.int("installed_at"), + platform, + receipt: receipts.get(`${platform}\0${version}`) ?? {}, + version, + }; + }); +} diff --git a/src/core/registry-schema.ts b/src/core/registry-schema.ts new file mode 100644 index 000000000..adace09c2 --- /dev/null +++ b/src/core/registry-schema.ts @@ -0,0 +1,122 @@ +import type { SqliteSchemaOwner } from "../ports/index.js"; + +const REGISTRY_V1 = ` +CREATE TABLE devices ( + id TEXT PRIMARY KEY, + platform TEXT NOT NULL, + physical INTEGER NOT NULL, + driver_device_id TEXT NOT NULL, + state TEXT NOT NULL, + model TEXT NOT NULL, + os_version TEXT NOT NULL, + spec_mode TEXT, + image_tag TEXT, + class TEXT, + mode TEXT, + lease_identity TEXT, + created_at INTEGER NOT NULL, + last_lease_ended_at INTEGER, + ready_at INTEGER, + shutdown_at INTEGER, + foreign_state_detected_at INTEGER, + foreign_provenance_detected_at INTEGER, + recovering_since INTEGER, + recovery_attempts INTEGER, + deferred_reclaim_lease_id TEXT, + quarantined_at INTEGER, + quarantine_attempts INTEGER, + quarantine_next_retry_at REAL, + quarantine_cause_kind TEXT, + quarantine_cause_stalled_state TEXT, + quarantine_cause_message TEXT, + address TEXT, + reclaiming_since INTEGER, + absent_reason TEXT +) STRICT; + +CREATE TABLE device_enrolled_apps ( + device_id TEXT NOT NULL REFERENCES devices (id), + position INTEGER NOT NULL, + app TEXT NOT NULL, + PRIMARY KEY (device_id, position) +) STRICT; + +CREATE TABLE leases ( + id TEXT PRIMARY KEY, + device_id TEXT NOT NULL, + requester_id TEXT NOT NULL, + owner_id TEXT NOT NULL, + granted_at INTEGER NOT NULL, + ttl_ms REAL NOT NULL, + ttl_deadline REAL NOT NULL, + last_renewed_at INTEGER NOT NULL, + id_chosen_by_requester INTEGER NOT NULL +) STRICT; + +CREATE TABLE lease_requests ( + id TEXT PRIMARY KEY, + requester_id TEXT NOT NULL, + owner_id TEXT NOT NULL, + idempotency_key TEXT, + lease_id TEXT, + fleet_request_id TEXT, + platform TEXT NOT NULL, + model TEXT, + os_version TEXT, + mode TEXT, + image_tag TEXT, + class TEXT, + physical INTEGER, + created_at INTEGER NOT NULL, + state TEXT NOT NULL, + settled_at INTEGER, + failure_code TEXT, + failure_message TEXT +) STRICT; + +CREATE TABLE lease_grants ( + request_id TEXT PRIMARY KEY REFERENCES lease_requests (id), + device_id TEXT NOT NULL REFERENCES devices (id), + lease_id TEXT NOT NULL, + requester_id TEXT NOT NULL, + owner_id TEXT NOT NULL, + granted_at INTEGER NOT NULL, + ttl_ms REAL NOT NULL, + ttl_deadline REAL NOT NULL, + last_renewed_at INTEGER NOT NULL, + id_chosen_by_requester INTEGER NOT NULL, + estimated_provision_ms INTEGER NOT NULL, + estimated_boot_ms INTEGER NOT NULL, + estimated_reclaim_ms INTEGER NOT NULL, + estimated_ready_ms INTEGER NOT NULL +) STRICT; + +CREATE TABLE lease_grant_environment ( + request_id TEXT NOT NULL REFERENCES lease_grants (request_id), + name TEXT NOT NULL, + value TEXT NOT NULL, + PRIMARY KEY (request_id, name) +) STRICT; + +CREATE TABLE components ( + platform TEXT NOT NULL, + version TEXT NOT NULL, + installed_at INTEGER NOT NULL, + PRIMARY KEY (platform, version) +) STRICT; + +CREATE TABLE component_receipt ( + platform TEXT NOT NULL, + version TEXT NOT NULL, + key TEXT NOT NULL, + value TEXT NOT NULL, + PRIMARY KEY (platform, version, key), + FOREIGN KEY (platform, version) REFERENCES components (platform, version) +) STRICT; +`; + +export const registryOwner: SqliteSchemaOwner = { + migrations: [REGISTRY_V1], + name: "registry", + version: 1, +}; diff --git a/src/core/registry.test.ts b/src/core/registry.test.ts index ae0b7dbae..e43841392 100644 --- a/src/core/registry.test.ts +++ b/src/core/registry.test.ts @@ -1,18 +1,28 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + import { describe, expect, it } from "vitest"; import { EventBus } from "../bus/index.js"; -import { FakeClock, MemoryFilesystem } from "../ports/index.js"; +import { FakeClock, NodeFilesystem, NodeSqliteOpener, NoopLogger } from "../ports/index.js"; +import { type StateDatabase, openStateDatabase } from "../state/index.js"; +import { fakeDeviceDataTable, loadTestRegistry, openTestState } from "./testing.js"; import { + type DeviceDataTable, type DeviceRecord, + type DeviceTransitionUpdate, + type Platform, type VirtualSpec, Registry, + registryOwner, RegistryEventError, + RegistryLoadError, UnknownDeviceError, UnknownLeaseError, transitionEnteredAt, } from "./index.js"; -const statePath = "/home/agent/.simlock/state.json"; const spec: VirtualSpec = { physical: false, model: "iPhone 16", @@ -20,34 +30,47 @@ const spec: VirtualSpec = { platform: "ios", }; -class ObservingFilesystem extends MemoryFilesystem { - readonly operations: string[] = []; +function totalChanges(state: StateDatabase): unknown { + return state.database.prepare("SELECT total_changes() AS changes").get()?.changes; +} - override async writeFileAtomic( - path: string, - contents: string, - options?: { mode?: number }, - ): Promise { - this.operations.push("save"); - await super.writeFileAtomic(path, contents, options); - } +async function loadAfterCorruptingDevice(assignment: string): Promise { + const clock = new FakeClock(1_000); + const state = await openTestState(); + const registry = await loadTestRegistry({ + clock, + eventBus: new EventBus(clock), + idGenerator: { generate: () => "stored" }, + state, + }); + await registry.registerDevice({ + driverData: { fakeDeviceId: "fake-1" }, + driverDeviceId: "driver_stored", + provisionDuration: 0, + spec, + }); + state.database.prepare(`UPDATE devices SET ${assignment}`).run(); + return loadTestRegistry({ + clock, + eventBus: new EventBus(clock), + idGenerator: { generate: () => "new" }, + state, + }); } describe("Registry: component records", () => { - async function load(filesystem: MemoryFilesystem) { + async function load(state: StateDatabase) { const clock = new FakeClock(1_000); - return Registry.load({ + return loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem, idGenerator: { generate: () => "test" }, - statePath, + state, }); } it("keeps one record per platform and version, the latest install replacing the earlier one", async () => { - const filesystem = new MemoryFilesystem(); - const registry = await load(filesystem); + const registry = await load(await openTestState()); await registry.recordComponent({ installedAt: 1, @@ -75,8 +98,8 @@ 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); + const state = await openTestState(); + const registry = await load(state); for (const [platform, version] of [ ["ios", "26.4"], ["ios", "27.0"], @@ -92,41 +115,17 @@ describe("Registry: component records", () => { { 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"); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - components: [ - { installedAt: 1, platform: "ios", receipt: { image: 7 }, version: "26.5" }, - { installedAt: 2, platform: "ios", receipt: { image: "IMG" }, version: "26.4" }, - ], - devices: [], - leases: [], - }), - ); - - const registry = await load(filesystem); - - expect(registry.snapshot.components).toEqual([ - { installedAt: 2, platform: "ios", receipt: { image: "IMG" }, version: "26.4" }, - ]); + expect((await load(state)).snapshot.components).toEqual(kept); }); }); describe("Registry", () => { - it("loads an empty registry when no state file exists", async () => { + it("loads an empty registry from a new state.db", async () => { const clock = new FakeClock(1_000); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => "test" }, - statePath, }); expect(registry.snapshot).toEqual({ @@ -137,33 +136,34 @@ describe("Registry", () => { }); }); - it("atomically persists a registered device before emitting device.provisioned", async () => { + it("persists a registered device before emitting device.provisioned", async () => { const clock = new FakeClock(1_000); - const filesystem = new ObservingFilesystem(); + const state = await openTestState(); const bus = new EventBus(clock); - bus.subscribe("device.provisioned", () => filesystem.operations.push("event")); - const registry = await Registry.load({ + const storedAtEvent: unknown[] = []; + bus.subscribe("device.provisioned", () => + storedAtEvent.push(state.database.prepare("SELECT id FROM devices").all()), + ); + const registry = await loadTestRegistry({ clock, eventBus: bus, - filesystem, idGenerator: { generate: () => "test" }, - statePath, + state, }); await registry.registerDevice({ - driverData: { driverOnly: "value" }, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_test", provisionDuration: 25, spec, }); - expect(filesystem.operations).toEqual(["save", "event"]); - await expect(filesystem.readFile(statePath)).resolves.toMatch(/"id":"dev_test"/); + expect(storedAtEvent).toEqual([[{ id: "dev_test" }]]); expect(registry.snapshot.devices).toEqual([ { physical: false, createdAt: 1_000, - driverData: { driverOnly: "value" }, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_test", id: "dev_test", leaseIdentity: "reusable", @@ -174,176 +174,294 @@ describe("Registry", () => { ]); }); - it("restores persisted device records after a reload", async () => { - const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - const options = { - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "test" }, - statePath, - }; - const registry = await Registry.load(options); - await registry.registerDevice({ - driverData: { driverOnly: "value" }, - driverDeviceId: "driver_test", - provisionDuration: 25, - spec, - }); - - const reloaded = await Registry.load(options); - - expect(reloaded.snapshot).toEqual(registry.snapshot); - }); - - it("writes state.json owner-only, mode 0o600, as the daemon's local-state guarantee says", async () => { - const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - const registry = await Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "test" }, - statePath, - }); - - await registry.registerDevice({ - driverData: {}, - driverDeviceId: "driver_test", - provisionDuration: 25, - spec, - }); - - expect((await filesystem.stat(statePath)).mode).toBe(0o600); - }); - - it("loads a legacy warm record as busy reclaiming rather than eligible ready inventory", async () => { - const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [ - { - createdAt: 500, - driverData: {}, - driverDeviceId: "driver_legacy", - id: "dev_legacy", - lastLeaseEndedAt: 900, - spec, - state: "warm", - }, - ], - leases: [], - }), - ); - - const registry = await Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "new" }, - statePath, - }); - - expect(registry.snapshot.devices).toMatchObject([{ id: "dev_legacy", state: "reclaiming" }]); - }); + it("a registry restarted on the same state.db returns every record as committed, optional fields set and absent", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock-registry-")); + try { + const clock = new FakeClock(1_000); + let next = 0; + const deviceData = new Map([ + ["android", fakeDeviceDataTable], + ["ios", fakeDeviceDataTable], + ]); + const openState = () => + openStateDatabase({ + dataDirectory: directory, + filesystem: new NodeFilesystem(), + logger: new NoopLogger(), + oldFiles: [], + owners: [registryOwner, fakeDeviceDataTable], + sqlite: new NodeSqliteOpener(), + upgradeStep: "remove it.", + }); + const first = await openState(); + const registry = await Registry.load({ + clock, + deviceData, + eventBus: new EventBus(clock), + idGenerator: { generate: () => String((next += 1)) }, + state: first, + }); + const timing = { + estimatedBootMs: 2, + estimatedProvisionMs: 1, + estimatedReadyMs: 4, + estimatedReclaimMs: 3, + }; + const register = (driverDeviceId: string, deviceSpec: VirtualSpec, fakeDeviceId: string) => + registry.registerDevice({ + driverData: { fakeDeviceId }, + driverDeviceId, + provisionDuration: 5, + spec: deviceSpec, + }); + const ready = (id: string, update?: DeviceTransitionUpdate) => + registry.transitionDevice( + id, + "ready", + { event: "device.ready", payload: { bootDuration: 7, deviceId: id } }, + update, + ); + + const plain = await register("drv-plain", spec, "fk-plain"); + const full = await register( + "drv-full", + { ...spec, imageTag: "default", mode: "slim" }, + "fk-full", + ); + await ready(full.id, { + address: "127.0.0.1:5554", + driverData: { fakeDeviceId: "fk-full-booted" }, + mode: "slim", + }); + clock.advance(10); + await registry.markForeignStateDetected(full.id, 1_011); + await registry.markForeignProvenanceDetected(full.id, 1_012); + await registry.markRecoveryAttempt(full.id, 1_013); + const stalled = await register("drv-stalled", spec, "fk-stalled"); + await registry.enterQuarantine(stalled.id, 9_000, { + kind: "stalled", + message: "stuck booting", + stalledState: "provisioning", + }); + const deferred = await register("drv-deferred", spec, "fk-deferred"); + await ready(deferred.id); + const deferredLease = await registry.createLease({ + deviceId: deferred.id, + ownerId: "agent-2", + requesterId: "agent-2", + ttlDeadline: 5_000, + ttlMs: 4_000, + }); + clock.advance(10); + await registry.beginRelease(deferredLease.id, { deferReclaim: true }); + + const apps = ["com.b", "com.a", "com.c"]; + const physicalInput = { + apps, + class: "tablet", + driverDeviceId: "udid-1", + model: "iPad", + osVersion: "26.5", + platform: "ios", + } as const; + const physical = await registry.enrollPhysical(physicalInput); + const absent = await registry.enrollPhysical({ ...physicalInput, driverDeviceId: "udid-2" }); + await registry.transitionDevice( + absent.id, + "absent", + { + event: "device.absence-detected", + payload: { absentReason: "locked", deviceId: absent.id, previousState: "ready" }, + }, + { absentReason: "locked" }, + ); + const returning = await registry.enrollPhysical({ + ...physicalInput, + apps: [], + driverDeviceId: "udid-3", + }); + const returningLease = await registry.createLease({ + deviceId: returning.id, + ownerId: "agent-3", + requesterId: "agent-3", + ttlDeadline: 5_000, + ttlMs: 4_000, + }); + await registry.beginRelease(returningLease.id); - it("loads a registry written before leaseIdentity existed with every device reusable", async () => { - const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - const legacy = (id: string, platform: "ios" | "android", state: string) => ({ - physical: false, - createdAt: 500, - driverData: {}, - driverDeviceId: `driver_${id}`, - id, - lastLeaseEndedAt: 900, - spec: { ...spec, platform }, - state, - }); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [legacy("dev_ios", "ios", "shutdown"), legacy("dev_android", "android", "ready")], - leases: [], - }), - ); + await registry.createLeaseRequest({ + ownerId: "agent-0", + request: { platform: "ios" }, + requesterId: "agent-0", + }); + await registry.createLeaseRequest({ + fleetRequestId: "fleet-1", + id: "req_full", + idempotencyKey: "key-1", + leaseId: "lse_chosen", + ownerId: "agent-1", + request: { + class: "phone", + imageTag: "default", + mode: "slim", + model: "iPhone 16", + osVersion: "26.5", + physical: true, + platform: "ios", + }, + requesterId: "requester-1", + }); + await registry.createLeaseRequest({ + id: "req_granted", + ownerId: "agent-1", + request: { platform: "ios" }, + requesterId: "agent-1", + }); + const lease = await registry.createLease({ + deviceId: full.id, + leaseId: "lse_chosen", + ownerId: "agent-1", + request: { environment: { SIMLOCK_UDID: "abc", OTHER: "x" }, id: "req_granted", timing }, + requesterId: "requester-1", + ttlDeadline: 2_000, + ttlMs: 60_000, + }); + await registry.createLeaseRequest({ + id: "req_failed", + ownerId: "agent-1", + request: { platform: "android" }, + requesterId: "agent-1", + }); + await registry.settleLeaseRequest("req_failed", { + failure: { code: "no-capacity", message: "no room" }, + state: "failed", + }); + await registry.createLeaseRequest({ + id: "req_cancelled", + ownerId: "agent-1", + request: { platform: "android" }, + requesterId: "agent-1", + }); + await registry.settleLeaseRequest("req_cancelled", { state: "cancelled" }); + await registry.recordComponent({ + installedAt: 1_005, + platform: "ios", + receipt: { image: "IMG", stamp: "s1" }, + version: "26.5", + }); + await registry.recordComponent({ + installedAt: 1_006, + platform: "android", + receipt: {}, + version: "35", + }); + first.close(); - // Loaded under a config that says `fresh`: a record's policy comes from the record, and a - // record with none was created under the only policy there was. - const registry = await Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "new" }, - leaseIdentity: { android: "fresh", ios: "fresh" }, - statePath, - }); + const second = await openState(); + const reloaded = await Registry.load({ + clock, + deviceData, + eventBus: new EventBus(clock), + idGenerator: { generate: () => "unused" }, + state: second, + }); - expect(registry.snapshot.devices.map((device) => device.leaseIdentity)).toEqual([ - "reusable", - "reusable", - ]); + expect(reloaded.snapshot).toEqual(registry.snapshot); + expect(reloaded.leaseRequests()).toEqual(registry.leaseRequests()); + expect(reloaded.snapshot.devices.find((device) => device.id === plain.id)).toEqual({ + createdAt: 1_000, + driverData: { fakeDeviceId: "fk-plain" }, + driverDeviceId: "drv-plain", + id: plain.id, + leaseIdentity: "reusable", + mode: "full", + physical: false, + spec, + state: "provisioning", + }); + expect(reloaded.snapshot.devices.find((device) => device.id === full.id)).toEqual({ + address: "127.0.0.1:5554", + createdAt: 1_000, + driverData: { fakeDeviceId: "fk-full-booted" }, + driverDeviceId: "drv-full", + foreignProvenanceDetectedAt: 1_012, + foreignStateDetectedAt: 1_011, + id: full.id, + leaseIdentity: "reusable", + mode: "slim", + physical: false, + readyAt: 1_000, + recoveringSince: 1_013, + recoveryAttempts: 1, + spec: { ...spec, imageTag: "default", mode: "slim" }, + state: "leased", + }); + expect(reloaded.snapshot.devices.find((device) => device.id === physical.id)).toMatchObject({ + enrolledApps: apps, + physical: true, + spec: { class: "tablet", physical: true }, + }); + expect(reloaded.snapshot.leases).toContainEqual(lease); + expect(reloaded.leaseRequests().find((request) => request.id === "req_full")).toEqual({ + createdAt: 1_020, + fleetRequestId: "fleet-1", + id: "req_full", + idempotencyKey: "key-1", + leaseId: "lse_chosen", + ownerId: "agent-1", + request: { + class: "phone", + imageTag: "default", + mode: "slim", + model: "iPhone 16", + osVersion: "26.5", + physical: true, + platform: "ios", + }, + requesterId: "requester-1", + state: "open", + }); + expect(reloaded.snapshot.components).toEqual([ + { + installedAt: 1_005, + platform: "ios", + receipt: { image: "IMG", stamp: "s1" }, + version: "26.5", + }, + { installedAt: 1_006, platform: "android", receipt: {}, version: "35" }, + ]); + second.close(); + } finally { + await rm(directory, { force: true, recursive: true }); + } }); - it("refuses to load a device record whose leaseIdentity is not a known policy", async () => { - const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [ - { - createdAt: 500, - driverData: {}, - driverDeviceId: "driver_odd", - id: "dev_odd", - leaseIdentity: "disposable", - spec, - state: "ready", - }, - ], - leases: [], - }), + it("refuses to load a device row whose lease_identity is not a known policy", async () => { + await expect(loadAfterCorruptingDevice("lease_identity = 'disposable'")).rejects.toThrow( + RegistryLoadError, ); - - await expect( - Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "new" }, - statePath, - }), - ).rejects.toThrow("Invalid device record"); }); it("stamps each registered device with its own platform's policy and keeps it across a reload under another", async () => { const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); + const state = await openTestState(); let nextId = 1; const idGenerator = { generate: () => `${nextId++}` }; - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem, idGenerator, leaseIdentity: { android: "reusable", ios: "fresh" }, - statePath, + state, }); const ios = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_ios", provisionDuration: 0, spec, }); const android = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_android", provisionDuration: 0, spec: { physical: false, model: "Pixel 9", osVersion: "36", platform: "android" }, @@ -351,13 +469,12 @@ describe("Registry", () => { expect([ios.leaseIdentity, android.leaseIdentity]).toEqual(["fresh", "reusable"]); - const reloaded = await Registry.load({ + const reloaded = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem, idGenerator, leaseIdentity: { android: "fresh", ios: "reusable" }, - statePath, + state, }); expect(reloaded.snapshot.devices.map((device) => device.leaseIdentity)).toEqual([ "fresh", @@ -365,77 +482,33 @@ describe("Registry", () => { ]); }); - it("preserves unknown persisted fields when saving a later mutation", async () => { - const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [ - { - createdAt: 500, - driverData: { driverOnly: "existing" }, - driverDeviceId: "driver_existing", - futureDeviceField: "keep me", - id: "dev_existing", - spec, - state: "provisioning", - }, - ], - futureTopLevelField: { version: 2 }, - leases: [], - }), - ); - const registry = await Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "new" }, - statePath, - }); - - await registry.registerDevice({ - driverData: {}, - driverDeviceId: "driver_new", - provisionDuration: 0, - spec, - }); - - const saved = JSON.parse(await filesystem.readFile(statePath)) as { - readonly devices: Array>; - readonly futureTopLevelField: unknown; - }; - expect(saved.futureTopLevelField).toEqual({ version: 2 }); - expect(saved.devices[0]).toMatchObject({ futureDeviceField: "keep me" }); - }); - it("persists a transition before emitting its device.ready fact", async () => { const clock = new FakeClock(1_000); - const filesystem = new ObservingFilesystem(); + const state = await openTestState(); const bus = new EventBus(clock); - bus.subscribe("device.ready", () => filesystem.operations.push("event")); - const registry = await Registry.load({ + const storedAtEvent: unknown[] = []; + bus.subscribe("device.ready", () => + storedAtEvent.push(state.database.prepare("SELECT state FROM devices").all()), + ); + const registry = await loadTestRegistry({ clock, eventBus: bus, - filesystem, idGenerator: { generate: () => "test" }, - statePath, + state, }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_test", provisionDuration: 0, spec, }); - filesystem.operations.length = 0; await registry.transitionDevice(device.id, "ready", { event: "device.ready", payload: { bootDuration: 50, deviceId: device.id }, }); - expect(filesystem.operations).toEqual(["save", "event"]); + expect(storedAtEvent).toEqual([[{ state: "ready" }]]); expect(registry.snapshot.devices[0]?.state).toBe("ready"); }); @@ -450,15 +523,13 @@ describe("Registry", () => { async (platform, deviceSpec) => { const clock = new FakeClock(1_000); const bus = new EventBus(clock); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: bus, - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => "test" }, - statePath, }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_test", provisionDuration: 0, spec: deviceSpec, @@ -479,15 +550,13 @@ describe("Registry", () => { it("rejects a device event whose payload identifies another device", async () => { const clock = new FakeClock(); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => "test" }, - statePath, }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_test", provisionDuration: 0, spec, @@ -504,18 +573,17 @@ describe("Registry", () => { it("round-trips leases and never deletes a device with an active lease", async () => { const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); const suffixes = ["device", "lease"]; + const state = await openTestState(); const options = { clock, eventBus: new EventBus(clock), - filesystem, idGenerator: { generate: () => suffixes.shift() ?? "unexpected" }, - statePath, + state, }; - const registry = await Registry.load(options); + const registry = await loadTestRegistry(options); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_device", provisionDuration: 0, spec, @@ -532,7 +600,7 @@ describe("Registry", () => { ttlMs: 60_000, ttlDeadline: 2_000, }); - const reloaded = await Registry.load(options); + const reloaded = await loadTestRegistry(options); expect(lease).toMatchObject({ deviceId: device.id, id: "lse_lease", grantedAt: 1_000 }); expect(reloaded.snapshot).toEqual(registry.snapshot); @@ -552,18 +620,17 @@ describe("Registry", () => { it("reloads a lease written for a request with the request granted, holding the leased device, environment, lease and timing it was written with", async () => { const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); const suffixes = ["device", "lease"]; + const state = await openTestState(); const options = { clock, eventBus: new EventBus(clock), - filesystem, idGenerator: { generate: () => suffixes.shift() ?? "unexpected" }, - statePath, + state, }; - const registry = await Registry.load(options); + const registry = await loadTestRegistry(options); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_device", provisionDuration: 0, spec, @@ -593,7 +660,7 @@ describe("Registry", () => { ttlDeadline: 2_000, ttlMs: 60_000, }); - const reloaded = await Registry.load(options); + const reloaded = await loadTestRegistry(options); expect(reloaded.snapshot.leases).toEqual([lease]); expect(reloaded.leaseRequests()).toMatchObject([ @@ -614,15 +681,13 @@ describe("Registry", () => { it("leaves a request already settled as it was when a lease is written for it", async () => { const clock = new FakeClock(1_000); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => "x" }, - statePath, }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_device", provisionDuration: 0, spec, @@ -668,15 +733,13 @@ describe("Registry", () => { it("enters quarantine from reclaiming, tracking attempts and the next retry deadline", async () => { const clock = new FakeClock(1_000); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => "test" }, - statePath, }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_test", provisionDuration: 0, spec, @@ -709,15 +772,13 @@ describe("Registry", () => { it("enters quarantine from provisioning, its stalled-transition entry point", async () => { const clock = new FakeClock(1_000); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => "test" }, - statePath, }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_test", provisionDuration: 0, spec, @@ -735,16 +796,14 @@ describe("Registry", () => { it("enters quarantine from shutdown, a spent fresh device's failed-delete entry point", async () => { const clock = new FakeClock(1_000); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => "test" }, leaseIdentity: { android: "reusable", ios: "fresh" }, - statePath, }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_test", provisionDuration: 0, spec, @@ -776,15 +835,13 @@ describe("Registry", () => { // a device reaches by having its lease released. A leased device reaching it would mean // pulling a device out from under its holder -- the one thing safety rule 2 forbids outright. const clock = new FakeClock(1_000); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => "test" }, - statePath, }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_test", provisionDuration: 0, spec, @@ -809,15 +866,13 @@ describe("Registry", () => { it("records a quarantine retry failure without leaving quarantined", async () => { const clock = new FakeClock(1_000); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => "test" }, - statePath, }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_test", provisionDuration: 0, spec, @@ -850,15 +905,13 @@ describe("Registry", () => { it("recovers a quarantined device and clears its quarantine bookkeeping", async () => { const clock = new FakeClock(1_000); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => "test" }, - statePath, }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_test", provisionDuration: 0, spec, @@ -882,7 +935,7 @@ describe("Registry", () => { expect(recovered).toEqual({ physical: false, createdAt: 1_000, - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_test", id: device.id, lastLeaseEndedAt: 1_000, @@ -902,15 +955,13 @@ describe("Registry", () => { const bus = new EventBus(clock); const events: unknown[] = []; bus.subscribe("device.deleted", (envelope) => events.push(envelope.payload)); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: bus, - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => "test" }, - statePath, }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_test", provisionDuration: 0, spec, @@ -937,12 +988,10 @@ describe("Registry", () => { it("rejects mutations for a device that is not registered", async () => { const clock = new FakeClock(); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => "test" }, - statePath, }); await expect(registry.transitionDevice("dev_missing", "ready")).rejects.toThrow( @@ -958,15 +1007,13 @@ describe("Registry", () => { it("records the first recovery attempt's start time and count", async () => { const clock = new FakeClock(1_000); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => "test" }, - statePath, }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_test", provisionDuration: 0, spec, @@ -979,15 +1026,13 @@ describe("Registry", () => { it("keeps the original recoveringSince and increments the attempt count on retry", async () => { const clock = new FakeClock(1_000); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => "test" }, - statePath, }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_test", provisionDuration: 0, spec, @@ -1001,15 +1046,13 @@ describe("Registry", () => { it("clears both recovery markers", async () => { const clock = new FakeClock(1_000); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => "test" }, - statePath, }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_test", provisionDuration: 0, spec, @@ -1022,344 +1065,75 @@ describe("Registry", () => { expect(cleared.recoveryAttempts).toBeUndefined(); }); - it("survives a save/reload round-trip with recovery markers set", async () => { + it("persists readyAt and shutdownAt across a reload", async () => { const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); + const state = await openTestState(); const options = { clock, eventBus: new EventBus(clock), - filesystem, idGenerator: { generate: () => "test" }, - statePath, + state, }; - const registry = await Registry.load(options); + const registry = await loadTestRegistry(options); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_test", provisionDuration: 0, spec, }); - await registry.markRecoveryAttempt(device.id, 1_500); - - const reloaded = await Registry.load(options); - - expect(reloaded.snapshot).toEqual(registry.snapshot); - expect(reloaded.snapshot.devices[0]).toMatchObject({ - recoveringSince: 1_500, - recoveryAttempts: 1, + await registry.transitionDevice(device.id, "ready", { + event: "device.ready", + payload: { bootDuration: 5, deviceId: device.id }, }); - }); - it("rejects non-numeric recovery markers when loading persisted state", async () => { - const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [ - { - createdAt: 500, - driverData: {}, - driverDeviceId: "driver_bad", - id: "dev_bad", - recoveringSince: "not-a-number", - spec, - state: "leased", - }, - ], - leases: [], - }), - ); + clock.advance(5_000); + await registry.transitionDevice(device.id, "shutdown", { + event: "device.shutdown", + payload: { deviceId: device.id, initiator: "test" }, + }); + const reloaded = await loadTestRegistry(options); - await expect( - Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "new" }, - statePath, - }), - ).rejects.toThrow("Invalid device record in registry state"); + expect(reloaded.snapshot.devices[0]?.readyAt).toBe(1_000); + expect(reloaded.snapshot.devices[0]?.shutdownAt).toBe(6_000); }); - it("survives a save/reload round-trip with mode set to slim", async () => { + it("registers a new device as full", async () => { const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - const options = { + const registry = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem, idGenerator: { generate: () => "test" }, - statePath, - }; - const registry = await Registry.load(options); + }); + const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_test", provisionDuration: 0, spec, }); - await registry.transitionDevice( - device.id, - "ready", - { event: "device.ready", payload: { bootDuration: 5, deviceId: device.id } }, - { mode: "slim" }, - ); - - const reloaded = await Registry.load(options); - expect(reloaded.snapshot).toEqual(registry.snapshot); - expect(reloaded.snapshot.devices[0]).toMatchObject({ mode: "slim" }); + expect(device.mode).toBe("full"); }); - it("persists readyAt across a reload, and loads a record written before it without one", async () => { + it.each(["mode", "spec_mode"])( + "fails the load when a stored %s is neither slim nor full", + async (column) => { + await expect(loadAfterCorruptingDevice(`${column} = 'reduced'`)).rejects.toThrow( + RegistryLoadError, + ); + }, + ); + + it("records the planned mode of a slim spec on the device it registers", async () => { const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - const options = { + const registry = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem, idGenerator: { generate: () => "test" }, - statePath, - }; - const registry = await Registry.load(options); + }); + const device = await registry.registerDevice({ - driverData: {}, - driverDeviceId: "driver_test", - provisionDuration: 0, - spec, - }); - await registry.transitionDevice(device.id, "ready", { - event: "device.ready", - payload: { bootDuration: 5, deviceId: device.id }, - }); - - clock.advance(5_000); - await registry.transitionDevice(device.id, "shutdown", { - event: "device.shutdown", - payload: { deviceId: device.id, initiator: "test" }, - }); - const reloaded = await Registry.load(options); - - // Stamped on the move into `ready`, and left alone by a later move out of it. - expect(reloaded.snapshot.devices[0]?.readyAt).toBe(1_000); - expect(reloaded.snapshot.devices[0]?.shutdownAt).toBe(6_000); - const state = JSON.parse(await filesystem.readFile(statePath)) as { - devices: Record[]; - }; - const [written] = state.devices; - if (written === undefined) throw new Error("expected a written device"); - const { readyAt: _dropped, shutdownAt: _also, ...older } = written; - await filesystem.writeFileAtomic(statePath, JSON.stringify({ ...state, devices: [older] })); - const legacy = await Registry.load(options); - expect(legacy.snapshot.devices[0]).not.toHaveProperty("readyAt"); - expect(legacy.snapshot.devices[0]).not.toHaveProperty("shutdownAt"); - }); - - it("registers a new device as full", async () => { - const clock = new FakeClock(1_000); - const registry = await Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem: new MemoryFilesystem(), - idGenerator: { generate: () => "test" }, - statePath, - }); - - const device = await registry.registerDevice({ - driverData: {}, - driverDeviceId: "driver_test", - provisionDuration: 0, - spec, - }); - - expect(device.mode).toBe("full"); - }); - - // ADR 0007 §11: no mode is derived from the old key, whatever it said, and the old key is not - // carried forward as an unknown field either. - it.each([ - ["no featureProfile", {}], - ['featureProfile "reduced"', { featureProfile: "reduced" }], - ['featureProfile "full"', { featureProfile: "full" }], - ])( - "loads a record written before mode existed as full (%s) and does not write featureProfile back", - async (_label, legacyFields) => { - const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [ - { - createdAt: 500, - driverData: {}, - driverDeviceId: "driver_legacy", - id: "dev_legacy", - spec, - state: "ready", - ...legacyFields, - }, - ], - leases: [], - }), - ); - const registry = await Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "new" }, - statePath, - }); - - expect(registry.snapshot.devices[0]?.mode).toBe("full"); - - // Any commit rewrites the whole file, legacy record included. - await registry.registerDevice({ - driverData: {}, - driverDeviceId: "driver_new", - provisionDuration: 0, - spec, - }); - const written = JSON.parse(await filesystem.readFile(statePath)) as { - devices: Record[]; - }; - const legacy = written.devices.find((device) => device.id === "dev_legacy"); - expect(legacy).toMatchObject({ mode: "full" }); - expect(legacy).not.toHaveProperty("featureProfile"); - }, - ); - - it("fails the load when a stored mode is neither slim nor full", async () => { - const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [ - { - createdAt: 500, - driverData: {}, - driverDeviceId: "driver_garbage", - id: "dev_garbage", - mode: "reduced", - spec, - state: "ready", - }, - ], - leases: [], - }), - ); - - await expect( - Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "new" }, - statePath, - }), - ).rejects.toThrow("Invalid device record in registry state"); - }); - - describe("a stored spec's mode", () => { - async function loadDevice(storedSpec: Record) { - const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [ - { - createdAt: 500, - driverData: {}, - driverDeviceId: "driver_stored", - id: "dev_stored", - mode: "full", - spec: storedSpec, - state: "ready", - }, - ], - leases: [], - }), - ); - const load = () => - Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "new" }, - statePath, - }); - return { filesystem, load }; - } - - it.each([true, false])( - "ignores a stored spec.full of %s and does not write it back", - async (full) => { - const { filesystem, load } = await loadDevice({ ...spec, full }); - const registry = await load(); - - expect(registry.snapshot.devices[0]?.spec).toEqual(spec); - - await registry.registerDevice({ - driverData: {}, - driverDeviceId: "driver_new", - provisionDuration: 0, - spec, - }); - const written = JSON.parse(await filesystem.readFile(statePath)) as { - devices: { id: string; spec: Record }[]; - }; - const { physical: _physical, ...stored } = spec; - expect(written.devices.find((device) => device.id === "dev_stored")?.spec).toEqual(stored); - }, - ); - - it("loads a stored slim spec as slim", async () => { - const { load } = await loadDevice({ ...spec, mode: "slim" }); - - expect((await load()).snapshot.devices[0]?.spec).toEqual({ ...spec, mode: "slim" }); - }); - - it("loads a stored spec's image tag", async () => { - const { load } = await loadDevice({ ...spec, imageTag: "google_apis_playstore" }); - - expect((await load()).snapshot.devices[0]?.spec).toEqual({ - ...spec, - imageTag: "google_apis_playstore", - }); - }); - - it("fails the load on a stored spec.imageTag that is not a string", async () => { - const { load } = await loadDevice({ ...spec, imageTag: 7 }); - - await expect(load()).rejects.toThrow("Invalid device record in registry state"); - }); - - it.each(["full", "reduced"])("fails the load on a stored spec.mode of %s", async (mode) => { - const { load } = await loadDevice({ ...spec, mode }); - - await expect(load()).rejects.toThrow("Invalid device record in registry state"); - }); - }); - - it("records the planned mode of a slim spec on the device it registers", async () => { - const clock = new FakeClock(1_000); - const registry = await Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem: new MemoryFilesystem(), - idGenerator: { generate: () => "test" }, - statePath, - }); - - const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_test", provisionDuration: 0, spec: { ...spec, mode: "slim" }, @@ -1372,15 +1146,13 @@ describe("Registry", () => { it("clears recovery markers as part of the same commit that ends a lease", async () => { const clock = new FakeClock(1_000); const suffixes = ["device", "lease"]; - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => suffixes.shift() ?? "unexpected" }, - statePath, }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_device", provisionDuration: 0, spec, @@ -1408,16 +1180,16 @@ describe("Registry", () => { describe("a reclaim put off at a daemon start", () => { async function leased() { const clock = new FakeClock(1_000); + const state = await openTestState(); const options = { clock, eventBus: new EventBus(clock), - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => "test" }, - statePath, + state, }; - const registry = await Registry.load(options); + const registry = await loadTestRegistry(options); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_test", provisionDuration: 0, spec, @@ -1445,7 +1217,7 @@ describe("Registry", () => { deferredReclaimLeaseId: lease.id, state: "reclaiming", }); - expect((await Registry.load(options)).snapshot.devices[0]).toMatchObject({ + expect((await loadTestRegistry(options)).snapshot.devices[0]).toMatchObject({ deferredReclaimLeaseId: lease.id, }); }); @@ -1477,86 +1249,18 @@ describe("Registry", () => { expect(registry.snapshot.devices[0]).toMatchObject({ state: "deleted" }); expect(registry.snapshot.devices[0]).not.toHaveProperty("deferredReclaimLeaseId"); }); - - it("rejects a non-string name when loading persisted state", async () => { - const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [ - { - createdAt: 500, - deferredReclaimLeaseId: 7, - driverData: {}, - driverDeviceId: "driver_bad", - id: "dev_bad", - spec, - state: "reclaiming", - }, - ], - leases: [], - }), - ); - - await expect( - Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "new" }, - statePath, - }), - ).rejects.toThrow("Invalid device record in registry state"); - }); - - it("rejects a non-string address when loading persisted state", async () => { - const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [ - { - createdAt: 500, - address: 7, - driverData: {}, - driverDeviceId: "driver_bad", - id: "dev_bad", - spec, - state: "reclaiming", - }, - ], - leases: [], - }), - ); - - await expect( - Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "new" }, - statePath, - }), - ).rejects.toThrow("Invalid device record in registry state"); - }); }); it("writes a device the same way whether it is marked missing alone or together with its lease's end", async () => { const marked = async (viaLease: boolean) => { const clock = new FakeClock(1_000); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => "test" }, - statePath, }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_test", provisionDuration: 0, spec, @@ -1588,7 +1292,7 @@ describe("Registry", () => { expect(viaLease).toEqual({ physical: false, createdAt: 1_000, - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_test", id: "dev_test", leaseIdentity: "reusable", @@ -1599,270 +1303,18 @@ describe("Registry", () => { }); }); - it("loads a lease record written before ownerId existed with ownerId defaulted to requesterId (ADR 0003 §4)", async () => { - const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [ - { - id: "dev_1", - driverDeviceId: "driver_device", - spec, - state: "leased", - driverData: {}, - createdAt: 1_000, - }, - ], - leases: [ - { - id: "lse_1", - deviceId: "dev_1", - requesterId: "agent-1", - grantedAt: 1_000, - lastRenewedAt: 1_000, - ttlMs: 60_000, - ttlDeadline: 2_000, - // No `ownerId` -- exactly what a pre-ADR-0003 daemon wrote. - }, - ], - }), - ); - - const registry = await Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "unexpected" }, - statePath, - }); - - expect(registry.snapshot.leases).toEqual([ - { - id: "lse_1", - deviceId: "dev_1", - requesterId: "agent-1", - ownerId: "agent-1", - grantedAt: 1_000, - lastRenewedAt: 1_000, - idChosenByRequester: false, - ttlMs: 60_000, - ttlDeadline: 2_000, - }, - ]); - - // The migrated default round-trips through a further save/reload unchanged, and the - // written file now carries `ownerId` explicitly (it is no longer an "unknown field" - // preserved verbatim -- see `#unknownLeaseFields` -- but the registry's own understanding - // of the record). - await registry.renewLease("lse_1", 3_000, 60_000); - const reloaded = await Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "unexpected" }, - statePath, - }); - expect(reloaded.snapshot.leases).toEqual(registry.snapshot.leases); - expect(reloaded.snapshot.leases[0]?.ownerId).toBe("agent-1"); - }); - - it("a state file without idChosenByRequester loads every lease as false", async () => { - const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - const lease = (id: string, deviceId: string) => ({ - deviceId, - grantedAt: 1_000, - id, - lastRenewedAt: 1_000, - ownerId: "agent-1", - requesterId: "agent-1", - ttlDeadline: 2_000, - ttlMs: 60_000, - }); - const device = (id: string) => ({ - physical: false, - createdAt: 1_000, - driverData: {}, - driverDeviceId: `driver_${id}`, - id, - spec, - state: "leased", - }); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [device("dev_1"), device("dev_2")], - leases: [lease("lse_1", "dev_1"), lease("ad-7f3a", "dev_2")], - }), - ); - - const registry = await Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "unexpected" }, - statePath, - }); - - expect(registry.snapshot.leases.map((loaded) => [loaded.id, loaded])).toEqual([ - ["lse_1", expect.objectContaining({ idChosenByRequester: false })], - ["ad-7f3a", expect.objectContaining({ idChosenByRequester: false })], - ]); - }); - - it("keeps the leaseId a request stored across a reload, and loads a record without one as having none", async () => { - const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - const options = { - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "unexpected" }, - statePath, - }; - const registry = await Registry.load(options); - await registry.createLeaseRequest({ - id: "req_1", - ownerId: "agent-1", - request: { platform: "ios" }, - requesterId: "agent-1", - leaseId: "ad-7f3a", - }); - await registry.createLeaseRequest({ - id: "req_2", - ownerId: "agent-2", - request: { platform: "ios" }, - requesterId: "agent-2", - }); - - const reloaded = await Registry.load(options); - - expect(reloaded.leaseRequests()).toMatchObject([ - { id: "req_1", leaseId: "ad-7f3a" }, - { id: "req_2" }, - ]); - expect(reloaded.leaseRequests()[1]).not.toHaveProperty("leaseId"); - }); - - it("keeps the fleetRequestId a request stored across a reload, and loads a record without one as having none", async () => { - const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - const options = { - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "unexpected" }, - statePath, - }; - const registry = await Registry.load(options); - await registry.createLeaseRequest({ - fleetRequestId: "req_gw1", - id: "req_1", - ownerId: "agent-1", - request: { platform: "ios" }, - requesterId: "agent-1", - }); - await registry.createLeaseRequest({ - id: "req_2", - ownerId: "agent-2", - request: { platform: "ios" }, - requesterId: "agent-2", - }); - - const reloaded = await Registry.load(options); - - expect(reloaded.leaseRequests()).toMatchObject([ - { fleetRequestId: "req_gw1", id: "req_1" }, - { id: "req_2" }, - ]); - expect(reloaded.leaseRequests()[1]).not.toHaveProperty("fleetRequestId"); - }); - - it("drops a stored lease request whose fleetRequestId is not a string and keeps the others", async () => { - const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - const open = (id: string, extra: Record) => ({ - createdAt: 1_000, - id, - ownerId: "agent-1", - request: { platform: "ios" }, - requesterId: "agent-1", - state: "open", - ...extra, - }); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [], - leaseRequests: [ - open("req_bad", { fleetRequestId: 7 }), - open("req_ok", { fleetRequestId: "req_gw1" }), - ], - leases: [], - }), - ); - - const registry = await Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "unexpected" }, - statePath, - }); - - expect(registry.leaseRequests().map((record) => record.id)).toEqual(["req_ok"]); - }); - - it("drops a stored lease request whose leaseId is not a string and keeps the others", async () => { - const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - const open = (id: string, extra: Record) => ({ - createdAt: 1_000, - id, - ownerId: "agent-1", - request: { platform: "ios" }, - requesterId: "agent-1", - state: "open", - ...extra, - }); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [], - leaseRequests: [open("req_bad", { leaseId: 7 }), open("req_ok", { leaseId: "ad-7f3a" })], - leases: [], - }), - ); - - const registry = await Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "unexpected" }, - statePath, - }); - - expect(registry.leaseRequests().map((record) => record.id)).toEqual(["req_ok"]); - }); - it("keeps idChosenByRequester true on the lease of a stored grant across a reload", async () => { const clock = new FakeClock(1_000); + const state = await openTestState(); const options = { clock, eventBus: new EventBus(clock), - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => "x" }, - statePath, + state, }; - const registry = await Registry.load(options); + const registry = await loadTestRegistry(options); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_device", provisionDuration: 0, spec, @@ -1897,7 +1349,7 @@ describe("Registry", () => { ttlMs: 60_000, }); - const reloaded = await Registry.load(options); + const reloaded = await loadTestRegistry(options); expect(reloaded.leaseRequests()[0]?.grant?.lease).toMatchObject({ id: "ad-7f3a", @@ -1905,78 +1357,20 @@ describe("Registry", () => { }); }); - it("loads the lease of a stored grant written before idChosenByRequester as one simlock named", async () => { + it("writes idChosenByRequester true for a lease created with a leaseId, false without one, and keeps both across a reload", async () => { const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - const lease = { - deviceId: "dev_1", - grantedAt: 1_000, - id: "lse_1", - lastRenewedAt: 1_000, - ownerId: "agent-1", - requesterId: "agent-1", - ttlDeadline: 2_000, - ttlMs: 60_000, - }; - const device = { - physical: false, - createdAt: 1_000, - driverData: {}, - driverDeviceId: "driver_dev_1", - id: "dev_1", - spec, - state: "leased", - }; - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [device], - leaseRequests: [ - { - createdAt: 1_000, - grant: { device, environment: {}, lease, timing: {} }, - id: "req_1", - ownerId: "agent-1", - request: { platform: "ios" }, - requesterId: "agent-1", - settledAt: 1_000, - state: "granted", - }, - ], - leases: [lease], - }), - ); - - const registry = await Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "unexpected" }, - statePath, - }); - - expect(registry.leaseRequests()[0]?.grant?.lease).toMatchObject({ - id: "lse_1", - idChosenByRequester: false, - }); - }); - - it("writes idChosenByRequester true for a lease created with a leaseId, false without one, and keeps both across a reload", async () => { - const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); let next = 0; + const state = await openTestState(); const options = { clock, eventBus: new EventBus(clock), - filesystem, idGenerator: { generate: () => String((next += 1)) }, - statePath, + state, }; - const registry = await Registry.load(options); + const registry = await loadTestRegistry(options); const ready = async (driverDeviceId: string) => { const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId, provisionDuration: 0, spec, @@ -2001,242 +1395,24 @@ describe("Registry", () => { id: expect.stringMatching(/^lse_/), idChosenByRequester: false, }); - const reloaded = await Registry.load(options); + const reloaded = await loadTestRegistry(options); expect(reloaded.snapshot.leases).toEqual([chosen, generated]); }); - it("migrates a lease record written before ADR 0004's ttlMs/lastRenewedAt, dropping mode", async () => { - const filesystem = new MemoryFilesystem(); - const clock = new FakeClock(5_000); - await filesystem.mkdirp("/home/agent/.simlock"); - // Exactly what a pre-ADR-0004 daemon persisted: a `mode`, and neither of the two fields a - // record carries now. Neither is recoverable from what is on disk -- `ttlDeadline - - // grantedAt` is the grant-time width only until the first renewal moved the deadline -- so - // each takes its documented default rather than a guess dressed up as arithmetic. - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [ - { - createdAt: 0, - driverData: {}, - driverDeviceId: "driver_1", - id: "dev_1", - spec: { model: "iPhone 16", osVersion: "26.5", platform: "ios" }, - state: "leased", - }, - ], - leases: [ - { - deviceId: "dev_1", - grantedAt: 1_000, - id: "lse_1", - mode: "held", - ownerId: "agent-1", - requesterId: "agent-1", - ttlDeadline: 2_000, - }, - ], - }), - ); - - const registry = await Registry.load({ - clock, - defaultTtlMs: 900_000, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "unexpected" }, - statePath, - }); - - expect(registry.snapshot.leases).toEqual([ - { - id: "lse_1", - deviceId: "dev_1", - requesterId: "agent-1", - ownerId: "agent-1", - grantedAt: 1_000, - // `lease.defaultTtlMs`, which the daemon passes in from its own config. - ttlMs: 900_000, - ttlDeadline: 2_000, - // A lease that has never been renewed reports the moment it was granted. - lastRenewedAt: 1_000, - idChosenByRequester: false, - }, - ]); - - // `mode` is a retired concept, not a field from a newer schema, so the next write drops it - // rather than preserving it through the unknown-field forward-compatibility path. - await registry.renewLease("lse_1", 9_000, 7_000); - const written = JSON.parse(await filesystem.readFile(statePath)) as { - leases: Record[]; - }; - expect(written.leases[0]).toEqual({ - deviceId: "dev_1", - grantedAt: 1_000, - id: "lse_1", - lastRenewedAt: 5_000, - idChosenByRequester: false, - ownerId: "agent-1", - requesterId: "agent-1", - ttlDeadline: 9_000, - ttlMs: 7_000, - }); - }); - - it.each([ - ["zero", 0], - ["negative", -1], - ["not a number", "soon"], - ["not finite", Number.POSITIVE_INFINITY], - ])("falls back to the default width for a %s ttlMs on disk", async (_label, stored) => { - // A stored width has to be a positive, finite duration: `0` or a negative one would make - // every renewal of this lease resolve to a deadline in the past, which the expiry - // scheduler reads as "expire immediately". An unusable value takes the same default an - // absent one does -- refusing the whole registry over one field would cost the operator - // every device Simlock knows about. - const filesystem = new MemoryFilesystem(); - const clock = new FakeClock(5_000); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [ - { - createdAt: 0, - driverData: {}, - driverDeviceId: "driver_1", - id: "dev_1", - spec: { model: "iPhone 16", osVersion: "26.5", platform: "ios" }, - state: "leased", - }, - ], - leases: [ - { - deviceId: "dev_1", - grantedAt: 1_000, - id: "lse_1", - lastRenewedAt: 1_500, - ownerId: "agent-1", - requesterId: "agent-1", - ttlDeadline: 2_000, - ttlMs: stored, - }, - ], - }), - ); - - const registry = await Registry.load({ - clock, - defaultTtlMs: 900_000, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "unexpected" }, - statePath, - }); - - expect(registry.snapshot.leases).toMatchObject([{ id: "lse_1", ttlMs: 900_000 }]); - // A `lastRenewedAt` that is usable is kept as it is -- only the unusable field migrates. - expect(registry.snapshot.leases[0]?.lastRenewedAt).toBe(1_500); - }); - - it("falls back to grantedAt for an unusable lastRenewedAt on disk", async () => { - const filesystem = new MemoryFilesystem(); - const clock = new FakeClock(5_000); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [ - { - createdAt: 0, - driverData: {}, - driverDeviceId: "driver_1", - id: "dev_1", - spec: { model: "iPhone 16", osVersion: "26.5", platform: "ios" }, - state: "leased", - }, - ], - leases: [ - { - deviceId: "dev_1", - grantedAt: 1_000, - id: "lse_1", - lastRenewedAt: null, - ownerId: "agent-1", - requesterId: "agent-1", - ttlDeadline: 2_000, - ttlMs: 60_000, - }, - ], - }), - ); - - const registry = await Registry.load({ - clock, - defaultTtlMs: 900_000, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "unexpected" }, - statePath, - }); - - // Unlike a width, a timestamp of `0` is a legitimate answer, so only non-numbers and - // non-finite values migrate -- and the stored width is untouched. - expect(registry.snapshot.leases).toMatchObject([ - { id: "lse_1", lastRenewedAt: 1_000, ttlMs: 60_000 }, - ]); - }); - - it("rejects a lease record whose ownerId is present but not a string", async () => { - const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [], - leases: [ - { - id: "lse_1", - deviceId: "dev_1", - requesterId: "agent-1", - ownerId: 42, - grantedAt: 1_000, - lastRenewedAt: 1_000, - ttlMs: 60_000, - ttlDeadline: 2_000, - }, - ], - }), - ); - - await expect( - Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "unexpected" }, - statePath, - }), - ).rejects.toThrow(/Invalid lease record/); - }); - - it("removes a lease and marks its device deleted in one write, announcing the lease before device.deleted, both after the commit", async () => { + it("removes a lease and marks its device deleted in one commit, announcing the lease before device.deleted, both after the commit", async () => { const clock = new FakeClock(1_000); - const filesystem = new ObservingFilesystem(); const bus = new EventBus(clock); const suffixes = ["device", "lease"]; + const state = await openTestState(); const options = { clock, eventBus: bus, - filesystem, idGenerator: { generate: () => suffixes.shift() ?? "unexpected" }, - statePath, + state, }; - const registry = await Registry.load(options); + const registry = await loadTestRegistry(options); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_device", provisionDuration: 0, spec, @@ -2253,20 +1429,31 @@ describe("Registry", () => { ttlDeadline: 2_000, }); await registry.markRecoveryAttempt(device.id, 1_500); - bus.subscribe("device.deleted", () => filesystem.operations.push("device.deleted")); - filesystem.operations.length = 0; + const operations: string[] = []; + const stored = () => { + const row = state.database + .prepare( + "SELECT (SELECT COUNT(*) FROM leases) AS leases, (SELECT state FROM devices) AS device", + ) + .get(); + return `${String(row?.leases)} leases stored, device ${String(row?.device)}`; + }; + bus.subscribe("device.deleted", () => operations.push(`device.deleted: ${stored()}`)); const ended = await registry.endLeaseAndMarkDeviceMissing(lease.id, "doctor", () => - filesystem.operations.push("lease announced"), + operations.push(`lease announced: ${stored()}`), ); - expect(filesystem.operations).toEqual(["save", "lease announced", "device.deleted"]); + expect(operations).toEqual([ + "lease announced: 0 leases stored, device deleted", + "device.deleted: 0 leases stored, device deleted", + ]); expect(ended.lease).toEqual(lease); expect(ended.device).toMatchObject({ id: device.id, state: "deleted" }); expect(ended.device).not.toHaveProperty("recoveryAttempts"); expect(registry.snapshot.leases).toEqual([]); expect(registry.snapshot.devices).toEqual([ended.device]); - expect((await Registry.load(options)).snapshot).toEqual(registry.snapshot); + expect((await loadTestRegistry(options)).snapshot).toEqual(registry.snapshot); expect(bus.replay().filter((entry) => entry.event === "device.deleted")).toMatchObject([ { payload: { deviceId: device.id, initiator: "doctor" } }, ]); @@ -2276,17 +1463,15 @@ describe("Registry", () => { const clock = new FakeClock(1_000); const bus = new EventBus(clock); let next = 0; - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: bus, - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => String(next++) }, - statePath, }); const leases = []; for (const name of ["one", "two"]) { const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: `driver_${name}`, provisionDuration: 0, spec, @@ -2322,14 +1507,14 @@ describe("Registry", () => { it("refuses to end a lease it does not hold, writing nothing and announcing nothing", async () => { const clock = new FakeClock(1_000); - const filesystem = new ObservingFilesystem(); - const registry = await Registry.load({ + const state = await openTestState(); + const registry = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem, idGenerator: { generate: () => "test" }, - statePath, + state, }); + const changesBefore = totalChanges(state); let announced = false; await expect( @@ -2339,22 +1524,20 @@ describe("Registry", () => { ).rejects.toThrow(UnknownLeaseError); expect(announced).toBe(false); - expect(filesystem.operations).toEqual([]); + expect(totalChanges(state)).toBe(changesBefore); }); }); describe("Registry: the device event a transition carries", () => { async function provisioned() { const clock = new FakeClock(1_000); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => "x" }, - statePath, }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId: "driver_x", provisionDuration: 0, spec, @@ -2400,113 +1583,82 @@ describe("Registry: the device event a transition carries", () => { }); }); -describe("Registry: physical devices (ADR 0022 §1)", () => { - const virtualRecord = { - createdAt: 500, - driverData: {}, - driverDeviceId: "driver_virtual", - id: "dev_virtual", - mode: "full", - spec: { model: "iPhone 16", osVersion: "26.5", platform: "ios" }, - state: "ready", - }; - const physicalSpec = { - class: "phone", - model: "iPhone 15 Pro", - osVersion: "18.4", - physical: true, - platform: "ios", - }; - const physicalRecord = { - address: "00008110-001A2B3C4D5E", - createdAt: 600, - driverData: { note: "kept" }, - driverDeviceId: "00008110-001A2B3C4D5E", - enrolledApps: ["com.example.one", "com.example.two"], - id: "dev_physical", - physical: true, - spec: physicalSpec, - state: "ready", - }; - const lease = { - deviceId: "dev_physical", - grantedAt: 700, - id: "lse_physical", - idChosenByRequester: false, - lastRenewedAt: 700, - ownerId: "agent", - requesterId: "agent", - ttlDeadline: 90_000, - ttlMs: 60_000, - }; - - async function stateFile(state: Record) { - const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic(statePath, JSON.stringify({ leases: [], ...state })); - const load = () => - Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "new" }, - statePath, - }); - const written = async () => - JSON.parse(await filesystem.readFile(statePath)) as Record[]>; - return { filesystem, load, written }; - } - - const invalid = "Invalid device record in registry state"; +const physicalInput = { + apps: ["com.example.one", "com.example.two"], + class: "phone", + driverDeviceId: "00008110-001A2B3C4D5E" as string, + model: "iPhone 15 Pro", + osVersion: "18.4", + platform: "ios", +} as const; - it("loads a record in devices with no physical as virtual, on the record and its spec, and writes it back with no physical key on either", async () => { - const { load, written } = await stateFile({ devices: [virtualRecord] }); - const registry = await load(); +const physicalSpec = { + class: "phone", + model: "iPhone 15 Pro", + osVersion: "18.4", + physical: true, + platform: "ios", +}; - expect(registry.snapshot.devices[0]).toMatchObject({ - physical: false, - spec: { physical: false }, +// why: a device id is "dev_" plus the next name pushed to `names`, so a test picks its ids. +async function seededWorld() { + const clock = new FakeClock(1_000); + const bus = new EventBus(clock); + const state = await openTestState(); + const names: string[] = []; + const registry = await loadTestRegistry({ + clock, + eventBus: bus, + idGenerator: { generate: () => names.shift() ?? "unexpected" }, + state, + }); + const reload = () => + loadTestRegistry({ + clock, + eventBus: new EventBus(clock), + idGenerator: { generate: () => "unexpected" }, + state, }); - await registry.markForeignStateDetected("dev_virtual", 5); - - const [stored] = (await written()).devices ?? []; - expect(stored).toMatchObject({ foreignStateDetectedAt: 5, id: "dev_virtual" }); - expect(stored).not.toHaveProperty("physical"); - expect(stored?.spec).not.toHaveProperty("physical"); - }); - - it.each([ - ["the record says physical true", { physical: true }], - ["the record says physical as a string", { physical: "false" }], - ["its spec says physical true", { spec: { ...virtualRecord.spec, physical: true } }], - ["its spec says physical as a string", { spec: { ...virtualRecord.spec, physical: "no" } }], - ["its spec carries a class", { spec: { ...virtualRecord.spec, class: "phone" } }], - ])( - "fails the load when a record in devices breaks the virtual rule: %s", - async (_why, change) => { - const { load } = await stateFile({ devices: [{ ...virtualRecord, ...change }] }); - - await expect(load()).rejects.toThrow(invalid); - }, - ); - - it("keeps a physical record's class, enrolled apps and address through a save and a load", async () => { - const { load, written } = await stateFile({ - devices: [], - leases: [lease], - physicalDevices: [physicalRecord], + const enroll = (name: string, overrides: Partial = {}) => { + names.push(name); + return registry.enrollPhysical({ ...physicalInput, ...overrides }); + }; + const register = async (name: string) => { + names.push(name); + const device = await registry.registerDevice({ + driverData: { fakeDeviceId: `fake-${name}` }, + driverDeviceId: `driver_${name}`, + provisionDuration: 0, + spec, + }); + await registry.transitionDevice(device.id, "ready", { + event: "device.ready", + payload: { bootDuration: 0, deviceId: device.id }, + }); + return device; + }; + const lease = (deviceId: string, leaseId = `lse_${deviceId}`) => + registry.createLease({ + deviceId, + leaseId, + ownerId: "agent", + requesterId: "agent", + ttlDeadline: 90_000, + ttlMs: 60_000, }); - const registry = await load(); + return { bus, clock, enroll, lease, register, registry, reload, state }; +} + +describe("Registry: physical devices (ADR 0022 §1)", () => { + it("keeps a physical record's class and enrolled apps through a reload", async () => { + const { enroll, registry, reload } = await seededWorld(); + await enroll("physical"); await registry.markForeignStateDetected("dev_physical", 5); - expect((await written()).physicalDevices).toEqual([ - { ...physicalRecord, foreignStateDetectedAt: 5 }, - ]); - expect((await load()).snapshot.devices).toEqual([ + expect((await reload()).snapshot.devices).toEqual([ expect.objectContaining({ - address: "00008110-001A2B3C4D5E", enrolledApps: ["com.example.one", "com.example.two"], + foreignStateDetectedAt: 5, physical: true, spec: physicalSpec, state: "ready", @@ -2514,115 +1666,32 @@ describe("Registry: physical devices (ADR 0022 §1)", () => { ]); }); - it.each([ - ["physical is missing on the record", { physical: undefined }], - ["physical is false on the record", { physical: false }], - ["physical is missing on the spec", { spec: { ...physicalSpec, physical: undefined } }], - ["physical is false on the spec", { spec: { ...physicalSpec, physical: false } }], - ["its class is missing", { spec: { ...physicalSpec, class: undefined } }], - ["its class is watch", { spec: { ...physicalSpec, class: "watch" } }], - ["its state is shutdown", { state: "shutdown" }], - ["its state is provisioning", { state: "provisioning" }], - ["its spec has a mode", { spec: { ...physicalSpec, mode: "slim" } }], - ["its spec has an imageTag", { spec: { ...physicalSpec, imageTag: "default" } }], - ["the record has a mode", { mode: "full" }], - ["the record has a leaseIdentity", { leaseIdentity: "reusable" }], - ["enrolledApps is missing", { enrolledApps: undefined }], - ["enrolledApps is a string", { enrolledApps: "com.example.one" }], - ["enrolledApps holds a number", { enrolledApps: ["com.example.one", 7] }], - ])( - "fails the load when a record in physicalDevices breaks the physical rule: %s", - async (_why, change) => { - const { load } = await stateFile({ - devices: [], - physicalDevices: [{ ...physicalRecord, ...change }], - }); - - await expect(load()).rejects.toThrow(invalid); - }, - ); - it.each(["ready", "leased", "reclaiming", "quarantined", "deleted"] as const)( - "loads a physical record in the %s state", - async (state) => { - const { load } = await stateFile({ - devices: [], - physicalDevices: [{ ...physicalRecord, state }], - }); + "reloads a physical record in the %s state", + async (target) => { + const { enroll, lease, registry, reload } = await seededWorld(); + await enroll("physical"); + if (target === "deleted") await registry.unenrollPhysical("dev_physical"); + if (target !== "ready" && target !== "deleted") await lease("dev_physical"); + if (target === "reclaiming" || target === "quarantined") { + await registry.beginRelease("lse_dev_physical"); + } + if (target === "quarantined") { + await registry.enterQuarantine("dev_physical", 5_000, { kind: "purge-failed" }); + } - expect((await load()).snapshot.devices[0]).toMatchObject({ physical: true, state }); + expect((await reload()).snapshot.devices[0]).toMatchObject({ + physical: true, + state: target, + }); }, ); - it.each([ - ["its state is unknown", { state: "absent" }], - ["its spec is not an object", { spec: "iPhone 15 Pro" }], - ["its model is missing", { spec: { ...physicalSpec, model: undefined } }], - ["its model is a number", { spec: { ...physicalSpec, model: 15 } }], - ["its OS version is missing", { spec: { ...physicalSpec, osVersion: undefined } }], - ["its OS version is a number", { spec: { ...physicalSpec, osVersion: 18 } }], - ["its platform is unknown", { spec: { ...physicalSpec, platform: "tizen" } }], - ])("fails the load when a physical record breaks the shape: %s", async (_why, change) => { - const { load } = await stateFile({ - devices: [], - physicalDevices: [{ ...physicalRecord, ...change }], - }); - - await expect(load()).rejects.toThrow(invalid); - }); - - it("fails the load when a record in devices has a state no device has, or a spec that is not an object", async () => { - for (const change of [{ state: "absent" }, { spec: "iPhone 16" }]) { - const { load } = await stateFile({ devices: [{ ...virtualRecord, ...change }] }); - - await expect(load()).rejects.toThrow(invalid); - } - }); - - it("loads a file with no physicalDevices with no physical record, and fails one whose physicalDevices is a string", async () => { - const without = await stateFile({ devices: [virtualRecord] }); - expect((await without.load()).snapshot.devices.map((device) => device.physical)).toEqual([ - false, - ]); - - const broken = await stateFile({ devices: [], physicalDevices: "none" }); - await expect(broken.load()).rejects.toThrow("Invalid registry state"); - }); - - it("writes a virtual and a physical record to separate lists, so a reader of devices alone, as an older Simlock, finds no physical record", async () => { - const { load, written } = await stateFile({ - devices: [virtualRecord], - physicalDevices: [physicalRecord], - }); - const registry = await load(); - await registry.markForeignStateDetected("dev_virtual", 5); - - const file = await written(); - expect(file.devices?.map((device) => device.id)).toEqual(["dev_virtual"]); - expect(file.physicalDevices?.map((device) => device.id)).toEqual(["dev_physical"]); - expect(file.devices?.some((device) => device.physical === true)).toBe(false); - }); - - it("keeps a top-level key it does not know, and does not keep physicalDevices twice", async () => { - const { load, written } = await stateFile({ - devices: [], - futureKey: { kept: true }, - physicalDevices: [physicalRecord], - }); - const registry = await load(); - await registry.markForeignStateDetected("dev_physical", 5); - - const file = await written(); - expect(file.futureKey).toEqual({ kept: true }); - expect(file.physicalDevices).toHaveLength(1); - }); - it("lists every virtual record, and no physical one, in snapshot.virtualDevices, in the order of snapshot.devices", async () => { - const { load } = await stateFile({ - devices: [virtualRecord, { ...virtualRecord, id: "dev_virtual_2" }], - physicalDevices: [physicalRecord], - }); - const registry = await load(); + const { enroll, register, registry } = await seededWorld(); + await register("virtual"); + await register("virtual_2"); + await enroll("physical"); expect(registry.snapshot.devices.map((device) => device.id)).toEqual([ "dev_virtual", @@ -2635,111 +1704,75 @@ describe("Registry: physical devices (ADR 0022 §1)", () => { ]); }); - it("lists a virtual device registered after a physical one before it, as the file's two lists are read", async () => { - const { load } = await stateFile({ devices: [], physicalDevices: [physicalRecord] }); - const registry = await load(); - await registry.registerDevice({ - driverData: {}, - driverDeviceId: "driver_new", - provisionDuration: 0, - spec, - }); + it("lists a virtual device registered after a physical one before it", async () => { + const { enroll, register, registry } = await seededWorld(); + await enroll("physical"); + await register("virtual"); expect(registry.snapshot.devices.map((device) => device.physical)).toEqual([false, true]); }); it("refuses to mark a physical device missing, whether the call is markDeviceMissing or endLeaseAndMarkDeviceMissing, and writes nothing", async () => { - const idle = await stateFile({ devices: [], physicalDevices: [physicalRecord] }); - const idleRegistry = await idle.load(); - const idleBefore = await idle.filesystem.readFile(statePath); + const { enroll, lease, registry, state } = await seededWorld(); + await enroll("physical"); + const idleChanges = totalChanges(state); - await expect(idleRegistry.markDeviceMissing("dev_physical", "doctor")).rejects.toThrow( + await expect(registry.markDeviceMissing("dev_physical", "doctor")).rejects.toThrow( "Cannot mark a physical device missing", ); - expect(await idle.filesystem.readFile(statePath)).toBe(idleBefore); - expect(idleRegistry.snapshot.devices.map((device) => device.id)).toEqual(["dev_physical"]); + expect(totalChanges(state)).toBe(idleChanges); + expect(registry.snapshot.devices.map((device) => device.id)).toEqual(["dev_physical"]); - const { filesystem, load } = await stateFile({ - devices: [], - leases: [lease], - physicalDevices: [{ ...physicalRecord, state: "leased" }], - }); - const registry = await load(); - const before = await filesystem.readFile(statePath); + await lease("dev_physical", "lse_physical"); + const leasedChanges = totalChanges(state); await expect( registry.endLeaseAndMarkDeviceMissing("lse_physical", "startup", () => undefined), ).rejects.toThrow("Cannot mark a physical device missing"); - expect(await filesystem.readFile(statePath)).toBe(before); + expect(totalChanges(state)).toBe(leasedChanges); expect(registry.snapshot.leases.map((held) => held.id)).toEqual(["lse_physical"]); }); - describe("a stored grant's device", () => { - const grantOf = (device: Record) => ({ - createdAt: 1_000, - grant: { device, environment: {}, lease, timing: {} }, + it("keeps a grant of a physical device as it is, with no mode, across a reload", async () => { + const { enroll, registry, reload } = await seededWorld(); + await enroll("physical"); + await registry.createLeaseRequest({ id: "req_1", ownerId: "agent", request: { platform: "ios" }, requesterId: "agent", - settledAt: 1_000, - state: "granted", - }); - - it("loads a grant written before physical devices existed as a grant of a virtual device, on its device and its spec", async () => { - const { load } = await stateFile({ - devices: [{ ...virtualRecord, state: "leased" }], - leaseRequests: [grantOf({ ...virtualRecord, state: "leased" })], - }); - - const device = (await load()).leaseRequests()[0]?.grant?.device; - - expect(device).toMatchObject({ mode: "full", physical: false, spec: { physical: false } }); - }); - - it("keeps a grant of a physical device as it is, with no mode", async () => { - const { load } = await stateFile({ - devices: [], - leaseRequests: [grantOf({ ...physicalRecord, state: "leased" })], - physicalDevices: [{ ...physicalRecord, state: "leased" }], - }); - - const device = (await load()).leaseRequests()[0]?.grant?.device; - - expect(device).toMatchObject({ physical: true, spec: { class: "phone", physical: true } }); - expect(device).not.toHaveProperty("mode"); }); - - it("loads a stored grant whose device has no spec without failing the load", async () => { - const { spec: _spec, ...withoutSpec } = { ...virtualRecord, state: "leased" }; - const { load } = await stateFile({ - devices: [{ ...virtualRecord, state: "leased" }], - leaseRequests: [grantOf(withoutSpec)], - }); - - expect((await load()).leaseRequests()).toHaveLength(1); + await registry.createLease({ + deviceId: "dev_physical", + leaseId: "lse_physical", + ownerId: "agent", + request: { + environment: {}, + id: "req_1", + timing: { + estimatedBootMs: 0, + estimatedProvisionMs: 0, + estimatedReadyMs: 0, + estimatedReclaimMs: 0, + }, + }, + requesterId: "agent", + ttlDeadline: 90_000, + ttlMs: 60_000, }); - it("drops a stored grant that gives a physical device a mode, as it drops one with an unknown mode", async () => { - const { load } = await stateFile({ - devices: [], - leaseRequests: [grantOf({ ...physicalRecord, mode: "full", state: "leased" })], - physicalDevices: [{ ...physicalRecord, state: "leased" }], - }); + const device = (await reload()).leaseRequests()[0]?.grant?.device; - expect((await load()).leaseRequests()).toEqual([]); - }); + expect(device).toMatchObject({ physical: true, spec: { class: "phone", physical: true } }); + expect(device).not.toHaveProperty("mode"); }); it("moves a physical device to reclaiming when its lease is released and stamps lastLeaseEndedAt with the clock's time", async () => { - const { load } = await stateFile({ - devices: [], - leases: [lease], - physicalDevices: [{ ...physicalRecord, state: "leased" }], - }); - const registry = await load(); + const { enroll, lease, registry } = await seededWorld(); + await enroll("physical"); + await lease("dev_physical", "lse_physical"); const released = await registry.beginRelease("lse_physical"); @@ -2760,12 +1793,10 @@ describe("Registry: device.deleted carries physical, and enrollment writes (ADR const clock = new FakeClock(1_000); const bus = new EventBus(clock); let next = 1; - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: bus, - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => `r${next++}` }, - statePath, }); const deleted: unknown[] = []; const modules: string[] = []; @@ -2778,7 +1809,7 @@ describe("Registry: device.deleted carries physical, and enrollment writes (ADR async function readyVirtual(registry: Registry, driverDeviceId: string) { const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "fake-1" }, driverDeviceId, provisionDuration: 0, spec, @@ -2984,53 +2015,6 @@ describe("Registry: device.deleted carries physical, and enrollment writes (ADR }); describe("Registry: absent physical devices (ADR 0022 §2, §8)", () => { - const physicalSpec = { - class: "phone", - model: "iPhone 15 Pro", - osVersion: "18.4", - physical: true, - platform: "ios", - }; - const physicalRecord = { - address: "00008110-001A2B3C4D5E", - createdAt: 600, - driverData: {}, - driverDeviceId: "00008110-001A2B3C4D5E", - enrolledApps: ["com.example.one"], - id: "dev_physical", - physical: true, - spec: physicalSpec, - state: "ready", - }; - const virtualRecord = { - createdAt: 500, - driverData: {}, - driverDeviceId: "driver_virtual", - id: "dev_virtual", - mode: "full", - spec: { model: "iPhone 16", osVersion: "26.5", platform: "ios" }, - state: "leased", - }; - const leaseOf = (deviceId: string) => ({ - deviceId, - grantedAt: 700, - id: `lse_${deviceId}`, - idChosenByRequester: false, - lastRenewedAt: 700, - ownerId: "agent", - requesterId: "agent", - ttlDeadline: 90_000, - ttlMs: 60_000, - }); - const invalid = "Invalid device record in registry state"; - - interface AbsentWrites { - endLeaseAndMarkDeviceAbsent( - leaseId: string, - absentReason: string, - announceLeaseEnd: (ended: unknown) => void, - ): Promise; - } type Writer = ( deviceId: string, to: string, @@ -3038,52 +2022,33 @@ describe("Registry: absent physical devices (ADR 0022 §2, §8)", () => { update: Record, ) => Promise; - async function stateFile(state: Record) { - const clock = new FakeClock(1_000); - const bus = new EventBus(clock); - const filesystem = new ObservingFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ devices: [], leases: [], ...state }), + const transitionAny = (registry: Registry): Writer => + registry.transitionDevice.bind(registry) as unknown as Writer; + const goAbsent = (registry: Registry, deviceId: string, absentReason: string) => + transitionAny(registry)( + deviceId, + "absent", + { + event: "device.absence-detected", + payload: { absentReason, deviceId, previousState: "ready" }, + }, + { absentReason }, ); - filesystem.operations.length = 0; - const load = () => - Registry.load({ - clock, - eventBus: bus, - filesystem, - idGenerator: { generate: () => "new" }, - statePath, - }); - const loaded = async () => { - const registry = await load().catch((error: unknown) => error); - expect(registry).toBeInstanceOf(Registry); - return registry as Registry; - }; - const written = async () => - JSON.parse(await filesystem.readFile(statePath)) as Record[]>; - const transitionAny = (registry: Registry): Writer => - registry.transitionDevice.bind(registry) as unknown as Writer; - return { bus, filesystem, load, loaded, transitionAny, written }; - } + const storedRows = (state: StateDatabase, columns: string) => + state.database.prepare(`SELECT ${columns} FROM devices ORDER BY rowid`).all(); it("endLeaseAndMarkDeviceAbsent removes the lease, writes absent with its absentReason and stamps lastLeaseEndedAt in one commit, and calls announceLeaseEnd before emitting device.absence-detected", async () => { - const { bus, filesystem, loaded, written } = await stateFile({ - leases: [leaseOf("dev_physical")], - physicalDevices: [{ ...physicalRecord, state: "leased" }], - }); - const registry = await loaded(); + const { bus, enroll, lease, registry, state } = await seededWorld(); + await enroll("physical"); + await lease("dev_physical"); const order: string[] = []; const payloads: unknown[] = []; bus.subscribeAll((envelope) => { order.push(envelope.event); payloads.push(envelope.payload); }); - const end = (registry as unknown as Partial).endLeaseAndMarkDeviceAbsent; - expect(end).toBeTypeOf("function"); - await end?.call(registry, "lse_dev_physical", "locked", () => { + await registry.endLeaseAndMarkDeviceAbsent("lse_dev_physical", "locked", () => { order.push("announce"); }); @@ -3093,14 +2058,12 @@ describe("Registry: absent physical devices (ADR 0022 §2, §8)", () => { lastLeaseEndedAt: 1_000, state: "absent", }); - expect(filesystem.operations).toEqual(["save"]); - const file = await written(); - expect(file.leases).toEqual([]); - expect(file.physicalDevices?.[0]).toMatchObject({ - absentReason: "locked", - lastLeaseEndedAt: 1_000, - state: "absent", + expect(state.database.prepare("SELECT COUNT(*) AS leases FROM leases").get()).toEqual({ + leases: 0, }); + expect(storedRows(state, "state, absent_reason, last_lease_ended_at")).toEqual([ + { absent_reason: "locked", last_lease_ended_at: 1_000, state: "absent" }, + ]); expect(order).toEqual(["announce", "device.absence-detected"]); expect(payloads[0]).toEqual({ absentReason: "locked", @@ -3110,12 +2073,11 @@ describe("Registry: absent physical devices (ADR 0022 §2, §8)", () => { }); it("absent -> reclaiming writes the new osVersion, stamps reclaimingSince, removes absentReason, keeps lastLeaseEndedAt, and transitionEnteredAt returns reclaimingSince", async () => { - const { loaded, transitionAny } = await stateFile({ - physicalDevices: [ - { ...physicalRecord, absentReason: "locked", lastLeaseEndedAt: 500, state: "absent" }, - ], - }); - const registry = await loaded(); + const { clock, enroll, lease, registry } = await seededWorld(); + await enroll("physical"); + await lease("dev_physical"); + await registry.endLeaseAndMarkDeviceAbsent("lse_dev_physical", "locked", () => undefined); + clock.advance(500); await transitionAny(registry)( "dev_physical", @@ -3126,22 +2088,21 @@ describe("Registry: absent physical devices (ADR 0022 §2, §8)", () => { const stored = registry.snapshot.devices[0] as DeviceRecord & Record; expect(stored).toMatchObject({ - lastLeaseEndedAt: 500, - reclaimingSince: 1_000, + lastLeaseEndedAt: 1_000, + reclaimingSince: 1_500, spec: { osVersion: "18.5" }, state: "reclaiming", }); expect(stored).not.toHaveProperty("absentReason"); - expect(transitionEnteredAt(stored)).toBe(1_000); + expect(transitionEnteredAt(stored)).toBe(1_500); }); it("beginRelease of a physical lease stamps reclaimingSince and lastLeaseEndedAt; of a virtual lease it stamps no reclaimingSince", async () => { - const { loaded } = await stateFile({ - devices: [virtualRecord], - leases: [leaseOf("dev_physical"), leaseOf("dev_virtual")], - physicalDevices: [{ ...physicalRecord, state: "leased" }], - }); - const registry = await loaded(); + const { enroll, lease, register, registry } = await seededWorld(); + await enroll("physical"); + await register("virtual"); + await lease("dev_physical"); + await lease("dev_virtual"); const physical = await registry.beginRelease("lse_dev_physical"); const virtual = await registry.beginRelease("lse_dev_virtual"); @@ -3157,8 +2118,14 @@ describe("Registry: absent physical devices (ADR 0022 §2, §8)", () => { it("transitionEnteredAt of a reclaiming physical record with no reclaimingSince is its lastLeaseEndedAt", () => { const reclaiming = { - ...physicalRecord, + createdAt: 600, + driverData: {}, + driverDeviceId: "00008110-001A2B3C4D5E", + enrolledApps: ["com.example.one"], + id: "dev_physical", lastLeaseEndedAt: 2_000, + physical: true, + spec: physicalSpec, state: "reclaiming", } as unknown as DeviceRecord; @@ -3168,76 +2135,57 @@ describe("Registry: absent physical devices (ADR 0022 §2, §8)", () => { expect(transitionEnteredAt(reclaiming)).toBe(2_000); }); - it("a physical record with reclaimingSince and an absent one with absentReason survive a save and a load; an absentReason on a record that is not absent, or with another value, an absent record without one, and a reclaimingSince that is not a number, fail the load", async () => { - const reclaiming = { - ...physicalRecord, - id: "dev_a", - lastLeaseEndedAt: 400, - reclaimingSince: 450, - state: "reclaiming", - }; - const absent = { ...physicalRecord, absentReason: "untrusted", id: "dev_b", state: "absent" }; - const { loaded, written } = await stateFile({ physicalDevices: [reclaiming, absent] }); - const registry = await loaded(); + it("a physical record with reclaimingSince and an absent one with absentReason survive a reload", async () => { + const { enroll, lease, registry, reload } = await seededWorld(); + await enroll("a"); + await lease("dev_a"); + await registry.beginRelease("lse_dev_a"); await registry.markForeignStateDetected("dev_a", 5); + await enroll("b", { driverDeviceId: "other" }); + await goAbsent(registry, "dev_b", "untrusted"); - expect((await written()).physicalDevices).toEqual([ - { ...reclaiming, foreignStateDetectedAt: 5 }, - absent, - ]); - expect( - (await stateFile({ physicalDevices: [absent] }).then((file) => file.loaded())).snapshot - .devices[0], - ).toMatchObject({ - absentReason: "untrusted", - state: "absent", - }); + const reloaded = await reload(); - const broken = [ - ["absentReason on a ready record", { absentReason: "locked", state: "ready" }], - ["absentReason on a reclaiming record", { absentReason: "locked", state: "reclaiming" }], - ["another absentReason", { absentReason: "asleep", state: "absent" }], - ["no absentReason", { state: "absent" }], - ["a reclaimingSince that is a string", { reclaimingSince: "450", state: "reclaiming" }], - ] as const; - for (const [why, change] of broken) { - const { load } = await stateFile({ physicalDevices: [{ ...physicalRecord, ...change }] }); - - await expect(load(), why).rejects.toThrow(invalid); - } + expect(reloaded.snapshot.devices).toEqual([ + expect.objectContaining({ + foreignStateDetectedAt: 5, + id: "dev_a", + lastLeaseEndedAt: 1_000, + reclaimingSince: 1_000, + state: "reclaiming", + }), + expect.objectContaining({ absentReason: "untrusted", id: "dev_b", state: "absent" }), + ]); }); it("absent -> ready (device add) and absent -> deleted (device remove) remove absentReason", async () => { - const absent = { ...physicalRecord, absentReason: "not-present", state: "absent" }; - const added = await stateFile({ physicalDevices: [absent] }); - const addRegistry = await added.loaded(); - const removed = await stateFile({ physicalDevices: [absent] }); - const removeRegistry = await removed.loaded(); - - await addRegistry.reenrollPhysical("dev_physical", { + const added = await seededWorld(); + await added.enroll("physical"); + await goAbsent(added.registry, "dev_physical", "not-present"); + const removed = await seededWorld(); + await removed.enroll("physical"); + await goAbsent(removed.registry, "dev_physical", "not-present"); + + await added.registry.reenrollPhysical("dev_physical", { + ...physicalInput, apps: ["com.example.one"], - class: "phone", - driverDeviceId: physicalRecord.driverDeviceId, - model: "iPhone 15 Pro", - osVersion: "18.4", - platform: "ios", }); - await removeRegistry.unenrollPhysical("dev_physical"); + await removed.registry.unenrollPhysical("dev_physical"); - expect(addRegistry.snapshot.devices[0]).toMatchObject({ state: "ready" }); - expect(addRegistry.snapshot.devices[0]).not.toHaveProperty("absentReason"); - expect(removeRegistry.snapshot.devices[0]).toMatchObject({ state: "deleted" }); - expect(removeRegistry.snapshot.devices[0]).not.toHaveProperty("absentReason"); - expect((await added.written()).physicalDevices?.[0]).not.toHaveProperty("absentReason"); - expect((await removed.written()).physicalDevices?.[0]).not.toHaveProperty("absentReason"); + expect(added.registry.snapshot.devices[0]).toMatchObject({ state: "ready" }); + expect(added.registry.snapshot.devices[0]).not.toHaveProperty("absentReason"); + expect(removed.registry.snapshot.devices[0]).toMatchObject({ state: "deleted" }); + expect(removed.registry.snapshot.devices[0]).not.toHaveProperty("absentReason"); + expect(storedRows(added.state, "absent_reason")).toEqual([{ absent_reason: null }]); + expect(storedRows(removed.state, "absent_reason")).toEqual([{ absent_reason: null }]); }); it("a transition into reclaiming stamps reclaimingSince on a physical device only, and a leased -> reclaiming move needs no device event", async () => { - const { loaded } = await stateFile({ - devices: [virtualRecord], - physicalDevices: [{ ...physicalRecord, state: "leased" }], - }); - const registry = await loaded(); + const { enroll, lease, register, registry } = await seededWorld(); + await enroll("physical"); + await register("virtual"); + await lease("dev_physical"); + await lease("dev_virtual"); const moveToReclaiming = (id: string) => (registry.transitionDevice as unknown as (id: string, to: string) => Promise).call( registry, @@ -3257,10 +2205,8 @@ describe("Registry: absent physical devices (ADR 0022 §2, §8)", () => { }); it("transitions to and from absent emit device.absence-detected and device.returned, each from the registry", async () => { - const { bus, loaded, transitionAny } = await stateFile({ - physicalDevices: [{ ...physicalRecord, state: "ready" }], - }); - const registry = await loaded(); + const { bus, enroll, registry } = await seededWorld(); + await enroll("physical"); const seen: { event: string; module: string; payload: unknown }[] = []; bus.subscribeAll((envelope) => seen.push({ event: envelope.event, module: envelope.module, payload: envelope.payload }), @@ -3292,9 +2238,9 @@ describe("Registry: absent physical devices (ADR 0022 §2, §8)", () => { }); it("an absent device moves to ready with a device.ready event and to deleted with a device.deleted event, and either is refused with device.returned", async () => { - const absent = { ...physicalRecord, absentReason: "locked", state: "absent" }; - const { bus, loaded, transitionAny } = await stateFile({ physicalDevices: [absent] }); - const registry = await loaded(); + const { bus, enroll, registry } = await seededWorld(); + await enroll("physical"); + await goAbsent(registry, "dev_physical", "locked"); const seen: string[] = []; bus.subscribeAll((envelope) => seen.push(envelope.event)); const returned = { event: "device.returned", payload: { deviceId: "dev_physical" } }; @@ -3316,33 +2262,16 @@ describe("Registry: absent physical devices (ADR 0022 §2, §8)", () => { }); it("a ready physical device that goes absent is not stamped reclaimingSince, and device add re-enrolling it emits device.enrolled with reenrolled true, not device.ready", async () => { - const { bus, loaded, transitionAny } = await stateFile({ - physicalDevices: [{ ...physicalRecord, state: "ready" }], - }); - const registry = await loaded(); + const { bus, enroll, registry } = await seededWorld(); + await enroll("physical"); const seen: string[] = []; bus.subscribeAll((envelope) => seen.push(envelope.event)); - await transitionAny(registry)( - "dev_physical", - "absent", - { - event: "device.absence-detected", - payload: { absentReason: "locked", deviceId: "dev_physical", previousState: "ready" }, - }, - { absentReason: "locked" }, - ); + await goAbsent(registry, "dev_physical", "locked"); const absent = registry.snapshot.devices.find((entry) => entry.id === "dev_physical"); const enrolled: unknown[] = []; bus.subscribe("device.enrolled", (envelope) => enrolled.push(envelope.payload)); - await registry.reenrollPhysical("dev_physical", { - apps: [], - class: "phone", - driverDeviceId: physicalRecord.driverDeviceId, - model: "iPhone 15 Pro", - osVersion: "18.4", - platform: "ios", - }); + await registry.reenrollPhysical("dev_physical", { ...physicalInput, apps: [] }); expect(absent).not.toHaveProperty("reclaimingSince"); expect(seen).toEqual(["device.absence-detected", "device.enrolled"]); @@ -3350,26 +2279,17 @@ describe("Registry: absent physical devices (ADR 0022 §2, §8)", () => { }); it("endLeaseAndMarkDeviceAbsent ends only the named lease, keeps every other device and lease, and emits from the registry", async () => { - const { bus, loaded } = await stateFile({ - leases: [leaseOf("dev_other"), leaseOf("dev_physical")], - physicalDevices: [ - { - ...physicalRecord, - id: "dev_other", - driverDeviceId: "other", - address: "other", - state: "leased", - }, - { ...physicalRecord, state: "leased" }, - ], - }); - const registry = await loaded(); + const { bus, enroll, lease, registry } = await seededWorld(); + await enroll("other", { driverDeviceId: "other" }); + await enroll("physical"); + await lease("dev_other"); + await lease("dev_physical"); const modules: string[] = []; bus.subscribeAll((envelope) => modules.push(envelope.module)); await registry.endLeaseAndMarkDeviceAbsent("lse_dev_physical", "locked", () => undefined); - expect(registry.snapshot.leases.map((lease) => lease.id)).toEqual(["lse_dev_other"]); + expect(registry.snapshot.leases.map((held) => held.id)).toEqual(["lse_dev_other"]); expect(registry.snapshot.devices.map((entry) => [entry.id, entry.state])).toEqual([ ["dev_other", "leased"], ["dev_physical", "absent"], @@ -3378,11 +2298,9 @@ describe("Registry: absent physical devices (ADR 0022 §2, §8)", () => { }); it("endLeaseAndMarkDeviceAbsent of an unknown lease throws UnknownLeaseError and changes nothing", async () => { - const { loaded } = await stateFile({ - leases: [leaseOf("dev_physical")], - physicalDevices: [{ ...physicalRecord, state: "leased" }], - }); - const registry = await loaded(); + const { enroll, lease, registry } = await seededWorld(); + await enroll("physical"); + await lease("dev_physical"); await expect( registry.endLeaseAndMarkDeviceAbsent("lse_missing", "locked", () => undefined), @@ -3392,14 +2310,11 @@ describe("Registry: absent physical devices (ADR 0022 §2, §8)", () => { }); it("rewriteAbsentReason replaces the reason of an absent physical device and refuses a physical device that is not absent and a virtual one", async () => { - const { loaded, written } = await stateFile({ - devices: [virtualRecord], - physicalDevices: [ - { ...physicalRecord, absentReason: "not-present", state: "absent" }, - { ...physicalRecord, id: "dev_ready", driverDeviceId: "r", address: "r", state: "ready" }, - ], - }); - const registry = await loaded(); + const { enroll, register, registry, state } = await seededWorld(); + await register("virtual"); + await enroll("physical"); + await goAbsent(registry, "dev_physical", "not-present"); + await enroll("ready", { driverDeviceId: "r" }); await expect(registry.rewriteAbsentReason("dev_ready", "locked")).rejects.toThrow( "Device is not absent: dev_ready", @@ -3414,99 +2329,42 @@ describe("Registry: absent physical devices (ADR 0022 §2, §8)", () => { state: "absent", }); expect( - (await written()).physicalDevices?.find((entry) => entry.id === "dev_physical"), - ).toMatchObject({ absentReason: "locked" }); - }); - - it("a loaded ready physical record written without the marks carries neither reclaimingSince nor absentReason", async () => { - const { loaded } = await stateFile({ - physicalDevices: [{ ...physicalRecord, state: "ready" }], - }); - const registry = await loaded(); - - expect(registry.snapshot.devices[0]).not.toHaveProperty("reclaimingSince"); - expect(registry.snapshot.devices[0]).not.toHaveProperty("absentReason"); - }); - - it("a record in physicalDevices in absent loads; a record in devices in absent fails to load as corrupt", async () => { - const { loaded } = await stateFile({ - physicalDevices: [{ ...physicalRecord, absentReason: "locked", state: "absent" }], - }); - const registry = await loaded(); - const { load } = await stateFile({ - devices: [{ ...virtualRecord, state: "absent" }], - }); - - expect(registry.snapshot.devices[0]).toMatchObject({ physical: true, state: "absent" }); - await expect(load()).rejects.toThrow(invalid); + state.database.prepare("SELECT absent_reason FROM devices WHERE id = 'dev_physical'").get(), + ).toEqual({ absent_reason: "locked" }); }); }); describe("Registry: quarantineCause", () => { - const virtualRecord = { - createdAt: 500, - driverData: {}, - driverDeviceId: "driver_virtual", - id: "dev_virtual", - mode: "full", - physical: false, - spec, - state: "reclaiming", - }; - const physicalRecord = { - createdAt: 600, - driverData: {}, - driverDeviceId: "00008110-001A2B3C4D5E", - enrolledApps: ["com.example.one"], - id: "dev_physical", - physical: true, - spec: { - class: "phone", - model: "iPhone 15 Pro", - osVersion: "18.4", - physical: true, - platform: "ios", - }, - state: "reclaiming", - }; - const quarantineFields = { - quarantineAttempts: 0, - quarantineNextRetryAt: 5_000, - quarantinedAt: 900, + const purgeCause = { + kind: "purge-failed" as const, + message: "DriverCrashError: simctl erase exited 164", }; - const purgeCause = { kind: "purge-failed", message: "DriverCrashError: simctl erase exited 164" }; - const invalid = "Invalid device record in registry state"; - async function stateFile(state: Record) { - const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic(statePath, JSON.stringify({ leases: [], ...state })); - const load = () => - Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "new" }, - statePath, - }); - const written = async () => - JSON.parse(await filesystem.readFile(statePath)) as Record[]>; - return { filesystem, load, written }; + async function reclaimingVirtual() { + const world = await seededWorld(); + await world.register("virtual"); + await world.lease("dev_virtual", "lse_virtual"); + await world.registry.beginRelease("lse_virtual"); + return world; } - const quarantinedVirtual = (cause: unknown) => ({ - ...virtualRecord, - ...quarantineFields, - quarantineCause: cause, - state: "quarantined", - }); - const quarantinedPhysical = (cause: unknown) => ({ - ...physicalRecord, - ...quarantineFields, - quarantineCause: cause, - state: "quarantined", - }); + async function quarantinedVirtual() { + const world = await reclaimingVirtual(); + await world.registry.enterQuarantine("dev_virtual", 5_000, purgeCause); + return world; + } + + async function quarantinedPhysical() { + const world = await seededWorld(); + await world.enroll("physical"); + await world.lease("dev_physical", "lse_physical"); + await world.registry.beginRelease("lse_physical"); + await world.registry.enterQuarantine("dev_physical", 5_000, purgeCause); + return world; + } + + const storedCauseKinds = (world: { state: StateDatabase }) => + world.state.database.prepare("SELECT quarantine_cause_kind FROM devices").all(); it("a quarantined record with each kind, written by enterQuarantine and loaded by a new Registry, has its cause, with the clock short of quarantineNextRetryAt", async () => { const causes = [ @@ -3518,16 +2376,14 @@ describe("Registry: quarantineCause", () => { ] as const; for (const cause of causes) { - const { load } = await stateFile({ - devices: [ - { ...virtualRecord, state: cause.kind === "delete-failed" ? "shutdown" : "reclaiming" }, - ], - }); - const registry = await load(); + const { registry, reload } = await reclaimingVirtual(); + if (cause.kind === "delete-failed") { + await registry.completeReclaimWithoutPurge("dev_virtual"); + } const entered = await registry.enterQuarantine("dev_virtual", 5_000, cause); expect(entered.quarantineCause, cause.kind).toEqual(cause); - const reloaded = await load(); + const reloaded = await reload(); expect(reloaded.snapshot.devices[0], cause.kind).toMatchObject({ quarantineCause: cause, state: "quarantined", @@ -3535,81 +2391,6 @@ describe("Registry: quarantineCause", () => { } }); - it("a quarantined record with a cause from an earlier entry loads as is, and a record with no cause loads with none", async () => { - const withCause = await stateFile({ devices: [quarantinedVirtual(purgeCause)] }); - const without = await stateFile({ - devices: [{ ...virtualRecord, ...quarantineFields, state: "quarantined" }], - }); - - expect((await withCause.load()).snapshot.devices[0]?.quarantineCause).toEqual(purgeCause); - expect((await without.load()).snapshot.devices[0]).not.toHaveProperty("quarantineCause"); - }); - - it("a record that is not quarantined loads without its cause, well-formed or malformed, with no RegistryLoadError, and the next write does not carry it", async () => { - const causes = [purgeCause, { kind: "bogus", message: 7 }, "not an object"]; - for (const state of ["ready", "reclaiming"] as const) { - for (const cause of causes) { - const { load, written } = await stateFile({ - devices: [{ ...virtualRecord, quarantineCause: cause, state }], - }); - - const registry = await load(); - const why = `${state} ${JSON.stringify(cause)}`; - expect(registry.snapshot.devices[0], `loaded ${why}`).not.toHaveProperty("quarantineCause"); - await registry.markForeignStateDetected("dev_virtual", 5); - - expect(registry.snapshot.devices[0], why).toMatchObject({ state }); - expect(registry.snapshot.devices[0], why).not.toHaveProperty("quarantineCause"); - expect((await written()).devices?.[0], why).not.toHaveProperty("quarantineCause"); - } - } - const physical = await stateFile({ - devices: [], - physicalDevices: [{ ...physicalRecord, quarantineCause: purgeCause, state: "ready" }], - }); - const registry = await physical.load(); - expect(registry.snapshot.devices[0]).not.toHaveProperty("quarantineCause"); - await registry.markForeignStateDetected("dev_physical", 5); - expect(registry.snapshot.devices[0]).not.toHaveProperty("quarantineCause"); - expect((await physical.written()).physicalDevices?.[0]).not.toHaveProperty("quarantineCause"); - }); - - it("a quarantined record whose cause has an unknown kind, stalled without stalledState, stalledState on another kind, a message on stalled, a non-string, empty or 301-character message, or a control character fails the load", async () => { - const accepted = await stateFile({ devices: [quarantinedVirtual(purgeCause)] }); - await expect((await accepted.load()).snapshot.devices[0]?.quarantineCause).toEqual(purgeCause); - const bad: readonly (readonly [string, unknown])[] = [ - ["an unknown kind", { kind: "exploded", message: "Error: x" }], - ["stalled without stalledState", { kind: "stalled" }], - [ - "stalledState on another kind", - { kind: "purge-failed", message: "Error: x", stalledState: "reclaiming" }, - ], - [ - "a message on stalled", - { kind: "stalled", message: "Error: x", stalledState: "reclaiming" }, - ], - [ - "a stalledState that is not provisioning or reclaiming", - { kind: "stalled", stalledState: "ready" }, - ], - ["a non-string message", { kind: "purge-failed", message: 7 }], - ["an empty message", { kind: "purge-failed", message: "" }], - ["a 301-character message", { kind: "purge-failed", message: "x".repeat(301) }], - ["a control character", { kind: "purge-failed", message: "Error: a\nb" }], - ["a cause that is not an object", "purge-failed"], - ]; - - for (const [why, cause] of bad) { - const { load } = await stateFile({ devices: [quarantinedVirtual(cause)] }); - await expect(load(), why).rejects.toThrow(invalid); - const physical = await stateFile({ - devices: [], - physicalDevices: [quarantinedPhysical(cause)], - }); - await expect(physical.load(), `${why} (physical)`).rejects.toThrow(invalid); - } - }); - describe("every exit from quarantined removes it", () => { const readyEvent = (id: string) => ({ event: "device.ready" as const, @@ -3646,44 +2427,482 @@ describe("Registry: quarantineCause", () => { ]; it.each(exits)("%s", async (_name, exit) => { - const { load, written } = await stateFile({ devices: [quarantinedVirtual(purgeCause)] }); - const registry = await load(); + const world = await quarantinedVirtual(); + const { registry } = world; expect(registry.snapshot.devices[0]).toHaveProperty("quarantineCause"); const result = await exit(registry); expect(result).not.toHaveProperty("quarantineCause"); expect(registry.snapshot.devices[0]).not.toHaveProperty("quarantineCause"); - expect((await written()).devices?.[0]).not.toHaveProperty("quarantineCause"); + expect(storedCauseKinds(world)).toEqual([{ quarantine_cause_kind: null }]); }); it.each([ [ "reenrollPhysical", (r: Registry) => - r.reenrollPhysical("dev_physical", { - apps: ["com.example.one"], - class: "phone", - driverDeviceId: "00008110-001A2B3C4D5E", - model: "iPhone 15 Pro", - osVersion: "18.4", - platform: "ios", - }), + r.reenrollPhysical("dev_physical", { ...physicalInput, apps: ["com.example.one"] }), ], ["unenrollPhysical", (r: Registry) => r.unenrollPhysical("dev_physical")], ])("%s", async (_name, exit) => { - const { load, written } = await stateFile({ - devices: [], - physicalDevices: [quarantinedPhysical(purgeCause)], - }); - const registry = await load(); + const world = await quarantinedPhysical(); + const { registry } = world; expect(registry.snapshot.devices[0]).toHaveProperty("quarantineCause"); const result = await exit(registry); expect(result).not.toHaveProperty("quarantineCause"); expect(registry.snapshot.devices[0]).not.toHaveProperty("quarantineCause"); - expect((await written()).physicalDevices?.[0]).not.toHaveProperty("quarantineCause"); + expect(storedCauseKinds(world)).toEqual([{ quarantine_cause_kind: null }]); }); }); }); + +describe("Registry: state.db rows", () => { + async function world( + options: { readonly leaseRequestLimits?: { maxRecords: number; retentionMs: number } } = {}, + ) { + const clock = new FakeClock(1_000); + const state = await openTestState(); + let next = 0; + const open = (idGenerator: { generate: () => string }) => + loadTestRegistry({ + clock, + eventBus: new EventBus(clock), + idGenerator, + state, + ...options, + }); + const registry = await open({ generate: () => String((next += 1)) }); + const readyDevice = async (fakeDeviceId: string) => { + const device = await registry.registerDevice({ + driverData: { fakeDeviceId }, + driverDeviceId: `drv-${fakeDeviceId}`, + provisionDuration: 0, + spec, + }); + await registry.transitionDevice(device.id, "ready", { + event: "device.ready", + payload: { bootDuration: 0, deviceId: device.id }, + }); + return device; + }; + return { clock, open, readyDevice, registry, state }; + } + + it("a renew with 1,000 settled requests stored changes exactly one row", async () => { + const { readyDevice, registry, state } = await world(); + const device = await readyDevice("fk-1"); + const lease = await registry.createLease({ + deviceId: device.id, + ownerId: "agent-1", + requesterId: "agent-1", + ttlDeadline: 5_000, + ttlMs: 4_000, + }); + for (let index = 0; index < 1_000; index += 1) { + await registry.createLeaseRequest({ + id: `req_${String(index)}`, + ownerId: "agent-1", + request: { platform: "ios" }, + requesterId: "agent-1", + }); + await registry.settleLeaseRequest(`req_${String(index)}`, { state: "cancelled" }); + } + expect(state.database.prepare("SELECT COUNT(*) AS n FROM lease_requests").get()?.n).toBe(1_000); + + const before = totalChanges(state); + await registry.renewLease(lease.id, 9_000, 8_000); + + expect(Number(totalChanges(state)) - Number(before)).toBe(1); + expect(state.database.prepare("SELECT ttl_deadline, ttl_ms FROM leases").all()).toEqual([ + { ttl_deadline: 9_000, ttl_ms: 8_000 }, + ]); + }); + + it("a renew with a fractional ttl is stored and read back unchanged", async () => { + const { open, readyDevice, registry } = await world(); + const device = await readyDevice("fk-1"); + const lease = await registry.createLease({ + deviceId: device.id, + ownerId: "agent-1", + requesterId: "agent-1", + ttlDeadline: 5_000.5, + ttlMs: 4_000.5, + }); + + const renewed = await registry.renewLease(lease.id, 2_500.5, 1_500.5); + + expect(renewed).toMatchObject({ ttlDeadline: 2_500.5, ttlMs: 1_500.5 }); + const reloaded = await open({ generate: () => "unused" }); + expect(reloaded.snapshot.leases).toEqual([renewed]); + }); + + it("a grant with a fractional ttl is stored in lease_grants and read back unchanged", async () => { + const { open, readyDevice, registry } = await world(); + const device = await readyDevice("fk-1"); + await registry.createLeaseRequest({ + id: "req_1", + ownerId: "agent-1", + request: { platform: "ios" }, + requesterId: "agent-1", + }); + + const lease = await registry.createLease({ + deviceId: device.id, + ownerId: "agent-1", + request: { + environment: {}, + id: "req_1", + timing: { + estimatedBootMs: 0, + estimatedProvisionMs: 0, + estimatedReadyMs: 0, + estimatedReclaimMs: 0, + }, + }, + requesterId: "agent-1", + ttlDeadline: 5_000.5, + ttlMs: 4_000.5, + }); + + expect(lease).toMatchObject({ ttlDeadline: 5_000.5, ttlMs: 4_000.5 }); + const reloaded = await open({ generate: () => "unused" }); + expect(reloaded.leaseRequests()).toEqual(registry.leaseRequests()); + expect(reloaded.snapshot.leases).toEqual([lease]); + }); + + it("a quarantine retry at a fractional time is stored and read back unchanged", async () => { + const { open, readyDevice, registry } = await world(); + const device = await readyDevice("fk-1"); + const lease = await registry.createLease({ + deviceId: device.id, + ownerId: "agent-1", + requesterId: "agent-1", + ttlDeadline: 2_000, + ttlMs: 60_000, + }); + await registry.beginRelease(lease.id); + await registry.enterQuarantine(device.id, 5_000.5, { kind: "purge-failed" }); + + const retried = await registry.recordQuarantineRetryFailure( + device.id, + 1, + 50_700.000_000_000_01, + ); + + expect(retried.quarantineNextRetryAt).toBe(50_700.000_000_000_01); + const reloaded = await open({ generate: () => "unused" }); + expect(reloaded.snapshot.devices).toEqual([retried]); + }); + + it("a grant writes the lease, the device's move to leased and the request's granted result in one transaction", async () => { + const { clock, state } = await world(); + const timing = { + estimatedBootMs: 2, + estimatedProvisionMs: 1, + estimatedReadyMs: 4, + estimatedReclaimMs: 3, + }; + let failWrites = false; + const failing: DeviceDataTable = { + ...fakeDeviceDataTable, + write: (database, deviceId, driverData) => { + if (failWrites) throw new Error("table refused the write"); + fakeDeviceDataTable.write(database, deviceId, driverData); + }, + }; + const registry = await Registry.load({ + clock, + deviceData: new Map([["ios", failing]]), + eventBus: new EventBus(clock), + idGenerator: { generate: () => "x" }, + state, + }); + const device = await registry.registerDevice({ + driverData: { fakeDeviceId: "fk-grant" }, + driverDeviceId: "drv-grant", + provisionDuration: 0, + spec, + }); + await registry.transitionDevice(device.id, "ready", { + event: "device.ready", + payload: { bootDuration: 0, deviceId: device.id }, + }); + await registry.createLeaseRequest({ + id: "req_grant", + ownerId: "agent-1", + request: { platform: "ios" }, + requesterId: "agent-1", + }); + + failWrites = true; + await expect( + registry.createLease({ + deviceId: device.id, + ownerId: "agent-1", + request: { environment: {}, id: "req_grant", timing }, + requesterId: "agent-1", + ttlDeadline: 5_000, + ttlMs: 4_000, + }), + ).rejects.toThrow("table refused the write"); + + const restarted = await Registry.load({ + clock, + deviceData: new Map([["ios", fakeDeviceDataTable]]), + eventBus: new EventBus(clock), + idGenerator: { generate: () => "y" }, + state, + }); + for (const view of [registry, restarted]) { + expect(view.snapshot.leases).toEqual([]); + expect(view.snapshot.devices.map((record) => record.state)).toEqual(["ready"]); + expect(view.leaseRequests().map((request) => request.state)).toEqual(["open"]); + } + }); + + it("a commit that throws in SQLite leaves snapshot and the commit listeners as before the call, and the caller's promise rejects", async () => { + const { readyDevice, registry, state } = await world(); + const device = await readyDevice("fk-throw"); + const committed: string[] = []; + registry.onCommit(() => committed.push("commit")); + const before = registry.snapshot; + state.database.exec( + "CREATE TRIGGER no_leases BEFORE INSERT ON leases BEGIN SELECT RAISE(ABORT, 'disk full'); END", + ); + + await expect( + registry.createLease({ + deviceId: device.id, + ownerId: "agent-1", + requesterId: "agent-1", + ttlDeadline: 5_000, + ttlMs: 4_000, + }), + ).rejects.toThrow("disk full"); + + expect(registry.snapshot).toEqual(before); + expect(committed).toEqual([]); + expect(state.database.prepare("SELECT state FROM devices").all()).toEqual([{ state: "ready" }]); + state.database.exec("DROP TRIGGER no_leases"); + await registry.createLease({ + deviceId: device.id, + ownerId: "agent-1", + requesterId: "agent-1", + ttlDeadline: 5_000, + ttlMs: 4_000, + }); + expect(committed).toEqual(["commit"]); + }); + + it("pruning deletes the rows of dropped requests and their grant and environment rows, past the retention and past the record cap", async () => { + const counts = (state: StateDatabase) => + ["lease_requests", "lease_grants", "lease_grant_environment"].map( + (table) => state.database.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()?.n, + ); + const ask = (registry: Registry, id: string) => + registry.createLeaseRequest({ + id, + ownerId: "agent-1", + request: { platform: "ios" }, + requesterId: "agent-1", + }); + + const aged = await world({ leaseRequestLimits: { maxRecords: 10, retentionMs: 1_000 } }); + const device = await aged.readyDevice("fk-aged"); + await ask(aged.registry, "req_old"); + await aged.registry.createLease({ + deviceId: device.id, + ownerId: "agent-1", + request: { + environment: { SIMLOCK_UDID: "abc", OTHER: "x" }, + id: "req_old", + timing: { + estimatedBootMs: 2, + estimatedProvisionMs: 1, + estimatedReadyMs: 4, + estimatedReclaimMs: 3, + }, + }, + requesterId: "agent-1", + ttlDeadline: 5_000, + ttlMs: 4_000, + }); + expect(counts(aged.state)).toEqual([1, 1, 2]); + aged.clock.advance(999); + await ask(aged.registry, "req_new"); + expect(counts(aged.state)).toEqual([2, 1, 2]); + aged.clock.advance(2); + await ask(aged.registry, "req_newer"); + expect(counts(aged.state)).toEqual([2, 0, 0]); + expect( + aged.state.database.prepare("SELECT id FROM lease_requests ORDER BY rowid").all(), + ).toEqual([{ id: "req_new" }, { id: "req_newer" }]); + + const capped = await world({ leaseRequestLimits: { maxRecords: 2, retentionMs: 1_000_000 } }); + await ask(capped.registry, "req_a"); + await capped.registry.settleLeaseRequest("req_a", { state: "cancelled" }); + await ask(capped.registry, "req_b"); + await ask(capped.registry, "req_c"); + expect( + capped.state.database.prepare("SELECT id FROM lease_requests ORDER BY rowid").all(), + ).toEqual([{ id: "req_b" }, { id: "req_c" }]); + }); + + it("a replayed answer's device is the current device record, before and after a restart, while its lease, environment and timing are as first granted", async () => { + const { open, readyDevice, registry, state } = await world(); + const device = await readyDevice("fk-replay"); + await registry.createLeaseRequest({ + id: "req_replay", + ownerId: "agent-1", + request: { platform: "ios" }, + requesterId: "agent-1", + }); + const timing = { + estimatedBootMs: 2, + estimatedProvisionMs: 1, + estimatedReadyMs: 4, + estimatedReclaimMs: 3, + }; + const lease = await registry.createLease({ + deviceId: device.id, + ownerId: "agent-1", + request: { environment: { SIMLOCK_UDID: "abc" }, id: "req_replay", timing }, + requesterId: "agent-1", + ttlDeadline: 5_000, + ttlMs: 4_000, + }); + expect(registry.leaseRequests()[0]?.grant?.device.state).toBe("leased"); + await registry.beginRelease(lease.id); + + const restarted = await open({ generate: () => "after" }); + for (const view of [registry, restarted]) { + const grant = view.leaseRequests()[0]?.grant; + expect(grant?.device).toMatchObject({ id: device.id, state: "reclaiming" }); + expect(grant?.lease).toEqual(lease); + expect(grant?.environment).toEqual({ SIMLOCK_UDID: "abc" }); + expect(grant?.timing).toEqual(timing); + } + expect(state.database.prepare("SELECT COUNT(*) AS n FROM lease_grants").get()?.n).toBe(1); + }); + + it("load refuses with RegistryLoadError naming the table and key for a virtual device with no device-data row, a device whose platform has no table, a grant naming a missing device and a state outside its type", async () => { + const reload = (state: StateDatabase, platforms: readonly Platform[] = ["ios", "android"]) => + Registry.load({ + clock: new FakeClock(1_000), + deviceData: new Map(platforms.map((platform) => [platform, fakeDeviceDataTable])), + eventBus: new EventBus(new FakeClock(1_000)), + idGenerator: { generate: () => "z" }, + state, + }); + const grantedWorld = async () => { + const built = await world(); + const device = await built.readyDevice("fk-load"); + await built.registry.createLeaseRequest({ + id: "req_load", + ownerId: "agent-1", + request: { platform: "ios" }, + requesterId: "agent-1", + }); + await built.registry.createLease({ + deviceId: device.id, + ownerId: "agent-1", + request: { + environment: {}, + id: "req_load", + timing: { + estimatedBootMs: 0, + estimatedProvisionMs: 0, + estimatedReadyMs: 0, + estimatedReclaimMs: 0, + }, + }, + requesterId: "agent-1", + ttlDeadline: 5_000, + ttlMs: 4_000, + }); + return { ...built, deviceId: device.id }; + }; + + const cases: { + readonly corrupt: (state: StateDatabase, deviceId: string) => void; + readonly platforms?: readonly Platform[]; + readonly message: (deviceId: string) => RegExp; + }[] = [ + { + corrupt: (state, deviceId) => + state.database.prepare("DELETE FROM fake_device_data WHERE device_id = ?").run(deviceId), + message: (deviceId) => new RegExp(`devices row ${deviceId}`), + }, + { + corrupt: () => undefined, + message: (deviceId) => new RegExp(`devices row ${deviceId}`), + platforms: ["android"], + }, + { + corrupt: (state, deviceId) => { + state.database.exec("PRAGMA foreign_keys=OFF"); + state.database.prepare("DELETE FROM fake_device_data WHERE device_id = ?").run(deviceId); + state.database.prepare("DELETE FROM devices WHERE id = ?").run(deviceId); + }, + message: () => /lease_grants row req_load/, + }, + { + corrupt: (state, deviceId) => + state.database.prepare("UPDATE devices SET state = 'warm' WHERE id = ?").run(deviceId), + message: (deviceId) => new RegExp(`devices row ${deviceId}`), + }, + ]; + for (const { corrupt, message, platforms } of cases) { + const { deviceId, state } = await grantedWorld(); + await expect(reload(state)).resolves.toBeInstanceOf(Registry); + corrupt(state, deviceId); + const refusal = await reload(state, platforms).catch((error: unknown) => error); + expect(refusal).toBeInstanceOf(RegistryLoadError); + expect((refusal as Error).message).toMatch(message(deviceId)); + } + }); + + it("a physical device loads with empty driver data and has no device-data row", async () => { + const { open, readyDevice, registry, state } = await world(); + const virtual = await readyDevice("fk-virtual"); + const physical = await registry.enrollPhysical({ + apps: ["com.a"], + class: "phone", + driverDeviceId: "udid-1", + model: "iPhone 15", + osVersion: "18.4", + platform: "ios", + }); + + const restarted = await open({ generate: () => "later" }); + + expect(restarted.snapshot.devices.find((device) => device.id === physical.id)).toMatchObject({ + driverData: {}, + physical: true, + }); + expect(state.database.prepare("SELECT device_id FROM fake_device_data").all()).toEqual([ + { device_id: virtual.id }, + ]); + }); + + it("two transitions of two devices started in one tick both persist, in memory and after a restart", async () => { + const { open, readyDevice, registry } = await world(); + const first = await readyDevice("fk-first"); + const second = await readyDevice("fk-second"); + const shutdown = (id: string) => + registry.transitionDevice(id, "shutdown", { + event: "device.shutdown", + payload: { deviceId: id, initiator: "idle" }, + }); + + await Promise.all([shutdown(first.id), shutdown(second.id)]); + + const restarted = await open({ generate: () => "later" }); + for (const view of [registry, restarted]) { + expect(view.snapshot.devices.map((device) => device.state)).toEqual(["shutdown", "shutdown"]); + } + }); +}); diff --git a/src/core/registry.ts b/src/core/registry.ts index 82d101697..863ba306e 100644 --- a/src/core/registry.ts +++ b/src/core/registry.ts @@ -1,16 +1,9 @@ import type { EventBus, EventMap } from "../bus/index.js"; -import { quarantineCauseSchema } from "../contract/index.js"; -import type { Clock, Filesystem, IdGenerator } from "../ports/index.js"; -import { - DEFAULT_LEASE_MAX_REQUEST_RECORDS, - DEFAULT_LEASE_REQUEST_RETENTION_MS, - DEFAULT_LEASE_TTL_MS, -} from "./config.js"; +import type { Clock, IdGenerator } from "../ports/index.js"; +import type { StateDatabase } from "../state/index.js"; +import { DEFAULT_LEASE_MAX_REQUEST_RECORDS, DEFAULT_LEASE_REQUEST_RETENTION_MS } from "./config.js"; import { type AbsentReason, - DEVICE_CLASSES, - type DeviceClass, - type DeviceMode, type DeviceRecord, type QuarantineCause, type DeviceState, @@ -22,18 +15,14 @@ import { type LeaseRecord, type LeaseRequestFailure, type LeaseRequestRecord, - type LeaseRequestState, type PhysicalClass, type PhysicalDevice, - type PhysicalSpec, - type PhysicalState, type Platform, transition, type VirtualDevice, type VirtualSpec, - type VirtualState, } from "./domain.js"; -import type { ComponentReceipt, DeviceRequest } from "./driver.js"; +import type { ComponentReceipt, DeviceDataTable } from "./driver.js"; import { type LeaseRequestLimits, type LeaseRequestOutcome, @@ -45,22 +34,23 @@ import { withNewLeaseRequest, withSettledLeaseRequest, } from "./lease-request-store.js"; - -const DEFAULT_REGISTRY_PATH = "~/.simlock/state.json"; +import { + deleteComponentRows, + deleteLease, + deleteLeaseRequest, + loadRegistryRows, + writeComponent, + writeDevice, + writeLease, + writeLeaseRequest, +} from "./registry-rows.js"; export interface RegistryOptions { - readonly filesystem: Filesystem; readonly clock: Clock; readonly idGenerator: IdGenerator; readonly eventBus: EventBus; - readonly statePath?: string; - /** - * The width a lease record written before ADR 0004 loads with, since it has none of its own - * (`lease.defaultTtlMs`; the daemon passes the configured value, and `DEFAULT_LEASE_TTL_MS` - * stands in for a caller that has no config to hand). Only ever read during that migration -- - * a granted lease's width always comes from the grant itself. - */ - readonly defaultTtlMs?: number; + readonly state: StateDatabase; + readonly deviceData: ReadonlyMap; /** * `lease.identity`: the policy a newly registered device is stamped with, looked up by its * spec's platform. Only registration reads it -- a loaded record keeps the policy it was @@ -152,13 +142,6 @@ export type RegistryDeviceEvent = readonly payload: Omit; }; -class RegistryLoadError extends Error { - constructor(message: string) { - super(message); - this.name = "RegistryLoadError"; - } -} - export class UnknownDeviceError extends Error { constructor(readonly deviceId: string) { super(`Unknown device: ${deviceId}`); @@ -191,29 +174,23 @@ export class Registry implements LeaseRequestStore { #leaseRequests: readonly LeaseRequestRecord[] = []; #components: readonly ComponentRecord[] = []; readonly #commitListeners: (() => void)[] = []; - #unknownState: Record = {}; - readonly #unknownDeviceFields = new Map>(); - readonly #unknownLeaseFields = new Map>(); - readonly #unknownLeaseRequestFields = new Map>(); private constructor(private readonly options: Required) {} static async load(options: RegistryOptions): Promise { const registry = new Registry({ ...options, - defaultTtlMs: options.defaultTtlMs ?? DEFAULT_LEASE_TTL_MS, leaseIdentity: options.leaseIdentity ?? { android: "reusable", ios: "reusable" }, leaseRequestLimits: options.leaseRequestLimits ?? { maxRecords: DEFAULT_LEASE_MAX_REQUEST_RECORDS, retentionMs: DEFAULT_LEASE_REQUEST_RETENTION_MS, }, - statePath: options.statePath ?? DEFAULT_REGISTRY_PATH, }); - - if (await registry.options.filesystem.exists(registry.options.statePath)) { - registry.#restore(await registry.options.filesystem.readFile(registry.options.statePath)); - } - + const loaded = loadRegistryRows(options.state.database, options.deviceData); + registry.#devices = loaded.devices; + registry.#leases = loaded.leases; + registry.#leaseRequests = loaded.leaseRequests; + registry.#components = loaded.components; return registry; } @@ -242,7 +219,7 @@ export class Registry implements LeaseRequestStore { ), cloneComponent(record), ]; - await this.#commit(this.#devices, this.#leases, this.#leaseRequests, components); + this.#commit(this.#devices, this.#leases, this.#leaseRequests, components); } /** @@ -255,7 +232,7 @@ export class Registry implements LeaseRequestStore { (existing) => existing.platform !== platform || existing.version !== version, ); if (components.length === this.#components.length) return; - await this.#commit(this.#devices, this.#leases, this.#leaseRequests, components); + this.#commit(this.#devices, this.#leases, this.#leaseRequests, components); } async registerDevice({ @@ -277,7 +254,7 @@ export class Registry implements LeaseRequestStore { }; const devices = [...this.#devices, record]; - await this.#commit(devices, this.#leases); + this.#commit(devices, this.#leases); this.options.eventBus.emit( "device.provisioned", { @@ -308,7 +285,7 @@ export class Registry implements LeaseRequestStore { const updated = this.#transitioned(device, to, update); const devices = [...this.#devices]; devices[index] = updated; - await this.#commit(devices, this.#leases); + this.#commit(devices, this.#leases); if (event !== undefined) { this.#emitDeviceEvent(event, updated); @@ -325,7 +302,7 @@ export class Registry implements LeaseRequestStore { const updated = this.#transitioned(device, "shutdown"); const devices = [...this.#devices]; devices[index] = updated; - await this.#commit(devices, this.#leases); + this.#commit(devices, this.#leases); return cloneDevice(updated); } @@ -361,7 +338,7 @@ export class Registry implements LeaseRequestStore { }; const devices = [...this.#devices]; devices[index] = updated; - await this.#commit(devices, this.#leases); + this.#commit(devices, this.#leases); return cloneDevice(updated); } @@ -382,7 +359,7 @@ export class Registry implements LeaseRequestStore { }; const devices = [...this.#devices]; devices[index] = updated; - await this.#commit(devices, this.#leases); + this.#commit(devices, this.#leases); return cloneDevice(updated); } @@ -413,7 +390,7 @@ export class Registry implements LeaseRequestStore { } = this.#transitioned(device, to); const devices = [...this.#devices]; devices[index] = updated as DeviceRecord; - await this.#commit(devices, this.#leases); + this.#commit(devices, this.#leases); return this.#committed(deviceId); } @@ -434,7 +411,7 @@ export class Registry implements LeaseRequestStore { const updated: DeviceRecord = { ...rest, quarantineAttempts: attempts }; const devices = [...this.#devices]; devices[index] = updated; - await this.#commit(devices, this.#leases); + this.#commit(devices, this.#leases); return cloneDevice(updated); } @@ -451,7 +428,7 @@ export class Registry implements LeaseRequestStore { } = this.#transitioned(device, "deleted"); const devices = [...this.#devices]; devices[index] = updated as DeviceRecord; - await this.#commit(devices, this.#leases); + this.#commit(devices, this.#leases); this.options.eventBus.emit( "device.deleted", { deviceId, initiator, physical: device.physical }, @@ -462,15 +439,15 @@ export class Registry implements LeaseRequestStore { async markForeignStateDetected(deviceId: string, at: number): Promise { const { device, index } = this.#requireDeviceRecord(deviceId); - // Doctor re-reports persistent drift on every reaper tick; keep the first-detected - // timestamp and skip the commit so a flagged device stops rewriting state.json. + // why: Doctor re-reports persistent drift on every reaper tick; keep the first-detected + // timestamp and skip the commit so a flagged device stops rewriting its row. if (device.foreignStateDetectedAt !== undefined) { return cloneDevice(device); } const updated = { ...device, foreignStateDetectedAt: at }; const devices = [...this.#devices]; devices[index] = updated; - await this.#commit(devices, this.#leases); + this.#commit(devices, this.#leases); return cloneDevice(updated); } @@ -482,7 +459,7 @@ export class Registry implements LeaseRequestStore { const updated = { ...device, foreignProvenanceDetectedAt: at }; const devices = [...this.#devices]; devices[index] = updated; - await this.#commit(devices, this.#leases); + this.#commit(devices, this.#leases); return cloneDevice(updated); } @@ -496,7 +473,7 @@ export class Registry implements LeaseRequestStore { const updated = rest as DeviceRecord; const devices = [...this.#devices]; devices[index] = updated; - await this.#commit(devices, this.#leases); + this.#commit(devices, this.#leases); return cloneDevice(updated); } @@ -510,7 +487,7 @@ export class Registry implements LeaseRequestStore { }; const devices = [...this.#devices]; devices[index] = updated; - await this.#commit(devices, this.#leases); + this.#commit(devices, this.#leases); return cloneDevice(updated); } @@ -528,7 +505,7 @@ export class Registry implements LeaseRequestStore { const updated = rest as DeviceRecord; const devices = [...this.#devices]; devices[index] = updated; - await this.#commit(devices, this.#leases); + this.#commit(devices, this.#leases); return cloneDevice(updated); } @@ -540,7 +517,7 @@ export class Registry implements LeaseRequestStore { if (device.state === "deleted") { return cloneDevice(device); } - await this.#commitMissing(device, this.#leases); + this.#commitMissing(device, this.#leases); this.options.eventBus.emit( "device.deleted", { deviceId, initiator, physical: device.physical }, @@ -568,7 +545,7 @@ export class Registry implements LeaseRequestStore { throw new UnknownLeaseError(leaseId); } const { device } = this.#requireDeviceRecord(lease.deviceId); - const deleted = await this.#commitMissing( + const deleted = this.#commitMissing( device, this.#leases.filter((candidate) => candidate.id !== leaseId), ); @@ -599,7 +576,7 @@ export class Registry implements LeaseRequestStore { }; const devices = [...this.#devices]; devices[index] = absent; - await this.#commit( + this.#commit( devices, this.#leases.filter((candidate) => candidate.id !== leaseId), ); @@ -621,7 +598,7 @@ export class Registry implements LeaseRequestStore { const updated: PhysicalDevice = { ...device, absentReason }; const devices = [...this.#devices]; devices[index] = updated; - await this.#commit(devices, this.#leases); + this.#commit(devices, this.#leases); return cloneDevice(updated); } @@ -629,7 +606,7 @@ export class Registry implements LeaseRequestStore { * The one place a device is written as missing. Recovery markers go with it: a deleted device * has no recovery to track, and a stale count would only mislead a reader of the record. */ - async #commitMissing(device: DeviceRecord, leases: LeaseRecord[]): Promise { + #commitMissing(device: DeviceRecord, leases: LeaseRecord[]): DeviceRecord { // A physical record is never written as missing: that would unenrol it (ADR 0022 §4). if (device.physical) { throw new RegistryEventError(`Cannot mark a physical device missing: ${device.id}`); @@ -644,7 +621,7 @@ export class Registry implements LeaseRequestStore { const devices = this.#devices.map((candidate) => candidate.id === device.id ? deleted : candidate, ); - await this.#commit(devices, leases); + this.#commit(devices, leases); return deleted; } @@ -667,7 +644,7 @@ export class Registry implements LeaseRequestStore { }, state: "ready", }; - await this.#commit([...this.#devices, record], this.#leases); + this.#commit([...this.#devices, record], this.#leases); this.#emitEnrolled(record, false); return cloneDevice(record) as PhysicalDevice; } @@ -710,7 +687,7 @@ export class Registry implements LeaseRequestStore { }; const devices = [...this.#devices]; devices[index] = updated; - await this.#commit(devices, this.#leases); + this.#commit(devices, this.#leases); this.#emitEnrolled(updated, true); return this.#committed(deviceId) as PhysicalDevice; } @@ -735,7 +712,7 @@ export class Registry implements LeaseRequestStore { } const devices = [...this.#devices]; devices[index] = updated; - await this.#commit(devices, this.#leases); + this.#commit(devices, this.#leases); this.options.eventBus.emit( "device.deleted", { deviceId, initiator: "operator", physical: true }, @@ -819,7 +796,7 @@ export class Registry implements LeaseRequestStore { }, grantedAt, ).records; - await this.#commit(devices, [...this.#leases, lease], leaseRequests); + this.#commit(devices, [...this.#leases, lease], leaseRequests); return cloneLease(lease); } @@ -853,7 +830,7 @@ export class Registry implements LeaseRequestStore { const devices = [...this.#devices]; devices[deviceIndex] = reclaiming; const leases = this.#leases.filter((candidate) => candidate.id !== leaseId); - await this.#commit(devices, leases); + this.#commit(devices, leases); return { device: cloneDevice(reclaiming), lease: cloneLease(lease) }; } @@ -873,7 +850,7 @@ export class Registry implements LeaseRequestStore { const renewed = { ...lease, lastRenewedAt: this.options.clock.now(), ttlDeadline, ttlMs }; const leases = [...this.#leases]; leases[index] = renewed; - await this.#commit(this.#devices, leases); + this.#commit(this.#devices, leases); return cloneLease(renewed); } @@ -882,7 +859,18 @@ export class Registry implements LeaseRequestStore { this.#leaseRequests, this.options.clock.now(), this.options.leaseRequestLimits.retentionMs, - ).map(cloneLeaseRequest); + ).map((record) => this.#withCurrentDevice(record)); + } + + /** why: a granted request stores the lease, environment and timing as first answered, but names its device only by id (ADR 0036 §4). */ + #withCurrentDevice(record: LeaseRequestRecord): LeaseRequestRecord { + const copy = cloneLeaseRequest(record); + if (copy.grant === undefined) return copy; + const { grant } = copy; + const device = this.#devices.find((candidate) => candidate.id === grant.device.id); + return device === undefined + ? copy + : { ...copy, grant: { ...grant, device: cloneDevice(device) } }; } async createLeaseRequest(input: NewLeaseRequest): Promise { @@ -898,7 +886,7 @@ export class Registry implements LeaseRequestStore { now, this.options.leaseRequestLimits, ); - await this.#commit(this.#devices, this.#leases, leaseRequests); + this.#commit(this.#devices, this.#leases, leaseRequests); return cloneLeaseRequest(record); } @@ -913,8 +901,8 @@ export class Registry implements LeaseRequestStore { this.options.clock.now(), ); if (settled === undefined) return undefined; - await this.#commit(this.#devices, this.#leases, records); - return cloneLeaseRequest(settled); + this.#commit(this.#devices, this.#leases, records); + return this.#withCurrentDevice(settled); } /** @@ -934,8 +922,8 @@ export class Registry implements LeaseRequestStore { records = result.records; if (result.settled !== undefined) settled.push(result.settled); } - if (settled.length > 0) await this.#commit(this.#devices, this.#leases, records); - return settled.map(cloneLeaseRequest); + if (settled.length > 0) this.#commit(this.#devices, this.#leases, records); + return settled.map((record) => this.#withCurrentDevice(record)); } /** why: the exits return the committed record, which has dropped any cause. */ @@ -955,37 +943,31 @@ export class Registry implements LeaseRequestStore { return { device, index }; } - async #commit( + #commit( devices: DeviceRecord[], leases: LeaseRecord[], leaseRequests: readonly LeaseRequestRecord[] = this.#leaseRequests, components: readonly ComponentRecord[] = this.#components, - ): Promise { - await this.options.filesystem.mkdirp(parentDirectory(this.options.statePath)); + ): void { const committed = devices.map(withoutCauseUnlessQuarantined); - await this.options.filesystem.writeFileAtomic( - this.options.statePath, - JSON.stringify({ - ...this.#unknownState, - devices: committed - .filter(isVirtual) - .map((device) => ({ ...this.#unknownDeviceFields.get(device.id), ...stored(device) })), - physicalDevices: committed.filter(isPhysical).map((device) => ({ - ...this.#unknownDeviceFields.get(device.id), - ...device, - })), - leases: leases.map((lease) => ({ - ...this.#unknownLeaseFields.get(lease.id), - ...lease, - })), - leaseRequests: leaseRequests.map((record) => ({ - ...this.#unknownLeaseRequestFields.get(record.id), - ...record, - })), - components, - }), - { mode: 0o600 }, - ); + const { deviceData, state } = this.options; + state.transaction(() => { + const { database } = state; + const device = changes(this.#devices, committed, (record) => record.id); + const lease = changes(this.#leases, leases, (record) => record.id); + const request = changes(this.#leaseRequests, leaseRequests, (record) => record.id); + const component = changes(this.#components, components, componentKey); + for (const id of request.removed) deleteLeaseRequest(database, id); + for (const record of device.changed) writeDevice(database, record, deviceData); + for (const id of lease.removed) deleteLease(database, id); + for (const record of lease.changed) writeLease(database, record); + for (const record of request.changed) writeLeaseRequest(database, record); + for (const key of component.removed) { + const [platform, version] = key.split("\0") as [Platform, string]; + deleteComponentRows(database, platform, version); + } + for (const record of component.changed) writeComponent(database, record); + }); this.#devices = committed; this.#leases = leases; this.#leaseRequests = leaseRequests; @@ -994,82 +976,10 @@ export class Registry implements LeaseRequestStore { } /** Calls `listener` after every commit, once the new state is what `snapshot` reads. */ - // fallow-ignore-next-line unused-class-member -- called by createCore, which holds the registry as a `Registry`; the audit does not follow it. onCommit(listener: () => void): void { this.#commitListeners.push(listener); } - #restore(contents: string): void { - let parsed: unknown; - try { - parsed = JSON.parse(contents) as unknown; - } catch { - throw new RegistryLoadError(`Invalid JSON in registry state: ${this.options.statePath}`); - } - - if (!isObject(parsed) || !Array.isArray(parsed.devices) || !Array.isArray(parsed.leases)) { - throw new RegistryLoadError(`Invalid registry state: ${this.options.statePath}`); - } - - if (parsed.physicalDevices !== undefined && !Array.isArray(parsed.physicalDevices)) { - throw new RegistryLoadError(`Invalid registry state: ${this.options.statePath}`); - } - - this.#unknownState = unknownFields(parsed, [ - "devices", - "physicalDevices", - "leases", - "leaseRequests", - "components", - ]); - const restore = (device: unknown, physical: boolean): DeviceRecord => { - const record = parseDevice(device, physical); - this.#unknownDeviceFields.set( - record.id, - unknownFields(device as Record, [ - ...deviceRecordKeys, - ...retiredDeviceRecordKeys, - ]), - ); - return record; - }; - this.#devices = [ - ...parsed.devices.map((device) => restore(device, false)), - ...((parsed.physicalDevices ?? []) as unknown[]).map((device) => restore(device, true)), - ]; - this.#leases = parsed.leases.map((lease) => { - const record = parseLease(lease, this.options.defaultTtlMs); - this.#unknownLeaseFields.set( - record.id, - unknownFields(lease, [...leaseRecordKeys, ...retiredLeaseRecordKeys]), - ); - return record; - }); - this.#leaseRequests = this.#restoreLeaseRequests(parsed.leaseRequests); - this.#components = restoreComponents(parsed.components); - } - - /** - * A state file written before lease requests were stored has no `leaseRequests` key and loads - * with none, and so does one whose key is not a list. A record that does not parse is dropped rather than failing the load: a request - * is not worth every device Simlock knows about, and a client repeating a dropped request - * simply starts a new one. - */ - #restoreLeaseRequests(value: unknown): LeaseRequestRecord[] { - if (!Array.isArray(value)) return []; - const records: LeaseRequestRecord[] = []; - for (const candidate of value) { - const record = parseLeaseRequest(candidate); - if (record === undefined) continue; - this.#unknownLeaseRequestFields.set( - record.id, - unknownFields(candidate as Record, leaseRequestRecordKeys), - ); - records.push(record); - } - return records; - } - #emitDeviceEvent(event: RegistryDeviceEvent, device: DeviceRecord): void { switch (event.event) { case "device.ready": @@ -1101,66 +1011,23 @@ export class Registry implements LeaseRequestStore { } } -const deviceRecordKeys = [ - "id", - "driverDeviceId", - "spec", - "state", - "driverData", - "createdAt", - "lastLeaseEndedAt", - "readyAt", - "shutdownAt", - "foreignStateDetectedAt", - "foreignProvenanceDetectedAt", - "recoveringSince", - "recoveryAttempts", - "deferredReclaimLeaseId", - "quarantinedAt", - "quarantineAttempts", - "quarantineNextRetryAt", - "quarantineCause", - "address", - "mode", - "leaseIdentity", - "physical", - "enrolledApps", - "reclaimingSince", - "absentReason", -] as const; -const retiredDeviceRecordKeys = ["featureProfile"] as const; -const leaseRecordKeys = [ - "id", - "deviceId", - "requesterId", - "ownerId", - "grantedAt", - "ttlMs", - "ttlDeadline", - "lastRenewedAt", - "idChosenByRequester", -] as const; -const leaseRequestRecordKeys = [ - "id", - "requesterId", - "ownerId", - "idempotencyKey", - "leaseId", - "fleetRequestId", - "request", - "createdAt", - "state", - "settledAt", - "grant", - "failure", -] as const; -/** - * Fields a lease record written before ADR 0004 carries that this daemon neither reads nor - * keeps. Listed here so they are stripped on load rather than preserved through the - * unknown-field forward-compatibility path -- `mode` is not a field from a *newer* schema this - * daemon should hand back untouched, it is a concept that no longer exists. - */ -const retiredLeaseRecordKeys = ["mode"] as const; +function componentKey(record: ComponentRecord): string { + return `${record.platform}\0${record.version}`; +} + +/** why: records are immutable, so a record that is not the committed object has changed and one that is not in `after` is gone. */ +function changes( + before: readonly T[], + after: readonly T[], + keyOf: (record: T) => string, +): { readonly changed: T[]; readonly removed: string[] } { + const committed = new Map(before.map((record) => [keyOf(record), record])); + const kept = new Set(after.map(keyOf)); + return { + changed: after.filter((record) => committed.get(keyOf(record)) !== record), + removed: [...committed.keys()].filter((key) => !kept.has(key)), + }; +} function cloneDevice(device: T): T { return { ...device, spec: { ...device.spec } } as T; @@ -1170,20 +1037,6 @@ function isVirtual(device: DeviceRecord): device is VirtualDevice { return !device.physical; } -function isPhysical(device: DeviceRecord): device is PhysicalDevice { - return device.physical; -} - -/** - * A virtual record as `devices` holds it: with no `physical` key on the record or its spec, so - * the file reads the same to an older Simlock as it did before physical devices existed. - */ -function stored(device: VirtualDevice): Record { - const { physical: _physical, spec, ...record } = device; - const { physical: _specPhysical, ...storedSpec } = spec; - return { ...record, spec: storedSpec }; -} - /** why: the one place a cause goes when its device leaves quarantine, however it left. */ function withoutCauseUnlessQuarantined(device: DeviceRecord): DeviceRecord { if (device.state === "quarantined" || device.quarantineCause === undefined) return device; @@ -1199,48 +1052,10 @@ function cloneComponent(record: ComponentRecord): ComponentRecord { return { ...record, receipt: { ...record.receipt } }; } -/** - * A state file written before components were recorded has no `components` key and loads with - * none. A record that does not parse is dropped rather than failing the load, like a lease - * request: losing it only means Simlock no longer claims that component, which errs towards - * never removing it (safety rule 1). - */ -function restoreComponents(value: unknown): ComponentRecord[] { - if (!Array.isArray(value)) return []; - return value.flatMap((candidate: unknown) => { - const record = parseComponent(candidate); - return record === undefined ? [] : [record]; - }); -} - -function parseComponent(value: unknown): ComponentRecord | undefined { - if ( - !isObject(value) || - !isPlatform(value.platform) || - typeof value.version !== "string" || - typeof value.installedAt !== "number" || - !isObject(value.receipt) || - !Object.values(value.receipt).every((field) => typeof field === "string") - ) { - return undefined; - } - return { - installedAt: value.installedAt, - platform: value.platform, - receipt: { ...(value.receipt as Record) }, - version: value.version, - }; -} - function cloneLeaseRequest(record: LeaseRequestRecord): LeaseRequestRecord { return { ...record, request: { ...record.request } }; } -function parentDirectory(path: string): string { - const separator = path.lastIndexOf("/"); - return separator <= 0 ? "/" : path.slice(0, separator); -} - /** The one device event a transition carries must be the one its states call for, about this device. */ function assertTransitionEvent( device: DeviceRecord, @@ -1282,522 +1097,3 @@ function eventForTransition( } return undefined; } - -/** - * why: parsed as one group so `parseDevice`'s required-field check does not grow two branches per - * field added. - */ -const optionalDeviceNumberKeys = [ - "lastLeaseEndedAt", - "readyAt", - "shutdownAt", - "foreignStateDetectedAt", - "foreignProvenanceDetectedAt", - "recoveringSince", - "recoveryAttempts", - "quarantinedAt", - "quarantineAttempts", - "quarantineNextRetryAt", -] as const; - -type OptionalDeviceNumbers = Partial>; - -function parseOptionalDeviceNumbers(value: Record): OptionalDeviceNumbers { - const parsed: OptionalDeviceNumbers = {}; - for (const key of optionalDeviceNumberKeys) { - const candidate = value[key]; - if (candidate === undefined) continue; - if (typeof candidate !== "number") { - throw new RegistryLoadError("Invalid device record in registry state"); - } - parsed[key] = candidate; - } - return parsed; -} - -function parseDevice(value: unknown, physical: boolean): DeviceRecord { - if (!isObject(value)) { - throw new RegistryLoadError("Invalid device record in registry state"); - } - - const { spec, state } = value; - if (!isObject(spec)) { - throw new RegistryLoadError("Invalid device record in registry state"); - } - const shared = parseSharedDeviceFields(value); - const record = physical - ? parsePhysicalDevice(value, spec, state, shared) - : parseVirtualDevice(value, spec, state, shared); - // why: a cause is for a quarantined record alone; on any other it is dropped unchecked. - if (record.state !== "quarantined" || value.quarantineCause === undefined) return record; - const cause = quarantineCauseSchema.safeParse(value.quarantineCause); - if (!cause.success) throw new RegistryLoadError("Invalid device record in registry state"); - return { ...record, quarantineCause: cause.data }; -} - -/** What a record in `devices` and one in `physicalDevices` both carry, checked once. */ -function parseSharedDeviceFields(value: Record): SharedDeviceFields { - const { address, createdAt, deferredReclaimLeaseId, driverData, driverDeviceId, id } = value; - if ( - typeof id !== "string" || - typeof driverDeviceId !== "string" || - typeof createdAt !== "number" || - !("driverData" in value) || - // Every other optional field is a number and is swept by - // `parseOptionalDeviceNumbers`, except `leaseIdentity`, which `parseLeaseIdentity` checks; - // `address` and `deferredReclaimLeaseId` are the strings checked here. - // Missing is expected of a record written by a daemon that predates the field; - // present-but-wrong-typed is corrupt. - !isOptionalString(address) || - !isOptionalString(deferredReclaimLeaseId) - ) { - throw new RegistryLoadError("Invalid device record in registry state"); - } - return { - ...parseOptionalDeviceNumbers(value), - ...(address === undefined ? {} : { address }), - ...(deferredReclaimLeaseId === undefined ? {} : { deferredReclaimLeaseId }), - createdAt, - driverData, - driverDeviceId, - id, - }; -} - -type SharedDeviceFields = Omit< - VirtualDevice, - "leaseIdentity" | "mode" | "physical" | "spec" | "state" ->; - -/** A record in `devices` is virtual: `physical` and a class are for `physicalDevices` alone. */ -function parseVirtualDevice( - value: Record, - spec: Record, - state: unknown, - shared: SharedDeviceFields, -): VirtualDevice { - const virtualState = state === "warm" ? "reclaiming" : state; - if ( - !isVirtualState(virtualState) || - (value.physical !== undefined && value.physical !== false) || - (spec.physical !== undefined && spec.physical !== false) || - "class" in spec - ) { - throw new RegistryLoadError("Invalid device record in registry state"); - } - return { - ...shared, - leaseIdentity: parseLeaseIdentity(value.leaseIdentity), - mode: parseDeviceMode(value.mode), - physical: false, - spec: parseVirtualSpec(spec), - state: virtualState, - }; -} - -/** A record in `physicalDevices` must be physical through and through (ADR 0022 §1). */ -function parsePhysicalDevice( - value: Record, - spec: Record, - state: unknown, - shared: SharedDeviceFields, -): PhysicalDevice { - const { enrolledApps } = value; - if ( - !isPhysicalState(state) || - value.physical !== true || - value.mode !== undefined || - value.leaseIdentity !== undefined || - !Array.isArray(enrolledApps) || - !enrolledApps.every((app) => typeof app === "string") - ) { - throw new RegistryLoadError("Invalid device record in registry state"); - } - return { - ...shared, - enrolledApps: [...(enrolledApps as string[])], - physical: true, - ...parsePhysicalMarks(state, value), - spec: parsePhysicalSpec(spec), - state, - }; -} - -function parsePhysicalMarks( - state: PhysicalState, - value: Record, -): Pick { - const { absentReason, reclaimingSince } = value; - const absent = state === "absent" ? isAbsentReason(absentReason) : absentReason === undefined; - if (!absent || !isOptionalNumber(reclaimingSince)) { - throw new RegistryLoadError("Invalid device record in registry state"); - } - return { - ...(reclaimingSince === undefined ? {} : { reclaimingSince }), - ...(absentReason === undefined ? {} : { absentReason: absentReason as AbsentReason }), - }; -} - -function parsePhysicalSpec(value: Record): PhysicalSpec { - if ( - value.physical !== true || - !isPlatform(value.platform) || - typeof value.model !== "string" || - typeof value.osVersion !== "string" || - !isPhysicalClass(value.class) || - value.mode !== undefined || - value.imageTag !== undefined - ) { - throw new RegistryLoadError("Invalid device record in registry state"); - } - return { - class: value.class, - model: value.model, - osVersion: value.osVersion, - physical: true, - platform: value.platform, - }; -} - -function isPhysicalClass(value: unknown): value is PhysicalClass { - return value === "phone" || value === "tablet"; -} - -/** - * A record written before `leaseIdentity` existed was created under the only policy there was, - * so it loads as `reusable`. A present-but-unknown value fails the load: guessing `reusable` for - * it could hand a fresh identity out for a second lease. - */ -function parseLeaseIdentity(value: unknown): LeaseIdentity { - if (value === undefined) return "reusable"; - if (value === "reusable" || value === "fresh") return value; - throw new RegistryLoadError("Invalid device record in registry state"); -} - -/** - * A record written before `mode` existed loads as `full` (ADR 0007 §11). A present-but-unknown - * value fails the load rather than being guessed at: a wrong `full` would let a slimmed device - * be granted as a full one. - */ -function parseDeviceMode(value: unknown): DeviceMode { - if (value === undefined) return "full"; - if (value === "slim" || value === "full") return value; - throw new RegistryLoadError("Invalid device record in registry state"); -} - -/** - * A spec's planned mode (ADR 0007 §6, §11). A spec written before it existed has none and loads - * as full; its retired `full` key is dropped, so it is not written back. A `mode` other than - * `"slim"` fails the load: no other value can be planned, and guessing could pool a slim device - * with full ones. - */ -function parseVirtualSpec(value: Record): VirtualSpec { - const { full: _retired, ...spec } = value; - if (!isVirtualSpecShape(spec) || (spec.mode !== undefined && spec.mode !== "slim")) { - throw new RegistryLoadError("Invalid device record in registry state"); - } - return { ...spec, physical: false }; -} - -/** - * ADR 0003 §4: a lease record written before `ownerId` existed loads with `ownerId` equal to - * `requesterId`; present-but-wrong-typed is still corrupt, same treatment as every other - * load-time migration in this module (see `address` on `parseDevice`). Split out of - * `parseLease` purely to keep that function's own branch count down -- this check has no - * meaning on its own outside a lease record's already-validated `requesterId`. - */ -function isValidOwnerId(value: unknown): value is string | undefined { - return value === undefined || typeof value === "string"; -} - -/** The required-string and timing fields every lease record has always had -- split out of - * `parseLease` so that function's own branch count reflects only what changes per schema - * version (the `ownerId` migration, and ADR 0004's `ttlMs`/`lastRenewedAt` one), not the whole - * record shape at once. `mode` is deliberately not checked any more: a record written before - * ADR 0004 still carries one, and it is simply dropped on load rather than being a reason to - * refuse the whole registry. */ -function hasValidLeaseCore(value: Record): value is Record & { - id: string; - deviceId: string; - requesterId: string; - grantedAt: number; - ttlDeadline: number; -} { - return ( - typeof value.id === "string" && - typeof value.deviceId === "string" && - typeof value.requesterId === "string" && - typeof value.grantedAt === "number" && - typeof value.ttlDeadline === "number" - ); -} - -/** - * ADR 0004's migration, for the two fields a lease written before it does not have. Neither - * can be recovered from what is on disk (`ttlDeadline - grantedAt` is the grant-time width - * only until the first renewal moves the deadline), so each takes its documented default - * rather than a guess dressed up as arithmetic. A value that is present but unusable takes the - * same default: it is one field of one record, and refusing to load the whole registry over it - * would cost an operator every device Simlock knows about. - * - * They are validated separately because they are different kinds of number. A timestamp only - * has to be a finite number -- any point on the clock is a legitimate answer to "when was this - * last renewed", including zero. A duration additionally has to be positive: a `ttlMs` of `0` - * or a negative one would make every renewal of that lease resolve to a deadline in the past, - * which `LeaseExpiryScheduler` reads as "expire immediately". - */ -function finiteTimestampOr(value: unknown, fallback: number): number { - return typeof value === "number" && Number.isFinite(value) ? value : fallback; -} - -function positiveDurationOr(value: unknown, fallback: number): number { - return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback; -} - -function parseLease(value: unknown, defaultTtlMs: number): LeaseRecord { - if (!isObject(value) || !hasValidLeaseCore(value) || !isValidOwnerId(value.ownerId)) { - throw new RegistryLoadError("Invalid lease record in registry state"); - } - - const { deviceId, grantedAt, id, lastRenewedAt, ownerId, requesterId, ttlDeadline, ttlMs } = - value; - return { - deviceId, - grantedAt, - id, - idChosenByRequester: value.idChosenByRequester === true, - lastRenewedAt: finiteTimestampOr(lastRenewedAt, grantedAt), - ownerId: ownerId ?? requesterId, - requesterId, - ttlDeadline, - ttlMs: positiveDurationOr(ttlMs, defaultTtlMs), - }; -} - -/** - * `undefined` for anything that is not a whole, consistent record: every required field typed, - * and the result its state promises present (see `parseLeaseRequestResult`). - */ -function parseLeaseRequest(value: unknown): LeaseRequestRecord | undefined { - if (!hasLeaseRequestFields(value)) return undefined; - const { - createdAt, - fleetRequestId, - id, - idempotencyKey, - leaseId, - ownerId, - request, - requesterId, - state, - } = value; - const result = parseLeaseRequestResult(state, value); - if (result === undefined) return undefined; - return { - createdAt, - id, - ...(idempotencyKey === undefined ? {} : { idempotencyKey }), - ...(leaseId === undefined ? {} : { leaseId }), - ...(fleetRequestId === undefined ? {} : { fleetRequestId }), - ownerId, - request: withoutRetiredRequestKeys(request), - requesterId, - state, - ...result, - }; -} - -/** The fields every lease-request record has, whatever its state. */ -// fallow-ignore-next-line complexity -- one type guard, one check per field of the record. -function hasLeaseRequestFields(value: unknown): value is Record & { - readonly createdAt: number; - readonly fleetRequestId?: string; - readonly id: string; - readonly idempotencyKey?: string; - readonly leaseId?: string; - readonly ownerId: string; - readonly request: DeviceRequest; - readonly requesterId: string; - readonly state: LeaseRequestState; -} { - return ( - isObject(value) && - typeof value.id === "string" && - typeof value.requesterId === "string" && - typeof value.ownerId === "string" && - isOptionalString(value.idempotencyKey) && - isOptionalString(value.leaseId) && - isOptionalString(value.fleetRequestId) && - isDeviceRequest(value.request) && - typeof value.createdAt === "number" && - isLeaseRequestState(value.state) - ); -} - -/** A settled record's settlement time and the result its state promises: a `granted` record's - * grant, a `failed` one's failure. An open record has none of them. */ -function parseLeaseRequestResult( - state: LeaseRequestState, - value: Record, -): Pick | undefined { - if (state === "open") return {}; - const { failure, grant, settledAt } = value; - if (typeof settledAt !== "number") return undefined; - if (state === "granted") { - const parsed = parseStoredGrant(grant); - return parsed === undefined ? undefined : { grant: parsed, settledAt }; - } - if (state === "failed") { - return isLeaseRequestFailure(failure) ? { failure, settledAt } : undefined; - } - return { settledAt }; -} - -/** - * A stored grant's device follows the device record's own load rule (ADR 0007 §11): no `mode` - * loads as `full`, the retired keys (and the spec's `full`) are dropped, and an unknown `mode` makes the record - * unusable, so it is skipped like any other inconsistent lease request. Its lease loads - * `idChosenByRequester` as a lease record does (`parseLease`). - */ -function parseStoredGrant(grant: unknown): LeaseGrant | undefined { - if (!isObject(grant) || !isObject(grant.device)) return undefined; - const device = storedGrantDevice(grant.device); - if (device === undefined) return undefined; - // A grant written before ADR 0020 names a lease whose ID simlock generated, as every ID then was. - const lease = isObject(grant.lease) - ? { ...grant.lease, idChosenByRequester: grant.lease.idChosenByRequester === true } - : grant.lease; - return { ...grant, device, lease } as unknown as LeaseGrant; -} - -/** - * The device of a stored grant as it loads: the retired keys dropped, a grant written before - * physical devices existed naming a virtual device, and the mode rule of its type. `undefined` - * for one that breaks it: a virtual device with a mode that is not `slim` or `full`, or a - * physical device with any mode at all. - */ -function storedGrantDevice(stored: Record): Record | undefined { - const device: Record = { ...stored }; - for (const key of retiredDeviceRecordKeys) delete device[key]; - device.physical ??= false; - if (isObject(device.spec)) device.spec = storedGrantSpec(device.spec); - if (device.physical !== true) device.mode ??= "full"; - return hasStoredGrantMode(device) ? device : undefined; -} - -/** A stored grant's spec: the retired `full` key dropped, and `physical` false when it has none. */ -function storedGrantSpec(stored: Record): Record { - const { full: _retired, ...spec } = stored; - return { ...spec, physical: spec.physical ?? false }; -} - -/** A virtual device has a `slim` or `full` mode and a physical one has none. */ -function hasStoredGrantMode(device: Record): boolean { - if (device.physical === true) return device.mode === undefined; - return device.mode === "slim" || device.mode === "full"; -} - -function isDeviceRequest(value: unknown): value is DeviceRequest { - return ( - isObject(value) && - isPlatform(value.platform) && - isOptionalString(value.model) && - (value.class === undefined || isDeviceClass(value.class)) && - hasOptionalRequestFields(value) - ); -} - -function hasOptionalRequestFields(value: Record): boolean { - return ( - isOptionalString(value.osVersion) && - (value.mode === undefined || value.mode === "slim" || value.mode === "full") && - isOptionalString(value.imageTag) - ); -} - -function isOptionalNumber(value: unknown): value is number | undefined { - return value === undefined || typeof value === "number"; -} - -function isOptionalString(value: unknown): value is string | undefined { - return value === undefined || typeof value === "string"; -} - -function withoutRetiredRequestKeys(request: DeviceRequest): DeviceRequest { - const { - full: _retired, - physical, - ...current - } = request as DeviceRequest & { readonly full?: unknown }; - return physical === true ? { ...current, physical: true } : current; -} - -function isLeaseRequestState(value: unknown): value is LeaseRequestState { - return value === "open" || value === "granted" || value === "failed" || value === "cancelled"; -} - -function isLeaseRequestFailure(value: unknown): value is LeaseRequestFailure { - return isObject(value) && typeof value.code === "string" && typeof value.message === "string"; -} - -function isVirtualSpecShape(value: unknown): value is VirtualSpec { - return ( - isObject(value) && - isPlatform(value.platform) && - typeof value.model === "string" && - typeof value.osVersion === "string" && - isOptionalString(value.imageTag) - ); -} - -function isDeviceClass(value: unknown): value is DeviceClass { - return DEVICE_CLASSES.some((deviceClass) => deviceClass === value); -} - -function isPlatform(value: unknown): value is Platform { - return value === "ios" || value === "android"; -} - -function isVirtualState(value: unknown): value is VirtualState { - return ( - value === "provisioning" || - value === "ready" || - value === "leased" || - value === "reclaiming" || - value === "quarantined" || - value === "shutdown" || - value === "deleted" - ); -} - -function isAbsentReason(value: unknown): value is AbsentReason { - return value === "locked" || value === "untrusted" || value === "not-present"; -} - -function isPhysicalState(value: unknown): value is PhysicalState { - return ( - value === "ready" || - value === "absent" || - value === "leased" || - value === "reclaiming" || - value === "quarantined" || - value === "deleted" - ); -} - -function isObject(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); -} - -function unknownFields( - value: Record, - knownKeys: readonly string[], -): Record { - const fields: Record = {}; - for (const [key, child] of Object.entries(value)) { - if (!knownKeys.includes(key)) { - fields[key] = child; - } - } - return fields; -} diff --git a/src/core/testing.ts b/src/core/testing.ts index e59d84817..d6ac4fb50 100644 --- a/src/core/testing.ts +++ b/src/core/testing.ts @@ -1,9 +1,22 @@ +import { describe, expect, it } from "vitest"; + import type { EventBus } from "../bus/index.js"; -import { type Clock, MemoryFilesystem } from "../ports/index.js"; +import { + type Clock, + MemoryFilesystem, + NodeSqliteOpener, + NoopLogger, + type SqliteOpener, + type SqliteSchemaOwner, +} from "../ports/index.js"; +import { openStateDatabase, type StateDatabase } from "../state/index.js"; import { ComponentInstaller } from "./component-installer.js"; -import { DiskSpaceGuard, type Driver } from "./driver.js"; +import { type DeviceDataTable, DiskSpaceGuard, type Driver } from "./driver.js"; +import { fakeDeviceDataTable } from "./fake-driver.js"; import { DriverCatalog } from "./driver-catalog.js"; -import type { Registry } from "./registry.js"; +import type { Platform } from "./domain.js"; +import { Registry, type RegistryOptions } from "./registry.js"; +import { registryOwner } from "./registry-schema.js"; import { SerializedDecision } from "./serialized-decision.js"; /** @@ -18,7 +31,7 @@ export { type ResourceStrategyOptions, } from "./capacity/index.js"; export { readyTransitionUpdate } from "./driver.js"; -export { FakeDriver } from "./fake-driver.js"; +export { FakeDriver, fakeDeviceDataTable } from "./fake-driver.js"; export type { FakeDriverOptions } from "./fake-driver.js"; export { QuarantineCoordinator } from "./quarantine-coordinator.js"; @@ -59,33 +72,64 @@ export function testComponentWiring< }; } -export class HeldWritesFilesystem extends MemoryFilesystem { - holding = false; - readonly #held: (() => void)[] = []; +export const fakeDeviceDataTables: ReadonlyMap = new Map([ + ["android", fakeDeviceDataTable], + ["ios", fakeDeviceDataTable], +]); + +// why: the real adapter on SQLite's in-memory database, whatever path the state module asks for. +const memorySqlite: SqliteOpener = { + open: (_path, options) => new NodeSqliteOpener().open(":memory:", options), +}; + +function openMemoryState(owners: readonly SqliteSchemaOwner[]): Promise { + return openStateDatabase({ + dataDirectory: "/memory", + filesystem: new MemoryFilesystem(), + logger: new NoopLogger(), + oldFiles: [], + owners, + sqlite: memorySqlite, + upgradeStep: "", + }); +} - override async writeFileAtomic(path: string, contents: string): Promise { - if (this.holding) await new Promise((resolve) => this.#held.push(resolve)); - await super.writeFileAtomic(path, contents); - } +export function openTestState(): Promise { + return openMemoryState([registryOwner, fakeDeviceDataTable]); +} - async held(count: number): Promise { - for (let turn = 0; this.#held.length < count; turn++) { - if (turn === 100) throw new Error(`Only ${String(this.#held.length)} writes were held`); - await new Promise((resolve) => setImmediate(resolve)); - } - } +export function describeDeviceDataTable( + name: string, + table: DeviceDataTable, + examples: readonly [unknown, unknown, ...unknown[]], +): void { + describe(`DeviceDataTable ${name}`, () => { + it("reads back each example it was written with, a second write replaces the first, and a missing id is refused", async () => { + const state = await openMemoryState([table]); + const [first, second] = examples; + for (const [index, example] of examples.entries()) { + const id = `dev_${String(index)}`; + table.write(state.database, id, example); + const read = table.read(state.database, id); + expect(read).toStrictEqual(example); + } + table.write(state.database, "dev_replace", first); + table.write(state.database, "dev_replace", second); + expect(table.read(state.database, "dev_replace")).toStrictEqual(second); + expect(() => table.read(state.database, "dev_missing")).toThrow(); + state.close(); + }); + }); +} - async releaseUntil(done: Promise): Promise { - let settled = false; - const settle = () => { - settled = true; - }; - done.then(settle, settle); - for (let turn = 0; !settled; turn++) { - if (turn === 100) throw new Error("The held writes never settled"); - await new Promise((resolve) => setImmediate(resolve)); - this.#held.shift()?.(); - } - await done; - } +export async function loadTestRegistry( + options: Omit & { + readonly state?: StateDatabase | undefined; + }, +): Promise { + return Registry.load({ + ...options, + deviceData: fakeDeviceDataTables, + state: options.state ?? (await openTestState()), + }); } diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 19daa951d..3e874473d 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -26,10 +26,10 @@ Flows: [startup](../../docs/internal/flows/startup.md), [device.exec](../../docs ## Composition (`main.ts`) -Both modes: config (`config.json`) → `Logger` → host info → `EventBus` → event history (`createEventHistory`, not yet started). +Both modes: config (`config.json`) → `Logger` → host info → `EventBus` → event history (`createEventHistory`, not yet started) → `openStateDatabase` (the role's `state.db`; a gateway has no tables in it yet; closed last in `dispose`, or by `startDaemon` when the start fails after the open). The role (`StartDaemonOptions.role`; the entry reads it from `--gateway` through `parseDaemonArgv`) then picks one branch; a gateway builds none of the worker's parts. The data directory is `daemonDataDirectory(resolveSimlockHome(), role)`: `` for a worker, `/gateway` for a gateway. The daemon never reads the other role's folder. -- **Worker** — `Registry` (`state.json`) → instance id (`instance.json`) → +- **Worker** — `openStateDatabase` (`state.db`, before the token checks) → `Registry` → instance id (`instance.json`) → `discoverDrivers` (validates each root; a refused root costs that platform only) → `ComponentInstaller` → `createCore` → `createLeasing` → `core.connect` → `CleanupReaper`, `Nuke`, `TokenStore`, `AdminSecretManager` → `GatewayUplink` diff --git a/src/daemon/connection-host.ts b/src/daemon/connection-host.ts index 3e1146545..abac5e1af 100644 --- a/src/daemon/connection-host.ts +++ b/src/daemon/connection-host.ts @@ -22,6 +22,24 @@ export class DaemonAlreadyRunningError extends Error { } } +/** + * why: a second daemon must learn a daemon runs before it opens `state.db`, which migrates the + * live daemon's file. A socket nobody answers is left for `DaemonEndpointHost.start` to recover. + */ +export async function refuseWhenDaemonAnswers(options: { + readonly connector: IpcConnector; + readonly endpoint: string; +}): Promise { + try { + const live = await options.connector.connect(options.endpoint); + await live.close(); + } catch (error: unknown) { + if (error instanceof IpcError && isUnavailable(error)) return; + throw error; + } + throw new DaemonAlreadyRunningError(options.endpoint); +} + export interface DaemonEndpointHostOptions { readonly connector: IpcConnector; readonly endpoint: string; diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index e91d31ee3..57d8b556c 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -2,9 +2,12 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { capacityChangedPayload, FakeDriver, + loadTestRegistry, + openTestState, testComponentWiring, type FakeDriverOptions, } from "../core/testing.js"; +import type { StateDatabase } from "../state/index.js"; import { EventBus, type EventEnvelope } from "../bus/index.js"; import type { EventHistoryHandle } from "../history/index.js"; @@ -29,7 +32,6 @@ import { type LatestPresence, Nuke, PassthroughRefusedError, - Registry, SerializedDecision, RuntimeMissingError, type CatalogReader, @@ -207,6 +209,42 @@ function withHttp(config: Config, http: Config["http"] | undefined): Config { return http === undefined ? config : { ...config, http }; } +interface SeededPhysicalDevice { + readonly createdAt: number; + readonly driverDeviceId: string; + readonly enrolledApps: readonly string[]; + readonly id: string; + readonly lastLeaseEndedAt?: number; + readonly reclaimingSince?: number; + readonly spec: { readonly class: string; readonly model: string; readonly osVersion: string }; + readonly state: string; +} + +function seedPhysicalDevices(state: StateDatabase, devices: readonly SeededPhysicalDevice[]): void { + for (const device of devices) { + state.database + .prepare( + "INSERT INTO devices (id, platform, physical, driver_device_id, state, model, os_version, class, created_at, last_lease_ended_at, reclaiming_since) VALUES (?, 'ios', 1, ?, ?, ?, ?, ?, ?, ?, ?)", + ) + .run( + device.id, + device.driverDeviceId, + device.state, + device.spec.model, + device.spec.osVersion, + device.spec.class, + device.createdAt, + device.lastLeaseEndedAt ?? null, + device.reclaimingSince ?? null, + ); + device.enrolledApps.forEach((app, position) => { + state.database + .prepare("INSERT INTO device_enrolled_apps (device_id, position, app) VALUES (?, ?, ?)") + .run(device.id, position, app); + }); + } +} + // fallow-ignore-next-line complexity -- one test harness builder; each option is a plain pass-through to a collaborator. async function buildDispatcher( overrides: { @@ -256,8 +294,7 @@ async function buildDispatcher( readonly otherStallDrivers?: readonly FakeDriver[]; /** Extra leasing options, such as `defaultModes` (a platform's default device mode). */ readonly engine?: Pick[0], "defaultModes">; - /** A `state.json` the registry loads, for a test that starts from records already on disk. */ - readonly state?: object; + readonly physicalDevices?: readonly SeededPhysicalDevice[]; readonly presence?: (driverDeviceId: string) => LatestPresence | undefined; readonly capabilitySources?: DispatcherOptions["capabilitySources"]; readonly load?: DispatcherOptions["load"]; @@ -266,15 +303,13 @@ async function buildDispatcher( const clock = overrides.clock ?? new FakeClock(1_000); const eventBus = new EventBus(clock); const filesystem = new MemoryFilesystem(); - if (overrides.state !== undefined) { - await filesystem.writeFileAtomic("/state.json", JSON.stringify(overrides.state)); - } - const registry = await Registry.load({ + const state = await openTestState(); + seedPhysicalDevices(state, overrides.physicalDevices ?? []); + const registry = await loadTestRegistry({ clock, eventBus, - filesystem, idGenerator: sequence(), - statePath: "/state.json", + state, }); const driver = new FakeDriver({ availableOsVersions: ["26.5"], @@ -1454,28 +1489,20 @@ describe("Dispatcher: device mode on every surface", () => { it("lease.request grants a physical device with physical true and its class on the device", async () => { const { dispatcher, driver, engine } = await buildDispatcher({ - state: { - devices: [], - leases: [], - physicalDevices: [ - { - createdAt: 1, - driverData: {}, - driverDeviceId: "00008110-001A2B3C4D5E", - enrolledApps: [], - id: "dev_phys", - physical: true, - spec: { - class: "tablet", - model: "iPad Pro", - osVersion: "18.4", - physical: true, - platform: "ios", - }, - state: "ready", + physicalDevices: [ + { + createdAt: 1, + driverDeviceId: "00008110-001A2B3C4D5E", + enrolledApps: [], + id: "dev_phys", + spec: { + class: "tablet", + model: "iPad Pro", + osVersion: "18.4", }, - ], - }, + state: "ready", + }, + ], }); await engine.convergeRunningCapacity(); driver.setPhysicalPresence("00008110-001A2B3C4D5E", true); @@ -1491,28 +1518,20 @@ describe("Dispatcher: device mode on every surface", () => { it("status.get and list.get show a physical record with physical, its class and no mode or enrolledApps, and count nothing of it in the capacity figures", async () => { const { dispatcher, engine } = await buildDispatcher({ - state: { - devices: [], - leases: [], - physicalDevices: [ - { - createdAt: 1, - driverData: {}, - driverDeviceId: "00008110-001A2B3C4D5E", - enrolledApps: ["com.example.kept"], - id: "dev_phys", - physical: true, - spec: { - class: "tablet", - model: "iPad Pro", - osVersion: "18.4", - physical: true, - platform: "ios", - }, - state: "ready", + physicalDevices: [ + { + createdAt: 1, + driverDeviceId: "00008110-001A2B3C4D5E", + enrolledApps: ["com.example.kept"], + id: "dev_phys", + spec: { + class: "tablet", + model: "iPad Pro", + osVersion: "18.4", }, - ], - }, + state: "ready", + }, + ], }); await engine.convergeRunningCapacity(); const lease = await dispatcher.dispatch("lease.request", request, session()); @@ -1539,7 +1558,6 @@ describe("Dispatcher: device mode on every surface", () => { it("status.get and list.get carry the latest presence read as presence on a physical device; a virtual device, and a physical device not yet read, carry none", async () => { const physical = (id: string, driverDeviceId: string) => ({ createdAt: 1, - driverData: {}, driverDeviceId, enrolledApps: [], id, @@ -1563,15 +1581,11 @@ describe("Dispatcher: device mode on every surface", () => { driverDeviceId === "UDID-UNREAD" ? undefined : (reads.get(driverDeviceId) ?? { present: true }), - state: { - devices: [], - leases: [], - physicalDevices: [ - physical("dev_read", "UDID-READ"), - physical("dev_present", "UDID-PRESENT"), - physical("dev_unread", "UDID-UNREAD"), - ], - }, + physicalDevices: [ + physical("dev_read", "UDID-READ"), + physical("dev_present", "UDID-PRESENT"), + physical("dev_unread", "UDID-UNREAD"), + ], }); await engine.convergeRunningCapacity(); const lease = await dispatcher.dispatch("lease.request", request, session()); @@ -1594,30 +1608,22 @@ describe("Dispatcher: device mode on every surface", () => { it("a reclaiming physical device's status entry has no reclaimingSince", async () => { const { dispatcher } = await buildDispatcher({ - state: { - devices: [], - leases: [], - physicalDevices: [ - { - createdAt: 1, - driverData: {}, - driverDeviceId: "00008110-001A2B3C4D5E", - enrolledApps: [], - id: "dev_phys", - lastLeaseEndedAt: 200, - physical: true, - reclaimingSince: 600, - spec: { - class: "phone", - model: "iPhone 15 Pro", - osVersion: "18.4", - physical: true, - platform: "ios", - }, - state: "reclaiming", + physicalDevices: [ + { + createdAt: 1, + driverDeviceId: "00008110-001A2B3C4D5E", + enrolledApps: [], + id: "dev_phys", + lastLeaseEndedAt: 200, + reclaimingSince: 600, + spec: { + class: "phone", + model: "iPhone 15 Pro", + osVersion: "18.4", }, - ], - }, + state: "reclaiming", + }, + ], }); const status = await dispatcher.dispatch("status.get", {}, session()); @@ -1702,7 +1708,7 @@ describe("Dispatcher: device mode on every surface", () => { const { dispatcher, registry } = await buildDispatcher({ driverOptions: { mode: "slim" } }); const granted = await dispatcher.dispatch("lease.request", request, session()); const provisioning = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "driver-provisioning" }, driverDeviceId: "driver-provisioning", provisionDuration: 0, spec: { physical: false, model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, @@ -1736,7 +1742,7 @@ describe("Dispatcher: device mode on every surface", () => { }); const register = (driverDeviceId: string, slim: boolean) => registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: driverDeviceId }, driverDeviceId, provisionDuration: 0, spec: { @@ -1773,7 +1779,7 @@ describe("Dispatcher: device mode on every surface", () => { const leased = await dispatcher.dispatch("lease.request", request, session()); const register = (driverDeviceId: string) => registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: driverDeviceId }, driverDeviceId, provisionDuration: 0, spec: { physical: false, model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, @@ -1813,7 +1819,7 @@ describe("Dispatcher: device mode on every surface", () => { claims: { isClaimed: (deviceId) => claimed.has(deviceId) }, }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "driver-booting" }, driverDeviceId: "driver-booting", provisionDuration: 0, spec: { physical: false, model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, @@ -1839,7 +1845,7 @@ describe("Dispatcher: device mode on every surface", () => { }); const { clock, dispatcher, registry } = await buildDispatcher({ otherStallDrivers: [android] }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "driver-ios-stuck" }, driverDeviceId: "driver-ios-stuck", provisionDuration: 0, spec: { physical: false, model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, @@ -2846,7 +2852,7 @@ describe("Dispatcher: status.get RAM budget", () => { session({ principal: "tok_other" }), ); await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "driver-provisioning" }, driverDeviceId: "driver-provisioning", provisionDuration: 0, spec: { ...ios, mode: "slim", physical: false }, @@ -2887,7 +2893,7 @@ describe("Dispatcher: status.get RAM budget", () => { }); for (let index = 0; index < count; index += 1) { await built.registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: `driver-${index}` }, driverDeviceId: `driver-${index}`, provisionDuration: 0, spec: { physical: false, model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, @@ -4155,7 +4161,7 @@ describe("Dispatcher: status.get while the daemon is starting", () => { it("status.get on a worker whose health is starting returns daemon, history and host and no other field", async () => { const { dispatcher, registry } = await buildDispatcher({ health: "starting" }); await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "driver-unchecked" }, driverDeviceId: "driver-unchecked", provisionDuration: 0, spec: { physical: false, model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, @@ -4173,7 +4179,7 @@ describe("Dispatcher: status.get while the daemon is starting", () => { async (health) => { const { dispatcher, registry } = await buildDispatcher({ health }); await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "driver-known" }, driverDeviceId: "driver-known", provisionDuration: 0, spec: { physical: false, model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, diff --git a/src/daemon/error-code.ts b/src/daemon/error-code.ts index 3f5862a77..281c7b1ed 100644 --- a/src/daemon/error-code.ts +++ b/src/daemon/error-code.ts @@ -88,8 +88,8 @@ export function classifyError(error: unknown): SimlockErrorCode | undefined { if (error instanceof AdminAuthenticationFailedError) { return "ADMIN_AUTHENTICATION_FAILED"; } - // A stored failure carries the code it was classified as when the request first failed. It is - // read back from `state.json`, so it is checked against the table rather than trusted. + // why: a stored failure carries the code it was classified as when the request first failed, and it is + // read back from `state.db`, so it is checked against the table rather than trusted. if (error instanceof ReplayedLeaseRequestError) { return isErrorCode(error.code) ? error.code : "INTERNAL"; } diff --git a/src/daemon/gateway-fleet.e2e.test.ts b/src/daemon/gateway-fleet.e2e.test.ts index 13f9f9974..9f8346466 100644 --- a/src/daemon/gateway-fleet.e2e.test.ts +++ b/src/daemon/gateway-fleet.e2e.test.ts @@ -31,7 +31,7 @@ import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import type { AlertDestination, PassthroughCommand } from "../core/index.js"; -import { FakeDriver } from "../core/testing.js"; +import { FakeDriver, fakeDeviceDataTables } from "../core/testing.js"; import type { Filesystem, IpcConnector, IpcListenerFactory } from "../ports/index.js"; import { FakeHostInfo, @@ -150,7 +150,6 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { filesystem: new MemoryFilesystem(), hostInfo: new FakeHostInfo(GATEWAY_HOST), logger: new NoopLogger(), - statePath: join(directory, "state.json"), version: "1.0.0-e2e", ...(alerts.poster === undefined ? {} : { webhookPoster: alerts.poster }), }); @@ -183,7 +182,6 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { dataDirectory: directory, filesystem, logger: new NoopLogger(), - statePath: join(directory, "state.json"), version: "1.0.0-e2e", }); daemons.push(daemon); @@ -242,11 +240,11 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { }, }, dataDirectory: directory, + deviceDataTables: fakeDeviceDataTables, drivers: [driver], filesystem, ...(options.ipc === undefined ? {} : { ipc: options.ipc }), logger: new NoopLogger(), - statePath: join(directory, "state.json"), version: "1.0.0-e2e", ...(options.alerts === undefined ? {} : { webhookPoster: options.alerts.poster }), }); @@ -507,7 +505,6 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { dataDirectory: directory, filesystem, logger: new NoopLogger(), - statePath: join(directory, "state.json"), version: "1.0.0-e2e", }); daemons.push(restartedGateway); diff --git a/src/daemon/gateway-modules.test.ts b/src/daemon/gateway-modules.test.ts index 9ff86b767..5da3a40ff 100644 --- a/src/daemon/gateway-modules.test.ts +++ b/src/daemon/gateway-modules.test.ts @@ -6,7 +6,7 @@ import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import { agentDeviceModuleWith } from "../agent-device/testing.js"; -import { FakeDriver } from "../core/testing.js"; +import { FakeDriver, fakeDeviceDataTables } from "../core/testing.js"; import type { GatewayModule, OptionalModuleDefinition } from "../modules/index.js"; import { fakeModule, type FakeModule } from "../modules/testing.js"; import { FakeClock, JsonLinesLogger, MemoryFilesystem, MemoryLogSink } from "../ports/index.js"; @@ -73,7 +73,6 @@ function gatewayOptions( hostLoadProbe: null, logger: new JsonLinesLogger({ clock, level: "debug", sink }), optionalModules: modules, - statePath: join(directory, "state.json"), version: "1.2.3", } as StartDaemonOptions; } @@ -131,7 +130,7 @@ async function joinWorker( filesystem: new MemoryFilesystem(), hostLoadProbe: null, optionalModules: modules, - statePath: join(directory, "state.json"), + deviceDataTables: fakeDeviceDataTables, version: "1.2.3", } as StartDaemonOptions); daemons.push(worker); diff --git a/src/daemon/lease-requires.e2e.test.ts b/src/daemon/lease-requires.e2e.test.ts index dfc9cc7a7..101adac0d 100644 --- a/src/daemon/lease-requires.e2e.test.ts +++ b/src/daemon/lease-requires.e2e.test.ts @@ -6,7 +6,7 @@ import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import { agentDeviceModuleWith, FakeAgentDevice } from "../agent-device/testing.js"; -import { FakeDriver } from "../core/testing.js"; +import { FakeDriver, fakeDeviceDataTables } from "../core/testing.js"; import { MemoryFilesystem, NoopLogger, SystemClock } from "../ports/index.js"; import type { DispatchSession } from "./dispatch.js"; import { startDaemon } from "./main.js"; @@ -65,7 +65,6 @@ describe("lease.request requires, through a gateway", () => { filesystem: new MemoryFilesystem(), logger: new NoopLogger(), optionalModules: [agentDeviceModuleWith({})], - statePath: join(directory, "state.json"), version: "1.0.0-e2e", }); daemons.push(gateway); @@ -110,7 +109,7 @@ describe("lease.request requires, through a gateway", () => { optionalModules: [agentDeviceModuleWith({ upstream: fake })], filesystem: new MemoryFilesystem(), logger: new NoopLogger(), - statePath: join(directory, "state.json"), + deviceDataTables: fakeDeviceDataTables, version: "1.0.0-e2e", } as Parameters[0]); daemons.push(daemon); diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index a6c4499d0..80c4d5e0b 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -13,11 +13,17 @@ import { OWNED_ROOT_MARKER_FILE, type OwnedRootError, REDACTED_VALUE, - Registry, + registryOwner, } from "../core/index.js"; import { agentDeviceModule } from "../agent-device/definition.js"; import { agentDeviceModuleWith, FakeAgentDeviceHealth } from "../agent-device/testing.js"; -import { FakeDriver } from "../core/testing.js"; +import { + FakeDriver, + fakeDeviceDataTable, + fakeDeviceDataTables, + loadTestRegistry, +} from "../core/testing.js"; +import { openStateDatabase } from "../state/index.js"; import { fakeModule, type FakeModule } from "../modules/testing.js"; import { IosSimctlDriver } from "../drivers/ios/index.js"; import { EventBus, type EventEnvelope } from "../bus/index.js"; @@ -31,10 +37,13 @@ import { FakeHostLoadProbe, type HostLoadCounters, FakeProcessSupervisor, + FakeSystemStats, FakeTcpProbe, JsonLinesLogger, MemoryFilesystem, MemoryLogSink, + NodeSqliteOpener, + NoopLogger, ScriptedProcessRunner, type IdGenerator, } from "../ports/index.js"; @@ -42,6 +51,8 @@ import { deviceModeWiring, modelPreferenceWiring, discoverDrivers, + productionDeviceDataTables, + resolveDeviceDataTables, emitSlimDiagnostic, parseDaemonArgv, processRunnerFor, @@ -65,7 +76,8 @@ afterEach(async () => { /** `drivers: undefined` is spelled out by a caller that wants real (module-substituted) * discovery rather than the fake driver below. */ async function start( - overrides: Partial> & { + overrides: Partial> & { + readonly deviceDataTables?: StartDaemonOptions["deviceDataTables"] | undefined; readonly drivers?: StartDaemonOptions["drivers"] | undefined; } = {}, ) { @@ -78,10 +90,10 @@ async function start( clock, dataDirectory: directory, drivers: [new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" })], + deviceDataTables: fakeDeviceDataTables, filesystem: new MemoryFilesystem(), hostLoadProbe: null, logger, - statePath: join(directory, "state.json"), version: "1.2.3", ...overrides, } as StartDaemonOptions); @@ -90,7 +102,7 @@ async function start( } describe("interrupted writes", () => { - it("startup followed by doctor --fix removes dead-pid .tmp files beside state.json and instance.json while preserving live-pid files", async () => { + it("startup followed by doctor --fix removes dead-pid .tmp files beside config.json and instance.json while preserving live-pid files", async () => { const directory = await mkdtemp(join(tmpdir(), "simlock-interrupted-write-")); temporaryDirectories.push(directory); const filesystem = new MemoryFilesystem(); @@ -99,7 +111,7 @@ describe("interrupted writes", () => { const livePid = 41002; const processSupervisor = new FakeProcessSupervisor([livePid]); const writeId = "00000000-0000-4000-8000-000000000001"; - const leftovers = ["state.json", "instance.json"].flatMap((target) => + const leftovers = ["config.json", "instance.json"].flatMap((target) => [deadPid, livePid].map((pid) => ({ path: join(directory, `.${target}.${pid}.${writeId}.tmp`), pid, @@ -114,7 +126,6 @@ describe("interrupted writes", () => { dataDirectory: directory, filesystem, processSupervisor, - statePath: join(directory, "state.json"), }); await daemon.dispatch( "doctor.run", @@ -169,7 +180,6 @@ describe("interrupted root assembly", () => { drivers: [driver], filesystem, processSupervisor, - statePath: join(directory, "state.json"), }); return { ...result, devices }; } @@ -274,6 +284,7 @@ describe("the version a daemon reports", () => { const clock = new FakeClock(1_000); const socketPath = join(directory, "daemon.sock"); const daemon = await startDaemon({ + deviceDataTables: fakeDeviceDataTables, clock, dataDirectory: directory, drivers: [new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" })], @@ -281,7 +292,6 @@ describe("the version a daemon reports", () => { hostLoadProbe: null, logger: new JsonLinesLogger({ clock, level: "debug", sink: new MemoryLogSink() }), socketPath, - statePath: join(directory, "state.json"), }); runningDaemons.push(daemon); const packageJson = JSON.parse( @@ -328,6 +338,20 @@ describe("the event history", () => { }); }); +async function queryState( + directory: string, + sql: string, +): Promise[]> { + const database = await new NodeSqliteOpener().open(join(directory, "state.db"), { + readOnly: true, + }); + try { + return database.prepare(sql).all(); + } finally { + database.close(); + } +} + /** A gateway URL on a port just released. Nothing listens there, so a worker's uplink dial * fails fast, and the fake clock never fires its retry. */ async function unreachableGatewayUrl(): Promise { @@ -338,11 +362,38 @@ async function unreachableGatewayUrl(): Promise { return `ws://127.0.0.1:${port}`; } +// why: a drivers module must export the device-data tables of its platforms, and the module file +// cannot import the repo's TypeScript, so this is the fake driver's table spelled out in plain JS. +const MODULE_DEVICE_DATA_TABLES = ` +const table = { + migrations: [ + "CREATE TABLE fake_device_data (device_id TEXT PRIMARY KEY, fake_device_id TEXT NOT NULL) STRICT", + ], + name: "fake-device-data", + read(database, deviceId) { + const row = database + .prepare("SELECT fake_device_id FROM fake_device_data WHERE device_id = ?") + .get(deviceId); + if (row === undefined) throw new Error("No fake driver data for device " + deviceId); + return { fakeDeviceId: row.fake_device_id }; + }, + version: 1, + write(database, deviceId, driverData) { + database + .prepare( + "INSERT INTO fake_device_data (device_id, fake_device_id) VALUES (?, ?) ON CONFLICT (device_id) DO UPDATE SET fake_device_id = excluded.fake_device_id", + ) + .run(deviceId, driverData.fakeDeviceId); + }, +}; +export const deviceDataTables = new Map([["android", table], ["ios", table]]); +`; + async function writeModule(contents: string): Promise { const directory = await mkdtemp(join(tmpdir(), "simlock-drivers-module-")); temporaryDirectories.push(directory); const modulePath = join(directory, "drivers.mjs"); - await writeFile(modulePath, contents, "utf8"); + await writeFile(modulePath, `${contents}\n${MODULE_DEVICE_DATA_TABLES}`, "utf8"); return modulePath; } @@ -523,12 +574,9 @@ describe("startDaemon", () => { }); it("stores lease requests under the configured limits, with failures classified by contract code", async () => { - const filesystem = new MemoryFilesystem(); const { daemon, directory } = await start({ configOverrides: { lease: { maxRequestRecords: 1 } }, - filesystem, }); - const statePath = join(directory, "state.json"); const missingRuntime = { model: "iPhone 16", osVersion: "99.0", @@ -550,13 +598,8 @@ describe("startDaemon", () => { // With the default cap both failures stay stored; with an unclassified failure the code // would be INTERNAL. await expect - .poll(async () => { - const state = JSON.parse(await filesystem.readFile(statePath)) as { - readonly leaseRequests: readonly unknown[]; - }; - return state.leaseRequests; - }) - .toMatchObject([{ failure: { code: "RUNTIME_MISSING" }, requesterId: "second" }]); + .poll(() => queryState(directory, "SELECT requester_id, failure_code FROM lease_requests")) + .toEqual([{ failure_code: "RUNTIME_MISSING", requester_id: "second" }]); }); it("establishes the instance identity once, and reuses it on the next start", async () => { @@ -598,6 +641,7 @@ describe("startDaemon", () => { new Error("adb server would not die"), ), ], + deviceDataTables: fakeDeviceDataTables, }); await daemon.stop("test"); @@ -670,6 +714,7 @@ describe("startDaemon", () => { Promise.resolve([{ name: "emulator", version: "35.4.9" }]), ), ], + deviceDataTables: fakeDeviceDataTables, hostInfo: new FakeHostInfo({ arch: "arm64", os: "macOS", osVersion: "15.5" }), }); @@ -694,6 +739,7 @@ describe("startDaemon", () => { ]), ), ], + deviceDataTables: fakeDeviceDataTables, hostInfo: new FakeHostInfo({ arch: "arm64", os: "macOS", osVersion: "15.5" }), }); @@ -712,6 +758,7 @@ describe("startDaemon", () => { return Promise.resolve([]); }), ], + deviceDataTables: fakeDeviceDataTables, hostInfo: new FakeHostInfo({ arch: "arm64", os: "macOS", osVersion: "15.5" }), }); @@ -889,31 +936,38 @@ describe("startDaemon wires core and leasing together", () => { it("settles the requests a restart left open before core's device steps announce the capacity figures", async () => { const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); const directory = await mkdtemp(join(tmpdir(), "simlock-main-")); temporaryDirectories.push(directory); - const statePath = join(directory, "state.json"); // The previous process's registry: one request still open when it stopped. - const previous = await Registry.load({ + const state = await openStateDatabase({ + dataDirectory: directory, + filesystem: new MemoryFilesystem(), + logger: new NoopLogger(), + oldFiles: [], + owners: [registryOwner, fakeDeviceDataTable], + sqlite: new NodeSqliteOpener(), + upgradeStep: "unused", + }); + const previous = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem, idGenerator: { generate: () => "1" }, - statePath, + state, }); await previous.createLeaseRequest({ ownerId: "agent-1", request: ios, requesterId: "agent-1", }); + state.close(); const daemon = await startDaemon({ clock, dataDirectory: directory, + deviceDataTables: fakeDeviceDataTables, drivers: [new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" })], - filesystem, + filesystem: new MemoryFilesystem(), logger: new JsonLinesLogger({ clock, level: "debug", sink: new MemoryLogSink() }), - statePath, version: "1.2.3", }); runningDaemons.push(daemon); @@ -925,140 +979,91 @@ describe("startDaemon wires core and leasing together", () => { expect(names.indexOf("capacity.changed")).toBeGreaterThan(names.indexOf("lease.rejected")); }); - it("finishes leasing's startup before core's convergence re-arms a quarantined device's retry", async () => { + it("ends the lease whose device is not running before core's device steps announce capacity, so a restart no longer holds it", async () => { const clock = new FakeClock(1_000); const directory = await mkdtemp(join(tmpdir(), "simlock-main-")); temporaryDirectories.push(directory); - const statePath = join(directory, "state.json"); - let holdWrites = false; - let releaseWrite: () => void = () => undefined; - const writeHeld = new Promise((resolve) => { - releaseWrite = resolve; - }); - let reachWrite: () => void = () => undefined; - const writeReached = new Promise((resolve) => { - reachWrite = resolve; - }); - class HoldingFilesystem extends MemoryFilesystem { - async writeFileAtomic( - ...arguments_: Parameters - ): Promise { - if (holdWrites && arguments_[0] === statePath) { - reachWrite(); - await writeHeld; - } - return super.writeFileAtomic(...arguments_); - } - } - const filesystem = new HoldingFilesystem(); - const options = (driver: FakeDriver) => + const options = () => ({ clock, dataDirectory: directory, - drivers: [driver], - filesystem, - hostLoadProbe: null, + deviceDataTables: fakeDeviceDataTables, + drivers: [new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" })], + filesystem: new MemoryFilesystem(), logger: new JsonLinesLogger({ clock, level: "debug", sink: new MemoryLogSink() }), - statePath, + // why: capacity follows the host's cpus and memory, and a small runner has too few slots for three leases at once, so a later request waits for ever on the fake clock (30 s timeout in runs 39459769408 and 39457371326). + systemStats: new FakeSystemStats({ cpuCount: 16, totalRamBytes: 64 * 1024 ** 3 }), version: "1.2.3", }) as StartDaemonOptions; - const failing = new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }); - failing.failOn("reclaim", 1, new DriverCrashError("purge exploded")); - const first = await startDaemon(options(failing)); - const grant = (await first.dispatch("lease.request", ios, agent)) as Grant; - await first.dispatch("lease.release", { leaseId: grant.lease.id }, agent); + const first = await startDaemon(options()); + // why: several leases, so a reconcile that runs beside core's steps lands some releases after the announcement. + const grants: Grant[] = []; + for (const requesterId of ["agent-1", "agent-2", "agent-3"]) { + grants.push((await first.dispatch("lease.request", { ...ios, requesterId }, agent)) as Grant); + } await first.stop("test"); - const previous = await Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "open-request" }, - statePath, - }); - await previous.createLeaseRequest({ - ownerId: "agent-1", - request: ios, - requesterId: "agent-1", - }); - holdWrites = true; + // why: the history orders events by their time, and the second start's must follow the first's. + clock.advance(1); + const secondRunStart = clock.now(); - const starting = startDaemon( - options(new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" })), - ); - // Waits on the write itself, not on real time: how long startup takes to reach it depends on - // the machine's load. The race lets a startup that never writes fail on the count below. - await Promise.race([writeReached, starting]); - const timersWhileLeasingStartupPending = clock.pendingTimerCount; - releaseWrite(); - runningDaemons.push(await starting); - const timersAfterStartup = clock.pendingTimerCount; + const daemon = await startDaemon(options()); + runningDaemons.push(daemon); - expect(timersWhileLeasingStartupPending).toBe(1); - expect(timersAfterStartup).toBeGreaterThan(timersWhileLeasingStartupPending); - }); + const leases = (await daemon.dispatch("list.get", { kind: "leases" }, admin)) as readonly { + readonly id: string; + }[]; + for (const grant of grants) { + expect(leases.map((lease) => lease.id)).not.toContain(grant.lease.id); + } + const secondRun = ( + await historyEventsWhen(directory, (all) => + all.some( + (event) => event.event === "capacity.changed" && event.timestamp >= secondRunStart, + ), + ) + ) + .filter((event) => event.timestamp >= secondRunStart) + .sort((left, right) => left.seq - right.seq) + .map((event) => event.event); + expect(secondRun.filter((name) => name === "lease.released")).toHaveLength(grants.length); + expect(secondRun.lastIndexOf("lease.released")).toBeLessThan( + secondRun.indexOf("capacity.changed"), + ); + // why: two daemon starts and a history wait of up to 4 s outrun the 5 s default on a loaded CI runner (run 39454292501 timed out at 5015 ms, 59 ms locally). + }, 30_000); - it("stays starting until leasing has ended the lease whose device is not running, and no longer holds the lease once it is up", async () => { + it("closes state.db on stop, and lists the same device and lease after a worker is stopped and started again", async () => { const clock = new FakeClock(1_000); const directory = await mkdtemp(join(tmpdir(), "simlock-main-")); temporaryDirectories.push(directory); - const statePath = join(directory, "state.json"); - let holdWrites = false; - let releaseWrite: () => void = () => undefined; - const writeHeld = new Promise((resolve) => { - releaseWrite = resolve; - }); - let reachWrite: () => void = () => undefined; - const writeReached = new Promise((resolve) => { - reachWrite = resolve; - }); - class HoldingFilesystem extends MemoryFilesystem { - async writeFileAtomic( - ...arguments_: Parameters - ): Promise { - if (holdWrites && arguments_[0] === statePath) { - reachWrite(); - await writeHeld; - } - return super.writeFileAtomic(...arguments_); - } - } - const filesystem = new HoldingFilesystem(); + const driver = new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }); const options = () => ({ clock, dataDirectory: directory, - drivers: [new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" })], - filesystem, + deviceDataTables: fakeDeviceDataTables, + drivers: [driver], + filesystem: new MemoryFilesystem(), logger: new JsonLinesLogger({ clock, level: "debug", sink: new MemoryLogSink() }), - statePath, version: "1.2.3", }) as StartDaemonOptions; const first = await startDaemon(options()); const grant = (await first.dispatch("lease.request", ios, agent)) as Grant; + const list = async (daemon: Awaited>, kind: string) => + ( + (await daemon.dispatch("list.get", { kind }, admin)) as readonly { readonly id: string }[] + ).map((row) => row.id); + const devicesBefore = await list(first, "devices"); await first.stop("test"); - // The restarted process's driver knows no device, so the leased one is gone from its platform. - holdWrites = true; + // why: closing the last connection checkpoints and removes the WAL, so a stop that left state.db open leaves it. + expect(existsSync(join(directory, "state.db-wal"))).toBe(false); - let started = false; - const starting = startDaemon(options()).then((daemon) => { - started = true; - return daemon; - }); - // Waits on the write, not on real time: the steps before it include real I/O, so under load - // they outlast any fixed sleep. From the write on, a startup that did not wait for it only - // has in-memory work left, which finishes before the next macrotask. - await Promise.race([writeReached, starting]); - await new Promise((resolve) => setImmediate(resolve)); - const startedWhileEndingPending = started; - releaseWrite(); - const daemon = await starting; + const daemon = await startDaemon(options()); runningDaemons.push(daemon); - expect(startedWhileEndingPending).toBe(false); - const state = JSON.parse(await filesystem.readFile(statePath)) as { - readonly leases: readonly { readonly id: string }[]; - }; - expect(state.leases.map((lease) => lease.id)).not.toContain(grant.lease.id); + expect(devicesBefore).toContain(grant.device.id); + expect(await list(daemon, "devices")).toEqual(devicesBefore); + expect(await list(daemon, "leases")).toEqual([grant.lease.id]); }); it("holds shutdown open while a release's erase runs, and does not read that erase as a stall", async () => { @@ -1097,16 +1102,10 @@ describe("startDaemon wires core and leasing together", () => { it("cancels the expiry timer of an outstanding lease on shutdown, so nothing expires after it", async () => { const clock = new FakeClock(1_000); const driver = new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }); - const filesystem = new MemoryFilesystem(); - const { daemon, directory } = await start({ clock, drivers: [driver], filesystem }); - const statePath = join(directory, "state.json"); + const { daemon, directory } = await start({ clock, drivers: [driver] }); await daemon.dispatch("lease.request", { ...ios, ttlMs: 10_000 }, agent); const leaseIds = async () => - ( - JSON.parse(await filesystem.readFile(statePath)) as { - readonly leases: readonly { readonly id: string }[]; - } - ).leases.map((lease) => lease.id); + (await queryState(directory, "SELECT id FROM leases")).map((row) => row.id); const before = await leaseIds(); expect(before).toHaveLength(1); @@ -1232,9 +1231,9 @@ describe("startDaemon startup readiness", () => { platform: "ios", }), ], + deviceDataTables: fakeDeviceDataTables, filesystem: new MemoryFilesystem(), socketPath, - statePath: join(directory, "state.json"), version: "1.2.3", } as StartDaemonOptions).then((daemon) => { runningDaemons.push(daemon); @@ -1295,10 +1294,10 @@ describe("startDaemon stopped while starting", () => { platform: "ios", }), ], + deviceDataTables: fakeDeviceDataTables, filesystem, hostLoadProbe: null, socketPath, - statePath: join(directory, "state.json"), version: "1.2.3", }); @@ -1358,8 +1357,8 @@ describe("startDaemon HTTP gateway startup readiness", () => { platform: "ios", }), ], + deviceDataTables: fakeDeviceDataTables, filesystem, - statePath: join(directory, "state.json"), version: "1.2.3", } as StartDaemonOptions).then((daemon) => { runningDaemons.push(daemon); @@ -1402,6 +1401,7 @@ describe("startDaemon stop with a warm target", () => { const driver = new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }); driver.hangMakeReady(); const daemon = await startDaemon({ + deviceDataTables: fakeDeviceDataTables, clock, configOverrides: { capacity: { config: { maxRunning: 8 }, strategy: "fixed" }, @@ -1414,7 +1414,6 @@ describe("startDaemon stop with a warm target", () => { drivers: [driver], filesystem: new MemoryFilesystem(), logger: new JsonLinesLogger({ clock, level: "debug", sink: new MemoryLogSink() }), - statePath: join(directory, "state.json"), version: "1.2.3", }); runningDaemons.push(daemon); @@ -1468,10 +1467,10 @@ describe("startDaemon HTTP gateway stop-during-start race (review finding S5)", configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, dataDirectory: directory, drivers: [new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" })], + deviceDataTables: fakeDeviceDataTables, filesystem, logger, socketPath, - statePath: join(directory, "state.json"), version: "1.2.3", } as StartDaemonOptions); // `stop()` is idempotent, so it is safe for `afterEach` to also stop whatever this @@ -1544,7 +1543,6 @@ describe("startDaemon socket race with HTTP enabled", () => { const directory = await mkdtemp(join(tmpdir(), "simlock-main-socket-race-")); temporaryDirectories.push(directory); const filesystem = new MemoryFilesystem(); - const statePath = join(directory, "state.json"); const options = (port: number): StartDaemonOptions => ({ clock: new FakeClock(1_000), @@ -1557,13 +1555,13 @@ describe("startDaemon socket race with HTTP enabled", () => { platform: "ios", }), ], + deviceDataTables: fakeDeviceDataTables, filesystem, logger: new JsonLinesLogger({ clock: new FakeClock(1_000), level: "debug", sink: new MemoryLogSink(), }), - statePath, version: "1.2.3", }) as StartDaemonOptions; @@ -1614,13 +1612,13 @@ describe("startDaemon gateway uplink when the socket claim fails", () => { platform: "ios", }), ], + deviceDataTables: fakeDeviceDataTables, filesystem, logger: new JsonLinesLogger({ clock: new FakeClock(1_000), level: "debug", sink: new MemoryLogSink(), }), - statePath: join(directory, "state.json"), version: "1.2.3", }) as StartDaemonOptions; @@ -1682,9 +1680,9 @@ describe("startDaemon HTTP gateway bind failure", () => { configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, dataDirectory: directory, drivers: [new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" })], + deviceDataTables: fakeDeviceDataTables, filesystem, logger, - statePath: join(directory, "state.json"), version: "1.2.3", } as StartDaemonOptions), ).rejects.toThrow(/EADDRINUSE|address already in use/i); @@ -1738,13 +1736,13 @@ describe("startDaemon HTTP status for a quarantined device", () => { const driver = new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }); driver.failOn("reclaim", 1, new DriverCrashError("purge exploded")); const daemon = await startDaemon({ + deviceDataTables: fakeDeviceDataTables, clock, configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, dataDirectory: directory, drivers: [driver], filesystem, hostLoadProbe: null, - statePath: join(directory, "state.json"), version: "1.2.3", } as StartDaemonOptions); runningDaemons.push(daemon); @@ -2832,6 +2830,7 @@ describe("startDaemon with the agent-device edge", () => { clock, dataDirectory: setup.directory, ...(ports.role === undefined ? {} : { role: ports.role }), + deviceDataTables: fakeDeviceDataTables, drivers: ports.drivers ?? [ new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }), ], @@ -2846,7 +2845,6 @@ describe("startDaemon with the agent-device edge", () => { ], processRunner: ports.processRunner, processSupervisor: ports.processSupervisor, - statePath: join(setup.directory, "state.json"), tcpProbe: new FakeTcpProbe(), version: "1.2.3", }); @@ -3280,13 +3278,13 @@ describe("startDaemon host load", () => { temporaryDirectories.push(directory); const clock = new FakeClock(1_000); const daemon = await startDaemon({ + deviceDataTables: fakeDeviceDataTables, clock, dataDirectory: directory, drivers: [new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" })], filesystem: new MemoryFilesystem(), hostInfo: new FakeHostInfo({ arch: "arm64", os: "macOS", osVersion: "15.5" }), logger: new JsonLinesLogger({ clock, level: "debug", sink: new MemoryLogSink() }), - statePath: join(directory, "state.json"), version: "1.2.3", ...overrides, } as StartDaemonOptions); @@ -3323,10 +3321,10 @@ describe("startDaemon host load", () => { platform: "ios", }), ], + deviceDataTables: fakeDeviceDataTables, filesystem: new MemoryFilesystem(), hostLoadProbe: new FakeHostLoadProbe(COUNTERS), socketPath, - statePath: join(directory, "state.json"), version: "1.2.3", } as StartDaemonOptions).then((daemon) => { runningDaemons.push(daemon); @@ -3467,10 +3465,10 @@ describe("startDaemon host load", () => { clock, dataDirectory: directory, drivers: [new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" })], + deviceDataTables: fakeDeviceDataTables, filesystem: new SecretRefusingFilesystem(), hostLoadProbe, socketPath: join(directory, "daemon.sock"), - statePath: join(directory, "state.json"), version: "1.2.3", } as StartDaemonOptions), ).rejects.toThrow("disk is read-only"); @@ -3535,7 +3533,6 @@ describe("startDaemon in gateway mode host load", () => { drivers: [], filesystem: new MemoryFilesystem(), logger: new JsonLinesLogger({ clock, level: "debug", sink: new MemoryLogSink() }), - statePath: join(directory, "state.json"), version: "1.2.3", ...rest, } as StartDaemonOptions); @@ -3599,9 +3596,9 @@ describe("startDaemon in gateway mode host load", () => { role: "gateway", dataDirectory: first.directory, drivers: [], + deviceDataTables: fakeDeviceDataTables, filesystem: new MemoryFilesystem(), hostLoadProbe, - statePath: join(first.directory, "state.json"), version: "1.2.3", } as StartDaemonOptions), ).rejects.toThrow(); @@ -3629,6 +3626,7 @@ describe("daemon role (ADR 0034)", () => { http: { enabled: true, host: "127.0.0.1", port: await freeLoopbackPort() }, }, drivers: [], + deviceDataTables: fakeDeviceDataTables, role: "gateway", }); runningDaemons.push(daemon); @@ -3652,3 +3650,131 @@ describe("daemon role (ADR 0034)", () => { }, ); }); + +describe("startDaemon state.db", () => { + const previousModule = process.env.SIMLOCK_DRIVERS_MODULE; + + afterEach(() => { + if (previousModule === undefined) { + delete process.env.SIMLOCK_DRIVERS_MODULE; + } else { + process.env.SIMLOCK_DRIVERS_MODULE = previousModule; + } + }); + + it("a worker started with state.json in its folder refuses with the old-file message and its step, and creates no state.db", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock-main-old-file-")); + temporaryDirectories.push(directory); + const oldFile = join(directory, "state.json"); + await writeFile(oldFile, "{}", "utf8"); + + await expect(start({ dataDirectory: directory })).rejects.toMatchObject({ + message: `Found ${oldFile}, which this Simlock no longer reads. To upgrade: with the older Simlock, release every lease and run \`simlock nuke --delete-devices\`; then remove ${oldFile} and start again. See "Breaking: state moves to state.db" in docs/CLI.md.`, + }); + expect(existsSync(join(directory, "state.db"))).toBe(false); + }); + + it("a start that fails after state.db opened closes it before it throws", async () => { + const clock = new FakeClock(1_000); + const directory = await mkdtemp(join(tmpdir(), "simlock-main-closes-state-")); + temporaryDirectories.push(directory); + const state = await openStateDatabase({ + dataDirectory: directory, + filesystem: new MemoryFilesystem(), + logger: new NoopLogger(), + oldFiles: [], + owners: [registryOwner, fakeDeviceDataTable], + sqlite: new NodeSqliteOpener(), + upgradeStep: "unused", + }); + const previous = await loadTestRegistry({ + clock, + eventBus: new EventBus(clock), + idGenerator: { generate: () => "1" }, + state, + }); + await previous.registerDevice({ + driverData: { fakeDeviceId: "fk-1" }, + driverDeviceId: "drv-1", + provisionDuration: 0, + spec: { model: "iPhone 16", osVersion: "26.5", physical: false, platform: "ios" }, + }); + state.database.exec("DELETE FROM fake_device_data"); + state.close(); + expect(existsSync(join(directory, "state.db-wal"))).toBe(false); + + await expect(start({ dataDirectory: directory })).rejects.toMatchObject({ + name: "RegistryLoadError", + }); + + expect(existsSync(join(directory, "state.db-wal"))).toBe(false); + }); + + it("a second startDaemon on a folder whose daemon runs leaves state.db's schema_versions and bytes unchanged", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock-main-live-state-")); + temporaryDirectories.push(directory); + await start({ dataDirectory: directory }); + const versions = () => queryState(directory, "SELECT owner, version FROM schema_versions"); + const before = await versions(); + const bytesBefore = await readFile(join(directory, "state.db")); + // why: a newer binary brings a newer version of an owner the live daemon's state.db has; opening would migrate it in. + const newerTable = { + ...fakeDeviceDataTable, + migrations: [ + ...fakeDeviceDataTable.migrations, + "CREATE TABLE newer_fake_data (id TEXT) STRICT", + ], + version: 2, + }; + + await expect( + start({ + dataDirectory: directory, + deviceDataTables: new Map([["ios", newerTable]]), + }), + ).rejects.toMatchObject({ name: "DaemonAlreadyRunningError" }); + + expect(await versions()).toEqual(before); + expect(await readFile(join(directory, "state.db"))).toEqual(bytesBefore); + }); + + it("a SIMLOCK_DRIVERS_MODULE without a deviceDataTables export fails start naming it", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock-main-no-tables-")); + temporaryDirectories.push(directory); + const modulePath = join(directory, "drivers.mjs"); + await writeFile(modulePath, "export function createDrivers() { return []; }\n", "utf8"); + process.env.SIMLOCK_DRIVERS_MODULE = modulePath; + + await expect( + start({ dataDirectory: directory, deviceDataTables: undefined, drivers: undefined }), + ).rejects.toMatchObject({ + message: `SIMLOCK_DRIVERS_MODULE ${modulePath} does not export deviceDataTables, a Map from platform to its device-data table`, + }); + expect(existsSync(join(directory, "state.db"))).toBe(false); + }); + + it("resolveDeviceDataTables answers the option's map when given, else the drivers module's export, else the production map", async () => { + expect(await resolveDeviceDataTables({ deviceDataTables: fakeDeviceDataTables })).toBe( + fakeDeviceDataTables, + ); + + // why: the module exports tables of its own, so a module checked first would answer a different map. + process.env.SIMLOCK_DRIVERS_MODULE = await writeModule( + "export function createDrivers() { return []; }", + ); + const optionMap = new Map(fakeDeviceDataTables); + expect(await resolveDeviceDataTables({ deviceDataTables: optionMap })).toBe(optionMap); + + delete process.env.SIMLOCK_DRIVERS_MODULE; + expect(await resolveDeviceDataTables({})).toEqual(productionDeviceDataTables()); + expect(productionDeviceDataTables().size).toBe(0); + + process.env.SIMLOCK_DRIVERS_MODULE = await writeModule( + "export function createDrivers() { return []; }", + ); + const fromModule = await resolveDeviceDataTables({}); + expect([...fromModule.keys()].sort()).toEqual(["android", "ios"]); + expect(fromModule.get("ios")?.name).toBe("fake-device-data"); + expect(fromModule).not.toBe(fakeDeviceDataTables); + }); +}); diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 2349de4dd..c19ed661c 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -1,5 +1,5 @@ import { homedir } from "node:os"; -import { dirname, join, resolve } from "node:path"; +import { join, resolve } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { type Alerts, createAlerts } from "../alerts/index.js"; @@ -17,9 +17,11 @@ import { type ConfigOverrides, type DaemonMode, type DeviceClass, + type DeviceDataTable, type DeviceMode, type Driver, type DriverRejection, + type Platform, type ModelPreferences, type PrerequisiteCheck, CleanupReaper, @@ -34,11 +36,13 @@ import { loadInstanceId, OwnedRootError, Registry, + registryOwner, Nuke, SerializedDecision, sweepWriteLeftovers, } from "../core/index.js"; import { createLeasing } from "../leasing/index.js"; +import { openStateDatabase, type StateDatabase } from "../state/index.js"; import { AdbServerUnavailableError, AndroidDriver, @@ -118,7 +122,7 @@ import { classifyError } from "./error-code.js"; import { createModuleHost, type OptionalModuleDefinition } from "../modules/index.js"; import { optionalModules } from "../module-registry/index.js"; import { DaemonServer } from "./server.js"; -import { DaemonEndpointHost } from "./connection-host.js"; +import { DaemonEndpointHost, refuseWhenDaemonAnswers } from "./connection-host.js"; import { describeLeaseRequestFailure } from "./error-code.js"; import { wakingQueueAfter } from "./enrollment-wake.js"; import { GatewayUplink } from "./gateway-uplink.js"; @@ -130,6 +134,7 @@ export interface StartDaemonOptions { readonly configPath?: string; readonly dataDirectory?: string; readonly defaultRequesterId?: string; + readonly deviceDataTables?: ReadonlyMap; readonly drivers?: readonly Driver[]; readonly gatewayRelay?: (relay: GatewayRelay) => void; /** why: test-only, hands over the gateway's uplink listener, to close one worker's socket. */ @@ -148,7 +153,6 @@ export interface StartDaemonOptions { readonly processRunner?: ProcessRunner; readonly processSupervisor?: ProcessSupervisor; readonly socketPath?: string; - readonly statePath?: string; readonly systemStats?: SystemStats; readonly tcpProbe?: TcpProbe; readonly version?: string; @@ -157,8 +161,24 @@ export interface StartDaemonOptions { } /** Constructs the daemon's real adapters once; all state remains in the daemon. */ -// fallow-ignore-next-line complexity -- explicit production composition necessarily wires all external ports. export async function startDaemon(options: StartDaemonOptions = {}): Promise { + let opened: StateDatabase | undefined; + try { + return await composeDaemon(options, (state) => { + opened = state; + }); + } catch (error: unknown) { + // why: a start that fails after `state.db` opened must not hold the file; a running daemon closes it in `dispose`. + opened?.close(); + throw error; + } +} + +// fallow-ignore-next-line complexity -- explicit production composition necessarily wires all external ports. +async function composeDaemon( + options: StartDaemonOptions, + onStateOpened: (state: StateDatabase) => void, +): Promise { const version = options.version ?? readPackageVersion(); const role = options.role ?? "worker"; const dataDirectory = options.dataDirectory ?? daemonDataDirectory(resolveSimlockHome(), role); @@ -171,7 +191,6 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise => { await sweepWriteLeftovers({ deviceRoots: deviceRoots(drivers), - directories: [dataDirectory, dirname(statePath)], + directories: [dataDirectory], filesystem, logger, processSupervisor, @@ -567,6 +596,7 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise[]; readonly socketPath: string; + readonly state: StateDatabase; readonly version: string; readonly webhookPoster?: WebhookPoster; } @@ -733,6 +764,7 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise { // why: before the HTTP gateway closes the worker uplinks, so this gateway's own stop sends no worker.disconnected (ADR 0035 §4). @@ -1082,6 +1115,38 @@ export interface DriverDiscovery { readonly rejections: readonly DriverRejection[]; } +const WORKER_UPGRADE_STEP = + "with the older Simlock, release every lease and run `simlock nuke --delete-devices`; then remove and start again."; +const GATEWAY_UPGRADE_STEP = + "remove and start again; then create each worker's join token again with `simlock --gateway token create --role worker`, set it as that worker's `gateway.token`, and drain workers again."; + +/** why: the drivers' table code, which the production map fills in once the real drivers have tables. */ +export function productionDeviceDataTables(): ReadonlyMap { + return new Map(); +} + +/** + * why: one function picks the map -- the option, else the `SIMLOCK_DRIVERS_MODULE` module's + * `deviceDataTables` export, else the production tables -- so the state open and `Registry.load` + * always see the same one. + */ +export async function resolveDeviceDataTables( + options: Pick, +): Promise> { + if (options.deviceDataTables !== undefined) return options.deviceDataTables; + const modulePath = process.env.SIMLOCK_DRIVERS_MODULE; + if (modulePath === undefined) return productionDeviceDataTables(); + const imported = (await import(pathToFileURL(resolve(modulePath)).href)) as { + deviceDataTables?: unknown; + }; + if (!(imported.deviceDataTables instanceof Map)) { + throw new Error( + `SIMLOCK_DRIVERS_MODULE ${modulePath} does not export deviceDataTables, a Map from platform to its device-data table`, + ); + } + return imported.deviceDataTables as ReadonlyMap; +} + export async function discoverDrivers(options: DriverDiscoveryContext): Promise { const logger = options.logger.child("driver-discovery"); const driversModule = process.env.SIMLOCK_DRIVERS_MODULE; diff --git a/src/daemon/optional-modules.test.ts b/src/daemon/optional-modules.test.ts index 1b21261f1..5d1ecad36 100644 --- a/src/daemon/optional-modules.test.ts +++ b/src/daemon/optional-modules.test.ts @@ -7,11 +7,17 @@ import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import { agentDeviceModuleWith, FakeAgentDevice } from "../agent-device/testing.js"; -import { FakeDriver } from "../core/testing.js"; +import { FakeDriver, fakeDeviceDataTables } from "../core/testing.js"; import type { OptionalModuleDefinition, WorkerHooks } from "../modules/index.js"; import { readHistoryEvents } from "../history/testing.js"; import { fakeModule, type FakeModule } from "../modules/testing.js"; -import { FakeClock, JsonLinesLogger, MemoryFilesystem, MemoryLogSink } from "../ports/index.js"; +import { + FakeClock, + IpcError, + JsonLinesLogger, + MemoryFilesystem, + MemoryLogSink, +} from "../ports/index.js"; import { startDaemon, type StartDaemonOptions } from "./main.js"; import type { DaemonServer } from "./server.js"; import { openRelay, openUplink, relayInput, settleWithin } from "./test-relay-support.js"; @@ -135,7 +141,7 @@ async function prepare(options: RigOptions) { logger: new JsonLinesLogger({ clock, level: "debug", sink }), optionalModules: options.modules, socketPath: join(directory, "daemon.sock"), - statePath: join(directory, "state.json"), + deviceDataTables: fakeDeviceDataTables, version: "1.2.3", ...options.extra, } as StartDaemonOptions; @@ -630,49 +636,69 @@ describe("optional modules: afterSocketClaimed", () => { expect(seen).toEqual([true]); }); - it("never runs in a daemon that lost the socket race", async () => { - const claimed = vi.fn(); - const filesystem = new MemoryFilesystem(); - const directory = await mkdtemp(join(tmpdir(), "simlock-modules-race-")); - directories.push(directory); - const options = (modules: readonly OptionalModuleDefinition[]) => - ({ - clock: new FakeClock(1_000), - configOverrides: { capabilities: { alpha: { enabled: true } } }, - dataDirectory: directory, - drivers: [ - new FakeDriver({ - availableOsVersions: ["26.5"], + it.each([ + // why: the loser refuses at the probe, before it opens state.db, so it builds no module at all + ["at the probe", undefined, 0], + // why: the loser's probe finds nothing answering, then its claim finds the address taken + [ + "at the claim", + { + connect: () => + Promise.reject(new IpcError("endpoint-not-found", "nothing answers", undefined)), + listen: () => Promise.reject(new IpcError("address-in-use", "address taken", undefined)), + } as StartDaemonOptions["ipc"], + 1, + ], + ] as const)( + "never runs in a daemon that lost the socket race %s", + async (_where, loserIpc, created) => { + const claimed = vi.fn(); + const filesystem = new MemoryFilesystem(); + const directory = await mkdtemp(join(tmpdir(), "simlock-modules-race-")); + directories.push(directory); + const options = ( + modules: readonly OptionalModuleDefinition[], + ipc?: StartDaemonOptions["ipc"], + ) => + ({ + clock: new FakeClock(1_000), + configOverrides: { capabilities: { alpha: { enabled: true } } }, + dataDirectory: directory, + drivers: [ + new FakeDriver({ + availableOsVersions: ["26.5"], + clock: new FakeClock(1_000), + platform: "ios", + }), + ], + filesystem, + ...(ipc === undefined ? {} : { ipc }), + logger: new JsonLinesLogger({ clock: new FakeClock(1_000), - platform: "ios", + level: "debug", + sink: new MemoryLogSink(), }), - ], - filesystem, - logger: new JsonLinesLogger({ - clock: new FakeClock(1_000), - level: "debug", - sink: new MemoryLogSink(), - }), - optionalModules: modules, - statePath: join(directory, "state.json"), - version: "1.2.3", - }) as StartDaemonOptions; - const first = await startDaemon(options([])); - daemons.push(first); - - const loser = fakeModule({ hooks: { afterSocketClaimed: claimed }, name: "alpha" }); - const second = await startDaemon(options(definitions(loser))).then( - () => "started", - () => "rejected", - ); - await sleep(50); + optionalModules: modules, + deviceDataTables: fakeDeviceDataTables, + version: "1.2.3", + }) as StartDaemonOptions; + const first = await startDaemon(options([])); + daemons.push(first); + + const loser = fakeModule({ hooks: { afterSocketClaimed: claimed }, name: "alpha" }); + const second = await startDaemon(options(definitions(loser), loserIpc)).then( + () => "started", + () => "rejected", + ); + await sleep(50); - expect({ claimed: claimed.mock.calls.length, created: loser.creates, second }).toEqual({ - claimed: 0, - created: 1, - second: "rejected", - }); - }); + expect({ claimed: claimed.mock.calls.length, created: loser.creates, second }).toEqual({ + claimed: 0, + created, + second: "rejected", + }); + }, + ); it.each([ [ diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 50b776152..330e7db4a 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -3,7 +3,13 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { Socket, connect } from "node:net"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { FakeDriver, testComponentWiring } from "../core/testing.js"; +import { + FakeDriver, + loadTestRegistry, + openTestState, + testComponentWiring, +} from "../core/testing.js"; +import type { StateDatabase } from "../state/index.js"; import { EventBus } from "../bus/index.js"; import { removeUsageRigs, ringEventHistory, usageRig, type UsageRig } from "../history/testing.js"; @@ -13,7 +19,6 @@ import { type DriverRejection, type PassthroughCommand, PassthroughRefusedError, - Registry, RuntimeMissingError, } from "../core/index.js"; import { PROTOCOL_VERSION_RANGE, type ProtocolRange } from "../contract/index.js"; @@ -1034,7 +1039,9 @@ describe("DaemonServer", () => { // ADR 0004 §3: a stop ends connections, not leases -- they persist, and the next daemon // judges each by its device (ADR 0019) and restores the timers of those it keeps. expect(harness.registry.snapshot.leases).toMatchObject([{ id: leaseId }]); - await expect(harness.stateFilesystem.readFile("/state.json")).resolves.toContain(leaseId); + expect(harness.state.database.prepare("SELECT id FROM leases").all()).toEqual([ + { id: leaseId }, + ]); expect(harness.eventBus.replay().map((event) => event.event)).toContain("daemon.stopping"); expect(harness.eventBus.replay().map((event) => event.event)).not.toContain("lease.released"); }); @@ -2127,7 +2134,7 @@ describe("DaemonServer lease liveness (ADR 0004)", () => { clock: new FakeClock(1_010), driver: first.driver, lease: leaseOverrides, - stateFilesystem: first.stateFilesystem, + state: first.state, }); await second.engine.convergeRunningCapacity(); @@ -2163,7 +2170,7 @@ describe("DaemonServer lease liveness (ADR 0004)", () => { clock: new FakeClock(2_000), driver: first.driver, lease: leaseOverrides, - stateFilesystem: first.stateFilesystem, + state: first.state, }); await second.engine.convergeRunningCapacity(); @@ -2230,7 +2237,7 @@ describe("DaemonServer decorations", () => { it("surfaces a derived transitionAgeMs for a mid-transition device in status and list --devices", async () => { const harness = await createHarness(); const device = await harness.registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "driver_provisioning" }, driverDeviceId: "driver_provisioning", provisionDuration: 0, spec: { physical: false, model: "iPhone 16", osVersion: "26.5", platform: "ios" }, @@ -3292,7 +3299,7 @@ async function createHarness( readonly settle?: () => Promise; readonly physicalDeviceWatcher?: Pick; readonly beginStop?: () => void; - readonly stateFilesystem?: MemoryFilesystem; + readonly state?: StateDatabase; readonly stopAuxiliary?: () => Promise; readonly adminSecret?: Auth["adminSecret"]; readonly resolveRole?: SessionRoleResolver; @@ -3312,15 +3319,14 @@ async function createHarness( const socketPath = options.socketPath ?? join(directory as string, "daemon.sock"); const clock = options.clock ?? new FakeClock(1_000); const eventBus = new EventBus(clock); - const stateFilesystem = options.stateFilesystem ?? new MemoryFilesystem(); + const state = options.state ?? (await openTestState()); const history = options.withHistory === true ? await usageRig() : undefined; if (history !== undefined) usageRigs.push(history); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: stateFilesystem, idGenerator: sequence(), - statePath: "/state.json", + state, }); const driver = options.driver ?? @@ -3415,7 +3421,7 @@ async function createHarness( await daemon.start(); } - return { clock, config, daemon, driver, engine, eventBus, registry, socketPath, stateFilesystem }; + return { clock, config, daemon, driver, engine, eventBus, registry, socketPath, state }; } /** diff --git a/src/daemon/stream-gateway.e2e.test.ts b/src/daemon/stream-gateway.e2e.test.ts index 0c703e891..940642611 100644 --- a/src/daemon/stream-gateway.e2e.test.ts +++ b/src/daemon/stream-gateway.e2e.test.ts @@ -7,7 +7,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { encodeScreenFrame, encodeScreenMeta, SCREEN_FRAME_TAG } from "../core/index.js"; import type { ScreenCapture } from "../core/index.js"; -import { FakeDriver } from "../core/testing.js"; +import { FakeDriver, fakeDeviceDataTables } from "../core/testing.js"; import { MemoryFilesystem, NoopLogger, SystemClock } from "../ports/index.js"; import type { DispatchSession } from "./dispatch.js"; import { startDaemon } from "./main.js"; @@ -95,7 +95,6 @@ describe("a screen stream through a gateway", () => { dataDirectory: gatewayDirectory, filesystem: new MemoryFilesystem(), logger: new NoopLogger(), - statePath: join(gatewayDirectory, "state.json"), version: "1.0.0-e2e", }); daemons.push(gateway); @@ -124,7 +123,7 @@ describe("a screen stream through a gateway", () => { ], filesystem: new MemoryFilesystem(), logger: new NoopLogger(), - statePath: join(workerDirectory, "state.json"), + deviceDataTables: fakeDeviceDataTables, version: "1.0.0-e2e", }); daemons.push(worker); diff --git a/src/daemon/test-relay-support.ts b/src/daemon/test-relay-support.ts index 75d29fe50..ae2732e46 100644 --- a/src/daemon/test-relay-support.ts +++ b/src/daemon/test-relay-support.ts @@ -6,7 +6,7 @@ import { join } from "node:path"; import { expect, vi } from "vitest"; -import { FakeDriver } from "../core/testing.js"; +import { FakeDriver, fakeDeviceDataTables } from "../core/testing.js"; import type { GatewayRelay } from "../gateway/index.js"; import { MemoryFilesystem, NoopLogger, SystemClock, type Logger } from "../ports/index.js"; import type { LinkChannel, LinkConnection } from "../link/index.js"; @@ -167,6 +167,7 @@ export async function startWorker( const logger = new RecordingLogger(); const options: StartDaemonOptions = { dataDirectory: directory, + deviceDataTables: fakeDeviceDataTables, drivers: [ new FakeDriver({ availableOsVersions: ["18.0"], @@ -178,7 +179,6 @@ export async function startWorker( filesystem: new MemoryFilesystem(), logger, relayTargets, - statePath: join(directory, "state.json"), version: "1.0.0-e2e", ...extra, }; @@ -351,7 +351,6 @@ export async function startFleet(context: FleetContext, options: FleetOptions = }); }, logger: new NoopLogger(), - statePath: join(gatewayDirectory, "state.json"), version: "1.0.0-e2e", }); daemons.push(gateway); diff --git a/src/daemon/worker-capabilities.e2e.test.ts b/src/daemon/worker-capabilities.e2e.test.ts index 5e58f711b..e034712fb 100644 --- a/src/daemon/worker-capabilities.e2e.test.ts +++ b/src/daemon/worker-capabilities.e2e.test.ts @@ -5,7 +5,7 @@ import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { FakeDriver } from "../core/testing.js"; +import { FakeDriver, fakeDeviceDataTables } from "../core/testing.js"; import { agentDeviceModuleWith, FakeAgentDevice } from "../agent-device/testing.js"; import { FakeHostInfo, MemoryFilesystem, NoopLogger, SystemClock } from "../ports/index.js"; import type { DispatchSession } from "./dispatch.js"; @@ -54,7 +54,6 @@ describe("a worker's capabilities through a gateway", () => { hostInfo: new FakeHostInfo({ arch: "x64", os: "Linux", osVersion: "6.8.0" }), logger: new NoopLogger(), optionalModules: [agentDeviceModuleWith({})], - statePath: join(gatewayDirectory, "state.json"), version: "1.0.0-e2e", }); daemons.push(gateway); @@ -82,7 +81,7 @@ describe("a worker's capabilities through a gateway", () => { optionalModules: [agentDeviceModuleWith({ upstream: options.fake })], filesystem: new MemoryFilesystem(), logger: new NoopLogger(), - statePath: join(workerDirectory, "state.json"), + deviceDataTables: fakeDeviceDataTables, version: "1.0.0-e2e", } as Parameters[0]); daemons.push(worker); diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index 0b8e828a2..d0508cdf3 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -2134,10 +2134,8 @@ function iosDriverData(device: DriverDevice): IosDriverData { name: value.name, runtimeId: value.runtimeId, udid: value.udid, - // why: Both are optional and post-date `state.json` registries written before slim mode - // shipped -- absent or wrong-typed is tolerated (ignored) rather than rejected, so an old - // registry keeps loading (compatibility requirement). A `full` key an older daemon stamped - // here is not read: the spec's mode is the only record of it (ADR 0007 §7). + // why: Both are optional: absent or wrong-typed is ignored rather than rejected. A `full` key + // an older daemon stamped here is not read: the spec's mode is the only record of it (ADR 0007 §7). ...(typeof value.slimSignature === "string" ? { slimSignature: value.slimSignature } : {}), ...(typeof value.slimMarkToken === "string" ? { slimMarkToken: value.slimMarkToken } : {}), }; diff --git a/src/gateway/drain-store.ts b/src/gateway/drain-store.ts index fafa67455..58667e6d2 100644 --- a/src/gateway/drain-store.ts +++ b/src/gateway/drain-store.ts @@ -14,7 +14,7 @@ import type { Filesystem, Logger } from "../ports/index.js"; import { NoopLogger } from "../ports/index.js"; /** why: Owner-only, like the other files that hold secrets or state (`tokens.json`, - * `admin.token`, `state.json`): the trust boundary is the OS user. */ + * `admin.token`, `state.db`): the trust boundary is the OS user. */ const WORKERS_FILE_MODE = 0o600; export interface DrainStore { diff --git a/src/history/AGENTS.md b/src/history/AGENTS.md index 35c269122..baa46d370 100644 --- a/src/history/AGENTS.md +++ b/src/history/AGENTS.md @@ -7,16 +7,16 @@ Flows: [startup](../../docs/internal/flows/startup.md). Catalog: [EVENTS.md](../ ## Files -| File | Role | -| -------------- | ------------------------------------------------------------------- | -| `index.ts` | the handle (`replay`, `status`, `start`, `stop`) and the CLI reader | -| `database.ts` | pragmas, schema, `quick_check`, the read query, lock-error test | -| `prune.ts` | age, size, projection prune, vacuum and checkpoint | -| `versions.ts` | `projection_versions`: migrate, refuse, the rebuild mark | -| `rebuild.ts` | refills a projection from the kept events, 1 000 at a time | -| `set-aside.ts` | renames a damaged file and its `-wal` and `-shm` | -| `projections/` | `HISTORY_PROJECTIONS`: one directory per projection (`usage`) | -| `testing.ts` | a reader, a seeder, a probing opener and a fixed handle for tests | +| File | Role | +| -------------- | ------------------------------------------------------------------------------------------------ | +| `index.ts` | the handle (`replay`, `status`, `start`, `stop`) and the CLI reader | +| `database.ts` | pragmas, schema, the read query (`quick_check` and the lock-error test are in `ports/sqlite.ts`) | +| `prune.ts` | age, size, projection prune, vacuum and checkpoint | +| `versions.ts` | `projection_versions`: migrate, refuse, the rebuild mark | +| `rebuild.ts` | refills a projection from the kept events, 1 000 at a time | +| `set-aside.ts` | renames a damaged file and its `-wal` and `-shm` | +| `projections/` | `HISTORY_PROJECTIONS`: one directory per projection (`usage`) | +| `testing.ts` | a reader, a seeder, a probing opener and a fixed handle for tests | ## How it works diff --git a/src/history/database.ts b/src/history/database.ts index 38f7cb749..f8a6a47e3 100644 --- a/src/history/database.ts +++ b/src/history/database.ts @@ -4,9 +4,6 @@ import type { SqliteDatabase } from "../ports/index.js"; export const BUSY_TIMEOUT_MS = 5_000; -const SQLITE_BUSY = 5; -const SQLITE_LOCKED = 6; - export const INSERT_EVENT_SQL = "INSERT OR IGNORE INTO events (id, timestamp, seq, size, envelope) VALUES (?, ?, ?, ?, ?)"; @@ -53,21 +50,6 @@ export function inTransaction(database: SqliteDatabase, work: () => T): T { } } -export function passesQuickCheck(database: SqliteDatabase): boolean { - const rows = database.prepare("PRAGMA quick_check").all(); - return rows.length === 1 && Object.values(rows[0] ?? {})[0] === "ok"; -} - -export function isLockError(error: unknown): boolean { - if (typeof error !== "object" || error === null) return false; - const { errcode, message } = error as { errcode?: unknown; message?: unknown }; - if (typeof errcode === "number") { - const primary = errcode & 0xff; - return primary === SQLITE_BUSY || primary === SQLITE_LOCKED; - } - return typeof message === "string" && /database (table )?is locked|busy/i.test(message); -} - export function envelopeSize(json: string): number { return Buffer.byteLength(json, "utf8"); } diff --git a/src/history/index.ts b/src/history/index.ts index e660f7edd..59e1ed0be 100644 --- a/src/history/index.ts +++ b/src/history/index.ts @@ -5,7 +5,9 @@ import { type Clock, type Filesystem, isMissingPathError, + isLockError, type Logger, + passesQuickCheck, type SqliteDatabase, type SqliteOpener, SqliteUnavailableError, @@ -15,8 +17,6 @@ import { configureDatabase, envelopeSize, INSERT_EVENT_SQL, - isLockError, - passesQuickCheck, selectEventsSince, } from "./database.js"; import { HISTORY_DB_NAME } from "./names.js"; diff --git a/src/http/app.test.ts b/src/http/app.test.ts index 96686e9da..c1c1a3c9b 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -1,7 +1,8 @@ import { describe, expect, it } from "vitest"; import { EventBus } from "../bus/index.js"; -import { UnknownLeaseError, Registry, SerializedDecision } from "../core/index.js"; +import { UnknownLeaseError, SerializedDecision } from "../core/index.js"; +import { loadTestRegistry, openTestState } from "../core/testing.js"; import { NoCapacityError, RequesterAlreadyLeasedError, @@ -1022,23 +1023,28 @@ describe("full lease-request lifecycle via GET / long-poll / SSE", () => { describe("GET /v1/lease-requests/:id across a daemon restart", () => { it("answers from the core record a previous daemon process stored", async () => { const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); + const state = await openTestState(); const load = () => - Registry.load({ + loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem, idGenerator: sequenceIdGenerator("stored"), - statePath: "/home/agent/.simlock/state.json", + state, }); const before = await load(); + const device = await before.registerDevice({ + driverData: { fakeDeviceId: "fake-1" }, + driverDeviceId: "fake-1", + provisionDuration: 0, + spec: { model: "iPhone 17 Pro", osVersion: "26.5", physical: false, platform: "ios" }, + }); const stored = await before.createLeaseRequest({ ownerId: "tok_agent", request: { model: "iPhone 17 Pro", platform: "ios" }, requesterId: "tok_agent", }); await before.settleLeaseRequest(stored.id, { - grant: makeGrant({ lease: { id: "lse_before_restart" } }), + grant: makeGrant({ device: { id: device.id }, lease: { id: "lse_before_restart" } }), state: "granted", }); @@ -1072,12 +1078,10 @@ describe("GET /v1/lease-requests/:id across a daemon restart", () => { describe("GET /v1/lease-requests/:id/events for a request nothing is driving", () => { it("ends the stream after the current state when the request has no live wait to report on", async () => { const clock = new FakeClock(1_000); - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem: new MemoryFilesystem(), idGenerator: sequenceIdGenerator("stored"), - statePath: "/home/agent/.simlock/state.json", }); // Stored open by a previous process; this one has not settled it yet. const stored = await registry.createLeaseRequest({ diff --git a/src/leasing/AGENTS.md b/src/leasing/AGENTS.md index a978fe79a..3472189ab 100644 --- a/src/leasing/AGENTS.md +++ b/src/leasing/AGENTS.md @@ -89,7 +89,7 @@ its lease as `device-lost` with no reclaim. | Reads before a crash or absence | 2 | `health.stableObservations` | | Recovery attempts | 3, backoff from 5 s | `health.maxRecoveryAttempts`, `health.recoveryBackoffMs` | -Writes go through core's `Registry` (`state.json`). Request states: `open` → +Writes go through core's `Registry` (`state.db`). Request states: `open` → `granted` | `failed` | `cancelled`. Waiter states live in memory only. ## Rules @@ -103,7 +103,7 @@ Writes go through core's `Registry` (`state.json`). Request states: `open` → `createLeasing` builds. - A daemon start fails every request the previous process left open, as `daemon-restarted`. -- A waiting reason is never stored: not in `state.json`, not in an event. +- A waiting reason is never stored: not in `state.db`, not in an event. ## Known gaps diff --git a/src/leasing/create-leasing.test.ts b/src/leasing/create-leasing.test.ts index c0b489ebb..90f195eb9 100644 --- a/src/leasing/create-leasing.test.ts +++ b/src/leasing/create-leasing.test.ts @@ -8,11 +8,18 @@ import { DriverCrashError, type VirtualSpec, type LeaseProgress, - Registry, + type Registry, UnknownLeaseError, } from "../core/index.js"; import { type CapacityLimits, type ResourceStrategyOptions } from "../core/testing.js"; -import { capacityChangedPayload, testComponentWiring, FakeDriver } from "../core/testing.js"; +import { + capacityChangedPayload, + FakeDriver, + loadTestRegistry, + openTestState, + testComponentWiring, +} from "../core/testing.js"; +import type { StateDatabase } from "../state/index.js"; import { EventBus, type EventMap } from "../bus/index.js"; import { @@ -20,7 +27,6 @@ import { FakeSystemStats, JsonLinesLogger, type Logger, - MemoryFilesystem, MemoryLogSink, } from "../ports/index.js"; import { createLeasing } from "./create-leasing.js"; @@ -30,7 +36,6 @@ import { createTestEngine } from "./testing.js"; import { QueueTimeoutError, RequestCancelledError } from "./wait-queue.js"; const gibibyte = 1024 ** 3; -const statePath = "/home/agent/.simlock/state.json"; const request = { model: "iPhone 16", osVersion: "26.5", @@ -155,7 +160,7 @@ async function createHarness( readonly driver?: FakeDriver; readonly drivers?: readonly FakeDriver[]; /** The state directory of an earlier harness: loading it again is a daemon restart. */ - readonly filesystem?: MemoryFilesystem; + readonly state?: StateDatabase; readonly identity?: Config["lease"]["identity"]; readonly lease?: Partial & { readonly maxPerRequester?: number }; readonly capacity?: Config["capacity"]; @@ -173,18 +178,17 @@ async function createHarness( } = {}, ) { const clock = new FakeClock(1_000); - const filesystem = options.filesystem ?? new MemoryFilesystem(); + const state = options.state ?? (await openTestState()); const bus = new EventBus(clock); const driver = options.driver ?? new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }); - let nextId = options.filesystem === undefined ? 1 : 1_000; - const registry = await Registry.load({ + let nextId = options.state === undefined ? 1 : 1_000; + const registry = await loadTestRegistry({ clock, eventBus: bus, - filesystem, idGenerator: { generate: () => `${nextId++}` }, ...(options.identity === undefined ? {} : { leaseIdentity: options.identity }), - statePath, + state, }); const baseConfig = config( { @@ -224,7 +228,7 @@ async function createHarness( systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes }), }); - return { bus, clock, decisions: wiring.decisions, driver, engine, filesystem, registry }; + return { bus, clock, decisions: wiring.decisions, driver, engine, registry, state }; } async function seedReady( @@ -357,34 +361,25 @@ describe("createLeasing", () => { }); it("gives no reclaiming stage to a waiter queued while the only reclaiming device of its model and OS is physical", async () => { - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [], - leases: [], - physicalDevices: [ - { - createdAt: 1, - driverData: {}, - driverDeviceId: "00008110-001A2B3C4D5E", - enrolledApps: [], - id: "dev_physical", - lastLeaseEndedAt: 1_000, - physical: true, - spec: { - class: "phone", - model: "iPhone 16", - osVersion: "26.5", - physical: true, - platform: "ios", - }, - state: "reclaiming", - }, - ], - }), - ); + const state = await openTestState(); + const seedClock = new FakeClock(1_000); + const seeding = await loadTestRegistry({ + clock: seedClock, + eventBus: new EventBus(seedClock), + idGenerator: { generate: () => "physical" }, + state, + }); + const physical = await seeding.enrollPhysical({ + apps: [], + class: "phone", + driverDeviceId: "00008110-001A2B3C4D5E", + model: "iPhone 16", + osVersion: "26.5", + platform: "ios", + }); + state.database + .prepare("UPDATE devices SET state = 'reclaiming', last_lease_ended_at = 1000 WHERE id = ?") + .run(physical.id); const clock = new FakeClock(1_000); const driver = new FakeDriver({ availableOsVersions: ["26.5"], @@ -392,7 +387,7 @@ describe("createLeasing", () => { estimateMs: { reclaim: 34_000 }, platform: "ios", }); - const harness = await createHarness({ driver, filesystem }); + const harness = await createHarness({ driver, state }); await harness.engine.request(request, { ownerId: "holder", requesterId: "holder" }); const progress: LeaseProgress[] = []; void harness.engine.request(request, { @@ -405,7 +400,7 @@ describe("createLeasing", () => { // The request is held up by the simulator limit; the physical device reclaiming beside it is // nobody's erase to wait for, so no reclaiming stage is quoted. expect(progress).toEqual([{ queuePosition: 1, stage: "queued" }]); - expect(harness.registry.snapshot.devices.map((device) => device.id)).toContain("dev_physical"); + expect(harness.registry.snapshot.devices.map((device) => device.id)).toContain(physical.id); }); it("a release whose reclaim leaves the device ready, with running capacity over its limit, has the pool shut the least recently used idle device down", async () => { @@ -1460,7 +1455,7 @@ describe("createLeasing RAM budget by mode", () => { it("counts a slim-spec device quarantined from provisioning at the full size", async () => { const harness = await createHarness({ limits: roomy, ramBudget, totalRamBytes: 9 * gibibyte }); const registered = await harness.registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "driver-stalled" }, driverDeviceId: "driver-stalled", provisionDuration: 0, spec: { ...slimRequest, physical: false }, @@ -1536,7 +1531,7 @@ describe("createLeasing RAM budget by mode", () => { // Restarted at 2 GiB slim: the three slim devices use 6 GiB of 5. const after = await createHarness({ driver, - filesystem: before.filesystem, + state: before.state, idleShutdownAfterMs: 0, limits: roomy, ramBudget: { ...ramBudget, iosSlimBytesPerDevice: 2 * gibibyte }, @@ -1700,8 +1695,7 @@ describe("createLeasing startup reclaim backgrounding (#43)", () => { }); it("recovers a background reclaim interrupted by a daemon crash on the next start", async () => { - const filesystem = new MemoryFilesystem(); - const restartStatePath = "/home/agent/.simlock/restart-state.json"; + const state = await openTestState(); let nextId = 1; const idGenerator = { generate: () => `${nextId++}` }; const systemStats = () => @@ -1721,12 +1715,11 @@ describe("createLeasing startup reclaim backgrounding (#43)", () => { const clock1 = new FakeClock(1_000); const bus1 = new EventBus(clock1); - const registry1 = await Registry.load({ + const registry1 = await loadTestRegistry({ clock: clock1, eventBus: bus1, - filesystem, idGenerator, - statePath: restartStatePath, + state, }); const engine1 = createTestEngine({ ...testComponentWiring({ @@ -1758,18 +1751,17 @@ describe("createLeasing startup reclaim backgrounding (#43)", () => { // ...and the process is abandoned before the driver's 34s reclaim resolves -- // exactly like a crashed daemon. Nothing here ever settles that promise. - // Next start: a fresh process reads the same persisted registry (state.json + // why: next start: a fresh process reads the same persisted registry (state.db // survives the crash) and reconnects to the same physical driver, but its // in-memory claim tracking starts empty -- there is no live claim for this // device, because the process that held it is gone. const clock2 = new FakeClock(clock1.now()); const bus2 = new EventBus(clock2); - const registry2 = await Registry.load({ + const registry2 = await loadTestRegistry({ clock: clock2, eventBus: bus2, - filesystem, idGenerator, - statePath: restartStatePath, + state, }); const engine2 = createTestEngine({ ...testComponentWiring({ @@ -1981,7 +1973,7 @@ describe("createLeasing fresh lease identity (#75)", () => { }); it("still deletes a device created under fresh after the configuration changes to reusable", async () => { - const filesystem = new MemoryFilesystem(); + const state = await openTestState(); const clock = new FakeClock(1_000); const bus = new EventBus(clock); let nextId = 1; @@ -1991,13 +1983,12 @@ describe("createLeasing fresh lease identity (#75)", () => { cpuCount: 8, totalRamBytes: 32 * gibibyte, }); - const beforeRegistry = await Registry.load({ + const beforeRegistry = await loadTestRegistry({ clock, eventBus: bus, - filesystem, idGenerator, leaseIdentity: freshIos, - statePath, + state, }); const before = createTestEngine({ clock, @@ -2014,13 +2005,12 @@ describe("createLeasing fresh lease identity (#75)", () => { // The operator switches iOS back to reusable and restarts the daemon mid-lease. const reusable = { android: "reusable", ios: "reusable" } as const; - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: bus, - filesystem, idGenerator, leaseIdentity: reusable, - statePath, + state, }); const after = createTestEngine({ ...testComponentWiring({ @@ -2069,20 +2059,19 @@ describe("createLeasing fresh lease identity (#75)", () => { }); async function restartAfterCrash(crashedIn: "reclaiming" | "shutdown") { - const filesystem = new MemoryFilesystem(); + const state = await openTestState(); const clock = new FakeClock(1_000); const bus = new EventBus(clock); let nextId = 1; const idGenerator = { generate: () => `${nextId++}` }; // One driver across both processes: the simulator outlives the daemon. const driver = new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }); - const crashed = await Registry.load({ + const crashed = await loadTestRegistry({ clock, eventBus: bus, - filesystem, idGenerator, leaseIdentity: freshIos, - statePath, + state, }); const driverDevice = await driver.makeReady( await driver.provision({ ...request, physical: false }), @@ -2114,13 +2103,12 @@ describe("createLeasing fresh lease identity (#75)", () => { await crashed.completeReclaimWithoutPurge(device.id); } - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: bus, - filesystem, idGenerator, leaseIdentity: freshIos, - statePath, + state, }); const engine = createTestEngine({ ...testComponentWiring({ @@ -2267,7 +2255,9 @@ describe("createLeasing logger wiring", () => { await harness.engine.release(first.lease.id, "explicit"); // The release has committed and the erase is still running. A disk that refuses the write // makes the reclaim's own commit throw, with no caller left to reject to. - harness.filesystem.defineFailure(statePath, "EIO"); + vi.spyOn(harness.state, "transaction").mockImplementation(() => { + throw new Error("EIO"); + }); clock.advance(20); await harness.engine.settle(); @@ -2300,7 +2290,7 @@ describe("createLeasing restart recovery of stored lease requests", () => { .poll(() => before.registry.leaseRequests().find((record) => record.requesterId === "agent")) .toMatchObject({ state: "open" }); - const after = await createHarness({ filesystem: before.filesystem }); + const after = await createHarness({ state: before.state }); await after.engine.convergeRunningCapacity(); return after; } @@ -2355,7 +2345,7 @@ describe("createLeasing a grant and its request's result", () => { const grant = await before.engine.request(request, asker); await flush(); - const after = await createHarness({ driver: before.driver, filesystem: before.filesystem }); + const after = await createHarness({ driver: before.driver, state: before.state }); await after.engine.convergeRunningCapacity(); const repeat = await after.engine.request(request, asker); @@ -2380,7 +2370,7 @@ describe("createLeasing a grant and its request's result", () => { expect(harness.registry.leaseRequests()).toMatchObject([{ grant, state: "granted" }]); }); - it("answers a repeat of a granted request whose lease was released since with the grant as recorded, and a renew of that lease with UnknownLeaseError", async () => { + it("answers a repeat of a granted request whose lease was released since with the lease as recorded and the device as it is now, and a renew of that lease with UnknownLeaseError", async () => { const harness = await createHarness(); await seedReady(harness); const grant = await harness.engine.request(request, asker); @@ -2390,7 +2380,9 @@ describe("createLeasing a grant and its request's result", () => { const repeat = await harness.engine.request(request, asker); expect(repeat.lease.id).toBe(grant.lease.id); - expect(repeat).toEqual(grant); + expect(grant.device.state).toBe("leased"); + expect(repeat).toEqual({ ...grant, device: harness.registry.snapshot.devices[0] }); + expect(repeat.device.state).toBe("ready"); await expect(harness.engine.renew(grant.lease.id)).rejects.toBeInstanceOf(UnknownLeaseError); }); }); @@ -2514,7 +2506,7 @@ describe("createLeasing: capacity.changed and queue.changed", () => { ); await harness.registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "sim-1" }, driverDeviceId: "sim-1", provisionDuration: 0, spec: { ...request, physical: false }, @@ -2727,7 +2719,7 @@ describe("createLeasing: lease.rejected names its request", () => { .catch(() => undefined); await expect.poll(() => admittedId(before, "agent")).toEqual(expect.stringMatching(/^req_/)); const requestId = await admittedId(before, "agent"); - const harness = await createHarness({ filesystem: before.filesystem }); + const harness = await createHarness({ state: before.state }); await harness.engine.convergeRunningCapacity(); return { harness, requestId, requester: "agent" }; }, @@ -3822,7 +3814,7 @@ describe("createLeasing a lease ID chosen by the requester", () => { it("after a daemon restart, an ID held only by a waiting request is accepted again", async () => { const before = await withWaiting("agent-2", "myid"); // Started again with room to spare, so the only thing that could refuse "myid" is the ID. - const after = await createHarness({ filesystem: before.filesystem, limits: roomy }); + const after = await createHarness({ state: before.state, limits: roomy }); await after.engine.convergeRunningCapacity(); await expect(after.engine.request(request, asking("agent-3", "myid"))).resolves.toMatchObject({ @@ -4022,7 +4014,7 @@ describe("createLeasing: a requester may hold up to lease.maxPerRequester leases const after = await createHarness({ driver, - filesystem: before.filesystem, + state: before.state, lease: { maxPerRequester: 1 }, limits: roomy, }); @@ -4212,7 +4204,7 @@ describe("createLeasing: a gateway dispatch is a probe (ADR 0021)", () => { .toMatchObject({ fleetRequestId: "req_gw1", state: "open" }); const requestId = await admittedId(before, "gw:open"); - const after = await createHarness({ filesystem: before.filesystem }); + const after = await createHarness({ state: before.state }); await after.engine.convergeRunningCapacity(); expect(payloads(after, "lease.declined")).toEqual([ diff --git a/src/leasing/lease-acquisition-coordinator.test.ts b/src/leasing/lease-acquisition-coordinator.test.ts index c953a221b..46d5f17ef 100644 --- a/src/leasing/lease-acquisition-coordinator.test.ts +++ b/src/leasing/lease-acquisition-coordinator.test.ts @@ -9,6 +9,7 @@ import { MemoryFilesystem, MemoryLogSink, } from "../ports/index.js"; +import type { StateDatabase } from "../state/index.js"; import { promiseState } from "../test-support/promise-state.js"; import { AcquisitionPlanner } from "./acquisition-planner.js"; import { @@ -32,10 +33,15 @@ import { specMode, type CatalogReader, ManagedDeviceLifecycle, - Registry, + type Registry, SerializedDecision, } from "../core/index.js"; -import { createCapacityStrategy, readyTransitionUpdate } from "../core/testing.js"; +import { + createCapacityStrategy, + loadTestRegistry, + openTestState, + readyTransitionUpdate, +} from "../core/testing.js"; import { FakeDriver } from "../core/testing.js"; import { QuarantineCoordinator } from "../core/testing.js"; import { @@ -53,7 +59,6 @@ import { LeaseLifecycle } from "./lease-lifecycle.js"; import { type LeaseRequestOptions, RequesterAlreadyLeasedError, WaitQueue } from "./wait-queue.js"; const gibibyte = 1024 ** 3; -const statePath = "/home/agent/.simlock/state.json"; const request = { physical: false, model: "iPhone 16", @@ -169,13 +174,12 @@ async function createHarness( new FakeDriver({ clock, platform: "ios", availableOsVersions: ["26.5"] }); const drivers = options.drivers ?? [driver]; let nextId = 0; - const filesystem = new MemoryFilesystem(); - const registry = await Registry.load({ + const state = await openTestState(); + const registry = await loadTestRegistry({ clock, eventBus: bus, - filesystem, idGenerator: { generate: () => `${nextId++}` }, - statePath, + state, }); const decisions = new SerializedDecision(); const claims = new DeviceOperationClaims(); @@ -297,13 +301,44 @@ async function createHarness( components, coordinator, driver, - filesystem, queue, registry, requestIds, + state, }; } +interface StoredByCommit { + readonly leaseRequesters: readonly string[]; + readonly requestRequesters: readonly string[]; +} + +/** + * why: runs `inspect` inside every registry commit, once its rows are written and before it commits: it + * sees what the commit stores, and throwing from it rolls that commit back. + */ +function inspectCommits( + harness: { readonly state: StateDatabase }, + inspect: (stored: StoredByCommit) => void, +): void { + const original = harness.state.transaction.bind(harness.state); + vi.spyOn(harness.state, "transaction").mockImplementation((work) => + original(() => { + const result = work(); + const requesters = (table: string) => + harness.state.database + .prepare(`SELECT requester_id FROM ${table}`) + .all() + .map((row) => String(row["requester_id"])); + inspect({ + leaseRequesters: requesters("leases"), + requestRequesters: requesters("lease_requests"), + }); + return result; + }), + ); +} + async function seedReady( harness: Awaited>, spec: VirtualSpec = request, @@ -1213,19 +1248,15 @@ describe("LeaseAcquisitionCoordinator", () => { queueDepth: harness.coordinator.queueDepth, }).toEqual({ now: 1_000, outcome: "pending", queueDepth: 1 }); - const write = harness.filesystem.writeFileAtomic.bind(harness.filesystem); let deadlineFellDueDuringTheGrantWrite = false; - harness.filesystem.writeFileAtomic = (path, contents) => { - // why: a real clock keeps turning while a commit is in flight, so the only faithful way to - // put this waiter's timeout inside the grant's write is to advance it from the write itself. - const inFlight = write(path, contents); - const leases = (JSON.parse(contents) as { leases?: { requesterId: string }[] }).leases ?? []; - if (leases.some((lease) => lease.requesterId === "waiter")) { + // why: a real clock keeps turning while a commit is in flight, so the only faithful way to + // put this waiter's timeout inside the grant's write is to advance it from the commit itself. + inspectCommits(harness, ({ leaseRequesters }) => { + if (leaseRequesters.includes("waiter")) { harness.clock.advance(100); deadlineFellDueDuringTheGrantWrite = harness.clock.now() >= 1_100; } - return inFlight; - }; + }); await harness.registry.beginRelease(held.lease.id); await harness.registry.transitionDevice(held.device.id, "ready", { @@ -1266,16 +1297,13 @@ describe("LeaseAcquisitionCoordinator", () => { const harness = await createHarness({ logger }); const device = await seedReady(harness); let failing = true; - const write = harness.filesystem.writeFileAtomic.bind(harness.filesystem); - harness.filesystem.writeFileAtomic = (path, contents) => { - // why: the grant is one registry commit, so failing the write that stores this waiter's - // lease is how a dead disk looks to the coordinator; the registry keeps its old state. - const stored = (JSON.parse(contents) as { leases?: { requesterId: string }[] }).leases ?? []; - if (failing && stored.some((lease) => lease.requesterId === "retrying")) { - return Promise.reject(new Error("state.json write refused")); + // why: the grant is one registry commit, so failing the commit that stores this waiter's + // lease is how a dead disk looks to the coordinator; the registry keeps its old state. + inspectCommits(harness, ({ leaseRequesters }) => { + if (failing && leaseRequesters.includes("retrying")) { + throw new Error("state write refused"); } - return write(path, contents); - }; + }); const acquisition = harness.coordinator.request(request, { ownerId: "retrying", @@ -1290,7 +1318,7 @@ describe("LeaseAcquisitionCoordinator", () => { level: "warn", fields: { deviceId: device.id, - error: "Error: state.json write refused", + error: "Error: state write refused", requesterId: "retrying", step: "grant", }, @@ -1331,17 +1359,13 @@ describe("LeaseAcquisitionCoordinator", () => { // booted one would leave a provisioned grant free to orphan its waiter again. if (path === "booted") await seedShutdown(harness); let failing = true; - const write = harness.filesystem.writeFileAtomic.bind(harness.filesystem); - harness.filesystem.writeFileAtomic = (statePathArg, contents) => { - // why: the grant is one registry commit, so failing the write that stores this waiter's - // lease is how a dead disk looks to the coordinator; the registry keeps its old state. - const stored = - (JSON.parse(contents) as { leases?: { requesterId: string }[] }).leases ?? []; - if (failing && stored.some((lease) => lease.requesterId === "orphaned")) { - return Promise.reject(new Error("state.json write refused")); + // why: the grant is one registry commit, so failing the commit that stores this waiter's + // lease is how a dead disk looks to the coordinator; the registry keeps its old state. + inspectCommits(harness, ({ leaseRequesters }) => { + if (failing && leaseRequesters.includes("orphaned")) { + throw new Error("state write refused"); } - return write(statePathArg, contents); - }; + }); const acquisition = harness.coordinator.request(request, { ownerId: "orphaned", @@ -1358,7 +1382,7 @@ describe("LeaseAcquisitionCoordinator", () => { level: "warn", fields: { deviceId: device?.id, - error: "Error: state.json write refused", + error: "Error: state write refused", requesterId: "orphaned", step: "grant", }, @@ -1978,7 +2002,7 @@ describe("LeaseAcquisitionCoordinator", () => { it.each([ ["answers that another operation owns the device", async (): Promise => false], - ["throws", async (): Promise => Promise.reject(new Error("state.json write failed"))], + ["throws", async (): Promise => Promise.reject(new Error("state write failed"))], ] as const)( "A failed boot whose destroy throws frees the waiter's running slot and leaves no fence, even when quarantine %s.", async (_label, enterFromStalledTransition) => { @@ -2122,16 +2146,12 @@ describe("LeaseAcquisitionCoordinator stored requests", () => { expect(heard).toEqual([{ queuePosition: 1, stage: "queued" }]); }); - it("writes a request to disk before the wait queue sees it", async () => { + it("stores a request before the wait queue sees it", async () => { const harness = await createHarness(); const order: string[] = []; - const write = harness.filesystem.writeFileAtomic.bind(harness.filesystem); - harness.filesystem.writeFileAtomic = async (path, contents) => { - await write(path, contents); - const stored = (JSON.parse(contents) as { leaseRequests?: { requesterId: string }[] }) - .leaseRequests; - if (stored?.some((record) => record.requesterId === "agent")) order.push("on disk"); - }; + inspectCommits(harness, ({ requestRequesters }) => { + if (requestRequesters.includes("agent") && !order.includes("stored")) order.push("stored"); + }); const create = harness.queue.create.bind(harness.queue); harness.queue.create = (...args) => { order.push("queued"); @@ -2140,7 +2160,7 @@ describe("LeaseAcquisitionCoordinator stored requests", () => { await harness.coordinator.request(request, keyed); - expect(order.slice(0, 2)).toEqual(["on disk", "queued"]); + expect(order.slice(0, 2)).toEqual(["stored", "queued"]); }); it("keeps a capacity failure terminal under the same key after capacity frees up", async () => { diff --git a/src/leasing/lease-end-participants.test.ts b/src/leasing/lease-end-participants.test.ts index 5e277f9e0..cda8cc95a 100644 --- a/src/leasing/lease-end-participants.test.ts +++ b/src/leasing/lease-end-participants.test.ts @@ -5,23 +5,23 @@ import { type DeviceRequest, type DriverDevice, type LeaseGrant, - Registry, + type Registry, UnknownLeaseError, } from "../core/index.js"; -import { FakeDriver, type FakeDriverOptions, testComponentWiring } from "../core/testing.js"; import { - FakeClock, - FakeSystemStats, - JsonLinesLogger, - MemoryFilesystem, - MemoryLogSink, -} from "../ports/index.js"; + FakeDriver, + type FakeDriverOptions, + loadTestRegistry, + openTestState, + testComponentWiring, +} from "../core/testing.js"; +import type { StateDatabase } from "../state/index.js"; +import { FakeClock, FakeSystemStats, JsonLinesLogger, MemoryLogSink } from "../ports/index.js"; import { NoCapacityError } from "./lease-acquisition-coordinator.js"; import type { EndedLease, LeaseEndParticipant } from "./lease-ports.js"; import { createTestEngine, type TestEngine } from "./testing.js"; const gibibyte = 1024 ** 3; -const statePath = "/home/agent/.simlock/state.json"; const END_WAIT_MS = 600_000; const PROBE_MS = 30_000; @@ -79,12 +79,12 @@ interface World { readonly bus: EventBus; readonly clock: FakeClock; readonly driver: FakeDriver; - readonly filesystem: MemoryFilesystem; + readonly state: StateDatabase; readonly ids: { next: number }; readonly sink: MemoryLogSink; } -function createWorld(driverOptions: Partial = {}): World { +async function createWorld(driverOptions: Partial = {}): Promise { const clock = new FakeClock(1_000); return { bus: new EventBus(clock), @@ -95,9 +95,9 @@ function createWorld(driverOptions: Partial = {}): World { platform: "ios", ...driverOptions, }), - filesystem: new MemoryFilesystem(), ids: { next: 1 }, sink: new MemoryLogSink(), + state: await openTestState(), }; } @@ -196,14 +196,13 @@ afterEach(() => { }); async function startEngine(options: EngineOptions = {}): Promise { - const world = options.world ?? createWorld(); - const { bus, clock, driver, filesystem, ids, sink } = world; - const registry = await Registry.load({ + const world = options.world ?? (await createWorld()); + const { bus, clock, driver, ids, sink, state } = world; + const registry = await loadTestRegistry({ clock, eventBus: bus, - filesystem, idGenerator: { generate: () => `${ids.next++}` }, - statePath, + state, }); const engine = createTestEngine({ ...testComponentWiring({ clock, drivers: [driver], eventBus: bus, registry }), @@ -313,7 +312,7 @@ async function endStartupLease(options: { readonly participant: TestParticipant; readonly ttlMs?: number; }) { - const world = createWorld(); + const world = await createWorld(); const first = await startEngine({ world }); const grant = await first.engine.request(request, { ...asking("agent"), @@ -955,7 +954,7 @@ describe("lease-end participants (#469)", () => { }); it("with no participant, the reclaim starts without the clock advancing and the device record carries no deferred-reclaim marker", async () => { - const world = createWorld({ latencyMs: { reclaim: 20 } }); + const world = await createWorld({ latencyMs: { reclaim: 20 } }); const harness = await startEngine({ world }); const grant = await harness.engine.request(request, asking("agent")); @@ -1017,7 +1016,7 @@ describe("lease-end participants (#469)", () => { }); it("a daemon stopped during the wipe that follows the wait also gets a full wipe at the next start", async () => { - const world = createWorld({ latencyMs: { reclaim: 20 } }); + const world = await createWorld({ latencyMs: { reclaim: 20 } }); const participant = new TestParticipant(); const harness = await startEngine({ participants: [participant], world }); const grant = await harness.engine.request(request, asking("agent")); diff --git a/src/leasing/lease-health-monitor.test.ts b/src/leasing/lease-health-monitor.test.ts index 055919326..2cf55300f 100644 --- a/src/leasing/lease-health-monitor.test.ts +++ b/src/leasing/lease-health-monitor.test.ts @@ -13,12 +13,11 @@ import { ManagedDeviceLifecycle, SerializedDecision, } from "../core/index.js"; -import { FakeDriver, HeldWritesFilesystem } from "../core/testing.js"; +import { FakeDriver, loadTestRegistry } from "../core/testing.js"; import type { DeviceLostReleaser } from "./lease-health-monitor.js"; import { LeaseHealthMonitor } from "./lease-health-monitor.js"; const gibibyte = 1024 ** 3; -const statePath = "/home/agent/.simlock/state.json"; const spec = { physical: false, model: "iPhone 16", osVersion: "26.5", platform: "ios" } as const; const androidSpec = { physical: false, @@ -117,7 +116,6 @@ async function createHarness( platform: "ios" | "android" = "ios", ) { const clock = new FakeClock(1_000); - const filesystem = new HeldWritesFilesystem(); const eventBus = new EventBus(clock); const driver = new FakeDriver({ availableOsVersions: [platform === "ios" ? "26.5" : "35"], @@ -125,12 +123,10 @@ async function createHarness( platform, }); let nextId = 1; - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem, idGenerator: { generate: () => `${nextId++}` }, - statePath, }); const claims = new DeviceOperationClaims(); const decisions = new SerializedDecision(); @@ -153,7 +149,6 @@ async function createHarness( decisions, driver, eventBus, - filesystem, monitor, registry, get releaseCalls() { @@ -678,93 +673,6 @@ describe("LeaseHealthMonitor", () => { harness.monitor.dispose(); }); - it.each([ - { - name: "recording a recovery attempt", - recoveryAttempts: 1, - async reachWrite(harness: Awaited>, driverDeviceId: string) { - harness.driver.setManagedReality({ - devices: [observedDevice(driverDeviceId, "stopped")], - processes: [], - }); - harness.driver.failOn("makeReady", 1, new Error("boom")); - harness.monitor.start(); - harness.clock.advance(30_000); - await flush(); - harness.filesystem.holding = true; - harness.clock.advance(30_000); - }, - }, - { - name: "clearing recovery markers on a device observed running", - recoveryAttempts: undefined, - async reachWrite(harness: Awaited>, driverDeviceId: string) { - const device = harness.registry.snapshot.virtualDevices.find( - (candidate) => candidate.driverDeviceId === driverDeviceId, - ); - await harness.registry.markRecoveryAttempt(device?.id ?? "", 1_000); - harness.driver.setManagedReality({ - devices: [observedDevice(driverDeviceId, "running")], - processes: [], - }); - harness.monitor.start(); - harness.filesystem.holding = true; - harness.clock.advance(30_000); - }, - }, - { - name: "clearing recovery markers after a successful reboot", - recoveryAttempts: undefined, - async reachWrite(harness: Awaited>, driverDeviceId: string) { - harness.driver.setManagedReality({ - devices: [observedDevice(driverDeviceId, "stopped")], - processes: [], - }); - harness.driver.hangMakeReady(); - harness.monitor.start(); - harness.clock.advance(30_000); - await flush(); - harness.clock.advance(30_000); - await flush(); - harness.filesystem.holding = true; - harness.driver.releaseMakeReady(); - }, - }, - ])( - "$name keeps its write, and another device's transition committed in the decision section while that write is in flight keeps its own", - async ({ reachWrite, recoveryAttempts }) => { - const harness = await createHarness(); - const { device } = await seedLeased(harness); - const idle = await harness.registry.registerDevice({ - driverData: { fakeDeviceId: "simlock-idle" }, - driverDeviceId: "simlock-idle", - provisionDuration: 0, - spec, - }); - await harness.registry.transitionDevice(idle.id, "ready", { - event: "device.ready", - payload: { bootDuration: 0, deviceId: idle.id }, - }); - - await reachWrite(harness, device.driverDeviceId); - await harness.filesystem.held(1); - const shuttingDown = harness.decisions.run(() => - harness.registry.transitionDevice(idle.id, "shutdown", { - event: "device.shutdown", - payload: { deviceId: idle.id, initiator: "warm-pool" }, - }), - ); - await harness.filesystem.releaseUntil(shuttingDown); - await flush(); - - const record = (id: string) => harness.registry.snapshot.devices.find((d) => d.id === id); - expect(record(device.id)?.state).toBe("leased"); - expect(record(device.id)?.recoveryAttempts).toBe(recoveryAttempts); - expect(record(idle.id)?.state).toBe("shutdown"); - harness.monitor.dispose(); - }, - ); - it("performs no driver calls when health.enabled is false", async () => { const harness = await createHarness({ enabled: false }); await seedLeased(harness); diff --git a/src/leasing/lease-lifecycle.test.ts b/src/leasing/lease-lifecycle.test.ts index 64d7ca20f..ea9d0ad82 100644 --- a/src/leasing/lease-lifecycle.test.ts +++ b/src/leasing/lease-lifecycle.test.ts @@ -1,10 +1,11 @@ import { describe, expect, it, vi } from "vitest"; import { EventBus } from "../bus/index.js"; -import { FakeClock, MemoryFilesystem, type Filesystem } from "../ports/index.js"; +import { FakeClock } from "../ports/index.js"; +import { loadTestRegistry, openTestState } from "../core/testing.js"; +import type { StateDatabase } from "../state/index.js"; import { LeaseExpiryScheduler } from "./lease-expiry-scheduler.js"; import { LeaseLifecycle } from "./lease-lifecycle.js"; -import { Registry } from "../core/index.js"; const noTiming = { estimatedBootMs: 0, @@ -13,23 +14,20 @@ const noTiming = { estimatedReclaimMs: 0, }; -const statePath = "/home/agent/.simlock/state.json"; - async function createHarness( - options: { readonly filesystem?: Filesystem; readonly platform?: "ios" | "android" } = {}, + options: { readonly state?: StateDatabase; readonly platform?: "ios" | "android" } = {}, ) { const clock = new FakeClock(1_000); const eventBus = new EventBus(clock); let nextId = 0; - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: options.filesystem ?? new MemoryFilesystem(), idGenerator: { generate: () => `${nextId++}` }, - statePath, + state: options.state, }); const device = await registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: "driver_1" }, driverDeviceId: "driver_1", provisionDuration: 0, spec: @@ -184,8 +182,8 @@ describe("LeaseLifecycle", () => { }); it("restores the renewed deadline (not the grant-time one) after a restart", async () => { - const filesystem = new MemoryFilesystem(); - const before = await createHarness({ filesystem }); + const state = await openTestState(); + const before = await createHarness({ state }); const grant = await before.lifecycle.grant({ environment: {}, timing: noTiming, @@ -205,12 +203,11 @@ describe("LeaseLifecycle", () => { // same persisted registry state and restore timers from it. const afterClock = new FakeClock(1_005); const afterEventBus = new EventBus(afterClock); - const afterRegistry = await Registry.load({ + const afterRegistry = await loadTestRegistry({ clock: afterClock, eventBus: afterEventBus, - filesystem, idGenerator: { generate: () => "unused" }, - statePath, + state, }); let afterLifecycle!: LeaseLifecycle; const afterScheduler = new LeaseExpiryScheduler(afterClock, async (leaseId) => { diff --git a/src/leasing/lease-reconciler.test.ts b/src/leasing/lease-reconciler.test.ts index 5ef8c9463..f49876ce1 100644 --- a/src/leasing/lease-reconciler.test.ts +++ b/src/leasing/lease-reconciler.test.ts @@ -1,14 +1,14 @@ import { describe, expect, it } from "vitest"; import { EventBus } from "../bus/index.js"; -import { FakeClock, MemoryFilesystem } from "../ports/index.js"; +import { FakeClock } from "../ports/index.js"; +import { loadTestRegistry, openTestState } from "../core/testing.js"; import { DeviceOperationClaims, type DriverReality, type LeaseRecord, type ObservedRunState, type Platform, - Registry, type ReleasedLease, SerializedDecision, StartupRead, @@ -18,26 +18,17 @@ import { LeaseLifecycle } from "./lease-lifecycle.js"; import { LeaseReconciler } from "./lease-reconciler.js"; import { LeaseReleaseCoordinator } from "./lease-release-coordinator.js"; -const STATE_PATH = "/home/agent/.simlock/state.json"; - -async function createHarness( - options: { readonly ids?: readonly string[]; readonly state?: object } = {}, -) { +async function createHarness(options: { readonly ids?: readonly string[] } = {}) { const clock = new FakeClock(1_000); const eventBus = new EventBus(clock); const ids = [...(options.ids ?? [])]; let nextId = 0; - const filesystem = new MemoryFilesystem(); - if (options.state !== undefined) { - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic(STATE_PATH, JSON.stringify(options.state)); - } - const registry = await Registry.load({ + const state = await openTestState(); + const registry = await loadTestRegistry({ clock, eventBus, - filesystem, idGenerator: { generate: () => ids.shift() ?? `${nextId++}` }, - statePath: STATE_PATH, + state, }); const lifecycle = new LeaseLifecycle({ clock, @@ -67,11 +58,11 @@ async function createHarness( clock, coordinator, eventBus, - filesystem, lifecycle, reclaims, reconciler, registry, + state, }; } @@ -84,7 +75,7 @@ async function leaseOn( ttlDeadline: number, ): Promise { const device = await harness.registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: driverDeviceId }, driverDeviceId, provisionDuration: 0, spec: { physical: false, model: "Phone", osVersion: "1", platform }, @@ -127,40 +118,21 @@ function eventNames(harness: Harness): string[] { describe("LeaseReconciler", () => { it("skips the lease of a physical device, whatever the read says of its ID or its deadline, and keeps the lease and the device as they are", async () => { - const lease = { - deviceId: "dev_phys", - grantedAt: 1, - id: "lse_phys", - idChosenByRequester: false, - lastRenewedAt: 1, + const harness = await createHarness(); + const phone = await harness.registry.enrollPhysical({ + apps: [], + class: "phone", + driverDeviceId: "00008110-001A2B3C4D5E", + model: "iPhone 15 Pro", + osVersion: "18.4", + platform: "ios", + }); + const lease = await harness.registry.createLease({ + deviceId: phone.id, ownerId: "agent", requesterId: "agent", ttlDeadline: 500, ttlMs: 60_000, - }; - const harness = await createHarness({ - state: { - devices: [], - leases: [lease], - physicalDevices: [ - { - createdAt: 1, - driverData: {}, - driverDeviceId: "00008110-001A2B3C4D5E", - enrolledApps: [], - id: "dev_phys", - physical: true, - spec: { - class: "phone", - model: "iPhone 15 Pro", - osVersion: "18.4", - physical: true, - platform: "ios", - }, - state: "leased", - }, - ], - }, }); // why: the deadline has passed, so each of these reads would end a virtual device's lease; @@ -170,7 +142,7 @@ describe("LeaseReconciler", () => { await harness.reconciler.run(read({})); await harness.reconciler.run(read({ ios: reality(["00008110-001A2B3C4D5E", "stopped"]) })); - expect(harness.registry.snapshot.leases.map((kept) => kept.id)).toEqual(["lse_phys"]); + expect(harness.registry.snapshot.leases.map((kept) => kept.id)).toEqual([lease.id]); expect(harness.registry.snapshot.devices[0]?.state).toBe("leased"); expect(eventNames(harness)).toEqual([]); expect(harness.reclaims).toEqual([]); @@ -372,19 +344,12 @@ describe("LeaseReconciler", () => { const harness = await createHarness(); const orphan = await leaseOn(harness, "ios", "d1", 5_000); const ended = await leaseOn(harness, "ios", "d2", 6_000); - const state = JSON.parse(await harness.filesystem.readFile(STATE_PATH)) as { - devices: { id: string }[]; - }; - await harness.filesystem.writeFileAtomic( - STATE_PATH, - JSON.stringify({ ...state, devices: state.devices.filter((d) => d.id !== orphan.deviceId) }), - ); - const reloaded = await Registry.load({ + harness.state.database.prepare("DELETE FROM devices WHERE id = ?").run(orphan.deviceId); + const reloaded = await loadTestRegistry({ clock: harness.clock, eventBus: harness.eventBus, - filesystem: harness.filesystem, idGenerator: { generate: () => "unused" }, - statePath: STATE_PATH, + state: harness.state, }); const reconciler = new LeaseReconciler({ clock: harness.clock, diff --git a/src/leasing/lease-release-coordinator.test.ts b/src/leasing/lease-release-coordinator.test.ts index df2609955..d81cafa1c 100644 --- a/src/leasing/lease-release-coordinator.test.ts +++ b/src/leasing/lease-release-coordinator.test.ts @@ -1,16 +1,16 @@ import { describe, expect, it } from "vitest"; import { EventBus } from "../bus/index.js"; -import { FakeClock, JsonLinesLogger, MemoryFilesystem, MemoryLogSink } from "../ports/index.js"; +import { FakeClock, JsonLinesLogger, MemoryLogSink } from "../ports/index.js"; import { DeviceOperationClaims, type DeviceRecord, type LeaseRecord, - Registry, UnknownLeaseError, type ReleasedLease, SerializedDecision, } from "../core/index.js"; +import { loadTestRegistry } from "../core/testing.js"; import { LeaseExpiryScheduler } from "./lease-expiry-scheduler.js"; import { LeaseLifecycle } from "./lease-lifecycle.js"; import { LeaseReleaseCoordinator } from "./lease-release-coordinator.js"; @@ -22,8 +22,6 @@ const noTiming = { estimatedReclaimMs: 0, }; -const statePath = "/home/agent/.simlock/state.json"; - async function flush(): Promise { for (let count = 0; count < 10; count += 1) { await Promise.resolve(); @@ -34,12 +32,10 @@ async function createHarness() { const clock = new FakeClock(1_000); const eventBus = new EventBus(clock); let nextId = 0; - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus, - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => `${nextId++}` }, - statePath, }); const scheduler = new LeaseExpiryScheduler(clock, () => undefined); const lifecycle = new LeaseLifecycle({ @@ -91,7 +87,7 @@ async function grant( harness: Awaited>, ): Promise<{ readonly device: DeviceRecord; readonly lease: LeaseRecord }> { const device = await harness.registry.registerDevice({ - driverData: {}, + driverData: { fakeDeviceId: `driver_${harness.registry.snapshot.devices.length}` }, driverDeviceId: `driver_${harness.registry.snapshot.devices.length}`, provisionDuration: 0, spec: { physical: false, model: "Phone", osVersion: "1", platform: "ios" }, @@ -292,14 +288,14 @@ describe("LeaseReleaseCoordinator", () => { expect(harness.registry.snapshot.leases).toEqual([]); }); - it("preserves concurrent releaseAll behavior: overlapping snapshots can reject", async () => { + it("a releaseAll that overlaps another finds nothing left to release", async () => { const harness = await createHarness(); await grant(harness); const first = harness.coordinator.releaseAll("killed"); const second = harness.coordinator.releaseAll("killed"); - await expect(Promise.all([first, second])).rejects.toBeInstanceOf(UnknownLeaseError); + await expect(Promise.all([first, second])).resolves.toEqual([[expect.any(String)], []]); }); describe("backgrounded reclaim", () => { diff --git a/src/leasing/lease-release-coordinator.ts b/src/leasing/lease-release-coordinator.ts index 41fd1c09d..606492a0f 100644 --- a/src/leasing/lease-release-coordinator.ts +++ b/src/leasing/lease-release-coordinator.ts @@ -78,7 +78,6 @@ interface ParticipantCalls { /** * why: lease commits happen in the serialized decision section; reclaiming is deliberately outside it. - * Concurrent `releaseAll` calls are not idempotent: overlapping snapshots can yield UnknownLeaseError. */ export class LeaseReleaseCoordinator implements LeaseReleaseCommands, LeaseExpirationAdmin, LeaseReleaseMaintenance, StartupLeaseEnder diff --git a/src/leasing/lease-request-book.test.ts b/src/leasing/lease-request-book.test.ts index c1187ccdc..ca72b8e36 100644 --- a/src/leasing/lease-request-book.test.ts +++ b/src/leasing/lease-request-book.test.ts @@ -1,7 +1,9 @@ import { describe, expect, it } from "vitest"; import { EventBus } from "../bus/index.js"; -import { FakeClock, MemoryFilesystem } from "../ports/index.js"; +import { FakeClock } from "../ports/index.js"; +import { loadTestRegistry, openTestState } from "../core/testing.js"; +import type { StateDatabase } from "../state/index.js"; import { IdempotencyConflictError, InMemoryLeaseRequestStore, @@ -10,12 +12,10 @@ import { import { type LeaseRequestLimits, type LeaseRequestStore, - Registry, SerializedDecision, } from "../core/index.js"; import { RequestCancelledError } from "./wait-queue.js"; -const statePath = "/home/agent/.simlock/state.json"; const request = { model: "iPhone 16", osVersion: "26.5", @@ -26,29 +26,26 @@ const failure = { code: "NO_CAPACITY", message: "No device capacity is currently async function loadRegistry( options: { readonly clock?: FakeClock; - readonly filesystem?: MemoryFilesystem; + readonly state?: StateDatabase; readonly limits?: LeaseRequestLimits; } = {}, ) { const clock = options.clock ?? new FakeClock(1_000); - const filesystem = options.filesystem ?? new MemoryFilesystem(); + const state = options.state ?? (await openTestState()); let nextId = 0; - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: new EventBus(clock), - filesystem, idGenerator: { generate: () => `${nextId++}` }, ...(options.limits === undefined ? {} : { leaseRequestLimits: options.limits }), - statePath, + state, }); - return { clock, filesystem, registry }; + return { clock, registry, state }; } -async function storedRequestIds(filesystem: MemoryFilesystem): Promise { - const state = JSON.parse(await filesystem.readFile(statePath)) as { - readonly leaseRequests: readonly { readonly id: string }[]; - }; - return state.leaseRequests.map((record) => record.id); +async function storedRequestIds(clock: FakeClock, state: StateDatabase): Promise { + const { registry } = await loadRegistry({ clock, state }); + return registry.leaseRequests().map((record) => record.id); } function newRequest(requesterId: string) { @@ -56,8 +53,8 @@ function newRequest(requesterId: string) { } describe("Registry lease requests", () => { - it("drops a settled record from reads once the retention window passes, and from disk at the next write", async () => { - const { clock, filesystem, registry } = await loadRegistry({ + it("drops a settled record from reads once the retention window passes, and from the stored state at the next write", async () => { + const { clock, registry, state } = await loadRegistry({ limits: { maxRecords: 100, retentionMs: 60_000 }, }); const settled = await registry.createLeaseRequest(newRequest("first")); @@ -69,7 +66,7 @@ describe("Registry lease requests", () => { clock.advance(1); expect(registry.leaseRequests()).toEqual([]); const next = await registry.createLeaseRequest(newRequest("second")); - expect(await storedRequestIds(filesystem)).toEqual([next.id]); + expect(await storedRequestIds(clock, state)).toEqual([next.id]); }); it("keeps an open record past the retention window", async () => { @@ -85,7 +82,7 @@ describe("Registry lease requests", () => { }); it("evicts the oldest settled record at the cap, and never an open one", async () => { - const { filesystem, registry } = await loadRegistry({ + const { clock, registry, state } = await loadRegistry({ limits: { maxRecords: 3, retentionMs: 60_000 }, }); const open = await registry.createLeaseRequest(newRequest("open")); @@ -95,36 +92,24 @@ describe("Registry lease requests", () => { await registry.settleLeaseRequest(newerSettled.id, { failure, state: "failed" }); const fourth = await registry.createLeaseRequest(newRequest("fourth")); - expect(await storedRequestIds(filesystem)).toEqual([open.id, newerSettled.id, fourth.id]); + expect(await storedRequestIds(clock, state)).toEqual([open.id, newerSettled.id, fourth.id]); // Every other record left is open or newer: the cap evicts the last settled one, then // admits past the cap rather than touch an open record. const fifth = await registry.createLeaseRequest(newRequest("fifth")); const sixth = await registry.createLeaseRequest(newRequest("sixth")); - expect(await storedRequestIds(filesystem)).toEqual([open.id, fourth.id, fifth.id, sixth.id]); - }); - - it("loads a state file written before lease requests were stored", async () => { - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic(statePath, JSON.stringify({ devices: [], leases: [] })); - - const { registry } = await loadRegistry({ filesystem }); - expect(registry.leaseRequests()).toEqual([]); - - const created = await registry.createLeaseRequest(newRequest("agent")); - expect(await storedRequestIds(filesystem)).toEqual([created.id]); + expect(await storedRequestIds(clock, state)).toEqual([open.id, fourth.id, fifth.id, sixth.id]); }); it("loads a stored class request after a reload, with its class and no model", async () => { - const { clock, filesystem, registry } = await loadRegistry(); + const { clock, registry, state } = await loadRegistry(); const created = await registry.createLeaseRequest({ ownerId: "agent", request: { class: "phone", platform: "ios" }, requesterId: "agent", }); - const { registry: reloaded } = await loadRegistry({ clock, filesystem }); + const { registry: reloaded } = await loadRegistry({ clock, state }); expect(reloaded.leaseRequests().map((record) => [record.id, record.request])).toEqual([ [created.id, { class: "phone", platform: "ios" }], @@ -132,14 +117,14 @@ describe("Registry lease requests", () => { }); it("reads a stored request back after a reload, result included", async () => { - const { clock, filesystem, registry } = await loadRegistry(); + const { clock, registry, state } = await loadRegistry(); const created = await registry.createLeaseRequest({ ...newRequest("agent"), idempotencyKey: "key-1", }); await registry.settleLeaseRequest(created.id, { failure, state: "failed" }); - const { registry: reloaded } = await loadRegistry({ clock, filesystem }); + const { registry: reloaded } = await loadRegistry({ clock, state }); expect(reloaded.leaseRequests()).toEqual([ { @@ -156,104 +141,6 @@ describe("Registry lease requests", () => { ]); }); - it("loads a granted record stored before mode existed with its grant's device as full, without featureProfile", async () => { - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - const grant = (id: string, device: Record) => ({ - createdAt: 1_000, - grant: { - device: { - driverDeviceId: "udid", - id: "dev_1", - spec: { physical: false, model: "iPhone 16", osVersion: "26.5", platform: "ios" }, - ...device, - }, - environment: {}, - lease: { id: "lse_1" }, - timing: {}, - }, - id, - ownerId: "agent", - request, - requesterId: "agent", - settledAt: 1_000, - state: "granted", - }); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [], - leaseRequests: [ - grant("req_legacy", { featureProfile: "reduced" }), - grant("req_slim", { mode: "slim" }), - grant("req_unknown", { mode: "reduced" }), - ], - leases: [], - }), - ); - - const { registry } = await loadRegistry({ filesystem }); - - const devices = registry.leaseRequests().map((record) => [record.id, record.grant?.device]); - expect(devices.map(([id]) => id)).toEqual(["req_legacy", "req_slim"]); - expect(devices[0]?.[1]).toMatchObject({ mode: "full" }); - expect(devices[0]?.[1]).not.toHaveProperty("featureProfile"); - expect(devices[1]?.[1]).toMatchObject({ mode: "slim" }); - }); - - it("drops a full key stored before ADR 0007 from a request and from its grant's device spec, and does not write it back", async () => { - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - const spec = { physical: false, model: "iPhone 16", osVersion: "26.5", platform: "ios" }; - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [], - leaseRequests: [ - { - createdAt: 1_000, - grant: { - device: { - physical: false, - driverDeviceId: "udid", - id: "dev_1", - mode: "full", - spec: { ...spec, full: true }, - }, - environment: {}, - lease: { id: "lse_1" }, - timing: {}, - }, - id: "req_legacy", - ownerId: "agent", - request: { ...request, full: true }, - requesterId: "agent", - settledAt: 1_000, - state: "granted", - }, - ], - leases: [], - }), - ); - - const { registry } = await loadRegistry({ filesystem }); - const [loaded] = registry.leaseRequests(); - expect(loaded?.request).toEqual(request); - expect(loaded?.grant?.device.spec).toEqual(spec); - - await registry.createLeaseRequest(newRequest("other")); - const written = JSON.parse(await filesystem.readFile(statePath)) as { - readonly leaseRequests: readonly { - readonly id: string; - readonly request: unknown; - readonly grant?: { readonly device: { readonly spec: unknown } }; - }[]; - }; - const stored = written.leaseRequests.find((record) => record.id === "req_legacy"); - expect(stored?.request).toEqual(request); - expect(stored?.grant?.device.spec).toEqual(spec); - }); - it("settles every open record as failed, leaving settled ones alone", async () => { const { registry } = await loadRegistry(); const open = await registry.createLeaseRequest(newRequest("open")); @@ -271,104 +158,6 @@ describe("Registry lease requests", () => { }); }); -describe("Registry lease-request load", () => { - const valid = { - createdAt: 1_000, - id: "req_valid", - ownerId: "agent", - request, - requesterId: "agent", - state: "open", - }; - - async function loadWith(leaseRequests: unknown) { - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ devices: [], leaseRequests, leases: [] }), - ); - return loadRegistry({ filesystem }); - } - - it.each([ - ["a granted record without its grant", { state: "granted" }], - ["a failed record whose failure has no code", { failure: { message: "x" }, state: "failed" }], - ["a settled record without its settlement time", { settledAt: undefined, state: "cancelled" }], - ["a request whose mode is neither slim nor full", { request: { ...request, mode: "fast" } }], - ])("drops %s and loads the rest", async (_label, broken) => { - const { registry } = await loadWith([ - { ...valid, id: "req_broken", settledAt: 1_000, ...broken }, - valid, - ]); - - expect(registry.leaseRequests().map((record) => record.id)).toEqual(["req_valid"]); - }); - - it.each([ - [ - "class is one of the seven: it is kept", - { class: "watch", platform: "ios" }, - { class: "watch", platform: "ios" }, - ], - [ - "class is not one of the seven: it is dropped", - { class: "phablet", platform: "ios" }, - undefined, - ], - [ - "physical is true: it is kept as physical", - { model: "iPhone 15 Pro", physical: true, platform: "ios" }, - { model: "iPhone 15 Pro", physical: true, platform: "ios" }, - ], - [ - "physical is missing: it is loaded as virtual", - { model: "iPhone 16", platform: "ios" }, - { model: "iPhone 16", platform: "ios" }, - ], - [ - "physical is false: it is loaded as virtual", - { model: "iPhone 16", physical: false, platform: "ios" }, - { model: "iPhone 16", platform: "ios" }, - ], - [ - "physical is anything but true: it is loaded as virtual", - { model: "iPhone 16", physical: "yes", platform: "ios" }, - { model: "iPhone 16", platform: "ios" }, - ], - [ - "image tag is a string: it is kept", - { ...request, imageTag: "google_apis" }, - { ...request, imageTag: "google_apis" }, - ], - ["image tag is not a string: it is dropped", { ...request, imageTag: 7 }, undefined], - ])("reads a stored request whose %s, and loads the rest", async (_label, stored, loaded) => { - const { registry } = await loadWith([{ ...valid, id: "req_row", request: stored }, valid]); - - expect(registry.leaseRequests().map((record) => [record.id, record.request])).toEqual([ - ...(loaded === undefined ? [] : [["req_row", loaded]]), - ["req_valid", request], - ]); - }); - - it("loads with no requests, rather than failing the load, when the stored list is not a list", async () => { - const { registry } = await loadWith({ not: "a list" }); - - expect(registry.leaseRequests()).toEqual([]); - }); - - it("writes back a field it does not know on a stored request", async () => { - const { filesystem, registry } = await loadWith([{ ...valid, fromANewerDaemon: 7 }]); - - await registry.createLeaseRequest(newRequest("other")); - - const state = JSON.parse(await filesystem.readFile(statePath)) as { - readonly leaseRequests: readonly Record[]; - }; - expect(state.leaseRequests[0]).toMatchObject({ fromANewerDaemon: 7, id: "req_valid" }); - }); -}); - type Grant = { readonly lease: { readonly id: string } }; function bookOver(store: LeaseRequestStore) { diff --git a/src/leasing/physical-device-watcher.test.ts b/src/leasing/physical-device-watcher.test.ts index e10713669..7f2785e7b 100644 --- a/src/leasing/physical-device-watcher.test.ts +++ b/src/leasing/physical-device-watcher.test.ts @@ -7,15 +7,21 @@ import { type PhysicalDevice, Registry, } from "../core/index.js"; -import { FakeDriver, testComponentWiring } from "../core/testing.js"; +import { + FakeDriver, + loadTestRegistry, + openTestState, + testComponentWiring, +} from "../core/testing.js"; +import type { StateDatabase } from "../state/index.js"; import { EventBus } from "../bus/index.js"; import { FakeClock, FakeSystemStats, JsonLinesLogger, type Logger, - MemoryFilesystem, MemoryLogSink, + type SqliteDatabase, } from "../ports/index.js"; import { createTestEngine, type TestEngine } from "./testing.js"; @@ -25,7 +31,6 @@ const latestPresence = (driverDeviceId: string): unknown => ); const gibibyte = 1024 ** 3; -const statePath = "/home/agent/.simlock/state.json"; const PROBE_MS = 30_000; const DAY_MS = 24 * 60 * 60_000; @@ -123,15 +128,15 @@ interface Harness { readonly clock: FakeClock; readonly driver: FakeDriver; readonly engine: TestEngine; - readonly filesystem: MemoryFilesystem; readonly registry: Registry; + readonly state: StateDatabase; } const harnesses: Harness[] = []; async function createHarness( options: HarnessOptions = {}, - filesystem: MemoryFilesystem = new MemoryFilesystem(), + state?: StateDatabase, ): Promise { const clock = new FakeClock(1_000); const bus = new EventBus(clock); @@ -143,12 +148,12 @@ async function createHarness( }); const drivers = options.android === true ? [driver, androidDriver] : [driver]; let nextId = 1; - const registry = await Registry.load({ + const stateDatabase = state ?? (await openTestState()); + const registry = await loadTestRegistry({ clock, eventBus: bus, - filesystem, idGenerator: { generate: () => `${nextId++}` }, - statePath, + state: stateDatabase, }); const wiring = testComponentWiring({ clock, drivers, eventBus: bus, registry }); const engine = createTestEngine({ @@ -162,7 +167,15 @@ async function createHarness( registry, systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte }), }); - const harness = { androidDriver, bus, clock, driver, engine, filesystem, registry }; + const harness = { + androidDriver, + bus, + clock, + driver, + engine, + registry, + state: stateDatabase, + }; harnesses.push(harness); return harness; } @@ -190,27 +203,19 @@ function startWatcher(harness: Harness): void { async function reopen( first: Harness, - patch: (records: Record[]) => void, + patch: (database: SqliteDatabase) => void, options: HarnessOptions = {}, ): Promise { - const raw = JSON.parse(await first.filesystem.readFile(statePath)) as { - physicalDevices: Record[]; - }; - patch(raw.physicalDevices); - await first.filesystem.writeFileAtomic(statePath, JSON.stringify(raw)); + patch(first.state.database); first.engine.dispose(); - return createHarness(options, first.filesystem); + return createHarness(options, first.state); } -function markAbsent( - records: Record[], - driverDeviceId: string, - absentReason: string, -): void { - const record = records.find((candidate) => candidate.driverDeviceId === driverDeviceId); - if (record === undefined) throw new Error(`no record for ${driverDeviceId}`); - record.state = "absent"; - record.absentReason = absentReason; +function markAbsent(database: SqliteDatabase, driverDeviceId: string, absentReason: string): void { + const { changes } = database + .prepare("UPDATE devices SET state = 'absent', absent_reason = ? WHERE driver_device_id = ?") + .run(absentReason, driverDeviceId); + if (changes === 0) throw new Error(`no record for ${driverDeviceId}`); } async function enrollIphone(harness: Harness, driverDeviceId: string): Promise { @@ -232,7 +237,11 @@ async function absentHarness( ): Promise<{ readonly device: PhysicalDevice; readonly harness: Harness }> { const first = await createHarness(options); const device = await enrollIphone(first, "UDID-A"); - const harness = await reopen(first, (records) => markAbsent(records, "UDID-A", reason), options); + const harness = await reopen( + first, + (database) => markAbsent(database, "UDID-A", reason), + options, + ); return { device, harness }; } @@ -333,24 +342,22 @@ interface RecordedWrite { function recordStateWrites(harness: Harness): RecordedWrite[] { const writes: RecordedWrite[] = []; - const original = harness.filesystem.writeFileAtomic.bind(harness.filesystem); - vi.spyOn(harness.filesystem, "writeFileAtomic").mockImplementation( - async (path, contents, options) => { - if (path === statePath) { - const parsed = JSON.parse(contents) as { - devices?: { id: string; state: string }[]; - physicalDevices?: { id: string; state: string }[]; - }; - const records = [...(parsed.devices ?? []), ...(parsed.physicalDevices ?? [])]; - writes.push({ - claims: Object.fromEntries( - records.map((record) => [record.id, harness.engine.core.claims.claim(record.id)?.kind]), - ), - states: Object.fromEntries(records.map((record) => [record.id, record.state])), - }); - } - return original(path, contents, options); - }, + const original = harness.state.transaction.bind(harness.state); + vi.spyOn(harness.state, "transaction").mockImplementation((work) => + original(() => { + const result = work(); + const records = harness.state.database.prepare("SELECT id, state FROM devices").all() as { + id: string; + state: string; + }[]; + writes.push({ + claims: Object.fromEntries( + records.map((record) => [record.id, harness.engine.core.claims.claim(record.id)?.kind]), + ), + states: Object.fromEntries(records.map((record) => [record.id, record.state])), + }); + return result; + }), ); return writes; } @@ -820,7 +827,7 @@ describe("PhysicalDeviceWatcher acting on a device", () => { gone(harness, "UDID-B"); startWatcher(harness); await tick(harness); - vi.spyOn(harness.filesystem, "writeFileAtomic").mockImplementationOnce(async () => { + vi.spyOn(harness.state, "transaction").mockImplementationOnce(() => { throw new Error("disk full"); }); const problems = () => @@ -1056,18 +1063,16 @@ describe("PhysicalDeviceWatcher acting on a device", () => { const returned = await enrollIphone(first, "UDID-B"); const harness = await reopen( first, - (records) => markAbsent(records, "UDID-B", "not-present"), + (database) => markAbsent(database, "UDID-B", "not-present"), options, ); gone(harness, "UDID-A"); back(harness, "UDID-B"); - const original = harness.filesystem.writeFileAtomic.bind(harness.filesystem); - vi.spyOn(harness.filesystem, "writeFileAtomic").mockImplementationOnce( - async (path, contents, writeOptions) => { - watcherOf(harness)?.dispose(); - return original(path, contents, writeOptions); - }, - ); + const original = harness.state.transaction.bind(harness.state); + vi.spyOn(harness.state, "transaction").mockImplementationOnce((work) => { + watcherOf(harness)?.dispose(); + return original(work); + }); startWatcher(harness); await tick(harness); @@ -1089,13 +1094,11 @@ describe("PhysicalDeviceWatcher acting on a device", () => { startWatcher(first); await tick(first); back(first, "UDID-B"); - const original = first.filesystem.writeFileAtomic.bind(first.filesystem); - vi.spyOn(first.filesystem, "writeFileAtomic").mockImplementationOnce( - async (path, contents, writeOptions) => { - watcherOf(first)?.dispose(); - return original(path, contents, writeOptions); - }, - ); + const original = first.state.transaction.bind(first.state); + vi.spyOn(first.state, "transaction").mockImplementationOnce((work) => { + watcherOf(first)?.dispose(); + return original(work); + }); await tick(first); @@ -1209,8 +1212,8 @@ describe("PhysicalDeviceWatcher around restarts and doctor", () => { await first.registry.transitionDevice(device.id, "reclaiming"); const harness = await reopen( first, - (records) => { - for (const record of records) record.lastLeaseEndedAt = 1; + (database) => { + database.exec("UPDATE devices SET last_lease_ended_at = 1"); }, options, ); @@ -1262,9 +1265,9 @@ describe("PhysicalDeviceWatcher and nuke maintenance", () => { const returned = await enrollIphone(first, "UDID-Y"); const harness = await reopen( first, - (records) => { - markAbsent(records, "UDID-X", "locked"); - markAbsent(records, "UDID-Y", "locked"); + (database) => { + markAbsent(database, "UDID-X", "locked"); + markAbsent(database, "UDID-Y", "locked"); }, options, ); diff --git a/src/leasing/physical-leasing.test.ts b/src/leasing/physical-leasing.test.ts index 8a3f2c056..1faba99d5 100644 --- a/src/leasing/physical-leasing.test.ts +++ b/src/leasing/physical-leasing.test.ts @@ -6,18 +6,16 @@ import { NoDriverError, type Config, type PhysicalDevice, - Registry, UnknownModelError, } from "../core/index.js"; -import { FakeDriver, testComponentWiring } from "../core/testing.js"; +import { FakeDriver, loadTestRegistry, testComponentWiring } from "../core/testing.js"; import { EventBus, type EventMap } from "../bus/index.js"; -import { FakeClock, FakeSystemStats, MemoryFilesystem } from "../ports/index.js"; +import { FakeClock, FakeSystemStats } from "../ports/index.js"; import { NoCapacityError } from "./lease-acquisition-coordinator.js"; import { createTestEngine } from "./testing.js"; import { QueueTimeoutError, RequestCancelledError } from "./wait-queue.js"; const gibibyte = 1024 ** 3; -const statePath = "/home/agent/.simlock/state.json"; const physicalRequest = { model: "iPhone 15 Pro", @@ -122,12 +120,10 @@ async function createHarness( platform: "ios", }); let nextId = 1; - const registry = await Registry.load({ + const registry = await loadTestRegistry({ clock, eventBus: bus, - filesystem: new MemoryFilesystem(), idGenerator: { generate: () => `${nextId++}` }, - statePath, }); const wiring = testComponentWiring({ clock, drivers: [driver], eventBus: bus, registry }); const engine = createTestEngine({ diff --git a/src/ports/AGENTS.md b/src/ports/AGENTS.md index 29aadaa15..7f163dce5 100644 --- a/src/ports/AGENTS.md +++ b/src/ports/AGENTS.md @@ -26,7 +26,7 @@ Uses: nothing from other components. Imported by: every component that touches t | `TcpStreamConnector` | `tcp-stream.ts` | `NodeTcpStreamConnector` | `FakeTcpStreamConnector` | A long-lived loopback connection, bytes both ways | | `BytePipeLauncher` | `byte-pipe.ts` | `NodeBytePipeLauncher` | `FakeBytePipeLauncher` | A child with binary stdout and stdin as its liveness | | `KeySetFetcher` | `key-set-fetcher.ts` | `NodeKeySetFetcher` | `FakeKeySetFetcher` | One GET of a key-set URL: no redirects, body capped at 64 KiB | -| `SqliteOpener` | `sqlite.ts` | `NodeSqliteOpener` | none; tests use the adapter on a temp file | Open a SQLite file; `exec`, `prepare`, `close` | +| `SqliteOpener` | `sqlite.ts` | `NodeSqliteOpener` | none; tests use the adapter on a temp file | Open a SQLite file (`:memory:` is not pre-created); `exec`, `prepare`, `close`. `sqlite.ts` also holds `SqliteSchemaOwner` (`name`, `version`, `migrations[i]` takes version `i` to `i + 1`), `passesQuickCheck` and `isLockError` | | `WebhookPoster` | `webhook-poster.ts` | `FetchWebhookPoster` | `FakeWebhookPoster` (`testing.ts`) | POST to an operator-named URL; a redirect is not followed | | `IdGenerator` | `id-generator.ts` | `CryptoIdGenerator` | none; tests inline one | Random ids | | `TokenSecrets` | `token-secrets.ts` | `CryptoTokenSecrets` | none; tests inline one | New secret, its hash | diff --git a/src/ports/index.ts b/src/ports/index.ts index a3b88170d..06f9bdeca 100644 --- a/src/ports/index.ts +++ b/src/ports/index.ts @@ -129,8 +129,16 @@ export { } from "./host-load.js"; export { filterSqliteExperimentalWarning, + isLockError, NodeSqliteOpener, + passesQuickCheck, SqliteUnavailableError, } from "./sqlite.js"; -export type { SqliteDatabase, SqliteOpener, SqliteStatement } from "./sqlite.js"; +export type { + SqliteDatabase, + SqliteOpener, + SqliteSchemaOwner, + SqliteStatement, + SqliteValue, +} from "./sqlite.js"; export { FetchWebhookPoster, type WebhookPoster } from "./webhook-poster.js"; diff --git a/src/ports/logger.ts b/src/ports/logger.ts index 4bce73fb2..b943d2105 100644 --- a/src/ports/logger.ts +++ b/src/ports/logger.ts @@ -118,7 +118,7 @@ export class MemoryLogSink implements LogSink { const DEFAULT_MAX_BYTES = 5 * 1024 * 1024; // why: Owner-only, like the other files that hold secrets or state (`config.json`, -// `state.json`, `tokens.json`, `admin.token`): the trust boundary is the OS user, and a shared +// `state.db`, `tokens.json`, `admin.token`): the trust boundary is the OS user, and a shared // runner's other users have no business reading a daemon's log. Set at each // `open`, never a later `chmod`, so no generation is ever born world-readable. const FILE_MODE = 0o600; diff --git a/src/ports/paths.ts b/src/ports/paths.ts index c7c98b5ef..01c8f0672 100644 --- a/src/ports/paths.ts +++ b/src/ports/paths.ts @@ -4,7 +4,7 @@ import { join, resolve } from "node:path"; import type { Filesystem } from "./filesystem.js"; /** - * Resolves simlock's data directory (config.json, state.json, daemon.sock, daemon.log, + * why: Resolves simlock's data directory (config.json, state.db, daemon.sock, daemon.log, * and the device roots under `devices/`). `SIMLOCK_HOME` overrides the default * `~/.simlock` -- used by tests that need an isolated data directory per daemon instance, * and by anyone running multiple independent simlock installs on one machine. diff --git a/src/ports/sqlite.ts b/src/ports/sqlite.ts index 35f2c672d..3022544cf 100644 --- a/src/ports/sqlite.ts +++ b/src/ports/sqlite.ts @@ -19,6 +19,12 @@ export interface SqliteDatabase { close(): void; } +export interface SqliteSchemaOwner { + readonly name: string; + readonly version: number; + readonly migrations: readonly string[]; +} + export interface SqliteOpener { open(path: string, options: { readonly readOnly: boolean }): Promise; } @@ -35,7 +41,7 @@ export class NodeSqliteOpener implements SqliteOpener { } // why: SQLite creates a missing file 0644 (less the umask) and gives -wal and -shm the main // file's mode, so creating it 0600 first keeps all three owner-only, like the other local state. - if (!options.readOnly) closeSync(openSync(path, "a", 0o600)); + if (!options.readOnly && path !== ":memory:") closeSync(openSync(path, "a", 0o600)); return new engine.DatabaseSync(path, { readOnly: options.readOnly }); } } @@ -53,3 +59,21 @@ export function filterSqliteExperimentalWarning(): void { (emit as (...args: unknown[]) => void)(warning, ...rest); }) as typeof process.emitWarning; } + +const SQLITE_BUSY = 5; +const SQLITE_LOCKED = 6; + +export function passesQuickCheck(database: SqliteDatabase): boolean { + const rows = database.prepare("PRAGMA quick_check").all(); + return rows.length === 1 && Object.values(rows[0] ?? {})[0] === "ok"; +} + +export function isLockError(error: unknown): boolean { + if (typeof error !== "object" || error === null) return false; + const { errcode, message } = error as { errcode?: unknown; message?: unknown }; + if (typeof errcode === "number") { + const primary = errcode & 0xff; + return primary === SQLITE_BUSY || primary === SQLITE_LOCKED; + } + return typeof message === "string" && /database (table )?is locked|busy/i.test(message); +} diff --git a/src/state/AGENTS.md b/src/state/AGENTS.md new file mode 100644 index 000000000..cf73029b7 --- /dev/null +++ b/src/state/AGENTS.md @@ -0,0 +1,29 @@ +# State + +Does: opens a daemon's `state.db` in its data directory, refuses what it cannot trust, and migrates each owner's tables. +Entry: `index.ts` → `openStateDatabase(options)`, `StateDatabase`, `STATE_DB_NAME`. +Uses: ports (`SqliteOpener`, `Filesystem`, `Logger`, `SqliteSchemaOwner`). Never imports: core, leasing, daemon, drivers, gateway. +Imported by: daemon (opens it for both roles), core (`Registry` takes a `StateDatabase`). +Flows: [startup](../../docs/internal/flows/startup.md). Decision: [ADR 0036](../../docs/internal/adr/0036-daemon-state-is-a-sqlite-database-whose-tables-each-owner-keeps.md). + +## Files + +| File | Role | +| ---------- | ----------------------------------------------------------------------------------------- | +| `index.ts` | the surface | +| `open.ts` | the old-file check, the open, `quick_check`, the version transaction, `transaction(work)` | + +## How it works + +1. **Old files.** Any of `oldFiles` in the data directory refuses the start; the message carries the role's `upgradeStep` with `` replaced by the file found. Nothing is opened or created. +2. **Open.** `node:sqlite` missing refuses. The file opens (mode `0600`), then `busy_timeout=5000`, `journal_mode=WAL`, `synchronous=NORMAL`. A lock past 5 s refuses with the lock message; any other error refuses as damage (`open: `). +3. **Check.** `PRAGMA quick_check` must answer exactly one `ok` row; anything else refuses as damage (`quick_check: `). +4. **Versions.** In one `BEGIN IMMEDIATE` transaction: create `schema_versions`, then for each owner read its version, refuse a newer one, run `migrations[from]` for each step up and write the version. A throw rolls back every owner's steps and refuses with the migration message. Reading inside the write transaction makes two daemons starting at once migrate once. +5. **Use.** `transaction(work)` runs `work` in a `BEGIN IMMEDIATE` and rolls back on a throw. The caller owns its tables; this module never reads them. + +## Rules + +- `state.db` is never deleted or renamed by Simlock; a refusal leaves it untouched. +- Each owner creates only its own tables and keeps its own version in `schema_versions`. +- A refusal is a thrown `Error` whose message is the user-facing text; the daemon logs it as `Daemon failed to start`. +- The module has no table of its own except `schema_versions`. diff --git a/src/state/CLAUDE.md b/src/state/CLAUDE.md new file mode 100644 index 000000000..43c994c2d --- /dev/null +++ b/src/state/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/src/state/index.ts b/src/state/index.ts new file mode 100644 index 000000000..b472f65ac --- /dev/null +++ b/src/state/index.ts @@ -0,0 +1,2 @@ +export { openStateDatabase, STATE_DB_NAME } from "./open.js"; +export type { StateDatabase } from "./open.js"; diff --git a/src/state/open.ts b/src/state/open.ts new file mode 100644 index 000000000..f68eed3e8 --- /dev/null +++ b/src/state/open.ts @@ -0,0 +1,196 @@ +import { join } from "node:path"; + +import { + type Filesystem, + isLockError, + type Logger, + passesQuickCheck, + type SqliteDatabase, + type SqliteOpener, + type SqliteSchemaOwner, + SqliteUnavailableError, +} from "../ports/index.js"; + +export const STATE_DB_NAME = "state.db"; + +const BUSY_TIMEOUT_MS = 5_000; + +export interface OpenStateDatabaseOptions { + readonly dataDirectory: string; + readonly sqlite: SqliteOpener; + readonly filesystem: Filesystem; + readonly owners: readonly SqliteSchemaOwner[]; + readonly oldFiles: readonly string[]; + readonly upgradeStep: string; + readonly logger: Logger; +} + +export interface StateDatabase { + readonly database: SqliteDatabase; + transaction(work: () => T): T; + close(): void; +} + +class StateRefusal extends Error { + constructor(message: string, options?: ErrorOptions) { + super(message, options); + this.name = "StateRefusal"; + } +} + +function describe(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +function damaged(path: string, detail: string, cause: unknown): StateRefusal { + return new StateRefusal( + `${path} is damaged (${detail}). Move it away to start with empty state; every device and lease it held is forgotten.`, + { cause }, + ); +} + +function refusalFor(error: unknown, path: string): StateRefusal { + if (error instanceof StateRefusal) return error; + if (isLockError(error)) { + return new StateRefusal( + `${path} is locked by another process. Stop the other Simlock daemon using it, then start again.`, + { cause: error }, + ); + } + return damaged(path, `open: ${describe(error)}`, error); +} + +export async function openStateDatabase(options: OpenStateDatabaseOptions): Promise { + const { dataDirectory, filesystem, owners } = options; + for (const name of options.oldFiles) { + const oldFile = join(dataDirectory, name); + if (await filesystem.exists(oldFile)) { + throw new StateRefusal( + `Found ${oldFile}, which this Simlock no longer reads. To upgrade: ${options.upgradeStep.replaceAll("", oldFile)} See "Breaking: state moves to state.db" in docs/CLI.md.`, + ); + } + } + await filesystem.mkdirp(dataDirectory); + const path = join(dataDirectory, STATE_DB_NAME); + let database: SqliteDatabase | undefined; + try { + database = await options.sqlite.open(path, { readOnly: false }); + configure(database); + check(database, path); + migrate(database, owners, path, options.logger); + } catch (error: unknown) { + try { + database?.close(); + } catch { + // why: the open already failed; the refusal is what the caller must see + } + if (error instanceof SqliteUnavailableError) { + throw new StateRefusal("node:sqlite is not available; Simlock needs Node 22.13 or later.", { + cause: error, + }); + } + throw refusalFor(error, path); + } + return stateDatabase(database); +} + +function configure(database: SqliteDatabase): void { + database.exec(`PRAGMA busy_timeout=${BUSY_TIMEOUT_MS}`); + database.exec("PRAGMA journal_mode=WAL"); + database.exec("PRAGMA synchronous=NORMAL"); +} + +function check(database: SqliteDatabase, path: string): void { + let first: unknown; + try { + if (passesQuickCheck(database)) return; + first = Object.values(database.prepare("PRAGMA quick_check").all()[0] ?? {})[0]; + } catch (error: unknown) { + if (isLockError(error)) throw error; + throw damaged(path, `quick_check: ${describe(error)}`, error); + } + throw damaged(path, `quick_check: ${String(first)}`, undefined); +} + +function stateDatabase(database: SqliteDatabase): StateDatabase { + let closed = false; + return { + close: () => { + if (closed) return; + closed = true; + database.close(); + }, + database, + transaction: (work) => inTransaction(database, work), + }; +} + +function inTransaction(database: SqliteDatabase, work: () => T): T { + database.exec("BEGIN IMMEDIATE"); + try { + const result = work(); + database.exec("COMMIT"); + return result; + } catch (error: unknown) { + try { + database.exec("ROLLBACK"); + } catch { + // why: the connection may already have ended the transaction; the first error is the one to report + } + throw error; + } +} + +function migrate( + database: SqliteDatabase, + owners: readonly SqliteSchemaOwner[], + path: string, + logger: Logger, +): void { + inTransaction(database, () => { + database.exec( + "CREATE TABLE IF NOT EXISTS schema_versions (owner TEXT PRIMARY KEY, version INTEGER NOT NULL) STRICT", + ); + for (const owner of owners) migrateOwner(database, owner, path, logger); + }); +} + +function migrateOwner( + database: SqliteDatabase, + owner: SqliteSchemaOwner, + path: string, + logger: Logger, +): void { + const row = database + .prepare("SELECT version FROM schema_versions WHERE owner = ?") + .get(owner.name); + const stored = row === undefined ? 0 : Number(row.version); + if (stored > owner.version) { + throw new StateRefusal( + `${owner.name} in ${path} is at version ${String(stored)}; this Simlock knows up to ${String(owner.version)}. Upgrade Simlock, or move state.db away.`, + ); + } + if (stored === owner.version) return; + for (let from = stored; from < owner.version; from += 1) { + try { + database.exec(owner.migrations[from] ?? ""); + } catch (error: unknown) { + if (isLockError(error)) throw error; + throw new StateRefusal( + `${owner.name} in ${path} could not move from version ${String(from)} to ${String(from + 1)}: ${describe(error)}. Upgrade Simlock, or move state.db away.`, + { cause: error }, + ); + } + logger.debug("Moved a state.db schema owner up one version", { + from, + owner: owner.name, + to: from + 1, + }); + } + database + .prepare( + `INSERT INTO schema_versions (owner, version) VALUES (?, ?) + ON CONFLICT (owner) DO UPDATE SET version = excluded.version`, + ) + .run(owner.name, owner.version); +} diff --git a/src/state/state.test.ts b/src/state/state.test.ts new file mode 100644 index 000000000..fad509dad --- /dev/null +++ b/src/state/state.test.ts @@ -0,0 +1,269 @@ +import { existsSync, statSync } from "node:fs"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; + +import { ProbeSqliteOpener } from "../history/testing.js"; +import { + NodeFilesystem, + NodeSqliteOpener, + NoopLogger, + type SqliteOpener, + type SqliteSchemaOwner, +} from "../ports/index.js"; +import { openStateDatabase, STATE_DB_NAME } from "./index.js"; + +const directories: string[] = []; + +afterEach(async () => { + await Promise.all( + directories.splice(0).map((path) => rm(path, { force: true, recursive: true })), + ); +}); + +const sqlite = new NodeSqliteOpener(); + +const owners: readonly SqliteSchemaOwner[] = [ + { + migrations: [ + "CREATE TABLE runs (step TEXT NOT NULL) STRICT", + "INSERT INTO runs VALUES ('alpha-1')", + ], + name: "alpha", + version: 2, + }, + { + migrations: ["CREATE TABLE beta_rows (id TEXT NOT NULL) STRICT"], + name: "beta", + version: 1, + }, +]; + +async function newDirectory(): Promise { + const directory = await mkdtemp(join(tmpdir(), "simlock-state-")); + directories.push(directory); + return directory; +} + +function open(dataDirectory: string, schemaOwners: readonly SqliteSchemaOwner[] = owners) { + return openStateDatabase({ + dataDirectory, + filesystem: new NodeFilesystem(), + logger: new NoopLogger(), + oldFiles: ["state.json"], + owners: schemaOwners, + sqlite, + upgradeStep: "remove it.", + }); +} + +describe("openStateDatabase", () => { + it("on an empty folder creates state.db mode 0600 and records each owner's version, sets WAL, busy_timeout 5000 and synchronous NORMAL, and a second open runs no migration", async () => { + const directory = await newDirectory(); + const path = join(directory, STATE_DB_NAME); + + const first = await open(directory); + expect(existsSync(path)).toBe(true); + expect(statSync(path).mode & 0o777).toBe(0o600); + expect( + first.database.prepare("SELECT owner, version FROM schema_versions ORDER BY owner").all(), + ).toEqual([ + { owner: "alpha", version: 2 }, + { owner: "beta", version: 1 }, + ]); + expect(first.database.prepare("SELECT step FROM runs").all()).toEqual([{ step: "alpha-1" }]); + expect(Object.values(first.database.prepare("PRAGMA journal_mode").get() ?? {})).toEqual([ + "wal", + ]); + expect(Object.values(first.database.prepare("PRAGMA busy_timeout").get() ?? {})).toEqual([ + 5000, + ]); + expect(Object.values(first.database.prepare("PRAGMA synchronous").get() ?? {})).toEqual([1]); + first.close(); + + const second = await open(directory); + expect(second.database.prepare("SELECT step FROM runs").all()).toEqual([{ step: "alpha-1" }]); + second.close(); + }); +}); + +describe("openStateDatabase refusals", () => { + const SEE = 'See "Breaking: state moves to state.db" in docs/CLI.md.'; + + async function seeded(directory: string): Promise { + const path = join(directory, STATE_DB_NAME); + const state = await open(directory); + state.database.exec("CREATE TABLE padding (x TEXT)"); + for (let row = 0; row < 400; row += 1) { + state.database + .prepare("INSERT INTO padding (x) VALUES (?)") + .run(`row-${String(row)}`.repeat(20)); + } + state.database.exec("PRAGMA wal_checkpoint(TRUNCATE)"); + state.close(); + return path; + } + + it("refuses with each Shared values message, word for word, for an old file, a damaged file, a file that is not SQLite, a newer version and a migration that throws", async () => { + const upgradeStep = "remove and start again."; + const refusal = async ( + directory: string, + schemaOwners: readonly SqliteSchemaOwner[] = owners, + ): Promise => { + try { + const state = await openStateDatabase({ + dataDirectory: directory, + filesystem: new NodeFilesystem(), + logger: new NoopLogger(), + oldFiles: ["state.json"], + owners: schemaOwners, + sqlite, + upgradeStep, + }); + state.close(); + } catch (error: unknown) { + return (error as Error).message; + } + return "opened"; + }; + + const oldFileDirectory = await newDirectory(); + await writeFile(join(oldFileDirectory, "state.json"), "{}"); + expect(await refusal(oldFileDirectory)).toBe( + `Found ${join(oldFileDirectory, "state.json")}, which this Simlock no longer reads. To upgrade: remove ${join(oldFileDirectory, "state.json")} and start again. ${SEE}`, + ); + expect(existsSync(join(oldFileDirectory, STATE_DB_NAME))).toBe(false); + + const notSqlite = await newDirectory(); + await writeFile(join(notSqlite, STATE_DB_NAME), "this is not a sqlite database ".repeat(20)); + expect(await refusal(notSqlite)).toBe( + `${join(notSqlite, STATE_DB_NAME)} is damaged (open: file is not a database). Move it away to start with empty state; every device and lease it held is forgotten.`, + ); + + const damaged = await newDirectory(); + const damagedPath = await seeded(damaged); + const bytes = await readFile(damagedPath); + bytes.fill(0xff, 4096 * 3, 4096 * 8); + await writeFile(damagedPath, bytes); + expect(await refusal(damaged)).toMatch( + new RegExp( + `^${join(damaged, STATE_DB_NAME).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")} is damaged \\(quick_check: .+\\)\\. Move it away to start with empty state; every device and lease it held is forgotten\\.$`, + ), + ); + + const newer = await newDirectory(); + (await open(newer)).close(); + expect( + await refusal(newer, [ + { ...owners[0]!, migrations: owners[0]!.migrations.slice(0, 1), version: 1 }, + ]), + ).toBe( + `alpha in ${join(newer, STATE_DB_NAME)} is at version 2; this Simlock knows up to 1. Upgrade Simlock, or move state.db away.`, + ); + + const failing = await newDirectory(); + const failingOwners: readonly SqliteSchemaOwner[] = [ + owners[0]!, + { + migrations: ["CREATE TABLE gamma (x INTEGER) STRICT", "INSERT INTO nowhere VALUES (1)"], + name: "gamma", + version: 2, + }, + ]; + expect(await refusal(failing, failingOwners)).toBe( + `gamma in ${join(failing, STATE_DB_NAME)} could not move from version 1 to 2: no such table: nowhere. Upgrade Simlock, or move state.db away.`, + ); + const afterwards = await sqlite.open(join(failing, STATE_DB_NAME), { readOnly: true }); + expect(afterwards.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all()).toEqual( + [], + ); + afterwards.close(); + }); + + it( + "a lock held past 5 s at open, at the quick_check, at BEGIN IMMEDIATE and in a migration step gives the lock message, not the damage one", + { timeout: 30_000 }, + async () => { + const directory = await newDirectory(); + const path = join(directory, STATE_DB_NAME); + const lockMessage = `${path} is locked by another process. Stop the other Simlock daemon using it, then start again.`; + (await open(directory)).close(); + const refusal = async (opener: SqliteOpener, folder: string = directory): Promise => { + try { + ( + await openStateDatabase({ + dataDirectory: folder, + filesystem: new NodeFilesystem(), + logger: new NoopLogger(), + oldFiles: [], + owners, + sqlite: opener, + upgradeStep: "", + }) + ).close(); + } catch (error: unknown) { + return (error as Error).message; + } + return "opened"; + }; + const lockedAt = (sql: string) => + new ProbeSqliteOpener({ + fault: (call) => { + if (call.kind !== "open" && call.sql.startsWith(sql)) { + throw Object.assign(new Error("database is locked"), { errcode: 5 }); + } + }, + }); + + expect(await refusal(lockedAt("PRAGMA quick_check"))).toBe(lockMessage); + expect(await refusal(lockedAt("BEGIN IMMEDIATE"))).toBe(lockMessage); + expect(await refusal(lockedAt("CREATE TABLE runs"), await newDirectory())).toBe( + `${join(directories.at(-1)!, STATE_DB_NAME)} is locked by another process. Stop the other Simlock daemon using it, then start again.`, + ); + + const holder = await sqlite.open(path, { readOnly: false }); + holder.exec("PRAGMA locking_mode=EXCLUSIVE"); + holder.exec("BEGIN EXCLUSIVE"); + const message = await refusal(sqlite); + holder.exec("COMMIT"); + holder.close(); + expect(message).toBe(lockMessage); + }, + ); + + it("reads the versions inside the write transaction, so two daemons starting at once migrate once", async () => { + const directory = await newDirectory(); + let racing = false; + const other = await sqlite.open(join(directory, STATE_DB_NAME), { readOnly: false }); + const racingOpener = new ProbeSqliteOpener({ + fault: (call) => { + if (call.kind !== "exec" || call.sql !== "BEGIN IMMEDIATE" || racing) return; + racing = true; + other.exec("BEGIN IMMEDIATE"); + other.exec( + "CREATE TABLE schema_versions (owner TEXT PRIMARY KEY, version INTEGER NOT NULL) STRICT", + ); + other.exec(owners[0]!.migrations.join(";")); + other.exec("CREATE TABLE beta_rows (id TEXT NOT NULL) STRICT"); + other.exec("INSERT INTO schema_versions VALUES ('alpha', 2), ('beta', 1)"); + other.exec("COMMIT"); + other.close(); + }, + }); + + const state = await openStateDatabase({ + dataDirectory: directory, + filesystem: new NodeFilesystem(), + logger: new NoopLogger(), + oldFiles: [], + owners, + sqlite: racingOpener, + upgradeStep: "", + }); + + expect(racing).toBe(true); + expect(state.database.prepare("SELECT step FROM runs").all()).toEqual([{ step: "alpha-1" }]); + state.close(); + }); +});