mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-26 23:28:43 +00:00
fix(client): log client recovery kills of the background service
This commit is contained in:
parent
1b7cc2e5a7
commit
c777d2e1c4
6 changed files with 89 additions and 8 deletions
|
|
@ -1,6 +1,6 @@
|
|||
export * as ServiceRegistration from "./service-registration"
|
||||
|
||||
import { Service, type Info } from "@opencode/client/effect/service"
|
||||
import { Service, ServiceRecovery, type Info } from "@opencode/client/effect/service"
|
||||
import path from "node:path"
|
||||
import { Effect, FileSystem, Schedule, Schema } from "effect"
|
||||
import { HttpServer } from "effect/http"
|
||||
|
|
@ -44,6 +44,15 @@ export const register = Effect.fnUntraced(function* (options: {
|
|||
fs.rename(temp, options.file).pipe(Effect.retry({ times: 20, schedule: Schedule.spaced("10 millis") })),
|
||||
),
|
||||
)
|
||||
const recovered = yield* Effect.promise(() => ServiceRecovery.take(options.file).catch(() => undefined))
|
||||
if (recovered !== undefined)
|
||||
yield* Effect.logWarning("previous managed service was killed by client recovery", {
|
||||
previousServicePID: recovered.pid,
|
||||
previousVersion: recovered.version,
|
||||
signal: recovered.signal,
|
||||
reason: recovered.reason,
|
||||
killedAt: recovered.at,
|
||||
})
|
||||
yield* current.pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("managed service registration check failed; shutting down", {
|
||||
|
|
|
|||
|
|
@ -4,10 +4,11 @@ import { contenderPool, spawnServiceContender } from "../service-contender.js"
|
|||
import { defaultEnsureTiming, ensureTiming, type EnsureTiming } from "../service-timing.js"
|
||||
import { matchesVersion } from "../service-version.js"
|
||||
import { PtyHandoff } from "../pty-handoff.js"
|
||||
import { ServiceRecovery } from "../service-recovery.js"
|
||||
import { decide, fallback, headers, probeResult, same } from "../service-probe.js"
|
||||
|
||||
export * from "../service.js"
|
||||
export { headers }
|
||||
export { headers, ServiceRecovery }
|
||||
/** Contents of the local service registration file. */
|
||||
export type Info = typeof Info.Type
|
||||
|
||||
|
|
@ -81,7 +82,11 @@ export const ensure = Effect.fn("service.ensure")(function* (options: EnsureOpti
|
|||
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)
|
||||
const signal = yield* terminate(info, options, timing)
|
||||
if (signal !== undefined)
|
||||
yield* Effect.tryPromise(() => ServiceRecovery.record(options.file ?? fallback(), info, signal)).pipe(
|
||||
Effect.ignore,
|
||||
)
|
||||
pool.evict(info.pid)
|
||||
pool.recruitNow()
|
||||
timeouts = undefined
|
||||
|
|
@ -181,7 +186,7 @@ const stopped = Effect.fnUntraced(function* (pid: number) {
|
|||
|
||||
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
|
||||
if (current === undefined || !same(current, info)) return undefined
|
||||
yield* signal(info.pid, "SIGTERM")
|
||||
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
|
||||
|
|
@ -190,10 +195,12 @@ const terminate = Effect.fnUntraced(function* (info: Info, options: { readonly f
|
|||
yield* signal(info.pid, "SIGKILL")
|
||||
yield* stopped(info.pid).pipe(Effect.retry(poll(timing)))
|
||||
}
|
||||
const sent = Option.isNone(done) ? "SIGKILL" : "SIGTERM"
|
||||
const latest = yield* read(options.file)
|
||||
if (latest === undefined || !same(latest, info)) return
|
||||
if (latest === undefined || !same(latest, info)) return sent
|
||||
const fs = yield* FileSystem.FileSystem
|
||||
yield* fs.remove(options.file ?? fallback()).pipe(Effect.ignore)
|
||||
return sent
|
||||
})
|
||||
|
||||
/** Effect-based local service lifecycle operations. */
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { contenderPool, spawnServiceContender } from "../service-contender.js"
|
|||
import { defaultEnsureTiming, ensureTiming, type EnsureTiming } from "../service-timing.js"
|
||||
import { matchesVersion } from "../service-version.js"
|
||||
import { PtyHandoff } from "../pty-handoff.js"
|
||||
import { ServiceRecovery } from "../service-recovery.js"
|
||||
import { decide, fallback, headers, probeResult, same } from "../service-probe.js"
|
||||
|
||||
export * from "../service.js"
|
||||
|
|
@ -61,7 +62,9 @@ export async function ensure(options: EnsureOptions = {}): Promise<Endpoint> {
|
|||
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)
|
||||
const signal = await terminate(registration.info, options, timing)
|
||||
if (signal !== undefined)
|
||||
await ServiceRecovery.record(options.file ?? fallback(), registration.info, signal).catch(() => undefined)
|
||||
pool.evict(registration.info.pid)
|
||||
pool.recruitNow()
|
||||
timeouts = undefined
|
||||
|
|
@ -152,17 +155,20 @@ 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
|
||||
if (current === undefined || !same(current, info)) return undefined
|
||||
signal(info.pid, "SIGTERM")
|
||||
let sent: "SIGTERM" | "SIGKILL" = "SIGTERM"
|
||||
// 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")
|
||||
sent = "SIGKILL"
|
||||
if (!(await waitUntilStopped(info.pid, timing))) throw new Error(`Server process ${info.pid} is still running`)
|
||||
}
|
||||
const latest = await read(options.file)
|
||||
if (latest === undefined || !same(latest, info)) return
|
||||
if (latest === undefined || !same(latest, info)) return sent
|
||||
await rm(options.file ?? fallback(), { force: true })
|
||||
return sent
|
||||
}
|
||||
|
||||
function delay(milliseconds: number) {
|
||||
|
|
|
|||
57
packages/client/src/service-recovery.ts
Normal file
57
packages/client/src/service-recovery.ts
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
export * as ServiceRecovery from "./service-recovery.js"
|
||||
|
||||
import { readFile, rename, rm, writeFile } from "node:fs/promises"
|
||||
import type { Info } from "./service.js"
|
||||
|
||||
/** Why and how a client's recovery stopped an unresponsive service, for the next service to log. */
|
||||
export type Entry = {
|
||||
readonly pid: number
|
||||
readonly version?: string
|
||||
readonly signal: "SIGTERM" | "SIGKILL"
|
||||
readonly reason: string
|
||||
readonly at: string
|
||||
}
|
||||
|
||||
// The killed service often cannot write anything, and the client may not log to the service's log file,
|
||||
// so the next service to register reports the kill from this sidecar.
|
||||
export async function record(file: string, info: Info, signal: Entry["signal"]) {
|
||||
const temporary = `${file}.recovery.${crypto.randomUUID()}.tmp`
|
||||
await writeFile(
|
||||
temporary,
|
||||
JSON.stringify({
|
||||
pid: info.pid,
|
||||
version: info.version,
|
||||
signal,
|
||||
reason: "/api/info probes timed out",
|
||||
at: new Date().toISOString(),
|
||||
} satisfies Entry),
|
||||
{ mode: 0o600, flag: "wx" },
|
||||
)
|
||||
await rename(temporary, file + ".recovery").finally(() => rm(temporary, { force: true }))
|
||||
}
|
||||
|
||||
/** Read and remove the last recovery record, if any. */
|
||||
export async function take(file: string): Promise<Entry | undefined> {
|
||||
const claimed = `${file}.recovery.${crypto.randomUUID()}.taken`
|
||||
const moved = await rename(file + ".recovery", claimed).then(
|
||||
() => true,
|
||||
() => false,
|
||||
)
|
||||
if (!moved) return undefined
|
||||
const value: unknown = await readFile(claimed, "utf8")
|
||||
.then((text) => JSON.parse(text))
|
||||
.catch(() => undefined)
|
||||
.finally(() => rm(claimed, { force: true }))
|
||||
if (typeof value !== "object" || value === null) return undefined
|
||||
if (!("pid" in value) || typeof value.pid !== "number") return undefined
|
||||
if (!("signal" in value) || (value.signal !== "SIGTERM" && value.signal !== "SIGKILL")) return undefined
|
||||
if (!("reason" in value) || typeof value.reason !== "string") return undefined
|
||||
if (!("at" in value) || typeof value.at !== "string") return undefined
|
||||
return {
|
||||
pid: value.pid,
|
||||
version: "version" in value && typeof value.version === "string" ? value.version : undefined,
|
||||
signal: value.signal,
|
||||
reason: value.reason,
|
||||
at: value.at,
|
||||
}
|
||||
}
|
||||
|
|
@ -222,6 +222,7 @@ test("evicts an unresponsive registered service before starting its replacement"
|
|||
expect(await existing.exited).toBe(stoppedExitCode)
|
||||
expect(replacement.pid).not.toBe(original.pid)
|
||||
expect(endpoint.url).toBe(replacement.url)
|
||||
expect(await Bun.file(registration + ".recovery").json()).toMatchObject({ pid: original.pid, signal: "SIGTERM" })
|
||||
})
|
||||
|
||||
test("recovers when the starting service it waits for is stopped", async () => {
|
||||
|
|
|
|||
|
|
@ -196,6 +196,7 @@ test("evicts an unresponsive registered service before starting its replacement"
|
|||
expect(await existing.exited).toBe(stoppedExitCode)
|
||||
expect(replacement.pid).not.toBe(original.pid)
|
||||
expect(endpoint.url).toBe(replacement.url)
|
||||
expect(await Bun.file(registration + ".recovery").json()).toMatchObject({ pid: original.pid, signal: "SIGTERM" })
|
||||
expect(await status(endpoint.url)).toMatchObject({ version: "test", pid: replacement.pid })
|
||||
})
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue