From 536f23f0b02f9b952ddfc605abec1550374cc967 Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Wed, 18 Nov 2026 12:41:41 -0800 Subject: [PATCH] Never kill a desktop server that is still starting The desktop app and the bb-app launcher each gave the server 60 seconds to answer /health, then stopped it. The server runs migrate(db) before it listens, so a long migration on a big bb.db or a starved host was killed, rolled back, and failed again on every launch. Both now wait without a deadline while the process lives. Desktop shows "Still starting bb" after 10 seconds, and fails only when bb-app exits, offering Try again and Choose server. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/README.md | 7 + apps/desktop/src/main.ts | 117 +++++++------ apps/desktop/src/owned-runtime-startup.ts | 41 +++++ apps/desktop/src/server-probe.ts | 45 +++-- apps/desktop/src/types.ts | 3 +- .../test/owned-runtime-startup.test.ts | 164 ++++++++++++++++++ apps/desktop/test/server-probe.test.ts | 2 +- packages/bb-app/src/launcher.ts | 31 ++-- .../test/server-health-identity.test.ts | 86 ++++++++- 9 files changed, 396 insertions(+), 100 deletions(-) create mode 100644 apps/desktop/src/owned-runtime-startup.ts create mode 100644 apps/desktop/test/owned-runtime-startup.test.ts diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 0de609e59db..df5d5abe789 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -463,6 +463,13 @@ npx bb-app@latest pnpm exec turbo run dev --filter=@bb/desktop ``` +When the app starts its own `bb-app`, it waits for the server with no deadline +for as long as that process runs: the server upgrades its database before it +listens, and that can take minutes on a large `bb.db` or a busy computer. After +10 seconds the window shows "Still starting bb". The `bb-app` launcher likewise +waits for its server child without a deadline. Startup fails only when the +process exits, and that screen offers **Try again** and **Choose server…**. + The desktop supervisor handles normal quits plus `SIGINT` and `SIGTERM`, and it writes a PID file so the next launch can reap a stale Electron-owned `bb-app` launcher. Hard crashes such as process aborts, segfaults, or kernel-level kills diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 244453b90d8..38014cfe8c0 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -107,11 +107,11 @@ import { reapStaleOwnedRuntime, writeOwnedRuntimePidFile, } from "./owned-runtime-supervisor.js"; +import { waitForOwnedRuntimeStartup } from "./owned-runtime-startup.js"; import { probeBbServer, waitForCompatibleServer, type CompatibleServerProbeResult, - type ServerProbeResult, } from "./server-probe.js"; import { loadRemoteServerPage } from "./remote-server-load.js"; import { @@ -291,8 +291,9 @@ import { ATTACH_PROBE_TIMEOUT_MS, DEFAULT_BB_SERVER_URL, PROCESS_LOG_LINE_LIMIT, + MACHINE_READY_TIMEOUT_MS, + OWNED_RUNTIME_SLOW_START_NOTICE_MS, STARTUP_POLL_INTERVAL_MS, - STARTUP_TIMEOUT_MS, type RuntimeOwnership, type WindowStateKey, } from "./types.js"; @@ -359,20 +360,6 @@ interface LoadLogViewerWindowArgs { preloadPath: string; } -type StartupRaceResult = - | ProcessExitedStartupRaceResult - | ServerProbeStartupRaceResult; - -interface ProcessExitedStartupRaceResult { - exit: BbAppProcessExit; - kind: "process-exited"; -} - -interface ServerProbeStartupRaceResult { - kind: "server-probe"; - result: ServerProbeResult; -} - interface ResolveDataDirFromEnvArgs { env: NodeJS.ProcessEnv; homeDir: string; @@ -2205,17 +2192,33 @@ async function loadWindowUrl(args: LoadWindowUrlArgs): Promise { await desktopWindowFactory.loadUrl({ url: args.url }); } +const LOADING_VIEW_URL = createLocalViewUrl({ + viewModel: { + kind: "loading", + message: "Starting local services and opening the bb workspace.", + title: "Opening bb", + }, +}); + +const SLOW_START_VIEW_URL = createLocalViewUrl({ + viewModel: { + kind: "loading", + message: + "bb may be upgrading its data after an update. On a large database or a busy computer this can take several minutes. bb opens when it is ready.", + title: "Still starting bb", + }, +}); + async function loadLoadingView(): Promise { bbAppLoaded = false; - await loadWindowUrl({ - url: createLocalViewUrl({ - viewModel: { - kind: "loading", - message: "Starting local services and opening the bb workspace.", - title: "Opening bb", - }, - }), - }); + await loadWindowUrl({ url: LOADING_VIEW_URL }); +} + +async function loadSlowStartView(): Promise { + if (currentWindowUrl !== LOADING_VIEW_URL) { + return; + } + await loadWindowUrl({ url: SLOW_START_VIEW_URL }); } async function loadWindowsInstallerWaitView(): Promise { @@ -2240,7 +2243,7 @@ async function loadStartupError(args: LoadStartupErrorArgs): Promise { await loadActionView({ ...args, details: - args.actions.length === 0 + args.actions.length === 0 || args.logs.length > 0 ? `${args.details} Logs are under ${formatLogDirectory()}/.` : args.details, }); @@ -2609,6 +2612,11 @@ async function spawnOwnedRuntime( return { bbProcess, runtime }; } +const OWNED_RUNTIME_EXIT_ACTIONS: StartupAction[] = [ + { id: "retry", label: "Try again" }, + { id: "choose-server", label: "Choose server…" }, +]; + function reportOwnedRuntimeExit({ bbProcess, runtime }: OwnedRuntime): void { void bbProcess.exit.then((exit) => { if (quitting || currentRuntime !== runtime) { @@ -2626,7 +2634,7 @@ function reportOwnedRuntimeExit({ bbProcess, runtime }: OwnedRuntime): void { exit, )}.`, logs: bbProcess.logs.text(), - actions: [], + actions: OWNED_RUNTIME_EXIT_ACTIONS, title: "bb stopped", }); }); @@ -2656,18 +2664,23 @@ async function waitForWindowsInstallerToFinish(): Promise { return result === "finished" && !quitting; } -async function waitForOwnedRuntimeReady(bbProcess: BbAppProcess): Promise { +async function waitForOwnedRuntimeReady( + bbProcess: BbAppProcess, +): Promise { let timer: NodeJS.Timeout | undefined; const result = await Promise.race([ bbProcess.ready.then(() => "ready" as const), new Promise<"timed-out">((resolveTimeout) => { - timer = setTimeout(() => resolveTimeout("timed-out"), STARTUP_TIMEOUT_MS); + timer = setTimeout( + () => resolveTimeout("timed-out"), + MACHINE_READY_TIMEOUT_MS, + ); }), ]); clearTimeout(timer); if (result === "timed-out") { desktopLogger.warn( - `[desktop] bb-app did not report this computer connected within ${STARTUP_TIMEOUT_MS}ms; opening bb anyway`, + `[desktop] bb-app did not report this computer connected within ${MACHINE_READY_TIMEOUT_MS}ms; opening bb anyway`, ); } } @@ -2678,49 +2691,51 @@ async function startOwnedRuntime( const ownedRuntime = await spawnOwnedRuntime(args); const { bbProcess, runtime } = ownedRuntime; - const raceResult = await Promise.race([ - waitForCompatibleServer({ - intervalMs: STARTUP_POLL_INTERVAL_MS, - serverUrl: args.serverUrl, - timeoutMs: STARTUP_TIMEOUT_MS, - }).then(async (result) => { + const startup = await waitForOwnedRuntimeStartup({ + exit: bbProcess.exit, + onSlowStart: () => { + desktopLogger.info( + `[desktop] bb-app is still starting after ${OWNED_RUNTIME_SLOW_START_NOTICE_MS}ms; waiting for it while the process runs`, + ); + void loadSlowStartView(); + }, + slowStartNoticeMs: OWNED_RUNTIME_SLOW_START_NOTICE_MS, + waitForServer: async (signal) => { + const result = await waitForCompatibleServer({ + intervalMs: STARTUP_POLL_INTERVAL_MS, + serverUrl: args.serverUrl, + signal, + }); if (result.kind === "compatible") { await waitForOwnedRuntimeReady(bbProcess); } - return { kind: "server-probe", result }; - }), - bbProcess.exit.then((exit) => ({ - exit, - kind: "process-exited", - })), - ]); + return result; + }, + }); - if (raceResult.kind === "process-exited") { + if (startup.kind === "process-exited") { setCurrentRuntime(null); if (await waitForWindowsInstallerToFinish()) { return startOwnedRuntime(args); } await loadStartupError({ details: `bb-app exited before the server was ready with ${formatExitResult( - raceResult.exit, + startup.exit, )}.`, logs: bbProcess.logs.text(), - actions: [], + actions: OWNED_RUNTIME_EXIT_ACTIONS, title: "Could not start bb", }); return null; } - if (raceResult.result.kind === "compatible") { + if (startup.result.kind === "compatible") { reportOwnedRuntimeExit(ownedRuntime); return runtime; } await loadStartupError({ - details: - raceResult.result.kind === "incompatible" - ? `Port ${args.serverUrl} is responding, but it does not look like bb: ${raceResult.result.reason}.` - : `Timed out waiting for bb at ${args.serverUrl}: ${raceResult.result.reason}.`, + details: `Port ${args.serverUrl} is responding, but it does not look like bb: ${startup.result.reason}.`, logs: bbProcess.logs.text(), actions: [], title: "Could not start bb", diff --git a/apps/desktop/src/owned-runtime-startup.ts b/apps/desktop/src/owned-runtime-startup.ts new file mode 100644 index 00000000000..8db2ef1fdad --- /dev/null +++ b/apps/desktop/src/owned-runtime-startup.ts @@ -0,0 +1,41 @@ +import type { BbAppProcessExit } from "./bb-process.js"; +import type { SettledServerProbeResult } from "./server-probe.js"; + +export type OwnedRuntimeStartupResult = + | ProcessExitedStartupResult + | ServerProbeStartupResult; + +interface ProcessExitedStartupResult { + exit: BbAppProcessExit; + kind: "process-exited"; +} + +interface ServerProbeStartupResult { + kind: "server-probe"; + result: SettledServerProbeResult; +} + +interface WaitForOwnedRuntimeStartupArgs { + exit: Promise; + onSlowStart(): void; + slowStartNoticeMs: number; + waitForServer(signal: AbortSignal): Promise; +} + +export async function waitForOwnedRuntimeStartup( + args: WaitForOwnedRuntimeStartupArgs, +): Promise { + const probe = new AbortController(); + const slowStartNotice = setTimeout(args.onSlowStart, args.slowStartNoticeMs); + try { + return await Promise.race([ + args + .waitForServer(probe.signal) + .then((result) => ({ kind: "server-probe", result })), + args.exit.then((exit) => ({ exit, kind: "process-exited" })), + ]); + } finally { + clearTimeout(slowStartNotice); + probe.abort(); + } +} diff --git a/apps/desktop/src/server-probe.ts b/apps/desktop/src/server-probe.ts index 48fbf992ab8..2506be6d8b9 100644 --- a/apps/desktop/src/server-probe.ts +++ b/apps/desktop/src/server-probe.ts @@ -30,6 +30,10 @@ export interface CompatibleServerProbeResult { serverUrl: string; } +export type SettledServerProbeResult = + | CompatibleServerProbeResult + | IncompatibleServerProbeResult; + interface IncompatibleServerProbeResult { kind: "incompatible"; reason: string; @@ -52,7 +56,7 @@ interface WaitForCompatibleServerArgs { fetchImpl?: ServerProbeFetch; intervalMs: number; serverUrl: string; - timeoutMs: number; + signal: AbortSignal; } interface FetchJsonArgs { @@ -95,11 +99,18 @@ interface FetchJsonNetworkErrorResult { interface SleepArgs { delayMs: number; + signal: AbortSignal; } async function sleep(args: SleepArgs): Promise { await new Promise((resolvePromise) => { - setTimeout(resolvePromise, args.delayMs); + const finish = (): void => { + clearTimeout(timer); + args.signal.removeEventListener("abort", finish); + resolvePromise(); + }; + const timer = setTimeout(finish, args.delayMs); + args.signal.addEventListener("abort", finish, { once: true }); }); } @@ -223,35 +234,19 @@ export async function probeBbServer( export async function waitForCompatibleServer( args: WaitForCompatibleServerArgs, -): Promise { - const deadline = Date.now() + args.timeoutMs; - let lastResult: ServerProbeResult = { - kind: "unavailable", - reason: "Probe has not started", - serverUrl: args.serverUrl, - }; - - while (Date.now() <= deadline) { - lastResult = await probeBbServer({ +): Promise { + for (;;) { + args.signal.throwIfAborted(); + const result = await probeBbServer({ ...(args.fetchImpl === undefined ? {} : { fetchImpl: args.fetchImpl }), serverUrl: args.serverUrl, timeoutMs: Math.min(args.intervalMs, 1_000), }); - if (lastResult.kind === "compatible") { - return lastResult; - } - - if (lastResult.kind === "incompatible") { - return lastResult; + if (result.kind !== "unavailable") { + return result; } - await sleep({ delayMs: args.intervalMs }); + await sleep({ delayMs: args.intervalMs, signal: args.signal }); } - - return { - kind: "unavailable", - reason: `Timed out after ${args.timeoutMs}ms waiting for bb server. Last probe: ${lastResult.reason}`, - serverUrl: args.serverUrl, - }; } diff --git a/apps/desktop/src/types.ts b/apps/desktop/src/types.ts index b465111067c..4facf2cbeb7 100644 --- a/apps/desktop/src/types.ts +++ b/apps/desktop/src/types.ts @@ -5,7 +5,8 @@ const DEFAULT_WINDOW_WIDTH = 1280; export const MIN_WINDOW_HEIGHT = 600; export const MIN_WINDOW_WIDTH = 500; export const STARTUP_POLL_INTERVAL_MS = 250; -export const STARTUP_TIMEOUT_MS = 60_000; +export const OWNED_RUNTIME_SLOW_START_NOTICE_MS = 10_000; +export const MACHINE_READY_TIMEOUT_MS = 60_000; export const ATTACH_PROBE_TIMEOUT_MS = 1_500; export const PROCESS_LOG_LINE_LIMIT = 200; diff --git a/apps/desktop/test/owned-runtime-startup.test.ts b/apps/desktop/test/owned-runtime-startup.test.ts new file mode 100644 index 00000000000..4f276632a54 --- /dev/null +++ b/apps/desktop/test/owned-runtime-startup.test.ts @@ -0,0 +1,164 @@ +import { type ChildProcess, spawn } from "node:child_process"; +import { createServer } from "node:net"; +import { waitForProcessExit } from "@bb/config/child-process-exit"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { waitForOwnedRuntimeStartup } from "../src/owned-runtime-startup.js"; +import { + type ServerProbeFetch, + waitForCompatibleServer, +} from "../src/server-probe.js"; + +const SLOW_SERVER_SOURCE = ` +const { createServer } = require("node:http"); +const [port, listenAfterMs, exitAfterMs] = process.argv.slice(1).map(Number); +const server = createServer((request, response) => { + response.writeHead(200, { "content-type": "application/json" }); + response.end( + request.url === "/health" + ? JSON.stringify({ ok: true }) + : JSON.stringify({ hostDaemonPort: 4242, voiceTranscriptionEnabled: false }), + ); +}); +if (exitAfterMs > 0) setTimeout(() => process.exit(3), exitAfterMs); +else setTimeout(() => server.listen(port, "127.0.0.1"), listenAfterMs); +`; + +interface SlowServerArgs { + exitAfterMs: number; + listenAfterMs: number; +} + +const children: ChildProcess[] = []; + +async function reservePort(): Promise { + const server = createServer(); + await new Promise((resolvePromise) => { + server.listen(0, "127.0.0.1", resolvePromise); + }); + const address = server.address(); + if (address === null || typeof address === "string") { + throw new Error("Expected a TCP address"); + } + await new Promise((resolvePromise) => { + server.close(() => resolvePromise()); + }); + return address.port; +} + +function spawnSlowServer(port: number, args: SlowServerArgs): ChildProcess { + const child = spawn( + process.execPath, + [ + "-e", + SLOW_SERVER_SOURCE, + String(port), + String(args.listenAfterMs), + String(args.exitAfterMs), + ], + { stdio: "ignore" }, + ); + children.push(child); + return child; +} + +afterEach(async () => { + vi.useRealTimers(); + for (const child of children.splice(0)) { + if (child.exitCode === null && child.signalCode === null) { + const exited = waitForProcessExit(child); + child.kill("SIGKILL"); + await exited; + } + } +}); + +describe("waitForOwnedRuntimeStartup", () => { + it("waits for a slow server, shows the slow-start state, and never stops it", async () => { + const port = await reservePort(); + const child = spawnSlowServer(port, { exitAfterMs: 0, listenAfterMs: 600 }); + const onSlowStart = vi.fn(); + + const startup = await waitForOwnedRuntimeStartup({ + exit: waitForProcessExit(child), + onSlowStart, + slowStartNoticeMs: 100, + waitForServer: (signal) => + waitForCompatibleServer({ + intervalMs: 25, + serverUrl: `http://127.0.0.1:${port}`, + signal, + }), + }); + + expect(startup).toEqual({ + kind: "server-probe", + result: { + dataDir: null, + kind: "compatible", + serverUrl: `http://127.0.0.1:${port}`, + }, + }); + expect(onSlowStart).toHaveBeenCalledOnce(); + expect(child.exitCode).toBeNull(); + expect(child.signalCode).toBeNull(); + }); + + it("fails only when the process exits, and stops probing afterwards", async () => { + const port = await reservePort(); + const child = spawnSlowServer(port, { exitAfterMs: 300, listenAfterMs: 0 }); + let probes = 0; + const fetchImpl: ServerProbeFetch = (input, init) => { + probes += 1; + return fetch(input, init); + }; + const onSlowStart = vi.fn(); + + const startup = await waitForOwnedRuntimeStartup({ + exit: waitForProcessExit(child), + onSlowStart, + slowStartNoticeMs: 60_000, + waitForServer: (signal) => + waitForCompatibleServer({ + fetchImpl, + intervalMs: 25, + serverUrl: `http://127.0.0.1:${port}`, + signal, + }), + }); + + expect(startup).toEqual({ + exit: { code: 3, signal: null }, + kind: "process-exited", + }); + const probesAtExit = probes; + await new Promise((resolvePromise) => setTimeout(resolvePromise, 150)); + expect(probes).toBeLessThanOrEqual(probesAtExit + 1); + expect(onSlowStart).not.toHaveBeenCalled(); + }); + + it("has no deadline while the process is alive", async () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] }); + const fetchImpl: ServerProbeFetch = () => + Promise.reject(new TypeError("fetch failed")); + let settled = false; + + const startup = waitForOwnedRuntimeStartup({ + exit: new Promise(() => {}), + onSlowStart: () => {}, + slowStartNoticeMs: 10_000, + waitForServer: (signal) => + waitForCompatibleServer({ + fetchImpl, + intervalMs: 250, + serverUrl: "http://127.0.0.1:1", + signal, + }), + }).finally(() => { + settled = true; + }); + + await vi.advanceTimersByTimeAsync(5 * 60_000); + expect(settled).toBe(false); + void startup; + }); +}); diff --git a/apps/desktop/test/server-probe.test.ts b/apps/desktop/test/server-probe.test.ts index b3cb6843253..437e07746f7 100644 --- a/apps/desktop/test/server-probe.test.ts +++ b/apps/desktop/test/server-probe.test.ts @@ -215,7 +215,7 @@ describe("waitForCompatibleServer", () => { fetchImpl, intervalMs: 1, serverUrl: "http://127.0.0.1:65535", - timeoutMs: 100, + signal: new AbortController().signal, }), ).resolves.toEqual({ dataDir: null, diff --git a/packages/bb-app/src/launcher.ts b/packages/bb-app/src/launcher.ts index e424d3f3be5..cd55863c9a5 100644 --- a/packages/bb-app/src/launcher.ts +++ b/packages/bb-app/src/launcher.ts @@ -148,6 +148,7 @@ import { const HOST_AUTH_FILE_NAME = "auth.json"; const HOST_ID_FILE_NAME = "host-id"; const HEALTH_CHECK_TIMEOUT_MS = 60_000; +const SERVER_SLOW_START_NOTICE_MS = 15_000; const HEALTH_CHECK_INTERVAL_MS = 100; const HEALTH_CHECK_REQUEST_TIMEOUT_MS = 1_000; const MANAGED_PROCESS_TERMINATION_TIMEOUT_MS = 5_000; @@ -602,9 +603,8 @@ export interface DelayMillisecondsArgs { } interface WaitForServerHealthArgs { - childProcess: ChildProcess | null; + childProcess: ChildProcess; expectedLaunchId: string; - timeoutMs?: number; url: string; } @@ -2373,19 +2373,8 @@ async function isHealthyServerAnswering(url: string): Promise { export async function waitForServerHealth( args: WaitForServerHealthArgs, ): Promise { - const timeoutMs = args.timeoutMs ?? HEALTH_CHECK_TIMEOUT_MS; - const deadline = Date.now() + timeoutMs; let foreignServerAnswered = false; - const describeFailure = (reason: string): string => - foreignServerAnswered - ? `${reason}: another server is already answering at ${args.url}` - : reason; - while (Date.now() <= deadline) { - if (args.childProcess && hasProcessExited(args.childProcess)) { - throw new Error( - describeFailure("Process exited before becoming healthy"), - ); - } + while (!hasProcessExited(args.childProcess)) { try { const response = await fetch(args.url, { signal: AbortSignal.timeout(HEALTH_CHECK_REQUEST_TIMEOUT_MS), @@ -2401,7 +2390,9 @@ export async function waitForServerHealth( await delayMilliseconds({ ms: HEALTH_CHECK_INTERVAL_MS }); } throw new Error( - describeFailure(`Timed out waiting for health at ${args.url}`), + foreignServerAnswered + ? `Process exited before becoming healthy: another server is already answering at ${args.url}` + : "Process exited before becoming healthy", ); } @@ -3177,6 +3168,14 @@ export async function startFullStackServerProcess( args.processes.serverRun = serverRun; args.onSpawned?.(serverRun.childProcess); + const slowStartNotice = setTimeout(() => { + log( + " ", + dim( + "The server is still starting. After an update it may be upgrading a large database; bb waits for it.", + ), + ); + }, SERVER_SLOW_START_NOTICE_MS); try { await waitForServerHealth({ childProcess: serverRun.childProcess, @@ -3196,6 +3195,8 @@ export async function startFullStackServerProcess( throw new Error( `Server failed to become healthy: ${error instanceof Error ? error.message : String(error)}`, ); + } finally { + clearTimeout(slowStartNotice); } } diff --git a/packages/bb-app/test/server-health-identity.test.ts b/packages/bb-app/test/server-health-identity.test.ts index 93d3880c0c5..17c5006e394 100644 --- a/packages/bb-app/test/server-health-identity.test.ts +++ b/packages/bb-app/test/server-health-identity.test.ts @@ -1,3 +1,4 @@ +import { type ChildProcess, spawn } from "node:child_process"; import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { createServer, @@ -6,7 +7,7 @@ import { } from "node:http"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import type { BbAppStartContext, ManagedFullStackProcesses, @@ -93,7 +94,29 @@ function createStartContext(args: { }; } +function spawnIdleChild(): ChildProcess { + return spawn(process.execPath, ["-e", "setInterval(() => {}, 1_000)"], { + stdio: "ignore", + }); +} + +async function stopChild(child: ChildProcess): Promise { + if (child.exitCode !== null || child.signalCode !== null) { + return; + } + const exited = new Promise((resolvePromise) => { + child.once("exit", resolvePromise); + }); + child.kill("SIGKILL"); + await exited; +} + describe("waitForServerHealth", () => { + afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); + }); + it("keeps polling past foreign answers until the child echoes its launch id", async () => { let healthRequests = 0; const server = await listen((_request, response) => { @@ -105,37 +128,86 @@ describe("waitForServerHealth", () => { : { ok: true, launchId: "launch-expected" }, ); }); + const child = spawnIdleChild(); try { await waitForServerHealth({ - childProcess: null, + childProcess: child, expectedLaunchId: "launch-expected", - timeoutMs: 5_000, url: `http://127.0.0.1:${server.port}/health`, }); expect(healthRequests).toBe(3); } finally { + await stopChild(child); await server.close(); } }); - it("times out when the responder never echoes the launch id", async () => { + it("waits without a deadline while a slow child is still starting", async () => { + const child = spawnIdleChild(); + let listening = false; + vi.stubGlobal( + "fetch", + vi.fn(async () => { + if (!listening) { + throw new TypeError("fetch failed"); + } + return Response.json({ ok: true, launchId: "launch-slow" }); + }), + ); + vi.useFakeTimers({ toFake: ["setTimeout", "Date"] }); + + try { + let outcome: string | null = null; + const ready = waitForServerHealth({ + childProcess: child, + expectedLaunchId: "launch-slow", + url: "http://127.0.0.1:1/health", + }).then( + () => { + outcome = "healthy"; + }, + (error: unknown) => { + outcome = String(error); + }, + ); + + await vi.advanceTimersByTimeAsync(3 * 60_000); + expect(outcome).toBeNull(); + expect(child.exitCode).toBeNull(); + expect(child.signalCode).toBeNull(); + + listening = true; + await vi.advanceTimersByTimeAsync(1_000); + await ready; + expect(outcome).toBe("healthy"); + } finally { + await stopChild(child); + } + }); + + it("fails once the child exits while another server answers", async () => { const server = await listen((_request, response) => { answerHealth(response, { ok: true, launchId: "launch-other" }); }); + const child = spawn( + process.execPath, + ["-e", "setTimeout(() => process.exit(1), 300)"], + { stdio: "ignore" }, + ); try { await expect( waitForServerHealth({ - childProcess: null, + childProcess: child, expectedLaunchId: "launch-expected", - timeoutMs: 250, url: `http://127.0.0.1:${server.port}/health`, }), ).rejects.toThrow( - `Timed out waiting for health at http://127.0.0.1:${server.port}/health: another server is already answering`, + `Process exited before becoming healthy: another server is already answering at http://127.0.0.1:${server.port}/health`, ); } finally { + await stopChild(child); await server.close(); } });