mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
fix(core): recover persistent terminal handoff after temp cleanup
This commit is contained in:
parent
20cf09752d
commit
f993ec1542
4 changed files with 158 additions and 13 deletions
|
|
@ -1,5 +1,5 @@
|
|||
import { spawn } from "node:child_process"
|
||||
import { readFile } from "node:fs/promises"
|
||||
import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"
|
||||
import net from "node:net"
|
||||
import path from "node:path"
|
||||
import { Data, Duration, Effect, Schema, Semaphore } from "effect"
|
||||
|
|
@ -336,6 +336,10 @@ export const makeDaemonTransport = Effect.fn("PersistentPty.makeDaemonTransport"
|
|||
const current = owner
|
||||
const registered = registration
|
||||
if (!current || !registered) return null
|
||||
yield* Effect.tryPromise({
|
||||
try: () => restoreRegistration(directory, registered),
|
||||
catch: (cause) => failure("registration", cause),
|
||||
})
|
||||
const response = yield* Effect.tryPromise({
|
||||
try: (signal) => current.exchange({ op: "prepare_handoff" }, signal),
|
||||
catch: (cause) => failure("response", cause),
|
||||
|
|
@ -384,6 +388,17 @@ export const makeDaemonTransport = Effect.fn("PersistentPty.makeDaemonTransport"
|
|||
return { request, requestIfRunning, shutdown, handoff, subscribe } satisfies DaemonTransport
|
||||
})
|
||||
|
||||
// The daemon writes its registration once at startup, so temporary-file cleaners can delete it while the daemon
|
||||
// keeps running. The replacement server can only adopt the daemon by rediscovering this file.
|
||||
async function restoreRegistration(directory: string, registration: Registration) {
|
||||
const file = path.join(directory, "service.json")
|
||||
if (await stat(file).catch(() => undefined)) return
|
||||
await mkdir(directory, { recursive: true, mode: 0o700 })
|
||||
const temporary = path.join(directory, `service.${registration.instance_id}.${crypto.randomUUID()}.tmp`)
|
||||
await writeFile(temporary, JSON.stringify(registration), { mode: 0o600, flag: "wx" })
|
||||
await rename(temporary, file).finally(() => rm(temporary, { force: true }))
|
||||
}
|
||||
|
||||
async function openOwner(registration: Registration, ticket: string | undefined, signal: AbortSignal) {
|
||||
const socket = net.createConnection({ path: registration.socket })
|
||||
const frames = decoder(socket)
|
||||
|
|
|
|||
|
|
@ -121,14 +121,23 @@ const makeLayer = (options: Options = {}) =>
|
|||
const context = yield* Effect.context()
|
||||
const runFork = Effect.runForkWith(context)
|
||||
let binary: Promise<string> | undefined
|
||||
const daemon = yield* makeDaemonTransport(
|
||||
options.handoff?.directory ?? runtimeDirectory(),
|
||||
() =>
|
||||
(binary ??= resolveBinary(global.bin).catch((error) => {
|
||||
binary = undefined
|
||||
throw error
|
||||
})),
|
||||
options.handoff,
|
||||
const executable = () =>
|
||||
(binary ??= resolveBinary(global.bin).catch((error) => {
|
||||
binary = undefined
|
||||
throw error
|
||||
}))
|
||||
const daemon = yield* (
|
||||
options.handoff === undefined
|
||||
? makeDaemonTransport(runtimeDirectory(), executable)
|
||||
: makeDaemonTransport(options.handoff.directory, executable, options.handoff).pipe(
|
||||
// A failed boot would stay registered and block every client until a manual restart. The skipped
|
||||
// daemon stops by itself when its handoff ticket expires.
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("starting without persistent terminals from the previous server", {
|
||||
error: error.message,
|
||||
}).pipe(Effect.andThen(makeDaemonTransport(runtimeDirectory(), executable))),
|
||||
),
|
||||
)
|
||||
).pipe(Effect.mapError(unavailable))
|
||||
const removing = new Set<Pty.ID>()
|
||||
// Controller activity selects a terminal; observer reads and pane visibility do not.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { expect } from "bun:test"
|
||||
import { spawn } from "node:child_process"
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises"
|
||||
import { mkdtemp, rm, stat, writeFile } from "node:fs/promises"
|
||||
import net from "node:net"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
|
|
@ -133,6 +133,34 @@ it.live("does not replay a dispatched mutating request when its response is lost
|
|||
}),
|
||||
)
|
||||
|
||||
it.live("restores a removed registration before preparing a handoff", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* temporaryDirectory()
|
||||
const socketPath = path.join(directory, "daemon.sock")
|
||||
yield* listen(socketPath, (_socket, request) => {
|
||||
if (request.op === "ping") return pong
|
||||
if (request.op === "prepare_handoff")
|
||||
return { type: "handoff", ticket: "ticket", expires_at: Date.now() + 60_000 }
|
||||
return { type: "terminals", terminals: [] }
|
||||
})
|
||||
yield* Effect.promise(() => writeRegistration(directory, socketPath))
|
||||
const file = path.join(directory, "service.json")
|
||||
const registration = yield* Effect.promise(() => Bun.file(file).json())
|
||||
const original = yield* makeDaemonTransport(directory)
|
||||
yield* original.request({ op: "list" })
|
||||
yield* Effect.promise(() => rm(file))
|
||||
|
||||
const handoff = yield* original.handoff
|
||||
expect(handoff).toMatchObject({ directory, instanceID: "test", ticket: "ticket" })
|
||||
expect(yield* Effect.promise(() => Bun.file(file).json())).toEqual(registration)
|
||||
expect((yield* Effect.promise(() => stat(file))).mode & 0o777).toBe(0o600)
|
||||
|
||||
if (!handoff) throw new Error("Expected a handoff")
|
||||
const replacement = yield* makeDaemonTransport(directory, undefined, handoff)
|
||||
expect(yield* replacement.request({ op: "list" })).toEqual({ type: "terminals", terminals: [] })
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("rejects incompatible daemons without replacing or killing them", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* temporaryDirectory()
|
||||
|
|
@ -187,13 +215,15 @@ function listen(
|
|||
const server = net.createServer((socket) => {
|
||||
sockets.add(socket)
|
||||
socket.once("close", () => sockets.delete(socket))
|
||||
void readRequest(socket)
|
||||
.then((envelope) => {
|
||||
const serve = (): Promise<void> =>
|
||||
readRequest(socket).then((envelope) => {
|
||||
const response =
|
||||
envelope.request.op === "own" ? { type: "owned" } : handle(socket, envelope.request, envelope.token)
|
||||
if (response) socket.write(frame(response))
|
||||
// Owner connections stay open for later handoff requests.
|
||||
if (envelope.request.op === "own") return serve()
|
||||
})
|
||||
.catch(() => socket.destroy())
|
||||
void serve().catch(() => socket.destroy())
|
||||
})
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject)
|
||||
|
|
|
|||
|
|
@ -385,6 +385,97 @@ smoke(
|
|||
30_000,
|
||||
)
|
||||
|
||||
smoke(
|
||||
"hands off a live daemon after its registration file was removed",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* testDirectory("xdg")
|
||||
const scope = yield* Scope.Scope
|
||||
const originalScope = yield* Scope.fork(scope)
|
||||
const options = {
|
||||
hostname: "127.0.0.1",
|
||||
port: 0,
|
||||
password: "secret",
|
||||
app: { version: "test-version" },
|
||||
database: { path: fixture.database },
|
||||
fs: { filewatcher: false },
|
||||
}
|
||||
const original = yield* ServerProcess.start<never, never>(options).pipe(
|
||||
Effect.provideService(Scope.Scope, originalScope),
|
||||
)
|
||||
const base = HttpServer.formatAddress(original.address)
|
||||
const sessionID = Session.ID.make("ses_persistent_pty_cleaned")
|
||||
const terminal = Schema.decodeUnknownSync(PersistentPty.Info)(
|
||||
(yield* request(base, "POST", `/api/experimental/session/${sessionID}/terminal`, {
|
||||
command: "/bin/sh",
|
||||
args: ["-c", "stty -echo; printf before-cleanup; exec cat"],
|
||||
cwd: process.cwd(),
|
||||
title: "survivor",
|
||||
env: {},
|
||||
})).data,
|
||||
)
|
||||
expect(yield* waitForText(base, terminal.id, "before-cleanup")).toContain("before-cleanup")
|
||||
const [directory] = yield* Effect.promise(() => fs.readdir(fixture.directory))
|
||||
if (!directory) throw new Error("Missing daemon directory")
|
||||
const file = path.join(fixture.directory, directory, "service.json")
|
||||
const registration = Schema.decodeUnknownSync(Schema.Struct({ pid: Schema.Number }))(
|
||||
yield* Effect.promise(() => Bun.file(file).json()),
|
||||
)
|
||||
// Age-based temporary cleanup removes the registration while the daemon and its owner stay alive.
|
||||
yield* Effect.promise(() => fs.rm(file))
|
||||
expect((yield* request(base, "GET", `/api/experimental/session/${sessionID}/terminal`)).data).toMatchObject([
|
||||
{ id: terminal.id, pid: terminal.pid },
|
||||
])
|
||||
|
||||
const handoff = Schema.decodeUnknownSync(PersistentPty.Handoff)(
|
||||
(yield* request(base, "POST", "/api/experimental/persistent-pty/handoff")).handoff,
|
||||
)
|
||||
yield* Scope.close(originalScope, Exit.void)
|
||||
expect(process.kill(registration.pid, 0)).toBeTrue()
|
||||
|
||||
const replacementScope = yield* Scope.fork(scope)
|
||||
const replacement = yield* ServerProcess.start<never, never>({ ...options, pty: { handoff } }).pipe(
|
||||
Effect.provideService(Scope.Scope, replacementScope),
|
||||
)
|
||||
const replacementBase = HttpServer.formatAddress(replacement.address)
|
||||
expect(
|
||||
(yield* request(replacementBase, "GET", `/api/experimental/session/${sessionID}/terminal`)).data,
|
||||
).toMatchObject([{ id: terminal.id, pid: terminal.pid }])
|
||||
expect(yield* waitForText(replacementBase, terminal.id, "before-cleanup")).toContain("before-cleanup")
|
||||
|
||||
yield* Scope.close(replacementScope, Exit.void)
|
||||
yield* waitForExit(registration.pid)
|
||||
yield* waitForExit(terminal.pid)
|
||||
}),
|
||||
30_000,
|
||||
)
|
||||
|
||||
it.live("starts without inherited terminals when a handoff cannot be adopted", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* testDirectory("xdg")
|
||||
// An older owner can hand off after its registration file is gone, leaving nothing for the replacement to adopt.
|
||||
const handoff = {
|
||||
directory: path.join(fixture.directory, "unregistered"),
|
||||
instanceID: "previous",
|
||||
ticket: "ticket",
|
||||
expiresAt: Date.now() + 60_000,
|
||||
}
|
||||
const server = yield* ServerProcess.start<never, never>({
|
||||
hostname: "127.0.0.1",
|
||||
port: 0,
|
||||
password: "secret",
|
||||
app: { version: "test-version" },
|
||||
database: { path: fixture.database },
|
||||
fs: { filewatcher: false },
|
||||
pty: { handoff },
|
||||
})
|
||||
const base = HttpServer.formatAddress(server.address)
|
||||
expect(
|
||||
(yield* request(base, "GET", "/api/experimental/session/ses_persistent_pty_orphaned/terminal")).data,
|
||||
).toEqual([])
|
||||
}),
|
||||
)
|
||||
|
||||
function testDirectory(mode: "xdg" | "override") {
|
||||
return Effect.acquireRelease(
|
||||
Effect.promise(async () => {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue