diff --git a/docs/internal/flows/device-selection.md b/docs/internal/flows/device-selection.md index 95482f9ae..13a101aef 100644 --- a/docs/internal/flows/device-selection.md +++ b/docs/internal/flows/device-selection.md @@ -15,9 +15,9 @@ How one lease request becomes one concrete device, virtual or physical. | Default mode | `ios.defaultMode` (`full`); Android always `full` | Per request with no `mode` | | Operator preference lists | `ios.defaultModels`, `android.defaultModels` | Merged once at start | | Built-in preference lists | `Driver.defaultModels` of each driver | Merged once at start, after the operator's | -| Catalog | `DriverCatalog.listCatalog` → `Driver.listCatalog` | Per class or range request; no cache | +| Catalog | `DriverCatalog.listCatalog` → `Driver.listCatalog` | Per class or range request; built on every read (Android keeps only its `avdmanager list device` answer, below) | | Android profile library (16) | `drivers/android/profiles/` | Static | -| Android SDK profiles | `avdmanager list device` | Each catalog; each resolve of a model the library lacks; each library provision (seed) | +| Android SDK profiles | `avdmanager list device`, kept in `AvdmanagerDeviceList` | Asked by each catalog, each resolve of a model the library lacks, each library provision (seed); run again only when the sdklib jar, the tools' `source.properties`, the user's devices.xml, an image's or add-on's devices.xml, or an `extras//` extra's devices.xml or `source.properties` changed size or modified time, appeared or went, or an image was installed or removed; 30 s limit | | Android devices.xml | `$ANDROID_USER_HOME/devices.xml`, else `.android/devices.xml` | Each catalog; a resolve no earlier source answered | | Android system images | `/system-images/android-*//` + `source.properties` | Each resolve, catalog, provision | | Android fit rule | `drivers/android/image-fit.ts` `fits` | With every image read | diff --git a/src/core/warm-pool/AGENTS.md b/src/core/warm-pool/AGENTS.md index 61bb75e4c..fa62600a9 100644 --- a/src/core/warm-pool/AGENTS.md +++ b/src/core/warm-pool/AGENTS.md @@ -131,5 +131,3 @@ pool's own `state.db` tables, kept across restarts and cleared by nuke. it waits; a burst larger than `count` pays the boot. - **A failing target retries forever.** 1, 2, 4 … minutes, at most 10 apart, no attempt limit; each try boots or creates a device. `retry.ts` is the one place to add a limit. -- **A hung `avdmanager` leaves one stuck process per 30 s.** The catalog check abandons a read - after 30 s, but the driver's call has no timeout of its own. diff --git a/src/core/warm-pool/catalog-check.ts b/src/core/warm-pool/catalog-check.ts index ba7946643..0fba0a3db 100644 --- a/src/core/warm-pool/catalog-check.ts +++ b/src/core/warm-pool/catalog-check.ts @@ -4,7 +4,7 @@ import type { DriverCatalog, PlatformCatalog } from "../driver-catalog.js"; import { stableError } from "../stable-error.js"; import type { LearnedKind } from "./learned.js"; -/** why: the longest the pool waits for a catalog read; `avdmanager` has no timeout of its own. */ +/** why: the longest the pool waits for a catalog read, whatever bound the driver's own read has. */ const CATALOG_READ_LIMIT_MS = 30_000; interface CatalogCheckOptions { diff --git a/src/drivers/android/AGENTS.md b/src/drivers/android/AGENTS.md index 21770c28c..fd342c41a 100644 --- a/src/drivers/android/AGENTS.md +++ b/src/drivers/android/AGENTS.md @@ -18,7 +18,7 @@ Parent: [drivers](../AGENTS.md). Flows: [device selection](../../../docs/interna | `adb-host-protocol.ts` | adb host-protocol framing (`adbHostRequest`, `OKAY`/`FAIL`), for both callers | | `default-adb-server.ts` | `DefaultAdbServerGate`: protocol check of the server on 5037 | | `physical-handler.ts` | `AndroidPhysicalHandler`: enrol, presence, reclaim, passthrough for phones | -| `device-profile-source.ts` | `DeviceProfileRegistry`; SDK and devices.xml profile sources | +| `device-profile-source.ts` | `DeviceProfileRegistry`; SDK and devices.xml profile sources; `AvdmanagerDeviceList`, the kept `list device` answer | | `profiles/index.ts` | `LibraryDeviceProfileSource`: Simlock's 16 profiles | | `image-fit.ts` | `fits`, `misfitReason`: which system image a profile takes | | `sdk-paths.ts` | `locateSdk`: SDK root and tool paths, shared with `prerequisites.ts` | @@ -80,8 +80,7 @@ Reclaim — `reclaim`: Ownership gate: before any `emu kill` or snapshot load, `adb emu avd path` (5 s timeout, asked every time, never cached) must name this device's own AVD directory; unreachable, timed out or another path → nothing is sent (a snapshot reclaim then shuts down and wipes). `shutdown`: gate, then `adb emu kill`, wait, SIGKILL. `destroy`: kills the emulator this process started, or after a restart each attached -emulator whose bounded `emu avd path` names this AVD (any serial that cannot answer → refuse), then `avdmanager delete avd`, frees the port. -`listManaged`: `/*.avd` + `adb devices` + `ro.boot.qemu.avd_name` per serial; only root members count. +emulator whose bounded `emu avd path` names this AVD (any serial that cannot answer → refuse), then `avdmanager delete avd`, frees the port. `listManaged`: `/*.avd` + `adb devices` + `ro.boot.qemu.avd_name` per serial; only root members count. Profiles — library (`profiles/`), SDK (`avdmanager list device`), devices.xml (`$ANDROID_USER_HOME/devices.xml`, else `.android/devices.xml` under `ANDROID_PREFS_ROOT`, `ANDROID_SDK_HOME` @@ -115,8 +114,8 @@ No slim: `resolveSpec` ignores `mode` and returns a full spec. `fresh` is core's Screen — `screenCapture` and `input`, only when `create` got `scrcpyServerPath` and `tcpStreamConnector`: [screen](screen/AGENTS.md), [input](input/AGENTS.md). -Plain facts: `avdmanager list device` runs on every `listCatalog`, resolve of a model the library lacks, -and library provision (seed); nothing is cached. The sdkmanager catalog is never read. Existing devices are not re-checked for fit. +Plain facts: `listCatalog`, a resolve of a model the library lacks and a library provision (seed) share one `AvdmanagerDeviceList`: `avdmanager list device` runs again only when the size or modified time of a file it reads profiles from changed, or one appeared or went: the tools package's `lib/sdklib/sdklib.core.jar` (legacy `tools/lib/sdklib*.jar`) and `source.properties`, the user's devices.xml, `devices.xml` in each `system-images/*/*/*` and `add-ons/*` directory (a new image is a new path), and `devices.xml` and `source.properties` in each `extras/*/*` directory (avdmanager reads an extra whose `source.properties` says `Extra.Path=DeviceProfiles`). +Otherwise the last good answer is served; a failed run is not kept; concurrent callers share one run. The sdkmanager catalog is never read. Existing devices are not re-checked for fit. ## State and timers @@ -130,9 +129,9 @@ and library provision (seed); nothing is cached. The sdkmanager catalog is never | `adb devices` in `listManaged` | 30 s | none | | AVD path query (listing / boot) | 5 s | none | | Physical read / uninstall | 30 s / 60 s | none | +| `avdmanager list device` | 30 s | none | -Writes: `/.avd/` (config, boot properties, snapshots, baseline marker); `$SIMLOCK_HOME/adb-server.json` (`pid`, `port`, `startedAt`). -Reads only: the user's AVD home, devices.xml, the SDK. +Writes: `/.avd/` (config, boot properties, snapshots, baseline marker); `$SIMLOCK_HOME/adb-server.json` (`pid`, `port`, `startedAt`). Reads only: the user's AVD home, devices.xml, the SDK. ## Rules @@ -145,6 +144,5 @@ Reads only: the user's AVD home, devices.xml, the SDK. - **Simlock's adb server is stopped by pid only.** `ADB_REJECT_KILL_SERVER=1` refuses its `kill-server`. No record → `occupied`: find it with `lsof` (Windows: `Get-NetTCPConnection -LocalPort `; the message names `lsof` only), or move `drivers.android.adbServerPort` (one per instance). -- **A physical command can restart a 5037 server of another protocol (ADR 0022 §5).** One started - between the gate and the command is restarted by adb's client. Run every adb on the host from one platform-tools. +- **A physical command can restart a 5037 server of another protocol (ADR 0022 §5).** One started between the gate and the command is restarted by adb's client. Run every adb on the host from one platform-tools. - **Port checks are partial.** A port handed out but not yet booted reads free to another instance. diff --git a/src/drivers/android/device-profile-source.test.ts b/src/drivers/android/device-profile-source.test.ts index 0d60b9e3b..98a8b9286 100644 --- a/src/drivers/android/device-profile-source.test.ts +++ b/src/drivers/android/device-profile-source.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest"; import type { DeviceClass } from "../../core/index.js"; import { MemoryFilesystem, ScriptedProcessRunner } from "../../ports/index.js"; import { + AvdmanagerDeviceList, BuiltinDeviceProfileSource, DeviceProfileRegistry, parseAvdmanagerDeviceProfiles, @@ -20,7 +21,7 @@ const noFit = { apiRange: undefined, imageKind: undefined, playStore: true, tabl describe("BuiltinDeviceProfileSource", () => { it("lists each profile answering to its name and its avdmanager id", async () => { const runner = new ScriptedProcessRunner([processResult(pixelDevices)]); - const source = new BuiltinDeviceProfileSource(avdmanager, runner); + const source = sdkSource(runner); await expect(source.profiles()).resolves.toEqual([ { @@ -41,7 +42,7 @@ describe("BuiltinDeviceProfileSource", () => { `id: 1 or "glasses"\n Name: Glasses\n OEM : Google\n Tag : ai-glasses\n`, ), ]); - const source = new BuiltinDeviceProfileSource(avdmanager, runner); + const source = sdkSource(runner); const profiles = await source.profiles(); @@ -59,7 +60,7 @@ describe("BuiltinDeviceProfileSource", () => { `id: 69 or "2.7in QVGA"\n Name: 2.7" QVGA\n OEM : Generic\n`, ), ]); - const source = new BuiltinDeviceProfileSource(avdmanager, runner); + const source = sdkSource(runner); // SDK profiles first, so the User one moves after `2.7" QVGA`. const profiles = await source.profiles(); @@ -76,7 +77,7 @@ describe("BuiltinDeviceProfileSource", () => { const runner = new ScriptedProcessRunner([ processResult(`Available devices:\nid: 0 or "TV_1080p"\n Name: tv_1080p\n`), ]); - const source = new BuiltinDeviceProfileSource(avdmanager, runner); + const source = sdkSource(runner); await expect(source.profiles()).resolves.toEqual([ { @@ -460,7 +461,7 @@ describe("parseDevicesXml image-fit fields", () => { describe("DeviceProfileRegistry", () => { it("resolves the first source's profile when two sources both name the same model", async () => { const runner = new ScriptedProcessRunner([processResult(pixelDevices)]); - const builtin = new BuiltinDeviceProfileSource(avdmanager, runner); + const builtin = sdkSource(runner); const filesystem = await filesystemWithDevicesXml( devicesXml().replace("My Custom Phone", "Pixel 8"), ); @@ -479,7 +480,7 @@ describe("DeviceProfileRegistry", () => { it("falls through to a later source when the first has no match", async () => { const runner = new ScriptedProcessRunner([processResult(pixelDevices)]); - const builtin = new BuiltinDeviceProfileSource(avdmanager, runner); + const builtin = sdkSource(runner); const filesystem = await filesystemWithDevicesXml(devicesXml()); const user = new UserDeviceProfileSource(devicesXmlPath, filesystem); const registry = new DeviceProfileRegistry([builtin, user]); @@ -508,10 +509,7 @@ describe("DeviceProfileRegistry", () => { await filesystemWithDevicesXml("not even close to xml {{{"), (diagnostic) => diagnostics.push(diagnostic), ); - const registry = new DeviceProfileRegistry([ - new BuiltinDeviceProfileSource(avdmanager, runner), - user, - ]); + const registry = new DeviceProfileRegistry([sdkSource(runner), user]); await expect(registry.resolve("pixel_8")).resolves.toMatchObject({ name: "Pixel 8" }); // A read of the malformed devices.xml would have reported it. @@ -524,9 +522,7 @@ describe("DeviceProfileRegistry", () => { processResult(pixelDevices), processResult(pixelDevices), ]); - const registry = new DeviceProfileRegistry([ - new BuiltinDeviceProfileSource(avdmanager, runner), - ]); + const registry = new DeviceProfileRegistry([sdkSource(runner)]); for (const model of ["pixel 8", "PIXEL_8", "Pixel_8"]) { await expect(registry.resolve(model)).resolves.toMatchObject({ name: "Pixel 8" }); @@ -535,7 +531,7 @@ describe("DeviceProfileRegistry", () => { it("rejects an unresolvable model with UnknownModelError", async () => { const runner = new ScriptedProcessRunner([processResult(pixelDevices)]); - const builtin = new BuiltinDeviceProfileSource(avdmanager, runner); + const builtin = sdkSource(runner); const registry = new DeviceProfileRegistry([builtin]); await expect(registry.resolve("Nope")).rejects.toMatchObject({ name: "UnknownModelError" }); @@ -543,7 +539,7 @@ describe("DeviceProfileRegistry", () => { it("lists a model's other names, only for models that have one", async () => { const runner = new ScriptedProcessRunner([processResult(pixelDevices)]); - const builtin = new BuiltinDeviceProfileSource(avdmanager, runner); + const builtin = sdkSource(runner); const user = new UserDeviceProfileSource( devicesXmlPath, await filesystemWithDevicesXml(devicesXml()), @@ -567,9 +563,7 @@ describe("DeviceProfileRegistry", () => { `id: 1 or "PIXEL_8"\n Name: Pixel 8 Copy\n`, ), ]); - const registry = new DeviceProfileRegistry([ - new BuiltinDeviceProfileSource(avdmanager, runner), - ]); + const registry = new DeviceProfileRegistry([sdkSource(runner)]); await expect(registry.catalog()).resolves.toEqual({ customModels: [], @@ -586,10 +580,7 @@ describe("DeviceProfileRegistry", () => { `${pixelDevices}---------\n` + `id: 1 or "My Custom Phone"\n Name: My Custom Phone\n OEM : User\n`; const registry = new DeviceProfileRegistry([ - new BuiltinDeviceProfileSource( - avdmanager, - new ScriptedProcessRunner([processResult(withUserProfile)]), - ), + sdkSource(new ScriptedProcessRunner([processResult(withUserProfile)])), new UserDeviceProfileSource(devicesXmlPath, await filesystemWithDevicesXml(devicesXml())), ]); @@ -610,10 +601,7 @@ describe("DeviceProfileRegistry", () => { ]) { const output = `Available devices:\n${first}---------\n${second}`; const registry = new DeviceProfileRegistry([ - new BuiltinDeviceProfileSource( - avdmanager, - new ScriptedProcessRunner([processResult(output), processResult(output)]), - ), + sdkSource(new ScriptedProcessRunner([processResult(output)])), ]); await expect(registry.catalog()).resolves.toMatchObject({ @@ -629,10 +617,7 @@ describe("DeviceProfileRegistry", () => { it("lists a name in both sources once, and not in customModels", async () => { const registry = new DeviceProfileRegistry([ - new BuiltinDeviceProfileSource( - avdmanager, - new ScriptedProcessRunner([processResult(pixelDevices)]), - ), + sdkSource(new ScriptedProcessRunner([processResult(pixelDevices)])), new UserDeviceProfileSource( devicesXmlPath, await filesystemWithDevicesXml(devicesXml().replace("My Custom Phone", "PIXEL 8")), @@ -655,10 +640,7 @@ describe("DeviceProfileRegistry", () => { for (const filesystem of [unreadable, malformed]) { const diagnostics: DeviceProfileSourceDiagnostic[] = []; const registry = new DeviceProfileRegistry([ - new BuiltinDeviceProfileSource( - avdmanager, - new ScriptedProcessRunner([processResult(pixelDevices)]), - ), + sdkSource(new ScriptedProcessRunner([processResult(pixelDevices)])), new UserDeviceProfileSource(devicesXmlPath, filesystem, (diagnostic) => diagnostics.push(diagnostic), ), @@ -686,10 +668,7 @@ describe("DeviceProfileRegistry", () => { filesystem.exists = () => Promise.reject(Object.assign(new Error(failure.message), failure)); const diagnostics: DeviceProfileSourceDiagnostic[] = []; const registry = new DeviceProfileRegistry([ - new BuiltinDeviceProfileSource( - avdmanager, - new ScriptedProcessRunner([processResult(pixelDevices)]), - ), + sdkSource(new ScriptedProcessRunner([processResult(pixelDevices)])), new UserDeviceProfileSource(devicesXmlPath, filesystem, (diagnostic) => diagnostics.push(diagnostic), ), @@ -720,10 +699,7 @@ describe("DeviceProfileRegistry", () => { `${pixelDevices}---------\n` + `id: 68 or "iPhone 13 mini"\n Name: iPhone 13 mini\n OEM : User\n`; const registry = new DeviceProfileRegistry([ - new BuiltinDeviceProfileSource( - avdmanager, - new ScriptedProcessRunner(Array.from({ length: 3 }, () => processResult(withUserProfile))), - ), + sdkSource(new ScriptedProcessRunner([processResult(withUserProfile)])), new UserDeviceProfileSource(devicesXmlPath, await filesystemWithDevicesXml(twoDevices)), ]); @@ -780,6 +756,41 @@ function processResult(stdout: string) { }; } +/** why: an SDK with none of the files `avdmanager` reads profiles from, so each source reads once. */ +function sdkSource(processRunner: ScriptedProcessRunner): BuiltinDeviceProfileSource { + return new BuiltinDeviceProfileSource( + new AvdmanagerDeviceList({ + avdmanager, + devicesXmlPath, + filesystem: new MemoryFilesystem(), + processRunner, + sdkRoot: "/android-sdk", + }), + ); +} + +describe("AvdmanagerDeviceList", () => { + it.each([ + ["is stopped at its 30 s limit", null, "stopped before it finished"], + ["exits non-zero", 3, "exit code 3"], + ] as const)( + "names why `avdmanager list device` failed when it %s and prints nothing", + async (_case, code, reason) => { + const runner = new ScriptedProcessRunner([ + { + match: { args: ["list", "device"], command: avdmanager }, + result: { code, stderr: "", stdout: "" }, + }, + ]); + + await expect(sdkSource(runner).profiles()).rejects.toMatchObject({ + message: `${avdmanager} list device failed: ${reason}`, + name: "DriverCrashError", + }); + }, + ); +}); + describe("device classes", () => { const entry = (id: string, name: string, tag?: string) => `id: 1 or "${id}"\n Name: ${name}\n OEM : Google\n` + @@ -788,10 +799,7 @@ describe("device classes", () => { async function modelClasses(output: string, devicesXmlText?: string) { const sources = [ - new BuiltinDeviceProfileSource( - avdmanager, - new ScriptedProcessRunner([processResult(`Available devices:\n${output}`)]), - ), + sdkSource(new ScriptedProcessRunner([processResult(`Available devices:\n${output}`)])), ...(devicesXmlText === undefined ? [] : [ @@ -845,15 +853,10 @@ describe("device classes", () => { const sdkOutput = `Available devices:\n${sdkTelevision}---------\n${sdk720}---------\n${sdkWear}---------\n` + `id: 43 or "pixel_8"\n Name: Pixel 8\n OEM : Google\n---------\n`; - // why: `avdmanager list device` is read once for the catalog and once more for each resolve - // of a name the library lacks (`Television (720p)`, `tv_720p`, `My Custom Phone`, and the - // `tv_720p` resolve below). - const runner = new ScriptedProcessRunner( - Array.from({ length: 5 }, () => processResult(sdkOutput)), - ); + const runner = new ScriptedProcessRunner([processResult(sdkOutput)]); const registry = new DeviceProfileRegistry([ new LibraryDeviceProfileSource(), - new BuiltinDeviceProfileSource(avdmanager, runner), + sdkSource(runner), new UserDeviceProfileSource( devicesXmlPath, await filesystemWithDevicesXml(collidingDevicesXml), @@ -896,10 +899,7 @@ describe("device classes", () => { it("lists no class for a profile whose tag is outside the table, and keeps the model", async () => { const output = entry("odd", "Odd Device", "android-toaster") + entry("pixel_8", "Pixel 8"); const registry = new DeviceProfileRegistry([ - new BuiltinDeviceProfileSource( - avdmanager, - new ScriptedProcessRunner([processResult(`Available devices:\n${output}`)]), - ), + sdkSource(new ScriptedProcessRunner([processResult(`Available devices:\n${output}`)])), ]); const catalog = await registry.catalog(); diff --git a/src/drivers/android/device-profile-source.ts b/src/drivers/android/device-profile-source.ts index 0c63a5ee0..c02d59c2d 100644 --- a/src/drivers/android/device-profile-source.ts +++ b/src/drivers/android/device-profile-source.ts @@ -1,3 +1,5 @@ +import { dirname } from "node:path"; + import { DriverCrashError, UnknownModelError, type DeviceClass } from "../../core/index.js"; import type { Filesystem, ProcessRunner } from "../../ports/index.js"; @@ -243,25 +245,149 @@ export async function hiddenUserProfiles( return hidden; } -/** Today's behavior, refactored behind `DeviceProfileSource`: resolves against `avdmanager list device`. */ -export class BuiltinDeviceProfileSource implements DeviceProfileSource { - readonly #avdmanager: string; - readonly #processRunner: ProcessRunner; - readonly #env: (() => NodeJS.ProcessEnv) | undefined; +/** + * why: as long as the warm pool waits for a catalog read, so a hung `avdmanager` is stopped when + * the pool stops waiting for it rather than left running. + */ +const AVDMANAGER_LIST_TIMEOUT_MS = 30_000; +export interface AvdmanagerDeviceListOptions { + readonly avdmanager: string; + readonly devicesXmlPath: string; /** - * `env` is a thunk, not a value: it is the driver's own scoped environment (ADR 0001, - * decision 4), and the driver builds it from state it only settles once the AVD root is - * proven. Reading it per call means this source can never be handed a snapshot that was - * taken before containment was established. - * - * Omitting it leaves the child's environment inherited rather than replaced -- an empty - * override is not "no override", it is a child spawned with no `PATH` at all. + * why: a thunk, not a value: it is the driver's own scoped environment (ADR 0001, decision + * 4), built from state the driver only settles once the AVD root is proven, so a run can + * never get a snapshot taken before that. Omitted, the child inherits the environment: an + * empty override would be a child with no `PATH` at all. */ - constructor(avdmanager: string, processRunner: ProcessRunner, env?: () => NodeJS.ProcessEnv) { - this.#avdmanager = avdmanager; - this.#processRunner = processRunner; - this.#env = env; + readonly env?: (() => NodeJS.ProcessEnv) | undefined; + readonly filesystem: Filesystem; + readonly processRunner: ProcessRunner; + readonly sdkRoot: string; +} + +/** + * why: `avdmanager list device` starts two JVMs (about 1 s, and 3 s of CPU) and the warm pool + * reads the catalog every 30 s (ADR 0015's Consequences left a cache for when the cost shows). + * So its answer is kept and it runs again only when a file it reads device definitions from + * changed: its tools package's sdklib jar and `source.properties`, the user's devices.xml, the + * devices.xml of each installed system image and add-on, and the devices.xml and + * `source.properties` of each `extras//` directory, each keyed by its size and + * modified time or its absence, the image, add-on and extra directories by their paths. While + * that key is unchanged the kept answer equals a fresh read. A failed run is not kept, and + * callers that ask while a run for the same key is under way share it. + */ +export class AvdmanagerDeviceList { + readonly #options: AvdmanagerDeviceListOptions; + #kept: + | { readonly key: string; readonly profiles: readonly AvdmanagerDeviceProfile[] } + | undefined; + #running: + | { readonly key: string; readonly read: Promise } + | undefined; + + constructor(options: AvdmanagerDeviceListOptions) { + this.#options = options; + } + + /** why: in the order `avdmanager` prints them: a library provision seeds from the first. */ + async read(): Promise { + const key = await this.#inputsKey(); + if (this.#kept?.key === key) return this.#kept.profiles; + if (this.#running?.key === key) return await this.#running.read; + const running = { key, read: this.#run() }; + this.#running = running; + try { + const profiles = await running.read; + this.#kept = { key, profiles }; + return profiles; + } finally { + if (this.#running === running) this.#running = undefined; + } + } + + async #run(): Promise { + const { avdmanager, env, processRunner } = this.#options; + const result = await processRunner.run(avdmanager, ["list", "device"], { + ...(env === undefined ? {} : { env: env() }), + timeoutMs: AVDMANAGER_LIST_TIMEOUT_MS, + }); + if (result.code !== 0) { + const reason = + result.stderr || + result.stdout || + (result.code === null ? "stopped before it finished" : `exit code ${result.code}`); + throw new DriverCrashError(`${avdmanager} list device failed: ${reason}`); + } + return parseAvdmanagerDeviceProfiles(result.stdout); + } + + /** why: the key is read before the run, so a file changed during it makes the next read run again. */ + async #inputsKey(): Promise { + const { avdmanager, devicesXmlPath, sdkRoot } = this.#options; + // why: `/bin/avdmanager`, where the package is `cmdline-tools/` or the + // legacy `tools`, whose sdklib jars sit straight in `lib/`. + const toolsPackage = dirname(dirname(avdmanager)); + const legacyJars = (await this.#children(`${toolsPackage}/lib`)).filter((name) => + /^sdklib.*\.jar$/.test(name), + ); + const images = await this.#descendants(`${sdkRoot}/system-images`, 3); + const addOns = await this.#descendants(`${sdkRoot}/add-ons`, 1); + // why: sdklib's DeviceManager reads `extras///devices.xml` when the item's + // source.properties has the line `Extra.Path=DeviceProfiles`, so both files are keyed. + const extras = await this.#descendants(`${sdkRoot}/extras`, 2); + const paths = [ + `${toolsPackage}/source.properties`, + `${toolsPackage}/lib/sdklib/sdklib.core.jar`, + ...legacyJars.map((name) => `${toolsPackage}/lib/${name}`), + devicesXmlPath, + ...[...images, ...addOns].map((directory) => `${directory}/devices.xml`), + ...extras.flatMap((directory) => [ + `${directory}/source.properties`, + `${directory}/devices.xml`, + ]), + ]; + const stamps = await Promise.all( + paths.map(async (path) => `${path}=${await this.#stamp(path)}`), + ); + return stamps.join("\n"); + } + + async #stamp(path: string): Promise { + try { + const stat = await this.#options.filesystem.stat(path); + return `${stat.size}@${stat.modifiedAtMs}`; + } catch { + return "absent"; + } + } + + async #descendants(root: string, depth: number): Promise { + let level = [root]; + for (let step = 0; step < depth; step += 1) { + const next = await Promise.all( + level.map(async (path) => (await this.#children(path)).map((name) => `${path}/${name}`)), + ); + level = next.flat(); + } + return level; + } + + /** why: an absent or unreadable directory, or a file, has no entries to key on. */ + async #children(path: string): Promise { + try { + return (await this.#options.filesystem.readdir(path)).filter((name) => !name.startsWith(".")); + } catch { + return []; + } + } +} + +export class BuiltinDeviceProfileSource implements DeviceProfileSource { + readonly #devices: AvdmanagerDeviceList; + + constructor(devices: AvdmanagerDeviceList) { + this.#devices = devices; } /** @@ -270,7 +396,7 @@ export class BuiltinDeviceProfileSource implements DeviceProfileSource { * devices.xml one whatever order `avdmanager` prints them in. */ async profiles(): Promise { - const profiles = (await this.#avdmanagerProfiles()).map((profile): DeviceProfile => ({ + const profiles = (await this.#devices.read()).map((profile): DeviceProfile => ({ avdmanagerId: profile.id, custom: profile.oem === "User", deviceClass: classOfTag(profile.tag), @@ -287,23 +413,9 @@ export class BuiltinDeviceProfileSource implements DeviceProfileSource { ...profiles.filter((profile) => isCustom(profile)), ]; } - - async #avdmanagerProfiles(): Promise { - const result = await this.#processRunner.run( - this.#avdmanager, - ["list", "device"], - this.#env === undefined ? {} : { env: this.#env() }, - ); - if (result.code !== 0) { - throw new DriverCrashError( - `${this.#avdmanager} list device failed: ${result.stderr || result.stdout}`, - ); - } - return parseAvdmanagerDeviceProfiles(result.stdout); - } } -interface AvdmanagerDeviceProfile { +export interface AvdmanagerDeviceProfile { readonly id: string; readonly name: string; /** The entry's `OEM :` line, or undefined without one. `User` marks a devices.xml profile. */ diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index 363c29e53..1e03e5ab0 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -1603,6 +1603,270 @@ describe("AndroidDriver", () => { expect(runner.calls.filter((call) => call.command === binaries.avdmanager)).toHaveLength(1); }); + describe("avdmanager list device reads", () => { + const toolsPackage = `${sdk}/cmdline-tools/latest`; + const sdklibJar = `${toolsPackage}/lib/sdklib/sdklib.core.jar`; + const userDevicesXml = `${home}/.android/devices.xml`; + const imageDevicesXml = `${sdk}/system-images/android-34/google_apis/arm64-v8a/devices.xml`; + const addOnDevicesXml = `${sdk}/add-ons/addon-acme/devices.xml`; + const extraDirectory = `${sdk}/extras/acme/device_profiles`; + const extraDevicesXml = `${extraDirectory}/devices.xml`; + const rereadDevices = `Available devices:\nid: 0 or "reread_phone"\n Name: Reread Phone\n OEM : Acme\n`; + + /** why: sdklib reads `extras///devices.xml` only when the item's source.properties says `Extra.Path=DeviceProfiles`. */ + async function profilesExtra(filesystem: MemoryFilesystem, devicesXml?: string): Promise { + await filesystem.mkdirp(extraDirectory); + await filesystem.writeFileAtomic( + `${extraDirectory}/source.properties`, + "Pkg.Revision=1\nExtra.Path=DeviceProfiles\n", + ); + if (devicesXml !== undefined) await filesystem.writeFileAtomic(extraDevicesXml, devicesXml); + } + + /** why: every input the read is keyed on is present, so a change to any of them is a change, not a creation. */ + async function readsHarness( + options: { + readonly avdmanager?: string; + readonly before?: (filesystem: MemoryFilesystem) => Promise; + readonly results?: readonly ScriptedProcessExpectation[]; + } = {}, + ) { + const filesystem = await androidFilesystem(); + await filesystem.mkdirp(`${toolsPackage}/lib/sdklib`); + await filesystem.writeFileAtomic(sdklibJar, "jar"); + await filesystem.writeFileAtomic(`${toolsPackage}/source.properties`, "Pkg.Revision=20.0\n"); + await filesystem.writeFileAtomic(imageDevicesXml, ""); + await filesystem.mkdirp(`${sdk}/add-ons/addon-acme`); + await filesystem.writeFileAtomic(addOnDevicesXml, ""); + await options.before?.(filesystem); + const avdmanager = options.avdmanager ?? binaries.avdmanager; + const runner = new ScriptedProcessRunner( + options.results ?? [ + processResult(avdmanager, ["list", "device"], pixelDevices), + processResult(avdmanager, ["list", "device"], rereadDevices), + ], + ); + const driver = await createDriver(filesystem, runner); + const listRuns = () => + runner.calls.filter( + (call) => call.command === avdmanager && call.args.join(" ") === "list device", + ); + return { driver, filesystem, listRuns, runner }; + } + + it("runs `avdmanager list device` once, with a 30 s limit, for two catalogs read while none of its inputs changed", async () => { + const { driver, listRuns } = await readsHarness(); + + const first = await driver.listCatalog(); + const second = await driver.listCatalog(); + + expect(first.models).toContain("Pixel 5"); + expect(second.models).toContain("Pixel 5"); + expect(second.models).not.toContain("Reread Phone"); + expect(listRuns()).toHaveLength(1); + expect(listRuns()[0]?.options.timeoutMs).toBe(30_000); + }); + + it("runs `avdmanager list device` again after any file it reads device profiles from changed", async () => { + const legacyTools = `${sdk}/tools`; + const legacyJar = `${legacyTools}/lib/sdklib-26.0.0-dev.jar`; + const cases: readonly { + readonly change: string; + readonly avdmanager?: string; + readonly before?: (filesystem: MemoryFilesystem) => Promise; + readonly act: (filesystem: MemoryFilesystem) => Promise; + }[] = [ + { + act: async (filesystem) => + filesystem.defineAttributes(sdklibJar, { modifiedAtMs: 5_000 }), + change: "the sdklib jar's modified time", + }, + { + act: async (filesystem) => filesystem.writeFileAtomic(sdklibJar, "jar, updated"), + change: "the sdklib jar's size", + }, + { + act: async (filesystem) => + filesystem.writeFileAtomic( + `${toolsPackage}/source.properties`, + "Pkg.Revision=21.0.1\n", + ), + change: "the command-line tools' source.properties", + }, + { + act: async (filesystem) => writeDevicesXml(filesystem, customDeviceXml("Made", 2048)), + change: "devices.xml created", + }, + { + act: async (filesystem) => + writeDevicesXml( + filesystem, + customDeviceXml("Kept", 2048) + customDeviceXml("New", 2048), + ), + before: async (filesystem) => writeDevicesXml(filesystem, customDeviceXml("Kept", 2048)), + change: "devices.xml edited", + }, + { + act: async (filesystem) => filesystem.rm(userDevicesXml), + before: async (filesystem) => writeDevicesXml(filesystem, customDeviceXml("Kept", 2048)), + change: "devices.xml deleted", + }, + { + act: async (filesystem) => + filesystem.mkdirp(`${sdk}/system-images/android-35/google_apis/arm64-v8a`), + change: "a system image installed", + }, + { + act: async (filesystem) => { + await filesystem.mkdirp(`${sdk}/system-images/android-36/android-wear/arm64-v8a`); + await filesystem.writeFileAtomic( + `${sdk}/system-images/android-36/android-wear/arm64-v8a/devices.xml`, + "", + ); + }, + change: "a system image installed with its own devices.xml", + }, + { + act: async (filesystem) => + filesystem.writeFileAtomic(imageDevicesXml, ""), + change: "an installed system image's devices.xml", + }, + { + act: async (filesystem) => + filesystem.writeFileAtomic(addOnDevicesXml, ""), + change: "an add-on's devices.xml", + }, + { + act: async (filesystem) => filesystem.writeFileAtomic(extraDevicesXml, ""), + before: async (filesystem) => profilesExtra(filesystem), + change: "an extra's devices.xml created", + }, + { + act: async (filesystem) => + filesystem.writeFileAtomic(extraDevicesXml, ""), + before: async (filesystem) => profilesExtra(filesystem, ""), + change: "an extra's devices.xml edited", + }, + { + act: async (filesystem) => filesystem.rm(extraDevicesXml), + before: async (filesystem) => profilesExtra(filesystem, ""), + change: "an extra's devices.xml removed", + }, + { + act: async (filesystem) => + filesystem.writeFileAtomic( + `${extraDirectory}/source.properties`, + "Extra.Path=DeviceProfiles\n", + ), + before: async (filesystem) => { + await profilesExtra(filesystem, ""); + await filesystem.writeFileAtomic( + `${extraDirectory}/source.properties`, + "Extra.Path=usb_driver\n", + ); + }, + change: "an extra's source.properties made it a device-profiles extra", + }, + { + act: async (filesystem) => filesystem.writeFileAtomic(legacyJar, "legacy jar, updated"), + avdmanager: `${legacyTools}/bin/avdmanager`, + before: async (filesystem) => { + await filesystem.rm(toolsPackage); + await filesystem.mkdirp(`${legacyTools}/bin`); + await filesystem.writeFileAtomic(`${legacyTools}/bin/avdmanager`, "binary"); + await filesystem.writeFileAtomic(`${legacyTools}/bin/sdkmanager`, "binary"); + await filesystem.mkdirp(`${legacyTools}/lib`); + await filesystem.writeFileAtomic(legacyJar, "legacy jar"); + }, + change: "the legacy tools' sdklib jar", + }, + ]; + + const seen: Record = {}; + for (const row of cases) { + const { driver, filesystem, listRuns } = await readsHarness({ + ...(row.avdmanager === undefined ? {} : { avdmanager: row.avdmanager }), + ...(row.before === undefined ? {} : { before: row.before }), + }); + const first = await driver.listCatalog(); + await row.act(filesystem); + const second = await driver.listCatalog(); + seen[row.change] = [ + first.models.includes("Reread Phone"), + second.models.includes("Reread Phone"), + listRuns().length, + ]; + } + + expect(seen).toEqual(Object.fromEntries(cases.map((row) => [row.change, [false, true, 2]]))); + }); + + it("runs `avdmanager list device` again after a read that failed", async () => { + const { driver, listRuns } = await readsHarness({ + results: [ + { + match: { args: ["list", "device"], command: binaries.avdmanager }, + result: { code: 1, stderr: "Error: could not read device definitions", stdout: "" }, + }, + processResult(binaries.avdmanager, ["list", "device"], rereadDevices), + ], + }); + + await expect(driver.listCatalog()).rejects.toThrow("could not read device definitions"); + const catalog = await driver.listCatalog(); + + expect(catalog.models).toContain("Reread Phone"); + expect(listRuns()).toHaveLength(2); + }); + + it("runs one `avdmanager list device` for two catalogs read at once", async () => { + const scripted = new ScriptedProcessRunner([ + processResult(binaries.avdmanager, ["list", "device"], pixelDevices), + ]); + let release: () => void = () => undefined; + const held = new Promise((resolve) => { + release = resolve; + }); + // why: the run stays in flight until both catalogs have asked, so the second cannot be served from a finished read. + const runner: ProcessRunner = { + run: async (command, args, options) => { + await held; + return scripted.run(command, args, options); + }, + spawn: (command, args, options) => scripted.spawn(command, args, options), + spawnStreaming: (command, args, options) => scripted.spawnStreaming(command, args, options), + }; + const driver = await createDriver(await androidFilesystem(), runner); + + const catalogs = Promise.allSettled([driver.listCatalog(), driver.listCatalog()]); + // why: the filesystem fake settles in microtasks, so one macrotask lets both catalogs + // reach the read before the first run ends. + await new Promise((resolve) => setImmediate(resolve)); + release(); + + expect( + (await catalogs).map( + (catalog) => catalog.status === "fulfilled" && catalog.value.models.includes("Pixel 5"), + ), + ).toEqual([true, true]); + expect(scripted.calls.filter((call) => call.args.join(" ") === "list device")).toHaveLength( + 1, + ); + }); + + it("seeds a library provision from the `avdmanager list device` read the catalog made", async () => { + const harness = await libraryHarness({ listing: pixelDevices }); + + await harness.driver.listCatalog(); + await harness.provision("Pixel 9"); + + expect(harness.seedDeviceId()).toBe("pixel_5"); + expect( + harness.runner.calls.filter((call) => call.args.join(" ") === "list device"), + ).toHaveLength(1); + }); + }); + it("lists every installed system image with its API level, tag, and ABI, a foreign-ABI image included", async () => { const filesystem = await androidFilesystem({ images: [ @@ -2218,7 +2482,6 @@ describe("AndroidDriver", () => { // hardware properties to config.ini right after create relies on that directory existing. await filesystem.mkdirp(`${avdDirectory}/simlock_one.avd`); const runner = new ScriptedProcessRunner([ - processResult(binaries.avdmanager, ["list", "device"], pixelDevices), processResult(binaries.avdmanager, ["list", "device"], pixelDevices), processResult(binaries.avdmanager, [ "create", @@ -2264,7 +2527,6 @@ describe("AndroidDriver", () => { await writeDevicesXml(filesystem, customDeviceXml("Custom A", ramMiB)); await filesystem.mkdirp(`${avdDirectory}/simlock_one.avd`); const runner = new ScriptedProcessRunner([ - processResult(binaries.avdmanager, ["list", "device"], pixelDevices), processResult(binaries.avdmanager, ["list", "device"], pixelDevices), processResult(binaries.avdmanager, [ "create", @@ -2325,9 +2587,7 @@ describe("AndroidDriver", () => { }); await driver.provision(spec); - // why: Only one `avdmanager list device` call happened (asserted implicitly by the runner - // never receiving the unscripted second call a `properties`-profile seed lookup would - // require), and no properties were merged into config.ini -- it was never even written. + // why: no properties were merged into config.ini -- it was never even written. await expect(filesystem.exists(`${avdDirectory}/simlock_one.avd/config.ini`)).resolves.toBe( false, ); @@ -2479,7 +2739,6 @@ describe("AndroidDriver", () => { const userHarness = await libraryHarness({ devicesXml: customDeviceXml("Custom A", 4096), listing: pixelDevices, - secondList: true, }); const userSpec = await userHarness.resolve("Custom A"); await userHarness.driver.provision(userSpec); @@ -3403,8 +3662,9 @@ describe("AndroidDriver.create", () => { expect(driver.leaseEnvironment(VIRTUAL_DEVICE)).toEqual({ ANDROID_ADB_SERVER_PORT: "5199" }); await driver.resolveSpec({ model: "Pixel 5", platform: "android" }); - expect(runner.calls[0]?.options).toEqual({ - env: { ...scopedEnv, ANDROID_ADB_SERVER_PORT: "5199" }, + expect(runner.calls[0]?.options.env).toEqual({ + ...scopedEnv, + ANDROID_ADB_SERVER_PORT: "5199", }); }); @@ -6087,7 +6347,6 @@ async function libraryHarness( readonly imageTag?: string; readonly listing?: string; readonly profiles?: readonly LibraryDeviceProfile[]; - readonly secondList?: boolean; readonly seed?: string; readonly seedBootProp?: string; readonly sources?: readonly DeviceProfileSource[]; @@ -6120,9 +6379,6 @@ async function libraryHarness( const listing = options.listing ?? pixelDevices; const runner = new ScriptedProcessRunner([ processResult(binaries.avdmanager, ["list", "device"], listing), - ...(options.secondList === true - ? [processResult(binaries.avdmanager, ["list", "device"], listing)] - : []), processResult(binaries.avdmanager, [ "create", "avd", @@ -6970,7 +7226,6 @@ describe("AndroidDriver custom profile fit from devices.xml", () => { const harness = await libraryHarness({ devicesXml: xml, extraImages: [["35", "android-tv", "arm64-v8a"]], - secondList: true, }); await harness.provision("Keyed"); return [...(await harness.config()).keys()].sort(); diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index 66e782932..ec5580e0d 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -66,11 +66,11 @@ import { AdbServerSupervisor, AdbServerUnavailableError } from "./adb-server.js" import { isAndroidDriverData, type AndroidDriverData } from "./data.js"; import { AndroidPhysicalHandler, PHYSICAL_RECLAIM_ESTIMATE_MS } from "./physical-handler.js"; import { + AvdmanagerDeviceList, BuiltinDeviceProfileSource, hiddenUserProfiles, containsForbiddenCharacter, DeviceProfileRegistry, - parseAvdmanagerDeviceProfiles, UserDeviceProfileSource, type DeviceProfileSource, type DeviceProfileSourceDiagnostic, @@ -512,6 +512,7 @@ export class AndroidDriver implements Driver { readonly #adbServerPort: number; readonly #baseEnv: Readonly>; readonly #acceptAndroidLicenses: boolean; + readonly #avdmanagerDevices: AvdmanagerDeviceList; readonly #clock: Clock; readonly #deviceProfiles: DeviceProfileRegistry; readonly #profileSources: ReturnType | undefined; @@ -584,9 +585,18 @@ export class AndroidDriver implements Driver { this.#legacyAvdHome = options.env.ANDROID_AVD_HOME ?? join(options.homeDirectory, ".android", "avd"); this.#portAllocator = portAllocatorFor(options.processRunner, sdk.adb); + // why: scoped like every other call: an unscoped `avdmanager` would read the user's `~/.android`. + this.#avdmanagerDevices = new AvdmanagerDeviceList({ + avdmanager: sdk.avdmanager, + devicesXmlPath: userDevicesXmlPath(options), + env: () => this.#env(), + filesystem: options.filesystem, + processRunner: options.processRunner, + sdkRoot: sdk.root, + }); const defaults = options.deviceProfileSources === undefined - ? defaultDeviceProfileSources(options, sdk, this.#onDiagnostic, () => this.#env()) + ? defaultDeviceProfileSources(options, this.#avdmanagerDevices, this.#onDiagnostic) : undefined; this.#profileSources = defaults; this.#deviceProfiles = new DeviceProfileRegistry( @@ -1473,8 +1483,7 @@ export class AndroidDriver implements Driver { } async #defaultAvdmanagerDeviceId(): Promise { - const result = await this.#runOrThrow(this.#sdk.avdmanager, ["list", "device"]); - const [first] = parseAvdmanagerDeviceProfiles(result.stdout); + const [first] = await this.#avdmanagerDevices.read(); if (first === undefined) { throw new DriverCrashError( `${this.#sdk.avdmanager} list device reported no built-in device profiles`, @@ -2778,26 +2787,30 @@ function hasUnacceptedLicense(result: ProcessResult): boolean { * `ANDROID_PREFS_ROOT/.android`, else `ANDROID_SDK_HOME/.android`, else `~/.android`. Not * `ANDROID_AVD_HOME`, which only relocates created AVDs. */ +function userDevicesXmlPath(options: AndroidDriverOptions): string { + const { ANDROID_PREFS_ROOT, ANDROID_SDK_HOME, ANDROID_USER_HOME } = options.env; + return ANDROID_USER_HOME !== undefined + ? `${ANDROID_USER_HOME}/devices.xml` + : `${ANDROID_PREFS_ROOT ?? ANDROID_SDK_HOME ?? options.homeDirectory}/.android/devices.xml`; +} + function defaultDeviceProfileSources( options: AndroidDriverOptions, - sdk: AndroidSdkPaths, + avdmanagerDevices: AvdmanagerDeviceList, onDiagnostic: ((diagnostic: AndroidDriverDiagnostic) => void) | undefined, - env: () => NodeJS.ProcessEnv, ): { readonly library: DeviceProfileSource; readonly builtin: DeviceProfileSource; readonly user: DeviceProfileSource; } { - const { ANDROID_PREFS_ROOT, ANDROID_SDK_HOME, ANDROID_USER_HOME } = options.env; - const devicesXmlPath = - ANDROID_USER_HOME !== undefined - ? `${ANDROID_USER_HOME}/devices.xml` - : `${ANDROID_PREFS_ROOT ?? ANDROID_SDK_HOME ?? options.homeDirectory}/.android/devices.xml`; return { library: new LibraryDeviceProfileSource(), - // why: Scoped like every other call: an unscoped `avdmanager` would read the user's `~/.android`. - builtin: new BuiltinDeviceProfileSource(sdk.avdmanager, options.processRunner, env), - user: new UserDeviceProfileSource(devicesXmlPath, options.filesystem, onDiagnostic), + builtin: new BuiltinDeviceProfileSource(avdmanagerDevices), + user: new UserDeviceProfileSource( + userDevicesXmlPath(options), + options.filesystem, + onDiagnostic, + ), }; } diff --git a/src/ports/filesystem.ts b/src/ports/filesystem.ts index 1c76686f5..9b4151b90 100644 --- a/src/ports/filesystem.ts +++ b/src/ports/filesystem.ts @@ -587,7 +587,7 @@ export class MemoryFilesystem implements Filesystem { defineAttributes( path: string, - attributes: { readonly uid?: number; readonly mode?: number }, + attributes: { readonly uid?: number; readonly mode?: number; readonly modifiedAtMs?: number }, ): void { const entry = this.#rawEntryAt(path); @@ -598,6 +598,10 @@ export class MemoryFilesystem implements Filesystem { if (attributes.mode !== undefined) { entry.mode = attributes.mode & 0o777; } + + if (attributes.modifiedAtMs !== undefined) { + entry.modifiedAtMs = attributes.modifiedAtMs; + } } #failIfDefined(path: string): void {