diff --git a/docs/CLI.md b/docs/CLI.md index da6ef3bee..ffbf72145 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -145,7 +145,7 @@ command starts it again) to bring the platform up. |---|---|---| | 0 | — | success (for a `lease` that stayed alive: the lease ended normally) | | 1 | `INTERNAL` | internal / unexpected error | -| 1 | `DAEMON_STARTUP_FAILED` | the daemon was started but did not accept connections before the startup timeout, or answered the handshake then closed before the CLI's startup status probe answered | +| 1 | `DAEMON_STARTUP_FAILED` | the daemon was started but did not accept connections before the startup timeout, or exited while starting (the message is the daemon's start error), or answered the handshake then closed before the CLI's startup status probe answered | | 1 | `PROVISION_FAILED` | creating a device for the request failed twice; the message is the driver's error | | 1 | `HISTORY_UNAVAILABLE` | `stats` while `history.db` could not be opened, so the usage figures cannot be read; the daemon's log says why | | 1 | `WORKER_UNREACHABLE` | the gateway cannot reach the worker this lease or request lives on (its uplink is down), or a worker named with `component install --worker` cannot be asked | @@ -2521,7 +2521,11 @@ Totals ## `simlock daemon ` -If a command auto-starts a daemon and it answers the handshake but closes +If a command auto-starts a daemon and that daemon exits before it accepts +connections, the command fails at once with `DAEMON_STARTUP_FAILED` and the +daemon's start error (`The daemon could not start: `, or the exit code +when it logged none); a daemon that exits because another one holds the socket +is not a failure, and the command goes on with that one. If it answers the handshake but closes before the CLI's startup status probe answers, the command reports `DAEMON_STARTUP_FAILED` (exit 1). The probe shares the launch timeout and runs before the command's operation, including after a rejected credential falls diff --git a/e2e/start-refusal.test.ts b/e2e/start-refusal.test.ts new file mode 100644 index 000000000..bb42016bf --- /dev/null +++ b/e2e/start-refusal.test.ts @@ -0,0 +1,25 @@ +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; + +import { withDaemon } from "./helpers/index.js"; + +describe("an auto-started daemon that refuses to start (#760)", () => { + it("simlock status prints DAEMON_STARTUP_FAILED with the daemon's start error, exit 1, in under 5 s", async () => { + const env = await withDaemon({ mode: "auto" }); + const stateJson = join(env.home, "state.json"); + await writeFile(stateJson, "{}\n", "utf8"); + + const startedAt = Date.now(); + const result = await env.cli(["status"]); + const elapsedMs = Date.now() - startedAt; + + expect(result.code, result.stderr).toBe(1); + const failure = JSON.parse(result.stderr.trim().split("\n").at(-1) ?? "{}") as { + error: { code: string; message: string }; + }; + expect(failure.error.code).toBe("DAEMON_STARTUP_FAILED"); + expect(failure.error.message).toContain(`The daemon could not start: Found ${stateJson}, `); + expect(elapsedMs).toBeLessThan(5_000); + }); +}); diff --git a/src/cli/AGENTS.md b/src/cli/AGENTS.md index c2a696ff7..305dbd7c3 100644 --- a/src/cli/AGENTS.md +++ b/src/cli/AGENTS.md @@ -63,7 +63,8 @@ Surface: [CLI.md](../../docs/CLI.md) — every command, flag and exit code. None, or a rejected one → an `agent` session and one stderr `notice` line. 3. **Auto-launch** (`AutoLaunchAdminConnector`) — when nothing listens: load the config first (a bad one fails on this stderr), launch the daemon detached, retry every 50 ms - for `DAEMON_STARTUP_TIMEOUT_MS`. After a launch, `status.get` probes the connection + for `DAEMON_STARTUP_TIMEOUT_MS`; a launched daemon that exits fails the command at once + with `startErrorFrom`'s text, unless another daemon answers a last connect. After a launch, `status.get` probes the connection before handing it to a command, within that same deadline. A connection loss during this probe becomes `DAEMON_STARTUP_FAILED`; a silent probe times out with that code and starts closing its client without waiting for the daemon to end its side. An answered probe ends the window, including a `starting` status: subsequent diff --git a/src/cli/environment.ts b/src/cli/environment.ts index 468ff5482..8bf6171cf 100644 --- a/src/cli/environment.ts +++ b/src/cli/environment.ts @@ -8,9 +8,11 @@ import type { SimlockAdminClient } from "../admin/index.js"; import type { ConfigOverrides, ModuleConfigEntry } from "../core/index.js"; import type { Clock, + DaemonExit, DaemonLauncher, Filesystem, IpcConnector, + LaunchedDaemon, ParentWatch, ParentWatchHandle, } from "../ports/index.js"; @@ -38,7 +40,11 @@ class AutoLaunchAdminConnector { if (!(await isUnavailable(error))) throw error; } await this.checkConfig(); - await this.launcher.launch(); + const launched = await this.launcher.launch(); + let exit: DaemonExit | undefined; + void launched.exited.then((value) => { + exit = value; + }); // why: the constant lives behind the ports barrel, which loads on the first connection that needs it. const { DAEMON_STARTUP_TIMEOUT_MS } = await import("../ports/index.js"); const deadline = this.clock.now() + DAEMON_STARTUP_TIMEOUT_MS; @@ -50,6 +56,8 @@ class AutoLaunchAdminConnector { } catch (error: unknown) { if (!(await isUnavailable(error))) throw error; lastError = error; + if (exit !== undefined) + return await this.connectAfterExit(launched, exit, resolveCredential); await new Promise((resolve) => this.clock.setTimer(50, resolve)); } } @@ -62,6 +70,22 @@ class AutoLaunchAdminConnector { ); } + private async connectAfterExit( + launched: LaunchedDaemon, + exit: DaemonExit, + resolveCredential: () => Promise, + ): Promise { + const output = await launched.readOutput().catch(() => ""); + try { + return await this.finishConnection(await this.connectClient(resolveCredential)); + } catch (error: unknown) { + if (!(await isUnavailable(error))) throw error; + } + const { SimlockError } = await import("../contract/index.js"); + const { startErrorFrom } = await import("../ports/index.js"); + throw new SimlockError("DAEMON_STARTUP_FAILED", "transport", startErrorFrom(exit, output), {}); + } + private async finishConnection(client: SimlockAdminClient): Promise { if (this.startupDeadline === undefined) return client; const { isSimlockError, SimlockError } = await import("../contract/index.js"); diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 62314630e..3b5dfff03 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1486,6 +1486,141 @@ describe("CLI: auto-launch's failed start (#672)", () => { }); }); +describe("CLI: auto-launch's daemon that exits while starting (#760)", () => { + it("status fails at once with the daemon's start error when the launched daemon exits with a fatal line", async () => { + const clock = new FakeClock(0); + const fatal = JSON.stringify({ + message: "Daemon failed to start", + fields: { message: "Found /simlock/state.json, remove it" }, + }); + const launcher = new FakeDaemonLauncher(undefined, { + exit: { code: 1, signal: null }, + output: `older line\n${fatal}\n`, + }); + const output = outputCapture({ + filesystem: new MemoryFilesystem(), + clock, + systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte }), + ipc: new MemoryIpcTransport(), + launcher, + daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, + }); + let settled = false; + const exitCode = runCli(["status"], output.environmentWith()).then((code) => { + settled = true; + return code; + }); + for (let tick = 0; tick < 100 && !settled; tick += 1) { + clock.advance(50); + await settle(); + await settle(); + } + expect(settled, "status had not settled by 5 s").toBe(true); + expect(clock.now()).toBeLessThan(20_000); + expect(await exitCode).toBe(1); + expect(JSON.parse(output.stderr)).toEqual({ + error: { + code: "DAEMON_STARTUP_FAILED", + message: "The daemon could not start: Found /simlock/state.json, remove it", + }, + }); + }); + + it("status names the exit code when the launched daemon's output cannot be read", async () => { + const clock = new FakeClock(0); + const launcher = { + launch: async () => ({ + exited: Promise.resolve({ code: 3, signal: null }), + readOutput: async (): Promise => { + throw new Error("daemon.log was replaced"); + }, + }), + }; + const output = outputCapture({ + filesystem: new MemoryFilesystem(), + clock, + systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte }), + ipc: new MemoryIpcTransport(), + launcher, + daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, + }); + let settled = false; + const exitCode = runCli(["status"], output.environmentWith()).then((code) => { + settled = true; + return code; + }); + for (let tick = 0; tick < 100 && !settled; tick += 1) { + clock.advance(50); + await settle(); + await settle(); + } + expect(settled, "status had not settled by 5 s").toBe(true); + expect(await exitCode).toBe(1); + expect(JSON.parse(output.stderr).error.message).toBe( + "The daemon exited with code 3 while starting; see `simlock daemon logs`", + ); + }); +}); + +describe("CLI: auto-launch's daemon that lost the socket to another daemon (#760)", () => { + it("status goes on with the daemon that holds the socket when the launched daemon exits already running", async () => { + const filesystem = new MemoryFilesystem(); + const clock = new FakeClock(0); + // why: the winner is not listening yet at the first poll after the launch, so the loop reaches + // the launched daemon's exit before it finds the winner. + class LateWinnerTransport extends MemoryIpcTransport { + connects = 0; + override async connect(endpoint: string): ReturnType { + this.connects += 1; + if (this.connects === 2) { + throw new IpcError("endpoint-not-found", `No IPC endpoint at ${endpoint}`, undefined); + } + return super.connect(endpoint); + } + } + const ipcTransport = new LateWinnerTransport(); + const launcher = new FakeDaemonLauncher( + async () => { + await startInMemoryDaemon({ + adminTokenPath: "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/simlock/admin.token", + filesystem, + ipcTransport, + socketPath: "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/simlock/daemon.sock", + }); + }, + { + exit: { code: 1, signal: null }, + output: `${JSON.stringify({ + message: "Daemon failed to start", + fields: { message: "Simlock daemon is already running at /simlock/daemon.sock" }, + })}\n`, + }, + ); + const output = outputCapture({ + filesystem, + clock, + systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte }), + ipc: ipcTransport, + launcher, + daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, + }); + let settled = false; + const exitCode = runCli(["status"], output.environmentWith()).then((code) => { + settled = true; + return code; + }); + for (let tick = 0; tick < 100 && !settled; tick += 1) { + clock.advance(50); + await settle(); + await settle(); + } + expect(settled, "status had not settled by 5 s").toBe(true); + expect(await exitCode).toBe(0); + expect(output.stderr).not.toContain("DAEMON_STARTUP_FAILED"); + expect(ipcTransport.connects).toBeGreaterThanOrEqual(3); + }); +}); + describe("CLI: auto-launch's handshake cut short by the launched daemon (#684)", () => { it.each([ { closeAfter: "hello", rejectedCredential: false }, diff --git a/src/mcp/AGENTS.md b/src/mcp/AGENTS.md index 396ff3841..addfc4d78 100644 --- a/src/mcp/AGENTS.md +++ b/src/mcp/AGENTS.md @@ -42,6 +42,8 @@ Surface: [CLI.md](../../docs/CLI.md#simlock-mcp). - a tool call → `connectWithAutoLaunch`: launches the daemon only when nothing listens (`connection-refused`, `endpoint-not-found`), retries every 50 ms for `startupTimeoutMs` (default `DAEMON_STARTUP_TIMEOUT_MS`), else `DAEMON_STARTUP_FAILED`; + a launched daemon that exits fails at once with `startErrorFrom`'s text, unless another + daemon answers a last connect; - the renew timer → `connectToRunningDaemon`: never launches. The lease survives either way: the daemon released nothing. 7. **End** — stdin EOF, `SIGINT`/`SIGTERM` or transport close → `McpSession.close`: stop diff --git a/src/mcp/connect.test.ts b/src/mcp/connect.test.ts index 2684e2193..2adb9679c 100644 --- a/src/mcp/connect.test.ts +++ b/src/mcp/connect.test.ts @@ -2,7 +2,7 @@ // default startup deadline it shares with the CLI's own loop (#663). import { describe, expect, it } from "vitest"; -import { FakeClock, FakeDaemonLauncher, MemoryIpcTransport } from "../ports/index.js"; +import { FakeClock, FakeDaemonLauncher, IpcError, MemoryIpcTransport } from "../ports/index.js"; import { connectWithAutoLaunch } from "./connect.js"; const settle = (): Promise => new Promise((resolve) => setImmediate(resolve)); @@ -57,3 +57,106 @@ describe("MCP: auto-launch's startup deadline (#663)", () => { expect(launcher.launches).toBe(1); }); }); + +describe("MCP: auto-launch's daemon that exits while starting (#760)", () => { + const fatal = (message: string): string => + `${JSON.stringify({ message: "Daemon failed to start", fields: { message } })}\n`; + + // why: the winner is not listening yet at the first poll after the launch, so the loop reaches + // the launched daemon's exit before it finds the winner. + class LateWinnerTransport extends MemoryIpcTransport { + connects = 0; + override async connect(endpoint: string): ReturnType { + this.connects += 1; + if (this.connects === 2) { + throw new IpcError("endpoint-not-found", `No IPC endpoint at ${endpoint}`, undefined); + } + return super.connect(endpoint); + } + } + + async function answerHello(ipc: MemoryIpcTransport): Promise { + await ipc.listen("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/simlock/daemon.sock", (connection) => { + connection.onData((chunk) => { + for (const line of chunk.split("\n").filter((value) => value !== "")) { + const frame = JSON.parse(line) as { id: number; type: string }; + if (frame.type !== "hello") continue; + void connection.write( + `${JSON.stringify({ + id: frame.id, + ok: true, + payload: { + daemonProtocolRange: { max: 3, min: 3 }, + principal: "agent-1", + protocolVersion: 3, + role: "agent", + version: "0.3.0", + }, + })}\n`, + ); + } + }); + }); + } + + it("rejects with the start error as soon as the launched daemon exits, and connects when another daemon answers", async () => { + const outcome = async (message: string, winner: boolean) => { + const clock = new FakeClock(0); + const ipc = new LateWinnerTransport(); + const launcher = new FakeDaemonLauncher(winner ? () => answerHello(ipc) : undefined, { + exit: { code: 1, signal: null }, + output: fatal(message), + }); + const result = await Promise.race([ + connectWithAutoLaunch({ + clock, + ipc, + launcher, + principal: "agent-1", + socketPath: "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/simlock/daemon.sock", + }).then( + (client) => `connected as ${client.role}`, + (error: unknown) => `${(error as { code: string }).code}: ${(error as Error).message}`, + ), + settle() + .then(settle) + .then(settle) + .then(() => "still waiting"), + ]); + return { result, elapsed: clock.now() }; + }; + expect({ + refused: await outcome("Found state.json", false), + raced: await outcome("Simlock daemon is already running", true), + }).toEqual({ + refused: { + result: "DAEMON_STARTUP_FAILED: The daemon could not start: Found state.json", + elapsed: 0, + }, + raced: { result: "connected as agent", elapsed: 0 }, + }); + }); + + it("names the exit code when the launched daemon's output cannot be read", async () => { + const clock = new FakeClock(0); + const launcher = { + launch: async () => ({ + exited: Promise.resolve({ code: 3, signal: null }), + readOutput: async (): Promise => { + throw new Error("daemon.log was replaced"); + }, + }), + }; + const result = await connectWithAutoLaunch({ + clock, + ipc: new MemoryIpcTransport(), + launcher, + principal: "agent-1", + socketPath: "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/simlock/daemon.sock", + }).then( + () => "connected", + (error: unknown) => (error as Error).message, + ); + expect(result).toBe("The daemon exited with code 3 while starting; see `simlock daemon logs`"); + }); +}); diff --git a/src/mcp/connect.ts b/src/mcp/connect.ts index a3b3f9f06..983b1e581 100644 --- a/src/mcp/connect.ts +++ b/src/mcp/connect.ts @@ -17,9 +17,12 @@ import { import { DAEMON_STARTUP_TIMEOUT_MS, IpcError, + startErrorFrom, type Clock, + type DaemonExit, type DaemonLauncher, type IpcConnector, + type LaunchedDaemon, } from "../ports/index.js"; /** What it takes to reach a daemon that is already listening -- no launcher anywhere in it, @@ -53,7 +56,11 @@ export async function connectWithAutoLaunch( } catch (error: unknown) { if (!isUnavailable(error)) throw error; } - await options.launcher.launch(); + const launched = await options.launcher.launch(); + let exit: DaemonExit | undefined; + void launched.exited.then((value) => { + exit = value; + }); const deadline = options.clock.now() + (options.startupTimeoutMs ?? DAEMON_STARTUP_TIMEOUT_MS); let lastError: unknown; while (options.clock.now() < deadline) { @@ -62,6 +69,7 @@ export async function connectWithAutoLaunch( } catch (error: unknown) { if (!isUnavailable(error)) throw error; lastError = error; + if (exit !== undefined) return await connectAfterExit(options, launched, exit); await delay(options.clock, options.retryIntervalMs ?? 50); } } @@ -73,6 +81,20 @@ export async function connectWithAutoLaunch( ); } +async function connectAfterExit( + options: ConnectToRunningDaemonOptions, + launched: LaunchedDaemon, + exit: DaemonExit, +): Promise { + const output = await launched.readOutput().catch(() => ""); + try { + return await connectToRunningDaemon(options); + } catch (error: unknown) { + if (!isUnavailable(error)) throw error; + } + throw new SimlockError("DAEMON_STARTUP_FAILED", "transport", startErrorFrom(exit, output), {}); +} + /** * Connects only to a daemon that is already listening, and never launches one -- which is * exactly `connectWithAutoLaunch` minus its one extra power, so the latter is written in terms diff --git a/src/ports/AGENTS.md b/src/ports/AGENTS.md index 7f163dce5..5537d5cec 100644 --- a/src/ports/AGENTS.md +++ b/src/ports/AGENTS.md @@ -15,7 +15,7 @@ Uses: nothing from other components. Imported by: every component that touches t | (wrapper) | `logging-process-runner.ts` | `LoggingProcessRunner` | — | One `process` log line per command, at `debug` only | | `ProcessSupervisor` | `process-supervisor.ts` | `NodeProcessSupervisor` | `FakeProcessSupervisor` | Is a pid alive; signal it | | `ParentWatch` | `parent-watch.ts` | `NodeParentWatch` | `FakeParentWatch` | Call once when a pid exits (polls) | -| `DaemonLauncher` | `daemon-launcher.ts` | `NodeDaemonLauncher` | `FakeDaemonLauncher` | Detached daemon, its log, `DAEMON_STARTUP_TIMEOUT_MS` | +| `DaemonLauncher` | `daemon-launcher.ts` | `NodeDaemonLauncher` | `FakeDaemonLauncher` | Detached daemon, its log, `DAEMON_STARTUP_TIMEOUT_MS`; `launch()` answers a `LaunchedDaemon` (`exited`, `readOutput` of the log since the launch); `startErrorFrom` | | `IpcConnector`, `IpcListenerFactory` | `ipc.ts` | `NodeIpcTransport` | `MemoryIpcTransport` | The daemon's unix socket | | `UplinkConnector`, `UplinkListenerFactory` | `uplink.ts` | `WebSocketUplinkConnector`, `WebSocketUplinkListenerFactory` | `MemoryUplinkTransport` | A worker's uplink to its gateway | | `Logger`, `LogSink` | `logger.ts` | `JsonLinesLogger`, `NodeFileLogSink` | `NoopLogger`, `MemoryLogSink` | JSON-line logs, `child(module)`, rotation | diff --git a/src/ports/daemon-launcher.test.ts b/src/ports/daemon-launcher.test.ts index 668260437..9bb031865 100644 --- a/src/ports/daemon-launcher.test.ts +++ b/src/ports/daemon-launcher.test.ts @@ -1,9 +1,11 @@ import { describe, expect, it } from "vitest"; -import { mkdtemp, readFile, readdir, rm, stat } from "node:fs/promises"; +import { spawn } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { NodeDaemonLauncher } from "./daemon-launcher.js"; +import { NodeDaemonLauncher, startErrorFrom } from "./daemon-launcher.js"; describe("NodeDaemonLauncher", () => { it("rejects asynchronous spawn failures", async () => { @@ -94,3 +96,147 @@ describe("NodeDaemonLauncher", () => { } }); }); + +describe("NodeDaemonLauncher's LaunchedDaemon", () => { + it("gives the exit code and only the log bytes written since the launch, across a rotation too", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock-launcher-")); + const logPath = join(directory, "daemon.log"); + const older = `${JSON.stringify({ message: "Daemon failed to start", fields: { message: "older" } })}\n`; + const launch = async (script: string) => { + await rm(logPath, { force: true }); + await rm(`${logPath}.1`, { force: true }); + await writeFile(logPath, older); + const launched = await new NodeDaemonLauncher({ + args: ["-e", script, logPath], + command: process.execPath, + logPath, + simlockHome: directory, + }).launch(); + return { exit: await launched.exited, output: await launched.readOutput() }; + }; + try { + const plain = await launch("console.log('newer'); process.exit(1)"); + const rotated = await launch( + "const fs = require('node:fs'); const p = process.argv[1]; fs.renameSync(p, p + '.1'); console.log('tail'); fs.writeFileSync(p, 'fatal\\n'); process.exit(2)", + ); + expect({ plain, rotated }).toEqual({ + plain: { exit: { code: 1, signal: null }, output: "newer\n" }, + rotated: { exit: { code: 2, signal: null }, output: "tail\nfatal\n" }, + }); + } finally { + await rm(directory, { force: true, recursive: true }); + } + }); + + it("refuses to read the log when neither file is the one the daemon was launched into", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock-launcher-")); + const logPath = join(directory, "daemon.log"); + try { + await writeFile(logPath, "older\n"); + const launched = await new NodeDaemonLauncher({ + args: [ + "-e", + "require('node:fs').rmSync(process.argv[1]); require('node:fs').writeFileSync(process.argv[1], 'x'); require('node:fs').writeFileSync(process.argv[1] + '.1', 'y')", + logPath, + ], + command: process.execPath, + logPath, + simlockHome: directory, + }).launch(); + await launched.exited; + await expect(launched.readOutput()).rejects.toThrow("daemon.log was replaced"); + } finally { + await rm(directory, { force: true, recursive: true }); + } + }); +}); + +describe("NodeDaemonLauncher in a parent that awaits nothing", () => { + it("lets the parent process exit while the launched daemon keeps running", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock-launcher-")); + const launcherModule = fileURLToPath(new URL("./daemon-launcher.ts", import.meta.url)); + const parentScript = ` + const { NodeDaemonLauncher } = await import(${JSON.stringify(launcherModule)}); + const launcher = new NodeDaemonLauncher({ + args: ["-e", "console.log(process.pid); setTimeout(() => {}, 30000)"], + command: process.execPath, + logPath: ${JSON.stringify(join(directory, "daemon.log"))}, + simlockHome: ${JSON.stringify(directory)}, + }); + await launcher.launch(); + `; + const parent = spawn( + process.execPath, + ["--experimental-transform-types", "--input-type=module", "-e", parentScript], + { stdio: "ignore" }, + ); + let childPid: number | undefined; + try { + const outcome = await Promise.race([ + new Promise((resolve) => parent.once("exit", () => resolve("parent exited"))), + new Promise((resolve) => setTimeout(() => resolve("parent still running"), 8000)), + ]); + expect(outcome).toBe("parent exited"); + await expect + .poll(async () => (await readFile(join(directory, "daemon.log"), "utf8")).trim()) + .toMatch(/^\d+$/); + childPid = Number((await readFile(join(directory, "daemon.log"), "utf8")).trim()); + expect(() => process.kill(childPid as number, 0)).not.toThrow(); + } finally { + parent.kill(); + if (childPid !== undefined) process.kill(childPid); + await rm(directory, { force: true, recursive: true }); + } + // why: the 8 s guard above must be able to fire before vitest's own 5 s default does. + }, 20_000); +}); + +describe("startErrorFrom", () => { + it("names the last fatal line's message, else the exit code or signal", () => { + const fatal = (message: string): string => + JSON.stringify({ message: "Daemon failed to start", fields: { message } }); + const info = JSON.stringify({ message: "Daemon listening", fields: { message: "ready" } }); + const exit1 = { code: 1, signal: null }; + const cases = [ + { + label: "the fatal line alone", + exit: exit1, + output: `${fatal("boom")}\n`, + error: "The daemon could not start: boom", + }, + { + label: "the fatal line after other lines", + exit: exit1, + output: `${info}\n${fatal("boom")}\n`, + error: "The daemon could not start: boom", + }, + { + label: "two fatal lines", + exit: exit1, + output: `${fatal("first")}\n${fatal("second")}\n`, + error: "The daemon could not start: second", + }, + { + label: "no fatal line, code 1", + exit: exit1, + output: `${info}\n`, + error: "The daemon exited with code 1 while starting; see `simlock daemon logs`", + }, + { + label: "no fatal line, SIGKILL", + exit: { code: null, signal: "SIGKILL" }, + output: "", + error: "The daemon exited with code SIGKILL while starting; see `simlock daemon logs`", + }, + { + label: "a non-JSON line before the fatal line", + exit: exit1, + output: `not json\n${fatal("boom")}\n`, + error: "The daemon could not start: boom", + }, + ]; + expect(cases.map((c) => ({ label: c.label, error: startErrorFrom(c.exit, c.output) }))).toEqual( + cases.map((c) => ({ label: c.label, error: c.error })), + ); + }); +}); diff --git a/src/ports/daemon-launcher.ts b/src/ports/daemon-launcher.ts index 930a345b6..ef3d5033e 100644 --- a/src/ports/daemon-launcher.ts +++ b/src/ports/daemon-launcher.ts @@ -1,10 +1,44 @@ import { spawn } from "node:child_process"; -import { mkdir, open } from "node:fs/promises"; +import { mkdir, open, readFile, stat } from "node:fs/promises"; import { dirname } from "node:path"; /** Starts the detached daemon owned by the operating system rather than the CLI. */ export interface DaemonLauncher { - launch(): Promise; + launch(): Promise; +} + +export interface DaemonExit { + readonly code: number | null; + readonly signal: string | null; +} + +export interface LaunchedDaemon { + readonly exited: Promise; + readOutput(): Promise; +} + +export function startErrorFrom(exit: DaemonExit, output: string): string { + const lines = output.split("\n"); + for (let index = lines.length - 1; index >= 0; index -= 1) { + const message = fatalMessage(lines[index] ?? ""); + if (message !== undefined) return `The daemon could not start: ${message}`; + } + return `The daemon exited with code ${String(exit.code ?? exit.signal)} while starting; see \`simlock daemon logs\``; +} + +function fatalMessage(line: string): string | undefined { + let record: unknown; + try { + record = JSON.parse(line); + } catch { + return undefined; + } + if (typeof record !== "object" || record === null) return undefined; + const { message, fields } = record as { message?: unknown; fields?: unknown }; + if (message !== "Daemon failed to start") return undefined; + if (typeof fields !== "object" || fields === null) return undefined; + const detail = (fields as { message?: unknown }).message; + return typeof detail === "string" ? detail : undefined; } /** @@ -35,12 +69,14 @@ export interface NodeDaemonLauncherOptions { export class NodeDaemonLauncher implements DaemonLauncher { constructor(private readonly options: NodeDaemonLauncherOptions) {} - async launch(): Promise { + async launch(): Promise { await mkdir(dirname(this.options.logPath), { recursive: true }); // why: 0600 at creation, like the other files that hold secrets or state under the home: // this `open` is what first creates `daemon.log` for an auto-launched daemon -- the daemon's // own sink only appends to the file this one made. const log = await open(this.options.logPath, "a", 0o600); + const { ino, size } = await log.stat(); + const logPath = this.options.logPath; try { const child = spawn(this.options.command, this.options.args, { detached: true, @@ -50,11 +86,15 @@ export class NodeDaemonLauncher implements DaemonLauncher { env: { ...process.env, SIMLOCK_HOME: this.options.simlockHome }, stdio: ["ignore", log.fd, log.fd], }); + const exited = new Promise((resolve) => { + child.once("exit", (code, signal) => resolve({ code, signal })); + }); await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); }); child.unref(); + return { exited, readOutput: () => readLogSince(logPath, ino, size) }; } finally { await log.close(); } @@ -64,10 +104,34 @@ export class NodeDaemonLauncher implements DaemonLauncher { export class FakeDaemonLauncher implements DaemonLauncher { launches = 0; - constructor(private readonly onLaunch: () => Promise | void = () => undefined) {} + constructor( + private readonly onLaunch: () => Promise | void = () => undefined, + private readonly result: { readonly exit?: DaemonExit; readonly output?: string } = {}, + ) {} - async launch(): Promise { + async launch(): Promise { this.launches += 1; await this.onLaunch(); + const { exit, output = "" } = this.result; + return { + exited: exit === undefined ? new Promise(() => undefined) : Promise.resolve(exit), + readOutput: async () => output, + }; + } +} + +const MAX_OUTPUT_BYTES = 64 * 1024; + +// why: `NodeFileLogSink` rotates by renaming the log to `.1`, so the bytes written since +// the launch can sit in either file; the inode noted at launch says which one is the old log. +async function readLogSince(logPath: string, ino: number, size: number): Promise { + const chunks: Buffer[] = []; + if ((await stat(logPath)).ino === ino) { + chunks.push((await readFile(logPath)).subarray(size)); + } else { + const rotatedPath = `${logPath}.1`; + if ((await stat(rotatedPath)).ino !== ino) throw new Error("daemon.log was replaced"); + chunks.push((await readFile(rotatedPath)).subarray(size), await readFile(logPath)); } + return Buffer.concat(chunks).subarray(-MAX_OUTPUT_BYTES).toString("utf8"); } diff --git a/src/ports/index.ts b/src/ports/index.ts index f4ae86dea..6fab33e3c 100644 --- a/src/ports/index.ts +++ b/src/ports/index.ts @@ -17,9 +17,12 @@ export { } from "./paths.js"; export { DAEMON_STARTUP_TIMEOUT_MS, + type DaemonExit, type DaemonLauncher, FakeDaemonLauncher, + type LaunchedDaemon, NodeDaemonLauncher, + startErrorFrom, } from "./daemon-launcher.js"; export { type IpcConnection,