diff --git a/packages/cli/src/server-process.ts b/packages/cli/src/server-process.ts index 1c40512d272..f11681ac4a6 100644 --- a/packages/cli/src/server-process.ts +++ b/packages/cli/src/server-process.ts @@ -152,7 +152,7 @@ const processEffect = Effect.fnUntraced(function* (options: Options) { serviceOptions === undefined ? undefined : { - onListen: (address, shutdown) => + onListen: (address, shutdown, ready) => Effect.gen(function* () { if (!config.password) yield* ServiceConfig.password(password) return yield* ServiceRegistration.register({ @@ -161,6 +161,7 @@ const processEffect = Effect.fnUntraced(function* (options: Options) { id: instanceID, file: serviceOptions.file, shutdown, + ready, }) }), }, diff --git a/packages/cli/src/services/service-registration.ts b/packages/cli/src/services/service-registration.ts index 7757d60428d..544122dfe69 100644 --- a/packages/cli/src/services/service-registration.ts +++ b/packages/cli/src/services/service-registration.ts @@ -17,6 +17,8 @@ export const register = Effect.fnUntraced(function* (options: { readonly id: string readonly file: string readonly shutdown: Effect.Effect + /** Completes when the server finishes booting, so clients can tell a hung boot from a hung owner. */ + readonly ready?: Effect.Effect }) { const fs = yield* FileSystem.FileSystem const temp = options.file + "." + options.id + ".tmp" @@ -26,8 +28,9 @@ export const register = Effect.fnUntraced(function* (options: { version: OPENCODE_VERSION, url: HttpServer.formatAddress(options.address), pid: process.pid, + state: "starting", password: options.password, - } + } satisfies Info const encoded = yield* encodeInfo(info) const current = fs.readFileString(options.file).pipe(Effect.flatMap(decodeInfo)) const owns = (found: Info) => @@ -72,6 +75,21 @@ export const register = Effect.fnUntraced(function* (options: { Effect.andThen(options.shutdown), Effect.forkScoped, ) + if (options.ready !== undefined) + yield* options.ready.pipe( + Effect.andThen(() => current), + Effect.filterOrFail(owns), + Effect.andThen( + encodeInfo({ ...info, state: "ready" }).pipe( + Effect.andThen((ready) => fs.writeFileString(temp, ready, { mode: 0o600 })), + Effect.andThen( + fs.rename(temp, options.file).pipe(Effect.retry({ times: 20, schedule: Schedule.spaced("10 millis") })), + ), + ), + ), + Effect.ignore, + Effect.forkScoped, + ) return current.pipe( Effect.flatMap((found) => (owns(found) ? fs.remove(options.file) : Effect.void)), Effect.ignore, diff --git a/packages/cli/test/service.test.ts b/packages/cli/test/service.test.ts index 7e37142f1b4..264e367385b 100644 --- a/packages/cli/test/service.test.ts +++ b/packages/cli/test/service.test.ts @@ -398,6 +398,41 @@ it.effect("replacing a managed service registration stops its owner and preserve }), ) +it.effect("a managed service advertises ready only after its readiness effect succeeds", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem + const directory = yield* fs.makeTempDirectoryScoped() + const decode = Schema.decodeUnknownEffect(Schema.fromJsonString(Service.Info)) + const register = (name: string, ready: Effect.Effect) => + Effect.gen(function* () { + const file = path.join(directory, name) + const cleanup = yield* ServiceRegistration.register({ + address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 4321), + password: "secret", + id: name, + file, + shutdown: Effect.never, + ready, + }) + const state = () => fs.readFileString(file).pipe(Effect.flatMap(decode), Effect.map((info) => info.state)) + return { cleanup, state } + }) + const pending = yield* Deferred.make() + const good = yield* register("good.json", Deferred.await(pending)) + const bad = yield* register("bad.json", Effect.die("boot failed")) + expect(yield* good.state()).toBe("starting") + expect(yield* bad.state()).toBe("starting") + // Registration writes happen on forked fibers; file I/O needs live time even under the test clock. + yield* TestClock.withLive(Effect.sleep("20 millis")) + expect(yield* bad.state()).toBe("starting") + yield* Deferred.succeed(pending, undefined) + yield* TestClock.withLive(Effect.sleep("20 millis")) + expect(yield* good.state()).toBe("ready") + yield* good.cleanup + yield* bad.cleanup + }), +) + // Real process: a server whose boot failed must still be watching its registration. test("deleting a failed service registration stops its owner", async () => { const service = await startManagedService("opencode-service-failed-delete-", true) @@ -774,6 +809,7 @@ test("service registration replaces a stale owner with the bound address", async version: OPENCODE_VERSION, url: "http://127.0.0.1:4321", pid: process.pid, + state: "starting", password: "secret", }) await Effect.runPromise(cleanup.pipe(Effect.provide(NodeFileSystem.layer))) diff --git a/packages/client/src/effect/service.ts b/packages/client/src/effect/service.ts index 4ec16aa7fcb..7fc88c95274 100644 --- a/packages/client/src/effect/service.ts +++ b/packages/client/src/effect/service.ts @@ -1,10 +1,12 @@ import { Effect, FileSystem, Option, Schedule, Schema } from "effect" import type { DiscoverOptions, EnsureOptions, StopOptions } from "../service.js" import { contenderPool, spawnServiceContender } from "../service-contender.js" -import { defaultEnsureTiming, ensureTiming, type EnsureTiming } from "../service-timing.js" +import { defaultEnsureTiming, ensureTiming, type EnsureTiming, unresponsiveThreshold } from "../service-timing.js" import { matchesVersion } from "../service-version.js" import { PtyHandoff } from "../pty-handoff.js" import { decide, fallback, headers, probeResult, same } from "../service-probe.js" +import { completeRestart, releaseRestart, tryBeginRestart } from "../service-restart.js" +import { processStopped } from "../service-process.js" export * from "../service.js" export { headers } @@ -49,7 +51,8 @@ export const incumbent = Effect.fn("service.incumbent")(function* ( export const ensure = Effect.fn("service.ensure")(function* (options: EnsureOptions = {}) { const timing = ensureTiming(options) const pool = contenderPool(timing) - let timeouts: { readonly info: Info; readonly count: number } | undefined + let timeouts: { readonly info: Info; readonly count: number; readonly start: number } | undefined + let restartToken: string | undefined let announced = false const announce = (reason: "missing" | "version-mismatch", previousVersion?: string) => Effect.sync(() => { @@ -73,22 +76,34 @@ export const ensure = Effect.fn("service.ensure")(function* (options: EnsureOpti const info = registration.info const service = registration.service if (registration.timedOut && info !== undefined) { - timeouts = { - info, - count: timeouts !== undefined && same(timeouts.info, info) ? timeouts.count + 1 : 1, - } - if (timeouts.count >= 3) { - yield* announce("missing") - yield* Effect.logWarning("Background service is unresponsive; recovery cannot preserve persistent terminals") - yield* Effect.tryPromise(() => PtyHandoff.clear(options.file ?? fallback())) - yield* terminate(info, options, timing) - pool.evict(info.pid) - pool.recruitNow() - timeouts = undefined + const now = Date.now() + const streak = timeouts !== undefined && same(timeouts.info, info) ? timeouts : undefined + const count = streak === undefined ? 1 : streak.count + 1 + const start = streak?.start ?? now + timeouts = { info, count, start } + const threshold = unresponsiveThreshold(timing, info.state === "starting") + if (count >= threshold.failures && now - start >= threshold.window) { + const acquired = yield* Effect.tryPromise(() => tryBeginRestart(options.file, timing)) + if (acquired !== undefined) { + restartToken = acquired.token + yield* announce("missing") + yield* Effect.logWarning("Background service is unresponsive; recovery cannot preserve persistent terminals") + yield* Effect.tryPromise(() => PtyHandoff.clear(options.file ?? fallback())) + yield* terminate(info, options, timing) + pool.evict(info.pid) + pool.recruitNow() + timeouts = undefined + } } } else timeouts = undefined if (service !== undefined) { - pool.serviceAnswered() + // A ready service is the end of this reboot (z in the cooldown window), whoever started it. + const token = restartToken + if (service.state === "ready" && token !== undefined) { + restartToken = undefined + yield* Effect.tryPromise(() => completeRestart(options.file, token, timing)) + } + pool.serviceAnswered(service.info.pid, service.state === "ready") const decision = decide(service, options) if (decision._tag === "fail") return yield* Effect.fail(decision.error) if (decision._tag === "reuse") { @@ -96,11 +111,15 @@ export const ensure = Effect.fn("service.ensure")(function* (options: EnsureOpti return Option.some(service) } if (decision._tag === "replace") { - yield* announce("version-mismatch", service.version) - if (service.state !== "ready") - yield* Effect.logWarning("Background service is not ready; replacement cannot preserve persistent terminals") - yield* stop({ file: options.file, pty: decision.pty }).pipe(Effect.ignore) - pool.evict(service.info.pid) + const acquired = yield* Effect.tryPromise(() => tryBeginRestart(options.file, timing)) + if (acquired !== undefined) { + restartToken = acquired.token + yield* announce("version-mismatch", service.version) + if (service.state !== "ready") + yield* Effect.logWarning("Background service is not ready; replacement cannot preserve persistent terminals") + yield* stop({ file: options.file, pty: decision.pty }).pipe(Effect.ignore) + pool.evict(service.info.pid) + } } return Option.none() } @@ -120,6 +139,11 @@ export const ensure = Effect.fn("service.ensure")(function* (options: EnsureOpti schedule: Schedule.spaced(timing.pollInterval).pipe(Schedule.upTo({ duration: timing.promiseTimeout })), }), Effect.ensuring(Effect.sync(() => pool.releaseAll())), + Effect.ensuring( + Effect.promise(() => + restartToken === undefined ? Promise.resolve() : releaseRestart(options.file, restartToken), + ), + ), ) if (Option.isNone(found)) return yield* Effect.fail(pool.failure() ?? new Error("Timed out waiting for the background service to start")) @@ -144,6 +168,7 @@ export const Info = Schema.Struct({ version: Schema.optional(Schema.String), url: Schema.String, pid: Schema.Int.check(Schema.isGreaterThan(0)), + state: Schema.optional(Schema.Union([Schema.Literal("starting"), Schema.Literal("ready")])), password: Schema.optional(Schema.String), }) @@ -168,26 +193,26 @@ const registered = Effect.fnUntraced(function* (file?: string, timeout?: number) const poll = (timing: EnsureTiming) => Schedule.max([Schedule.spaced(timing.stopPollInterval), Schedule.recurs(timing.stopPollAttempts)]) -const signal = (pid: number, name: NodeJS.Signals) => - Effect.try({ try: () => process.kill(pid, name), catch: (cause) => cause }).pipe(Effect.ignore) +const signal = (pid: number, name: NodeJS.Signals, timing: EnsureTiming) => + Effect.try({ + try: () => (timing.signal ? timing.signal(pid, name) : process.kill(pid, name)), + catch: (cause) => cause, + }).pipe(Effect.ignore) const stopped = Effect.fnUntraced(function* (pid: number) { - const running = yield* Effect.try({ try: () => process.kill(pid, 0), catch: () => false }).pipe( - Effect.orElseSucceed(() => false), - ) - if (!running) return true + if (yield* Effect.promise(() => processStopped(pid))) return true return yield* Effect.fail(new Error(`Server process ${pid} is still running`)) }) const terminate = Effect.fnUntraced(function* (info: Info, options: { readonly file?: string }, timing: EnsureTiming) { const current = yield* read(options.file) if (current === undefined || !same(current, info)) return - yield* signal(info.pid, "SIGTERM") + yield* signal(info.pid, "SIGTERM", timing) const done = yield* stopped(info.pid).pipe(Effect.retry(poll(timing)), Effect.option) // The registration can disappear or change hands before this process exits. Only the PID we // signalled can tell us whether it has stopped, so escalate based on that process. if (Option.isNone(done)) { - yield* signal(info.pid, "SIGKILL") + yield* signal(info.pid, "SIGKILL", timing) yield* stopped(info.pid).pipe(Effect.retry(poll(timing))) } const latest = yield* read(options.file) diff --git a/packages/client/src/promise/service.ts b/packages/client/src/promise/service.ts index 5d5d0bad4a1..8de0c4b170b 100644 --- a/packages/client/src/promise/service.ts +++ b/packages/client/src/promise/service.ts @@ -1,10 +1,12 @@ import { readFile, rm } from "node:fs/promises" import type { DiscoverOptions, Endpoint, Info, EnsureOptions, StopOptions } from "../service.js" import { contenderPool, spawnServiceContender } from "../service-contender.js" -import { defaultEnsureTiming, ensureTiming, type EnsureTiming } from "../service-timing.js" +import { defaultEnsureTiming, ensureTiming, type EnsureTiming, unresponsiveThreshold } from "../service-timing.js" import { matchesVersion } from "../service-version.js" import { PtyHandoff } from "../pty-handoff.js" import { decide, fallback, headers, probeResult, same } from "../service-probe.js" +import { completeRestart, releaseRestart, tryBeginRestart } from "../service-restart.js" +import { processStopped } from "../service-process.js" export * from "../service.js" export { fallback, headers } @@ -29,7 +31,8 @@ export async function ensure(options: EnsureOptions = {}): Promise { const timing = ensureTiming(options) const deadline = Date.now() + timing.promiseTimeout const pool = contenderPool(timing) - let timeouts: { readonly info: Info; readonly count: number } | undefined + let timeouts: { readonly info: Info; readonly count: number; readonly start: number } | undefined + let restartToken: string | undefined let announced = false const announce = (reason: "missing" | "version-mismatch", previousVersion?: string) => { @@ -53,24 +56,36 @@ export async function ensure(options: EnsureOptions = {}): Promise { throw pool.failure() ?? new Error("Timed out waiting for the background service to start") const registration = await registered(options.file, timing.requestTimeout) if (registration.timedOut && registration.info !== undefined) { - timeouts = { - info: registration.info, - count: timeouts !== undefined && same(timeouts.info, registration.info) ? timeouts.count + 1 : 1, - } - if (timeouts.count >= 3) { - announce("missing") - console.warn("Background service is unresponsive; recovery cannot preserve persistent terminals") - await PtyHandoff.clear(options.file ?? fallback()) - await terminate(registration.info, options, timing) - pool.evict(registration.info.pid) - pool.recruitNow() - timeouts = undefined + const now = Date.now() + const streak = timeouts !== undefined && same(timeouts.info, registration.info) ? timeouts : undefined + const count = streak === undefined ? 1 : streak.count + 1 + const start = streak?.start ?? now + timeouts = { info: registration.info, count, start } + const threshold = unresponsiveThreshold(timing, registration.info.state === "starting") + if (count >= threshold.failures && now - start >= threshold.window) { + const acquired = await tryBeginRestart(options.file, timing) + if (acquired !== undefined) { + restartToken = acquired.token + announce("missing") + console.warn("Background service is unresponsive; recovery cannot preserve persistent terminals") + await PtyHandoff.clear(options.file ?? fallback()) + await terminate(registration.info, options, timing) + pool.evict(registration.info.pid) + pool.recruitNow() + timeouts = undefined + } } } else timeouts = undefined if (registration.service !== undefined) { - pool.serviceAnswered() const service = registration.service + // A ready service is the end of this reboot (z in the cooldown window), whoever started it. + const token = restartToken + if (service.state === "ready" && token !== undefined) { + restartToken = undefined + await completeRestart(options.file, token, timing) + } + pool.serviceAnswered(service.info.pid, service.state === "ready") const decision = decide(service, options) if (decision._tag === "fail") throw decision.error if (decision._tag === "reuse") { @@ -78,11 +93,15 @@ export async function ensure(options: EnsureOptions = {}): Promise { return service.endpoint } if (decision._tag === "replace") { - announce("version-mismatch", service.version) - if (service.state !== "ready") - console.warn("Background service is not ready; replacement cannot preserve persistent terminals") - await stop({ file: options.file, pty: decision.pty }).catch(() => undefined) - pool.evict(service.info.pid) + const acquired = await tryBeginRestart(options.file, timing) + if (acquired !== undefined) { + restartToken = acquired.token + announce("version-mismatch", service.version) + if (service.state !== "ready") + console.warn("Background service is not ready; replacement cannot preserve persistent terminals") + await stop({ file: options.file, pty: decision.pty }).catch(() => undefined) + pool.evict(service.info.pid) + } } } else { const failed = pool.reap() @@ -95,6 +114,7 @@ export async function ensure(options: EnsureOptions = {}): Promise { await delay(timing.pollInterval) } } finally { + if (restartToken !== undefined) await releaseRestart(options.file, restartToken) pool.releaseAll() } } @@ -127,24 +147,19 @@ async function registered(file?: string, timeout?: number) { return { info, ...(await probeResult(info, timeout)) } } -function signal(pid: number, name: NodeJS.Signals) { +function signal(pid: number, name: NodeJS.Signals, timing: EnsureTiming) { try { + if (timing.signal) { + timing.signal(pid, name) + return + } process.kill(pid, name) } catch {} } -function stopped(pid: number) { - try { - process.kill(pid, 0) - return false - } catch { - return true - } -} - async function waitUntilStopped(pid: number, timing: EnsureTiming) { for (let attempt = 0; attempt <= timing.stopPollAttempts; attempt++) { - if (stopped(pid)) return true + if (await processStopped(pid)) return true if (attempt < timing.stopPollAttempts) await delay(timing.stopPollInterval) } return false @@ -153,11 +168,11 @@ async function waitUntilStopped(pid: number, timing: EnsureTiming) { async function terminate(info: Info, options: { readonly file?: string }, timing: EnsureTiming) { const current = await read(options.file) if (current === undefined || !same(current, info)) return - signal(info.pid, "SIGTERM") + signal(info.pid, "SIGTERM", timing) // The registration can disappear or change hands before this process exits. Only the PID we // signalled can tell us whether it has stopped, so escalate based on that process. if (!(await waitUntilStopped(info.pid, timing))) { - signal(info.pid, "SIGKILL") + signal(info.pid, "SIGKILL", timing) if (!(await waitUntilStopped(info.pid, timing))) throw new Error(`Server process ${info.pid} is still running`) } const latest = await read(options.file) diff --git a/packages/client/src/service-contender.ts b/packages/client/src/service-contender.ts index 79542c30a44..6cabd9c8faa 100644 --- a/packages/client/src/service-contender.ts +++ b/packages/client/src/service-contender.ts @@ -3,6 +3,8 @@ import type { EnsureTiming } from "./service-timing.js" export type ServiceContender = { readonly child: ChildProcess + readonly ready: () => boolean + readonly markReady: () => void readonly error: () => Error | undefined readonly closed: () => boolean readonly stderr: () => string @@ -10,6 +12,9 @@ export type ServiceContender = { } const stderrLimit = 8 * 1024 +// Keep live handles referenced until the child exits so the runtime's process watcher still +// reaps detached contenders after `ensure()` returns, while `unref()` lets this client exit. +const liveContenders = new Set() export function spawnServiceContender( command: string, @@ -22,8 +27,13 @@ export function spawnServiceContender( stdio: ["ignore", "ignore", "pipe"], env: { ...process.env, ...env }, }) + liveContenders.add(child) + const forget = () => { + liveContenders.delete(child) + } let error: Error | undefined let closed = false + let ready = false let stderr = Buffer.alloc(0) const onStderr = (chunk: Buffer) => { const tail = chunk.subarray(-stderrLimit) @@ -35,14 +45,21 @@ export function spawnServiceContender( child.stderr?.on("data", onStderr) if (child.stderr !== null && "unref" in child.stderr && typeof child.stderr.unref === "function") child.stderr.unref() child.once("error", (cause) => { + forget() error = new Error("Failed to start server", { cause }) }) + child.once("exit", forget) child.once("close", () => { + forget() closed = true }) child.unref() return { child, + ready: () => ready, + markReady: () => { + ready = true + }, error: () => error, closed: () => closed, stderr: () => stderr.toString("utf8").trim(), @@ -67,7 +84,12 @@ export function contenderPool(timing: EnsureTiming) { /** The first startup failure seen since the last eviction. */ failure: () => failure, /** A registered service answered, so the next attempt waits the base delay again. */ - serviceAnswered() { + serviceAnswered(pid: number, ready: boolean) { + if (ready) { + for (const contender of contenders) { + if (contender.child.pid === pid) contender.markReady() + } + } spawnDelay = timing.spawnDelay }, /** diff --git a/packages/client/src/service-process.ts b/packages/client/src/service-process.ts new file mode 100644 index 00000000000..abdf8baada5 --- /dev/null +++ b/packages/client/src/service-process.ts @@ -0,0 +1,61 @@ +import { execFile } from "node:child_process" +import { readFile } from "node:fs/promises" + +// Shared by the Effect and Promise clients. Keep this module free of Effect so the +// Promise client never loads the Effect runtime. + +export function parseLinuxProcState(stat: string) { + const close = stat.lastIndexOf(")") + if (close < 0) return undefined + return stat.slice(close + 1).trimStart()[0] +} + +export function parsePsState(output: string) { + return output.trim()[0] +} + +export function isZombieState(state: string | undefined) { + return state === "Z" +} + +function alive(pid: number) { + try { + process.kill(pid, 0) + return true + } catch { + return false + } +} + +function psState(pid: number) { + return new Promise((resolve) => { + execFile("ps", ["-o", "state=", "-p", String(pid)], (error, stdout) => { + if (error) { + resolve(undefined) + return + } + resolve(parsePsState(stdout)) + }) + }) +} + +/** + * Whether `pid` has exited, including POSIX `` zombies whose parent has not + * reaped them yet (which still answer `kill(pid, 0)` until waited on). + */ +export async function processStopped(pid: number, platform = process.platform): Promise { + if (!alive(pid)) return true + if (platform === "win32") return false + if (platform === "linux") { + const stat = await readFile(`/proc/${pid}/stat`, "utf8").catch((error: unknown) => + error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ESRCH") + ? null + : undefined, + ) + if (stat === null) return true + if (stat !== undefined) return isZombieState(parseLinuxProcState(stat)) + } + const state = await psState(pid) + if (state === undefined) return !alive(pid) + return isZombieState(state) +} diff --git a/packages/client/src/service-restart.ts b/packages/client/src/service-restart.ts new file mode 100644 index 00000000000..cf1b391ca84 --- /dev/null +++ b/packages/client/src/service-restart.ts @@ -0,0 +1,117 @@ +import { randomUUID } from "node:crypto" +import { open, readFile, rename, unlink, writeFile } from "node:fs/promises" +import { fallback } from "./service-probe.js" +import type { EnsureTiming } from "./service-timing.js" + +type Lock = { + token: string + pid: number + startedAt: number + completedAt?: number +} + +/** Shared cross-process reboot state lives next to the registration file. */ +export function restartLockPath(file?: string) { + return `${file ?? fallback()}.restart` +} + +/** + * Claim a reboot, or return undefined when another client's reboot should be reused. Any client + * process may call this; the lock file, not in-memory state, decides who owns the current window. + */ +export async function tryBeginRestart( + file: string | undefined, + timing: EnsureTiming, +): Promise<{ readonly token: string } | undefined> { + const path = restartLockPath(file) + try { + const claimed = await claim(path, timing) + if (claimed !== undefined) return claimed + const existing = await readLock(path) + if (existing === undefined) return undefined + const now = nowOf(timing) + if (existing.completedAt !== undefined) { + // A finished reboot is not in progress. Its completion starts the cooldown for everyone. + if (now < existing.completedAt + timing.restartCooldown) return undefined + } else if (alive(existing.pid) && now - existing.startedAt < timing.restartLockStale) { + // The owner is still working; reuse its reboot rather than killing the server a second time. + return undefined + } + await unlink(path).catch(() => undefined) + return await claim(path, timing) + } catch { + // The lock is best-effort; it must never break ensure(). + return undefined + } +} + +/** Mark the reboot held by `token` finished so other clients start their cooldown from now. */ +export async function completeRestart(file: string | undefined, token: string, timing?: EnsureTiming) { + const path = restartLockPath(file) + try { + const existing = await readLock(path) + if (existing?.token !== token) return + const completed = { ...existing, completedAt: nowOf(timing) } satisfies Lock + const temporary = `${path}.${token}.tmp` + await writeFile(temporary, JSON.stringify(completed)) + await rename(temporary, path) + } catch { + // Best-effort. + } +} + +/** Drop a claim that never reached a ready service so a later client may reboot immediately. */ +export async function releaseRestart(file: string | undefined, token: string) { + const path = restartLockPath(file) + try { + const existing = await readLock(path) + if (existing?.token === token) await unlink(path) + } catch { + // Best-effort. + } +} + +async function claim(path: string, timing: EnsureTiming) { + const token = randomUUID() + try { + const handle = await open(path, "wx") + try { + await handle.writeFile(JSON.stringify({ token, pid: process.pid, startedAt: nowOf(timing) } satisfies Lock)) + } finally { + await handle.close() + } + return { token } + } catch (error) { + if (isCode(error, "EEXIST")) return undefined + throw error + } +} + +async function readLock(path: string): Promise { + try { + const lock = JSON.parse(await readFile(path, "utf8")) as Lock + if (typeof lock.token !== "string" || !Number.isInteger(lock.pid) || !Number.isFinite(lock.startedAt)) + return undefined + return lock + } catch { + return undefined + } +} + +function alive(pid: number) { + try { + process.kill(pid, 0) + return true + } catch (error) { + // EPERM still means the process exists, just owned by another user. + return isCode(error, "EPERM") + } +} + +function nowOf(timing: EnsureTiming | undefined) { + return timing?.now?.() ?? Date.now() +} + +function isCode(error: unknown, code: string) { + return error instanceof Error && "code" in error && error.code === code +} diff --git a/packages/client/src/service-timing.ts b/packages/client/src/service-timing.ts index 03db9f6cb2c..61ebde66240 100644 --- a/packages/client/src/service-timing.ts +++ b/packages/client/src/service-timing.ts @@ -6,6 +6,15 @@ export type EnsureTiming = { readonly promiseTimeout: number readonly stopPollInterval: number readonly stopPollAttempts: number + readonly unresponsiveWindow: number + readonly unresponsiveFailures: number + readonly startingWindow: number + readonly startingFailures: number + readonly restartCooldown: number + readonly restartLockStale: number + /** Test hook for deterministic cross-process restart timing. */ + readonly now?: () => number + readonly signal?: (pid: number, name: NodeJS.Signals) => void } const timings = new WeakMap() @@ -13,20 +22,41 @@ const timings = new WeakMap() // A freshly spawned service registers in ~250 ms, so the poll cadence is a large share of the // time a client waits for it. Probes are sequential, so the wait between them only matters while // the connection is refused; both variants give up after promiseTimeout of wall-clock time. +// promiseTimeout must stay longer than startingWindow: the loop stops at this deadline, so a +// window that reaches or exceeds it could never elapse and escalation would be unreachable. export const defaultEnsureTiming: EnsureTiming = { pollInterval: 25, requestTimeout: 2_000, spawnDelay: 5_000, maxSpawnDelay: 30_000, - promiseTimeout: 120_000, + promiseTimeout: 300_000, stopPollInterval: 50, stopPollAttempts: 100, + // A service that was ready and stops answering is hung: three two-second probes replace it in + // roughly six seconds, as before the slow-boot tolerance was added. + unresponsiveWindow: 0, + unresponsiveFailures: 3, + // A service still reporting `starting` may hold its event loop for minutes while loading. Only + // escalate after this much longer streak, and let promiseTimeout bound the overall wait. + startingWindow: 240_000, + startingFailures: 12, + // Shared across processes through the restart lock file: clients that see a completed reboot wait + // out this cooldown before starting their own, and abandon a lock whose owner died or stalled. + restartCooldown: 30_000, + restartLockStale: 600_000, } export function ensureTiming(options: object) { return timings.get(options) ?? defaultEnsureTiming } +/** Pick the timeout streak that escalates an unresponsive owner, based on its advertised state. */ +export function unresponsiveThreshold(timing: EnsureTiming, starting: boolean) { + return starting + ? { window: timing.startingWindow, failures: timing.startingFailures } + : { window: timing.unresponsiveWindow, failures: timing.unresponsiveFailures } +} + // Keep test timing out of the public lifecycle option types. export function withEnsureTiming(options: A, overrides: Partial): A { timings.set(options, { ...defaultEnsureTiming, ...overrides }) diff --git a/packages/client/src/service.ts b/packages/client/src/service.ts index 78d4b9a60eb..73312927f18 100644 --- a/packages/client/src/service.ts +++ b/packages/client/src/service.ts @@ -52,6 +52,8 @@ export type Info = { readonly url: string /** Operating system process identifier. */ readonly pid: number + /** Readiness advertised while the service boots; absent on registrations from older servers. */ + readonly state?: "starting" | "ready" /** Private service password, when authentication is enabled. */ readonly password?: string } diff --git a/packages/client/test/fixture/service-timing.ts b/packages/client/test/fixture/service-timing.ts index 8c9ff85e15a..2e0603bdad8 100644 --- a/packages/client/test/fixture/service-timing.ts +++ b/packages/client/test/fixture/service-timing.ts @@ -1,4 +1,4 @@ -import { withEnsureTiming } from "../../src/service-timing" +import { withEnsureTiming, type EnsureTiming } from "../../src/service-timing" const timing = { pollInterval: 20, @@ -7,10 +7,13 @@ const timing = { maxSpawnDelay: 1_200, promiseTimeout: 3_000, stopPollInterval: 5, + unresponsiveWindow: 0, + unresponsiveFailures: 3, + restartCooldown: 0, } -export function accelerate(ensure: (options?: A) => B) { - return (options: A) => ensure(withEnsureTiming(options, timing)) +export function accelerate(ensure: (options?: A) => B, overrides: Partial = {}) { + return (options: A) => ensure(withEnsureTiming(options, { ...timing, ...overrides })) } export async function waitForExit(pid: number) { diff --git a/packages/client/test/fixture/service.ts b/packages/client/test/fixture/service.ts index 77cabf01410..60d33231526 100644 --- a/packages/client/test/fixture/service.ts +++ b/packages/client/test/fixture/service.ts @@ -1,6 +1,6 @@ import { appendFile, rename, rm, writeFile } from "node:fs/promises" -const [registration, mode, delay] = process.argv.slice(2) +const [registration, mode, delay, state] = process.argv.slice(2) if (registration === undefined || mode === undefined) throw new Error("Missing service fixture arguments") if (mode === "failed") process.exit(1) if (mode === "stderr-failed") { @@ -75,8 +75,21 @@ const server = Bun.serve({ return new Response(null, { status: 404 }) requests += 1 if (mode === "starting") await writeFile(registration + ".status-request", "") - if (mode === "hanging" || controlled === "hang") { + if (mode === "hanging" || controlled === "hang" || (mode === "recovering" && requests <= 3) || mode === "intermittent") { await appendFile(registration + ".requests", process.pid + "\n") + // A single healthy answer in the middle of a timeout streak must reset the streak. + if (mode === "intermittent" && requests === 3) + return Response.json( + { version, pid: process.pid, urls: [server.url.toString()], paths: { tmp: "/tmp/opencode" } }, + { status: 503 }, + ) + if (mode === "intermittent" && requests === 6) + return Response.json({ + version, + pid: process.pid, + urls: [server.url.toString()], + paths: { tmp: "/tmp/opencode" }, + }) return new Promise(() => {}) } if (mode === "modern" && requests === 1) { @@ -116,6 +129,7 @@ await writeFile( version, url: server.url.toString(), pid: process.pid, + ...(state === "ready" || state === "starting" ? { state } : {}), password: "private", }), { mode: 0o600 }, @@ -123,7 +137,10 @@ await writeFile( await rename(registration + ".tmp", registration) async function shutdown(signal?: NodeJS.Signals) { - if (signal !== undefined) await writeFile(registration + ".signal", signal) + if (signal !== undefined) { + await appendFile(registration + ".signals", signal + "\n") + await writeFile(registration + ".signal", signal) + } // A lingering server unregisters on SIGTERM but keeps running, and holds its port, until killed. if (mode === "lingering") { await rm(registration, { force: true }) diff --git a/packages/client/test/promise-service.test.ts b/packages/client/test/promise-service.test.ts index c0cdb746736..a58b3c39806 100644 --- a/packages/client/test/promise-service.test.ts +++ b/packages/client/test/promise-service.test.ts @@ -8,9 +8,14 @@ import { stoppedExitCode, } from "./fixture/service-fixture" import { accelerate } from "./fixture/service-timing" +import { completeRestart, releaseRestart, tryBeginRestart } from "../src/service-restart" +import { defaultEnsureTiming, type EnsureTiming, withEnsureTiming } from "../src/service-timing" const ensure = accelerate(Service.ensure) const stop = accelerate(Service.stop) +const ensureSlowWindow = accelerate(Service.ensure, { unresponsiveWindow: 2_000, spawnDelay: 5_000 }) +const ensurePatient = accelerate(Service.ensure, { spawnDelay: 5_000 }) +const ensureTolerant = accelerate(Service.ensure, { startingWindow: 2_000, startingFailures: 12, spawnDelay: 5_000 }) test("discovers a registered service", async () => { await using fixture = await serviceFixture() @@ -224,6 +229,124 @@ test("evicts an unresponsive registered service before starting its replacement" expect(endpoint.url).toBe(replacement.url) }) +test("escalates a ready owner that stops answering after three probes", async () => { + await using fixture = await serviceFixture() + const registration = fixture.registration + const existing = fixture.spawn("hanging", "0", "ready") + await fixture.waitForFile() + const starts: EnsureReason[] = [] + + const endpoint = await ensure({ + file: registration, + version: "test", + command: fixture.command("delayed", "10"), + onStart: (reason) => starts.push(reason), + }) + fixture.track((await Bun.file(registration).json()).pid) + + expect((await Bun.file(registration + ".requests").text()).trim().split("\n")).toHaveLength(3) + expect(await existing.exited).toBe(stoppedExitCode) + expect(starts).toEqual(["missing"]) + expect(endpoint.url).toBe((await Bun.file(registration).json()).url) +}) + +test("a starting owner survives the tolerant timeout window", async () => { + await using fixture = await serviceFixture() + const registration = fixture.registration + const starting = fixture.spawn("recovering", "0", "starting") + await fixture.waitForFile() + const starts: EnsureReason[] = [] + + const endpoint = await ensureTolerant({ + file: registration, + version: "test", + command: fixture.command("delayed", "10"), + onStart: (reason) => starts.push(reason), + }) + + expect((await Bun.file(registration + ".requests").text()).trim().split("\n")).toHaveLength(3) + expect(starts).toEqual([]) + expect(await fixture.signal()).toBeUndefined() + expect(starting.exitCode).toBe(null) + expect(await fixture.starts()).toHaveLength(0) + expect(endpoint.url).toBe((await Bun.file(registration).json()).url) +}) + +test("reuses a registered service that answers after a short timeout streak", async () => { + await using fixture = await serviceFixture() + const registration = fixture.registration + const existing = fixture.spawn("recovering") + await fixture.waitForFile() + const original = await Bun.file(registration).json() + const starts: EnsureReason[] = [] + + const endpoint = await ensureSlowWindow({ + file: registration, + version: "test", + command: [], + onStart: (reason) => starts.push(reason), + }) + + expect(endpoint.url).toBe(original.url) + expect((await Bun.file(registration + ".requests").text()).trim().split("\n")).toHaveLength(3) + expect(await fixture.signal()).toBeUndefined() + expect(existing.exitCode).toBe(null) + expect(await Bun.file(registration).json()).toEqual(original) + expect(starts).toEqual([]) +}) + +test("a healthy answer interleaved into a timeout streak resets it", async () => { + await using fixture = await serviceFixture() + const registration = fixture.registration + const existing = fixture.spawn("intermittent") + await fixture.waitForFile() + const original = await Bun.file(registration).json() + const endpoint = await ensurePatient({ file: registration, version: "test", command: [] }) + expect(endpoint.url).toBe(original.url) + expect(await fixture.signal()).toBeUndefined() + expect(existing.exitCode).toBe(null) + expect(await Bun.file(registration).json()).toEqual(original) +}) + +test("two concurrent ensure calls share one reboot", async () => { + await using fixture = await serviceFixture() + const registration = fixture.registration + const existing = fixture.spawn("hanging") + await fixture.waitForFile() + const original = await Bun.file(registration).json() + const command = fixture.command("delayed", "0") + const results = await Promise.all([ + ensure({ file: registration, version: "test", command }), + ensurePatient({ file: registration, version: "test", command }), + ]) + const signals = (await Bun.file(registration + ".signals").text().catch(() => "")) + .trim() + .split("\n") + .filter(Boolean) + if (catchesSigterm) expect(signals).toHaveLength(1) + expect(await existing.exited).toBe(stoppedExitCode) + expect((await Bun.file(registration + ".starts").text()).trim().split("\n")).toHaveLength(1) + const replacement = await Bun.file(registration).json() + fixture.track(replacement.pid) + expect(replacement.pid).not.toBe(original.pid) + for (const result of results) expect(result.url).toBe(replacement.url) +}) + +test("restart lock honors the completion cooldown", async () => { + await using fixture = await serviceFixture() + const clock = { now: 1_000 } + const timing: EnsureTiming = { ...defaultEnsureTiming, restartCooldown: 150, now: () => clock.now } + const first = await tryBeginRestart(fixture.registration, timing) + if (first === undefined) throw new Error("expected to acquire the restart lock") + await completeRestart(fixture.registration, first.token, timing) + expect(await tryBeginRestart(fixture.registration, timing)).toBeUndefined() + clock.now += 150 + const second = await tryBeginRestart(fixture.registration, timing) + if (second === undefined) throw new Error("expected to acquire the restart lock after the cooldown") + await releaseRestart(fixture.registration, second.token) + expect(await Bun.file(fixture.registration + ".restart").exists()).toBe(false) +}) + test("recovers when the starting service it waits for is stopped", async () => { await using fixture = await serviceFixture() const registration = fixture.registration @@ -300,7 +423,6 @@ test("stop escalates when the registration disappears before the process exits", await stop({ file: registration }) expect(await fixture.signal()).toBe(stopSignal) - expect(() => process.kill(original.pid, 0)).toThrow() await expectNotListening(original.url) expect(await Bun.file(registration).exists()).toBe(false) await existing.exited @@ -308,6 +430,39 @@ test("stop escalates when the registration disappears before the process exits", test.skipIf(process.platform === "win32")( "stop fails when the process survives SIGKILL", + async () => { + await using fixture = await serviceFixture() + const registration = fixture.registration + const existing = fixture.spawn("lingering", "60000") + await fixture.waitForFile() + const original = await Bun.file(registration).json() + + try { + await expect( + Service.stop( + withEnsureTiming( + { file: registration }, + { + stopPollInterval: 5, + stopPollAttempts: 20, + signal: (pid, name) => { + if (name !== "SIGKILL") process.kill(pid, name) + }, + }, + ), + ), + ).rejects.toThrow(`Server process ${original.pid} is still running`) + expect(await Bun.file(registration + ".signal").text()).toBe("SIGTERM") + } finally { + existing.kill("SIGKILL") + await existing.exited + } + }, + 15_000, +) + +test.skipIf(process.platform === "win32")( + "stop treats an unreaped zombie service process as stopped", async () => { await using fixture = await serviceFixture() const registration = fixture.registration @@ -315,8 +470,11 @@ test.skipIf(process.platform === "win32")( await fixture.waitForFile() const original = await Bun.file(registration).json() - await expect(stop({ file: registration })).rejects.toThrow(`Server process ${original.pid} is still running`) - expect(await Bun.file(registration + ".signal").text()).toBe("SIGTERM") + await stop({ file: registration }) + + expect(() => process.kill(original.pid, 0)).not.toThrow() + await expectNotListening(original.url) + expect(await Bun.file(registration).exists()).toBe(false) }, 15_000, ) @@ -343,7 +501,6 @@ test.skipIf(!catchesSigterm)( await stopping - expect(() => process.kill(original.pid, 0)).toThrow() await expectNotListening(original.url) expect(await Bun.file(registration).json()).toEqual(replacement) expect(await fetch(new URL("/api/info", replacement.url)).then((response) => response.json())).toMatchObject({ diff --git a/packages/client/test/service-contender-pool.test.ts b/packages/client/test/service-contender-pool.test.ts index 9bfc62732bf..46e878420ee 100644 --- a/packages/client/test/service-contender-pool.test.ts +++ b/packages/client/test/service-contender-pool.test.ts @@ -15,6 +15,21 @@ afterEach(() => { }) }) +test("a clean contender exit does not write a warning", async () => { + const original = console.warn + const warnings: unknown[][] = [] + console.warn = (...args: unknown[]) => { + warnings.push(args) + } + try { + const contender = clean() + await finished(contender) + expect(warnings).toEqual([]) + } finally { + console.warn = original + } +}) + test("remembers the first startup failure and reports it once no attempt is left", async () => { const pool = contenderPool({ ...defaultEnsureTiming, spawnDelay: 0 }) const survivor = running() diff --git a/packages/client/test/service-process.test.ts b/packages/client/test/service-process.test.ts new file mode 100644 index 00000000000..765e9ff5636 --- /dev/null +++ b/packages/client/test/service-process.test.ts @@ -0,0 +1,31 @@ +import { expect, test } from "bun:test" +import { isZombieState, parseLinuxProcState, parsePsState, processStopped } from "../src/service-process" + +test("parses Linux /proc//stat state even when comm contains spaces and parentheses", () => { + expect(parseLinuxProcState("2117 (opencode) Z 1 2117 2117 0 -1")).toBe("Z") + expect(parseLinuxProcState("2117 (opencode (serve)) Z 1 2117 2117 0 -1")).toBe("Z") + expect(parseLinuxProcState("2117 (opencode (serve)) S 1 2117 2117 0 -1")).toBe("S") + expect(parseLinuxProcState("2117 (opencode) D 1 2117 2117 0 -1")).toBe("D") + expect(parseLinuxProcState("malformed")).toBeUndefined() +}) + +test("parses ps state output and identifies zombie states", () => { + expect(parsePsState("Z\n")).toBe("Z") + expect(parsePsState(" Z+ \n")).toBe("Z") + expect(parsePsState("ZN\n")).toBe("Z") + expect(parsePsState("S+\n")).toBe("S") + expect(parsePsState("")).toBeUndefined() + expect(isZombieState("Z")).toBe(true) + expect(isZombieState("S")).toBe(false) + expect(isZombieState("D")).toBe(false) + expect(isZombieState(undefined)).toBe(false) +}) + +test("reports the current process as running and an exited process as stopped", async () => { + expect(await processStopped(process.pid)).toBe(false) + + const child = Bun.spawn([process.execPath, "-e", "process.exit(0)"], { stdout: "ignore", stderr: "ignore" }) + const pid = child.pid + await child.exited + expect(await processStopped(pid)).toBe(true) +}) diff --git a/packages/client/test/service.test.ts b/packages/client/test/service.test.ts index 81101f273ab..1ec84255384 100644 --- a/packages/client/test/service.test.ts +++ b/packages/client/test/service.test.ts @@ -11,9 +11,14 @@ import { stoppedExitCode, } from "./fixture/service-fixture" import { accelerate } from "./fixture/service-timing" +import { completeRestart, releaseRestart, tryBeginRestart } from "../src/service-restart" +import { defaultEnsureTiming, type EnsureTiming, withEnsureTiming } from "../src/service-timing" const ensure = accelerate(Service.ensure) const stop = accelerate(Service.stop) +const ensureSlowWindow = accelerate(Service.ensure, { unresponsiveWindow: 2_000, spawnDelay: 5_000 }) +const ensurePatient = accelerate(Service.ensure, { spawnDelay: 5_000 }) +const ensureTolerant = accelerate(Service.ensure, { startingWindow: 2_000, startingFailures: 12, spawnDelay: 5_000 }) test("a concurrent same-version start cannot invalidate a resolved endpoint", async () => { await using fixture = await serviceFixture() @@ -199,6 +204,130 @@ test("evicts an unresponsive registered service before starting its replacement" expect(await status(endpoint.url)).toMatchObject({ version: "test", pid: replacement.pid }) }) +test("escalates a ready owner that stops answering after three probes", async () => { + await using fixture = await serviceFixture() + const registration = fixture.registration + const existing = fixture.spawn("hanging", "0", "ready") + await fixture.waitForFile() + const starts: EnsureReason[] = [] + + const endpoint = await run( + ensure({ + file: registration, + version: "test", + command: fixture.command("delayed", "10"), + onStart: (reason) => starts.push(reason), + }), + ) + fixture.track((await Bun.file(registration).json()).pid) + + expect((await Bun.file(registration + ".requests").text()).trim().split("\n")).toHaveLength(3) + expect(await existing.exited).toBe(stoppedExitCode) + expect(starts).toEqual(["missing"]) + expect(endpoint.url).toBe((await Bun.file(registration).json()).url) +}) + +test("a starting owner survives the tolerant timeout window", async () => { + await using fixture = await serviceFixture() + const registration = fixture.registration + const starting = fixture.spawn("recovering", "0", "starting") + await fixture.waitForFile() + const starts: EnsureReason[] = [] + + const endpoint = await run( + ensureTolerant({ + file: registration, + version: "test", + command: fixture.command("delayed", "10"), + onStart: (reason) => starts.push(reason), + }), + ) + + expect((await Bun.file(registration + ".requests").text()).trim().split("\n")).toHaveLength(3) + expect(starts).toEqual([]) + expect(await fixture.signal()).toBeUndefined() + expect(starting.exitCode).toBe(null) + expect(await fixture.starts()).toHaveLength(0) + expect(endpoint.url).toBe((await Bun.file(registration).json()).url) +}) + +test("reuses a registered service that answers after a short timeout streak", async () => { + await using fixture = await serviceFixture() + const registration = fixture.registration + const existing = fixture.spawn("recovering") + await fixture.waitForFile() + const original = await Bun.file(registration).json() + const starts: EnsureReason[] = [] + + const endpoint = await run( + ensureSlowWindow({ + file: registration, + version: "test", + command: [], + onStart: (reason) => starts.push(reason), + }), + ) + + expect(endpoint.url).toBe(original.url) + expect((await Bun.file(registration + ".requests").text()).trim().split("\n")).toHaveLength(3) + expect(await fixture.signal()).toBeUndefined() + expect(existing.exitCode).toBe(null) + expect(await Bun.file(registration).json()).toEqual(original) + expect(starts).toEqual([]) +}) + +test("a healthy answer interleaved into a timeout streak resets it", async () => { + await using fixture = await serviceFixture() + const registration = fixture.registration + const existing = fixture.spawn("intermittent") + await fixture.waitForFile() + const original = await Bun.file(registration).json() + const endpoint = await run(ensurePatient({ file: registration, version: "test", command: [] })) + expect(endpoint.url).toBe(original.url) + expect(await fixture.signal()).toBeUndefined() + expect(existing.exitCode).toBe(null) + expect(await Bun.file(registration).json()).toEqual(original) +}) + +test("two concurrent ensure calls share one reboot", async () => { + await using fixture = await serviceFixture() + const registration = fixture.registration + const existing = fixture.spawn("hanging") + await fixture.waitForFile() + const original = await Bun.file(registration).json() + const command = fixture.command("delayed", "0") + const results = await Promise.all([ + run(ensure({ file: registration, version: "test", command })), + run(ensurePatient({ file: registration, version: "test", command })), + ]) + const signals = (await Bun.file(registration + ".signals").text().catch(() => "")) + .trim() + .split("\n") + .filter(Boolean) + if (catchesSigterm) expect(signals).toHaveLength(1) + expect(await existing.exited).toBe(stoppedExitCode) + expect((await Bun.file(registration + ".starts").text()).trim().split("\n")).toHaveLength(1) + const replacement = await Bun.file(registration).json() + fixture.track(replacement.pid) + expect(replacement.pid).not.toBe(original.pid) + for (const result of results) expect(result.url).toBe(replacement.url) +}) + +test("restart lock honors the completion cooldown", async () => { + await using fixture = await serviceFixture() + const clock = { now: 1_000 } + const timing: EnsureTiming = { ...defaultEnsureTiming, restartCooldown: 150, now: () => clock.now } + const first = await tryBeginRestart(fixture.registration, timing) + if (first === undefined) throw new Error("expected to acquire the restart lock") + await completeRestart(fixture.registration, first.token, timing) + expect(await tryBeginRestart(fixture.registration, timing)).toBeUndefined() + clock.now += 150 + const second = await tryBeginRestart(fixture.registration, timing) + if (second === undefined) throw new Error("expected to acquire the restart lock after the cooldown") + await releaseRestart(fixture.registration, second.token) + expect(await Bun.file(fixture.registration + ".restart").exists()).toBe(false) +}) + test("signals an unresponsive registered service process", async () => { await using fixture = await serviceFixture() const registration = fixture.registration @@ -221,7 +350,6 @@ test("stop escalates when the registration disappears before the process exits", await run(stop({ file: registration })) expect(await fixture.signal()).toBe(stopSignal) - expect(() => process.kill(original.pid, 0)).toThrow() await expectNotListening(original.url) expect(await Bun.file(registration).exists()).toBe(false) await existing.exited @@ -229,6 +357,41 @@ test("stop escalates when the registration disappears before the process exits", test.skipIf(process.platform === "win32")( "stop fails when the process survives SIGKILL", + async () => { + await using fixture = await serviceFixture() + const registration = fixture.registration + const existing = fixture.spawn("lingering", "60000") + await fixture.waitForFile() + const original = await Bun.file(registration).json() + + try { + await expect( + run( + Service.stop( + withEnsureTiming( + { file: registration }, + { + stopPollInterval: 5, + stopPollAttempts: 20, + signal: (pid, name) => { + if (name !== "SIGKILL") process.kill(pid, name) + }, + }, + ), + ), + ), + ).rejects.toThrow(`Server process ${original.pid} is still running`) + expect(await Bun.file(registration + ".signal").text()).toBe("SIGTERM") + } finally { + existing.kill("SIGKILL") + await existing.exited + } + }, + 15_000, +) + +test.skipIf(process.platform === "win32")( + "stop treats an unreaped zombie service process as stopped", async () => { await using fixture = await serviceFixture() const registration = fixture.registration @@ -236,8 +399,38 @@ test.skipIf(process.platform === "win32")( await fixture.waitForFile() const original = await Bun.file(registration).json() - await expect(run(stop({ file: registration }))).rejects.toThrow(`Server process ${original.pid} is still running`) - expect(await Bun.file(registration + ".signal").text()).toBe("SIGTERM") + await run(stop({ file: registration })) + + // The zombie remains in the process table until its parent exits, yet the service is stopped. + expect(() => process.kill(original.pid, 0)).not.toThrow() + await expectNotListening(original.url) + expect(await Bun.file(registration).exists()).toBe(false) + }, + 15_000, +) + +test.skipIf(process.platform === "win32")( + "evicts an unresponsive unreaped service that becomes a zombie", + async () => { + await using fixture = await serviceFixture() + const registration = fixture.registration + fixture.spawnUnreaped("hanging") + await fixture.waitForFile() + const original = await Bun.file(registration).json() + + const endpoint = await run( + ensure({ + file: registration, + version: "test", + command: fixture.command("delayed", "10"), + }), + ) + const replacement = await Bun.file(registration).json() + fixture.track(replacement.pid) + + expect(() => process.kill(original.pid, 0)).not.toThrow() + expect(replacement.pid).not.toBe(original.pid) + expect(endpoint.url).toBe(replacement.url) }, 15_000, ) @@ -264,7 +457,6 @@ test.skipIf(!catchesSigterm)( await stopping - expect(() => process.kill(original.pid, 0)).toThrow() await expectNotListening(original.url) expect(await Bun.file(registration).json()).toEqual(replacement) expect(await status(replacement.url)).toMatchObject({ pid: successor.pid }) diff --git a/packages/server/src/process.ts b/packages/server/src/process.ts index 43b5197f41b..957b4eea1bf 100644 --- a/packages/server/src/process.ts +++ b/packages/server/src/process.ts @@ -14,7 +14,7 @@ import { hasMcpClientTicketURL } from "@opencode/protocol/groups/mcp" import { isMachineLinkUpgrade } from "@opencode/protocol/groups/machine" import { isPairingConnectURL } from "@opencode/protocol/groups/server" import { Global } from "@opencode/util/global" -import { Cause, Context, Effect, Exit, Latch, Layer, Option, Ref, Scope } from "effect" +import { Cause, Context, Deferred, Effect, Exit, Latch, Layer, Option, Ref, Scope } from "effect" import { HttpMiddleware, HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http" import { NetAddress } from "effect/net" import { createServer } from "node:http" @@ -33,6 +33,7 @@ export interface Lifecycle { readonly onListen: ( address: NetAddress.SocketAddress, shutdown: Effect.Effect, + ready: Effect.Effect, ) => Effect.Effect, E, R> } @@ -64,6 +65,8 @@ export const start = Effect.fn("ServerProcess.start")(function* ( const port = Option.fromNullishOr(options.port) const shutdown = yield* Latch.make() const status = yield* Status.make() + // `status.ready` mutates the status; listeners need an effect that waits until boot actually built the routes. + const booted = yield* Deferred.make() const bound = yield* listen({ hostname, port }) const localURLs = () => { const address = bound.server.address() @@ -96,7 +99,7 @@ export const start = Effect.fn("ServerProcess.start")(function* ( ) .pipe(Effect.provide(NodeHttpServer.layerHttpServices), withoutParentSpan) if (lifecycle) - yield* lifecycle.onListen(bound.http.address, shutdown.open.pipe(Effect.asVoid)).pipe( + yield* lifecycle.onListen(bound.http.address, shutdown.open.pipe(Effect.asVoid), Deferred.await(booted)).pipe( Effect.flatMap((cleanup) => Effect.addFinalizer(() => Scope.close(bound.scope, Exit.void).pipe(Effect.andThen(cleanup))), ), @@ -143,6 +146,8 @@ export const start = Effect.fn("ServerProcess.start")(function* ( yield* Ref.set(machinesFlag, yield* machinesEnabled.pipe(Effect.provide(context))) yield* Ref.set(application, Option.some(Context.get(context, HttpRouter.HttpRouter).asHttpEffect())) yield* status.ready + // Only advertise readiness to listeners after the routes are installed and /api/info reports 200. + yield* Deferred.succeed(booted, undefined) const bus = Context.get(context, Bus.Service) return { address: bound.http.address, @@ -153,20 +158,26 @@ export const start = Effect.fn("ServerProcess.start")(function* ( } }).pipe( withoutParentSpan, - Effect.catchCause((cause) => { - if (!lifecycle || Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause) - return status.fail.pipe( - Effect.andThen( - Scope.close(applicationScope, Exit.failCause(cause)).pipe( - Effect.catchCause((cleanupCause) => - Effect.logError("failed to clean up background service boot", { cause: cleanupCause }), + Effect.catchCause((cause) => + // A failed boot must never satisfy a listener waiting to advertise `ready`. The readiness + // channel is failure-free, so the boot cause is parked as a defect that listeners only ignore. + Deferred.failCause(booted, Cause.die(cause)).pipe( + Effect.andThen(() => { + if (!lifecycle || Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause) + return status.fail.pipe( + Effect.andThen( + Scope.close(applicationScope, Exit.failCause(cause)).pipe( + Effect.catchCause((cleanupCause) => + Effect.logError("failed to clean up background service boot", { cause: cleanupCause }), + ), + ), ), - ), - ), - Effect.andThen(Effect.logError("background service boot failed", { cause })), - Effect.andThen(Effect.never), - ) - }), + Effect.andThen(Effect.logError("background service boot failed", { cause })), + Effect.andThen(Effect.never), + ) + }), + ), + ), ) if (!lifecycle) return yield* boot return yield* Effect.raceFirst(boot, shutdown.await.pipe(Effect.andThen(Effect.interrupt))) diff --git a/packages/server/test/process.test.ts b/packages/server/test/process.test.ts index 20ada8bae07..ea5cd1f52a3 100644 --- a/packages/server/test/process.test.ts +++ b/packages/server/test/process.test.ts @@ -1,5 +1,8 @@ import { expect } from "bun:test" -import { Effect } from "effect" +import fs from "node:fs/promises" +import os from "node:os" +import path from "node:path" +import { Deferred, Effect, Exit, Fiber } from "effect" import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http" import { it } from "../../core/test/lib/effect" import { ServerProcess } from "../src/process" @@ -259,3 +262,86 @@ it.live("server info lists remote URLs alongside local addresses while they are expect((yield* info()).urls).toEqual([base]) }), ) + +it.live("a listener's readiness waits for boot before /api/info reports ready", () => + Effect.gen(function* () { + const release = yield* Deferred.make() + const base = yield* Deferred.make() + const ready = yield* Deferred.make>() + const fiber = yield* Effect.forkChild( + ServerProcess.start( + { hostname: "127.0.0.1", port: 0, password: "secret", database: { path: ":memory:" } }, + { + onListen: (address, _shutdown, readyEffect) => + Effect.gen(function* () { + yield* Deferred.succeed(base, HttpServer.formatAddress(address)) + yield* Deferred.succeed(ready, readyEffect) + yield* Deferred.await(release) + return Effect.void + }), + }, + ), + ) + const url = yield* Deferred.await(base) + const readyEffect = yield* Deferred.await(ready) + const infoStatus = () => + Effect.promise(() => + fetch(new URL("/api/info", url), { headers: { authorization: `Basic ${btoa("opencode:secret")}` } }).then( + (response) => response.status, + ), + ) + + // Boot is gated, so the effect handed to the listener must still be pending and the health + // endpoint must stay unavailable. With `status.ready` passed directly this flipped the status. + const completion = yield* Deferred.make() + yield* Effect.forkChild(readyEffect.pipe(Effect.andThen(Deferred.succeed(completion, undefined)))) + yield* Effect.yieldNow + expect(yield* Deferred.isDone(completion)).toBe(false) + expect(yield* infoStatus()).toBe(503) + + yield* Deferred.succeed(release, undefined) + yield* readyEffect + expect(yield* Deferred.isDone(completion)).toBe(true) + expect(yield* infoStatus()).toBe(200) + yield* Fiber.join(fiber) + }), +) + +it.live("a failed boot fails readiness and keeps /api/info reporting failure", () => + Effect.gen(function* () { + const database = yield* Effect.promise(() => fs.mkdtemp(path.join(os.tmpdir(), "opencode-server-boot-"))) + const release = yield* Deferred.make() + const base = yield* Deferred.make() + const ready = yield* Deferred.make>() + yield* Effect.forkChild( + ServerProcess.start( + { hostname: "127.0.0.1", port: 0, password: "secret", database: { path: database } }, + { + onListen: (address, _shutdown, readyEffect) => + Effect.gen(function* () { + yield* Deferred.succeed(base, HttpServer.formatAddress(address)) + yield* Deferred.succeed(ready, readyEffect) + yield* Deferred.await(release) + return Effect.void + }), + }, + ), + ) + const url = yield* Deferred.await(base) + const readyEffect = yield* Deferred.await(ready) + const infoStatus = () => + Effect.promise(() => + fetch(new URL("/api/info", url), { headers: { authorization: `Basic ${btoa("opencode:secret")}` } }).then( + (response) => response.status, + ), + ) + expect(yield* infoStatus()).toBe(503) + + yield* Deferred.succeed(release, undefined) + // A failed boot never advertises readiness: a client waiting on this effect sees the failure + // instead of a success that would hand out an endpoint whose routes were never built. + expect(Exit.isFailure(yield* Effect.exit(readyEffect))).toBe(true) + expect(yield* infoStatus()).toBe(500) + yield* Effect.promise(() => fs.rm(database, { recursive: true, force: true })) + }), +)