diff --git a/packages/host-service/src/daemon/singleton.ts b/packages/host-service/src/daemon/singleton.ts index 27c7c189bef..f540702c1da 100644 --- a/packages/host-service/src/daemon/singleton.ts +++ b/packages/host-service/src/daemon/singleton.ts @@ -61,8 +61,8 @@ export function getSupervisor(scriptPath?: string): DaemonSupervisor { * migration plan, decision D3 — fire-and-track). Stash the promise so * callers that need the daemon up can await it via `waitForDaemonReady`. */ -export function startDaemonBootstrap(organizationId: string): void { - if (bootstrapPromise) return; +export function startDaemonBootstrap(organizationId: string): Promise { + if (bootstrapPromise) return bootstrapPromise; const sup = getSupervisor(); console.log("[supervisor] kicking off bootstrap (org):", organizationId); bootstrapPromise = sup @@ -87,6 +87,7 @@ export function startDaemonBootstrap(organizationId: string): void { bootstrapPromise = null; throw err; }); + return bootstrapPromise; } /** diff --git a/packages/host-service/src/serve.ts b/packages/host-service/src/serve.ts index 20eb9ad0cbe..d40ae782431 100644 --- a/packages/host-service/src/serve.ts +++ b/packages/host-service/src/serve.ts @@ -1,4 +1,4 @@ -import { serve } from "@hono/node-server"; +import { createAdaptorServer } from "@hono/node-server"; import { moveLegacyAppHome } from "@superset/agent-setup/legacy-home-move"; import { SANDBOX_PATHS } from "@superset/shared/sandbox/contract"; import { createApp } from "./app"; @@ -31,10 +31,28 @@ import { detachFromLaunchDirectory } from "./runtime/working-directory"; import { installProcessSafetyNet, installUpgradeSocketGuard } from "./safety"; import { configureSelfUpdater } from "./self-update"; import { boxLogsEnabled, captureFatalStartupError, initSentry } from "./sentry"; +import { createStandaloneShutdown } from "./standalone-shutdown"; import { startTerminalBaseEnvResolution } from "./terminal/env"; import { startTerminalReaper } from "./terminal/reaper"; import { connectRelay, type TunnelClient } from "./tunnel"; +const stopping = new AbortController(); +const cleanup: { + stopServing?: () => Promise; + stopDaemon?: () => Promise; + dispose?: () => Promise; +} = {}; +const shutdown = createStandaloneShutdown({ + stopServing: async () => cleanup.stopServing?.(), + stopDaemon: async () => cleanup.stopDaemon?.(), + dispose: async () => cleanup.dispose?.(), +}); + +function stopOnSignal(signal: NodeJS.Signals): void { + stopping.abort(); + void shutdown(signal); +} + async function main(): Promise { installConsoleTimestamps(); recordBootStamp("host.process.start", processStartedAt()); @@ -78,12 +96,24 @@ async function main(): Promise { // so an in-flight bootstrap doesn't race with the first terminal launch. // Non-terminal requests (workspaces, git, chat) are unaffected if the // daemon takes time to come up or fails entirely. - startDaemonBootstrap(env.ORGANIZATION_ID); + const daemonBootstrap = startDaemonBootstrap(env.ORGANIZATION_ID); + // Bootstrap already logs its errors. The host can serve non-terminal requests without it. + void daemonBootstrap.catch(() => {}); + if (process.env.NODE_ENV === "development") { + cleanup.stopDaemon = async () => { + try { + await daemonBootstrap; + } finally { + await getSupervisor().stop(env.ORGANIZATION_ID); + } + }; + } // Standalone entry only: the desktop provisions these itself for hosts it // spawns (with its per-agent disable settings); this covers CLI/systemd // launches, which previously had no notify hooks or shell wrappers (#6254). await provisionAgentIntegrations(); + if (stopping.signal.aborted) return; const configTokenSource = env.SUPERSET_AUTH_CONFIG_PATH ? new ConfigFileSessionTokenSource({ @@ -115,6 +145,7 @@ async function main(): Promise { readLinkedPullRequests, onPullRequestLinked, terminalAgentStore, + dispose, } = createApp({ config: { organizationId: env.ORGANIZATION_ID, @@ -133,135 +164,117 @@ async function main(): Promise { credentials: new LocalGitCredentialProvider(), }, }); - - // Dev-mode shutdown: kill the daemon on host-service exit so dev - // iteration on daemon code resets cleanly. Production keeps the - // daemon detached so PTYs survive host-service restarts. - // Per the migration plan's D5 decision. - const isDev = process.env.NODE_ENV === "development"; - if (isDev) { - let shuttingDown = false; - const devShutdown = async (signal: NodeJS.Signals) => { - if (shuttingDown) return; - shuttingDown = true; - console.log( - "[host-service] dev-mode signal, stopping pty-daemon for clean iteration:", - signal, - ); - try { - await getSupervisor().stop(env.ORGANIZATION_ID); - } catch (err) { - console.error( - "[host-service] dev shutdown: supervisor.stop failed:", - caught(err), - ); - } finally { - process.exit(0); - } - }; - process.on("SIGINT", () => void devShutdown("SIGINT")); - process.on("SIGTERM", () => void devShutdown("SIGTERM")); - } + cleanup.dispose = dispose; const relayAbort = new AbortController(); let tunnelPromise: Promise = Promise.resolve(null); const hostname = env.SUPERSET_HOST_RUN_MODE === "sandbox" ? undefined : "127.0.0.1"; - const listen = { fetch: app.fetch, port: env.PORT, hostname }; - const server = serve(listen, (info) => { - // Install only after the server is listening so startup throws still - // reach `main().catch(...)` and exit with a non-zero code. - installProcessSafetyNet(); - const address = info.address.includes(":") - ? `[${info.address}]` - : info.address; - console.log( - "[host-service] listening (address, port):", - address, - info.port, - ); - recordBootStamp("host.listening"); - - startTerminalReaper(db); - startVitalsLog(); - // A cloud workspace created with an agent starts it now: the pty daemon - // and event bus are up, and a person opening the workspace sees the - // agent's terminal the way they would on their own machine. - void launchSandboxAgent(); - // A stop keeps the disk and drops every process, so nothing else on the - // box will notice that its agents are gone. - if (env.SUPERSET_HOST_RUN_MODE === "sandbox") void resumeCrashedAgents(); - const sandboxWorkspaceId = process.env.SUPERSET_SANDBOX_WORKSPACE_ID; - if (env.SUPERSET_HOST_RUN_MODE === "sandbox" && sandboxWorkspaceId) { - startSandboxAgentStatusReporter({ - apiUrl: env.SUPERSET_API_URL, - workspaceId: sandboxWorkspaceId, - hostSecret: env.HOST_SERVICE_SECRET, - store: terminalAgentStore, - }); - startSandboxBoxPressureReporter({ - apiUrl: env.SUPERSET_API_URL, - workspaceId: sandboxWorkspaceId, - hostSecret: env.HOST_SERVICE_SECRET, - read: readSandboxBoxResources, - }); - if (boxLogsEnabled()) { - startSandboxBootPhaseLog({ path: SANDBOX_PATHS.bootLog }); - } - startSandboxKeepalive({ - keepalive: (pingsEveryMs) => - api.sandbox.keepalive.mutate({ pingsEveryMs }), - store: terminalAgentStore, - }); - startSandboxPullRequestReporter({ - read: readLinkedPullRequests, - report: (pullRequests) => - api.cloudWorkspace.reportPullRequests.mutate({ - id: sandboxWorkspaceId, - pullRequests, - }), - onLinked: onPullRequestLinked, - }); - } - - if (env.RELAY_URL && env.SUPERSET_HOST_RUN_MODE !== "sandbox") { - tunnelPromise = connectRelay({ - signal: relayAbort.signal, - api, - relayUrl: env.RELAY_URL, - localPort: info.port, - organizationId: env.ORGANIZATION_ID, - authProvider, - hostServiceSecret: env.HOST_SERVICE_SECRET, - }); - } + const server = createAdaptorServer({ + fetch: app.fetch, + port: env.PORT, + hostname, }); + const stopServing = async () => { + // Cancel registration retries before replacing this process. + relayAbort.abort(); + const tunnel = await Promise.race([ + tunnelPromise, + new Promise((resolve) => setTimeout(() => resolve(null), 1_000)), + ]); + tunnel?.close(); + const httpServer = server as unknown as { + closeAllConnections?: () => void; + close: (callback: () => void) => void; + }; + httpServer.closeAllConnections?.(); + await Promise.race([ + new Promise((resolve) => httpServer.close(() => resolve())), + new Promise((resolve) => setTimeout(resolve, 3_000)), + ]); + }; + cleanup.stopServing = stopServing; installUpgradeSocketGuard(server); injectWebSocket(server); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen({ port: env.PORT, host: hostname }, () => { + server.off("error", reject); + resolve(); + }); + }); + if (stopping.signal.aborted) return; + const info = server.address(); + if (!info || typeof info === "string") { + throw new Error("The host server did not start a TCP listener"); + } + // Install only after the server is listening so startup throws still + // reach `main().catch(...)` and exit with a non-zero code. + installProcessSafetyNet(); + const address = info.address.includes(":") + ? `[${info.address}]` + : info.address; + console.log("[host-service] listening (address, port):", address, info.port); + recordBootStamp("host.listening"); + + startTerminalReaper(db); + startVitalsLog(); + // A cloud workspace created with an agent starts it now: the pty daemon + // and event bus are up, and a person opening the workspace sees the + // agent's terminal the way they would on their own machine. + void launchSandboxAgent(); + // A stop keeps the disk and drops every process, so nothing else on the + // box will notice that its agents are gone. + if (env.SUPERSET_HOST_RUN_MODE === "sandbox") void resumeCrashedAgents(); + const sandboxWorkspaceId = process.env.SUPERSET_SANDBOX_WORKSPACE_ID; + if (env.SUPERSET_HOST_RUN_MODE === "sandbox" && sandboxWorkspaceId) { + startSandboxAgentStatusReporter({ + apiUrl: env.SUPERSET_API_URL, + workspaceId: sandboxWorkspaceId, + hostSecret: env.HOST_SERVICE_SECRET, + store: terminalAgentStore, + }); + startSandboxBoxPressureReporter({ + apiUrl: env.SUPERSET_API_URL, + workspaceId: sandboxWorkspaceId, + hostSecret: env.HOST_SERVICE_SECRET, + read: readSandboxBoxResources, + }); + if (boxLogsEnabled()) { + startSandboxBootPhaseLog({ path: SANDBOX_PATHS.bootLog }); + } + startSandboxKeepalive({ + keepalive: (pingsEveryMs) => + api.sandbox.keepalive.mutate({ pingsEveryMs }), + store: terminalAgentStore, + }); + startSandboxPullRequestReporter({ + read: readLinkedPullRequests, + report: (pullRequests) => + api.cloudWorkspace.reportPullRequests.mutate({ + id: sandboxWorkspaceId, + pullRequests, + }), + onLinked: onPullRequestLinked, + }); + } + + if (env.RELAY_URL && env.SUPERSET_HOST_RUN_MODE !== "sandbox") { + tunnelPromise = connectRelay({ + signal: relayAbort.signal, + api, + relayUrl: env.RELAY_URL, + localPort: info.port, + organizationId: env.ORGANIZATION_ID, + authProvider, + hostServiceSecret: env.HOST_SERVICE_SECRET, + }); + } // Standalone only: this process owns its listener and relay socket, so it // can hand the port to a successor build (system.update). The desktop // entry never registers this and its host-service stays non-updatable. - const selfUpdater = configureSelfUpdater({ - stopServing: async () => { - // Cancel registration retries before replacing this process. - relayAbort.abort(); - const tunnel = await Promise.race([ - tunnelPromise, - new Promise((resolve) => setTimeout(() => resolve(null), 1_000)), - ]); - tunnel?.close(); - const httpServer = server as unknown as { - closeAllConnections?: () => void; - close: (callback: () => void) => void; - }; - httpServer.closeAllConnections?.(); - await Promise.race([ - new Promise((resolve) => httpServer.close(() => resolve())), - new Promise((resolve) => setTimeout(resolve, 3_000)), - ]); - }, - }); + const selfUpdater = configureSelfUpdater({ stopServing }); if (env.SUPERSET_HOST_AUTO_UPDATE && selfUpdater.status().updatable) { const timer = setInterval( () => void selfUpdater.checkForUpdates(), @@ -271,8 +284,11 @@ async function main(): Promise { } } +process.on("SIGINT", () => stopOnSignal("SIGINT")); +process.on("SIGTERM", () => stopOnSignal("SIGTERM")); void main().catch(async (error) => { + if (stopping.signal.aborted) return; + stopping.abort(); console.error("[host-service] Failed to start:", caught(error)); - await captureFatalStartupError(error); - process.exit(1); + await shutdown("startup failure", () => captureFatalStartupError(error)); }); diff --git a/packages/host-service/src/standalone-shutdown.test.ts b/packages/host-service/src/standalone-shutdown.test.ts new file mode 100644 index 00000000000..ed97a782a7a --- /dev/null +++ b/packages/host-service/src/standalone-shutdown.test.ts @@ -0,0 +1,159 @@ +import { expect, test } from "bun:test"; +import { createStandaloneShutdown } from "./standalone-shutdown"; + +function setup( + overrides: Partial[0]> = {}, +) { + const calls: string[] = []; + let deadline = () => {}; + const shutdown = createStandaloneShutdown({ + stopServing: async () => { + calls.push("stop serving"); + }, + dispose: async () => { + calls.push("dispose"); + }, + exit: (code) => { + calls.push(`exit ${code}`); + }, + hardExit: () => { + calls.push("hard exit"); + }, + scheduleDeadline: (callback) => { + deadline = callback; + return () => { + calls.push("cancel deadline"); + }; + }, + log: () => {}, + ...overrides, + }); + return { shutdown, calls, deadline: () => deadline() }; +} + +test("stops serving and disposes before exiting, cancelling the deadline", async () => { + const { shutdown, calls, deadline } = setup(); + await shutdown("SIGTERM"); + deadline(); + expect(calls).toEqual([ + "stop serving", + "dispose", + "cancel deadline", + "exit 0", + ]); +}); + +test("reports a startup failure and disposes the partly started host before exiting", async () => { + const { shutdown, calls } = setup(); + await shutdown("startup failure", async () => { + calls.push("report startup error"); + }); + expect(calls).toEqual([ + "report startup error", + "stop serving", + "dispose", + "cancel deadline", + "exit 1", + ]); +}); + +test("reports a startup failure before the cleanup deadline", async () => { + const entered = Promise.withResolvers(); + const pending = Promise.withResolvers(); + const { shutdown, calls, deadline } = setup({ + dispose: () => { + entered.resolve(); + return pending.promise; + }, + }); + const completion = shutdown("startup failure", async () => { + calls.push("report startup error"); + }); + await entered.promise; + deadline(); + pending.resolve(); + await completion; + + expect(calls).toEqual([ + "report startup error", + "stop serving", + "cancel deadline", + "hard exit", + ]); +}); + +test("stops the development daemon before disposing the app", async () => { + const events: string[] = []; + const { shutdown } = setup({ + stopServing: async () => { + events.push("server"); + }, + stopDaemon: async () => { + events.push("daemon"); + }, + dispose: async () => { + events.push("dispose"); + }, + }); + await shutdown("SIGINT"); + expect(events).toEqual(["server", "daemon", "dispose"]); +}); + +test.each([ + "server", + "daemon", + "dispose", +])("a failing %s cleanup does not skip the remaining steps", async (failing) => { + const events: string[] = []; + const step = async (name: string) => { + events.push(name); + if (name === failing) throw new Error(`${name} failed`); + }; + const { shutdown, calls } = setup({ + stopServing: () => step("server"), + stopDaemon: () => step("daemon"), + dispose: () => step("dispose"), + }); + await shutdown("SIGTERM"); + expect(events).toEqual(["server", "daemon", "dispose"]); + expect(calls).toEqual(["cancel deadline", "exit 0"]); +}); + +test("keeps cleanup failures in a structured log argument", async () => { + const logs: unknown[][] = []; + const { shutdown } = setup({ + stopServing: () => Promise.reject("fixture failure"), + log: (...args) => { + logs.push(args); + }, + }); + + await shutdown("SIGTERM"); + + expect(logs).toContainEqual([ + "[host-service] shutdown step failed:", + "stop serving", + { error: "fixture failure" }, + ]); +}); + +test.each([ + "deadline", + "second signal", +])("hard-exits on %s without exiting again after disposal resolves", async (reason) => { + const pending = Promise.withResolvers(); + const entered = Promise.withResolvers(); + const { shutdown, calls, deadline } = setup({ + dispose: () => { + entered.resolve(); + return pending.promise; + }, + }); + const first = shutdown("SIGTERM"); + await entered.promise; + if (reason === "deadline") deadline(); + else await shutdown("SIGINT"); + pending.resolve(); + await first; + expect(calls).toEqual(["stop serving", "cancel deadline", "hard exit"]); +}); diff --git a/packages/host-service/src/standalone-shutdown.ts b/packages/host-service/src/standalone-shutdown.ts new file mode 100644 index 00000000000..b1fd13cc37e --- /dev/null +++ b/packages/host-service/src/standalone-shutdown.ts @@ -0,0 +1,82 @@ +import { caught } from "./runtime/box-log-filter"; + +interface StandaloneShutdownOptions { + stopServing: () => Promise; + dispose: () => Promise; + stopDaemon?: () => Promise; + exit?: (code: number) => void; + hardExit?: () => void; + scheduleDeadline?: (callback: () => void, delayMs: number) => () => void; + log?: (message: string, ...details: unknown[]) => void; +} + +// The CLI escalates to SIGKILL after 10 seconds. +const SHUTDOWN_TIMEOUT_MS = 8_000; + +export function createStandaloneShutdown({ + stopServing, + dispose, + stopDaemon, + exit = (code) => process.exit(code), + hardExit = () => process.kill(process.pid, "SIGKILL"), + scheduleDeadline = (callback, delayMs) => { + const timer = setTimeout(callback, delayMs); + return () => clearTimeout(timer); + }, + log = (message, ...details) => console.log(message, ...details), +}: StandaloneShutdownOptions): ( + reason: NodeJS.Signals | "startup failure", + reportStartupError?: () => Promise, +) => Promise { + let shuttingDown = false; + let finished = false; + let cancelDeadline = () => {}; + const forceExit = () => { + if (finished) return; + finished = true; + cancelDeadline(); + hardExit(); + }; + + return async (reason, reportStartupError) => { + if (finished) return; + if (shuttingDown) { + log( + "[host-service] forcing exit after repeated shutdown signal:", + reason, + ); + forceExit(); + return; + } + shuttingDown = true; + log("[host-service] shutdown requested:", reason); + cancelDeadline = scheduleDeadline(() => { + if (finished) return; + log( + "[host-service] forcing exit after shutdown deadline (ms):", + SHUTDOWN_TIMEOUT_MS, + ); + forceExit(); + }, SHUTDOWN_TIMEOUT_MS); + + const steps = [ + ["report startup error", reportStartupError], + ["stop serving", stopServing], + ["stop dev daemon", stopDaemon], + ["dispose", dispose], + ] as const; + for (const [name, cleanup] of steps) { + if (finished) return; + try { + await cleanup?.(); + } catch (error) { + log("[host-service] shutdown step failed:", name, caught(error)); + } + } + if (finished) return; + finished = true; + cancelDeadline(); + log("[host-service] shutdown complete"); + exit(reason === "startup failure" ? 1 : 0); + }; +}