Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions e2e/helpers/cli.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

import { describe, expect, it } from "vitest";

import { withDaemon } from "./env.js";

describe("cliBackground firstStdoutLine", () => {
it("rejects with the exit code and stderr, not the timeout, when the process exits without a stdout line", async () => {
const env = await withDaemon();

await expect(env.cliBackground(["lease", "--bogus"]).firstStdoutLine(60_000)).rejects.toThrow(
/^simlock lease --bogus exited with code 2, signal null before printing a stdout line; stderr: .*Unknown option '--bogus'/,
);
});

it("rejects a call made after the process has already exited without a stdout line", async () => {
const env = await withDaemon();
const handle = env.cliBackground(["lease", "--bogus"]);
await handle.waitForExit();

await expect(handle.firstStdoutLine(60_000)).rejects.toThrow(/exited with code 2/);
});

it("resolves the line a process printed just before exiting, for a call made before or after the exit", async () => {
const env = await withDaemon();
const handle = env.cliBackground(["--help"]);
const beforeExit = handle.firstStdoutLine(60_000);

expect((await handle.waitForExit()).code).toBe(0);
await expect(beforeExit).resolves.toBe("Usage: simlock <command> [options]");
await expect(handle.firstStdoutLine(60_000)).resolves.toBe(
"Usage: simlock <command> [options]",
);
});

it("resolves a line printed after the process exited, once the pipe closes", async () => {
const env = await withDaemon();
const dir = mkdtempSync(join(tmpdir(), "late-stdout-"));
const preload = join(dir, "late-stdout.cjs");
writeFileSync(
preload,
`process.on("exit", () => {
require("node:child_process")
.spawn("sh", ["-c", "sleep 1; echo late line"], { detached: true, stdio: "inherit" })
.unref();
});`,
);
try {
const handle = env.cliBackground(["lease", "--bogus"], {
env: { NODE_OPTIONS: `--require ${preload}` },
});

await expect(handle.firstStdoutLine(60_000)).resolves.toBe("late line");
expect((await handle.waitForExit()).code).toBe(2);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});
33 changes: 22 additions & 11 deletions e2e/helpers/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,6 @@ export interface CliBackgroundHandle {
readonly pid: number | undefined;
}

/**
* Starts a `simlock` invocation that stays running (held-mode `lease`), for tests
* that need to observe progress, kill the process, or hold a lease across other
* assertions.
*/
export function cliBackground(
args: readonly string[],
env: NodeJS.ProcessEnv,
Expand All @@ -98,14 +93,15 @@ export function cliBackground(
let stdout = "";
let stderr = "";
const progress: unknown[] = [];
const stdoutWaiters: ((line: string) => void)[] = [];
const stdoutWaiters: { resolve(line: string): void; reject(error: Error): void }[] = [];
let firstLineSeen: string | undefined;
let exitedWithoutLine: Error | undefined;

child.stdout.on("data", (chunk: Buffer) => {
stdout += chunk.toString("utf8");
if (firstLineSeen === undefined && stdout.includes("\n")) {
firstLineSeen = stdout.slice(0, stdout.indexOf("\n"));
for (const waiter of stdoutWaiters.splice(0)) waiter(firstLineSeen);
for (const waiter of stdoutWaiters.splice(0)) waiter.resolve(firstLineSeen);
}
});
child.stderr.on("data", (chunk: Buffer) => {
Expand All @@ -126,7 +122,15 @@ export function cliBackground(
// attached after the fact never fires. That would time out as "process never
// exited" when it had in fact already exited.
const exited = new Promise<CliResult>((resolve) => {
child.once("close", (code) => {
// A process that dies before printing would otherwise surface only as a timeout, a minute
// later and without its stderr. "close", not "exit": it comes after the last stdout chunk,
// so a line printed just before exiting has already been seen and its waiters resolved. A
// failed spawn emits "close" too.
child.once("close", (code, signal) => {
exitedWithoutLine = new Error(
`simlock ${args.join(" ")} exited with code ${code}, signal ${signal} before printing a stdout line; stderr: ${stderr.trim() || "(empty)"}`,
);
for (const waiter of stdoutWaiters.splice(0)) waiter.reject(exitedWithoutLine);
resolve({ code, stdout, stderr, ...parseOutputs(stdout, stderr) });
});
});
Expand All @@ -137,13 +141,20 @@ export function cliBackground(
stdoutSoFar: () => stdout,
async firstStdoutLine(timeout = 30_000) {
if (firstLineSeen !== undefined) return firstLineSeen;
if (exitedWithoutLine !== undefined) throw exitedWithoutLine;
return new Promise<string>((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error(`Timed out after ${timeout}ms waiting for first stdout line`));
}, timeout);
stdoutWaiters.push((line) => {
clearTimeout(timer);
resolve(line);
stdoutWaiters.push({
resolve(line) {
clearTimeout(timer);
resolve(line);
},
reject(error) {
clearTimeout(timer);
reject(error);
},
});
});
},
Expand Down
40 changes: 37 additions & 3 deletions src/daemon/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
CryptoTokenSecrets,
FakeClock,
FakeSystemStats,
IpcError,
JsonLinesLogger,
MemoryFilesystem,
MemoryLogSink,
Expand Down Expand Up @@ -1023,6 +1024,32 @@ describe("DaemonServer", () => {
await holder.close();
});

it("drops a lease-lost push to a connection whose peer has hung up instead of leaving its failed write unhandled", async () => {
const connection = new BlockingConnection();
const harness = await createHarness({ host: new SingleConnectionHost(connection) });
await connection.request(
{ clientVersion: "test", protocolVersion: DAEMON_PROTOCOL_VERSION },
"hello",
);
const grant = await connection.request(
{ model: "iPhone 16", osVersion: "26.5", platform: "ios" },
"lease.request",
);
const unhandled: unknown[] = [];
const recordUnhandled = (reason: unknown) => unhandled.push(reason);
process.on("unhandledRejection", recordUnhandled);
try {
connection.hangUp();
await harness.engine.release(leaseIdOf(grant), "explicit");
await new Promise((resolve) => setImmediate(resolve));

expect(connection.frames.filter((frame) => frame.push === "lease-lost")).toHaveLength(1);
expect(unhandled).toEqual([]);
} finally {
process.off("unhandledRejection", recordUnhandled);
}
});

it("ignores lease-lost facts for leases with no currently connected holder without breaking the daemon", async () => {
const harness = await createHarness();
harness.eventBus.emit(
Expand Down Expand Up @@ -3047,11 +3074,11 @@ class SingleConnectionHost implements ConnectionHost {
async stop(): Promise<void> {}
}

/** One side of a connection whose writes complete only when this test says so. */
class BlockingConnection implements IpcConnection {
readonly closed = false;
readonly frames: Record<string, unknown>[] = [];
#blocked = false;
#hungUp = false;
#pending: Array<() => void> = [];
#dataListeners = new Set<(chunk: string) => void>();

Expand All @@ -3072,6 +3099,9 @@ class BlockingConnection implements IpcConnection {
for (const line of contents.split("\n")) {
if (line.trim() !== "") this.frames.push(JSON.parse(line) as Record<string, unknown>);
}
if (this.#hungUp) {
throw new IpcError("unknown", "This socket has been ended by the other party", "EPIPE");
}
if (!this.#blocked) return;
await new Promise<void>((resolve) => this.#pending.push(resolve));
}
Expand All @@ -3082,14 +3112,19 @@ class BlockingConnection implements IpcConnection {
this.#blocked = true;
}

/** From here on every write fails as a Node socket's does after its peer's FIN and before it is
* destroyed: `closed` is still false, and the write rejects with EPIPE. */
hangUp(): void {
this.#hungUp = true;
}

releaseAll(): void {
this.#blocked = false;
const pending = this.#pending;
this.#pending = [];
for (const resolve of pending) resolve();
}

/** Sends a request frame and waits for its reply, which arrives on `frames`. */
async request(payload: unknown, type: string, id = type): Promise<ServerFrame> {
for (const listener of this.#dataListeners) {
listener(`${JSON.stringify({ id, payload, type })}\n`);
Expand All @@ -3099,7 +3134,6 @@ class BlockingConnection implements IpcConnection {
}
}

/** A `FakeDriver` that claims the `simctl` wrapper, for the `device.exec` flows. */
function passthroughDriver(clock: FakeClock): FakeDriver {
return new FakeDriver({
availableOsVersions: ["26.5"],
Expand Down
8 changes: 7 additions & 1 deletion src/daemon/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1606,7 +1606,13 @@ function errorStack(error: unknown): string | undefined {
return error instanceof Error ? error.stack : undefined;
}

/**
* A frame for a peer that has gone is dropped, never rejected. Once the peer's FIN arrives the
* socket fails every write with EPIPE, but `closed` stays false until the socket is destroyed.
* Most pushes are fired without a catch, so a write in that window would reject unhandled and
* take the daemon down, failing every lease request still waiting.
*/
function writeFrame(socket: IpcConnection, frame: unknown): Promise<void> {
if (socket.closed) return Promise.resolve();
return socket.write(serializeFrame(frame));
return socket.write(serializeFrame(frame)).catch(() => undefined);
}
Loading