diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index 8b88151e7..4d121b978 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -103,7 +103,7 @@ Simlock registry (ADR 0002, `docs/internal/adr/0002-opt-in-slim-ios-simulators.m only") is satisfied by waiting for that commit to become observable, not by waiting on a registry write: the driver writes the launchd overrides file while the simulator is shut down, boots it once, and only fires `onSlimmed` once the readback shows the overrides in force. The registry's own `device.ready` for that same boot is a separate, -later event, emitted through the normal readiness path once the driver call returns. A slim +later event, emitted through the normal readiness path once the driver call returns. A boot with a lease's except list (ADR 0066) reports `categories` as the smaller list (the worker's slim set minus the excepted categories), `signature` as that list's signature and `labelCount` as the labels written `true`, so a kept label that a slimmed category also lists is not counted; a boot whose smaller list is empty is granted `full` and emits none. A slim request on a runtime older than iOS 18.5 is resolved to a full spec before planning (ADR 0007 §4), so it never reaches a slim boot. A *skipped* slim on a slim-spec device -- its runtime id didn't parse, the overrides file could not be written, or the readback disagreed or failed -- is deliberately not an event: it isn't a fact worth putting in front of every event-bus diff --git a/src/core/driver.ts b/src/core/driver.ts index 01cf5d7d2..5acb20943 100644 --- a/src/core/driver.ts +++ b/src/core/driver.ts @@ -29,6 +29,7 @@ export interface ExactDeviceRequest { readonly osVersion?: string; readonly mode?: DeviceMode; readonly imageTag?: string; + readonly except?: readonly string[]; } export interface DeviceRequest extends Omit { @@ -301,6 +302,7 @@ export interface Driver { options: { readonly purpose: "prepare" | "recover"; readonly mode: DeviceMode; + readonly except?: readonly string[]; }, ): Promise; reclaim( @@ -598,6 +600,22 @@ export class UnsupportedRequestOptionError extends Error { } } +/** why: A refusal that carries its own message, where `UnsupportedRequestOptionError` builds a fixed one. */ +export class BadDeviceRequestError extends Error { + constructor(message: string) { + super(message); + this.name = "BadDeviceRequestError"; + } +} + +/** why: A device booted with a lease's except list but a kept category's service is not running, or that could not be shown (ADR 0066 §2): the driver refuses the device rather than tell the lease it is on. */ +export class KeptCategoriesError extends Error { + constructor(message: string) { + super(message); + this.name = "KeptCategoriesError"; + } +} + export class UnknownModelError extends Error { readonly class: DeviceClass | undefined; readonly model: string | undefined; diff --git a/src/core/index.ts b/src/core/index.ts index fed09fa5e..37ab84623 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -107,6 +107,8 @@ export { UnknownModelError, BaselineMismatchError, BaselineStaleError, + BadDeviceRequestError, + KeptCategoriesError, UnsupportedRequestOptionError, } from "./driver.js"; export { diff --git a/src/daemon/error-code.test.ts b/src/daemon/error-code.test.ts index 35e0e58eb..2027c49d1 100644 --- a/src/daemon/error-code.test.ts +++ b/src/daemon/error-code.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it } from "vitest"; -import { ComponentInstallerClosedError, UnsupportedRequestOptionError } from "../core/index.js"; +import { + BadDeviceRequestError, + ComponentInstallerClosedError, + UnsupportedRequestOptionError, +} from "../core/index.js"; import { NoCapacityError, ProvisionFailedError, @@ -57,5 +61,12 @@ describe("classifyError on a request option the driver does not have", () => { code: "BAD_REQUEST", message: "ios lease requests do not take imageTag", }); + + const bad = new BadDeviceRequestError('unknown slim category "wallet"'); + expect(classifyError(bad)).toBe("BAD_REQUEST"); + expect(describeLeaseRequestFailure(bad)).toEqual({ + code: "BAD_REQUEST", + message: 'unknown slim category "wallet"', + }); }); }); diff --git a/src/daemon/error-code.ts b/src/daemon/error-code.ts index bbb0fb05d..0e25d31f5 100644 --- a/src/daemon/error-code.ts +++ b/src/daemon/error-code.ts @@ -35,6 +35,7 @@ import { UnknownLeaseError, UnknownModelError, UnknownPassthroughToolError, + BadDeviceRequestError, UnsupportedRequestOptionError, type LeaseRequestFailure, } from "../core/index.js"; @@ -153,7 +154,7 @@ export function classifyError(error: unknown): SimlockErrorCode | undefined { } // A request option the platform's driver does not have: the request itself is wrong, and // asking again unchanged can never succeed. - if (error instanceof UnsupportedRequestOptionError) { + if (error instanceof UnsupportedRequestOptionError || error instanceof BadDeviceRequestError) { return "BAD_REQUEST"; } if (error instanceof InsufficientDiskSpaceError) { diff --git a/src/drivers/ios/AGENTS.md b/src/drivers/ios/AGENTS.md index 80ec6ff4c..840166c59 100644 --- a/src/drivers/ios/AGENTS.md +++ b/src/drivers/ios/AGENTS.md @@ -18,6 +18,7 @@ Resolve and boot: - `RuntimeMissingError` is only for what a download can fix: an OS outside the device type's range, an installed runtime not paired with the type, and anything below iOS 16 are refused instead. - A boot is `simctl boot`, `bootstatus -b`, then `listapps` until it succeeds, on one deadline: bootstatus can finish before the installer accepts requests. - Slim (ADR 0060), on `prepare` of a slim spec only: the managed labels are merged into the simulator's `disabled.plist` before the boot (other entries kept; a failed write is logged and the boot goes on), and `launchctl print-disabled system` is read back after it. A label not as written returns `full`; a readback that fails returns `slim`; both call `onSlimSkipped`, logged only. Every label as written and the write ok: `slim`, and `onSlimmed` becomes `device.slimmed`. +- Slim `except` (ADR 0066, `slim-except.ts`): an excepted category's labels are written `false`; an unknown name is `BAD_REQUEST`; a kept label not read back throws `KeptCategoriesError`. - A recovery boot writes no overrides and reads nothing back. - The overrides folder lives outside the device set (`launchdOverridesRoot`), so `destroy` removes it itself after `simctl delete`. - After every boot and before the readback, `runAfterBoot` (`boot-courtesies.ts`) runs the volume step, then the window step. Each only reports its failure (`onSilenceFailed`, `onWindowFailed`), and the device stays in use. diff --git a/src/drivers/ios/index.test.ts b/src/drivers/ios/index.test.ts index 6153c0d9a..67de79faa 100644 --- a/src/drivers/ios/index.test.ts +++ b/src/drivers/ios/index.test.ts @@ -11,7 +11,6 @@ import { DriverCrashError, OwnedRootError, OWNED_ROOT_MARKER_FILE, - type OwnedRootMarker, PassthroughRefusedError, RuntimeMissingError, UnknownModelError, @@ -36,18 +35,36 @@ import { SLIM_CATEGORIES, supportsPersistentSlim, type SilenceFailedFact, - type SlimmedFact, type SlimSkippedFact, } from "./index.js"; import { memorySourceDatabase, plantReadySeed, plantSource } from "./testing.js"; +import { + FaultyFilesystem, + createSlimDriver, + dataPath, + deviceRoot, + driverData, + instanceId, + overridesFolder, + overridesPath, + overridesPlist, + overridesRoot, + parseOverrides, + plantManagedDevice, + prepareSlim, + prepareSlimWith, + printDisabled, + simctl, + simctlArgs, + slimBootCalls, + waitForCalls, +} from "./test-slim.js"; const listFixture = readFileSync(new URL("./fixtures/simctl-list.json", import.meta.url), "utf8"); const listDevicesFixture = readFileSync( new URL("./fixtures/simctl-list-devices.json", import.meta.url), "utf8", ); -const deviceRoot = "/Devices"; -const instanceId = "instance-1"; const listInvocation = simctl("list", "-j", "devicetypes", "runtimes"); const listDevicesInvocation = simctl("list", "-j", "devices"); @@ -120,22 +137,11 @@ const listFixtureAfterDownload = JSON.stringify({ ], }); const spec = { physical: false, model: "iPhone 16", osVersion: "26.5", platform: "ios" } as const; -const driverData = { - deviceTypeId: "com.apple.CoreSimulator.SimDeviceType.iPhone-16", - name: "simlock-device-1", - runtimeId: "com.apple.CoreSimulator.SimRuntime.iOS-26-5", - udid: "00000000-0000-0000-0000-000000000001", -} as const; -const dataPath = `${deviceRoot}/${driverData.udid}/data`; const durableMarkPath = `${deviceRoot}/${driverData.udid}/simlock-mark.json`; const erasableMarkPath = `${dataPath}/simlock-mark.json`; /** why: Every simctl call the driver makes is scoped to its device set; so is every expectation. */ -function simctlArgs(...args: readonly string[]): string[] { - return ["simctl", "--set", deviceRoot, ...args]; -} - const scopedRunners: ScriptedProcessRunner[] = []; const legacyUdid = "00000000-0000-0000-0000-0000000000ff"; @@ -202,10 +208,6 @@ async function seededDatabase( }); } -function simctl(...args: readonly string[]): { readonly command: string; readonly args: string[] } { - return { args: simctlArgs(...args), command: "xcrun" }; -} - function deviceListResponse(state: string): string { return JSON.stringify({ devices: { @@ -4897,48 +4899,6 @@ async function createDriver( }); } -/** - * why: Bounded on purpose. An unexpected invocation makes `ScriptedProcessRunner.spawn` throw - * synchronously, `#invokeSimctl` turns that into a `DriverCrashError`, and the call this - * is waiting for never arrives -- an unbounded spin then hangs the whole suite instead of - * reporting which argv the driver actually produced. - */ -async function waitForCalls(runner: ScriptedProcessRunner, count: number): Promise { - for (let tick = 0; tick < 1_000 && runner.calls.length < count; tick += 1) { - await Promise.resolve(); - } - - expect( - runner.calls.map((call) => call.args), - `simctl never reached ${String(count)} calls`, - ).toHaveLength(count); -} - -/** - * why: Plants a managed device in the root the way a real one arrives: inside a root Simlock - * already owns and marked as such. - * - * A bare `mkdirp(dataPath)` describes a state that cannot occur -- `ensureOwnedRoot` creates - * a root empty and marks it in the same publish, so a root holding a device always carries - * the marker. Without it the fixture is a non-empty unmarked root, which the driver is - * required to refuse (ADR 0001, decision 2), and every test built on it fails at `create` - * for a reason that has nothing to do with what it set out to prove. - */ -async function plantManagedDevice(filesystem: Filesystem): Promise { - const marker: OwnedRootMarker = { - instanceId, - owner: "simlock", - platform: "ios", - schemaVersion: 1, - }; - await filesystem.mkdirp(deviceRoot); - await filesystem.writeFileAtomic( - `${deviceRoot}/${OWNED_ROOT_MARKER_FILE}`, - JSON.stringify(marker), - ); - await filesystem.mkdirp(dataPath); -} - /** why: the state a case starts from, with the writes and modes the planting made forgotten. */ async function plantOverrides( filesystem: FaultyFilesystem, @@ -4971,37 +4931,6 @@ function runnerReadingFileAtBoot(filesystem: FaultyFilesystem, clock: FakeClock) return { fileAtBoot: () => contents, runner }; } -async function createSlimDriver( - runner: ScriptedProcessRunner, - filesystem: Filesystem, - slim: { - readonly categories?: readonly string[]; - readonly bootTimeoutMs: number; - }, - onSlimmed?: (fact: SlimmedFact) => void, - onSlimSkipped?: (fact: SlimSkippedFact) => void, - slimByDefault = false, - clock = new FakeClock(), -): Promise { - return await IosSimctlDriver.create({ - database: await memorySourceDatabase(), - driverConfig: { deviceRoot }, - instanceId, - simlockHome: "/home/.simlock", - clock, - filesystem, - idGenerator: { generate: () => "device-1" }, - ...(onSlimmed === undefined ? {} : { onSlimmed }), - ...(onSlimSkipped === undefined ? {} : { onSlimSkipped }), - launchdOverridesRoot: overridesRoot, - processRunner: runner, - config: { slim }, - slimByDefault, - }); -} - -const overridesRoot = "/private/var/tmp"; - /** why: a LaunchServices database file and a neighbour that must stay, in the device folder `device`. */ async function plantLaunchServices(filesystem: MemoryFilesystem, device: string): Promise { const folder = `${device}/data/var/db/lsd`; @@ -5020,21 +4949,6 @@ async function launchServicesFiles( return (await filesystem.readdir(`${device}/data/var/db/lsd`)).sort(); } -function overridesFolder(udid: string): string { - return `${overridesRoot}/com.apple.CoreSimulator.SimDevice.${udid}`; -} - -function overridesPath(udid: string): string { - return `${overridesFolder(udid)}/disabled.plist`; -} - -function overridesPlist(entries: Readonly>): string { - const lines = Object.entries(entries).map( - ([label, off]) => `${label}<${String(off)}/>`, - ); - return `\n${lines.join("")}\n`; -} - /** why: Records every `warn` message, so the destroy's log line is asserted on its text. */ class RecordingLogger implements Logger { readonly warnings: string[] = []; @@ -5063,45 +4977,6 @@ class ModeRecordingFilesystem extends MemoryFilesystem { } } -/** why: Records what is written and fails the one operation a test names, as a full or unwritable store would. */ -class FaultyFilesystem extends MemoryFilesystem { - readonly writes: string[] = []; - readonly modes: { folder?: number | undefined; file?: number | undefined } = {}; - failing: "writeFileAtomic" | "mkdirp" | "rm" | "copyFile" | undefined; - failureMessage = "disk full"; - - override async writeFileAtomic( - path: string, - contents: string, - options?: Parameters[2], - ): Promise { - if (this.failing === "writeFileAtomic" && path.endsWith("disabled.plist")) { - throw new Error(this.failureMessage); - } - await super.writeFileAtomic(path, contents, options); - this.writes.push(path); - if (path.endsWith("disabled.plist")) this.modes.file = options?.mode; - } - - override async mkdirp(path: string, options?: Parameters[1]) { - if (this.failing === "mkdirp" && path.includes("CoreSimulator.SimDevice")) { - throw new Error(this.failureMessage); - } - await super.mkdirp(path, options); - if (path.includes("CoreSimulator.SimDevice")) this.modes.folder = options?.mode; - } - - override async copyFile(from: string, to: string): Promise { - if (this.failing === "copyFile") throw new Error(this.failureMessage); - await super.copyFile(from, to); - } - - override async rm(path: string): Promise { - if (this.failing === "rm") throw new Error(this.failureMessage); - await super.rm(path); - } -} - // why: spelled out here, not imported: the labels simslim v0.13.0 never disables (ADR 0060 §1). const neverDisabled = ["com.apple.assistantd", "com.apple.gamed", "com.apple.sharingd"]; @@ -5122,20 +4997,6 @@ function widgetsLabelList(): readonly string[] { return SLIM_CATEGORIES.find((category) => category.name === "widgets")?.labels ?? []; } -function parseOverrides(plist: string): Record { - const entries: Record = {}; - for (const match of plist.matchAll(/([^<]*)<\/key>\s*<(true|false)\/>/g)) { - entries[match[1] ?? ""] = match[2] === "true"; - } - return entries; -} - -/** why: `launchctl print-disabled system` as launchd prints it: one `"label" => state` line per entry. */ -function printDisabled(entries: Readonly>): string { - const lines = Object.entries(entries).map(([label, state]) => `\t"${label}" => ${state}`); - return ["disabled services = {", ...lines, "}", ""].join("\n"); -} - /** why: The readback of a boot that honoured every label as written. */ function wantedReadback(): string { return printDisabled( @@ -5148,66 +5009,6 @@ function wantedReadback(): string { ); } -/** why: The calls of one slim boot: the boot, its wait, the installer poll, then the readback. */ -function slimBootCalls(udid: string, readback: string) { - return [ - { match: simctl("boot", udid) }, - { match: simctl("bootstatus", udid, "-b") }, - { match: simctl("listapps", udid) }, - { - match: simctl("spawn", udid, "launchctl", "print-disabled", "system"), - result: { code: 0, stderr: "", stdout: readback }, - }, - ]; -} - -type ReadbackScript = - | { readonly stdout: string } - | { readonly code: number; readonly stderr: string } - | "hangs"; - -/** why: One slim `prepare` of the 18.5 device, with the readback scripted; the 120 s limit runs on a fake clock. */ -async function prepareSlimWith( - filesystem: FaultyFilesystem, - readback: ReadbackScript, - slimOptions: { readonly categories?: readonly string[]; readonly bootTimeoutMs: number }, -) { - const udid = "00000000-0000-0000-0000-000000000001"; - const runtimeId = "com.apple.CoreSimulator.SimRuntime.iOS-18-5"; - const calls = slimBootCalls(udid, ""); - const readbackCall = - readback === "hangs" - ? { hangs: true, match: calls[3]!.match } - : "stdout" in readback - ? { match: calls[3]!.match, result: { code: 0, stderr: "", stdout: readback.stdout } } - : { - match: calls[3]!.match, - result: { code: readback.code, stderr: readback.stderr, stdout: "" }, - }; - const runner = new ScriptedProcessRunner([...calls.slice(0, 3), readbackCall]); - const clock = new FakeClock(); - const onSlimmed = vi.fn(); - const onSlimSkipped = vi.fn(); - const driver = await createSlimDriver( - runner, - filesystem, - slimOptions, - onSlimmed, - onSlimSkipped, - false, - clock, - ); - const ready = driver.makeReady( - { address: udid, deviceId: udid, driverData: { ...driverData, runtimeId } }, - prepareSlim, - ); - if (readback === "hangs") { - await waitForCalls(runner, 4); - clock.advance(120_000); - } - return { onSlimSkipped, onSlimmed, result: await ready, runner }; -} - /** why: The readback of a boot that honoured every label, with the given labels changed or dropped (`undefined`). */ function readbackWith(changes: Readonly>): string { const entries: Record = Object.fromEntries( @@ -5274,7 +5075,6 @@ function assetInfoPlist(simulatorVersion: string, build: string): string { } const prepareFull = { mode: "full", purpose: "prepare" } as const; -const prepareSlim = { mode: "slim", purpose: "prepare" } as const; const recoverFull = { mode: "full", purpose: "recover" } as const; const recoverSlim = { mode: "slim", purpose: "recover" } as const; diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index 2dce1e0cb..2d1425596 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -2,6 +2,7 @@ import { dirname, join } from "node:path"; import { BootTimeoutError, + KeptCategoriesError, type ComponentInstallProgress, type ComponentInstallResult, type ComponentReceipt, @@ -35,7 +36,6 @@ import { type PassthroughCommand, type PassthroughContext, PassthroughRefusedError, - type ObservedRunState, removeListedComponent, RuntimeMissingError, sameReceipt, @@ -85,7 +85,22 @@ import { iosRuntimeVersionFromId } from "./runtime-version.js"; import { IosSourceTable, type ReadySeed, type SourceRow } from "./source-data.js"; import { createIosScreenCapture } from "./screen-capture.js"; import type { IosDriverConfig } from "./definition.js"; -import { overridesFor, resolveSlimCategories, slimSignature } from "./slim-labels.js"; +import { + overridesFor, + resolveSlimCategories, + slimSignature, + type SlimCategory, +} from "./slim-labels.js"; +import { assertKeptEnabled, checkExcept, splitByExcept } from "./slim-except.js"; +import { + isRecord, + parseCatalog, + parseManagedDevices, + type DeviceType, + type Runtime, + type SimctlCatalog, + UNBOUNDED_VERSION, +} from "./simctl-parse.js"; import { parseOverridesPlist, parsePrintDisabled, renderOverridesPlist } from "./slim-overrides.js"; /** why: ADR 0061 §1: a `making` row of this process older than this is a make that never ended. */ @@ -101,9 +116,6 @@ const PROVISION_ESTIMATE_MS = 500; // being deleted, which it does for a few seconds after `simctl runtime delete` answers (#259). const DELETING_POLL_MS = 1_000; const LATEST_COMPONENT = "latest"; -// why: `simctl`'s `minRuntimeVersion` / `maxRuntimeVersion` encode "no bound" as 0xFFFFFF -// (255.255.255) rather than omitting the field. -const UNBOUNDED_VERSION = 0xff_ff_ff; // why: `xcodebuild -downloadPlatform iOS -buildVersion` only reaches back to iOS 16.0 (Xcode // 16.1+); older runtimes must be installed through Xcode itself. const IOS_DOWNLOAD_FLOOR: readonly [number, number, number] = [16, 0, 0]; @@ -250,6 +262,7 @@ type SlimWrite = readonly kind: "written"; readonly resolved: ReturnType; readonly wanted: ReadonlyMap; + readonly kept: readonly SlimCategory[]; readonly startedAt: number; readonly writeError: string | undefined; }; @@ -262,34 +275,12 @@ const PRODUCT_FAMILY_CLASSES: ReadonlyMap = new ["Apple Vision", "vision"], ]); -interface DeviceType { - readonly identifier: string; - readonly name: string; - readonly minRuntimeVersion: number; - readonly maxRuntimeVersion: number; - readonly productFamily: string | undefined; -} - -interface Runtime { - readonly identifier: string; - readonly name: string; - readonly version: string; - readonly build?: string; - readonly isAvailable: boolean; - readonly supportedDeviceTypeIds: ReadonlySet; -} - interface RuntimeAsset { readonly path: string; readonly version: string; readonly build: string; } -interface SimctlCatalog { - readonly deviceTypes: readonly DeviceType[]; - readonly runtimes: readonly Runtime[]; -} - interface ResolvedIosSpec { readonly deviceType: DeviceType; readonly runtime: Runtime; @@ -442,6 +433,7 @@ export class IosSimctlDriver implements Driver { if (request.imageTag !== undefined) { throw new UnsupportedRequestOptionError("ios", "imageTag"); } + checkExcept(request.except ?? [], resolveSlimCategories(this.#slim?.categories)); const catalog = await this.#loadCatalog(); const deviceType = findDeviceType(catalog, request.model); @@ -1156,7 +1148,11 @@ export class IosSimctlDriver implements Driver { async makeReady( device: DriverDevice, - options: { readonly purpose: "prepare" | "recover"; readonly mode: DeviceMode }, + options: { + readonly purpose: "prepare" | "recover"; + readonly mode: DeviceMode; + readonly except?: readonly string[]; + }, ): Promise { const data = iosDriverData(device); const { plan, bootstatusTimeoutMs } = planSlimBoot( @@ -1166,7 +1162,9 @@ export class IosSimctlDriver implements Driver { options, ); const write = - plan.kind === "apply" ? await this.#writeOverrides(data.udid, plan.slim) : undefined; + plan.kind === "apply" + ? await this.#writeOverrides(data.udid, plan.slim, options.except) + : undefined; await this.#bootAndWait(data.udid, device.deviceId, bootstatusTimeoutMs); await runAfterBoot(this.#afterBoot, data.udid, device.deviceId); @@ -1243,9 +1241,14 @@ export class IosSimctlDriver implements Driver { return false; } - async #writeOverrides(udid: string, slim: SlimOptions): Promise { - const resolved = resolveSlimCategories(slim.categories); - if (resolved.categories.length === 0) { + async #writeOverrides( + udid: string, + slim: SlimOptions, + except: readonly string[] = [], + ): Promise { + const configured = resolveSlimCategories(slim.categories); + const { kept, resolved } = splitByExcept(configured, except); + if (configured.categories.length === 0) { return { detail: `none of the configured slim categories (${(slim.categories ?? []).join(", ")}) are known`, kind: "no-categories", @@ -1253,7 +1256,7 @@ export class IosSimctlDriver implements Driver { } const startedAt = this.#clock.now(); - const wanted = overridesFor(resolved.categories); + const wanted = overridesFor(resolved.categories, kept); let writeError: string | undefined; try { const folder = this.#overridesFolder(udid); @@ -1268,7 +1271,7 @@ export class IosSimctlDriver implements Driver { writeError = `could not write the launchd overrides file: ${errorMessage(error)}`; } - return { kind: "written", resolved, startedAt, wanted, writeError }; + return { kept, kind: "written", resolved, startedAt, wanted, writeError }; } async #readOverrides(file: string): Promise> { @@ -1288,6 +1291,9 @@ export class IosSimctlDriver implements Driver { data: IosDriverData, write: Extract, ): Promise { + if (write.kept.length > 0 && write.writeError !== undefined) { + throw new KeptCategoriesError(write.writeError); + } const outcome = await this.#invokeSimctl( ["spawn", data.udid, "launchctl", "print-disabled", "system"], READBACK_TIMEOUT_MS, @@ -1295,15 +1301,22 @@ export class IosSimctlDriver implements Driver { const details = write.writeError === undefined ? [] : [write.writeError]; if (outcome.kind === "timed-out" || outcome.result.code !== 0) { - const reason = - outcome.kind === "timed-out" - ? `timed out after ${String(READBACK_TIMEOUT_MS)}ms` - : `exit ${String(outcome.result.code)}: ${outcome.result.stderr.trim()}`; - details.push(`could not read back the launchd overrides: ${reason}`); + details.push(`could not read back the launchd overrides: ${readBackFailure(outcome)}`); + if (write.kept.length > 0) throw new KeptCategoriesError(details.join("; ")); return this.#skipApply(device, data, details.join("; "), "slim"); } + return this.#judgeReadBack(device, data, write, details, outcome.result.stdout); + } - const read = parsePrintDisabled(outcome.result.stdout); + #judgeReadBack( + device: DriverDevice, + data: IosDriverData, + write: Extract, + details: string[], + stdout: string, + ): DriverDevice { + const read = parsePrintDisabled(stdout); + assertKeptEnabled(write.kept, read); const mismatched = [...write.wanted.keys()] .sort() .filter((label) => (read.get(label) ?? false) !== write.wanted.get(label)); @@ -1317,18 +1330,26 @@ export class IosSimctlDriver implements Driver { return this.#skipApply(device, data, details.join("; "), "slim"); } - const labelCount = [...write.wanted.values()].filter(Boolean).length; + // why: an except list naming the whole slim set slims nothing: full, no `device.slimmed`. + if (write.resolved.categories.length === 0) return this.#asIs(device, data, "full"); + this.#reportSlimmed(device, data, write); + return this.#asIs(device, data, "slim"); + } + + #reportSlimmed( + device: DriverDevice, + data: IosDriverData, + write: Extract, + ): void { this.#onSlimmed?.({ address: data.udid, categories: write.resolved.categories.map((category) => category.name), deviceId: device.deviceId, durationMs: this.#clock.now() - write.startedAt, - labelCount, + labelCount: [...write.wanted.values()].filter(Boolean).length, signature: slimSignature(write.resolved.categories), unknownLabels: [...write.resolved.unknown], }); - - return this.#asIs(device, data, "slim"); } #skipApply( @@ -2135,105 +2156,6 @@ function configuredDeviceRoot(options: IosSimctlDriverOptions): string { return configured ?? join(options.simlockHome, "devices", "ios"); } -interface ParsedManagedDevice { - readonly dataPath?: string; - readonly name: string; - readonly runState: ObservedRunState; - readonly udid: string; -} - -function parseManagedDevices(value: unknown): ParsedManagedDevice[] { - if (!isRecord(value) || !isRecord(value.devices)) { - throw new DriverCrashError("Invalid simctl device list JSON"); - } - return Object.values(value.devices).flatMap((runtimeDevices) => - Array.isArray(runtimeDevices) ? runtimeDevices.flatMap(parseManagedDevice) : [], - ); -} - -function parseManagedDevice(value: unknown): readonly ParsedManagedDevice[] { - if (!isRecord(value) || typeof value.name !== "string" || typeof value.udid !== "string") { - return []; - } - - return [ - { - name: value.name, - runState: simctlRunState(value.state), - udid: value.udid, - ...(typeof value.dataPath === "string" ? { dataPath: value.dataPath } : {}), - }, - ]; -} - -function simctlRunState(state: unknown): ObservedRunState { - if (state === "Booted") return "running"; - if (state === "Shutdown") return "stopped"; - return "transitioning"; -} - -function parseCatalog(value: unknown): SimctlCatalog { - if (!isRecord(value) || !Array.isArray(value.devicetypes) || !Array.isArray(value.runtimes)) { - throw new DriverCrashError( - "Invalid simctl list JSON: expected devicetypes and runtimes arrays", - ); - } - - const deviceTypes = value.devicetypes.flatMap(parseDeviceType); - const runtimes = value.runtimes.flatMap(parseRuntime); - - // why: Device types come from the Xcode install itself and are never empty on a working - // toolchain, so an empty list here means the JSON was malformed. Runtimes are different: a - // fresh Xcode with zero simulator runtimes installed is a normal, if unusual, starting state - // -- and it must be able to reach the download-latest path in `#resolveDefaultRuntime` rather - // than being rejected here before any resolution is attempted. - if (deviceTypes.length === 0) { - throw new DriverCrashError("Invalid simctl list JSON: no usable device types"); - } - - return { deviceTypes, runtimes }; -} - -function parseDeviceType(value: unknown): readonly DeviceType[] { - if (!isRecord(value) || typeof value.identifier !== "string" || typeof value.name !== "string") { - return []; - } - - return [ - { - identifier: value.identifier, - maxRuntimeVersion: versionIntOr(value.maxRuntimeVersion, UNBOUNDED_VERSION), - minRuntimeVersion: versionIntOr(value.minRuntimeVersion, 0), - name: value.name, - productFamily: typeof value.productFamily === "string" ? value.productFamily : undefined, - }, - ]; -} - -function parseRuntime(value: unknown): readonly Runtime[] { - if ( - !isRecord(value) || - typeof value.identifier !== "string" || - typeof value.name !== "string" || - typeof value.version !== "string" || - typeof value.isAvailable !== "boolean" || - !value.name.toLocaleLowerCase().startsWith("ios ") - ) { - return []; - } - - return [ - { - ...(typeof value.buildversion === "string" ? { build: value.buildversion } : {}), - identifier: value.identifier, - isAvailable: value.isAvailable, - name: value.name, - supportedDeviceTypeIds: parseSupportedDeviceTypeIds(value.supportedDeviceTypes), - version: value.version, - }, - ]; -} - function runtimeMountsAsset(runtime: Runtime, asset: RuntimeAsset): boolean { return runtime.build === undefined ? runtime.version === asset.version @@ -2256,21 +2178,6 @@ function parseRuntimeAsset(path: string, plist: string): RuntimeAsset | undefine return build === undefined || version === undefined ? undefined : { build, path, version }; } -function versionIntOr(value: unknown, fallback: number): number { - return typeof value === "number" && Number.isFinite(value) ? value : fallback; -} - -function parseSupportedDeviceTypeIds(value: unknown): ReadonlySet { - if (!Array.isArray(value)) { - return new Set(); - } - const ids = value - .filter(isRecord) - .map((entry) => entry.identifier) - .filter((identifier): identifier is string => typeof identifier === "string"); - return new Set(ids); -} - interface RuntimeImage { readonly identifier: string; readonly runtimeIdentifier: string; @@ -2633,6 +2540,16 @@ function unknownDevice(result: ProcessResult): boolean { return /^Invalid device:/m.test(result.stderr); } +function readBackFailure( + outcome: + | { readonly kind: "timed-out" } + | { readonly kind: "finished"; readonly result: { code: number | null; stderr: string } }, +): string { + return outcome.kind === "timed-out" + ? `timed out after ${String(READBACK_TIMEOUT_MS)}ms` + : `exit ${String(outcome.result.code)}: ${outcome.result.stderr.trim()}`; +} + function alreadyBooted(stderr: string): boolean { return /current state:\s*Booted|already booted/i.test(stderr); } @@ -2668,10 +2585,6 @@ function specKey(spec: VirtualSpec): string { return `${spec.model.toLocaleLowerCase()}\u0000${spec.osVersion}`; } -function isRecord(value: unknown): value is Record { - return typeof value === "object" && value !== null; -} - function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); } @@ -2680,4 +2593,4 @@ export { type IosDriverConfig, iosDriverConfig } from "./definition.js"; export { iosDeviceDataTable } from "./device-data.js"; export { iosSourceDataOwner } from "./source-data.js"; export { iosPrerequisites } from "./prerequisites.js"; -export { labelsFor, SLIM_CATEGORIES } from "./slim-labels.js"; +export { labelsFor, SLIM_CATEGORIES, slimSignature } from "./slim-labels.js"; diff --git a/src/drivers/ios/simctl-parse.ts b/src/drivers/ios/simctl-parse.ts new file mode 100644 index 000000000..b9b822316 --- /dev/null +++ b/src/drivers/ios/simctl-parse.ts @@ -0,0 +1,145 @@ +import { DriverCrashError, type ObservedRunState } from "../../core/index.js"; + +export function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null; +} + +// why: `simctl`'s `minRuntimeVersion` / `maxRuntimeVersion` encode "no bound" as 0xFFFFFF +// (255.255.255) rather than omitting the field. +export const UNBOUNDED_VERSION = 0xff_ff_ff; + +export interface DeviceType { + readonly identifier: string; + readonly name: string; + readonly minRuntimeVersion: number; + readonly maxRuntimeVersion: number; + readonly productFamily: string | undefined; +} + +export interface Runtime { + readonly identifier: string; + readonly name: string; + readonly version: string; + readonly build?: string; + readonly isAvailable: boolean; + readonly supportedDeviceTypeIds: ReadonlySet; +} + +export interface SimctlCatalog { + readonly deviceTypes: readonly DeviceType[]; + readonly runtimes: readonly Runtime[]; +} + +interface ParsedManagedDevice { + readonly dataPath?: string; + readonly name: string; + readonly runState: ObservedRunState; + readonly udid: string; +} + +export function parseManagedDevices(value: unknown): ParsedManagedDevice[] { + if (!isRecord(value) || !isRecord(value.devices)) { + throw new DriverCrashError("Invalid simctl device list JSON"); + } + return Object.values(value.devices).flatMap((runtimeDevices) => + Array.isArray(runtimeDevices) ? runtimeDevices.flatMap(parseManagedDevice) : [], + ); +} + +function parseManagedDevice(value: unknown): readonly ParsedManagedDevice[] { + if (!isRecord(value) || typeof value.name !== "string" || typeof value.udid !== "string") { + return []; + } + + return [ + { + name: value.name, + runState: simctlRunState(value.state), + udid: value.udid, + ...(typeof value.dataPath === "string" ? { dataPath: value.dataPath } : {}), + }, + ]; +} + +function simctlRunState(state: unknown): ObservedRunState { + if (state === "Booted") return "running"; + if (state === "Shutdown") return "stopped"; + return "transitioning"; +} + +export function parseCatalog(value: unknown): SimctlCatalog { + if (!isRecord(value) || !Array.isArray(value.devicetypes) || !Array.isArray(value.runtimes)) { + throw new DriverCrashError( + "Invalid simctl list JSON: expected devicetypes and runtimes arrays", + ); + } + + const deviceTypes = value.devicetypes.flatMap(parseDeviceType); + const runtimes = value.runtimes.flatMap(parseRuntime); + + // why: Device types come from the Xcode install itself and are never empty on a working + // toolchain, so an empty list here means the JSON was malformed. Runtimes are different: a + // fresh Xcode with zero simulator runtimes installed is a normal, if unusual, starting state + // -- and it must be able to reach the download-latest path in `#resolveDefaultRuntime` rather + // than being rejected here before any resolution is attempted. + if (deviceTypes.length === 0) { + throw new DriverCrashError("Invalid simctl list JSON: no usable device types"); + } + + return { deviceTypes, runtimes }; +} + +function parseDeviceType(value: unknown): readonly DeviceType[] { + if (!isRecord(value) || typeof value.identifier !== "string" || typeof value.name !== "string") { + return []; + } + + return [ + { + identifier: value.identifier, + maxRuntimeVersion: versionIntOr(value.maxRuntimeVersion, UNBOUNDED_VERSION), + minRuntimeVersion: versionIntOr(value.minRuntimeVersion, 0), + name: value.name, + productFamily: typeof value.productFamily === "string" ? value.productFamily : undefined, + }, + ]; +} + +function parseRuntime(value: unknown): readonly Runtime[] { + if ( + !isRecord(value) || + typeof value.identifier !== "string" || + typeof value.name !== "string" || + typeof value.version !== "string" || + typeof value.isAvailable !== "boolean" || + !value.name.toLocaleLowerCase().startsWith("ios ") + ) { + return []; + } + + return [ + { + ...(typeof value.buildversion === "string" ? { build: value.buildversion } : {}), + identifier: value.identifier, + isAvailable: value.isAvailable, + name: value.name, + supportedDeviceTypeIds: parseSupportedDeviceTypeIds(value.supportedDeviceTypes), + version: value.version, + }, + ]; +} + +function versionIntOr(value: unknown, fallback: number): number { + return typeof value === "number" && Number.isFinite(value) ? value : fallback; +} + +function parseSupportedDeviceTypeIds(value: unknown): ReadonlySet { + if (!Array.isArray(value)) { + return new Set(); + } + const ids = value + .filter(isRecord) + .map((entry) => entry.identifier) + .filter((identifier): identifier is string => typeof identifier === "string"); + return new Set(ids); +} diff --git a/src/drivers/ios/slim-except.test.ts b/src/drivers/ios/slim-except.test.ts new file mode 100644 index 000000000..30587568c --- /dev/null +++ b/src/drivers/ios/slim-except.test.ts @@ -0,0 +1,221 @@ +import { readFileSync } from "node:fs"; + +import { describe, expect, it, vi } from "vitest"; + +import { BadDeviceRequestError, KeptCategoriesError } from "../../core/index.js"; +import { FakeClock, MemoryFilesystem, ScriptedProcessRunner } from "../../ports/index.js"; +import { SLIM_CATEGORIES, slimSignature, type SlimmedFact, type SlimSkippedFact } from "./index.js"; +import { + createSlimDriver, + driverData, + FaultyFilesystem, + overridesPath, + parseOverrides, + plantManagedDevice, + printDisabled, + simctl, + slimBootCalls, +} from "./test-slim.js"; + +const slim18_5 = { ...driverData, runtimeId: "com.apple.CoreSimulator.SimRuntime.iOS-18-5" }; +// why: spelled out, not imported: the labels simslim never disables (ADR 0060 §1). +const neverDisabled = ["com.apple.assistantd", "com.apple.gamed", "com.apple.sharingd"]; + +function labelsOf(names: readonly string[]): ReadonlySet { + return new Set( + SLIM_CATEGORIES.filter((category) => names.includes(category.name)).flatMap( + (category) => category.labels, + ), + ); +} + +/** why: What the driver must write: a label of a slimmed category and of no kept one is off (`true`), every other managed label on. */ +function expectedWrite(slimmed: readonly string[], kept: readonly string[]): Map { + const off = labelsOf(slimmed); + const keep = labelsOf(kept); + const wanted = new Map(); + for (const category of SLIM_CATEGORIES) { + for (const label of category.labels) { + wanted.set(label, off.has(label) && !keep.has(label) && !neverDisabled.includes(label)); + } + } + for (const label of neverDisabled) wanted.set(label, false); + return wanted; +} + +function readbackOf(wanted: ReadonlyMap): string { + return printDisabled( + Object.fromEntries([...wanted].map(([label, off]) => [label, off ? "disabled" : "enabled"])), + ); +} + +async function bootWithExcept(options: { + readonly categories?: readonly string[]; + readonly except: readonly string[]; + readonly readback: string | { readonly code: number; readonly stderr: string }; + readonly writeFails?: boolean; +}) { + const filesystem = new FaultyFilesystem(); + await plantManagedDevice(filesystem); + if (options.writeFails === true) filesystem.failing = "writeFileAtomic"; + const calls = slimBootCalls(slim18_5.udid, ""); + const readbackCall = + typeof options.readback === "string" + ? { match: calls[3]!.match, result: { code: 0, stderr: "", stdout: options.readback } } + : { + match: calls[3]!.match, + result: { code: options.readback.code, stderr: options.readback.stderr, stdout: "" }, + }; + const runner = new ScriptedProcessRunner([...calls.slice(0, 3), readbackCall]); + const onSlimmed = vi.fn<(fact: SlimmedFact) => void>(); + const onSlimSkipped = vi.fn<(fact: SlimSkippedFact) => void>(); + const driver = await createSlimDriver( + runner, + filesystem, + { + bootTimeoutMs: 300_000, + ...(options.categories === undefined ? {} : { categories: options.categories }), + }, + onSlimmed, + onSlimSkipped, + false, + new FakeClock(), + ); + const outcome = await driver + .makeReady( + { address: slim18_5.udid, deviceId: slim18_5.udid, driverData: slim18_5 }, + { except: options.except, mode: "slim", purpose: "prepare" }, + ) + .then( + (result) => ({ result }) as const, + (error: unknown) => ({ error }) as const, + ); + const file = overridesPath(slim18_5.udid); + const written = (await filesystem.exists(file)) + ? parseOverrides(await filesystem.readFile(file)) + : undefined; + return { onSlimSkipped, onSlimmed, outcome, written }; +} + +describe("IosSimctlDriver makeReady with an except list", () => { + const allNames = SLIM_CATEGORIES.map((category) => category.name); + + it("boots a slim device with an except list and grants only when every kept label reads back enabled", async () => { + const wanted = expectedWrite(allNames, ["store", "other"]); + const kept = readbackOf(wanted); + const firstKept = [...labelsOf(["store", "other"])].sort()[0]!; + const keptDisabled = readbackOf(new Map([...wanted, [firstKept, true]])); + + const granted = await bootWithExcept({ except: ["store", "other"], readback: kept }); + expect(granted.written).toEqual(Object.fromEntries(wanted)); + expect(granted.written?.["com.apple.amsaccountsd"]).toBe(false); + expect(granted.written?.["com.apple.passd"]).toBe(false); + expect(granted.outcome).toEqual({ result: expect.objectContaining({ mode: "slim" }) }); + expect(granted.onSlimSkipped).not.toHaveBeenCalled(); + + const refusals = [ + { + name: "a kept label reads back disabled", + run: { except: ["store", "other"], readback: keptDisabled }, + message: `1 kept labels are not enabled; first: ${firstKept}`, + }, + { + name: "the overrides write fails", + run: { except: ["store", "other"], readback: kept, writeFails: true }, + message: "could not write the launchd overrides file: disk full", + }, + { + name: "the readback fails", + run: { except: ["store", "other"], readback: { code: 1, stderr: "boom\n" } }, + message: "could not read back the launchd overrides: exit 1: boom", + }, + ]; + const nonKept = [...labelsOf(["widgets"])].find((label) => wanted.get(label) === true)!; + const mismatched = await bootWithExcept({ + except: ["store", "other"], + readback: readbackOf(new Map([...wanted, [nonKept, false]])), + }); + expect(mismatched.outcome).toEqual({ result: expect.objectContaining({ mode: "full" }) }); + expect(mismatched.onSlimmed).not.toHaveBeenCalled(); + + const wholeSet = await bootWithExcept({ + categories: ["store"], + except: ["store"], + readback: readbackOf(expectedWrite(["store"], ["store"])), + }); + expect(wholeSet.written).toEqual(Object.fromEntries(expectedWrite([], []))); + expect(wholeSet.outcome).toEqual({ result: expect.objectContaining({ mode: "full" }) }); + expect(wholeSet.onSlimmed).not.toHaveBeenCalled(); + + const sharedLabel = expectedWrite(["store", "icloud"], ["store"]); + const shared = await bootWithExcept({ + categories: ["store", "icloud"], + except: ["store"], + readback: readbackOf(sharedLabel), + }); + const icloud = SLIM_CATEGORIES.filter((category) => category.name === "icloud"); + expect(shared.written?.["com.apple.amsaccountsd"]).toBe(false); + expect(shared.written).toEqual(Object.fromEntries(sharedLabel)); + expect(shared.outcome).toEqual({ result: expect.objectContaining({ mode: "slim" }) }); + expect(shared.onSlimmed).toHaveBeenCalledWith( + expect.objectContaining({ + categories: ["icloud"], + labelCount: [...sharedLabel.values()].filter(Boolean).length, + signature: slimSignature(icloud), + }), + ); + + for (const refusal of refusals) { + const { outcome, onSlimmed } = await bootWithExcept(refusal.run); + expect(outcome, refusal.name).toEqual({ error: new KeptCategoriesError(refusal.message) }); + expect(onSlimmed, refusal.name).not.toHaveBeenCalled(); + } + }); +}); + +describe("IosSimctlDriver resolveSpec with an except list", () => { + const listFixture = readFileSync(new URL("./fixtures/simctl-list.json", import.meta.url), "utf8"); + + async function resolveWith(categories: readonly string[] | undefined, except: readonly string[]) { + const driver = await createSlimDriver( + new ScriptedProcessRunner([ + { + match: simctl("list", "-j", "devicetypes", "runtimes"), + result: { code: 0, stderr: "", stdout: listFixture }, + }, + ]), + new MemoryFilesystem(), + { bootTimeoutMs: 300_000, ...(categories === undefined ? {} : { categories }) }, + ); + return await driver + .resolveSpec({ + except, + mode: "slim", + model: "iPhone 16", + osVersion: "26.5", + platform: "ios", + }) + .then( + (spec) => ({ spec }) as const, + (error: unknown) => ({ error }) as const, + ); + } + + it("refuses an except list it cannot serve at resolve", async () => { + const names = SLIM_CATEGORIES.map((category) => category.name); + for (const name of [names[0]!, names.at(-1)!]) { + const accepted = await resolveWith(undefined, [name]); + expect(accepted, name).toEqual({ spec: expect.objectContaining({ mode: "slim" }) }); + } + expect(await resolveWith(["store"], ["store"])).toEqual({ + spec: expect.objectContaining({ mode: "slim" }), + }); + + expect(await resolveWith(["store"], ["wallet"])).toEqual({ + error: new BadDeviceRequestError('unknown slim category "wallet"'), + }); + expect(await resolveWith(["store"], ["mdm"])).toEqual({ + error: new BadDeviceRequestError('"mdm" is not in this worker\'s slim categories (store)'), + }); + }); +}); diff --git a/src/drivers/ios/slim-except.ts b/src/drivers/ios/slim-except.ts new file mode 100644 index 000000000..1552913bd --- /dev/null +++ b/src/drivers/ios/slim-except.ts @@ -0,0 +1,61 @@ +import { BadDeviceRequestError, KeptCategoriesError } from "../../core/index.js"; +import { + labelsFor, + SLIM_CATEGORIES, + type resolveSlimCategories, + type SlimCategory, +} from "./slim-labels.js"; + +type ResolvedCategories = ReturnType; + +/** + * why: A lease's except list (ADR 0066 §2) takes categories out of the worker's slim set: the + * categories left are the ones to turn off, the excepted ones are the ones to keep on. + */ +export function splitByExcept( + configured: ResolvedCategories, + except: readonly string[], +): { readonly kept: readonly SlimCategory[]; readonly resolved: ResolvedCategories } { + const { categories, unknown } = configured; + return { + kept: categories.filter((category) => except.includes(category.name)), + resolved: { + categories: categories.filter((category) => !except.includes(category.name)), + unknown, + }, + }; +} + +/** + * why: A kept category's service must be running (ADR 0066 §2): the device is refused when the + * readback does not show every kept label enabled. + */ +export function assertKeptEnabled( + kept: readonly SlimCategory[], + read: ReadonlyMap, +): void { + const notEnabled = labelsFor(kept).filter((label) => read.get(label) === true); + if (notEnabled.length > 0) { + throw new KeptCategoriesError( + `${String(notEnabled.length)} kept labels are not enabled; first: ${notEnabled[0] ?? ""}`, + ); + } +} + +/** + * why: A lease's except list is checked at resolve (ADR 0066 §2), before any device is made: a + * name no category has, or a category this worker does not slim, can never be served. + */ +export function checkExcept(except: readonly string[], slimSet: ResolvedCategories): void { + const slimmed = slimSet.categories.map((category) => category.name); + for (const name of except) { + if (!SLIM_CATEGORIES.some((category) => category.name === name)) { + throw new BadDeviceRequestError(`unknown slim category "${name}"`); + } + if (!slimmed.includes(name)) { + throw new BadDeviceRequestError( + `"${name}" is not in this worker's slim categories (${slimmed.join(", ")})`, + ); + } + } +} diff --git a/src/drivers/ios/slim-labels.ts b/src/drivers/ios/slim-labels.ts index 7a9645be2..8d75b0eed 100644 --- a/src/drivers/ios/slim-labels.ts +++ b/src/drivers/ios/slim-labels.ts @@ -343,9 +343,13 @@ export const NEVER_DISABLE_LABELS: readonly string[] = [ /** * why: Every managed label (all categories plus the never-disable labels) mapped to what the overrides - * file must say: `true` (off) for a label of a configured category, `false` for the rest. + * file must say: `true` (off) for a label of a configured category, `false` for the rest and for + * every label of a kept category. */ -export function overridesFor(categories: readonly SlimCategory[]): ReadonlyMap { +export function overridesFor( + categories: readonly SlimCategory[], + keep: readonly SlimCategory[] = [], +): ReadonlyMap { const wanted = new Map(); for (const category of SLIM_CATEGORIES) { for (const label of category.labels) wanted.set(label, false); @@ -354,6 +358,8 @@ export function overridesFor(categories: readonly SlimCategory[]): ReadonlyMap { + for (let tick = 0; tick < 1_000 && runner.calls.length < count; tick += 1) { + await Promise.resolve(); + } + + expect( + runner.calls.map((call) => call.args), + `simctl never reached ${String(count)} calls`, + ).toHaveLength(count); +} + +/** + * why: Plants a managed device in the root the way a real one arrives: inside a root Simlock + * already owns and marked as such. + * + * A bare `mkdirp(dataPath)` describes a state that cannot occur -- `ensureOwnedRoot` creates + * a root empty and marks it in the same publish, so a root holding a device always carries + * the marker. Without it the fixture is a non-empty unmarked root, which the driver is + * required to refuse (ADR 0001, decision 2), and every test built on it fails at `create` + * for a reason that has nothing to do with what it set out to prove. + */ +export async function plantManagedDevice(filesystem: Filesystem): Promise { + const marker: OwnedRootMarker = { + instanceId, + owner: "simlock", + platform: "ios", + schemaVersion: 1, + }; + await filesystem.mkdirp(deviceRoot); + await filesystem.writeFileAtomic( + `${deviceRoot}/${OWNED_ROOT_MARKER_FILE}`, + JSON.stringify(marker), + ); + await filesystem.mkdirp(dataPath); +} + +export async function createSlimDriver( + runner: ScriptedProcessRunner, + filesystem: Filesystem, + slim: { + readonly categories?: readonly string[]; + readonly bootTimeoutMs: number; + }, + onSlimmed?: (fact: SlimmedFact) => void, + onSlimSkipped?: (fact: SlimSkippedFact) => void, + slimByDefault = false, + clock = new FakeClock(), +): Promise { + return await IosSimctlDriver.create({ + database: await memorySourceDatabase(), + driverConfig: { deviceRoot }, + instanceId, + simlockHome: "/home/.simlock", + clock, + filesystem, + idGenerator: { generate: () => "device-1" }, + ...(onSlimmed === undefined ? {} : { onSlimmed }), + ...(onSlimSkipped === undefined ? {} : { onSlimSkipped }), + launchdOverridesRoot: overridesRoot, + processRunner: runner, + config: { slim }, + slimByDefault, + }); +} + +export const overridesRoot = "/private/var/tmp"; + +export function overridesFolder(udid: string): string { + return `${overridesRoot}/com.apple.CoreSimulator.SimDevice.${udid}`; +} + +export function overridesPath(udid: string): string { + return `${overridesFolder(udid)}/disabled.plist`; +} + +export function overridesPlist(entries: Readonly>): string { + const lines = Object.entries(entries).map( + ([label, off]) => `${label}<${String(off)}/>`, + ); + return `\n${lines.join("")}\n`; +} + +/** why: Records what is written and fails the one operation a test names, as a full or unwritable store would. */ +export class FaultyFilesystem extends MemoryFilesystem { + readonly writes: string[] = []; + readonly modes: { folder?: number | undefined; file?: number | undefined } = {}; + failing: "writeFileAtomic" | "mkdirp" | "rm" | "copyFile" | undefined; + failureMessage = "disk full"; + + override async writeFileAtomic( + path: string, + contents: string, + options?: Parameters[2], + ): Promise { + if (this.failing === "writeFileAtomic" && path.endsWith("disabled.plist")) { + throw new Error(this.failureMessage); + } + await super.writeFileAtomic(path, contents, options); + this.writes.push(path); + if (path.endsWith("disabled.plist")) this.modes.file = options?.mode; + } + + override async mkdirp(path: string, options?: Parameters[1]) { + if (this.failing === "mkdirp" && path.includes("CoreSimulator.SimDevice")) { + throw new Error(this.failureMessage); + } + await super.mkdirp(path, options); + if (path.includes("CoreSimulator.SimDevice")) this.modes.folder = options?.mode; + } + + override async copyFile(from: string, to: string): Promise { + if (this.failing === "copyFile") throw new Error(this.failureMessage); + await super.copyFile(from, to); + } + + override async rm(path: string): Promise { + if (this.failing === "rm") throw new Error(this.failureMessage); + await super.rm(path); + } +} + +export function parseOverrides(plist: string): Record { + const entries: Record = {}; + for (const match of plist.matchAll(/([^<]*)<\/key>\s*<(true|false)\/>/g)) { + entries[match[1] ?? ""] = match[2] === "true"; + } + return entries; +} + +/** why: `launchctl print-disabled system` as launchd prints it: one `"label" => state` line per entry. */ +export function printDisabled(entries: Readonly>): string { + const lines = Object.entries(entries).map(([label, state]) => `\t"${label}" => ${state}`); + return ["disabled services = {", ...lines, "}", ""].join("\n"); +} + +/** why: The calls of one slim boot: the boot, its wait, the installer poll, then the readback. */ +export function slimBootCalls(udid: string, readback: string) { + return [ + { match: simctl("boot", udid) }, + { match: simctl("bootstatus", udid, "-b") }, + { match: simctl("listapps", udid) }, + { + match: simctl("spawn", udid, "launchctl", "print-disabled", "system"), + result: { code: 0, stderr: "", stdout: readback }, + }, + ]; +} + +export type ReadbackScript = + | { readonly stdout: string } + | { readonly code: number; readonly stderr: string } + | "hangs"; + +/** why: One slim `prepare` of the 18.5 device, with the readback scripted; the 120 s limit runs on a fake clock. */ +export async function prepareSlimWith( + filesystem: FaultyFilesystem, + readback: ReadbackScript, + slimOptions: { readonly categories?: readonly string[]; readonly bootTimeoutMs: number }, +): Promise<{ + readonly onSlimSkipped: Mock<(fact: SlimSkippedFact) => void>; + readonly onSlimmed: Mock<(fact: SlimmedFact) => void>; + readonly result: DriverDevice; + readonly runner: ScriptedProcessRunner; +}> { + const udid = "00000000-0000-0000-0000-000000000001"; + const runtimeId = "com.apple.CoreSimulator.SimRuntime.iOS-18-5"; + const calls = slimBootCalls(udid, ""); + const readbackCall = + readback === "hangs" + ? { hangs: true, match: calls[3]!.match } + : "stdout" in readback + ? { match: calls[3]!.match, result: { code: 0, stderr: "", stdout: readback.stdout } } + : { + match: calls[3]!.match, + result: { code: readback.code, stderr: readback.stderr, stdout: "" }, + }; + const runner = new ScriptedProcessRunner([...calls.slice(0, 3), readbackCall]); + const clock = new FakeClock(); + const onSlimmed = vi.fn<(fact: SlimmedFact) => void>(); + const onSlimSkipped = vi.fn<(fact: SlimSkippedFact) => void>(); + const driver = await createSlimDriver( + runner, + filesystem, + slimOptions, + onSlimmed, + onSlimSkipped, + false, + clock, + ); + const ready = driver.makeReady( + { address: udid, deviceId: udid, driverData: { ...driverData, runtimeId } }, + prepareSlim, + ); + if (readback === "hangs") { + await waitForCalls(runner, 4); + clock.advance(120_000); + } + return { onSlimSkipped, onSlimmed, result: await ready, runner }; +} + +export const prepareSlim = { mode: "slim", purpose: "prepare" } as const;