diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index af73a7c4b..3b8001fa0 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 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 +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 and a worker's `ios.slim.exclude` name is (ADR 0083); a boot that writes no label `true` 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/docs/internal/adr/0083-a-worker-may-turn-single-slim-services-on-or-off-beside-its-categories.md b/docs/internal/adr/0083-a-worker-may-turn-single-slim-services-on-or-off-beside-its-categories.md index 37f47c643..214bd9675 100644 --- a/docs/internal/adr/0083-a-worker-may-turn-single-slim-services-on-or-off-beside-its-categories.md +++ b/docs/internal/adr/0083-a-worker-may-turn-single-slim-services-on-or-off-beside-its-categories.md @@ -1,6 +1,6 @@ # 0083. A worker may turn single slim services on or off beside its categories -- **Status:** Accepted — not yet implemented +- **Status:** Accepted - **Date:** 2026-11-17 - **Issue:** [#1644](https://github.com/callstackincubator/simlock/issues/1644) (requests [#1556](https://github.com/callstackincubator/simlock/issues/1556), [#1552](https://github.com/callstackincubator/simlock/issues/1552)) - **Narrows:** [ADR 0060](0060-ios-slim-writes-launchd-overrides-while-the-simulator-is-shut-down.md) §1 (the managed labels gain the worker's named services and the ones it recorded, a never-disable label may be written `true`, and a record file sits beside the overrides) and §2 (a device is `slim` only when some label is written `true`); [ADR 0066](0066-a-slim-lease-may-keep-named-categories-running.md) §2 (a kept category also wins over a service the worker turns off by name). diff --git a/docs/internal/adr/README.md b/docs/internal/adr/README.md index 471e8a90b..e47135fc2 100644 --- a/docs/internal/adr/README.md +++ b/docs/internal/adr/README.md @@ -115,5 +115,5 @@ the status is stale. | [0078](0078-an-android-worker-tries-its-default-image-tag-first-and-falls-back-to-none.md) | An Android worker tries its default image tag first, and a lease falls back to none | Accepted | | [0079](0079-one-capture-per-device-is-shared-by-every-viewer-and-every-capture-sends-a-key-frame-every-5-s.md) | One capture per device is shared by every viewer, and every capture sends a key frame at least every 5 s | Accepted; narrows 0045 §5 | | [0080](0080-an-android-worker-may-enrol-phones-reached-over-the-network.md) | An Android worker may enrol phones reached over the network | Accepted; narrows 0022 §6 and §7, and 0073 §2 and §5 | -| [0083](0083-a-worker-may-turn-single-slim-services-on-or-off-beside-its-categories.md) | A worker may turn single slim services on or off beside its categories | Accepted — not yet implemented; narrows 0060 §1, §2 and 0066 §2 | +| [0083](0083-a-worker-may-turn-single-slim-services-on-or-off-beside-its-categories.md) | A worker may turn single slim services on or off beside its categories | Accepted; narrows 0060 §1, §2 and 0066 §2 | | [0084](0084-a-worker-may-serve-a-platforms-enrolled-phones-only.md) | A worker may serve a platform's enrolled phones only | Accepted; narrows 0022 and 0009 §4 | diff --git a/e2e/helpers/ios-device-set.ts b/e2e/helpers/ios-device-set.ts index 3f5b8689b..76f21dcfa 100644 --- a/e2e/helpers/ios-device-set.ts +++ b/e2e/helpers/ios-device-set.ts @@ -101,6 +101,17 @@ export async function sweepStaleDeviceSets(): Promise { } } +// why: a simulator's daemons run from the runtime's own root, not from the device set, so a service +// is found by its binary's name under a `RuntimeRoot`. +export async function runtimeRootProcesses(binary: string): Promise { + const { stdout } = await execFileAsync("ps", ["-axo", "command="], { + maxBuffer: 16 * 1024 * 1024, + }); + return stdout + .split("\n") + .filter((line) => line.includes("RuntimeRoot") && line.includes(`/usr/libexec/${binary}`)); +} + /** * Host processes whose command line names a path inside `deviceSet`. A booted simulator runs a * `launchd_sim` (and its children) out of its device directory, so a non-empty result means a diff --git a/e2e/slow-ios-slim.test.ts b/e2e/slow-ios-slim.test.ts index e43717e21..dbacedebb 100644 --- a/e2e/slow-ios-slim.test.ts +++ b/e2e/slow-ios-slim.test.ts @@ -7,6 +7,7 @@ import type { TestEnv } from "./helpers/env.js"; import { iosDeviceSet, processesInDeviceSet, + runtimeRootProcesses, setDevices, simctlInSet, sweepStaleDeviceSets, @@ -442,6 +443,45 @@ describe.skipIf(process.platform !== "darwin")( }, ); + it( + "a worker's exclude turns off a service no category holds, and its include keeps a category's service running", + { timeout: 1_800_000 }, + async () => { + const diagnosticd = "com.apple.diagnosticd"; + const apsd = "com.apple.apsd"; + // why: one lane home serves one env at a time (keepSeeds), so one daemon runs both configs in turn. + const env = await withRealDaemon({ ios: { defaultMode: "slim" } }); + const { model, os } = await catalogModelWithOs(env, (versions) => + versions.find((version) => Number(version.split(".")[0]) >= 26), + ); + await env.withConfig( + { ios: { slim: { categories: [], exclude: [diagnosticd] } } }, + async () => { + const excluded = await leaseDetached(env, model, os, "slim-exclude"); + await expectSlim(env, excluded.mode, "a worker with only an exclude must grant slim"); + expect((await printDisabled(excluded)).has(diagnosticd)).toBe(true); + expect( + await runtimeRootProcesses("diagnosticd"), + "no diagnosticd runs while the excluding worker's device is booted", + ).toEqual([]); + await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); + }, + ); + + await env.withConfig({ ios: { slim: { include: [apsd] } } }, async () => { + const included = await leaseDetached(env, model, os, "slim-include"); + await expectSlim(env, included.mode, "a worker with only an include must grant slim"); + const disabled = await printDisabled(included); + expect(disabled.has(apsd), "apsd is kept running by include").toBe(false); + expect( + [...ALL_LABELS].filter((label) => label !== apsd && !disabled.has(label)), + "every other category label is disabled", + ).toEqual([]); + await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); + }); + }, + ); + it( "no simulator from this file's device sets is still running after its flows", { timeout: 60_000 }, diff --git a/src/core/config-role-checks.ts b/src/core/config-role-checks.ts index 8330f82f2..f9f46790b 100644 --- a/src/core/config-role-checks.ts +++ b/src/core/config-role-checks.ts @@ -4,7 +4,13 @@ import { isCapacityStrategyName, type CapacityStrategyName, } from "./capacity/index.js"; -import type { Config, DownloadPolicy, Layer, ModuleConfigEntry } from "./config-types.js"; +import type { + Config, + DownloadPolicy, + DriverConfigEntry, + Layer, + ModuleConfigEntry, +} from "./config-types.js"; import { MIN_EVENT_LOG_MAX_BYTES } from "./config-defaults.js"; import { asObject, mergeConfig, omit, pick } from "./config-helpers.js"; import { invalidValue, requireObject, type Warn } from "./validation.js"; @@ -136,6 +142,15 @@ export function runModuleChecks(config: Config, modules: readonly ModuleConfigEn } } +export function runDriverChecks( + config: Config, + driverSections: readonly DriverConfigEntry[], +): void { + for (const entry of driverSections) { + entry.check?.(config[entry.platform] as never, config); + } +} + function warnWorkerOnlySubKeys( layer: Record, section: string, diff --git a/src/core/config-types.ts b/src/core/config-types.ts index 1da96b0d9..e79bf885f 100644 --- a/src/core/config-types.ts +++ b/src/core/config-types.ts @@ -276,6 +276,8 @@ export interface DriverConfigEntry
{ simlockHome: string, settings: Readonly>, ) => Readonly>; + // why: ADR 0083 I4: runs on the merged config, after both layers, where a rule that spans keys of one section can be judged; it throws a `ConfigError`. + readonly check?: (section: never, config: Config) => void; } export interface ModuleConfigEntry { diff --git a/src/core/config.ts b/src/core/config.ts index 89deea67f..7ecca7f10 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -12,6 +12,7 @@ import { normalizeLayer, requireGatewayHttp, resolveStrategyName, + runDriverChecks, runModuleChecks, validateDeletedRetention, validateEventLogBounds, @@ -204,6 +205,7 @@ export function configFromLayers( validateMetricsRetention(merged); // why: a gateway reads a module's gateway keys, so a bad value stops it too. runModuleChecks(merged, modules); + runDriverChecks(merged, driverSections); if (role === "gateway") { warnWorkerOnlyKeys([fromFile, fromOverrides], warn, modules); requireGatewayHttp(merged); diff --git a/src/drivers/ios/AGENTS.md b/src/drivers/ios/AGENTS.md index 52a027220..3da73ff3a 100644 --- a/src/drivers/ios/AGENTS.md +++ b/src/drivers/ios/AGENTS.md @@ -16,14 +16,15 @@ Resolve and boot: - A slim spec is returned only for a slim request the driver will slim. The registry alone records a device's mode. - `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 boot is `simctl boot`, `bootstatus -b`, then `listapps` until it succeeds, on one deadline: bootstatus can finish before the installer is ready. +- 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, the boot goes on), and `launchctl print-disabled system` is read back after it. A label not as written is `full`; a failed readback is `slim`; both call `onSlimSkipped`, logged only. All as written and the write ok: `slim`, and `onSlimmed` is `device.slimmed`. Nothing written off and no kept category: `full`, no readback. +- Named services (ADR 0083): `exclude` beats `include` beats a category; `simlock-managed.json` records the names, so one dropped from both is written back on. A baseline saved before it keeps a dropped name off; `include` it. +- Slim `except` (ADR 0066): 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 slim overrides and reads nothing back. DeviceHub clipboard isolation is configured before preparation and recovery boots; ready default-set simulators reboot under the lease claim before a grant. Active leases at upgrade keep clipboard sync until a later boot or lease end. - 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`). - Volume (`ios.simulator.audio: false`): apps play at volume 0. A baseline source is not silenced. -- Window (`ios.simulator.headless: false`): DeviceHub is opened in the background and told not to shut down started devices when it quits. Only a non-zero exit of that open means DeviceHub is missing: Simulator.app is then opened instead, detached, so quitting it leaves the simulator running. +- Window (`ios.simulator.headless: false`): DeviceHub is opened in the background and leaves started devices running when it quits. Only a non-zero exit of that open means it is missing: Simulator.app is then opened, detached. Seeds (ADR 0061): @@ -31,9 +32,9 @@ Seeds (ADR 0061): - A seed is made from a throwaway (ADR 0076): `simlock-seed-` is booted once, shut down, cloned unbooted into the sources set, then deleted with its log folder; `saveSource` deletes the saved-from lease's log folder too. 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 source records its lineage and, in `ios_source_files`, the files and links naming it, after flushing its WALs. A clone keeps its source's lineage and, before its first boot, has its `com.apple.LaunchServices-*.csstore` deleted and those files and links swapped to its own UDID; a failed drop or swap deletes it. No lineage: a seed is remade, a baseline stale. - 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. +- 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 5 silent minutes more kills and logs it. - A `making` row of another process is swept at the first `listSources`, with its throwaway; one of this process, once older than any make takes, at the next make of its kind. -- A seed that `simctl delete` calls `Invalid device` is already gone: its row is dropped. `removeComponent` deletes the runtime's seeds first. +- A seed `simctl delete` calls `Invalid device` is gone: its row is dropped. `removeComponent` deletes the runtime's seeds first. Physical, passthrough, screen: @@ -51,13 +52,13 @@ Tunnels (`device-tcp.ts`): - **A restart between `simctl clone` and the durable mark under `default` (#968)** leaves one unlisted `simlock-` simulator in Xcode's set. Delete it with `simctl delete`. - **Runtime downloads outlive deletion (#79).** Reclaim them in Xcode → Settings → Platforms. -- **Slim costs (#87, #172).** Below iOS 18.5 a slim request gets `full`. Slim devices lose push, Spotlight, StoreKit, universal links, Siri, iCloud sync; use `--mode full` for them. +- **Slim costs (#87, #172).** Below iOS 18.5 a slim request gets `full`. Slim devices lose push, Spotlight, StoreKit, universal links, Siri, iCloud sync; use `--mode full`. - **The overrides file is undocumented.** If Apple ignores it, the readback grants `full`. - **A recovered slim device runs full but is recorded `slim` (#174)** until its next `makeReady`. -- **A cold slim lease takes a full cold boot.** MCP clients need a longer timeout. -- **A screen stream can freeze after a reboot under its lease.** The capture checks the boot only at start: after a crash reboot the old picture stays until the Screen tab is reopened. -- **An iPhone's rotation has not run on hardware**; only a Duo's panel switch is proven. A silent iPhone keeps its last picture. +- **A cold slim lease takes a full cold boot;** MCP clients need a longer timeout. +- **A screen stream can freeze after a reboot under its lease:** the capture checks the boot only at start; reopen the Screen tab. +- **An iPhone's rotation has not run on hardware**; only a Duo's panel switch is proven. - **A foldable's stream follows SpringBoard's `DisplayContentMode` log** (ADR 0075): another wording leaves it, and taps, on the panel picked at open; a tap between a fold and the new size lands on the old panel. - **A capture killed by SIGKILL cannot stop its CoreDevice stream**, and neither can a stop while `startMediaStream` runs past its limit. - **A new Xcode major turns iPhone streams off** until `vendor/screen-capture/Stubs/` is checked against it and the pin moves. -- **Untested on an iPhone:** DeviceHub or Xcode showing the same device during a stream; the holder's `devicectl` commands during one; the source ending after the first picture; `stop()` ending the stream. +- **Untested on an iPhone:** DeviceHub or Xcode showing the same device during a stream; the holder's `devicectl` commands during one; `stop()` ending the stream. diff --git a/src/drivers/ios/definition.test.ts b/src/drivers/ios/definition.test.ts index 6ca054770..d86b68946 100644 --- a/src/drivers/ios/definition.test.ts +++ b/src/drivers/ios/definition.test.ts @@ -6,7 +6,7 @@ import { iosDriverConfig } from "./definition.js"; const configPath = "/home/agent/.simlock/config.json"; -async function load(file: unknown) { +async function load(file: unknown, overrides?: unknown) { const filesystem = new MemoryFilesystem(); const warn = vi.fn(); await filesystem.mkdirp("/home/agent/.simlock"); @@ -17,6 +17,7 @@ async function load(file: unknown) { filesystem, systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * 1024 ** 3 }), warn, + ...(overrides === undefined ? {} : { overrides: overrides as never }), }); return { section: driverConfig(config, iosDriverConfig), warn }; } @@ -77,3 +78,45 @@ describe("the iOS driver's keys of the ios config section", () => { expect(section.simulator).toEqual({ audio: true, createTimeoutMs: 30_000, headless: true }); }); }); + +describe("the iOS driver's ios.slim.include and ios.slim.exclude", () => { + const bothLists = (names: string) => + `Invalid config value for "ios.slim": expected no service in both include and exclude (${names})`; + + it("load as lists of service names, and fail the load for a name in both lists or a value that is no list of names", async () => { + const both = await load({ + ios: { slim: { include: ["com.apple.apsd"], exclude: ["com.apple.diagnosticd"] } }, + }); + expect(both.section.slim).toEqual({ + bootTimeoutMs: 600_000, + exclude: ["com.apple.diagnosticd"], + include: ["com.apple.apsd"], + }); + expect(both.warn).not.toHaveBeenCalled(); + expect((await load({ ios: { slim: { include: [] } } })).section.slim.include).toEqual([]); + expect((await load({ ios: { slim: { exclude: ["a", "a"] } } })).section.slim.exclude).toEqual([ + "a", + "a", + ]); + + const refused = [ + [{ ios: { slim: { include: ["x", "y"], exclude: ["y", "x", "z"] } } }, bothLists("x, y")], + [ + { ios: { slim: { include: ["x"] } } }, + bothLists("x"), + { ios: { slim: { exclude: ["x"] } } }, + ], + [ + { ios: { slim: { exclude: "com.apple.diagnosticd" } } }, + 'Invalid config value for "ios.slim.exclude": expected an array of strings', + ], + [ + { ios: { slim: { exclude: [""] } } }, + 'Invalid config value for "ios.slim.exclude": expected an array of strings', + ], + ] as const; + for (const [file, message, overrides] of refused) { + await expect(load(file, overrides), message).rejects.toThrow(message); + } + }); +}); diff --git a/src/drivers/ios/definition.ts b/src/drivers/ios/definition.ts index a57914fbc..457e36b22 100644 --- a/src/drivers/ios/definition.ts +++ b/src/drivers/ios/definition.ts @@ -2,6 +2,7 @@ import { join } from "node:path"; import { booleanValue, + invalidValue, type DriverConfigEntry, objectValidator, positiveNumber, @@ -12,6 +13,10 @@ export interface IosDriverConfig { readonly slim: { /** why: undefined disables every category the driver knows. */ readonly categories?: readonly string[]; + /** why: services a slim device keeps running whatever the categories turn off (ADR 0083 §2). */ + readonly include?: readonly string[]; + /** why: services a slim device turns off beside the categories (ADR 0083 §2). */ + readonly exclude?: readonly string[]; /** why: a slim device gets its own boot deadline, because CI runners are slow. */ readonly bootTimeoutMs: number; }; @@ -45,8 +50,21 @@ export const iosDriverConfig: DriverConfigEntry = { full: { bootTimeoutMs: 300_000 }, simulator: { audio: true, createTimeoutMs: 30_000, headless: true }, }, + // why: ADR 0083 §1: the two lists are checked on the merged config, because the file and the overrides are validated one layer at a time. + check: (section: IosDriverConfig) => { + const { exclude = [], include = [] } = section.slim; + const both = [...new Set(include.filter((name) => exclude.includes(name)))].sort(); + if (both.length > 0) { + throw invalidValue("ios.slim", `no service in both include and exclude (${both.join(", ")})`); + } + }, validators: { - slim: objectValidator({ categories: stringArray, bootTimeoutMs: positiveNumber }), + slim: objectValidator({ + categories: stringArray, + bootTimeoutMs: positiveNumber, + include: stringArray, + exclude: stringArray, + }), full: objectValidator({ bootTimeoutMs: positiveNumber }), simulator: objectValidator({ audio: booleanValue, diff --git a/src/drivers/ios/index-save-source-lifecycle.test.ts b/src/drivers/ios/index-save-source-lifecycle.test.ts index 8e1d87ca1..e442cb6e7 100644 --- a/src/drivers/ios/index-save-source-lifecycle.test.ts +++ b/src/drivers/ios/index-save-source-lifecycle.test.ts @@ -11,6 +11,7 @@ import { plantManagedDevice, overridesFolder, overridesPath, + recordPath, overridesPlist, FaultyFilesystem, instanceId, @@ -183,7 +184,7 @@ describe("IosSimctlDriver", () => { it.each([ { - name: "copies the seed's disabled.plist to the new simulator", + name: "copies the seed's disabled.plist and its record of named services to the new simulator", seedHas: true, failing: undefined, }, @@ -199,6 +200,7 @@ describe("IosSimctlDriver", () => { if (seedHas) { await filesystem.mkdirp(overridesFolder(seedUdid)); await filesystem.writeFileAtomic(overridesPath(seedUdid), overridesPlist({ "a.b": true })); + await filesystem.writeFileAtomic(recordPath(seedUdid), '["a.b"]'); } await plantLaunchServices(filesystem, `${deviceRoot}/${driverData.udid}`); filesystem.failing = failing; @@ -233,7 +235,9 @@ describe("IosSimctlDriver", () => { ).toEqual(["com.apple.LaunchServices.unregisteredtypes-501.db"]); const copied = failing === undefined && seedHas; expect(await filesystem.exists(overridesPath(driverData.udid))).toBe(copied); + expect(await filesystem.exists(recordPath(driverData.udid))).toBe(copied); if (copied) { + expect(await filesystem.readFile(recordPath(driverData.udid))).toBe('["a.b"]'); expect(await filesystem.readFile(overridesPath(driverData.udid))).toBe( overridesPlist({ "a.b": true }), ); diff --git a/src/drivers/ios/slim-boot.ts b/src/drivers/ios/slim-boot.ts index f2c3ef028..7ff9b822b 100644 --- a/src/drivers/ios/slim-boot.ts +++ b/src/drivers/ios/slim-boot.ts @@ -23,6 +23,8 @@ import { type IosDriverData } from "./simulator-data.js"; // why: ADR 0060 §2: simslim's limit for a simulator just after its first boot. const READBACK_TIMEOUT_MS = 120_000; const OVERRIDES_FILE_NAME = "disabled.plist"; +// why: ADR 0083 S2: the names the worker's `include` and `exclude` held at the last write. +const RECORD_FILE_NAME = "simlock-managed.json"; export const DEFAULT_OVERRIDES_ROOT = "/private/var/tmp"; const OVERRIDES_FOLDER_PREFIX = "com.apple.CoreSimulator.SimDevice."; @@ -53,6 +55,7 @@ type SlimWrite = readonly kept: readonly SlimCategory[]; readonly startedAt: number; readonly writeError: string | undefined; + readonly unconfigured: string | undefined; }; type SlimPlan = @@ -137,6 +140,13 @@ export class SlimBoot { from, join(this.#overridesFolder(copyUdid), OVERRIDES_FILE_NAME), ); + const record = join(this.#overridesFolder(seedUdid), RECORD_FILE_NAME); + if (await this.#filesystem.exists(record)) { + await this.#filesystem.copyFile( + record, + join(this.#overridesFolder(copyUdid), RECORD_FILE_NAME), + ); + } } catch (error: unknown) { this.#logger?.warn( `could not copy the launchd overrides of seed ${seedUdid} to ${copyUdid}: ${errorMessage(error)}`, @@ -160,30 +170,77 @@ export class SlimBoot { ): 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", - }; + const folder = this.#overridesFolder(udid); + const include = slim.include ?? []; + const exclude = slim.exclude ?? []; + const names = [...new Set([...include, ...exclude])].sort(); + const recorded = await this.#readRecord(join(folder, RECORD_FILE_NAME)); + const noCategories = configured.categories.length === 0; + const noCategoriesDetail = `none of the configured slim categories (${(slim.categories ?? []).join(", ")}) are known`; + // why: a name the worker dropped is still written back on (ADR 0083 §5), so a record or a name keeps the write going even with no category. + if (noCategories && names.length === 0 && recorded.length === 0) { + return { detail: noCategoriesDetail, kind: "no-categories" }; } const startedAt = this.#clock.now(); - const wanted = overridesFor(resolved.categories, kept); - let writeError: string | undefined; + const wanted = overridesFor(resolved.categories, kept, { exclude, include, recorded }); + const writeError = await this.#tryWriteFiles(folder, wanted, { names, recorded }); + // why: no category and no `exclude` is the unconfigured case, which logs its skip as before (ADR 0083 §4). + const unconfigured = noCategories && exclude.length === 0 ? noCategoriesDetail : undefined; + return { kept, kind: "written", resolved, startedAt, unconfigured, wanted, writeError }; + } + + async #tryWriteFiles( + folder: string, + wanted: ReadonlyMap, + record: { readonly names: readonly string[]; readonly recorded: readonly string[] }, + ): Promise { try { - const folder = this.#overridesFolder(udid); - const file = join(folder, OVERRIDES_FILE_NAME); - const existing = await this.#readOverrides(file); - const merged = new Map([...existing, ...wanted]); - if (!sameEntries(existing, merged)) { - await this.#filesystem.mkdirp(folder, { mode: 0o700 }); - await this.#filesystem.writeFileAtomic(file, renderOverridesPlist(merged), { mode: 0o644 }); - } + await this.#writeFiles(folder, wanted, record); + return undefined; } catch (error: unknown) { - writeError = `could not write the launchd overrides file: ${errorMessage(error)}`; + return `could not write the launchd overrides file: ${errorMessage(error)}`; } + } - return { kept, kind: "written", resolved, startedAt, wanted, writeError }; + // why: the plist first, then the record: a restart between them leaves the old record, which still lists every name the plist may hold off (ADR 0083 S2). + async #writeFiles( + folder: string, + wanted: ReadonlyMap, + record: { readonly names: readonly string[]; readonly recorded: readonly string[] }, + ): Promise { + const file = join(folder, OVERRIDES_FILE_NAME); + const existing = await this.#readOverrides(file); + const merged = new Map([...existing, ...wanted]); + if (!sameEntries(existing, merged)) { + await this.#filesystem.mkdirp(folder, { mode: 0o700 }); + await this.#filesystem.writeFileAtomic(file, renderOverridesPlist(merged), { mode: 0o644 }); + } + if (JSON.stringify(record.names) !== JSON.stringify(record.recorded)) { + await this.#filesystem.mkdirp(folder, { mode: 0o700 }); + await this.#filesystem.writeFileAtomic( + join(folder, RECORD_FILE_NAME), + JSON.stringify(record.names), + { mode: 0o644 }, + ); + } + } + + // why: ADR 0083 S2: a record that is missing or cannot be read as a list of strings is an empty one, so an old simulator or a damaged file never fails a boot. + async #readRecord(file: string): Promise { + try { + if (!(await this.#filesystem.exists(file))) return []; + const parsed: unknown = JSON.parse(await this.#filesystem.readFile(file)); + if (Array.isArray(parsed) && parsed.every((name) => typeof name === "string")) { + return parsed as string[]; + } + throw new Error("it is not a list of strings"); + } catch (error: unknown) { + this.#logger?.warn( + `could not read the record of named services ${file}: ${errorMessage(error)}`, + ); + return []; + } } async #readOverrides(file: string): Promise> { @@ -206,6 +263,10 @@ export class SlimBoot { if (write.kept.length > 0 && write.writeError !== undefined) { throw new KeptCategoriesError(write.writeError); } + // why: ADR 0083 §4: with no label written off the device is `full` whatever a readback would say, so none is run unless a kept category needs it. + if (write.kept.length === 0 && !writesOff(write)) { + return this.#unreadFull(device, data, write); + } const outcome = await this.#simctl.invoke( ["spawn", data.udid, "launchctl", "print-disabled", "system"], READBACK_TIMEOUT_MS, @@ -220,6 +281,17 @@ export class SlimBoot { return this.#judgeReadBack(device, data, write, details, outcome.result.stdout); } + #unreadFull( + device: DriverDevice, + data: IosDriverData, + write: Extract, + ): DriverDevice { + const detail = [write.unconfigured, write.writeError].filter((part) => part !== undefined); + return detail.length === 0 + ? this.#asIs(device, data, "full") + : this.#skipApply(device, data, detail.join("; "), "full"); + } + #judgeReadBack( device: DriverDevice, data: IosDriverData, @@ -242,8 +314,8 @@ export class SlimBoot { return this.#skipApply(device, data, details.join("; "), "slim"); } - // 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"); + // why: nothing written off (an except list naming the whole slim set, or an include covering it) slims nothing: full, no `device.slimmed` (ADR 0083 §4). + if (!writesOff(write)) return this.#asIs(device, data, "full"); this.#reportSlimmed(device, data, write); return this.#asIs(device, data, "slim"); } @@ -336,3 +408,7 @@ function readBackFailure( ? `timed out after ${String(READBACK_TIMEOUT_MS)}ms` : `exit ${String(outcome.result.code)}: ${outcome.result.stderr.trim()}`; } + +function writesOff(write: Extract): boolean { + return [...write.wanted.values()].some(Boolean); +} diff --git a/src/drivers/ios/slim-labels.ts b/src/drivers/ios/slim-labels.ts index 8d75b0eed..e40f0cdee 100644 --- a/src/drivers/ios/slim-labels.ts +++ b/src/drivers/ios/slim-labels.ts @@ -341,23 +341,40 @@ export const NEVER_DISABLE_LABELS: readonly string[] = [ "com.apple.sharingd", ]; +export interface NamedServices { + readonly include: readonly string[]; + readonly exclude: readonly string[]; + readonly recorded: 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 and for - * every label of a kept category. + * why: Every managed label (all categories, the never-disable labels and the worker's named + * services) mapped to what the overrides file must say, last rule wins (ADR 0083 S1): `false` + * for all; `true` for a label of a configured category (never-disable labels excepted); `true` + * for an `exclude` name; `false` for an `include` name and for every label of a kept category. */ export function overridesFor( categories: readonly SlimCategory[], keep: readonly SlimCategory[] = [], + named: NamedServices = { exclude: [], include: [], recorded: [] }, ): ReadonlyMap { const wanted = new Map(); for (const category of SLIM_CATEGORIES) { for (const label of category.labels) wanted.set(label, false); } - for (const label of NEVER_DISABLE_LABELS) wanted.set(label, false); + for (const label of [ + ...NEVER_DISABLE_LABELS, + ...named.recorded, + ...named.include, + ...named.exclude, + ]) { + wanted.set(label, false); + } for (const label of labelsFor(categories)) { if (!NEVER_DISABLE_LABELS.includes(label)) wanted.set(label, true); } + for (const label of named.exclude) wanted.set(label, true); + for (const label of named.include) wanted.set(label, false); // why: an excepted category wins over a slimmed one that lists the same label (ADR 0066 §2). for (const label of labelsFor(keep)) wanted.set(label, false); return wanted; diff --git a/src/drivers/ios/slim-named-services.test.ts b/src/drivers/ios/slim-named-services.test.ts new file mode 100644 index 000000000..a19cdf25e --- /dev/null +++ b/src/drivers/ios/slim-named-services.test.ts @@ -0,0 +1,354 @@ +import { describe, expect, it, vi } from "vitest"; + +import { KeptCategoriesError } from "../../core/index.js"; +import { FakeClock, ScriptedProcessRunner, type Logger } from "../../ports/index.js"; +import type { IosDriverConfig } from "./definition.js"; +import { SLIM_CATEGORIES, type SlimmedFact, type SlimSkippedFact } from "./index.js"; +import { + createSlimDriver, + driverData, + FaultyFilesystem, + overridesFolder, + overridesPath, + overridesPlist, + parseOverrides, + plantManagedDevice, + printDisabled, + recordPath, + slimBootCalls, +} from "./test-slim.js"; + +const slim18_5 = { ...driverData, runtimeId: "com.apple.CoreSimulator.SimRuntime.iOS-18-5" }; +const diagnosticd = "com.apple.diagnosticd"; +// why: spelled out, not imported: the labels simslim never disables (ADR 0060 §1). +const neverDisabled = ["com.apple.assistantd", "com.apple.gamed", "com.apple.sharingd"]; + +/** why: What launchd prints once the worker's categories and the named services are off. */ +function disabledReadback( + categories: readonly string[], + off: readonly string[], + on: readonly string[] = [], +): Record { + const labels = SLIM_CATEGORIES.filter((category) => categories.includes(category.name)) + .flatMap((category) => category.labels) + .filter((label) => !neverDisabled.includes(label) && !on.includes(label)); + return Object.fromEntries([...labels, ...off].map((label) => [label, "disabled"])); +} + +async function plantOverrides( + filesystem: FaultyFilesystem, + options: { readonly plist?: Readonly>; readonly record?: string }, +): Promise { + const planted = [ + [overridesPath(slim18_5.udid), options.plist && overridesPlist(options.plist)], + [recordPath(slim18_5.udid), options.record], + ] as const; + for (const [path, contents] of planted) { + if (contents === undefined) continue; + await filesystem.mkdirp(overridesFolder(slim18_5.udid)); + await filesystem.writeFileAtomic(path, contents); + } + filesystem.writes.length = 0; +} + +async function readJson(filesystem: FaultyFilesystem, path: string): Promise { + return (await filesystem.exists(path)) ? JSON.parse(await filesystem.readFile(path)) : undefined; +} + +async function boot(options: { + readonly slim: Omit; + readonly readback?: Readonly>; + readonly readbackFails?: boolean; + readonly except?: readonly string[]; + readonly plist?: Readonly>; + readonly record?: string; + readonly failing?: FaultyFilesystem["failing"]; +}) { + const filesystem = new FaultyFilesystem(); + await plantManagedDevice(filesystem); + await plantOverrides(filesystem, options); + if (options.failing !== undefined) filesystem.failing = options.failing; + const warn = vi.fn<(message: string) => void>(); + const logger: Logger = { + debug: () => {}, + error: () => {}, + info: () => {}, + warn, + child: () => logger, + }; + const calls = slimBootCalls(slim18_5.udid, ""); + const runner = new ScriptedProcessRunner([ + ...calls.slice(0, 3), + { + match: calls[3]!.match, + result: + options.readbackFails === true + ? { code: 1, stderr: "boom\n", stdout: "" } + : { code: 0, stderr: "", stdout: printDisabled(options.readback ?? {}) }, + }, + ]); + const onSlimmed = vi.fn<(fact: SlimmedFact) => void>(); + const onSlimSkipped = vi.fn<(fact: SlimSkippedFact) => void>(); + const driver = await createSlimDriver( + runner, + filesystem, + { bootTimeoutMs: 300_000, ...options.slim }, + onSlimmed, + onSlimSkipped, + false, + new FakeClock(), + logger, + ); + 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: Readonly> = (await filesystem.exists(file)) + ? parseOverrides(await filesystem.readFile(file)) + : {}; + const record = await readJson(filesystem, recordPath(slim18_5.udid)); + return { filesystem, onSlimSkipped, onSlimmed, outcome, record, warn, written }; +} + +describe("IosSimctlDriver makeReady with include and exclude names", () => { + const apsd = "com.apple.apsd"; + const everyCategory = SLIM_CATEGORIES.map((category) => category.name); + const slimMode = { result: expect.objectContaining({ mode: "slim" }) }; + const fullMode = { result: expect.objectContaining({ mode: "full" }) }; + + it("grants the mode the readback shows for the named services", async () => { + const excludeOnly = await boot({ + slim: { categories: [], exclude: [diagnosticd] }, + readback: { [diagnosticd]: "disabled" }, + }); + expect(excludeOnly.written[diagnosticd]).toBe(true); + expect(excludeOnly.outcome).toEqual(slimMode); + expect(excludeOnly.onSlimmed).toHaveBeenCalledWith( + expect.objectContaining({ categories: [], labelCount: 1 }), + ); + + const all = disabledReadback(everyCategory, [diagnosticd]); + const asWritten = await boot({ slim: { exclude: [diagnosticd] }, readback: all }); + expect(asWritten.outcome).toEqual(slimMode); + expect(asWritten.onSlimmed).toHaveBeenCalledWith( + expect.objectContaining({ categories: everyCategory, labelCount: Object.keys(all).length }), + ); + + const excludeEnabled = await boot({ + slim: { exclude: [diagnosticd] }, + readback: { ...all, [diagnosticd]: "enabled" }, + }); + expect(excludeEnabled.outcome).toEqual(fullMode); + expect(excludeEnabled.onSlimmed).not.toHaveBeenCalled(); + expect(excludeEnabled.onSlimSkipped).toHaveBeenCalledWith( + expect.objectContaining({ + detail: expect.stringContaining( + `managed labels did not read back as written at boot; first: ${diagnosticd}`, + ), + }), + ); + + const includeDisabled = await boot({ + slim: { include: [apsd] }, + readback: disabledReadback(everyCategory, []), + }); + expect(includeDisabled.outcome).toEqual(fullMode); + expect(includeDisabled.onSlimmed).not.toHaveBeenCalled(); + + const readbackFails = await boot({ slim: { exclude: [diagnosticd] }, readbackFails: true }); + expect(readbackFails.outcome).toEqual(slimMode); + expect(readbackFails.onSlimSkipped).toHaveBeenCalledWith( + expect.objectContaining({ + detail: "could not read back the launchd overrides: exit 1: boom", + }), + ); + + const nothingOff = await boot({ + slim: { + categories: ["store"], + include: SLIM_CATEGORIES.find((c) => c.name === "store")!.labels, + }, + }); + expect(nothingOff.outcome).toEqual(fullMode); + expect(nothingOff.onSlimmed).not.toHaveBeenCalled(); + + const exceptCoversSet = await boot({ slim: { categories: ["store"] }, except: ["store"] }); + expect(exceptCoversSet.outcome).toEqual(fullMode); + expect(exceptCoversSet.onSlimmed).not.toHaveBeenCalled(); + + const noCategories = await boot({ slim: { categories: [] } }); + expect(noCategories.outcome).toEqual(fullMode); + expect(noCategories.written).toEqual({}); + expect(noCategories.onSlimSkipped).toHaveBeenCalledWith( + expect.objectContaining({ reason: "apply-failed" }), + ); + + const noCategoriesCases = [ + { slim: { categories: [], include: [apsd] } }, + { + slim: { categories: [] }, + plist: { [diagnosticd]: true }, + record: JSON.stringify([diagnosticd]), + }, + { slim: { categories: [], include: [apsd] }, readbackFails: true }, + { slim: { categories: [], include: [apsd] }, failing: "writeRecord" as const }, + ]; + for (const options of noCategoriesCases) { + const result = await boot(options); + expect(result.outcome).toEqual(fullMode); + expect(result.onSlimSkipped).toHaveBeenCalledWith( + expect.objectContaining({ reason: "apply-failed" }), + ); + expect(result.onSlimmed).not.toHaveBeenCalled(); + } + + const unconfiguredWriteFails = await boot({ + slim: { categories: [] }, + plist: { [diagnosticd]: true }, + record: JSON.stringify([diagnosticd]), + failing: "writeFileAtomic", + }); + expect(unconfiguredWriteFails.outcome).toEqual(fullMode); + expect(unconfiguredWriteFails.onSlimSkipped).toHaveBeenCalledWith( + expect.objectContaining({ + detail: expect.stringMatching(/none of the configured.*could not write the launchd/), + }), + ); + + const nothingOffUnreadable = await boot({ + slim: { + categories: ["store"], + include: SLIM_CATEGORIES.find((c) => c.name === "store")!.labels, + }, + readbackFails: true, + }); + expect(nothingOffUnreadable.outcome).toEqual(fullMode); + }); + + it("fails a lease's boot only on its kept categories", async () => { + const storeLabels = SLIM_CATEGORIES.find((category) => category.name === "store")!.labels; + const keptLabel = storeLabels[0]!; + const base = disabledReadback(everyCategory, [diagnosticd], storeLabels); + const slim = { exclude: [diagnosticd] }; + + const kept = await boot({ slim, except: ["store"], readback: base }); + expect(kept.outcome).toEqual(slimMode); + + const keptDisabled = await boot({ + slim, + except: ["store"], + readback: { ...base, [keptLabel]: "disabled" }, + }); + expect(keptDisabled.outcome).toEqual({ + error: new KeptCategoriesError(`1 kept labels are not enabled; first: ${keptLabel}`), + }); + + const excludeEnabled = await boot({ + slim, + except: ["store"], + readback: { ...base, [diagnosticd]: "enabled" }, + }); + expect(excludeEnabled.outcome).toEqual(fullMode); + }); +}); + +describe("IosSimctlDriver makeReady writes the managed labels of a slim device", () => { + const apsd = "com.apple.apsd"; + const passd = "com.apple.passd"; + const gamed = "com.apple.gamed"; + + it("writes each managed label as the precedence of the named services says, and keeps the record of the names", async () => { + const included = await boot({ slim: { include: [apsd] } }); + expect(included.written[apsd]).toBe(false); + expect(included.written[passd]).toBe(true); + + const excluded = await boot({ slim: { exclude: [diagnosticd, gamed] } }); + expect(excluded.written[diagnosticd]).toBe(true); + expect(excluded.written[gamed]).toBe(true); + expect(excluded.record).toEqual([diagnosticd, gamed]); + expect(excluded.filesystem.modes.record).toBe(0o644); + + const kept = await boot({ slim: { exclude: [apsd] }, except: ["store"] }); + expect(kept.written[apsd]).toBe(false); + + const unmanaged = await boot({ slim: {}, plist: { "com.example.unmanaged": true } }); + expect(unmanaged.written["com.example.unmanaged"]).toBe(true); + expect(unmanaged.written[passd]).toBe(true); + + const dropped = await boot({ + slim: { exclude: [gamed] }, + plist: { [diagnosticd]: true }, + record: JSON.stringify([diagnosticd, gamed]), + }); + expect(dropped.written[diagnosticd]).toBe(false); + expect(dropped.written[gamed]).toBe(true); + expect(dropped.record).toEqual([gamed]); + expect(dropped.filesystem.writes).toEqual([ + overridesPath(slim18_5.udid), + recordPath(slim18_5.udid), + ]); + + const droppedWithNoCategory = await boot({ + slim: { categories: [] }, + plist: { [diagnosticd]: true }, + record: JSON.stringify([diagnosticd]), + }); + expect(droppedWithNoCategory.written[diagnosticd]).toBe(false); + expect(droppedWithNoCategory.record).toEqual([]); + + const none = await boot({ slim: { exclude: [gamed] } }); + expect(none.warn).not.toHaveBeenCalled(); + expect(none.record).toEqual([gamed]); + + const unreadable = await boot({ + slim: { exclude: [gamed] }, + plist: { [diagnosticd]: true }, + record: "{not a list", + }); + expect(unreadable.warn).toHaveBeenCalledWith( + expect.stringContaining("could not read the record of named services"), + ); + expect(unreadable.written[diagnosticd]).toBe(true); + expect(unreadable.record).toEqual([gamed]); + + const wrongShape = await boot({ + slim: { exclude: [gamed] }, + record: JSON.stringify([1, 2]), + }); + expect(wrongShape.warn).toHaveBeenCalledTimes(1); + + const unchanged = await boot({ + slim: { exclude: [gamed] }, + plist: { [gamed]: true }, + record: JSON.stringify([gamed]), + }); + expect(unchanged.filesystem.writes).toContain(overridesPath(slim18_5.udid)); + expect(unchanged.filesystem.writes).not.toContain(recordPath(slim18_5.udid)); + + const emptyNeverWritten = await boot({ slim: {} }); + expect(emptyNeverWritten.record).toBeUndefined(); + expect(emptyNeverWritten.warn).not.toHaveBeenCalled(); + }); + + it("counts a failed record write as a failed overrides write", async () => { + const failed = await boot({ + slim: { categories: [], exclude: [diagnosticd] }, + readback: { [diagnosticd]: "disabled" }, + failing: "writeRecord", + }); + expect(failed.outcome).toEqual({ result: expect.objectContaining({ mode: "slim" }) }); + expect(failed.onSlimSkipped).toHaveBeenCalledWith( + expect.objectContaining({ + detail: "could not write the launchd overrides file: disk full", + reason: "apply-failed", + }), + ); + expect(failed.onSlimmed).not.toHaveBeenCalled(); + }); +}); diff --git a/src/drivers/ios/test-slim.ts b/src/drivers/ios/test-slim.ts index 03d03dbfc..2bd7ecd93 100644 --- a/src/drivers/ios/test-slim.ts +++ b/src/drivers/ios/test-slim.ts @@ -10,7 +10,9 @@ import { MemoryFilesystem, ScriptedProcessRunner, type Filesystem, + type Logger, } from "../../ports/index.js"; +import type { IosDriverConfig } from "./definition.js"; import { IosSimctlDriver, type SlimmedFact, type SlimSkippedFact } from "./index.js"; import { memorySourceDatabase } from "./testing.js"; @@ -85,14 +87,12 @@ export async function plantManagedDevice(filesystem: Filesystem): Promise export async function createSlimDriver( runner: ScriptedProcessRunner, filesystem: Filesystem, - slim: { - readonly categories?: readonly string[]; - readonly bootTimeoutMs: number; - }, + slim: IosDriverConfig["slim"], onSlimmed?: (fact: SlimmedFact) => void, onSlimSkipped?: (fact: SlimSkippedFact) => void, slimByDefault = false, clock = new FakeClock(), + logger?: Logger, ): Promise { return await IosSimctlDriver.create({ database: await memorySourceDatabase(), @@ -104,6 +104,7 @@ export async function createSlimDriver( idGenerator: { generate: () => "device-1" }, ...(onSlimmed === undefined ? {} : { onSlimmed }), ...(onSlimSkipped === undefined ? {} : { onSlimSkipped }), + ...(logger === undefined ? {} : { logger }), launchdOverridesRoot: overridesRoot, processRunner: runner, config: { slim }, @@ -121,6 +122,11 @@ export function overridesPath(udid: string): string { return `${overridesFolder(udid)}/disabled.plist`; } +/** why: ADR 0083 S2: the record of named services sits beside the overrides file. */ +export function recordPath(udid: string): string { + return `${overridesFolder(udid)}/simlock-managed.json`; +} + export function overridesPlist(entries: Readonly>): string { const lines = Object.entries(entries).map( ([label, off]) => `${label}<${String(off)}/>`, @@ -131,8 +137,12 @@ export function overridesPlist(entries: Readonly>): stri /** 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; + readonly modes: { + folder?: number | undefined; + file?: number | undefined; + record?: number | undefined; + } = {}; + failing: "writeFileAtomic" | "writeRecord" | "mkdirp" | "rm" | "copyFile" | undefined; failureMessage = "disk full"; override async writeFileAtomic( @@ -143,9 +153,13 @@ export class FaultyFilesystem extends MemoryFilesystem { if (this.failing === "writeFileAtomic" && path.endsWith("disabled.plist")) { throw new Error(this.failureMessage); } + if (this.failing === "writeRecord" && path.endsWith("simlock-managed.json")) { + 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; + if (path.endsWith("simlock-managed.json")) this.modes.record = options?.mode; } override async mkdirp(path: string, options?: Parameters[1]) { diff --git a/website/src/content/docs/docs/reference/configuration.mdx b/website/src/content/docs/docs/reference/configuration.mdx index 6cd0a0606..c057f9878 100644 --- a/website/src/content/docs/docs/reference/configuration.mdx +++ b/website/src/content/docs/docs/reference/configuration.mdx @@ -203,7 +203,9 @@ The warm pool never downloads. A gateway never asks a worker to download for a l | Key | Type | Default | Meaning | Applies to | | ---------------------------------- | ---------------------------------- | -------------------------------- | --------------------------------------------------------------------------------------------------------- | ---------- | | `ios.defaultMode` | `slim` or `full` | `full` | Device mode for an iOS request that names none. The worker makes both kinds either way. | Worker | -| `ios.slim.categories` | list of strings | every category | Which groups of simulator services a slim device has turned off: `widgets`, `siri`, `search`, `icloud`, `store`, `pim`, `web`, `family`, `health`, `photos`, `apps`, `messaging`, `connectivity`, `telemetry`, `mdm`, `other`. Narrowing the list turns the dropped services back on the next time a device is prepared. | Worker | +| `ios.slim.categories` | list of strings | every category | Which groups of simulator services a slim device has turned off: `widgets`, `siri`, `search`, `icloud`, `store`, `pim`, `web`, `family`, `health`, `photos`, `apps`, `messaging`, `connectivity`, `telemetry`, `mdm`, `other`. Narrowing the list turns the dropped services back on the next time a device is prepared. `categories` and `exclude` turn services off; `include` keeps them running. | Worker | +| `ios.slim.include` | list of strings | none | Launchd service names, such as `com.apple.apsd`, that a slim device keeps running even when a category turns them off. A name that is no service does nothing, and Simlock does not warn. A name in `exclude` too fails the config load. | Worker | +| `ios.slim.exclude` | list of strings | none | Launchd service names, such as `com.apple.diagnosticd`, that a slim device turns off beside its categories. This includes services no category holds and the three that slim never turns off (`assistantd`, `gamed`, `sharingd`). A lease's `--except` category still keeps its own services running. With `categories` set to `[]`, a list here alone makes a device slim. Removing a name turns the service back on the next time a device is prepared, except in a saved baseline made before this key existed; put the name in `include` for those. | Worker | | `ios.slim.bootTimeoutMs` | positive number | `600000` (10 min) | Boot deadline for a slim iOS device, which boots once. | Worker | | `ios.full.bootTimeoutMs` | positive number | `300000` (5 min) | Boot deadline for a full iOS device: a new device, a recovery boot and the boot that makes a seed. Counted from before `simctl boot`: the boot and `bootstatus` share it. | Worker | | `ios.defaultModels.` | model name, or non-empty list | not set | iOS models to try first for a class (`phone`, `tablet`, `watch`, `tv`, `vision`, `auto`, `desktop`), most preferred first, before Simlock's own list. A key that is not a class stops the daemon from starting. | Worker | diff --git a/website/src/content/docs/docs/using-devices/choosing-a-device.mdx b/website/src/content/docs/docs/using-devices/choosing-a-device.mdx index a99464fcb..5515301c8 100644 --- a/website/src/content/docs/docs/using-devices/choosing-a-device.mdx +++ b/website/src/content/docs/docs/using-devices/choosing-a-device.mdx @@ -141,6 +141,24 @@ The simulator boots with those categories running and the rest of the slim set o - A device the worker holds warm is shut down and booted again with your list before you get it, so the lease can take a little longer than one without `--except`. If that boot fails, the device is deleted and Simlock tries once more with another; a second failure is `PROVISION_FAILED`. - Over HTTP the body takes `except` as a list, and over MCP `lease_simulator` takes the same `except`. +### Keep or turn off single services (worker admin) + +A worker's config can name single services, beside the categories. `ios.slim.include` keeps a service running even when its category is off, and `ios.slim.exclude` turns one off, even one that no category holds: + +```jsonc +{ "ios": { "defaultMode": "slim", "slim": { + "include": ["com.apple.apsd"], + "exclude": ["com.apple.diagnosticd"] } } } +``` + +- Every slim device the worker prepares from then on boots that way. A lease changes nothing: `--except` still names categories only, and a category it keeps wins over `exclude` for its own services. +- With `categories` set to `[]`, `exclude` alone makes a device slim. A device with no service turned off is `full`. +- `exclude` also turns off the three services slim never touches (`assistantd`, `gamed`, `sharingd`). +- A name in both lists, or a list that holds anything but names, fails the config load. +- Simlock does not check that a name is a real service: a misspelling turns nothing off and keeps nothing running. +- Taking a name out of `exclude` turns the service back on at the next prepare, including in idle simulators that survive a restart. A baseline saved before this setting existed has no record of the name: put it in `include` to turn it on in that baseline's copies. +- An `include` or `exclude` service that does not read back as written grants a `full` device, as for any slim service. + ## Choose the system image (Android) `--image-tag` picks the kind of Android system image, such as `google_apis_playstore` for Google Play or `default` for plain Android. You can use the tags that `simlock catalog --platform android` lists under images.