diff --git a/src/daemon/driver-discovery.ts b/src/daemon/driver-discovery.ts index f00356b3b..3687c43dd 100644 --- a/src/daemon/driver-discovery.ts +++ b/src/daemon/driver-discovery.ts @@ -199,6 +199,7 @@ async function discoverIosDriver( idGenerator: options.idGenerator, instanceId: options.instanceId, logger: logger.child("ios"), + logsRoot: `${homedir()}/Library/Logs/CoreSimulator`, onSilenceFailed: logSilenceFailure(logger), onWindowFailed: logWindowFailure(logger), onSlimmed: emitSlimDiagnostic(options.eventBus), diff --git a/src/daemon/state-owners.test.ts b/src/daemon/state-owners.test.ts index c6c385faa..fe3963226 100644 --- a/src/daemon/state-owners.test.ts +++ b/src/daemon/state-owners.test.ts @@ -163,7 +163,7 @@ describe("the seed tables' one-ready-seed-per-kind index (#1367)", () => { state.database .prepare("SELECT version FROM schema_versions WHERE owner = ?") .get(owner.name), - ).toEqual({ version: 2 }); + ).toEqual({ version: owner.version }); expect( state.database .prepare(`SELECT source_id, kind, state FROM ${table} ORDER BY source_id`) diff --git a/src/drivers/ios/AGENTS.md b/src/drivers/ios/AGENTS.md index 51b81be92..fa28a8707 100644 --- a/src/drivers/ios/AGENTS.md +++ b/src/drivers/ios/AGENTS.md @@ -28,6 +28,8 @@ Resolve and boot: Seeds (ADR 0061): - A simulator is a clone of its kind's seed. A seed is known by its `ios_source_data` row, never by name, and lives in the sources set: `sources` in the owned set, an owned root of its own under `default`. It is in no `listManaged` or `simlock simctl list`. +- A seed is made from a throwaway (ADR 0076): `simlock-seed-` is created in the device set, booted once and shut down, cloned unbooted into the sources set, then deleted with its log folder (`logsRoot`), so a seed never names its own folder. Under `default` the throwaway carries this instance's marks and DeviceHub clipboard sync is off before its boot. `saveSource` deletes the saved-from lease's log folder the same way. A log folder that cannot be deleted is logged and the make or save goes on; a throwaway that cannot be deleted fails the make. +- A throwaway is deleted only through the `making` row that names it (`throwaway_udid`): `listManaged` leaves it out, and the first `listSources` of a later process (or the next make of its kind) deletes it with its log folder and the row. - Every clone (a seed's copy, `saveSource`'s own clone, a `provision` with `source`) has its `data/var/db/lsd/com.apple.LaunchServices-*.csstore` deleted before its first boot: it records each app, system apps included, under the original device's folder. A clone whose drop fails is deleted. - Two provisions of a kind make one seed; clones of a seed and its deletion take turns. - A `clone` or `create` waits `ios.simulator.createTimeoutMs`. At the limit it fails but `simctl` runs on: the UDID it later prints is deleted, the seed's deletion waits for it, and one silent 5 minutes more is killed and logged. diff --git a/src/drivers/ios/driver-options.ts b/src/drivers/ios/driver-options.ts index 0850a8fc0..10da15860 100644 --- a/src/drivers/ios/driver-options.ts +++ b/src/drivers/ios/driver-options.ts @@ -33,6 +33,8 @@ export interface IosSimctlDriverOptions { /** why: the daemon's pid is named in the staging directory of a new root. */ readonly pid?: number; readonly coreSimulatorRoot?: string; + // why: where CoreSimulator keeps each simulator's log folder, which `simctl delete` leaves behind; with none given the driver deletes no log folder. + readonly logsRoot?: string; // why: where launchd_sim keeps each simulator's overrides folder; a test points it elsewhere. readonly launchdOverridesRoot?: string; readonly onSlimmed?: (fact: SlimmedFact) => void; diff --git a/src/drivers/ios/index-device-set.test.ts b/src/drivers/ios/index-device-set.test.ts index 1a526fb5d..c0eea0a21 100644 --- a/src/drivers/ios/index-device-set.test.ts +++ b/src/drivers/ios/index-device-set.test.ts @@ -29,6 +29,7 @@ import { seededDatabase, simctlPassthrough, spec, + throwawayUdid, } from "./test-index.js"; describe("IosSimctlDriver device set", () => { @@ -75,13 +76,18 @@ describe("IosSimctlDriver device set", () => { { args: ["create", "simlock-seed-device-1", driverData.deviceTypeId, driverData.runtimeId], scoped: true, - sources: true, + stdout: `${throwawayUdid}\n`, + }, + { args: ["boot", throwawayUdid], scoped: true }, + { args: ["bootstatus", throwawayUdid, "-b"], scoped: true }, + { args: ["listapps", throwawayUdid], scoped: true }, + { args: ["shutdown", throwawayUdid], scoped: true }, + { + args: ["clone", throwawayUdid, "simlock-seed-device-1", sourcesSet], + scoped: true, stdout: `${seedUdid}\n`, }, - { args: ["boot", seedUdid], scoped: true, sources: true }, - { args: ["bootstatus", seedUdid, "-b"], scoped: true, sources: true }, - { args: ["listapps", seedUdid], scoped: true, sources: true }, - { args: ["shutdown", seedUdid], scoped: true, sources: true }, + { args: ["delete", throwawayUdid], scoped: true }, { args: ["clone", seedUdid, driverData.name, devicesDir], scoped: true, @@ -109,9 +115,9 @@ describe("IosSimctlDriver device set", () => { : ["simctl", ...step.args]; const runner = new ScriptedProcessRunner( steps.flatMap((step) => [ - ...(!scoped && step.args[0] === "boot" && step.sources !== true + ...(!scoped && step.args[0] === "boot" && step.args[1] !== seedUdid ? deviceHubEdit( - `Set :DevicePreferences:${driverData.udid}:pasteboardSyncEnabled false`, + `Set :DevicePreferences:${String(step.args[1])}:pasteboardSyncEnabled false`, ).map((match) => ({ match })) : []), { @@ -121,7 +127,7 @@ describe("IosSimctlDriver device set", () => { : { result: { code: 0, stderr: "", stdout: step.stdout } }), }, ...(!scoped && step.args[0] === "delete" - ? deviceHubEdit(`Delete :DevicePreferences:${driverData.udid}`).map((match) => ({ + ? deviceHubEdit(`Delete :DevicePreferences:${String(step.args[1])}`).map((match) => ({ match, })) : []), @@ -129,6 +135,7 @@ describe("IosSimctlDriver device set", () => { ); const filesystem = new MemoryFilesystem(); await plantDevice(filesystem, devicesDir); + await filesystem.mkdirp(`${devicesDir}/${throwawayUdid}/data`); if (scoped) await plantManagedDevice(filesystem); const driver = await IosSimctlDriver.create({ database: await memorySourceDatabase(), diff --git a/src/drivers/ios/index-seed-provision.test.ts b/src/drivers/ios/index-seed-provision.test.ts index b1443b98e..dd74be977 100644 --- a/src/drivers/ios/index-seed-provision.test.ts +++ b/src/drivers/ios/index-seed-provision.test.ts @@ -30,6 +30,8 @@ import { seededDatabase, sourcesSimctl, spec, + throwawaySeedSteps, + throwawayUdid, } from "./test-index.js"; /** @@ -61,19 +63,7 @@ describe("IosSimctlDriver", () => { const cloneInvocation = sourcesSimctl("clone", seedUdid, driverData.name, deviceRoot); const runner = new ScriptedProcessRunner([ { match: listInvocation, result: { code: 0, stderr: "", stdout: listFixture } }, - { - match: sourcesSimctl( - "create", - "simlock-seed-device-1", - driverData.deviceTypeId, - driverData.runtimeId, - ), - result: { code: 0, stderr: "", stdout: `${seedUdid}\n` }, - }, - { match: sourcesSimctl("boot", seedUdid) }, - { match: sourcesSimctl("bootstatus", seedUdid, "-b") }, - { match: sourcesSimctl("listapps", seedUdid) }, - { match: sourcesSimctl("shutdown", seedUdid) }, + ...throwawaySeedSteps(), { match: cloneInvocation, result: { code: 0, stderr: "", stdout: `${driverData.udid}\n` } }, ]); const filesystem = new MemoryFilesystem(); @@ -100,28 +90,26 @@ describe("IosSimctlDriver", () => { const copyUdid = "00000000-0000-0000-0000-000000000002"; const database = await memorySourceDatabase(); const rowsWhenCreated: unknown[] = []; - const seedCreate = sourcesSimctl( + const seedCreate = simctl( "create", "simlock-seed-device-1", driverData.deviceTypeId, driverData.runtimeId, ); const cloneInvocation = sourcesSimctl("clone", seedUdid, driverData.name, deviceRoot); + const [create, ...afterCreate] = throwawaySeedSteps(); const runner = new ScriptedProcessRunner([ { match: listInvocation, result: { code: 0, stderr: "", stdout: listFixture } }, { + ...create, match: seedCreate, onSpawn: () => { rowsWhenCreated.push( ...database.prepare("SELECT state, udid FROM ios_source_data").all(), ); }, - result: { code: 0, stderr: "", stdout: `${seedUdid}\n` }, }, - { match: sourcesSimctl("boot", seedUdid) }, - { match: sourcesSimctl("bootstatus", seedUdid, "-b") }, - { match: sourcesSimctl("listapps", seedUdid) }, - { match: sourcesSimctl("shutdown", seedUdid) }, + ...afterCreate, { match: cloneInvocation, result: { code: 0, stderr: "", stdout: `${driverData.udid}\n` } }, { match: cloneInvocation, result: { code: 0, stderr: "", stdout: `${copyUdid}\n` } }, ]); @@ -146,15 +134,20 @@ describe("IosSimctlDriver", () => { expect(runner.calls).toEqual([ { ...listInvocation, options: { timeoutMs: 30_000 } }, { ...seedCreate, options: { timeoutMs: 330_000 } }, - { ...sourcesSimctl("boot", seedUdid), options: { timeoutMs: 300_000 } }, - { ...sourcesSimctl("bootstatus", seedUdid, "-b"), options: { timeoutMs: 300_000 } }, - { ...sourcesSimctl("listapps", seedUdid), options: { timeoutMs: 30_000 } }, - { ...sourcesSimctl("shutdown", seedUdid), options: { timeoutMs: 30_000 } }, + { ...simctl("boot", throwawayUdid), options: { timeoutMs: 300_000 } }, + { ...simctl("bootstatus", throwawayUdid, "-b"), options: { timeoutMs: 300_000 } }, + { ...simctl("listapps", throwawayUdid), options: { timeoutMs: 30_000 } }, + { ...simctl("shutdown", throwawayUdid), options: { timeoutMs: 30_000 } }, + { + ...simctl("clone", throwawayUdid, "simlock-seed-device-1", `${deviceRoot}/sources`), + options: { timeoutMs: 330_000 }, + }, + { ...simctl("delete", throwawayUdid), options: { timeoutMs: 30_000 } }, { ...cloneInvocation, options: { timeoutMs: 330_000 } }, ]); await expect(driver.provision(spec)).resolves.toMatchObject({ deviceId: copyUdid }); - expect(runner.calls.slice(7)).toEqual([ + expect(runner.calls.slice(9)).toEqual([ { ...cloneInvocation, options: { timeoutMs: 330_000 } }, ]); }); @@ -188,19 +181,7 @@ describe("IosSimctlDriver", () => { const runner = new ScriptedProcessRunner([ { match: listInvocation, result: { code: 0, stderr: "", stdout: listFixture } }, { match: listInvocation, result: { code: 0, stderr: "", stdout: listFixture } }, - { - match: sourcesSimctl( - "create", - "simlock-seed-device-1", - driverData.deviceTypeId, - driverData.runtimeId, - ), - result: { code: 0, stderr: "", stdout: `${seedUdid}\n` }, - }, - { match: sourcesSimctl("boot", seedUdid) }, - { match: sourcesSimctl("bootstatus", seedUdid, "-b") }, - { match: sourcesSimctl("listapps", seedUdid) }, - { match: sourcesSimctl("shutdown", seedUdid) }, + ...throwawaySeedSteps(), { hangs: true, match: cloneInvocation }, { match: cloneInvocation, result: { code: 0, stderr: "", stdout: `${copyUdid}\n` } }, ]); @@ -209,12 +190,13 @@ describe("IosSimctlDriver", () => { const driver = await createDriver(runner, clock, filesystem); await plantManagedDevice(filesystem); await filesystem.mkdirp(`${deviceRoot}/${copyUdid}/data`); - const clones = (): number => runner.calls.filter((call) => call.args[3] === "clone").length; + const clones = (): number => + runner.calls.filter((call) => call.args[3] === "clone" && call.args[4] === seedUdid).length; const first = driver.provision(spec); const second = driver.provision(spec); const firstSettled = first.catch((caught: unknown) => caught); - await waitForCalls(runner, 8); + await waitForCalls(runner, 10); expect(runner.calls.filter((call) => call.args[3] === "create")).toHaveLength(1); for (let tick = 0; tick < 100; tick += 1) await Promise.resolve(); @@ -243,7 +225,7 @@ describe("IosSimctlDriver", () => { steps: [ { hangs: true, - match: sourcesSimctl( + match: simctl( "create", "simlock-seed-device-1", driverData.deviceTypeId, @@ -338,13 +320,9 @@ describe("IosSimctlDriver", () => { { call: "a seed's create", act: (driver: IosSimctlDriver) => driver.provision(spec), - deleteArgs: (udid: string) => sourcesSimctl("delete", udid).args, - hung: sourcesSimctl( - "create", - "simlock-seed-device-1", - driverData.deviceTypeId, - driverData.runtimeId, - ).args, + deleteArgs: (udid: string) => simctl("delete", udid).args, + hung: simctl("create", "simlock-seed-device-1", driverData.deviceTypeId, driverData.runtimeId) + .args, isDefault: false, seeded: false, steps: [], diff --git a/src/drivers/ios/index-seed-sources.test.ts b/src/drivers/ios/index-seed-sources.test.ts index f640a09b0..145896e29 100644 --- a/src/drivers/ios/index-seed-sources.test.ts +++ b/src/drivers/ios/index-seed-sources.test.ts @@ -24,6 +24,8 @@ import { seededDatabase, sourcesSimctl, spec, + throwawaySeedSteps, + throwawayUdid, } from "./test-index.js"; /** @@ -197,11 +199,13 @@ describe("IosSimctlDriver", () => { "the next seed make of a kind destroys this process's own making row of that kind older than 300 s: a row $name", async ({ now, destroyed }) => { const stuckUdid = "00000000-0000-0000-0000-0000000000dd"; + const stuckThrowaway = "00000000-0000-0000-0000-0000000000ee"; const database = plantSource(await memorySourceDatabase(), { deviceTypeId: driverData.deviceTypeId, maker: "device-1", runtimeId: driverData.runtimeId, state: "making", + throwawayUdid: stuckThrowaway, udid: stuckUdid, }); const copyUdid = "00000000-0000-0000-0000-000000000002"; @@ -212,21 +216,11 @@ describe("IosSimctlDriver", () => { ? [ { match: sourcesSimctl("shutdown", stuckUdid) }, { match: sourcesSimctl("delete", stuckUdid) }, + { match: simctl("shutdown", stuckThrowaway) }, + { match: simctl("delete", stuckThrowaway) }, ] : []), - { - match: sourcesSimctl( - "create", - "simlock-seed-device-1", - driverData.deviceTypeId, - driverData.runtimeId, - ), - result: { code: 0, stderr: "", stdout: `${seedUdid}\n` }, - }, - { match: sourcesSimctl("boot", seedUdid) }, - { match: sourcesSimctl("bootstatus", seedUdid, "-b") }, - { match: sourcesSimctl("listapps", seedUdid) }, - { match: sourcesSimctl("shutdown", seedUdid) }, + ...throwawaySeedSteps(), { match: cloneInvocation, result: { code: 0, stderr: "", stdout: `${copyUdid}\n` } }, ]); const filesystem = new MemoryFilesystem(); @@ -237,8 +231,19 @@ describe("IosSimctlDriver", () => { await driver.provision(spec); expect( - runner.calls.filter((call) => call.args[4] === stuckUdid).map((call) => call.args[3]), - ).toEqual(destroyed ? ["shutdown", "delete"] : []); + runner.calls + .filter((call) => [stuckUdid, stuckThrowaway].includes(call.args[4] ?? "")) + .map((call) => `${call.args[3] ?? ""} ${call.args[4] ?? ""}`), + ).toEqual( + destroyed + ? [ + `shutdown ${stuckUdid}`, + `delete ${stuckUdid}`, + `shutdown ${stuckThrowaway}`, + `delete ${stuckThrowaway}`, + ] + : [], + ); expect( database.prepare("SELECT udid FROM ios_source_data WHERE state = 'making'").all(), ).toEqual(destroyed ? [] : [{ udid: stuckUdid }]); @@ -254,7 +259,7 @@ describe("IosSimctlDriver", () => { }, { name: "the seed's boot fails", - message: `seed ${seedUdid} did not boot: `, + message: `seed ${throwawayUdid} did not boot: `, script: [{ code: 1, op: "bootstatus" }], tail: ["shutdown", "delete"], }, @@ -271,16 +276,16 @@ describe("IosSimctlDriver", () => { const steps = ["create", "boot", "bootstatus", "listapps", "shutdown"]; const upTo = steps.indexOf(failing.op); const results = new Map([ - ["create", { code: 0, stderr: "", stdout: `${seedUdid}\n` }], + ["create", { code: 0, stderr: "", stdout: `${throwawayUdid}\n` }], ]); const database = await memorySourceDatabase(); const entries = steps.slice(0, upTo + 1).map((op) => { - const match = sourcesSimctl( + const match = simctl( ...(op === "create" ? ["create", "simlock-seed-device-1", driverData.deviceTypeId, driverData.runtimeId] : op === "bootstatus" - ? [op, seedUdid, "-b"] - : [op, seedUdid]), + ? [op, throwawayUdid, "-b"] + : [op, throwawayUdid]), ); if (op !== failing.op) return { match, ...(results.has(op) ? { result: results.get(op)! } : {}) }; @@ -291,7 +296,7 @@ describe("IosSimctlDriver", () => { const runner = new ScriptedProcessRunner([ { match: listInvocation, result: { code: 0, stderr: "", stdout: listFixture } }, ...entries, - ...tail.map((op) => ({ match: sourcesSimctl(op, seedUdid) })), + ...tail.map((op) => ({ match: simctl(op, throwawayUdid) })), ]); const clock = new FakeClock(); const driver = await createDriver(runner, clock, undefined, database); @@ -314,7 +319,7 @@ describe("IosSimctlDriver", () => { ...tail, ]); expect(runner.calls.slice(1).map((call) => call.args[2])).toEqual( - runner.calls.slice(1).map(() => `${deviceRoot}/sources`), + runner.calls.slice(1).map(() => deviceRoot), ); expect(database.prepare("SELECT COUNT(*) AS n FROM ios_source_data").get()).toEqual({ n: 0 }); }, @@ -332,21 +337,21 @@ describe("IosSimctlDriver", () => { const runner = new ScriptedProcessRunner([ { match: listInvocation, result: { code: 0, stderr: "", stdout: listFixture } }, { - match: sourcesSimctl( + match: simctl( "create", "simlock-seed-device-1", driverData.deviceTypeId, driverData.runtimeId, ), - result: { code: 0, stderr: "", stdout: `${seedUdid}\n` }, + result: { code: 0, stderr: "", stdout: `${throwawayUdid}\n` }, }, ...ran.map((op) => { - const match = sourcesSimctl( - ...(op === "bootstatus" ? [op, seedUdid, "-b"] : [op, seedUdid]), + const match = simctl( + ...(op === "bootstatus" ? [op, throwawayUdid, "-b"] : [op, throwawayUdid]), ); return op === hangs ? { hangs: true, match } : { match }; }), - ...["shutdown", "shutdown", "delete"].map((op) => ({ match: sourcesSimctl(op, seedUdid) })), + ...["shutdown", "shutdown", "delete"].map((op) => ({ match: simctl(op, throwawayUdid) })), ]); const clock = new FakeClock(); const driver = await createDriver(runner, clock, undefined, database, undefined, 2_000); @@ -395,6 +400,7 @@ describe("IosSimctlDriver", () => { } } const planted = staleUdid; + const throwaway = throwawaySeedSteps(); const cloneOf = (udid: string) => sourcesSimctl("clone", udid, driverData.name, deviceRoot); const runner = new ScriptedProcessRunner([ { match: listInvocation, result: { code: 0, stderr: "", stdout: JSON.stringify(catalog) } }, @@ -402,19 +408,7 @@ describe("IosSimctlDriver", () => { ? [ { match: sourcesSimctl("shutdown", staleUdid) }, { match: sourcesSimctl("delete", staleUdid) }, - { - match: sourcesSimctl( - "create", - "simlock-seed-device-1", - driverData.deviceTypeId, - driverData.runtimeId, - ), - result: { code: 0, stderr: "", stdout: `${seedUdid}\n` }, - }, - { match: sourcesSimctl("boot", seedUdid) }, - { match: sourcesSimctl("bootstatus", seedUdid, "-b") }, - { match: sourcesSimctl("listapps", seedUdid) }, - { match: sourcesSimctl("shutdown", seedUdid) }, + ...throwaway, ] : []), { @@ -439,7 +433,18 @@ describe("IosSimctlDriver", () => { expect(runner.calls.map((call) => call.args[3]).filter((verb) => verb !== "list")).toEqual( remade - ? ["shutdown", "delete", "create", "boot", "bootstatus", "listapps", "shutdown", "clone"] + ? [ + "shutdown", + "delete", + "create", + "boot", + "bootstatus", + "listapps", + "shutdown", + "clone", + "delete", + "clone", + ] : ["clone"], ); }, diff --git a/src/drivers/ios/index-seed-throwaway.test.ts b/src/drivers/ios/index-seed-throwaway.test.ts new file mode 100644 index 000000000..7248f39d6 --- /dev/null +++ b/src/drivers/ios/index-seed-throwaway.test.ts @@ -0,0 +1,460 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { FakeClock, MemoryFilesystem, ScriptedProcessRunner } from "../../ports/index.js"; +import { IosSimctlDriver } from "./index.js"; +import { memorySourceDatabase, plantSource } from "./testing.js"; +import { + deviceHubEdit, + deviceRoot, + driverData, + instanceId, + plantManagedDevice, + simctl, +} from "./test-slim.js"; +import { + RecordingLogger, + listFixture, + logsRoot, + scopedRunners, + listInvocation, + seedUdid, + sourcesSimctl, + spec, + throwawaySeedSteps, + throwawayUdid, +} from "./test-index.js"; + +afterEach(() => { + scopedRunners.length = 0; +}); + +class BrokenLogRemoval extends MemoryFilesystem { + override async rm(path: string): Promise { + if (path.startsWith(logsRoot)) throw new Error("denied"); + await super.rm(path); + } +} + +const copyUdid = "00000000-0000-0000-0000-000000000002"; +const name = "simlock-seed-device-1"; +const coreSimulatorRoot = "/CoreSim"; + +interface World { + readonly label: string; + readonly config: Record; + readonly devicesDir: string; + readonly sourcesSet: string; + readonly isDefault: boolean; +} + +const worlds: readonly World[] = [ + { + config: { deviceRoot }, + devicesDir: deviceRoot, + isDefault: false, + label: "simlock set", + sourcesSet: `${deviceRoot}/sources`, + }, + { + config: { deviceSet: "default" }, + devicesDir: `${coreSimulatorRoot}/Devices`, + isDefault: true, + label: "default set", + sourcesSet: "/home/.simlock/devices/ios-sources", + }, +]; + +function simctlIn(world: World, set: string | undefined, ...args: readonly string[]) { + const scoped = set ?? (world.isDefault ? undefined : world.devicesDir); + return { + args: scoped === undefined ? ["simctl", ...args] : ["simctl", "--set", scoped, ...args], + command: "xcrun", + }; +} + +describe("IosSimctlDriver seed throwaway", () => { + it("the first provision of a kind makes its seed from a throwaway", async () => { + for (const world of worlds) { + const step = (match: { command: string; args: readonly string[] }, stdout?: string) => ({ + match, + ...(stdout === undefined ? {} : { result: { code: 0, stderr: "", stdout } }), + }); + const inSet = (...args: string[]) => simctlIn(world, undefined, ...args); + const hub = (command: string) => + world.isDefault ? deviceHubEdit(command).map((match) => ({ match })) : []; + const database = await memorySourceDatabase(); + const markedAtBoot: Promise[] = []; + const filesystem = new MemoryFilesystem(); + const runner = new ScriptedProcessRunner([ + step( + world.isDefault + ? { args: ["simctl", "list", "-j", "devicetypes", "runtimes"], command: "xcrun" } + : inSet("list", "-j", "devicetypes", "runtimes"), + listFixture, + ), + step( + inSet("create", name, driverData.deviceTypeId, driverData.runtimeId), + `${throwawayUdid}\n`, + ), + ...hub(`Set :DevicePreferences:${throwawayUdid}:pasteboardSyncEnabled false`), + { + match: inSet("boot", throwawayUdid), + onSpawn: () => { + markedAtBoot.push( + filesystem.exists(`${world.devicesDir}/${throwawayUdid}/simlock-mark.json`), + ); + }, + }, + step(inSet("bootstatus", throwawayUdid, "-b")), + step(inSet("listapps", throwawayUdid)), + step(inSet("shutdown", throwawayUdid)), + step(inSet("clone", throwawayUdid, name, world.sourcesSet), `${seedUdid}\n`), + step(inSet("delete", throwawayUdid)), + ...hub(`Delete :DevicePreferences:${throwawayUdid}`), + step( + simctlIn(world, world.sourcesSet, "clone", seedUdid, driverData.name, world.devicesDir), + `${copyUdid}\n`, + ), + ]); + scopedRunners.push(runner); + if (!world.isDefault) await plantManagedDevice(filesystem); + await filesystem.mkdirp(`${world.devicesDir}/${throwawayUdid}/data`); + await filesystem.mkdirp(`${world.devicesDir}/${copyUdid}/data`); + await filesystem.mkdirp(`${logsRoot}/${throwawayUdid}`); + const driver = await IosSimctlDriver.create({ + clock: new FakeClock(), + coreSimulatorRoot, + database, + driverConfig: world.config, + filesystem, + idGenerator: { generate: () => "device-1" }, + instanceId, + logsRoot, + processRunner: runner, + simlockHome: "/home/.simlock", + }); + + await expect(driver.provision(spec), world.label).resolves.toMatchObject({ + deviceId: copyUdid, + }); + + expect(await Promise.all(markedAtBoot), world.label).toEqual([world.isDefault]); + expect( + database.prepare("SELECT state, udid, throwaway_udid FROM ios_source_data").all(), + world.label, + ).toEqual([{ state: "ready", throwaway_udid: throwawayUdid, udid: seedUdid }]); + await expect(filesystem.exists(`${logsRoot}/${throwawayUdid}`), world.label).resolves.toBe( + false, + ); + } + + const whole = throwawaySeedSteps(); + const [create, boot, bootstatus, listapps, shutdown, clone, remove] = whole; + const failed = { code: 1, stderr: "boom", stdout: "" }; + const copy = { + match: sourcesSimctl("clone", seedUdid, driverData.name, deviceRoot), + result: { code: 0, stderr: "", stdout: `${copyUdid}\n` }, + }; + const failures = [ + { + label: "boot fails", + steps: [create, boot, { ...bootstatus, result: failed }, shutdown, remove], + error: /did not boot/, + rows: [], + logFolder: false, + warnings: [], + }, + { + label: "clone fails", + steps: [ + create, + boot, + bootstatus, + listapps, + shutdown, + { ...clone, result: failed }, + shutdown, + remove, + ], + error: /boom/, + rows: [], + logFolder: false, + warnings: [], + }, + { + label: "throwaway delete fails", + steps: [ + create, + boot, + bootstatus, + listapps, + shutdown, + clone, + { ...remove, result: failed }, + { match: sourcesSimctl("shutdown", seedUdid) }, + { match: sourcesSimctl("delete", seedUdid) }, + ], + error: /boom/, + rows: [{ state: "making", throwaway_udid: throwawayUdid, udid: seedUdid }], + logFolder: true, + warnings: [], + }, + { + label: "log folder delete fails", + steps: [...whole, copy], + filesystem: new BrokenLogRemoval(), + rows: [{ state: "ready", throwaway_udid: throwawayUdid, udid: seedUdid }], + logFolder: true, + warnings: [`could not delete log folder ${logsRoot}/${throwawayUdid}: denied`], + }, + { + label: "log folder absent", + steps: [...whole, copy], + absent: true, + rows: [{ state: "ready", throwaway_udid: throwawayUdid, udid: seedUdid }], + logFolder: false, + warnings: [], + }, + ]; + for (const failure of failures) { + const database = await memorySourceDatabase(); + const logger = new RecordingLogger(); + const filesystem = failure.filesystem ?? new MemoryFilesystem(); + const runner = new ScriptedProcessRunner([ + { match: listInvocation, result: { code: 0, stderr: "", stdout: listFixture } }, + ...failure.steps, + ]); + scopedRunners.push(runner); + await plantManagedDevice(filesystem); + await filesystem.mkdirp(`${deviceRoot}/${copyUdid}/data`); + if (failure.absent !== true) await filesystem.mkdirp(`${logsRoot}/${throwawayUdid}`); + const driver = await IosSimctlDriver.create({ + clock: new FakeClock(), + database, + driverConfig: { deviceRoot }, + filesystem, + idGenerator: { generate: () => "device-1" }, + instanceId, + logger, + logsRoot, + processRunner: runner, + simlockHome: "/home/.simlock", + }); + + const outcome = await driver.provision(spec).then( + () => undefined, + (error: unknown) => error as Error, + ); + + if (failure.error === undefined) expect(outcome, failure.label).toBeUndefined(); + else expect(outcome?.message, failure.label).toMatch(failure.error); + expect( + database.prepare("SELECT state, udid, throwaway_udid FROM ios_source_data").all(), + failure.label, + ).toEqual(failure.rows); + await expect(filesystem.exists(`${logsRoot}/${throwawayUdid}`), failure.label).resolves.toBe( + failure.logFolder, + ); + expect(logger.warnings, failure.label).toEqual(failure.warnings); + } + }); + + it("listManaged leaves out a throwaway a making row names", async () => { + const runtime = "com.apple.CoreSimulator.SimRuntime.iOS-26-5"; + const own = "00000000-0000-0000-0000-0000000000e1"; + const listed = JSON.stringify({ + devices: { + [runtime]: [throwawayUdid, own].map((udid) => ({ + dataPath: `/x/${udid}/data`, + name: udid, + state: "Shutdown", + udid, + })), + }, + }); + const cases = [ + { label: "simlock set, a making row", world: worlds[0]!, state: "making", left: [own] }, + { label: "default set, a making row", world: worlds[1]!, state: "making", left: [own] }, + { + label: "simlock set, a ready row", + world: worlds[0]!, + state: "ready", + left: [throwawayUdid, own], + }, + ] as const; + for (const { label, left, state, world } of cases) { + const database = plantSource(await memorySourceDatabase(), { + deviceTypeId: driverData.deviceTypeId, + runtimeId: driverData.runtimeId, + state, + throwawayUdid, + udid: seedUdid, + }); + const filesystem = new MemoryFilesystem(); + if (!world.isDefault) await plantManagedDevice(filesystem); + for (const udid of [throwawayUdid, own]) { + await filesystem.mkdirp(`${world.devicesDir}/${udid}/data`); + if (world.isDefault) { + const mark = JSON.stringify({ instanceId, token: "t", udid }); + await filesystem.writeFileAtomic(`${world.devicesDir}/${udid}/simlock-mark.json`, mark); + await filesystem.writeFileAtomic( + `${world.devicesDir}/${udid}/data/simlock-mark.json`, + mark, + ); + } + } + const runner = new ScriptedProcessRunner([ + { + match: simctlIn(world, undefined, "list", "-j", "devices"), + result: { code: 0, stderr: "", stdout: listed }, + }, + ]); + scopedRunners.push(runner); + const driver = await IosSimctlDriver.create({ + clock: new FakeClock(), + coreSimulatorRoot, + database, + driverConfig: world.config, + filesystem, + idGenerator: { generate: () => "device-1" }, + instanceId, + processRunner: runner, + simlockHome: "/home/.simlock", + }); + + const reality = await driver.listManaged(); + + expect(reality.devices.map((device) => device.deviceId).sort(), label).toEqual( + [...left].sort(), + ); + } + }); + + it("a restart mid-make: the first source read deletes the throwaway, its log folder, the seed clone and the row", async () => { + const invalid = { code: 1, stderr: `Invalid device: ${throwawayUdid}`, stdout: "" }; + const cases = [ + { + label: "throwaway only", + udid: undefined, + steps: [ + { match: simctl("shutdown", throwawayUdid) }, + { match: simctl("delete", throwawayUdid) }, + ], + }, + { + label: "throwaway and seed", + udid: seedUdid, + steps: [ + { match: sourcesSimctl("shutdown", seedUdid) }, + { match: sourcesSimctl("delete", seedUdid) }, + { match: simctl("shutdown", throwawayUdid) }, + { match: simctl("delete", throwawayUdid) }, + ], + }, + { + label: "throwaway already gone", + udid: undefined, + steps: [ + { match: simctl("shutdown", throwawayUdid) }, + { match: simctl("delete", throwawayUdid), result: invalid }, + ], + }, + ]; + for (const { label, steps, udid } of cases) { + const database = plantSource(await memorySourceDatabase(), { + deviceTypeId: driverData.deviceTypeId, + runtimeId: driverData.runtimeId, + state: "making", + throwawayUdid, + ...(udid === undefined ? {} : { udid }), + }); + const runner = new ScriptedProcessRunner(steps); + scopedRunners.push(runner); + const filesystem = new MemoryFilesystem(); + await plantManagedDevice(filesystem); + await filesystem.mkdirp(`${logsRoot}/${throwawayUdid}`); + const driver = await IosSimctlDriver.create({ + clock: new FakeClock(), + database, + driverConfig: { deviceRoot }, + filesystem, + idGenerator: { generate: () => "device-1" }, + instanceId, + logsRoot, + processRunner: runner, + simlockHome: "/home/.simlock", + }); + + await expect(driver.listSources(), label).resolves.toEqual([]); + + expect(runner.calls.length, label).toBe(steps.length); + expect(database.prepare("SELECT COUNT(*) AS n FROM ios_source_data").get(), label).toEqual({ + n: 0, + }); + await expect(filesystem.exists(`${logsRoot}/${throwawayUdid}`), label).resolves.toBe(false); + } + }); + + it("baseline.save deletes the saved-from lease's log folder", async () => { + const baselineName = "simlock-baseline-device-1"; + const leaseLogs = `${logsRoot}/${driverData.udid}`; + const clone = simctl("clone", driverData.udid, baselineName, `${deviceRoot}/sources`); + const cloneUdid = "00000000-0000-0000-0000-0000000000cc"; + const cases = [ + { label: "present", plant: true, clone: "ok", logs: false, warnings: [] }, + { label: "absent", plant: false, clone: "ok", logs: false, warnings: [] }, + { + label: "delete fails", + plant: true, + clone: "ok", + fs: new BrokenLogRemoval(), + logs: true, + warnings: [`could not delete log folder ${leaseLogs}: denied`], + }, + { label: "clone fails", plant: true, clone: "fails", logs: true, warnings: [] }, + ] as const; + for (const scenario of cases) { + const database = await memorySourceDatabase(); + const logger = new RecordingLogger(); + const filesystem = "fs" in scenario ? scenario.fs : new MemoryFilesystem(); + await plantManagedDevice(filesystem); + await filesystem.mkdirp(`${deviceRoot}/sources/${cloneUdid}`); + if (scenario.plant) await filesystem.mkdirp(leaseLogs); + const runner = new ScriptedProcessRunner([ + { match: listInvocation, result: { code: 0, stderr: "", stdout: listFixture } }, + { match: simctl("shutdown", driverData.udid) }, + scenario.clone === "ok" + ? { match: clone, result: { code: 0, stderr: "", stdout: `${cloneUdid}\n` } } + : { match: clone, result: { code: 1, stderr: "no space", stdout: "" } }, + ]); + scopedRunners.push(runner); + const driver = await IosSimctlDriver.create({ + clock: new FakeClock(), + database, + driverConfig: { deviceRoot }, + filesystem, + idGenerator: { generate: () => "device-1" }, + instanceId, + logger, + logsRoot, + processRunner: runner, + simlockHome: "/home/.simlock", + }); + + const saved = await driver + .saveSource({ + address: driverData.udid, + deviceId: driverData.udid, + driverData, + physical: false, + }) + .then( + () => "saved", + () => "failed", + ); + + expect(saved, scenario.label).toBe(scenario.clone === "ok" ? "saved" : "failed"); + await expect(filesystem.exists(leaseLogs), scenario.label).resolves.toBe(scenario.logs); + expect(logger.warnings, scenario.label).toEqual(scenario.warnings); + } + }); +}); diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index 906230f9d..5a5360730 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -212,12 +212,14 @@ export class IosSimctlDriver implements Driver { clock: options.clock, slimBoot: this.#slimBoot, database: options.database, + deviceHub: this.#deviceHub, deviceRoot, filesystem: options.filesystem, fullBootTimeoutMs: this.#fullBootTimeoutMs, idGenerator: options.idGenerator, instanceId: options.instanceId, logger: options.logger, + logsRoot: options.logsRoot, marks: this.#marks, ownsDeviceSet: rootOptions !== undefined, seedTurns: this.#seedTurns, @@ -470,7 +472,10 @@ export class IosSimctlDriver implements Driver { async listManaged(): Promise { const result = await this.#simctl.run(["list", "-j", "devices"], COMMAND_TIMEOUT_MS); - const listed = parseManagedDevices(JSON.parse(result.stdout) as unknown); + const throwaways = this.#seeds.makingThrowaways(); + const listed = parseManagedDevices(JSON.parse(result.stdout) as unknown).filter( + (device) => !throwaways.has(device.udid), + ); // why: Xcode's set also holds the user's own simulators and other Simlocks'; only a // durable mark naming this instance proves a simulator here is ours. const parsed = diff --git a/src/drivers/ios/seeds.ts b/src/drivers/ios/seeds.ts index 3d312130e..7398e0736 100644 --- a/src/drivers/ios/seeds.ts +++ b/src/drivers/ios/seeds.ts @@ -12,6 +12,7 @@ import type { Clock, Filesystem, IdGenerator, Logger } from "../../ports/index.j import { errorMessage } from "./command-run.js"; import { SeedTurns } from "./seed-turns.js"; import { COMMAND_TIMEOUT_MS, Simctl, unknownDevice } from "./simctl.js"; +import type { DeviceHubPreferences } from "./devicehub.js"; import { DeviceMarks } from "./marks.js"; import type { SlimBoot } from "./slim-boot.js"; import type { SimulatorBoot } from "./simulator-boot.js"; @@ -37,12 +38,14 @@ interface SeedsOptions { readonly clock: Clock; readonly slimBoot: SlimBoot; readonly database: SqliteDatabase; + readonly deviceHub: DeviceHubPreferences; readonly deviceRoot: string; readonly filesystem: Filesystem; readonly fullBootTimeoutMs: number; readonly idGenerator: IdGenerator; readonly instanceId: string; readonly logger: Logger | undefined; + readonly logsRoot: string | undefined; readonly marks: DeviceMarks; readonly ownsDeviceSet: boolean; readonly seedTurns: SeedTurns; @@ -55,12 +58,14 @@ export class Seeds { readonly #boot: SimulatorBoot; readonly #clock: Clock; readonly #slimBoot: SlimBoot; + readonly #deviceHub: DeviceHubPreferences; readonly #deviceRoot: string; readonly #filesystem: Filesystem; readonly #fullBootTimeoutMs: number; readonly #idGenerator: IdGenerator; readonly #instanceId: string; readonly #logger: Logger | undefined; + readonly #logsRoot: string | undefined; readonly #marks: DeviceMarks; readonly #ownsDeviceSet: boolean; readonly #seedMakes = new Map>(); @@ -75,12 +80,14 @@ export class Seeds { this.#boot = options.boot; this.#clock = options.clock; this.#slimBoot = options.slimBoot; + this.#deviceHub = options.deviceHub; this.#deviceRoot = options.deviceRoot; this.#filesystem = options.filesystem; this.#fullBootTimeoutMs = options.fullBootTimeoutMs; this.#idGenerator = options.idGenerator; this.#instanceId = options.instanceId; this.#logger = options.logger; + this.#logsRoot = options.logsRoot; this.#marks = options.marks; this.#ownsDeviceSet = options.ownsDeviceSet; this.#seedTurns = options.seedTurns; @@ -111,6 +118,11 @@ export class Seeds { ]; } + /** why: a throwaway a `making` row names is the driver's own leftover, deleted through that row (ADR 0001 §6), so it is no leased device and no orphan. */ + makingThrowaways(): ReadonlySet { + return new Set(this.#sources.makingThrowaways()); + } + async saveSource(device: VirtualDriverDevice): Promise<{ sourceId: string; sizeBytes?: number }> { const data = iosDriverData(device); const catalog = await this.#simctl.loadCatalog(); @@ -150,6 +162,8 @@ export class Seeds { await this.#dropLaunchServicesDatabase(this.#sourcesSet, cloneUdid); const sizeBytes = await this.#sizeOf(cloneUdid); this.#sources.markReady(sourceId, sizeBytes); + // why: ADR 0076: the lease is destroyed next, and `simctl delete` leaves its log folder behind for the baseline's copies to inherit. + await this.#deleteLogFolder(data.udid); return { sourceId, ...(sizeBytes === undefined ? {} : { sizeBytes }) }; } catch (error: unknown) { if (cloneUdid !== undefined && cloneUdid !== "") { @@ -310,6 +324,9 @@ export class Seeds { sourceId, specKey, }); + let throwaway: string | undefined; + let keepRow = false; + let seedClone: string | undefined; try { await this.#ensureSourcesSet(); const created = await this.#simctl.createSimulator( @@ -319,28 +336,46 @@ export class Seeds { resolved.deviceType.identifier, resolved.runtime.identifier, ], - { destination: this.#sourcesSet, source: this.#sourcesSet }, + {}, ); - const udid = created.stdout.trim(); - this.#sources.setUdid(sourceId, udid); + throwaway = created.stdout.trim(); + this.#sources.setThrowaway(sourceId, throwaway); + if (!this.#ownsDeviceSet) { + // why: ADR 0048: in Xcode's set a simulator is Simlock's only by its mark, and a booted one keeps the clipboard sync it booted with. + await this.#marks.writeMark(throwaway); + await this.#deviceHub.disablePasteboardSync(throwaway); + } try { - await this.#boot.bootAndWait(udid, sourceId, this.#fullBootTimeoutMs, this.#sourcesSet); + await this.#boot.bootAndWait(throwaway, sourceId, this.#fullBootTimeoutMs); } catch (error: unknown) { - await this.#deleteSeedSimulator(udid); // why: a seed that ran out of boot time is a boot timeout, as an Android seed's is. if (error instanceof BootTimeoutError) throw error; - throw new DriverCrashError(`seed ${udid} did not boot: ${errorMessage(error)}`); - } - try { - await this.#simctl.shutdown(udid, this.#sourcesSet); - } catch (error: unknown) { - await this.#deleteSeedSimulator(udid); - throw error; + throw new DriverCrashError(`seed ${throwaway} did not boot: ${errorMessage(error)}`); } - this.#sources.markReady(sourceId, await this.#sizeOf(udid)); - return { sourceId, udid, runtimeBuild: resolved.runtime.build }; + await this.#simctl.shutdown(throwaway); + const cloned = await this.#simctl.createSimulator( + ["clone", throwaway, `simlock-seed-${sourceId}`, this.#sourcesSet], + { destination: this.#sourcesSet }, + ); + seedClone = cloned.stdout.trim(); + this.#sources.setUdid(sourceId, seedClone); + const done = throwaway; + throwaway = undefined; + keepRow = true; + await this.#deleteThrowaway(done, false); + keepRow = false; + this.#sources.markReady(sourceId, await this.#sizeOf(seedClone)); + return { sourceId, udid: seedClone, runtimeBuild: resolved.runtime.build }; } catch (error: unknown) { - this.#sources.deleteRow(sourceId); + if (seedClone !== undefined) + await this.#deleteSeedSimulator(seedClone).catch(() => undefined); + if (throwaway !== undefined) { + keepRow = !(await this.#deleteThrowaway(throwaway, true).then( + () => true, + () => false, + )); + } + if (!keepRow) this.#sources.deleteRow(sourceId); throw error; } } @@ -361,6 +396,7 @@ export class Seeds { async #removeLeftover(row: SourceRow): Promise { try { if (row.udid !== undefined) await this.#deleteSeedSimulator(row.udid); + if (row.throwawayUdid !== undefined) await this.#deleteThrowaway(row.throwawayUdid, true); this.#sources.deleteRow(row.sourceId); } catch (error: unknown) { this.#logger?.warn( @@ -381,8 +417,30 @@ export class Seeds { async #deleteSeedSimulator(udid: string): Promise { await this.#simctl.bestEffortShutdown(udid, this.#sourcesSet); + await this.#deleteIn(udid, this.#sourcesSet); + } + + /** why: ADR 0076 §1: the throwaway lives in the device set and is deleted only through the `making` row that names it (ADR 0001 §6), with its log folder, which `simctl delete` leaves behind. */ + async #deleteThrowaway(udid: string, shutdownFirst: boolean): Promise { + if (shutdownFirst) await this.#simctl.bestEffortShutdown(udid); + await this.#deleteIn(udid, undefined); + if (!this.#ownsDeviceSet) await this.#deviceHub.removePasteboardPreference(udid); + await this.#deleteLogFolder(udid); + } + + async #deleteLogFolder(udid: string): Promise { + if (this.#logsRoot === undefined) return; + const path = join(this.#logsRoot, udid); + try { + await this.#filesystem.rm(path); + } catch (error: unknown) { + this.#logger?.warn(`could not delete log folder ${path}: ${errorMessage(error)}`); + } + } + + async #deleteIn(udid: string, set: string | undefined): Promise { const args = ["delete", udid]; - const outcome = await this.#simctl.invoke(args, COMMAND_TIMEOUT_MS, this.#sourcesSet); + const outcome = await this.#simctl.invoke(args, COMMAND_TIMEOUT_MS, set); // why: a seed deleted by hand is already gone, and its row must still be dropped. if (outcome.kind === "finished" && unknownDevice(outcome.result)) return; this.#simctl.checked(args, COMMAND_TIMEOUT_MS, outcome); diff --git a/src/drivers/ios/source-data.ts b/src/drivers/ios/source-data.ts index 2c47f4a49..674ed8170 100644 --- a/src/drivers/ios/source-data.ts +++ b/src/drivers/ios/source-data.ts @@ -29,9 +29,11 @@ export const iosSourceDataOwner: SqliteSchemaOwner = { OR (newer.created_at = ios_source_data.created_at AND newer.source_id > ios_source_data.source_id))); CREATE UNIQUE INDEX ios_source_data_ready_seed ON ios_source_data (spec_key) WHERE kind = 'seed' AND state = 'ready';`, + // why: ADR 0076: the throwaway a seed was copied from, kept so a restart mid-make can delete it through the row. + "ALTER TABLE ios_source_data ADD COLUMN throwaway_udid TEXT", ], name: "ios-source-data", - version: 2, + version: 3, }; export interface NewSourceRow { @@ -52,6 +54,7 @@ export interface SourceRow { readonly sourceId: string; readonly kind: "seed" | "baseline"; readonly udid: string | undefined; + readonly throwawayUdid: string | undefined; readonly deviceTypeId: string; readonly runtimeId: string; readonly runtimeBuild: string | undefined; @@ -104,6 +107,12 @@ export class IosSourceTable { .run(udid, sourceId); } + setThrowaway(sourceId: string, udid: string): void { + this.#database + .prepare("UPDATE ios_source_data SET throwaway_udid = ? WHERE source_id = ?") + .run(udid, sourceId); + } + markReady(sourceId: string, sizeBytes: number | undefined): void { this.#database .prepare("UPDATE ios_source_data SET state = 'ready', size_bytes = ? WHERE source_id = ?") @@ -144,6 +153,15 @@ export class IosSourceTable { ]); } + makingThrowaways(): readonly string[] { + return this.#database + .prepare( + "SELECT throwaway_udid FROM ios_source_data WHERE state = 'making' AND throwaway_udid IS NOT NULL", + ) + .all() + .map((row) => row["throwaway_udid"] as string); + } + allUdids(): readonly string[] { return this.#database .prepare("SELECT udid FROM ios_source_data WHERE udid IS NOT NULL") @@ -162,7 +180,7 @@ export class IosSourceTable { #rows(where: string, parameters: readonly (string | number)[]): readonly SourceRow[] { return this.#database .prepare( - `SELECT source_id, kind, udid, device_type_id, runtime_id, runtime_build, model, os_version, + `SELECT source_id, kind, udid, throwaway_udid, device_type_id, runtime_id, runtime_build, model, os_version, state, maker, size_bytes FROM ios_source_data ${where}`, ) .all(...parameters) @@ -170,6 +188,7 @@ export class IosSourceTable { sourceId: row["source_id"] as string, kind: row["kind"] as "seed" | "baseline", udid: (row["udid"] as string | null) ?? undefined, + throwawayUdid: (row["throwaway_udid"] as string | null) ?? undefined, deviceTypeId: row["device_type_id"] as string, runtimeId: row["runtime_id"] as string, runtimeBuild: (row["runtime_build"] as string | null) ?? undefined, diff --git a/src/drivers/ios/test-index.ts b/src/drivers/ios/test-index.ts index 4c50a1da3..0eacab7df 100644 --- a/src/drivers/ios/test-index.ts +++ b/src/drivers/ios/test-index.ts @@ -1,5 +1,6 @@ import { readFileSync } from "node:fs"; import { + type ScriptedProcessExpectation, ScriptedProcessRunner, type SqliteDatabase, FakeClock, @@ -358,3 +359,39 @@ export function assetInfoPlist(simulatorVersion: string, build: string): string } export const prepareFull = { mode: "full", purpose: "prepare" } as const; + +export const throwawayUdid = "00000000-0000-0000-0000-0000000000bb"; + +export const logsRoot = "/Logs/CoreSimulator"; + +/** why: the calls that make a seed from a throwaway under the `simlock` set, in order; a test starts its script with these, after the catalog read. */ +type ScriptedStep = Pick; + +export function throwawaySeedSteps( + seed: string = seedUdid, +): [ + ScriptedStep, + ScriptedStep, + ScriptedStep, + ScriptedStep, + ScriptedStep, + ScriptedStep, + ScriptedStep, +] { + const name = "simlock-seed-device-1"; + return [ + { + match: simctl("create", name, driverData.deviceTypeId, driverData.runtimeId), + result: { code: 0, stderr: "", stdout: `${throwawayUdid}\n` }, + }, + { match: simctl("boot", throwawayUdid) }, + { match: simctl("bootstatus", throwawayUdid, "-b") }, + { match: simctl("listapps", throwawayUdid) }, + { match: simctl("shutdown", throwawayUdid) }, + { + match: simctl("clone", throwawayUdid, name, `${deviceRoot}/sources`), + result: { code: 0, stderr: "", stdout: `${seed}\n` }, + }, + { match: simctl("delete", throwawayUdid) }, + ]; +} diff --git a/src/drivers/ios/testing.ts b/src/drivers/ios/testing.ts index 2d10c733e..6e074517e 100644 --- a/src/drivers/ios/testing.ts +++ b/src/drivers/ios/testing.ts @@ -17,6 +17,7 @@ export interface PlantedSource { readonly runtimeId: string; readonly sizeBytes?: number; readonly state?: "making" | "ready"; + readonly throwawayUdid?: string; readonly udid?: string; } @@ -38,6 +39,7 @@ export function plantSource(database: SqliteDatabase, source: PlantedSource): Sq specKey: `${source.deviceTypeId}\u0000${source.runtimeId}`, }); if (source.udid !== undefined) table.setUdid(sourceId, source.udid); + if (source.throwawayUdid !== undefined) table.setThrowaway(sourceId, source.throwawayUdid); if (source.state !== "making") table.markReady(sourceId, source.sizeBytes); return database; }