diff --git a/docs/internal/flows/device-exec.md b/docs/internal/flows/device-exec.md index c2eb1bd92..416067de9 100644 --- a/docs/internal/flows/device-exec.md +++ b/docs/internal/flows/device-exec.md @@ -2,7 +2,7 @@ Modules: [daemon](../../../src/daemon/AGENTS.md), [gateway](../../../src/gateway/AGENTS.md). Contract: `src/contract/operations.ts` `deviceExec` — role `agent`, effect `write`. -Input (strict): `{ leaseId, tool, args, stdin?, requesterId? }`. Output: `{ exitCode }`. +Input (strict): `{ leaseId, tool, args, stdin?, stdinFile?, requesterId? }`. Output: `{ exitCode }`. Runs the command on the machine that owns the device and streams its output back. ## Callers @@ -36,9 +36,14 @@ Runs the command on the machine that owns the device and streams its output back another device (ADR 0047), see "Resolution per platform". 5. Env — `execBaseEnvironment(process.env)` (`src/daemon/exec-env.ts`, the allowlisted keys, read once at start) + the command's `env`, minus its `unsetEnv`. -6. Spawn — `ProcessRunner.spawnStreaming`, pipes only. `stdin` (at most 8 MiB - of characters, refused `BAD_REQUEST` by the contract before any dispatcher - forwards or spawns) is written once, then closed. +6. Spawn — `ProcessRunner.spawnStreaming`, pipes only, with the lease's folder + (`LeaseFiles.folderOf`) as `cwd`. `stdin` (at most 8 MiB of characters, refused + `BAD_REQUEST` by the contract before any dispatcher forwards or spawns) is written + once, then closed. `stdinFile` instead names a file of that folder, opened first + (`UNKNOWN_FILE` before anything starts) and piped as `inputStream`; both together + are `BAD_REQUEST`, checked by the worker's dispatcher. A read failure rejects the + handle's `inputFailed`: the command is stopped as a timeout stops it and the + stream ends with `STDIN_FILE_FAILED`. A gateway forwards `stdinFile` unchanged. 7. `started` push the moment the process exists, then one `output` push per chunk (`{ requestId, stream, chunk }`). The push write is awaited before the child is read again: a slow reader slows the command. Nothing is buffered; no size cap. diff --git a/e2e/device-exec.test.ts b/e2e/device-exec.test.ts index 54289de8b..61c49b591 100644 --- a/e2e/device-exec.test.ts +++ b/e2e/device-exec.test.ts @@ -1,4 +1,6 @@ +import { realpath } from "node:fs/promises"; import { createServer } from "node:net"; +import { dirname, join } from "node:path"; import { describe, expect, it } from "vitest"; import { waitFor, withDaemon, type TestEnv } from "./helpers/index.js"; @@ -181,6 +183,7 @@ describe("device.exec over HTTP", () => { // device root is prepended and the driver's environment reached the child's own process. expect(JSON.parse(chunksOf(frames, "stdout"))).toEqual({ argv: ["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/fake/ios", "list", "devices", "--fake-exec-stderr=a warning", "--fake-exec-exit=3"], + cwd: expect.any(String), platform: "ios", }); expect(chunksOf(frames, "stderr")).toBe("a warning"); @@ -200,6 +203,95 @@ describe("device.exec over HTTP", () => { await env.cli(["release", leaseId]); }); + it("runs exec with stdinFile and the command reads the file's bytes, then end of input", async () => { + const { baseUrl, env, exec, lease, token } = await fleet(); + const auth = await token("agent"); + const leaseId = await lease({ device: "iPhone 16", os: "18.4", platform: "ios" }, auth); + const upload = async (name: string, body: string): Promise => { + const uploaded = await fetch(`${baseUrl}/v1/leases/${leaseId}/files/${name}`, { + body, + headers: { ...auth, "content-type": "application/octet-stream" }, + method: "PUT", + }); + expect(uploaded.status).toBe(201); + }; + const nineMiB = "0123456789abcdef".repeat(9 * 65_536); + await upload("fixture.txt", "stored payload"); + await upload("big.bin", nineMiB); + await upload("empty.bin", ""); + + const reads = [ + { name: "fixture.txt", stdin: "stored payload" }, + { name: "big.bin", stdin: nineMiB }, + { name: "empty.bin", stdin: "" }, + { name: "FIXTURE.TXT", stdin: "stored payload" }, + ]; + for (const { name, stdin } of reads) { + const response = await exec( + leaseId, + { args: ["list", "--fake-exec-echo-stdin"], stdinFile: name, tool: "simctl" }, + auth, + ); + expect(response.status).toBe(200); + const frames = await readSse(response); + expect(frames.at(-1)).toEqual({ data: { exitCode: 0 }, event: "exit" }); + expect((JSON.parse(chunksOf(frames, "stdout")) as { stdin: string }).stdin === stdin).toBe( + true, + ); + } + const none = await exec( + leaseId, + { args: ["list"], stdin: null, stdinFile: null, tool: "simctl" }, + auth, + ); + expect(none.status).toBe(200); + expect((await readSse(none)).at(-1)).toEqual({ data: { exitCode: 0 }, event: "exit" }); + + const refusals = [ + { body: { stdinFile: ".hidden" }, code: "BAD_REQUEST", status: 400 }, + { body: { stdinFile: "missing.tar" }, code: "UNKNOWN_FILE", status: 404 }, + { body: { stdin: "x", stdinFile: "fixture.txt" }, code: "BAD_REQUEST", status: 400 }, + ]; + for (const { body, code, status } of refusals) { + const refused = await exec(leaseId, { args: ["list"], tool: "simctl", ...body }, auth); + expect(refused.status).toBe(status); + expect(await errorCodeOf(refused)).toBe(code); + } + + await env.cli(["release", leaseId]); + }); + + it("runs every exec with the lease's folder as its working folder", async () => { + const { baseUrl, env, exec, lease, token } = await fleet(); + const auth = await token("agent"); + const leaseId = await lease({ device: "iPhone 16", os: "18.4", platform: "ios" }, auth); + const report = async (args: string[]): Promise<{ cwd: string; fileSize?: number }> => { + const response = await exec(leaseId, { args, tool: "simctl" }, auth); + expect(response.status).toBe(200); + const frames = await readSse(response); + expect(frames.at(-1)).toEqual({ data: { exitCode: 0 }, event: "exit" }); + return JSON.parse(chunksOf(frames, "stdout")) as { cwd: string; fileSize?: number }; + }; + + // why: no file was uploaded yet, so this shows the folder is made for the command. + const first = await report(["list"]); + expect(dirname(await realpath(first.cwd))).toBe( + join(await realpath(env.dataDirectory), "lease-files"), + ); + + const uploaded = await fetch(`${baseUrl}/v1/leases/${leaseId}/files/fixture.bin`, { + body: "x".repeat(1234), + headers: { ...auth, "content-type": "application/octet-stream" }, + method: "PUT", + }); + expect(uploaded.status).toBe(201); + const second = await report(["list", "--fake-exec-read-file=fixture.bin"]); + expect(second.fileSize).toBe(1234); + expect(await realpath(second.cwd)).toBe(await realpath(first.cwd)); + + await env.cli(["release", leaseId]); + }); + it("refuses through the fake driver's own mirrored list, and never runs what it refuses", async () => { // The fake driver's refusal rules are its own mirror of the real Android/iOS drivers' // (see `e2e/fake-driver/fake-driver.ts`'s own comment on `passthrough`), kept deliberately diff --git a/e2e/fake-driver/fake-driver.ts b/e2e/fake-driver/fake-driver.ts index e8a706514..6e8636378 100644 --- a/e2e/fake-driver/fake-driver.ts +++ b/e2e/fake-driver/fake-driver.ts @@ -193,8 +193,13 @@ const PASSTHROUGH_PROGRAM = // running while the route has to decide what to answer. "const sleepMs = Number(flag('--fake-exec-sleep') ?? 0);" + "if (sleepMs > 0) setTimeout(() => {}, sleepMs);" + + // why: `device.exec` runs every command in the lease's folder: `cwd` shows where, and + // `--fake-exec-read-file=` shows that a relative name finds a file stored there. + "const readFile = flag('--fake-exec-read-file');" + "const report = (stdin) => process.stdout.write(JSON.stringify({" + "argv," + + "cwd: process.cwd()," + + "...(readFile === undefined ? {} : { fileSize: require('node:fs').readFileSync(readFile).length })," + "platform: process.env.SIMLOCK_FAKE_PASSTHROUGH_PLATFORM ?? null," + "...(stdin === undefined ? {} : { stdin })," + "}));" + diff --git a/e2e/gateway-smoke.test.ts b/e2e/gateway-smoke.test.ts index f5c2f1ba9..9ee558543 100644 --- a/e2e/gateway-smoke.test.ts +++ b/e2e/gateway-smoke.test.ts @@ -201,6 +201,8 @@ describe("gateway smoke", () => { "--fake-exec-exit=3", "--fake-exec-echo-stdin", ], + // why: `device.exec` runs in the lease's folder on the worker, which lives under lease-files. + cwd: expect.stringContaining("lease-files"), platform: "android", stdin: "", }); diff --git a/e2e/lease-environment-passthrough.test.ts b/e2e/lease-environment-passthrough.test.ts index 2e769bb34..d03da9efe 100644 --- a/e2e/lease-environment-passthrough.test.ts +++ b/e2e/lease-environment-passthrough.test.ts @@ -96,6 +96,9 @@ describe("reaching a leased device", () => { expect(passthrough.code).toBe(7); expect(JSON.parse(passthrough.stdout)).toEqual({ argv: [`/fake/${platform}`, ...args], + // why: the fake reports its working folder; a worker's passthrough keeps the CLI's own, + // so only that a folder was reported is asserted here. + cwd: expect.any(String), platform, }); }, diff --git a/e2e/slow-android-lease-files.test.ts b/e2e/slow-android-lease-files.test.ts new file mode 100644 index 000000000..dec43bebe --- /dev/null +++ b/e2e/slow-android-lease-files.test.ts @@ -0,0 +1,134 @@ +import { existsSync } from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; + +import { DEVICE_READY_MS, waitFor, withHttpDaemon } from "./helpers/index.js"; + +const ANDROID_HOME = + process.env.ANDROID_HOME ?? + process.env.ANDROID_SDK_ROOT ?? + join(homedir(), "Library/Android/sdk"); +const hasAndroidSdk = + existsSync(ANDROID_HOME) && existsSync(join(ANDROID_HOME, "platform-tools", "adb")); + +const FILE_BYTES = 70_000_000; + +interface SseFrame { + readonly event: string; + readonly data: unknown; +} + +async function readSse(response: Response): Promise { + const frames: SseFrame[] = []; + for (const raw of (await response.text()).split("\n\n")) { + if (raw.trim() === "" || raw.startsWith(":")) continue; + let event: string | undefined; + let data = ""; + for (const line of raw.split("\n")) { + if (line.startsWith("event:")) event = line.slice(6).trim(); + else if (line.startsWith("data:")) data += line.slice(5).trim(); + } + if (event !== undefined) frames.push({ data: JSON.parse(data) as unknown, event }); + } + return frames; +} + +// why: only a real emulator proves that the folder a lease's upload went to is the folder `adb push` reads from, and that `adb pull` leaves a file the GET route serves, at a size no fake pipe is asked to carry. +describe.skipIf(!hasAndroidSdk)( + "a lease's files on a real emulator", + { tags: ["slow", "android"] }, + () => { + it( + "pushes an uploaded 70 MB file to the emulator with adb push, reads its size back with adb shell wc -c, and pulls it into a file a GET returns byte for byte", + { timeout: 600_000 }, + async () => { + const { env, port } = await withHttpDaemon((httpPort) => ({ + configOverrides: { + http: { enabled: true, host: "127.0.0.1", port: httpPort }, + idle: { shutdownAfterMs: 300_000 }, + warmPool: { learn: false }, + }, + driver: "real", + })); + const baseUrl = `http://127.0.0.1:${String(port)}`; + try { + const created = await env.cli(["token", "create", "--role", "agent"]); + expect(created.code, created.stderr).toBe(0); + const auth = { + authorization: `Bearer ${(created.json as { secret: string }).secret}`, + "content-type": "application/json", + }; + const requested = await fetch(`${baseUrl}/v1/lease-requests`, { + body: JSON.stringify({ device: "Pixel 9", platform: "android" }), + headers: auth, + method: "POST", + }); + expect(requested.status).toBe(201); + const requestId = ((await requested.json()) as { request: { id: string } }).request.id; + let leaseId = ""; + await waitFor( + async () => { + const polled = await fetch(`${baseUrl}/v1/lease-requests/${requestId}?wait=10`, { + headers: auth, + }); + const view = (await polled.json()) as { + request: { state: string; lease?: { id: string } }; + }; + leaseId = view.request.lease?.id ?? ""; + return view.request.state === "granted"; + }, + { label: "the lease request is granted", timeout: DEVICE_READY_MS }, + ); + + const bytes = Buffer.alloc(FILE_BYTES); + for (let at = 0; at < FILE_BYTES; at += 1) bytes[at] = at % 251; + const uploaded = await fetch(`${baseUrl}/v1/leases/${leaseId}/files/fixture.bin`, { + body: bytes, + headers: { ...auth, "content-type": "application/octet-stream" }, + method: "PUT", + }); + expect(uploaded.status).toBe(201); + + const run = async (args: string[]): Promise<{ exitCode: number; stdout: string }> => { + const response = await fetch(`${baseUrl}/v1/leases/${leaseId}/exec`, { + body: JSON.stringify({ args, tool: "adb" }), + headers: auth, + method: "POST", + }); + expect(response.status).toBe(200); + const frames = await readSse(response); + const exit = frames.find((frame) => frame.event === "exit"); + return { + exitCode: (exit?.data as { exitCode: number } | undefined)?.exitCode ?? -1, + stdout: frames + .filter((frame) => frame.event === "output") + .map((frame) => frame.data as { stream: string; chunk: string }) + .filter((chunk) => chunk.stream === "stdout") + .map((chunk) => chunk.chunk) + .join(""), + }; + }; + + expect((await run(["push", "fixture.bin", "/data/local/tmp/fixture.bin"])).exitCode).toBe( + 0, + ); + const size = await run(["shell", "wc", "-c", "/data/local/tmp/fixture.bin"]); + expect(size.exitCode).toBe(0); + expect(size.stdout).toContain(String(FILE_BYTES)); + expect((await run(["pull", "/data/local/tmp/fixture.bin", "back.bin"])).exitCode).toBe(0); + + const back = await fetch(`${baseUrl}/v1/leases/${leaseId}/files/back.bin`, { + headers: auth, + }); + expect(back.status).toBe(200); + expect(Buffer.from(await back.arrayBuffer()).equals(bytes)).toBe(true); + } finally { + await env + .cli(["nuke", "--delete-devices", "--yes"], { timeout: 120_000 }) + .catch(() => undefined); + } + }, + ); + }, +); diff --git a/src/contract/errors.ts b/src/contract/errors.ts index 99c590c4d..8f5a67edf 100644 --- a/src/contract/errors.ts +++ b/src/contract/errors.ts @@ -120,6 +120,8 @@ export interface ErrorDetailsMap { PASSTHROUGH_REFUSED: { readonly tool: string }; UNKNOWN_PASSTHROUGH_TOOL: { readonly tool: string }; EXEC_TIMEOUT: Record; + /** why: ADR 0067 §5: the lease file named by `stdinFile` could not be read to its end after `bytesRead` bytes, and the command was stopped. */ + STDIN_FILE_FAILED: { readonly name: string; readonly bytesRead: number }; /** why: `device.rotate` on a lease that is not on an iOS phone or tablet simulator; `class` is the physical class, the simulator's model family, or `emulator`. */ ROTATION_UNSUPPORTED: { readonly leaseId: string; @@ -229,6 +231,7 @@ const CODES_WITH_DECLARED_DETAILS_BY_CODE: Record FILE_TOO_LARGE: true, LEASE_FILES_FULL: true, UNKNOWN_FILE: true, + STDIN_FILE_FAILED: true, UPLOAD_STALLED: true, FILE_BUSY: true, LICENSE_NOT_ACCEPTED: true, @@ -368,6 +371,7 @@ export const ERROR_TABLE: { readonly [Code in SimlockErrorCode]: ErrorTableEntry FILE_TOO_LARGE: { code: "FILE_TOO_LARGE", kind: "domain", cliExitCode: 1, httpStatus: 413 }, LEASE_FILES_FULL: { code: "LEASE_FILES_FULL", kind: "domain", cliExitCode: 1, httpStatus: 413 }, UNKNOWN_FILE: { code: "UNKNOWN_FILE", kind: "domain", cliExitCode: 1, httpStatus: 404 }, + STDIN_FILE_FAILED: { code: "STDIN_FILE_FAILED", kind: "domain", cliExitCode: 1, httpStatus: 500 }, UPLOAD_STALLED: { code: "UPLOAD_STALLED", kind: "domain", cliExitCode: 1, httpStatus: 408 }, FILE_BUSY: { code: "FILE_BUSY", kind: "domain", cliExitCode: 1, httpStatus: 409 }, // why: a lease's tunnel socket refuses with these (ADR 0054 section 7), so every surface reports them alike. diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 4dbbeecce..485505df6 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -472,6 +472,9 @@ export const driverPassthrough = defineOperation({ output: passthroughCommandSchema, }); +/** why: the File name rule of a lease's files (1 to 128 characters), shared by the upload routes and exec's `stdinFile`. */ +export const LEASE_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; + // why: the daemon parses a request as one string, so unbounded stdin exhausts the heap (#1242). export const EXEC_STDIN_MAX_LENGTH = 8_388_608; @@ -496,6 +499,12 @@ export const EXEC_STDIN_MAX_LENGTH = 8_388_608; * `PASSTHROUGH_REFUSED` a lifecycle verb gets. Locally, where the CLI hands the tool its own * terminal, it stays allowed and interactive. * + * Every command runs with the lease's folder on the worker as its working folder (ADR 0067 §5), + * so a relative path names a file the holder uploaded. `stdinFile` names such a file to pipe to + * the command's stdin instead of `stdin`; the two together are `BAD_REQUEST`, checked by the + * worker's dispatcher, not here, because `.omit()` cannot build `run_on_device`'s input from an + * object carrying a refinement. + * * `stdin` is a **one-shot string**, not a stream: it is written to the child's stdin and the * pipe is then closed. ADR §19c is explicit that there is no pseudo-terminal here, so * line-oriented commands (`adb shell getprop`, `simctl spawn`) work and full-screen or @@ -522,6 +531,7 @@ export const deviceExec = defineOperation({ tool: z.string().min(1), args: z.array(z.string()), stdin: z.string().max(EXEC_STDIN_MAX_LENGTH).optional(), + stdinFile: z.string().regex(LEASE_FILE_NAME_PATTERN).optional(), /** * why: Who this command is being run *for* -- the requester the lease is attributed to (ADR * 0003 §4), not the connection's principal. Read **only on an admin session**, where it diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index 0293a60ee..82f753c3e 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -10,7 +10,7 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 81, max: 81 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 82, max: 82 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; diff --git a/src/daemon/dispatcher-exec.test.ts b/src/daemon/dispatcher-exec.test.ts index 94290c5cc..df68e4d45 100644 --- a/src/daemon/dispatcher-exec.test.ts +++ b/src/daemon/dispatcher-exec.test.ts @@ -8,9 +8,11 @@ import { ExecOutputDeliveryStalledError, FakeClock, NodeProcessRunner, + ProcessSpawnError, ScriptedProcessRunner, type ProcessRunner, } from "../ports/index.js"; +import { LeaseFilesError } from "../lease-files/index.js"; import { classifyError } from "./error-code.js"; import { buildDispatcher, flush, session } from "./test-dispatcher.js"; @@ -35,6 +37,10 @@ function recordingResolver( return resolver as unknown as PassthroughResolver; } +type LeaseFilesOverride = NonNullable< + NonNullable[0]>["leaseFiles"] +>; + describe("Dispatcher: device.exec", () => { const command = { args: ["--set", "/root", "list", "devices"], command: "simctl" }; @@ -149,6 +155,159 @@ describe("Dispatcher: device.exec", () => { expect(runner.calls[0]?.options.input).toBe("yes\n"); }); + it("refuses stdin and stdinFile together with BAD_REQUEST and spawns nothing", async () => { + const runner = new ScriptedProcessRunner([{ match: command }]); + const calls: RecordedPassthrough[] = []; + const { dispatcher, leaseId } = await withLease({ + passthroughOverride: recordingResolver(calls, () => + Promise.resolve({ args: ["--set", "/root", "list", "devices"], command: "simctl" }), + ), + processRunner: runner, + }); + const run = (extra: Record) => + dispatcher.dispatch( + "device.exec", + { args: ["list", "devices"], leaseId, tool: "simctl", ...extra }, + session({ principal: "tok_agent" }), + ); + + await expect(run({ stdin: "yes\n" })).resolves.toEqual({ exitCode: 0 }); + const spawned = runner.calls.length; + const asked = calls.length; + + const refusal = await run({ stdin: "yes\n", stdinFile: "fixture.tar" }).then( + () => undefined, + (error: unknown) => error, + ); + + expect(refusal).toMatchObject({ message: "Give stdin or stdinFile, not both" }); + expect(classifyError(refusal)).toBe("BAD_REQUEST"); + expect(runner.calls).toHaveLength(spawned); + expect(calls).toHaveLength(asked); + }); + + it("stops the command and fails with STDIN_FILE_FAILED when the stdinFile cannot be read to its end", async () => { + const oneMiB = 1024 * 1024; + for (const bytes of [oneMiB, 0]) { + let closed = false; + const runner = new ScriptedProcessRunner([{ hangs: true, match: command }]); + const { dispatcher, leaseId } = await withLease({ + leaseFiles: { + folderOf: () => Promise.resolve("/lease-folder"), + openFile: (_grant, name) => + Promise.resolve({ + close: () => { + closed = true; + return Promise.resolve(); + }, + name, + read: () => { + let sent = 0; + return new ReadableStream({ + pull(controller) { + if (sent >= bytes) { + controller.error(new Error("disk went away")); + return; + } + controller.enqueue(new Uint8Array(bytes)); + sent += bytes; + }, + }); + }, + size: bytes, + }), + }, + processRunner: runner, + }); + + let settled = false; + const outcome = dispatcher + .dispatch( + "device.exec", + { args: ["list", "devices"], leaseId, stdinFile: "fixture.tar", tool: "simctl" }, + session({ principal: "tok_agent" }), + ) + .then( + () => undefined, + (error: unknown) => error, + ) + .finally(() => { + settled = true; + }); + await flush(); + expect(settled).toBe(true); + const failure = await outcome; + + expect(classifyError(failure)).toBe("STDIN_FILE_FAILED"); + expect(failure).toMatchObject({ + details: { bytesRead: bytes, name: "fixture.tar" }, + message: `Reading fixture.tar failed after ${String(bytes)} bytes; the command was stopped`, + }); + expect(closed).toBe(true); + } + }); + + it("answers 404 for a lease that ended, a folder that vanished before the spawn or a stdinFile deleted before the open", async () => { + const ended = () => + Promise.reject(new LeaseFilesError("UNKNOWN_LEASE", "Unknown lease: x", { leaseId: "x" })); + const cases: readonly [string, LeaseFilesOverride, boolean, string][] = [ + [ + "folderOf on an ended grant", + { folderOf: ended, openFile: () => Promise.reject(new Error("unused")) }, + false, + "UNKNOWN_LEASE", + ], + [ + "spawn after the lease ended", + { + folderOf: vi.fn().mockResolvedValueOnce("/gone").mockImplementation(ended), + openFile: () => Promise.reject(new Error("unused")), + }, + false, + "UNKNOWN_LEASE", + ], + [ + "open of a file deleted after the listing", + { + folderOf: () => Promise.resolve("/lease-folder"), + openFile: () => Promise.reject(Object.assign(new Error("ENOENT"), { code: "ENOENT" })), + }, + true, + "UNKNOWN_FILE", + ], + ]; + for (const [title, leaseFiles, withFile, code] of cases) { + const spawnFails: ProcessRunner = { + run: () => Promise.reject(new Error("unused")), + spawn: () => { + throw new Error("unused"); + }, + spawnStreaming: () => { + throw new ProcessSpawnError("simctl", []); + }, + }; + const { dispatcher, leaseId } = await withLease({ leaseFiles, processRunner: spawnFails }); + + const failure = await dispatcher + .dispatch( + "device.exec", + { + args: ["list", "devices"], + leaseId, + ...(withFile ? { stdinFile: "fixture.tar" } : {}), + tool: "simctl", + }, + session({ principal: "tok_agent" }), + ) + .then( + () => undefined, + (error: unknown) => error, + ); + + expect(classifyError(failure), title).toBe(code); + } + }); + it("kills a command that outruns exec.timeoutMs and fails with EXEC_TIMEOUT", async () => { const runner = new ScriptedProcessRunner([{ hangs: true, match: command }]); const { clock, dispatcher, leaseId } = await withLease({ diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index c468c8a9d..054340571 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -39,6 +39,7 @@ import { type WarmKindForgetter, type WarmPoolReader, type CatalogReader, + type PassthroughCommand, type PassthroughResolver, isUnavailableInput, createUsageReader, @@ -60,9 +61,21 @@ import type { Logger, ProcessRunner, StreamingProcessHandle, + StreamingProcessResult, TimerHandle, } from "../ports/index.js"; -import { exitCodeOf, NoopLogger } from "../ports/index.js"; +import { + LeaseFilesError, + type LeaseFileView, + type LeaseFiles, + type LeaseFilesGrant, +} from "../lease-files/index.js"; +import { + exitCodeOf, + InputStreamFailedError, + NoopLogger, + ProcessSpawnError, +} from "../ports/index.js"; import { capabilityReason, type capabilitySchema, @@ -159,6 +172,7 @@ export interface DispatcherOptions { /** why: the lease's device input, which `device.rotate` writes to; optional so tests that never rotate need none. */ readonly inputs?: ModuleInputs; readonly processRunner?: ProcessRunner; + readonly leaseFiles?: Pick; /** * why: The environment a `device.exec` child starts from, before the driver's own scoping keys are * layered on top. Injected rather than read from `process.env` here (architecture rule 9), @@ -741,9 +755,14 @@ export class Dispatcher { if (this.options.passthrough === undefined) { throw new DispatchError("INTERNAL", "Tool passthrough is unavailable"); } - if (this.options.processRunner === undefined) { + const processRunner = this.options.processRunner; + if (processRunner === undefined) { throw new DispatchError("INTERNAL", "Command execution is unavailable"); } + // why: checked here, not as a refinement on the shared input, which `.omit()` could no longer build `run_on_device` from. + if (input.stdin !== undefined && input.stdinFile !== undefined) { + throw new DispatchError("BAD_REQUEST", "Give stdin or stdinFile, not both"); + } const lease = this.options.registry.snapshot.leases.find( (candidate) => candidate.id === input.leaseId, ); @@ -757,37 +776,114 @@ export class Dispatcher { // here, with pipes and no pty (ADR 0005 §19c), so a driver may refuse something it allows // a local `simlock ` invocation -- a bare `adb shell` would otherwise sit on those // pipes until `exec.timeoutMs` killed it. `platform` is the leased device's own. + const files = this.options.leaseFiles; + if (files === undefined) throw new DispatchError("INTERNAL", "Lease files are unavailable"); const command = await this.options.passthrough.passthrough( input.tool, toDriverDevice(record), input.args, { hasTerminal: false, platform: record.spec.platform }, ); + return this.#runExec( + { + command, + files, + grant: { grantedAt: lease.grantedAt, id: lease.id, platform: record.spec.platform }, + input, + processRunner, + }, + session, + ); + }; + + async #runExec( + run: { + readonly command: PassthroughCommand; + readonly files: Pick; + readonly grant: LeaseFilesGrant; + readonly input: z.infer<(typeof OPERATIONS)["device.exec"]["input"]>; + readonly processRunner: ProcessRunner; + }, + session: DispatchSession, + ): Promise<{ readonly exitCode: number }> { + const { command, files, grant, input, processRunner } = run; const execEnv: NodeJS.ProcessEnv = { ...this.options.execEnv, ...command.env }; for (const key of command.unsetEnv ?? []) { // why: the base comes from the daemon's environment, so a key it kept could re-aim the command. delete execEnv[key]; } - const handle = this.options.processRunner.spawnStreaming(command.command, command.args, { - env: execEnv, - // why: Returned, not fired and forgotten: whatever the transport hands back is what pauses - // the child until the chunk has actually gone somewhere (ADR 0005 §19e). - onChunk: (stream, chunk) => session.onOutput?.(stream, chunk), - ...(input.stdin === undefined ? {} : { input: input.stdin }), - }); - // why: Announced before the first chunk can arrive, because "it started" is what a transport - // needs to decide its response shape on -- see `DispatchSession.onStarted`. - session.onStarted?.(); - return { exitCode: await this.#awaitExec(handle, input.tool, input.args) }; - }; + const cwd = await this.#folderOf(files, grant); + const file = + input.stdinFile === undefined + ? undefined + : await this.#openStdinFile(files, grant, input.stdinFile); + try { + const handle = processRunner.spawnStreaming(command.command, command.args, { + cwd, + env: execEnv, + // why: Returned, not fired and forgotten: whatever the transport hands back is what pauses + // the child until the chunk has actually gone somewhere (ADR 0005 §19e). + onChunk: (stream, chunk) => session.onOutput?.(stream, chunk), + ...(input.stdin === undefined ? {} : { input: input.stdin }), + ...(file === undefined ? {} : { inputStream: file.read() }), + }); + // why: Announced before the first chunk can arrive, because "it started" is what a transport + // needs to decide its response shape on -- see `DispatchSession.onStarted`. + session.onStarted?.(); + return { + exitCode: await this.#awaitExec(handle, input.tool, input.args, input.stdinFile), + }; + } catch (error) { + if (error instanceof ProcessSpawnError) { + // why: Node reports no reason for a start that failed, so the folder is asked again: a lease that ended after `folderOf` made the working folder vanish (404), anything else is the spawn's own failure. + await this.#folderOf(files, grant); + } + throw error; + } finally { + await file?.close(); + } + } + + async #folderOf(files: Pick, grant: LeaseFilesGrant): Promise { + try { + return await files.folderOf(grant); + } catch (error) { + if (error instanceof LeaseFilesError) { + throw new DispatchError(error.code, error.message, error.details); + } + throw error; + } + } + + async #openStdinFile( + files: Pick, + grant: LeaseFilesGrant, + name: string, + ): Promise { + try { + return await files.openFile(grant, name); + } catch (error) { + if (error instanceof LeaseFilesError) { + throw new DispatchError(error.code, error.message, error.details); + } + // why: the file was listed and then deleted before the open, so it is gone, not a failure of the daemon. + if ((error as NodeJS.ErrnoException).code === "ENOENT") { + throw new DispatchError("UNKNOWN_FILE", `No file ${name} in this lease`, { name }); + } + throw error; + } + } async #awaitExec( handle: StreamingProcessHandle, tool: string, args: readonly string[], + stdinFile: string | undefined, ): Promise { const timeoutMs = this.options.config.exec.timeoutMs; const waited = handle.wait(); + // why: `inputFailed` only ever rejects, so the race below hears it as a value and never as a second way for the command to finish. + const inputFailed = handle.inputFailed?.catch((error: unknown) => error); let timer: TimerHandle | undefined; const expired = new Promise((resolve) => { timer = this.options.clock.setTimer(timeoutMs, () => resolve(EXEC_EXPIRED)); @@ -798,8 +894,14 @@ export class Dispatcher { // turn the timer fires has *finished*, and reporting that as a timeout would blame the // limit for a command that met it. `Promise.race` settles on whichever actually // happened first, which is exactly the question. - const outcome = await Promise.race([waited, expired]); - if (outcome !== EXEC_EXPIRED) return exitCodeOf(outcome); + const outcome = await Promise.race([ + waited, + expired, + ...(inputFailed === undefined ? [] : [inputFailed]), + ]); + if (outcome !== EXEC_EXPIRED && !(outcome instanceof InputStreamFailedError)) { + return exitCodeOf(outcome as StreamingProcessResult); + } // why: SIGTERM first, SIGKILL after a grace window: a tool that ignores the first must not be // able to hold this operation -- and the caller's connection -- open forever. The same @@ -815,6 +917,13 @@ export class Dispatcher { // timeout, not a competing answer to it. Swallowed here rather than left to reject // this `await` and skip the throw below. await waited.catch(() => undefined); + if (outcome instanceof InputStreamFailedError && stdinFile !== undefined) { + throw new DispatchError( + "STDIN_FILE_FAILED", + `Reading ${stdinFile} failed after ${String(outcome.bytesWritten)} bytes; the command was stopped`, + { bytesRead: outcome.bytesWritten, name: stdinFile }, + ); + } // why: `EXEC_TIMEOUT` rather than the exit code the kill produced: "we stopped it" and "it // failed" are different facts, and only the first tells a caller to raise the limit. throw new DispatchError( diff --git a/src/daemon/gateway-fleet.e2e.test.ts b/src/daemon/gateway-fleet.e2e.test.ts index cca8d4696..632e40ca9 100644 --- a/src/daemon/gateway-fleet.e2e.test.ts +++ b/src/daemon/gateway-fleet.e2e.test.ts @@ -39,6 +39,7 @@ import { FakeNpmCli, FakeUpdaterLauncher, MemoryFilesystem, + NodeFilesystem, NodeIpcTransport, NoopLogger, resolveDaemonSocketPath, @@ -215,12 +216,16 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { /** why: a worker on another protocol range is the gateway's `incompatible` worker. */ readonly protocolVersion?: ProtocolRange; readonly npm?: NpmCli; + /** why: a worker that runs a real command runs it in its lease folder, which has to exist on disk. */ + readonly realFilesystem?: boolean; }): Promise<{ daemon: DaemonServer; filesystem: Filesystem; directory: string }> { const directory = options.existing?.directory ?? (await mkdtemp(join(tmpdir(), `simlock-e2e-${options.label}-`))); if (options.existing === undefined) directories.push(directory); - const filesystem = options.existing?.filesystem ?? new MemoryFilesystem(); + const filesystem = + options.existing?.filesystem ?? + (options.realFilesystem === true ? new NodeFilesystem() : new MemoryFilesystem()); const driver = new FakeDriver({ availableOsVersions: ["18.0"], // why: a real command, so `device.exec` proves a real child process actually ran on @@ -380,6 +385,7 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { model: "Pixel-B", token: tokenB, stdout: "hello-from-b", + realFilesystem: true, }); // why: Both uplinks dial on their own schedule outside `startDaemon`'s own returned promise diff --git a/src/daemon/lease-files.test.ts b/src/daemon/lease-files.test.ts index a6b56574c..a47c329f6 100644 --- a/src/daemon/lease-files.test.ts +++ b/src/daemon/lease-files.test.ts @@ -154,7 +154,7 @@ describe("a lease's files at lease end", () => { }); }); -// why: the folder-level rules of `createLeaseFiles` that the worker's HTTP routes cannot reach yet (`folderOf` is for exec) or only by luck of timing: a held mkdir or listing, and grants whose lease ids differ only in case or in grant time. +// why: the folder-level rules of `createLeaseFiles` that the worker's HTTP routes cannot force (`folderOf` is reached by exec, which has no held mkdir) or only by luck of timing: a held mkdir or listing, and grants whose lease ids differ only in case or in grant time. class GatedFilesystem extends MemoryFilesystem { release: (() => void) | undefined; #gate: "mkdirp" | "readdir" | undefined; diff --git a/src/daemon/server.ts b/src/daemon/server.ts index e1b8210e0..a9aafabb8 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -101,6 +101,7 @@ export interface DaemonServerEngineOptions { readonly passthrough?: PassthroughResolver; readonly inputs?: DispatcherOptions["inputs"]; readonly processRunner?: ProcessRunner; + readonly leaseFiles?: DispatcherOptions["leaseFiles"]; readonly relayTargets?: RelayTargets; readonly relayTwoWayTargets?: TwoWayRelayTargets; readonly execEnv?: NodeJS.ProcessEnv; @@ -255,6 +256,7 @@ function buildDispatcher( ...(options.passthrough === undefined ? {} : { passthrough: options.passthrough }), ...(options.inputs === undefined ? {} : { inputs: options.inputs }), ...(options.processRunner === undefined ? {} : { processRunner: options.processRunner }), + ...(options.leaseFiles === undefined ? {} : { leaseFiles: options.leaseFiles }), ...(options.execEnv === undefined ? {} : { execEnv: options.execEnv }), queue: options.queue, ...(options.presence === undefined ? {} : { presence: options.presence }), diff --git a/src/daemon/test-dispatcher.ts b/src/daemon/test-dispatcher.ts index 18d2901a4..fb59a8485 100644 --- a/src/daemon/test-dispatcher.ts +++ b/src/daemon/test-dispatcher.ts @@ -1,3 +1,4 @@ +import { testLeaseFiles } from "./test-lease-files.js"; import { testConfig as configWithDefaults } from "../core/testing.js"; import { FakeDriver, @@ -152,6 +153,7 @@ export async function buildDispatcher( readonly passthroughTool?: string; readonly lease?: Partial; readonly processRunner?: ProcessRunner; + readonly leaseFiles?: DispatcherOptions["leaseFiles"]; readonly exec?: Partial; readonly passthroughContextSink?: unknown[]; readonly clock?: FakeClock; @@ -317,6 +319,7 @@ export async function buildDispatcher( ...(overrides.includeEnrollment === true ? { enrollment: engine.core.enrollment } : {}), passthrough: resolvePassthroughOverride(engine, overrides.passthroughOverride), ...(overrides.processRunner === undefined ? {} : { processRunner: overrides.processRunner }), + leaseFiles: overrides.leaseFiles ?? testLeaseFiles, execEnv: overrides.execEnv ?? { PATH: "/usr/bin" }, queue: engine, ...(overrides.presence === undefined ? {} : { presence: overrides.presence }), diff --git a/src/daemon/test-lease-files.ts b/src/daemon/test-lease-files.ts new file mode 100644 index 000000000..81edbcff6 --- /dev/null +++ b/src/daemon/test-lease-files.ts @@ -0,0 +1,9 @@ +import { tmpdir } from "node:os"; + +import type { DispatcherOptions } from "./dispatcher.js"; + +/** why: lease files for a test that runs exec but not their routes: every command runs in the temp folder, and no file exists. */ +export const testLeaseFiles: NonNullable = { + folderOf: () => Promise.resolve(tmpdir()), + openFile: () => Promise.reject(new Error("no lease file in this test")), +}; diff --git a/src/daemon/test-relay-support.ts b/src/daemon/test-relay-support.ts index a7e1ba599..ac8abf8cf 100644 --- a/src/daemon/test-relay-support.ts +++ b/src/daemon/test-relay-support.ts @@ -8,7 +8,13 @@ import { expect, vi } from "vitest"; import { FakeDriver, fakeDeviceDataTables } from "../core/testing.js"; import type { GatewayRelay } from "../gateway/index.js"; -import { MemoryFilesystem, NoopLogger, SystemClock, type Logger } from "../ports/index.js"; +import { + MemoryFilesystem, + NodeFilesystem, + NoopLogger, + SystemClock, + type Logger, +} from "../ports/index.js"; import type { LinkChannel, LinkConnection } from "../link/index.js"; import { linkPair, TappedTransport, type LinkPair } from "../link/testing.js"; import type { DispatchSession } from "./dispatch.js"; @@ -181,7 +187,8 @@ export async function startWorker( platform: "android", }), ], - filesystem: new MemoryFilesystem(), + // why: some tests run a real command on this worker, in a lease folder that has to exist on disk. + filesystem: new NodeFilesystem(), logger, relayTargets, version: "1.0.0-e2e", diff --git a/src/daemon/test-server.ts b/src/daemon/test-server.ts index f063dc56f..478c63744 100644 --- a/src/daemon/test-server.ts +++ b/src/daemon/test-server.ts @@ -1,3 +1,4 @@ +import { testLeaseFiles } from "./test-lease-files.js"; import { testConfig as configWithDefaults } from "../core/testing.js"; import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; @@ -317,6 +318,7 @@ export async function createHarness( leases: engine, ...(options.logger === undefined ? {} : { logger: options.logger }), passthrough: engine, + leaseFiles: testLeaseFiles, ...(options.processRunner === undefined ? {} : { processRunner: options.processRunner }), ...(options.protocolVersion === undefined ? {} : { protocolVersion: options.protocolVersion }), queue: engine, diff --git a/src/daemon/worker-composition.ts b/src/daemon/worker-composition.ts index ca6b5168b..9e5a006aa 100644 --- a/src/daemon/worker-composition.ts +++ b/src/daemon/worker-composition.ts @@ -510,6 +510,7 @@ export async function composeWorker( passthrough: core.catalog, inputs: leaseInputs, processRunner, + leaseFiles, execEnv: execBaseEnvironment(process.env), queue: leasing, presence: latestPresence, diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index fe10d9771..9059e9531 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -2292,6 +2292,43 @@ describe("GatewayDispatcher", () => { expect(forwarded()).toHaveLength(1); }); + it("forwards a device.exec's stdinFile to the lease's worker under the same name, and nothing when it is omitted", async () => { + const { coordinator, directory, dispatcher, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_1", client); + workers.connected("wrk_1", undefined, "0.3.0"); + workers.refresh("wrk_1", { + capacity: statusFixture().capacity, + health: "running", + queueDepth: 0, + catalog: catalogFixture([{ models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }]) + .platforms, + downloads: { policy: "on-request" }, + }); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + const grant = await coordinator.request( + { model: "iPhone 17", platform: "ios" }, + { allowDownload: false, noWait: true, ownerId: "agent-1", requesterId: "agent-1" }, + ); + const exec = (extra: { stdinFile?: string }) => { + client.execQueue.push({ exitCode: 0, kind: "ok" }); + return dispatcher.dispatch( + "device.exec", + { args: ["spawn", "booted", "untar"], leaseId: grant.lease.id, tool: "simctl", ...extra }, + session({ principal: "agent-1", role: "agent" }), + ); + }; + + await exec({ stdinFile: "fixture.tar" }); + await exec({}); + + expect(client.execInputs.map((forwarded) => forwarded.stdinFile)).toEqual([ + "fixture.tar", + undefined, + ]); + expect("stdinFile" in (client.execInputs[1] ?? {})).toBe(false); + }); + it("calls onStarted for a silent device.exec from the worker's own started push (ADR §19a/§19b/§19e)", async () => { const { coordinator, directory, dispatcher, workers } = harness(); const client = new ScriptedWorkerClient(); diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts index 06891698d..2d61d2afe 100644 --- a/src/gateway/dispatcher.ts +++ b/src/gateway/dispatcher.ts @@ -799,6 +799,7 @@ export class GatewayDispatcher { tool: input.tool, args: input.args, ...(input.stdin === undefined ? {} : { stdin: input.stdin }), + ...(input.stdinFile === undefined ? {} : { stdinFile: input.stdinFile }), }, session, ); diff --git a/src/gateway/fleet-forwarding.ts b/src/gateway/fleet-forwarding.ts index a8ce56b1d..63d1797fc 100644 --- a/src/gateway/fleet-forwarding.ts +++ b/src/gateway/fleet-forwarding.ts @@ -18,6 +18,7 @@ export interface FleetExecInput { readonly tool: string; readonly args: readonly string[]; readonly stdin?: string; + readonly stdinFile?: string; } export interface FleetRotateInput { @@ -158,6 +159,7 @@ export class FleetForwarding { tool: input.tool, args: [...input.args], ...(input.stdin === undefined ? {} : { stdin: input.stdin }), + ...(input.stdinFile === undefined ? {} : { stdinFile: input.stdinFile }), requesterId: namespacedRequesterId, }, { diff --git a/src/gateway/test-support.ts b/src/gateway/test-support.ts index 28cc8c61d..531936096 100644 --- a/src/gateway/test-support.ts +++ b/src/gateway/test-support.ts @@ -349,6 +349,8 @@ export class ScriptedWorkerClient { * that keeps streaming output on a call the gateway has already given up awaiting. */ lastExecOptions: ExecOptions | undefined; + /** why: every input a gateway forwarded to this worker, to see which fields reached it. */ + readonly execInputs: ExecInput[] = []; /** * P4 (round 3 review): the mirror of `lastExecOptions` above, for `requestLease` -- captured * before `requestLeaseQueue`'s own outcome is even read, so a `"hang"` outcome leaves a test a @@ -498,6 +500,7 @@ export class ScriptedWorkerClient { this.calls.push(`device.exec:${input.requesterId ?? ""}`); this.#throwIfFailing(); this.lastExecOptions = options; + this.execInputs.push(input); const outcome = this.execQueue.shift(); if (outcome?.kind === "error") throw outcome.error; const { onOutput, onStarted } = options; diff --git a/src/http/lease-declarations.ts b/src/http/lease-declarations.ts index c5a9dbd9b..3c9b9f697 100644 --- a/src/http/lease-declarations.ts +++ b/src/http/lease-declarations.ts @@ -7,6 +7,7 @@ import { imageTagSchema, exceptCategoriesSchema, EXEC_STDIN_MAX_LENGTH, + LEASE_FILE_NAME_PATTERN, INPUT_ORIENTATIONS, leaseIdSchema, OPERATIONS, @@ -143,6 +144,11 @@ const execBodySchema = z .max(EXEC_STDIN_MAX_LENGTH) .nullish() .transform((value) => value ?? undefined), + stdinFile: z + .string() + .regex(LEASE_FILE_NAME_PATTERN) + .nullish() + .transform((value) => value ?? undefined), requesterId: requesterIdSchema.nullish().transform((value) => value ?? undefined), }) .strict(); @@ -163,7 +169,11 @@ export const leaseExecRoute = declareRoute({ "Answers a stream of messages: output, then exit or error. A failure before the command starts is a plain JSON error.", request: { params: leaseParamsSchema, json: execBodySchema }, stream: execMessageSchema, - errors: { 404: ["UNKNOWN_LEASE"], 501: ["UNSUPPORTED_IN_GATEWAY_MODE"], 504: ["EXEC_TIMEOUT"] }, + errors: { + 404: ["UNKNOWN_LEASE", "UNKNOWN_FILE"], + 501: ["UNSUPPORTED_IN_GATEWAY_MODE"], + 504: ["EXEC_TIMEOUT"], + }, }); const rotateBodySchema = z.object({ orientation: z.enum(INPUT_ORIENTATIONS) }).strict(); diff --git a/src/http/openapi.test.ts b/src/http/openapi.test.ts index 0cdc20290..18cf13d52 100644 --- a/src/http/openapi.test.ts +++ b/src/http/openapi.test.ts @@ -152,7 +152,7 @@ describe("buildOpenApiDocument", () => { "get /v1/lease-requests/{id}/events 404": ["UNKNOWN_LEASE_REQUEST"], "get /v1/leases/{id} 404": ["UNKNOWN_LEASE"], "get /v1/leases/{id}/events 404": ["UNKNOWN_LEASE"], - "post /v1/leases/{id}/exec 404": ["UNKNOWN_LEASE"], + "post /v1/leases/{id}/exec 404": ["UNKNOWN_LEASE", "UNKNOWN_FILE"], "post /v1/leases/{id}/exec 501": ["UNSUPPORTED_IN_GATEWAY_MODE"], "post /v1/leases/{id}/exec 504": ["EXEC_TIMEOUT"], "post /v1/leases/{id}/renew 404": ["UNKNOWN_LEASE"], diff --git a/src/lease-files/index.ts b/src/lease-files/index.ts index 50103dfc5..14d20e74c 100644 --- a/src/lease-files/index.ts +++ b/src/lease-files/index.ts @@ -1,2 +1,3 @@ +export { LeaseFilesError } from "./errors.js"; export { createLeaseFiles } from "./lease-files.js"; -export type { LeaseFilesLimits } from "./types.js"; +export type { LeaseFilesGrant, LeaseFileView, LeaseFiles, LeaseFilesLimits } from "./types.js"; diff --git a/src/lease-files/names.ts b/src/lease-files/names.ts index 0c4a7185a..47128ff3c 100644 --- a/src/lease-files/names.ts +++ b/src/lease-files/names.ts @@ -1,9 +1,8 @@ +import { LEASE_FILE_NAME_PATTERN } from "../contract/index.js"; import { LeaseFilesError } from "./errors.js"; -const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; - export function isFileName(name: string): boolean { - return NAME_PATTERN.test(name); + return LEASE_FILE_NAME_PATTERN.test(name); } export function requireFileName(name: string): void { diff --git a/src/mcp/contracts.ts b/src/mcp/contracts.ts index dd1935ab4..dd918f8db 100644 --- a/src/mcp/contracts.ts +++ b/src/mcp/contracts.ts @@ -105,6 +105,7 @@ export const leaseStatusOutputSchema = leaseRecordSchema.partial().extend({ held export const runOnDeviceInputSchema = OPERATIONS["device.exec"].input.omit({ leaseId: true, requesterId: true, + stdinFile: true, }); export const runOnDeviceOutputSchema = z.object({ diff --git a/src/ports/index.ts b/src/ports/index.ts index f4a66f947..869a4d0bf 100644 --- a/src/ports/index.ts +++ b/src/ports/index.ts @@ -134,6 +134,7 @@ export { LoggingProcessRunner } from "./logging-process-runner.js"; export { exitCodeOf, ExecOutputDeliveryStalledError, + InputStreamFailedError, NodeProcessRunner, type ProcessHandle, ProcessSpawnError, diff --git a/src/ports/process-runner.test.ts b/src/ports/process-runner.test.ts index c4c4427e6..4f32fd437 100644 --- a/src/ports/process-runner.test.ts +++ b/src/ports/process-runner.test.ts @@ -232,6 +232,67 @@ describe("NodeProcessRunner: spawnStreaming", () => { expect(seen.join("").length).toBe(64 * 16 * 1024); }); + it("rejects inputFailed with the bytes written when the input stream cannot be read to its end, and not when the child closes its stdin early", async () => { + const runner = new NodeProcessRunner(); + const oneMiB = 1024 * 1024; + const failingAfter = (bytes: number): ReadableStream => { + let sent = 0; + return new ReadableStream({ + pull(controller) { + if (sent >= bytes) { + controller.error(new Error("disk went away")); + return; + } + controller.enqueue(new Uint8Array(Math.min(64 * 1024, bytes - sent))); + sent += 64 * 1024; + }, + }); + }; + const drainingChild = [ + "-e", + "process.stdin.on('data', () => {}); setInterval(() => {}, 1_000)", + ]; + + for (const bytes of [oneMiB, 0]) { + const handle = runner.spawnStreaming(process.execPath, drainingChild, { + inputStream: failingAfter(bytes), + onChunk: () => {}, + }); + const outcome = await Promise.race([ + handle.inputFailed?.catch((error: unknown) => error), + new Promise((resolve) => setTimeout(() => resolve("no failure"), 1_000)), + ]); + handle.kill("SIGKILL"); + await handle.wait(); + expect(outcome).toMatchObject({ bytesWritten: bytes }); + } + + let cancelled = false; + let chunks = 0; + const early = runner.spawnStreaming(process.execPath, ["-e", "process.exit(0)"], { + inputStream: new ReadableStream({ + cancel() { + cancelled = true; + }, + async pull(controller) { + await new Promise((resolve) => setTimeout(resolve, 5)); + chunks += 1; + controller.enqueue(new Uint8Array(64 * 1024)); + }, + }), + onChunk: () => {}, + }); + let failed = false; + early.inputFailed?.catch(() => { + failed = true; + }); + expect((await early.wait()).code).toBe(0); + await waitUntil(() => cancelled); + await new Promise((resolve) => setImmediate(resolve)); + expect(failed).toBe(false); + expect(chunks).toBeGreaterThan(0); + }); + it("does not settle wait() while a chunk's delivery is still pending past the exit grace window, even though a real pipe already delivered what the child wrote after it", async () => { // The defect this guards: a paused readable never emits `close`, so the exit-to-close // grace window used to treat "quiet because we paused it" the same as "quiet because the diff --git a/src/ports/process-runner.ts b/src/ports/process-runner.ts index 125bc6ea3..ab6cf470d 100644 --- a/src/ports/process-runner.ts +++ b/src/ports/process-runner.ts @@ -1,6 +1,7 @@ import { spawn as spawnChildProcess, type ChildProcess } from "node:child_process"; import { closeSync, openSync } from "node:fs"; import { constants } from "node:os"; +import type { Writable } from "node:stream"; import { childLaunch } from "./windows-command.js"; @@ -93,6 +94,11 @@ export interface ProcessStreamOptions { * own timeout), matching `ProcessRunOptions.input`. */ readonly input?: string; + /** + * why: Piped to the child's stdin and then closed, for input too big to hold as a string. + * Given together with `input`, `inputStream` is ignored. + */ + readonly inputStream?: ReadableStream; /** * Called with each chunk as it arrives. **May return a promise**, and if it does, this * runner stops reading that stream until it resolves -- which is how backpressure reaches @@ -115,6 +121,12 @@ export interface StreamingProcessResult { export interface StreamingProcessHandle { readonly pid: number; + /** + * why: Only on a child spawned with `inputStream`: rejects when that stream fails to be read + * to its end, with the bytes written to the child by then. A child that closes its stdin + * early is not a failure and never rejects it. + */ + inputFailed?: Promise; kill(signal?: NodeJS.Signals): void; wait(): Promise; } @@ -316,11 +328,72 @@ export class NodeProcessRunner implements ProcessRunner { // swallowed below rather than left to surface as an unhandled `error` on the stream. child.stdin?.on("error", () => undefined); child.stdin?.end(options.input); + } else if (options.inputStream !== undefined && child.stdin) { + const inputFailed = pumpInput(options.inputStream, child.stdin); + // why: a caller that never looks at `inputFailed` must not turn a read error into an unhandled rejection that ends the daemon. + inputFailed.catch(() => undefined); + handle.inputFailed = inputFailed; } return handle; } } +/** why: the input stream of a streamed child failed to be read to its end; `bytesWritten` is what the child's stdin had been handed by then. */ +export class InputStreamFailedError extends Error { + constructor( + readonly bytesWritten: number, + cause: unknown, + ) { + super(`Reading the input stream failed after ${String(bytesWritten)} bytes`, { cause }); + this.name = "InputStreamFailedError"; + } +} + +/** + * why: writes the stream to the child's stdin chunk by chunk, waiting for `drain` so a slow child holds the read back (nothing is buffered, ADR 0005 §19e), then closes stdin. A child that closes its stdin early (EPIPE) cancels the read quietly; only a read error rejects the returned promise, which never resolves otherwise. + */ +function pumpInput(source: ReadableStream, stdin: Writable): Promise { + return new Promise((_resolve, reject) => { + const reader = source.getReader(); + let written = 0; + let closed = false; + const onClosed = (): void => { + closed = true; + void reader.cancel().catch(() => undefined); + }; + stdin.on("error", onClosed); + stdin.on("close", onClosed); + void (async () => { + for (;;) { + let result: ReadableStreamReadResult; + try { + result = await reader.read(); + } catch (error) { + if (!closed) reject(new InputStreamFailedError(written, error)); + return; + } + if (closed) return; + if (result.done) { + stdin.end(); + return; + } + written += result.value.byteLength; + if (!stdin.write(result.value) && !closed) { + await new Promise((resolve) => { + const done = (): void => { + stdin.off("drain", done); + stdin.off("close", done); + resolve(); + }; + stdin.once("drain", done); + stdin.once("close", done); + }); + } + } + })(); + }); +} + /** * Thrown by `NodeStreamingProcessHandle#wait()` when the child exited but a chunk's delivery * -- the promise `onChunk` returned, which this handle was waiting on before resuming the @@ -378,6 +451,7 @@ export class ExecOutputDeliveryStalledError extends Error { */ class NodeStreamingProcessHandle implements StreamingProcessHandle { readonly pid: number; + inputFailed?: Promise; readonly #result: Promise; #chunkCount = 0; #pendingDeliveries = 0; @@ -801,7 +875,12 @@ export class ScriptedProcessRunner implements ProcessRunner { throw new Error(`Unexpected process invocation: ${command} ${args.join(" ")}`); } - return new ScriptedStreamingProcessHandle(this.#nextPid++, expectation, options.onChunk); + return new ScriptedStreamingProcessHandle( + this.#nextPid++, + expectation, + options.onChunk, + options.inputStream, + ); } } @@ -813,6 +892,7 @@ export class ScriptedProcessRunner implements ProcessRunner { * process or a real clock. */ class ScriptedStreamingProcessHandle implements StreamingProcessHandle { + inputFailed?: Promise; readonly #result: Promise; #resolve!: (result: StreamingProcessResult) => void; #finished = false; @@ -823,8 +903,10 @@ class ScriptedStreamingProcessHandle implements StreamingProcessHandle { readonly pid: number, expectation: ScriptedProcessExpectation, onChunk: (stream: "stdout" | "stderr", chunk: string) => void | Promise, + inputStream?: ReadableStream, ) { this.#ignoresSigterm = expectation.ignoresSigterm ?? false; + if (inputStream !== undefined) this.inputFailed = scriptedInputFailure(inputStream); this.#result = new Promise((resolve) => { this.#resolve = resolve; }); @@ -866,6 +948,27 @@ class ScriptedStreamingProcessHandle implements StreamingProcessHandle { } } +/** why: the scripted child reads its whole input at once, so a test sees a failing stream reject `inputFailed` as the real adapter does. */ +function scriptedInputFailure(source: ReadableStream): Promise { + const failed = new Promise((_resolve, reject) => { + void (async () => { + const reader = source.getReader(); + let read = 0; + try { + for (;;) { + const result = await reader.read(); + if (result.done) return; + read += result.value.byteLength; + } + } catch (error) { + reject(new InputStreamFailedError(read, error)); + } + })(); + }); + failed.catch(() => undefined); + return failed; +} + function scriptedChunks( expectation: ScriptedProcessExpectation, ): readonly { readonly stream: "stdout" | "stderr"; readonly chunk: string }[] { diff --git a/website/src/content/docs/docs/reference/errors.mdx b/website/src/content/docs/docs/reference/errors.mdx index 74de4bf06..0c5e3471d 100644 --- a/website/src/content/docs/docs/reference/errors.mdx +++ b/website/src/content/docs/docs/reference/errors.mdx @@ -22,7 +22,7 @@ In a script, check `code`, not the message: the wording of a message can change, | Exit | Error codes | Meaning | | --- | --- | --- | | 0 | — | Success. For a `simlock lease` that stayed running: the lease ended because you asked. | -| 1 | `INTERNAL`, `PROVISION_FAILED`, `UNKNOWN_LEASE`, `UNKNOWN_FILE`, `FILE_TOO_LARGE`, `LEASE_FILES_FULL`, `FILE_BUSY`, `UPLOAD_STALLED`, `BASELINE_SAVE_FAILED`, `FORBIDDEN`, `ADMIN_AUTHENTICATION_FAILED`, `SETUP_MCP_FAILED`, `DAEMON_STARTUP_FAILED`, `DAEMON_CONNECTION_LOST`, `DAEMON_STOPPING`, `DAEMON_UPDATING`, `HANDSHAKE_REQUIRED`, `PROTOCOL_VERSION_UNSUPPORTED`, `WORKER_UNREACHABLE`, `RELAY_TARGET_MISSING`, `ALERT_SEND_FAILED`, `UPDATE_RESOLVE_FAILED`, `HISTORY_UNAVAILABLE`, `DOCTOR_UNAVAILABLE`, `INPUT_UNAVAILABLE`, `NUKE_UNAVAILABLE`, `UNKNOWN_DAEMON_ERROR`, `SERVICE_FAILED`, `CANCELLED`, `TUNNEL_UNSUPPORTED`, `TUNNEL_PORT_IN_USE`, `TUNNEL_BAD_PORT`, `TUNNEL_LIMIT`, `TUNNEL_FAILED`, `TUNNEL_UNAVAILABLE`, `TUNNEL_DISCONNECTED`, `TUNNEL_CALLER_PORT_IN_USE` | The command failed. Read the code and the message. | +| 1 | `INTERNAL`, `PROVISION_FAILED`, `UNKNOWN_LEASE`, `UNKNOWN_FILE`, `STDIN_FILE_FAILED`, `FILE_TOO_LARGE`, `LEASE_FILES_FULL`, `FILE_BUSY`, `UPLOAD_STALLED`, `BASELINE_SAVE_FAILED`, `FORBIDDEN`, `ADMIN_AUTHENTICATION_FAILED`, `SETUP_MCP_FAILED`, `DAEMON_STARTUP_FAILED`, `DAEMON_CONNECTION_LOST`, `DAEMON_STOPPING`, `DAEMON_UPDATING`, `HANDSHAKE_REQUIRED`, `PROTOCOL_VERSION_UNSUPPORTED`, `WORKER_UNREACHABLE`, `RELAY_TARGET_MISSING`, `ALERT_SEND_FAILED`, `UPDATE_RESOLVE_FAILED`, `HISTORY_UNAVAILABLE`, `DOCTOR_UNAVAILABLE`, `INPUT_UNAVAILABLE`, `NUKE_UNAVAILABLE`, `UNKNOWN_DAEMON_ERROR`, `SERVICE_FAILED`, `CANCELLED`, `TUNNEL_UNSUPPORTED`, `TUNNEL_PORT_IN_USE`, `TUNNEL_BAD_PORT`, `TUNNEL_LIMIT`, `TUNNEL_FAILED`, `TUNNEL_UNAVAILABLE`, `TUNNEL_DISCONNECTED`, `TUNNEL_CALLER_PORT_IN_USE` | The command failed. Read the code and the message. | | 2 | `USAGE`, `BAD_REQUEST`, `BASELINE_MISMATCH`, `BAD_FRAME`, `UNKNOWN_REQUEST`, `IDEMPOTENCY_CONFLICT`, `PASSTHROUGH_REFUSED`, `UNKNOWN_PASSTHROUGH_TOOL`, `SETUP_REFUSED`, `GATEWAY_NOT_PRESENT`, `UPDATE_UNSUPPORTED_INSTALL`, `UPDATE_SHARED_INSTALL`, `UNSUPPORTED_IN_GATEWAY_MODE`, `UNSUPPORTED_IN_WORKER_MODE`, `WORKER_CONNECTED`, `WORKER_NOT_CONNECTED` | The request was wrong. Running it again unchanged fails again. | | 10 | `QUEUE_TIMEOUT`, `EXEC_TIMEOUT`, `DOWNLOAD_TIMEOUT` | A deadline ran out. | | 11 | `NO_CAPACITY`, `DEVICE_BUSY`, `COMPONENT_BUSY` | Busy right now. The same request can pass later. | @@ -111,6 +111,7 @@ A lease's tunnel socket (`GET /v1/leases/{id}/tunnel`, on a worker with `capabil | `LEASE_FILES_FULL` | 1 | 413 | The upload would take the lease's folder past 4 GiB, counting every file in it and the uploads running at the same time. The message gives the bytes held. | Delete files with `DELETE /v1/leases/{id}/files/{name}`, or finish the other uploads first. | | `UNKNOWN_FILE` | 1 | 404 | The lease has no file with this name (names match ignoring case). | List the files with `GET /v1/leases/{id}/files`. | | `FILE_BUSY` | 1 | 409 | Another request is uploading a file with this name. | Wait for it to finish, then upload again. | +| `STDIN_FILE_FAILED` | 1 | 500 | The stored file named by `stdinFile` could not be read to its end, so the command was stopped. The stream ends with this error. | Run the command again. Upload the file again if it keeps failing. | | `UPLOAD_STALLED` | 1 | 408 | No byte of the upload's body arrived for 330 seconds. The previous file is kept. | Send the upload again from the start. | A bad file name is `BAD_REQUEST`, and a worker whose free disk is under `diskPressure.freeBytesThreshold` answers an upload with `INSUFFICIENT_DISK_SPACE`. diff --git a/website/src/content/docs/docs/using-devices/programmatic-client.mdx b/website/src/content/docs/docs/using-devices/programmatic-client.mdx index 1931c1fb2..a48712ecd 100644 --- a/website/src/content/docs/docs/using-devices/programmatic-client.mdx +++ b/website/src/content/docs/docs/using-devices/programmatic-client.mdx @@ -113,7 +113,7 @@ Run it with a TypeScript runner, for example `npx tsx lease-and-launch.mts`. | `requestLease(request, { onProgress, signal })` | Waits for a device and resolves with the grant: `device`, `environment`, `lease` and `timing`, the same fields `simlock lease` prints. | | `renewLease({ leaseId, ttlMs? })` | Moves the deadline to now plus the TTL. Resolves with the lease, including the new `ttlDeadline`. | | `releaseLease({ leaseId })` | Ends the lease. A simulator or emulator is then deleted; a physical device is cleaned. | -| `exec({ leaseId, tool, args, stdin? }, { onOutput })` | Runs `simctl` or `adb` (or `devicectl` on a physical iPhone or iPad) on the device, and resolves with `{ exitCode }`. `stdin` holds at most 8,388,608 characters. | +| `exec({ leaseId, tool, args, stdin?, stdinFile? }, { onOutput })` | Runs `simctl` or `adb` (or `devicectl` on a physical iPhone or iPad) on the device, and resolves with `{ exitCode }`. `stdin` holds at most 8,388,608 characters. `stdinFile` names a file of the lease's folder to send on stdin instead; give one of the two. | | `rotate(leaseId, orientation)` | Turns an iPhone or iPad simulator. See [Rotate without a socket](/simlock/docs/using-devices/watching-the-screen#rotate-without-a-socket). | | `listLeases()` | Your leases. | | `getCatalog({ platform? })` | What you can ask for, as `simlock catalog --json` prints it. | diff --git a/website/src/content/docs/docs/using-devices/remote-agents.mdx b/website/src/content/docs/docs/using-devices/remote-agents.mdx index e22716446..28b8c2de8 100644 --- a/website/src/content/docs/docs/using-devices/remote-agents.mdx +++ b/website/src/content/docs/docs/using-devices/remote-agents.mdx @@ -149,8 +149,8 @@ The command runs on the worker, as the user who runs the worker's daemon. Treat - **Leave the device out.** Simlock adds the lease's device to the command: the UDID for `simctl` (where the subcommand takes one), `-s ` for `adb`, and `--device ` for `devicectl`. Write `["install","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/builds/MyApp.app"]`, not a UDID or serial. - **Naming another device is refused.** A command that names a different device, such as `booted`, another UDID, `adb -s emulator-5556`, `-e`, `-d` or `-t`, is refused with `422 PASSTHROUGH_REFUSED` before anything runs. Naming the lease's own device is accepted, except on a physical Android phone, which refuses any option before the subcommand, even its own `-s `. -- **Paths are on the worker.** `{"tool":"simctl","args":["install","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/builds/MyApp.app"]}` needs `/builds/MyApp.app` to exist on the worker. Upload a file to the lease's folder with [lease files](#lease-files), or use [agent-device](/simlock/docs/using-devices/agent-device), which uploads apps for you. -- **No terminal.** `stdin` in the body is sent to the command once, and may hold at most 8,388,608 characters; a longer one is refused with `BAD_REQUEST`. Interactive commands, such as a bare `adb shell`, are refused. +- **Paths are on the worker.** `{"tool":"simctl","args":["install","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/builds/MyApp.app"]}` needs `/builds/MyApp.app` to exist on the worker. Every command runs with the lease's folder as its working folder, so a relative path names a file you uploaded with [lease files](#lease-files): `{"tool":"adb","args":["push","fixture.bin","/data/local/tmp/fixture.bin"]}`. A file a command writes there can be downloaded again. Or use [agent-device](/simlock/docs/using-devices/agent-device), which uploads apps for you. +- **No terminal.** `stdin` in the body is sent to the command once, and may hold at most 8,388,608 characters; a longer one is refused with `BAD_REQUEST`. To send a stored file instead, name it in `stdinFile` (a [lease file](#lease-files)): the command reads its bytes, up to the file's own 2 GiB, and then sees end of input. A `stdinFile` that names no file is refused with `404 UNKNOWN_FILE` before the command starts; giving both `stdin` and `stdinFile` is refused with `BAD_REQUEST`. If the file cannot be read to its end, the command is stopped and the stream ends with an `error` event `STDIN_FILE_FAILED`. Through a gateway, the file must already be on the lease's worker. Interactive commands, such as a bare `adb shell`, are refused. - **Output is text.** Output is decoded as UTF-8, so binary output, such as a screenshot written to stdout, gets corrupted. Write it to a file on the worker instead. - **Time limit.** A command that runs longer than 10 minutes is stopped, and the stream ends with an `error` event carrying `EXEC_TIMEOUT`. Disconnecting doesn't stop the command. - **The same commands are refused as locally.** Everything `simlock simctl` and `simlock adb` refuse (see [Commands Simlock refuses](/simlock/docs/using-devices/working-with-a-device#commands-simlock-refuses)) is refused here with `422 PASSTHROUGH_REFUSED`, before anything runs. So is `simctl` on an Android lease, and `adb` on an iOS one.