diff --git a/packages/serve-sim/README.md b/packages/serve-sim/README.md index f621b3553..88d4eeb5e 100644 --- a/packages/serve-sim/README.md +++ b/packages/serve-sim/README.md @@ -209,6 +209,8 @@ serve-sim camera --stop-webcam Multiple booted simulators are supported — pass several device names, or leave it empty to attach to all of them. +Helpers started by `--detach` or `--no-preview` exit after their target simulators remain shut down beyond the grace period. A failed check keeps the helper alive. + ### Remote access (`--auth-token`) Requests that don't come straight from this machine — LAN clients, tunnels, reverse proxies — are refused unless the server is started with `--auth-token ` (or `SERVE_SIM_AUTH_TOKEN`). CLI and scripted clients send `Authorization: Bearer `. To share the preview with a browser, send the link with the token in the URL fragment: diff --git a/packages/serve-sim/src/__tests__/devtools-proxy.test.ts b/packages/serve-sim/src/__tests__/devtools-proxy.test.ts index 9205ba18c..4589543c6 100644 --- a/packages/serve-sim/src/__tests__/devtools-proxy.test.ts +++ b/packages/serve-sim/src/__tests__/devtools-proxy.test.ts @@ -1,27 +1,10 @@ import { afterEach, describe, expect, test } from "bun:test"; import { mkdirSync, rmSync, writeFileSync } from "fs"; -import { createServer as createNetServer } from "net"; import { spawn, type ChildProcess } from "child_process"; import { simMiddleware, type ServeSimState, type WebKitBridge } from "../middleware"; import { servePreview, type PreviewServer } from "../runtime"; import { STATE_DIR, stateFileForDevice } from "../state"; - -async function freePort(): Promise { - return new Promise((resolve, reject) => { - const server = createNetServer(); - server.once("error", reject); - server.listen(0, "127.0.0.1", () => { - const addr = server.address(); - if (!addr || typeof addr === "string") { - server.close(); - reject(new Error("failed to allocate port")); - return; - } - const port = addr.port; - server.close(() => resolve(port)); - }); - }); -} +import { freePort } from "./server-test-support"; describe("devtools proxy", () => { const udid = "DEVTOOLS-PROXY-DEVICE"; diff --git a/packages/serve-sim/src/__tests__/duo-preview-stream.test.ts b/packages/serve-sim/src/__tests__/duo-preview-stream.test.ts index 9285deddc..34fe12492 100644 --- a/packages/serve-sim/src/__tests__/duo-preview-stream.test.ts +++ b/packages/serve-sim/src/__tests__/duo-preview-stream.test.ts @@ -4,6 +4,7 @@ import type { ServerResponse } from "http"; import { join } from "node:path"; import { DuoPreview, DUO_SETTLE_MS } from "../duo-preview"; import type { DuoProjection } from "../duo-renderer"; +import { waitFor } from "./server-test-support"; class FakeResponse { writableLength = 0; @@ -42,14 +43,6 @@ function harness() { return { preview, calls }; } -async function waitFor(predicate: () => boolean): Promise { - const deadline = Date.now() + 1_000; - while (!predicate()) { - if (Date.now() >= deadline) throw new Error("condition not reached"); - await new Promise((resolve) => setTimeout(resolve, 5)); - } -} - describe("Duo live preview stream", () => { test("motion uses the fast target and sharpens once after settle", async () => { const { preview, calls } = harness(); diff --git a/packages/serve-sim/src/__tests__/fixtures/shutdown-watch-xcrun.sh b/packages/serve-sim/src/__tests__/fixtures/shutdown-watch-xcrun.sh new file mode 100755 index 000000000..f5cb235d4 --- /dev/null +++ b/packages/serve-sim/src/__tests__/fixtures/shutdown-watch-xcrun.sh @@ -0,0 +1,19 @@ +#!/bin/sh +set -eu + +case "$*" in + "simctl list devices booted -j") + printf started > "$SERVE_SIM_TEST_QUERY_DIR/query-started" + while [ ! -e "$SERVE_SIM_TEST_QUERY_DIR/release-query" ]; do + sleep 0.02 + done + printf finished > "$SERVE_SIM_TEST_QUERY_DIR/query-finished" + ;; + "simctl list devices -j") ;; + *) + printf 'Refusing unexpected simulator command: %s\n' "$*" >&2 + exit 88 + ;; +esac + +printf '{"devices":{"test":[{"udid":"%s","state":"Booted"}]}}\n' "$SERVE_SIM_TEST_UDID" diff --git a/packages/serve-sim/src/__tests__/server-test-support.ts b/packages/serve-sim/src/__tests__/server-test-support.ts new file mode 100644 index 000000000..89d922713 --- /dev/null +++ b/packages/serve-sim/src/__tests__/server-test-support.ts @@ -0,0 +1,24 @@ +import { createServer } from "net"; +import { setTimeout as delay } from "timers/promises"; + +export async function freePort(): Promise { + const server = createServer(); + const ready = Promise.withResolvers(); + server.once("error", ready.reject); + server.listen(0, "127.0.0.1", ready.resolve); + await ready.promise; + const address = server.address(); + const closed = Promise.withResolvers(); + server.close((error) => error ? closed.reject(error) : closed.resolve()); + await closed.promise; + if (!address || typeof address === "string") throw new Error("failed to allocate port"); + return address.port; +} + +export async function waitFor(predicate: () => boolean, timeoutMs = 1_000, intervalMs = 5): Promise { + const deadline = Date.now() + timeoutMs; + while (!predicate()) { + if (Date.now() >= deadline) throw new Error("condition not reached"); + await delay(intervalMs); + } +} diff --git a/packages/serve-sim/src/__tests__/shutdown-watch-responsive.test.ts b/packages/serve-sim/src/__tests__/shutdown-watch-responsive.test.ts new file mode 100644 index 000000000..01ce232e9 --- /dev/null +++ b/packages/serve-sim/src/__tests__/shutdown-watch-responsive.test.ts @@ -0,0 +1,88 @@ +import { expect, test } from "bun:test"; +import { spawn, type ChildProcess } from "child_process"; +import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs"; +import { tmpdir } from "os"; +import { delimiter, join } from "path"; +import { freePort, waitFor } from "./server-test-support"; + +const udid = "00000000-0000-4000-8000-000000000102"; + +// The real CLI subprocess's watchdog cannot use the test process's fake clock. +test.skipIf(process.platform === "win32")("serves HTTP while the shutdown boot-state query is pending", async () => { + const root = mkdtempSync(join(tmpdir(), "serve-sim-shutdown-watch-")); + const bin = join(root, "bin"); + const started = join(root, "query-started"); + const finished = join(root, "query-finished"); + const release = join(root, "release-query"); + let child: ChildProcess | undefined; + let stderr = ""; + let exited = false; + const { promise: closed, resolve: resolveClosed } = Promise.withResolvers(); + const waitClosed = async (ms: number) => { + const timeout = Promise.withResolvers(); + const timer = setTimeout(timeout.resolve, ms); + try { + await Promise.race([closed, timeout.promise]); + } finally { + clearTimeout(timer); + } + }; + try { + mkdirSync(bin); + const xcrun = join(bin, "xcrun"); + copyFileSync(join(import.meta.dir, "fixtures/shutdown-watch-xcrun.sh"), xcrun); + chmodSync(xcrun, 0o700); + writeFileSync(join(bin, "open"), "#!/bin/sh\nexit 88\n", { mode: 0o700 }); + const env: NodeJS.ProcessEnv = { ...process.env, PATH: `${bin}${delimiter}${process.env.PATH ?? ""}`, TMPDIR: root, TMP: root, TEMP: root }; + for (const key of Object.keys(env)) { + if (key.startsWith("SERVE_SIM_") || ["NODE_OPTIONS", "NODE_PATH", "DEBUG"].includes(key)) delete env[key]; + } + env.SERVE_SIM_TEST_QUERY_DIR = root; + env.SERVE_SIM_TEST_UDID = udid; + const port = await freePort(); + child = spawn(process.execPath, [join(import.meta.dir, "../index.ts"), udid, + "--port", String(port), "--host", "127.0.0.1", "--exit-on-simulator-shutdown"], { + env, stdio: ["ignore", "ignore", "pipe"], + }); + child.stderr?.on("data", (data) => { stderr += data; }); + child.once("close", () => { exited = true; resolveClosed(); }); + child.once("error", () => { exited = true; resolveClosed(); }); + const stateFile = join(root, "serve-sim", `server-${udid}.json`); + await waitFor(() => { + if (exited) throw new Error("CLI exited before readiness: " + stderr); + return existsSync(stateFile); + }, 10_000, 20); + const state = JSON.parse(readFileSync(stateFile, "utf8")); + expect(state.pid).toBe(child.pid); + expect(state.port).toBe(port); + await waitFor(() => { + if (exited) throw new Error("CLI exited before its boot query: " + stderr); + return existsSync(started); + }, 10_000, 20); + expect(existsSync(finished)).toBe(false); + const response = await fetch(`http://127.0.0.1:${port}/__shutdown_watch_probe__`, { signal: AbortSignal.timeout(1_500) }); + await response.arrayBuffer(); + expect(response.status).toBe(404); + expect(existsSync(finished)).toBe(false); + } catch (error) { + throw new Error("CLI shutdown-watch probe failed: " + stderr, { cause: error }); + } finally { + try { + if (child) { + writeFileSync(release, "release"); + if (existsSync(started) && !exited) await waitFor(() => existsSync(finished), 3_500, 20); + } + } finally { + try { + if (child) { + if (!exited) child.kill("SIGTERM"); + await waitClosed(2_000); + if (!exited) child.kill("SIGKILL"); + await closed; + } + } finally { + rmSync(root, { recursive: true, force: true }); + } + } + } +}, 20_000); diff --git a/packages/serve-sim/src/index.ts b/packages/serve-sim/src/index.ts index f467133ba..10e5d0079 100755 --- a/packages/serve-sim/src/index.ts +++ b/packages/serve-sim/src/index.ts @@ -1,11 +1,12 @@ #!/usr/bin/env node import WebSocket from "ws"; import { Command, InvalidArgumentError } from "commander"; -import { execFileSync, execSync, spawn as nodeSpawn, type ChildProcess } from "child_process"; +import { execFile, execFileSync, execSync, spawn as nodeSpawn, type ChildProcess } from "child_process"; import { existsSync, mkdirSync, openSync, closeSync, readSync, readFileSync, statSync, unlinkSync, writeFileSync } from "fs"; import { createHash, randomBytes } from "crypto"; import { networkInterfaces } from "os"; import { dirname, join, resolve } from "path"; +import { promisify } from "util"; import { STATE_DIR, stateFileForDevice, @@ -93,6 +94,7 @@ import { redactHome } from "./diagnostics-redact"; // `import.meta.dir` is Bun-only; resolve once via fileURLToPath so the bundled // CLI works under plain `node` too. const __dirname = dirnameOf(import.meta.url); +const execFileAsync = promisify(execFile); // Stamped in at build time (see build.ts), mirroring __PREVIEW_HTML_B64__. In // the un-bundled dev run the define is absent, so fall back to reading the @@ -144,18 +146,11 @@ function inThisDeviceSet(state: ServerState): boolean { /** * Snapshot simctl's boot state for `--detach` reuse and the shutdown watch. - * Cached for 1 second so a flurry of lookups shares one `simctl` call. */ -let bootedSnapshot: { at: number; booted: Set | null } = { at: 0, booted: null }; -function getBootedUdids(): Set | null { - const now = Date.now(); - if (bootedSnapshot.booted && now - bootedSnapshot.at < 1000) { - return bootedSnapshot.booted; - } +async function queryBootedUdids(): Promise | null> { try { - const output = execFileSync("xcrun", simctlArguments(["list", "devices", "booted", "-j"]), { + const { stdout: output } = await execFileAsync("xcrun", simctlArguments(["list", "devices", "booted", "-j"]), { encoding: "utf-8", - stdio: ["ignore", "pipe", "pipe"], timeout: 3_000, }); const data = JSON.parse(output) as { @@ -167,7 +162,6 @@ function getBootedUdids(): Set | null { if (device.state === "Booted") booted.add(device.udid); } } - bootedSnapshot = { at: now, booted }; return booted; } catch { // simctl lookup failed (Xcode offline, etc.) — we can't prove the device @@ -177,6 +171,29 @@ function getBootedUdids(): Set | null { } } +let bootedSnapshot: Promise | null> | null = null; +let bootedSnapshotAt: number | null = null; + +/** Share in-flight lookups, then cache successful snapshots for 1 second. */ +function getBootedUdids(): Promise | null> { + if ( + bootedSnapshot && + (bootedSnapshotAt === null || Date.now() - bootedSnapshotAt < 1000) + ) { + return bootedSnapshot; + } + bootedSnapshotAt = null; + bootedSnapshot = queryBootedUdids().then((booted) => { + if (booted) { + bootedSnapshotAt = Date.now(); + } else { + bootedSnapshot = null; + } + return booted; + }); + return bootedSnapshot; +} + function readStateFile(file: string): ServerState | null { try { if (!existsSync(file)) { @@ -211,10 +228,10 @@ function readStateFile(file: string): ServerState | null { * different `--auth-token` (or none), or a different `--allow-exec` opt-in, * is never reused: that is an error. */ -function readReusableState(udid: string, allowExec: boolean): ServerState | null { +async function readReusableState(udid: string, allowExec: boolean): Promise { const state = readState(udid); if (!state) return null; - const action = classifyStaleState(state, getBootedUdids(), process.pid, resolveDeviceSet()); + const action = classifyStaleState(state, await getBootedUdids(), process.pid, resolveDeviceSet()); if (action === "keep") { const mismatch = reuseAuthMismatch(state, resolveAuthToken(undefined)) ?? reuseExecMismatch(state, allowExec); @@ -489,7 +506,7 @@ async function follow(devices: string[], startPort: number, quiet: boolean, allo for (const udid of udids) { // Return existing server if already running (and still bound to a booted sim) - const existing = readReusableState(udid, allowExec); + const existing = await readReusableState(udid, allowExec); if (existing) { if (!quiet) { const name = getDeviceName(udid) ?? udid; @@ -606,7 +623,7 @@ async function detach(devices: string[], startPort: number, allowExec: boolean): let port = startPort; for (const udid of udids) { - const existing = readReusableState(udid, allowExec); + const existing = await readReusableState(udid, allowExec); if (existing) { states.push(existing); continue; @@ -2117,10 +2134,7 @@ async function serve( // grid can boot another device without tearing down the HTTP server. if (exitOnSimulatorShutdown) { startSimulatorShutdownWatch(targetDevices, { - checkBooted: async () => { - bootedSnapshot = { at: 0, booted: null }; - return getBootedUdids(); - }, + checkBooted: queryBootedUdids, onExit: () => { const label = targetDevices.join(", "); console.error(