From a495f2ac7139c757a0749ae889942415428e63d3 Mon Sep 17 00:00:00 2001 From: yuez Date: Wed, 21 Oct 2026 11:50:51 +0800 Subject: [PATCH] feat(instances): plugin socket server and one-nvim-per-workspace supervisor - JSONL plugin server with hello token auth, frame cap, heartbeat and E_LEASE rejection - PluginConnection with ack correlation, snapshot cache, per-epoch seq - lazy spawn (headless nvim), degrade-on-crash with process_exit fanout, no auto-restart - shutdown drain/stop with SIGTERM/SIGKILL escalation, RSS resources view - 57 tests against a generated fake nvim --- src/instances/connection.ts | 462 ++++++++++++++++ src/instances/errors.ts | 56 ++ src/instances/index.ts | 30 ++ src/instances/plugin-server.ts | 543 +++++++++++++++++++ src/instances/supervisor.ts | 773 +++++++++++++++++++++++++++ test/instances/connection.test.ts | 322 +++++++++++ test/instances/helpers.ts | 549 +++++++++++++++++++ test/instances/plugin-server.test.ts | 330 ++++++++++++ test/instances/supervisor.test.ts | 518 ++++++++++++++++++ 9 files changed, 3583 insertions(+) create mode 100644 src/instances/connection.ts create mode 100644 src/instances/errors.ts create mode 100644 src/instances/index.ts create mode 100644 src/instances/plugin-server.ts create mode 100644 src/instances/supervisor.ts create mode 100644 test/instances/connection.test.ts create mode 100644 test/instances/helpers.ts create mode 100644 test/instances/plugin-server.test.ts create mode 100644 test/instances/supervisor.test.ts diff --git a/src/instances/connection.ts b/src/instances/connection.ts new file mode 100644 index 0000000..6c4d82e --- /dev/null +++ b/src/instances/connection.ts @@ -0,0 +1,462 @@ +/** + * `PluginConnection` implementation over one accepted unix-socket connection. + * + * Framing (JSONL) is owned by `plugin-server.ts`; this module owns the + * protocol semantics: command/ack correlation, session subscriptions, the + * per-session snapshot cache and the `event` relay onto the daemon bus. + * + * The daemon never renumbers: `seq`/`epoch` always come from the plugin. + * A snapshot with a different `epoch` invalidates the cached state for that + * session (the plugin restarted or re-opened the session elsewhere). + */ + +import type { Socket } from "node:net"; +import type { Bus, Logger, PluginConnection } from "../core/interfaces.js"; +import { ERROR_CODES } from "../protocol/errors.js"; +import { PROTOCOL_VERSION, type SessionState } from "../protocol/types.js"; +import { InstanceError, errorMessage } from "./errors.js"; + +export const DEFAULT_COMMAND_TIMEOUT_MS = 25_000; +/** docs/protocol.md §2: "Write-queue cap 4 MB per connection". */ +export const DEFAULT_MAX_WRITE_QUEUE_BYTES = 4 * 1024 * 1024; + +/** The `hello` record, already validated by the server. */ +export interface PluginHello { + instanceId: string; + workspaceId: string; + cwd: string; + pid: number; + hasUI: boolean; + listenAddr: string | null; + pluginVersion: string; + capabilities?: string[]; +} + +export interface SnapshotCacheEntry { + epoch: string; + seq: number; + state: SessionState; +} + +export interface PluginSocketConnectionOptions { + socket: Socket; + hello: PluginHello; + bus: Bus; + logger?: Logger; + now?: () => number; + maxWriteQueueBytes?: number; + /** Called for `instance_state` records (the supervisor owns the state machine). */ + onInstanceState?: (record: Record, connection: PluginSocketConnection) => void; +} + +export interface CommandRequest { + id: string; + sessionId?: string; + method: string; + params?: Record; + clientRequestId?: string; +} + +export interface CommandAck { + seq?: number; + disposition?: string; +} + +interface PendingCommand { + method: string; + resolve: (ack: CommandAck) => void; + reject: (error: InstanceError) => void; + timer: NodeJS.Timeout; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function asString(value: unknown): string | undefined { + return typeof value === "string" && value !== "" ? value : undefined; +} + +function asNumber(value: unknown): number | undefined { + return typeof value === "number" && Number.isFinite(value) ? value : undefined; +} + +export class PluginSocketConnection implements PluginConnection { + readonly instanceId: string; + readonly workspaceId: string; + readonly cwd: string; + readonly pid: number; + readonly hasUI: boolean; + readonly listenAddr: string | null; + readonly pluginVersion: string; + readonly capabilities: string[]; + + /** Resolves exactly once when the connection is torn down (socket close, heartbeat, shutdown). */ + readonly closedPromise: Promise; + + private readonly socket: Socket; + private readonly bus: Bus; + private readonly logger: Logger | undefined; + private readonly now: () => number; + private readonly maxWriteQueueBytes: number; + private readonly onInstanceState: + | ((record: Record, connection: PluginSocketConnection) => void) + | undefined; + + private readonly pending = new Map(); + private readonly snapshots = new Map(); + /** Per session: the highest seq seen *within the current epoch*. */ + private readonly seqs = new Map(); + private readonly sessions = new Set(); + private readonly resolveClosed: () => void; + + private closed = false; + private dropNoticeSent = false; + private droppedRecords = 0; + private closeReasonValue: string | undefined; + + constructor(options: PluginSocketConnectionOptions) { + this.socket = options.socket; + this.bus = options.bus; + this.logger = options.logger; + this.now = options.now ?? Date.now; + this.maxWriteQueueBytes = options.maxWriteQueueBytes ?? DEFAULT_MAX_WRITE_QUEUE_BYTES; + this.onInstanceState = options.onInstanceState; + + this.instanceId = options.hello.instanceId; + this.workspaceId = options.hello.workspaceId; + this.cwd = options.hello.cwd; + this.pid = options.hello.pid; + this.hasUI = options.hello.hasUI; + this.listenAddr = options.hello.listenAddr; + this.pluginVersion = options.hello.pluginVersion; + this.capabilities = options.hello.capabilities ?? []; + + let resolveClosed: (() => void) | undefined; + this.closedPromise = new Promise((resolve) => { + resolveClosed = resolve; + }); + this.resolveClosed = resolveClosed as () => void; + } + + /** True once the peer went away or `close()` was called. */ + get isClosed(): boolean { + return this.closed; + } + + get closeReason(): string | undefined { + return this.closeReasonValue; + } + + get pendingCommands(): number { + return this.pending.size; + } + + get droppedCount(): number { + return this.droppedRecords; + } + + send(record: Record): void { + if (this.closed || this.socket.destroyed) return; + const line = JSON.stringify({ v: PROTOCOL_VERSION, ...record }) + "\n"; + const bytes = Buffer.byteLength(line, "utf8"); + + if (this.socket.writableLength + bytes > this.maxWriteQueueBytes) { + const type = record.type; + if (type === "event") { + // Low-priority records are dropped first (docs/protocol.md §2). + this.droppedRecords += 1; + if (!this.dropNoticeSent) { + this.dropNoticeSent = true; + const sessionId = asString(record.sessionId); + this.bus.publish({ + v: PROTOCOL_VERSION, + type: "dropped", + workspaceId: this.workspaceId, + ...(sessionId === undefined ? {} : { sessionId }), + payload: { reason: "backpressure" }, + }); + } + return; + } + // Control records must not be dropped: the write queue would grow unbounded. + this.logger?.warn("plugin write queue overflow, closing connection", { + instanceId: this.instanceId, + workspaceId: this.workspaceId, + type: typeof type === "string" ? type : "unknown", + queuedBytes: this.socket.writableLength, + }); + this.close("write queue overflow"); + return; + } + + try { + this.socket.write(line); + } catch (error) { + this.logger?.debug("plugin send failed", { + instanceId: this.instanceId, + error: errorMessage(error), + }); + } + } + + command(request: CommandRequest, timeoutMs = DEFAULT_COMMAND_TIMEOUT_MS): Promise { + if (this.closed || this.socket.destroyed) { + return Promise.reject( + InstanceError.unavailable(`instance ${this.instanceId} is not connected`, { + workspaceId: this.workspaceId, + }), + ); + } + if (this.pending.has(request.id)) { + return Promise.reject( + new InstanceError(ERROR_CODES.BAD_REQUEST, `duplicate command id ${request.id}`), + ); + } + + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + this.pending.delete(request.id); + reject(InstanceError.timeout(`command ${request.method} timed out after ${timeoutMs}ms`)); + }, timeoutMs); + timer.unref?.(); + + this.pending.set(request.id, { method: request.method, resolve, reject, timer }); + this.send({ + type: "cmd", + id: request.id, + ...(request.sessionId === undefined ? {} : { sessionId: request.sessionId }), + payload: { + method: request.method, + ...(request.params === undefined ? {} : { params: request.params }), + ...(request.clientRequestId === undefined + ? {} + : { clientRequestId: request.clientRequestId }), + }, + }); + }); + } + + subscribe(sessionId: string): void { + this.send({ type: "sub.subscribe", sessionId }); + } + + unsubscribe(sessionId: string): void { + this.send({ type: "sub.unsubscribe", sessionId }); + } + + snapshot(sessionId: string): SessionState | undefined { + return this.snapshots.get(sessionId)?.state; + } + + lastSeq(sessionId: string): number { + return this.seqs.get(sessionId)?.seq ?? 0; + } + + /** Session ids seen via `instance_state`, `snapshot` or `event` records. */ + sessionIds(): string[] { + return [...this.sessions]; + } + + hasSession(sessionId: string): boolean { + return this.sessions.has(sessionId); + } + + snapshotEntry(sessionId: string): SnapshotCacheEntry | undefined { + return this.snapshots.get(sessionId); + } + + close(reason: string): void { + if (this.closed) return; + this.closeReasonValue = reason; + this.logger?.debug("closing plugin connection", { + instanceId: this.instanceId, + workspaceId: this.workspaceId, + reason, + }); + try { + this.socket.end(); + } catch (error) { + this.logger?.debug("plugin socket end failed", { error: errorMessage(error) }); + } + // The server's "close" handler calls `notifyClosed`; destroy guarantees prompt cleanup. + this.socket.destroy(); + } + + /** Server hook: the socket is gone, fail in-flight work and notify once. */ + notifyClosed(reason?: string): void { + if (this.closed) return; + this.closed = true; + this.closeReasonValue = reason ?? this.closeReasonValue ?? "socket closed"; + + for (const [, pending] of this.pending) { + clearTimeout(pending.timer); + pending.reject( + InstanceError.unavailable( + `connection to ${this.instanceId} closed before ${pending.method} completed (${this.closeReasonValue})`, + { workspaceId: this.workspaceId }, + ), + ); + } + this.pending.clear(); + this.resolveClosed(); + } + + /** Server hook: one framed JSON record from the plugin. */ + handleRecord(record: Record): void { + if (this.closed) return; + const type = asString(record.type); + switch (type) { + case "ack": + this.handleAck(record); + return; + case "error": + this.handleError(record); + return; + case "snapshot": + this.handleSnapshot(record); + return; + case "event": + this.handleEvent(record); + return; + case "instance_state": + this.handleInstanceState(record); + return; + case "bye": + this.notifyClosed("plugin said bye"); + return; + case "hello": + case "hello_ack": + case "presence": + case "workspace_update": + return; + default: + this.logger?.debug("unhandled plugin record", { + instanceId: this.instanceId, + type: type ?? "missing", + }); + } + } + + private handleAck(record: Record): void { + const id = asString(record.id); + if (id === undefined) return; + const payload = isRecord(record.payload) ? record.payload : {}; + const seq = asNumber(record.seq) ?? asNumber(payload.seq); + const sessionId = asString(record.sessionId); + if (sessionId !== undefined && seq !== undefined) this.recordSeq(sessionId, this.epochFor(sessionId), seq); + + const pending = this.pending.get(id); + if (!pending) { + this.logger?.debug("ack for unknown command", { instanceId: this.instanceId, id }); + return; + } + this.pending.delete(id); + clearTimeout(pending.timer); + const disposition = asString(payload.disposition); + pending.resolve({ + ...(seq === undefined ? {} : { seq }), + ...(disposition === undefined ? {} : { disposition }), + }); + } + + private handleError(record: Record): void { + const id = asString(record.id); + const payload = isRecord(record.payload) ? record.payload : {}; + const code = asString(payload.code) ?? ERROR_CODES.INTERNAL; + const message = asString(payload.message) ?? "plugin command failed"; + const retryable = payload.retryable === true; + + if (id === undefined) { + this.logger?.warn("plugin error without id", { instanceId: this.instanceId, code, message }); + return; + } + const pending = this.pending.get(id); + if (!pending) return; + this.pending.delete(id); + clearTimeout(pending.timer); + pending.reject(new InstanceError(code, message, retryable)); + } + + private handleSnapshot(record: Record): void { + const sessionId = asString(record.sessionId); + if (sessionId === undefined) return; + this.sessions.add(sessionId); + + const epoch = asString(record.epoch) ?? this.instanceId; + const seq = asNumber(record.seq) ?? this.lastSeq(sessionId); + this.recordSeq(sessionId, epoch, seq); + + const payload = isRecord(record.payload) ? record.payload : {}; + const state = isRecord(payload.state) ? (payload.state as unknown as SessionState) : undefined; + + const cached = this.snapshots.get(sessionId); + if (cached !== undefined && cached.epoch !== epoch) { + // Epoch changed: the cached render state is useless. + this.snapshots.delete(sessionId); + } + if (state === undefined) return; + const previous = this.snapshots.get(sessionId); + this.snapshots.set(sessionId, { + epoch, + seq: previous !== undefined && previous.epoch === epoch ? Math.max(previous.seq, seq) : seq, + state, + }); + } + + private handleEvent(record: Record): void { + const sessionId = asString(record.sessionId); + if (sessionId === undefined) return; + this.sessions.add(sessionId); + + const epoch = asString(record.epoch) ?? this.instanceId; + const seq = asNumber(record.seq) ?? this.lastSeq(sessionId); + this.recordSeq(sessionId, epoch, seq); + + const payload = isRecord(record.payload) ? record.payload : {}; + const event = isRecord(payload.event) ? payload.event : payload; + const ts = asNumber(record.ts) ?? asNumber(event.ts) ?? this.now(); + + this.bus.publish({ + v: PROTOCOL_VERSION, + type: "event", + workspaceId: this.workspaceId, + sessionId, + epoch, + seq, + ts, + ...(asNumber(record.mono) === undefined ? {} : { mono: record.mono }), + ...(isRecord(record.origin) ? { origin: record.origin } : {}), + payload: { event }, + }); + } + + private handleInstanceState(record: Record): void { + const payload = isRecord(record.payload) ? record.payload : {}; + if (Array.isArray(payload.sessions)) { + for (const session of payload.sessions) { + if (typeof session === "string") { + this.sessions.add(session); + } else if (isRecord(session)) { + const sessionId = asString(session.sessionId); + if (sessionId !== undefined) this.sessions.add(sessionId); + } + } + } + this.onInstanceState?.(record, this); + } + + private epochFor(sessionId: string): string { + return this.seqs.get(sessionId)?.epoch ?? this.instanceId; + } + + /** `seq` is only comparable within one epoch (docs/protocol.md §1). */ + private recordSeq(sessionId: string, epoch: string, seq: number): void { + const previous = this.seqs.get(sessionId); + if (previous === undefined || previous.epoch !== epoch) { + this.seqs.set(sessionId, { epoch, seq }); + return; + } + if (seq > previous.seq) previous.seq = seq; + } +} diff --git a/src/instances/errors.ts b/src/instances/errors.ts new file mode 100644 index 0000000..f9ba66d --- /dev/null +++ b/src/instances/errors.ts @@ -0,0 +1,56 @@ +/** + * Errors raised by the instance layer (`src/instances/**`). + * + * The daemon surfaces map `code` onto the protocol error table + * (`docs/protocol.md` §7); `message` is English/debug only. + */ + +import { ERROR_CODES, errorBody } from "../protocol/errors.js"; +import type { ErrorBody } from "../protocol/types.js"; + +/** Not part of the public protocol table: a plugin command exceeded its timeout. */ +export const TIMEOUT_CODE = "E_TIMEOUT"; + +export class InstanceError extends Error { + readonly code: string; + readonly retryable: boolean; + readonly details: Record | undefined; + + constructor(code: string, message: string, retryable = false, details?: Record) { + super(message); + this.name = "InstanceError"; + this.code = code; + this.retryable = retryable; + this.details = details; + } + + toBody(): ErrorBody { + return errorBody(this.code, this.message, this.retryable, this.details); + } + + static unavailable(message: string, details?: Record): InstanceError { + return new InstanceError(ERROR_CODES.INSTANCE_UNAVAILABLE, message, true, details); + } + + static starting(message: string, details?: Record): InstanceError { + return new InstanceError(ERROR_CODES.INSTANCE_STARTING, message, true, details); + } + + static notFound(message: string): InstanceError { + return new InstanceError(ERROR_CODES.NOT_FOUND, message, false); + } + + static timeout(message: string): InstanceError { + return new InstanceError(TIMEOUT_CODE, message, true); + } +} + +export function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +/** Normalizes anything thrown in the instance layer. */ +export function asInstanceError(error: unknown): InstanceError { + if (error instanceof InstanceError) return error; + return new InstanceError(ERROR_CODES.INTERNAL, errorMessage(error), false); +} diff --git a/src/instances/index.ts b/src/instances/index.ts new file mode 100644 index 0000000..ebc5a1a --- /dev/null +++ b/src/instances/index.ts @@ -0,0 +1,30 @@ +/** + * Public surface of the instance layer. + * + * `createInstanceManager(deps)` returns an `InstanceManager` plus the plugin + * socket server handle used by diagnostics/test harnesses. + */ + +export { PluginServer, parseHello, DEFAULT_MAX_FRAME_BYTES, DEFAULT_HEARTBEAT_MS } from "./plugin-server.js"; +export type { PluginServerOptions, PluginServerRejection } from "./plugin-server.js"; +export { + PluginSocketConnection, + DEFAULT_COMMAND_TIMEOUT_MS, + DEFAULT_MAX_WRITE_QUEUE_BYTES, +} from "./connection.js"; +export type { PluginHello, SnapshotCacheEntry, PluginSocketConnectionOptions } from "./connection.js"; +export { + createInstanceManager, + ManagedInstanceManager, + parseProcRss, + parsePsRss, + summarizeResources, + DEFAULT_ENSURE_TIMEOUT_MS, + DEFAULT_MAX_INSTANCES, + DEFAULT_RSS_FRACTION, + DEFAULT_SHUTDOWN_GRACE_MS, + DEFAULT_SIGTERM_GRACE_MS, + DEFAULT_MIN_SPAWN_INTERVAL_MS, +} from "./supervisor.js"; +export type { InstanceManagerDeps, InstanceManagerHandle, SpawnFunction } from "./supervisor.js"; +export { InstanceError, TIMEOUT_CODE, asInstanceError, errorMessage } from "./errors.js"; diff --git a/src/instances/plugin-server.ts b/src/instances/plugin-server.ts new file mode 100644 index 0000000..fdf179d --- /dev/null +++ b/src/instances/plugin-server.ts @@ -0,0 +1,543 @@ +/** + * Plugin-facing unix-socket server (`/d.sock`). + * + * The plugin dials the daemon and speaks newline-delimited JSON (docs/protocol.md + * §2). Responsibilities: + * - write a fresh random 32-byte hex token to `/d.sock.token` (0600, atomic) + * - authenticate the first record (`hello`, timing-safe token compare, `v === 1`) + * - reject a second instance for an already-managed workspace with + * `hello_ack {rejected:{code:"E_LEASE"}}` and report it for diagnostics + * - split only on `\n`, strip `\r`, cap a frame at 8 MB + * - close sockets that go quiet for 45 s (any record counts as activity) + * - turn each accepted connection into a `PluginSocketConnection` + */ + +import { randomBytes, timingSafeEqual } from "node:crypto"; +import { chmod, rename, rm, writeFile } from "node:fs/promises"; +import { createServer, type Server, type Socket } from "node:net"; +import { dirname } from "node:path"; +import type { Bus, Logger } from "../core/interfaces.js"; +import { daemonSocketPath, daemonTokenPath, ensureDir } from "../core/paths.js"; +import { ERROR_CODES } from "../protocol/errors.js"; +import { PROTOCOL_VERSION } from "../protocol/types.js"; +import { + DEFAULT_MAX_WRITE_QUEUE_BYTES, + PluginSocketConnection, + type PluginHello, +} from "./connection.js"; +import { errorMessage } from "./errors.js"; + +export const DEFAULT_MAX_FRAME_BYTES = 8 * 1024 * 1024; +export const DEFAULT_HEARTBEAT_MS = 45_000; +export const DEFAULT_HELLO_TIMEOUT_MS = 10_000; + +export interface PluginServerRejection { + code: string; + message: string; +} + +export interface PluginServerOptions { + bus: Bus; + logger?: Logger; + daemonId?: string; + /** Defaults to `daemonSocketPath()`. */ + socketPath?: string; + /** Defaults to `daemonTokenPath()`. */ + tokenPath?: string; + maxFrameBytes?: number; + maxWriteQueueBytes?: number; + /** Idle limit: any record resets the timer (docs/protocol.md §2). */ + heartbeatMs?: number; + /** Sweep interval; defaults to `heartbeatMs / 3`. */ + heartbeatCheckMs?: number; + /** The first record must arrive within this window. */ + helloTimeoutMs?: number; + limits?: Record; + policy?: Record; + now?: () => number; + /** Publish a minimal `instance_state` on connect/disconnect (the supervisor disables this). */ + publishInstanceState?: boolean; + onOpen?: (connection: PluginSocketConnection) => void; + onClose?: (connection: PluginSocketConnection, reason: string) => void; + onRejected?: (hello: PluginHello, rejection: PluginServerRejection) => void; +} + +interface SocketState { + socket: Socket; + buffer: string; + lastActivity: number; + connection: PluginSocketConnection | undefined; + authTimer: NodeJS.Timeout | undefined; + /** No further records are parsed (protocol/auth rejection). */ + finished: boolean; + /** Reason reported to `onClose`; defaults to "socket closed". */ + closeReason: string | undefined; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function asString(value: unknown): string | undefined { + return typeof value === "string" && value !== "" ? value : undefined; +} + +function asNumber(value: unknown): number | undefined { + return typeof value === "number" && Number.isFinite(value) ? value : undefined; +} + +/** + * Validates the wire fields of a `hello` record. Returns `undefined` when a + * required field is missing or has the wrong type. + */ +export function parseHello(record: Record): PluginHello | undefined { + const instanceId = asString(record.instanceId); + const workspaceId = asString(record.workspaceId); + const cwd = asString(record.cwd); + const pid = asNumber(record.pid); + const pluginVersion = asString(record.pluginVersion); + if (instanceId === undefined || workspaceId === undefined || cwd === undefined) return undefined; + if (pid === undefined || !Number.isInteger(pid) || pid <= 0) return undefined; + if (pluginVersion === undefined) return undefined; + if (typeof record.hasUI !== "boolean") return undefined; + + const rawListen = record.listenAddr; + const listenAddr = typeof rawListen === "string" && rawListen !== "" ? rawListen : null; + const capabilities = Array.isArray(record.capabilities) + ? record.capabilities.filter((value): value is string => typeof value === "string") + : undefined; + + return { + instanceId, + workspaceId, + cwd, + pid, + hasUI: record.hasUI, + listenAddr, + pluginVersion, + ...(capabilities === undefined ? {} : { capabilities }), + }; +} + +export class PluginServer { + private readonly options: PluginServerOptions; + private readonly bus: Bus; + private readonly logger: Logger | undefined; + private readonly daemonId: string; + private readonly socketPath: string; + private readonly tokenPath: string; + private readonly maxFrameBytes: number; + private readonly maxWriteQueueBytes: number; + private readonly heartbeatMs: number; + private readonly heartbeatCheckMs: number; + private readonly helloTimeoutMs: number; + private readonly now: () => number; + private readonly publishInstanceState: boolean; + + private server: Server | undefined; + private heartbeatTimer: NodeJS.Timeout | undefined; + private started = false; + private closing = false; + private tokenValue = ""; + private readonly sockets = new Set(); + private readonly byWorkspace = new Map(); + + constructor(options: PluginServerOptions) { + this.options = options; + this.bus = options.bus; + this.logger = options.logger; + this.daemonId = options.daemonId ?? "d-local"; + this.socketPath = options.socketPath ?? daemonSocketPath(); + this.tokenPath = options.tokenPath ?? daemonTokenPath(); + this.maxFrameBytes = options.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES; + this.maxWriteQueueBytes = options.maxWriteQueueBytes ?? DEFAULT_MAX_WRITE_QUEUE_BYTES; + this.heartbeatMs = options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS; + this.heartbeatCheckMs = + options.heartbeatCheckMs ?? Math.max(5, Math.floor(this.heartbeatMs / 3)); + this.helloTimeoutMs = options.helloTimeoutMs ?? DEFAULT_HELLO_TIMEOUT_MS; + this.now = options.now ?? Date.now; + this.publishInstanceState = options.publishInstanceState ?? true; + } + + get path(): string { + return this.socketPath; + } + + get tokenFilePath(): string { + return this.tokenPath; + } + + get isStarted(): boolean { + return this.started; + } + + /** Current daemon token (also persisted at `tokenFilePath`, mode 0600). */ + get token(): string { + return this.tokenValue; + } + + connection(workspaceId: string): PluginSocketConnection | undefined { + return this.byWorkspace.get(workspaceId); + } + + connections(): PluginSocketConnection[] { + return [...this.byWorkspace.values()]; + } + + get connectionCount(): number { + return this.byWorkspace.size; + } + + setHandlers(handlers: { + onOpen?: PluginServerOptions["onOpen"]; + onClose?: PluginServerOptions["onClose"]; + onRejected?: PluginServerOptions["onRejected"]; + }): void { + if (handlers.onOpen !== undefined) this.options.onOpen = handlers.onOpen; + if (handlers.onClose !== undefined) this.options.onClose = handlers.onClose; + if (handlers.onRejected !== undefined) this.options.onRejected = handlers.onRejected; + } + + async start(): Promise { + if (this.started) return; + if (this.closing) throw new Error("plugin server is closing"); + + this.tokenValue = randomBytes(32).toString("hex"); + await this.writeToken(); + + ensureDir(dirname(this.socketPath)); + // A stale socket file from a crashed daemon would make listen() fail with EADDRINUSE. + await rm(this.socketPath, { force: true }).catch(() => undefined); + + const server = createServer((socket) => this.handleSocket(socket)); + this.server = server; + await new Promise((resolve, reject) => { + const onError = (error: Error): void => { + server.off("listening", onListening); + reject(error); + }; + const onListening = (): void => { + server.off("error", onError); + resolve(); + }; + server.once("error", onError); + server.once("listening", onListening); + server.listen(this.socketPath); + }); + + await chmod(this.socketPath, 0o600).catch((error: unknown) => { + this.logger?.debug("could not chmod plugin socket", { error: errorMessage(error) }); + }); + server.on("error", (error) => { + this.logger?.error("plugin server error", { error: error.message }); + }); + + this.heartbeatTimer = setInterval(() => this.sweepHeartbeats(), this.heartbeatCheckMs); + this.heartbeatTimer.unref?.(); + this.started = true; + this.logger?.info("plugin server listening", { + socketPath: this.socketPath, + tokenPath: this.tokenPath, + maxFrameBytes: this.maxFrameBytes, + }); + } + + async close(): Promise { + if (this.closing) return; + this.closing = true; + if (this.heartbeatTimer) { + clearInterval(this.heartbeatTimer); + this.heartbeatTimer = undefined; + } + for (const state of [...this.sockets]) { + state.closeReason = "daemon shutting down"; + try { + state.socket.destroy(); + } catch { + // already gone + } + } + this.sockets.clear(); + this.byWorkspace.clear(); + this.started = false; + + const server = this.server; + this.server = undefined; + if (server) { + await new Promise((resolve) => server.close(() => resolve())); + } + await rm(this.socketPath, { force: true }).catch(() => undefined); + this.logger?.info("plugin server closed", { socketPath: this.socketPath }); + } + + private async writeToken(): Promise { + const directory = dirname(this.tokenPath); + ensureDir(directory); + const temp = `${this.tokenPath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`; + await writeFile(temp, this.tokenValue, { mode: 0o600 }); + await chmod(temp, 0o600); + await rename(temp, this.tokenPath); + await chmod(this.tokenPath, 0o600).catch(() => undefined); + } + + private tokenMatches(candidate: string): boolean { + if (candidate.length !== this.tokenValue.length) return false; + const expected = Buffer.from(this.tokenValue, "utf8"); + const actual = Buffer.from(candidate, "utf8"); + if (expected.length !== actual.length) return false; + return timingSafeEqual(expected, actual); + } + + private handleSocket(socket: Socket): void { + if (this.closing) { + socket.destroy(); + return; + } + socket.setEncoding("utf8"); + const state: SocketState = { + socket, + buffer: "", + lastActivity: this.now(), + connection: undefined, + authTimer: undefined, + finished: false, + closeReason: undefined, + }; + this.sockets.add(state); + + state.authTimer = setTimeout(() => { + if (state.connection === undefined && !state.finished) { + this.reject(state, ERROR_CODES.UNAUTHORIZED, "hello timeout", "hello timeout"); + } + }, this.helloTimeoutMs); + state.authTimer.unref?.(); + + socket.on("data", (chunk: string | Buffer) => { + this.handleData(state, typeof chunk === "string" ? chunk : chunk.toString("utf8")); + }); + socket.on("error", (error) => { + this.logger?.debug("plugin socket error", { + error: error.message, + instanceId: state.connection?.instanceId, + }); + }); + socket.on("close", () => this.handleSocketClose(state)); + } + + private handleData(state: SocketState, chunk: string): void { + if (state.finished) return; + state.lastActivity = this.now(); + state.buffer += chunk; + + if (Buffer.byteLength(state.buffer, "utf8") > this.maxFrameBytes) { + this.reject(state, ERROR_CODES.PAYLOAD_TOO_LARGE, "frame exceeds maxFrameBytes", "frame too large"); + return; + } + + let newline = state.buffer.indexOf("\n"); + while (newline >= 0) { + let line = state.buffer.slice(0, newline); + state.buffer = state.buffer.slice(newline + 1); + if (line.endsWith("\r")) line = line.slice(0, -1); + if (line.trim() !== "") this.handleLine(state, line); + if (state.finished) return; + newline = state.buffer.indexOf("\n"); + } + } + + private handleLine(state: SocketState, line: string): void { + let record: unknown; + try { + record = JSON.parse(line); + } catch { + this.reject(state, ERROR_CODES.BAD_REQUEST, "malformed JSON", "malformed frame"); + return; + } + if (!isRecord(record)) { + this.reject(state, ERROR_CODES.BAD_REQUEST, "record must be a JSON object", "malformed frame"); + return; + } + + if (state.connection === undefined) { + this.handleHello(state, record); + return; + } + state.connection.handleRecord(record); + } + + private handleHello(state: SocketState, record: Record): void { + if (record.type !== "hello") { + this.reject(state, ERROR_CODES.BAD_REQUEST, "first record must be hello", "expected hello"); + return; + } + if (record.v !== PROTOCOL_VERSION) { + this.reject( + state, + ERROR_CODES.PROTOCOL_VERSION, + `unsupported protocol version ${String(record.v)}`, + "protocol version", + ); + return; + } + const token = asString(record.token); + if (token === undefined || !this.tokenMatches(token)) { + this.reject(state, ERROR_CODES.UNAUTHORIZED, "invalid daemon token", "unauthorized"); + return; + } + const hello = parseHello(record); + if (hello === undefined) { + this.reject(state, ERROR_CODES.BAD_REQUEST, "hello is missing required fields", "bad hello"); + return; + } + + const existing = this.byWorkspace.get(hello.workspaceId); + if (existing !== undefined && !existing.isClosed) { + const message = `workspace already managed by ${existing.instanceId}`; + this.writeAndFinish(state, { + v: PROTOCOL_VERSION, + type: "hello_ack", + daemonId: this.daemonId, + rejected: { code: ERROR_CODES.LEASE_CONFLICT, message }, + }); + this.logger?.warn("rejected unmanaged instance", { + workspaceId: hello.workspaceId, + instanceId: hello.instanceId, + managedBy: existing.instanceId, + }); + this.options.onRejected?.(hello, { code: ERROR_CODES.LEASE_CONFLICT, message }); + return; + } + + if (state.authTimer) { + clearTimeout(state.authTimer); + state.authTimer = undefined; + } + + const connection = new PluginSocketConnection({ + socket: state.socket, + hello, + bus: this.bus, + ...(this.logger === undefined ? {} : { logger: this.logger }), + now: this.now, + maxWriteQueueBytes: this.maxWriteQueueBytes, + }); + state.connection = connection; + this.byWorkspace.set(hello.workspaceId, connection); + + connection.send({ + v: PROTOCOL_VERSION, + type: "hello_ack", + daemonId: this.daemonId, + limits: this.options.limits ?? { maxFrameBytes: this.maxFrameBytes }, + policy: this.options.policy ?? { attention: "all" }, + }); + + this.logger?.info("plugin connected", { + workspaceId: hello.workspaceId, + instanceId: hello.instanceId, + pid: hello.pid, + hasUI: hello.hasUI, + pluginVersion: hello.pluginVersion, + }); + if (this.publishInstanceState) this.publishState(connection, "ready"); + this.options.onOpen?.(connection); + } + + private publishState(connection: PluginSocketConnection, status: string): void { + this.bus.publish({ + v: PROTOCOL_VERSION, + type: "instance_state", + workspaceId: connection.workspaceId, + instanceId: connection.instanceId, + ts: this.now(), + payload: { + status, + nvimPid: connection.pid, + pluginVersion: connection.pluginVersion, + hasUI: connection.hasUI, + listenAddr: connection.listenAddr, + sessions: connection.sessionIds().map((sessionId) => ({ sessionId })), + }, + }); + } + + private reject(state: SocketState, code: string, message: string, reason: string): void { + this.writeAndFinish( + state, + { + v: PROTOCOL_VERSION, + type: "error", + payload: { code, message, retryable: false }, + }, + reason, + ); + } + + private writeAndFinish( + state: SocketState, + record: Record, + reason = "rejected", + ): void { + if (state.finished) return; + state.finished = true; + state.closeReason = reason; + if (state.authTimer) { + clearTimeout(state.authTimer); + state.authTimer = undefined; + } + try { + state.socket.end(JSON.stringify(record) + "\n"); + } catch { + state.socket.destroy(); + } + // Do not let a peer that never reads keep the fd forever. + const timer = setTimeout(() => { + if (!state.socket.destroyed) state.socket.destroy(); + }, 500); + timer.unref?.(); + } + + private handleSocketClose(state: SocketState): void { + if (state.authTimer) { + clearTimeout(state.authTimer); + state.authTimer = undefined; + } + this.sockets.delete(state); + const connection = state.connection; + if (connection === undefined) return; + state.connection = undefined; + + if (this.byWorkspace.get(connection.workspaceId) === connection) { + this.byWorkspace.delete(connection.workspaceId); + } + const reason = state.closeReason ?? connection.closeReason ?? "socket closed"; + connection.notifyClosed(reason); + if (this.publishInstanceState && !this.closing) this.publishState(connection, "degraded"); + this.logger?.info("plugin disconnected", { + workspaceId: connection.workspaceId, + instanceId: connection.instanceId, + reason, + }); + this.options.onClose?.(connection, reason); + } + + private sweepHeartbeats(): void { + const now = this.now(); + for (const state of [...this.sockets]) { + if (state.finished) continue; + if (now - state.lastActivity <= this.heartbeatMs) continue; + this.logger?.warn("plugin heartbeat timeout", { + workspaceId: state.connection?.workspaceId, + instanceId: state.connection?.instanceId, + idleMs: now - state.lastActivity, + }); + state.closeReason = "heartbeat timeout"; + state.finished = true; + try { + state.socket.destroy(); + } catch { + // already gone + } + } + } +} diff --git a/src/instances/supervisor.ts b/src/instances/supervisor.ts new file mode 100644 index 0000000..a4415a4 --- /dev/null +++ b/src/instances/supervisor.ts @@ -0,0 +1,773 @@ +/** + * Instance supervisor: one managed nvim per workspace. + * + * Lifecycle (docs/protocol.md §5): + * - `ensure()` is idempotent and resolves once the spawned plugin says `hello`. + * - A crash degrades the instance and fans `pi2:process_exit` out for every + * session the instance knew about. It is **never** restarted automatically; + * the next `ensure()` spawns a new process (with exponential backoff). + * - `shutdown()` asks the plugin politely, then escalates SIGTERM → SIGKILL. + */ + +import { execFile, spawn, type ChildProcess, type SpawnOptions } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import { appendFile, mkdir, readFile } from "node:fs/promises"; +import { totalmem } from "node:os"; +import { dirname, join } from "node:path"; +import { promisify } from "node:util"; +import type { + Bus, + InstanceManager, + InstanceResourcesSnapshot, + Logger, + PluginConnection, +} from "../core/interfaces.js"; +import { + daemonSocketPath, + daemonTokenPath, + ensureDir, + instanceSocketPath as defaultInstanceSocketPath, + runtimeDir, + stateDir, +} from "../core/paths.js"; +import { ERROR_CODES } from "../protocol/errors.js"; +import { PROTOCOL_VERSION, type InstanceState } from "../protocol/types.js"; +import { PluginSocketConnection, type PluginHello } from "./connection.js"; +import { InstanceError, asInstanceError, errorMessage } from "./errors.js"; +import { PluginServer, type PluginServerOptions, type PluginServerRejection } from "./plugin-server.js"; + +const execFileAsync = promisify(execFile); + +export const DEFAULT_ENSURE_TIMEOUT_MS = 5_000; +export const DEFAULT_SHUTDOWN_GRACE_MS = 5_000; +export const DEFAULT_SIGTERM_GRACE_MS = 2_000; +export const DEFAULT_MIN_SPAWN_INTERVAL_MS = 2_000; +export const DEFAULT_MAX_SPAWN_INTERVAL_MS = 60_000; +/** Soft warning thresholds for `/api/v1/resources`. */ +export const DEFAULT_MAX_INSTANCES = 8; +export const DEFAULT_RSS_FRACTION = 0.6; + +export type SpawnFunction = (command: string, args: string[], options: SpawnOptions) => ChildProcess; + +export interface InstanceManagerDeps { + bus: Bus; + logger?: Logger; + /** Resolve the workspace cwd (the daemon's workspace lookup). */ + resolveCwd: (workspaceId: string) => string | undefined | Promise; + daemonId?: string; + now?: () => number; + /** Defaults to `daemonSocketPath()`. */ + socketPath?: string; + /** Defaults to `daemonTokenPath()`. */ + tokenPath?: string; + /** Defaults to `runtimeDir()`; exported to the spawned nvim as `PI2_RUNTIME_DIR`. */ + runtime?: string; + /** Defaults to `${stateDir()}/instances`. */ + logDir?: string; + nvimBin?: string; + nvimInit?: string; + env?: NodeJS.ProcessEnv; + spawnFn?: SpawnFunction; + instanceSocketPath?: (workspaceId: string, instanceId: string) => string; + pluginServerOptions?: Omit< + PluginServerOptions, + "bus" | "logger" | "onOpen" | "onClose" | "onRejected" | "publishInstanceState" + >; + ensureTimeoutMs?: number; + shutdownGraceMs?: number; + sigtermGraceMs?: number; + minSpawnIntervalMs?: number; + maxSpawnIntervalMs?: number; + maxWriteQueueBytes?: number; + heartbeatMs?: number; + readRss?: (pid: number) => Promise; + totalMemory?: () => number; +} + +export interface InstanceManagerHandle extends InstanceManager { + /** Stop the plugin server and kill every spawned nvim (daemon/test shutdown). */ + close(): Promise; + /** The plugin-facing socket server (exposed for diagnostics). */ + readonly pluginServer: PluginServer; +} + +interface SpawnWaiter { + promise: Promise; + settle(connection: PluginSocketConnection): void; + fail(error: InstanceError): void; + attach(child: ChildProcess, logPath: string): void; + cancel(reason: string): void; +} + +interface SpawnFailure { + count: number; + nextAllowedAt: number; +} + +/** `VmRSS: 123456 kB` from `/proc//status` → bytes. */ +export function parseProcRss(status: string): number | null { + const match = /^\s*VmRSS:\s+(\d+)\s+kB\s*$/m.exec(status); + if (!match?.[1]) return null; + const kib = Number(match[1]); + return Number.isFinite(kib) ? kib * 1024 : null; +} + +/** `ps -o rss= -p ` output (KiB, may have leading whitespace) → bytes. */ +export function parsePsRss(output: string): number | null { + const first = output.trim().split(/\s+/)[0]; + if (first === undefined || first === "") return null; + const kib = Number(first); + return Number.isFinite(kib) && kib >= 0 ? kib * 1024 : null; +} + +export function summarizeResources( + instances: InstanceResourcesSnapshot["instances"], + physicalMemoryBytes: number, + options: { maxInstances?: number; rssFraction?: number } = {}, +): InstanceResourcesSnapshot { + const maxInstances = options.maxInstances ?? DEFAULT_MAX_INSTANCES; + const rssFraction = options.rssFraction ?? DEFAULT_RSS_FRACTION; + const totalRssBytes = instances.reduce((sum, instance) => sum + (instance.rssBytes ?? 0), 0); + const reasons: string[] = []; + + if (instances.length > maxInstances) { + reasons.push(`${instances.length} instances (>${maxInstances})`); + } + if (physicalMemoryBytes > 0 && totalRssBytes > physicalMemoryBytes * rssFraction) { + const percent = Math.round((totalRssBytes / physicalMemoryBytes) * 100); + reasons.push(`instance RSS ${percent}% of physical memory (>${Math.round(rssFraction * 100)}%)`); + } + + return { + instances, + totalRssBytes, + physicalMemoryBytes, + warn: reasons.length > 0, + ...(reasons.length === 0 ? {} : { reason: reasons.join("; ") }), + }; +} + +async function waitForChildExit(child: ChildProcess, timeoutMs: number): Promise { + if (child.exitCode !== null || child.signalCode !== null) return true; + return new Promise((resolve) => { + let settled = false; + const finish = (value: boolean): void => { + if (settled) return; + settled = true; + clearTimeout(timer); + child.off("exit", onExit); + resolve(value); + }; + const onExit = (): void => finish(true); + const timer = setTimeout(() => finish(false), timeoutMs); + timer.unref?.(); + child.once("exit", onExit); + }); +} + +function waitForClose(connection: PluginSocketConnection, timeoutMs: number): Promise { + if (connection.isClosed) return Promise.resolve(true); + return new Promise((resolve) => { + let settled = false; + const finish = (value: boolean): void => { + if (settled) return; + settled = true; + clearTimeout(timer); + resolve(value); + }; + const timer = setTimeout(() => finish(false), timeoutMs); + timer.unref?.(); + void connection.closedPromise.then(() => finish(true)); + }); +} + +function tryKill(child: ChildProcess, signal: NodeJS.Signals): void { + try { + child.kill(signal); + } catch { + // already exited + } +} + +export class ManagedInstanceManager implements InstanceManagerHandle { + readonly pluginServer: PluginServer; + + private readonly bus: Bus; + private readonly logger: Logger | undefined; + private readonly deps: InstanceManagerDeps; + private readonly now: () => number; + private readonly socketPath: string; + private readonly tokenPath: string; + private readonly runtime: string; + private readonly logDir: string; + private readonly nvimBin: string; + private readonly nvimInit: string | undefined; + private readonly spawnFn: SpawnFunction; + private readonly instanceSocketPath: (workspaceId: string, instanceId: string) => string; + private readonly readRss: (pid: number) => Promise; + private readonly totalMemory: () => number; + private readonly ensureTimeoutMs: number; + private readonly shutdownGraceMs: number; + private readonly sigtermGraceMs: number; + private readonly minSpawnIntervalMs: number; + private readonly maxSpawnIntervalMs: number; + + private readonly states = new Map(); + private readonly unmanaged = new Map(); + private readonly connections = new Map(); + private readonly spawning = new Map>(); + private readonly waiters = new Map(); + private readonly children = new Map(); + private readonly failures = new Map(); + private readonly shuttingDown = new Set(); + private readonly changeHandlers = new Set<(state: InstanceState) => void>(); + + private closed = false; + + constructor(deps: InstanceManagerDeps) { + this.deps = deps; + this.bus = deps.bus; + this.logger = deps.logger; + this.now = deps.now ?? Date.now; + this.socketPath = deps.socketPath ?? daemonSocketPath(); + this.tokenPath = deps.tokenPath ?? daemonTokenPath(); + this.runtime = deps.runtime ?? runtimeDir(); + this.logDir = deps.logDir ?? join(stateDir(), "instances"); + this.nvimBin = deps.nvimBin ?? process.env.PI2_NVIM_BIN ?? "nvim"; + const init = deps.nvimInit ?? process.env.PI2_NVIM_INIT; + this.nvimInit = init !== undefined && init !== "" ? init : undefined; + this.spawnFn = deps.spawnFn ?? ((command, args, options) => spawn(command, args, options)); + this.instanceSocketPath = deps.instanceSocketPath ?? defaultInstanceSocketPath; + this.readRss = deps.readRss ?? defaultReadRss; + this.totalMemory = deps.totalMemory ?? totalmem; + this.ensureTimeoutMs = deps.ensureTimeoutMs ?? DEFAULT_ENSURE_TIMEOUT_MS; + this.shutdownGraceMs = deps.shutdownGraceMs ?? DEFAULT_SHUTDOWN_GRACE_MS; + this.sigtermGraceMs = deps.sigtermGraceMs ?? DEFAULT_SIGTERM_GRACE_MS; + this.minSpawnIntervalMs = deps.minSpawnIntervalMs ?? DEFAULT_MIN_SPAWN_INTERVAL_MS; + this.maxSpawnIntervalMs = deps.maxSpawnIntervalMs ?? DEFAULT_MAX_SPAWN_INTERVAL_MS; + + this.pluginServer = new PluginServer({ + ...(deps.pluginServerOptions ?? {}), + bus: deps.bus, + ...(deps.logger === undefined ? {} : { logger: deps.logger }), + ...(deps.daemonId === undefined ? {} : { daemonId: deps.daemonId }), + socketPath: this.socketPath, + tokenPath: this.tokenPath, + now: this.now, + publishInstanceState: false, + }); + this.pluginServer.setHandlers({ + onOpen: (connection) => this.handleOpen(connection), + onClose: (connection, reason) => this.handleClose(connection, reason), + onRejected: (hello, rejection) => this.handleRejected(hello, rejection), + }); + } + + /** Starts the plugin-facing unix socket server and writes the daemon token. */ + async start(): Promise { + await this.pluginServer.start(); + } + + async ensure(workspaceId: string, opts: { timeoutMs?: number } = {}): Promise { + if (this.closed) throw InstanceError.unavailable("instance manager is closed"); + if (typeof workspaceId !== "string" || workspaceId === "") { + throw new InstanceError(ERROR_CODES.BAD_REQUEST, "workspaceId is required"); + } + + const existing = this.connections.get(workspaceId); + if (existing !== undefined && !existing.isClosed) { + const state = this.readyState(existing, this.states.get(workspaceId)); + this.setState(state); + return state; + } + + const running = this.spawning.get(workspaceId); + if (running !== undefined) return running; + + const failure = this.failures.get(workspaceId); + const now = this.now(); + if (failure !== undefined && now < failure.nextAllowedAt) { + throw InstanceError.unavailable( + `instance for ${workspaceId} is backing off after ${failure.count} failed start(s)`, + { retryAfterMs: failure.nextAllowedAt - now }, + ); + } + + const timeoutMs = opts.timeoutMs ?? this.ensureTimeoutMs; + const promise = this.spawnInstance(workspaceId, timeoutMs); + this.spawning.set(workspaceId, promise); + try { + return await promise; + } finally { + if (this.spawning.get(workspaceId) === promise) this.spawning.delete(workspaceId); + } + } + + async shutdown(workspaceId: string, mode: "drain" | "stop"): Promise { + const connection = this.connections.get(workspaceId); + const child = this.children.get(workspaceId); + const previous = this.states.get(workspaceId); + + if (connection === undefined && child === undefined) { + if (previous !== undefined) { + this.setState({ + ...previous, + status: "stopped", + nvimPid: null, + attachedClients: 0, + reason: "shutdown: no live instance", + }); + } + return; + } + + this.shuttingDown.add(workspaceId); + const base: InstanceState = previous ?? { + workspaceId, + instanceId: connection?.instanceId ?? "unknown", + status: "ready", + nvimPid: child?.pid ?? null, + pluginVersion: connection?.pluginVersion ?? null, + hasUI: connection?.hasUI ?? false, + attachedClients: 0, + listenAddr: connection?.listenAddr ?? null, + startedAt: this.now(), + }; + this.setState({ ...base, status: "stopping", attachedClients: 0, reason: `shutdown:${mode}` }); + + try { + if (connection !== undefined) { + connection.send({ + v: PROTOCOL_VERSION, + type: "instance.shutdown", + payload: { mode }, + }); + const closedGracefully = await waitForClose(connection, this.shutdownGraceMs); + if (!closedGracefully) { + this.logger?.warn("instance ignored shutdown, escalating", { + workspaceId, + instanceId: connection.instanceId, + mode, + }); + connection.close("shutdown timeout"); + } + } + + const liveChild = this.children.get(workspaceId) ?? child; + if (liveChild !== undefined) { + tryKill(liveChild, "SIGTERM"); + const exited = await waitForChildExit(liveChild, this.sigtermGraceMs); + if (!exited) { + this.logger?.warn("instance ignored SIGTERM, sending SIGKILL", { workspaceId }); + tryKill(liveChild, "SIGKILL"); + await waitForChildExit(liveChild, 1_000); + } + } + } finally { + if (this.connections.get(workspaceId) === connection) this.connections.delete(workspaceId); + const liveChild = this.children.get(workspaceId); + if (liveChild === undefined || liveChild === child) this.children.delete(workspaceId); + this.shuttingDown.delete(workspaceId); + this.setState({ + ...(this.states.get(workspaceId) ?? base), + status: "stopped", + nvimPid: null, + attachedClients: 0, + reason: `shutdown complete (${mode})`, + }); + } + } + + get(workspaceId: string): PluginConnection | undefined { + return this.connections.get(workspaceId); + } + + list(): InstanceState[] { + return [...this.states.values(), ...this.unmanaged.values()]; + } + + instanceStates(): InstanceState[] { + return [...this.states.values()]; + } + + findWorkspaceBySession(sessionId: string): string | undefined { + for (const connection of this.connections.values()) { + if (connection.snapshot(sessionId) !== undefined || connection.hasSession(sessionId)) { + return connection.workspaceId; + } + } + return undefined; + } + + async resources(): Promise { + const instances: InstanceResourcesSnapshot["instances"] = []; + for (const connection of this.connections.values()) { + const state = this.states.get(connection.workspaceId); + const pid = connection.pid > 0 ? connection.pid : (state?.nvimPid ?? null); + const rssBytes = pid === null ? null : await this.readRss(pid); + instances.push({ + workspaceId: connection.workspaceId, + instanceId: connection.instanceId, + nvimPid: pid, + rssBytes, + sessions: connection.sessionIds().length, + hasUI: connection.hasUI, + }); + } + return summarizeResources(instances, this.totalMemory()); + } + + maybeUnsubscribe(workspaceId: string, sessionId: string): void { + this.connections.get(workspaceId)?.unsubscribe(sessionId); + } + + onInstanceChange(handler: (state: InstanceState) => void): void { + this.changeHandlers.add(handler); + } + + async close(): Promise { + if (this.closed) return; + this.closed = true; + for (const waiter of [...this.waiters.values()]) waiter.cancel("instance manager closed"); + this.waiters.clear(); + this.spawning.clear(); + for (const child of [...this.children.values()]) tryKill(child, "SIGKILL"); + this.children.clear(); + this.connections.clear(); + await this.pluginServer.close(); + this.logger?.info("instance manager closed", { workspaces: this.states.size }); + } + + private async spawnInstance(workspaceId: string, timeoutMs: number): Promise { + const cwd = await this.deps.resolveCwd(workspaceId); + if (cwd === undefined || cwd === "") { + throw InstanceError.notFound(`unknown workspace ${workspaceId}`); + } + + const instanceId = `i-${randomUUID()}`; + const socketPath = this.instanceSocketPath(workspaceId, instanceId); + const logPath = join(this.logDir, `${instanceId}.log`); + const startedAt = this.now(); + const previous = this.states.get(workspaceId); + + const starting: InstanceState = { + workspaceId, + instanceId, + status: "starting", + nvimPid: null, + pluginVersion: null, + hasUI: false, + attachedClients: 0, + listenAddr: socketPath, + startedAt: previous?.startedAt ?? startedAt, + }; + this.setState(starting); + + const waiter = this.createWaiter(workspaceId, timeoutMs); + let child: ChildProcess | undefined; + try { + const args = [ + "--headless", + "--listen", + socketPath, + ...(this.nvimInit === undefined ? [] : ["-u", this.nvimInit]), + "-c", + 'lua require("pi.host").start()', + ]; + const env: NodeJS.ProcessEnv = { + ...process.env, + ...(this.deps.env ?? {}), + PI2_RUNTIME_DIR: this.runtime, + PI2_DAEMON_SOCKET: this.socketPath, + PI2_DAEMON_TOKEN_PATH: this.tokenPath, + PI2_WORKSPACE_ID: workspaceId, + }; + this.logger?.info("spawning instance", { workspaceId, instanceId, cwd, command: this.nvimBin, logPath }); + child = this.spawnFn(this.nvimBin, args, { + cwd, + env, + stdio: "ignore", + detached: true, + }); + this.children.set(workspaceId, child); + if (child.pid !== undefined) this.setState({ ...starting, nvimPid: child.pid }); + child.unref(); + waiter.attach(child, logPath); + + const connection = await waiter.promise; + this.failures.delete(workspaceId); + // Note: the plugin mints its own `instanceId`; it need not match the id we + // used for `--listen`. Never infer "redundant spawn" from that difference. + return this.readyState(connection, this.states.get(workspaceId)); + } catch (error) { + const failure = asInstanceError(error); + this.recordFailure(workspaceId); + if (child !== undefined) { + tryKill(child, "SIGKILL"); + if (this.children.get(workspaceId) === child) this.children.delete(workspaceId); + } + this.setState({ + ...(this.states.get(workspaceId) ?? starting), + status: "stopped", + nvimPid: null, + attachedClients: 0, + reason: failure.message, + }); + this.logger?.warn("instance failed to start", { + workspaceId, + instanceId, + code: failure.code, + error: failure.message, + }); + throw failure; + } + } + + private createWaiter(workspaceId: string, timeoutMs: number): SpawnWaiter { + const manager = this; + let settled = false; + let resolvePromise!: (connection: PluginSocketConnection) => void; + let rejectPromise!: (error: Error) => void; + + const promise = new Promise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + // Callers always await this, but a synchronous spawn failure can cancel an + // unobserved waiter; keep Node from reporting an unhandled rejection. + void promise.catch(() => undefined); + + let timer: NodeJS.Timeout | undefined; + let exited = false; + + const cleanup = (): void => { + if (timer !== undefined) { + clearTimeout(timer); + timer = undefined; + } + if (this.waiters.get(workspaceId) === waiter) this.waiters.delete(workspaceId); + }; + + const waiter: SpawnWaiter = { + promise, + settle(connection) { + if (settled) return; + settled = true; + cleanup(); + resolvePromise(connection); + }, + fail(error) { + if (settled) return; + settled = true; + cleanup(); + rejectPromise(error); + }, + attach(child, logPath) { + child.once("exit", (code, signal) => { + exited = true; + if (manager.children.get(workspaceId) === child) manager.children.delete(workspaceId); + if (settled) return; + const message = `nvim exited before hello (code ${String(code)}, signal ${String(signal)})`; + void manager.appendLog(logPath, message); + waiter.fail(InstanceError.unavailable(message, { workspaceId })); + }); + child.once("error", (error) => { + void manager.appendLog(logPath, `spawn error: ${error.message}`); + waiter.fail(InstanceError.unavailable(`failed to spawn nvim: ${error.message}`, { workspaceId })); + }); + }, + cancel(reason) { + if (settled) return; + settled = true; + cleanup(); + rejectPromise(InstanceError.unavailable(reason)); + }, + }; + + timer = setTimeout(() => { + const message = exited + ? `instance for ${workspaceId} exited before hello` + : `instance for ${workspaceId} did not say hello within ${timeoutMs}ms`; + waiter.fail(exited ? InstanceError.unavailable(message) : InstanceError.starting(message)); + }, timeoutMs); + timer.unref?.(); + + this.waiters.set(workspaceId, waiter); + return waiter; + } + + private handleOpen(connection: PluginSocketConnection): void { + if (this.closed) { + connection.close("instance manager is closed"); + return; + } + this.connections.set(connection.workspaceId, connection); + this.waiters.get(connection.workspaceId)?.settle(connection); + this.setState(this.readyState(connection, this.states.get(connection.workspaceId))); + } + + private handleClose(connection: PluginSocketConnection, reason: string): void { + if (this.connections.get(connection.workspaceId) !== connection) return; + this.connections.delete(connection.workspaceId); + + const previous = this.states.get(connection.workspaceId); + if (this.closed || this.shuttingDown.has(connection.workspaceId) || previous?.status === "stopping") { + return; + } + + this.recordFailure(connection.workspaceId); + this.setState({ + ...(previous ?? this.readyState(connection, undefined)), + instanceId: connection.instanceId, + status: "degraded", + nvimPid: null, + attachedClients: 0, + reason, + }); + + // The plugin is gone: every session it owned is now interrupted. + for (const sessionId of connection.sessionIds()) { + const ts = this.now(); + this.bus.publish({ + v: PROTOCOL_VERSION, + type: "event", + workspaceId: connection.workspaceId, + sessionId, + epoch: connection.instanceId, + seq: connection.lastSeq(sessionId), + ts, + payload: { + event: { type: "pi2:process_exit", code: null, reason: "instance died", ts }, + }, + }); + } + } + + private handleRejected(hello: PluginHello, rejection: PluginServerRejection): void { + const state: InstanceState = { + workspaceId: hello.workspaceId, + instanceId: hello.instanceId, + status: "unmanaged", + nvimPid: hello.pid, + pluginVersion: hello.pluginVersion, + hasUI: hello.hasUI, + attachedClients: 0, + listenAddr: hello.listenAddr, + startedAt: this.now(), + reason: rejection.message, + }; + this.unmanaged.set(hello.instanceId, state); + this.logger?.warn("unmanaged instance rejected", { + workspaceId: hello.workspaceId, + instanceId: hello.instanceId, + reason: rejection.message, + }); + this.publishState(state); + } + + private recordFailure(workspaceId: string): void { + const previous = this.failures.get(workspaceId); + const count = (previous?.count ?? 0) + 1; + const delay = Math.min(this.maxSpawnIntervalMs, this.minSpawnIntervalMs * 2 ** (count - 1)); + this.failures.set(workspaceId, { count, nextAllowedAt: this.now() + delay }); + } + + private readyState( + connection: PluginSocketConnection, + previous: InstanceState | undefined, + ): InstanceState { + return { + workspaceId: connection.workspaceId, + instanceId: connection.instanceId, + status: "ready", + nvimPid: connection.pid, + pluginVersion: connection.pluginVersion, + hasUI: connection.hasUI, + attachedClients: 0, + listenAddr: connection.listenAddr, + startedAt: previous?.startedAt ?? this.now(), + }; + } + + private setState(state: InstanceState): void { + const previous = this.states.get(state.workspaceId); + this.states.set(state.workspaceId, state); + if (previous !== undefined && sameState(previous, state)) return; + this.publishState(state); + } + + private publishState(state: InstanceState): void { + const sessions = this.connections + .get(state.workspaceId) + ?.sessionIds() + .map((sessionId) => ({ sessionId })); + this.bus.publish({ + v: PROTOCOL_VERSION, + type: "instance_state", + workspaceId: state.workspaceId, + instanceId: state.instanceId, + ts: this.now(), + payload: { + ...state, + sessions: sessions ?? [], + }, + }); + for (const handler of this.changeHandlers) { + try { + handler(state); + } catch (error) { + this.logger?.warn("instance change handler threw", { error: errorMessage(error) }); + } + } + } + + private async appendLog(logPath: string, message: string): Promise { + try { + ensureDir(dirname(logPath)); + await appendFile(logPath, `${new Date(this.now()).toISOString()} ${message}\n`); + } catch (error) { + this.logger?.debug("could not write instance log", { logPath, error: errorMessage(error) }); + } + } +} + +function sameState(a: InstanceState, b: InstanceState): boolean { + return ( + a.instanceId === b.instanceId && + a.status === b.status && + a.nvimPid === b.nvimPid && + a.pluginVersion === b.pluginVersion && + a.hasUI === b.hasUI && + a.attachedClients === b.attachedClients && + a.listenAddr === b.listenAddr && + a.startedAt === b.startedAt && + a.reason === b.reason + ); +} + +async function defaultReadRss(pid: number): Promise { + if (!Number.isInteger(pid) || pid <= 0) return null; + if (process.platform === "linux") { + try { + return parseProcRss(await readFile(`/proc/${pid}/status`, "utf8")); + } catch { + return null; + } + } + try { + const { stdout } = await execFileAsync("ps", ["-o", "rss=", "-p", String(pid)]); + return parsePsRss(stdout); + } catch { + return null; + } +} + +/** + * Creates the instance manager and starts its plugin-facing socket server + * (so the daemon token exists before the first nvim is spawned). + */ +export async function createInstanceManager(deps: InstanceManagerDeps): Promise { + const manager = new ManagedInstanceManager(deps); + await manager.start(); + return manager; +} diff --git a/test/instances/connection.test.ts b/test/instances/connection.test.ts new file mode 100644 index 0000000..d6d2177 --- /dev/null +++ b/test/instances/connection.test.ts @@ -0,0 +1,322 @@ +import type { Socket } from "node:net"; +import { describe, expect, it, afterEach, beforeEach } from "vitest"; +import { daemonSocketPath } from "../../src/core/paths.js"; +import { PluginSocketConnection } from "../../src/instances/connection.js"; +import { PluginServer } from "../../src/instances/plugin-server.js"; +import { makeSessionState } from "../daemon/fakes.js"; +import { FakeBus, PluginClient, delay, makeTempEnv, waitFor, type TempEnv } from "./helpers.js"; + +function asRecord(value: unknown): Record { + return value as Record; +} + +describe("PluginSocketConnection", () => { + let env: TempEnv; + let bus: FakeBus; + let server: PluginServer; + let client: PluginClient; + let connection: PluginSocketConnection; + + beforeEach(async () => { + env = makeTempEnv(); + bus = new FakeBus(); + server = new PluginServer({ bus, daemonId: "d-test" }); + await server.start(); + client = await PluginClient.connect({ socketPath: daemonSocketPath() }); + await client.next("hello_ack"); + const established = server.connection("ws-test"); + if (!established) throw new Error("connection was not established"); + connection = established; + }); + + afterEach(async () => { + client.close(); + await server.close(); + env.cleanup(); + }); + + it("sends records as JSONL to the plugin", async () => { + connection.send({ type: "instance_state", payload: { status: "ready", sessions: [] } }); + const record = await client.next("instance_state"); + + expect(record.v).toBe(1); + expect(asRecord(record.payload).status).toBe("ready"); + expect(client.rawLines).toHaveLength(2); // hello_ack + record + }); + + it("correlates acks by id even when they arrive out of order", async () => { + client.onRecord((record) => { + if (record.type !== "cmd") return; + const id = String(record.id); + const seq = id === "req-alpha" ? 2 : 1; + setTimeout( + () => client.send({ v: 1, type: "ack", id, seq, payload: { disposition: "started" } }), + id === "req-alpha" ? 80 : 5, + ); + }); + + const alpha = connection.command({ id: "req-alpha", sessionId: "s1", method: "alpha" }); + const beta = connection.command({ id: "req-beta", sessionId: "s1", method: "beta" }); + + expect(await beta).toEqual({ seq: 1, disposition: "started" }); + expect(await alpha).toEqual({ seq: 2, disposition: "started" }); + + const cmd = await client.next("cmd", (record) => String(record.id) === "req-alpha"); + expect(asRecord(cmd.payload).method).toBe("alpha"); + expect(cmd.sessionId).toBe("s1"); + }); + + it("rejects with the plugin error code and message", async () => { + client.onRecord((record) => { + if (record.type !== "cmd") return; + client.send({ + v: 1, + type: "error", + id: record.id, + payload: { code: "E_LEASE", message: "session is owned by instance i-2", retryable: false }, + }); + }); + + await expect(connection.command({ id: "req-err", method: "prompt.send" })).rejects.toMatchObject({ + code: "E_LEASE", + message: "session is owned by instance i-2", + retryable: false, + }); + }); + + it("times out commands and ignores a late ack", async () => { + const started = Date.now(); + await expect(connection.command({ id: "req-slow", method: "slow" }, 60)).rejects.toMatchObject({ + code: "E_TIMEOUT", + }); + expect(Date.now() - started).toBeGreaterThanOrEqual(50); + expect(connection.pendingCommands).toBe(0); + + // A late ack must not resolve anything or throw. + client.send({ v: 1, type: "ack", id: "req-slow", seq: 3, payload: { disposition: "started" } }); + await delay(20); + expect(connection.pendingCommands).toBe(0); + }); + + it("sends subscription records", async () => { + connection.subscribe("s1"); + connection.unsubscribe("s1"); + + const subscribe = await client.next("sub.subscribe"); + const unsubscribe = await client.next("sub.unsubscribe"); + expect(subscribe.sessionId).toBe("s1"); + expect(unsubscribe.sessionId).toBe("s1"); + }); + + it("caches snapshots and invalidates them on epoch change", async () => { + const state = makeSessionState("s1", "ws-test"); + client.send({ + v: 1, + type: "snapshot", + sessionId: "s1", + epoch: "e1", + seq: 10, + payload: { state }, + }); + await waitFor(() => connection.snapshot("s1") !== undefined); + + expect(connection.snapshot("s1")?.sessionId).toBe("s1"); + expect(connection.lastSeq("s1")).toBe(10); + + const renamed = { ...state, name: "Renamed" }; + client.send({ + v: 1, + type: "snapshot", + sessionId: "s1", + epoch: "e1", + seq: 12, + payload: { state: renamed }, + }); + await waitFor(() => connection.snapshot("s1")?.name === "Renamed"); + expect(connection.lastSeq("s1")).toBe(12); + + const recreated = { ...state, name: "After restart" }; + client.send({ + v: 1, + type: "snapshot", + sessionId: "s1", + epoch: "e2", + seq: 1, + payload: { state: recreated }, + }); + await waitFor(() => connection.snapshot("s1")?.name === "After restart"); + expect(connection.snapshotEntry("s1")?.epoch).toBe("e2"); + // seq is only valid inside an epoch + expect(connection.lastSeq("s1")).toBe(1); + }); + + it("does not invent snapshots the plugin never sent", () => { + expect(connection.snapshot("missing")).toBeUndefined(); + expect(connection.lastSeq("missing")).toBe(0); + }); + + it("relays events onto the bus with the plugin envelope", async () => { + client.send({ + v: 1, + type: "event", + sessionId: "s1", + epoch: "e1", + seq: 7, + ts: 1733234400123, + mono: 918273, + payload: { event: { type: "agent_start", ts: 1733234400123 } }, + }); + + const published = await waitFor(() => bus.published.find((record) => record.type === "event")); + expect(published.v).toBe(1); + expect(published.workspaceId).toBe("ws-test"); + expect(published.sessionId).toBe("s1"); + expect(published.epoch).toBe("e1"); + expect(published.seq).toBe(7); + expect(published.ts).toBe(1733234400123); + expect(asRecord(published.payload).event).toMatchObject({ type: "agent_start" }); + expect(connection.lastSeq("s1")).toBe(7); + expect(connection.hasSession("s1")).toBe(true); + }); + + it("tracks sessions reported by instance_state", async () => { + client.send({ + v: 1, + type: "instance_state", + payload: { + status: "ready", + sessions: [{ sessionId: "s1", status: "busy" }, { sessionId: "s2" }], + }, + }); + await waitFor(() => connection.sessionIds().length === 2); + expect(connection.sessionIds().sort()).toEqual(["s1", "s2"]); + + client.send({ v: 1, type: "instance_state", payload: { sessions: ["s3"] } }); + await waitFor(() => connection.hasSession("s3")); + }); + + it("fails in-flight commands when the socket closes", async () => { + const pending = connection.command({ id: "req-pending", method: "never" }, 5_000); + connection.close("test shutdown"); + + await expect(pending).rejects.toMatchObject({ code: "E_INSTANCE_UNAVAILABLE" }); + await connection.closedPromise; + expect(connection.isClosed).toBe(true); + expect(connection.closeReason).toBe("test shutdown"); + await client.waitForClosed(); + await waitFor(() => server.connectionCount === 0); + }); + + it("treats a plugin bye as a close", async () => { + client.send({ v: 1, type: "bye" }); + await connection.closedPromise; + expect(connection.isClosed).toBe(true); + expect(connection.closeReason).toBe("plugin said bye"); + }); + + it("rejects commands once closed", async () => { + connection.close("done"); + await connection.closedPromise; + await expect(connection.command({ id: "req-late", method: "x" })).rejects.toMatchObject({ + code: "E_INSTANCE_UNAVAILABLE", + }); + }); + +}); + +describe("PluginSocketConnection write-queue cap", () => { + it("drops events and emits one dropped marker when the queue is full", () => { + const state = { queued: 0, destroyed: false }; + const writes: string[] = []; + const socket = { + get writableLength() { + return state.queued; + }, + get destroyed() { + return state.destroyed; + }, + write(line: string) { + writes.push(line); + state.queued += Buffer.byteLength(line, "utf8"); + }, + end() { + state.destroyed = true; + }, + destroy() { + state.destroyed = true; + }, + } as unknown as Socket; + const bus = new FakeBus(); + const connection = new PluginSocketConnection({ + socket, + hello: { + instanceId: "i-1", + workspaceId: "ws-1", + cwd: "/repo", + pid: 42, + hasUI: false, + listenAddr: null, + pluginVersion: "1.0.0", + }, + bus, + maxWriteQueueBytes: 100, + }); + + connection.send({ + type: "event", + sessionId: "s1", + seq: 1, + payload: { event: { type: "text_delta", delta: "x".repeat(200) } }, + }); + connection.send({ + type: "event", + sessionId: "s1", + seq: 2, + payload: { event: { type: "text_delta", delta: "y".repeat(200) } }, + }); + + expect(writes).toHaveLength(0); + expect(connection.droppedCount).toBe(2); + expect(bus.published.filter((record) => record.type === "dropped")).toHaveLength(1); + }); + + it("closes the connection rather than dropping a control record", () => { + const writes: string[] = []; + const state = { destroyed: false }; + const socket = { + writableLength: 1_000, + get destroyed() { + return state.destroyed; + }, + write(line: string) { + writes.push(line); + }, + end() { + state.destroyed = true; + }, + destroy() { + state.destroyed = true; + }, + } as unknown as Socket; + const connection = new PluginSocketConnection({ + socket, + hello: { + instanceId: "i-1", + workspaceId: "ws-1", + cwd: "/repo", + pid: 42, + hasUI: false, + listenAddr: null, + pluginVersion: "1.0.0", + }, + bus: new FakeBus(), + maxWriteQueueBytes: 100, + }); + + connection.send({ type: "cmd", id: "req-1", payload: { method: "prompt.send" } }); + + expect(writes).toHaveLength(0); + expect(connection.closeReason).toBe("write queue overflow"); + expect(state.destroyed).toBe(true); + }); +}); diff --git a/test/instances/helpers.ts b/test/instances/helpers.ts new file mode 100644 index 0000000..147586d --- /dev/null +++ b/test/instances/helpers.ts @@ -0,0 +1,549 @@ +/** + * Test harness for the instance layer. + * + * Three pieces: + * - `makeTempEnv()` isolates `PI2_RUNTIME_DIR`/`PI2_DATA_DIR`/`PI2_STATE_DIR` + * so the real `core/paths.ts` helpers point into a scratch directory. + * - `PluginClient` speaks the plugin side of the JSONL protocol over a real + * unix socket (tests of `plugin-server` / `connection`). + * - `writeFakeNvim()` generates an executable node script that impersonates + * `nvim` for `PI2_NVIM_BIN`: it dials the daemon, says `hello`, answers + * commands with `ack`/`error`, emits snapshots/instance_state, and can be + * told to crash or ignore shutdown. + */ + +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { connect, type Socket } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { daemonTokenPath } from "../../src/core/paths.js"; +import { FakeBus } from "../daemon/fakes.js"; + +export { FakeBus }; + +export interface TempEnv { + dir: string; + runtime: string; + data: string; + state: string; + /** Restores the env vars captured at creation (call from afterEach/afterAll). */ + restore(): void; + cleanup(): void; +} + +const ENV_KEYS = ["PI2_RUNTIME_DIR", "PI2_DATA_DIR", "PI2_STATE_DIR", "PI2_NVIM_BIN", "PI2_NVIM_INIT"] as const; + +export function makeTempEnv(prefix = "pi2d-instances-"): TempEnv { + const dir = mkdtempSync(join(tmpdir(), prefix)); + const runtime = join(dir, "run"); + const data = join(dir, "data"); + const state = join(dir, "state"); + for (const path of [runtime, data, state]) mkdirSync(path, { recursive: true, mode: 0o700 }); + + const saved = new Map(); + for (const key of ENV_KEYS) saved.set(key, process.env[key]); + process.env.PI2_RUNTIME_DIR = runtime; + process.env.PI2_DATA_DIR = data; + process.env.PI2_STATE_DIR = state; + + return { + dir, + runtime, + data, + state, + restore() { + for (const [key, value] of saved) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + }, + cleanup() { + this.restore(); + rmSync(dir, { recursive: true, force: true }); + }, + }; +} + +export function readDaemonToken(): string { + return readFileSync(daemonTokenPath(), "utf8").trim(); +} + +export function makeHello(overrides: Record = {}): Record { + return { + v: 1, + type: "hello", + token: readDaemonToken(), + instanceId: "i-test-1", + workspaceId: "ws-test", + cwd: "/repo/ws-test", + pid: process.pid, + hasUI: false, + listenAddr: "/tmp/i-test.sock", + pluginVersion: "1.8.0", + capabilities: ["snapshot", "attention"], + ...overrides, + }; +} + +export function delay(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +export async function waitFor( + predicate: () => T | undefined | false | null, + timeoutMs = 3_000, + intervalMs = 10, + label = "condition", +): Promise { + const deadline = Date.now() + timeoutMs; + let lastError: unknown; + while (Date.now() < deadline) { + try { + const value = predicate(); + if (value) return value; + } catch (error) { + lastError = error; + } + await delay(intervalMs); + } + throw new Error(`timed out waiting for ${label} after ${timeoutMs}ms${lastError ? `: ${String(lastError)}` : ""}`); +} + +export interface PluginClientOptions { + socketPath: string; + /** Defaults to `makeHello()`; pass `false` to send nothing automatically. */ + hello?: Record | false; + connectTimeoutMs?: number; +} + +type RecordHandler = (record: Record) => void; + +interface Waiter { + predicate: (record: Record) => boolean; + resolve: (record: Record) => void; + timer: NodeJS.Timeout; +} + +/** A plugin-side JSONL client used by plugin-server / connection tests. */ +export class PluginClient { + readonly socket: Socket; + readonly records: Record[] = []; + readonly rawLines: string[] = []; + readonly closePromise: Promise; + + private buffer = ""; + private waiters: Waiter[] = []; + private handlers: RecordHandler[] = []; + private closed = false; + private closeReason = ""; + + private constructor(socket: Socket) { + this.socket = socket; + this.closePromise = new Promise((resolve) => { + socket.once("close", () => { + this.closed = true; + resolve(); + }); + }); + socket.setEncoding("utf8"); + socket.on("data", (chunk: string) => this.onData(chunk)); + socket.on("error", () => { + // close event handles cleanup + }); + } + + static async connect(options: PluginClientOptions): Promise { + const socket = connect(options.socketPath); + socket.setEncoding("utf8"); + const client = new PluginClient(socket); + await new Promise((resolve, reject) => { + const timer = setTimeout( + () => reject(new Error(`connect to ${options.socketPath} timed out`)), + options.connectTimeoutMs ?? 3_000, + ); + timer.unref?.(); + socket.once("connect", () => { + clearTimeout(timer); + resolve(); + }); + socket.once("error", (error) => { + clearTimeout(timer); + reject(error); + }); + }); + if (options.hello !== false) { + client.send(options.hello ?? makeHello()); + } + return client; + } + + get isClosed(): boolean { + return this.closed; + } + + get reason(): string { + return this.closeReason; + } + + send(record: Record): void { + this.sendRaw(`${JSON.stringify(record)}\n`); + } + + sendRaw(text: string): void { + if (this.socket.destroyed) return; + this.socket.write(text); + } + + onRecord(handler: RecordHandler): () => void { + this.handlers.push(handler); + return () => { + this.handlers = this.handlers.filter((candidate) => candidate !== handler); + }; + } + + /** Resolves with the first matching record (already received ones included). */ + async next( + type: string, + predicate: (record: Record) => boolean = () => true, + timeoutMs = 3_000, + ): Promise> { + const matches = (record: Record): boolean => record.type === type && predicate(record); + const existing = this.records.find(matches); + if (existing) return existing; + + return new Promise>((resolve, reject) => { + const timer = setTimeout(() => { + this.waiters = this.waiters.filter((candidate) => candidate !== waiter); + reject( + new Error( + `timed out waiting for "${type}" after ${timeoutMs}ms; got ${JSON.stringify(this.records.map((r) => r.type))}`, + ), + ); + }, timeoutMs); + timer.unref?.(); + const waiter: Waiter = { + predicate: matches, + resolve: (record) => { + clearTimeout(timer); + resolve(record); + }, + timer, + }; + this.waiters.push(waiter); + const late = this.records.find(matches); + if (late) { + this.waiters = this.waiters.filter((candidate) => candidate !== waiter); + clearTimeout(timer); + resolve(late); + } + }); + } + + recordsOfType(type: string): Record[] { + return this.records.filter((record) => record.type === type); + } + + async waitForClosed(timeoutMs = 3_000): Promise { + if (this.closed) return; + await Promise.race([ + this.closePromise, + delay(timeoutMs).then(() => { + throw new Error(`socket did not close within ${timeoutMs}ms`); + }), + ]); + } + + close(): void { + if (!this.socket.destroyed) this.socket.destroy(); + } + + private onData(chunk: string): void { + this.buffer += chunk; + let newline = this.buffer.indexOf("\n"); + while (newline >= 0) { + let line = this.buffer.slice(0, newline); + this.buffer = this.buffer.slice(newline + 1); + if (line.endsWith("\r")) line = line.slice(0, -1); + if (line.trim() !== "") { + this.rawLines.push(line); + try { + const record = JSON.parse(line) as Record; + this.records.push(record); + for (const handler of [...this.handlers]) { + try { + handler(record); + } catch { + // test handler failures surface through assertions + } + } + for (const waiter of [...this.waiters]) { + if (!waiter.predicate(record)) continue; + this.waiters = this.waiters.filter((candidate) => candidate !== waiter); + clearTimeout(waiter.timer); + waiter.resolve(record); + } + } catch { + // non-JSON from the daemon is a test failure surfaced via rawLines + } + } + newline = this.buffer.indexOf("\n"); + } + } +} + +export interface FakeNvimOptions { + mode?: "ok" | "no-hello" | "bad-token" | "wrong-version" | "exit-immediately" | "exit-first-run"; + instanceId?: string; + workspaceId?: string; + pluginVersion?: string; + hasUI?: boolean; + /** Sessions reported via `instance_state` right after hello. */ + sessions?: string[]; + /** Snapshot state sent for each subscribed session. */ + snapshotState?: Record; + /** Snapshots emitted right after hello. */ + snapshots?: { sessionId: string; epoch?: string; seq?: number; state?: Record }[]; + crashAfterMs?: number; + crashExitCode?: number; + ackDelayMs?: number; + cmdMode?: "ack" | "error" | "silent"; + ignoreShutdown?: boolean; + ignoreSigterm?: boolean; + exitCode?: number; + /** For `exit-first-run`: how many initial runs exit instead of connecting. */ + failRuns?: number; + runLog?: string; +} + +export interface FakeNvim { + bin: string; + runLog: string; + counterFile: string; +} + +/** Creates an executable node script that impersonates nvim on the daemon socket. */ +export function writeFakeNvim(dir: string, options: FakeNvimOptions = {}): FakeNvim { + const suffix = Math.random().toString(16).slice(2); + const runLog = options.runLog ?? join(dir, `runs-${suffix}.jsonl`); + const counterFile = join(dir, `runs-${suffix}.txt`); + const bin = join(dir, `fake-nvim-${suffix}.mjs`); + const payload = { + ...options, + runLog, + counterFile, + }; + writeFileSync(bin, fakeNvimScript(payload), { mode: 0o755 }); + chmodSync(bin, 0o755); + return { bin, runLog, counterFile }; +} + +export function readRunLog(path: string): Record[] { + try { + return readFileSync(path, "utf8") + .split("\n") + .filter((line) => line.trim() !== "") + .map((line) => JSON.parse(line) as Record); + } catch { + return []; + } +} + +export function startRecords(runLog: string): Record[] { + return readRunLog(runLog).filter((entry) => entry.kind === "start"); +} + +function fakeNvimScript(options: FakeNvimOptions & { runLog: string; counterFile: string }): string { + const literal = JSON.stringify(options); + return `#!/usr/bin/env node +// Generated by test/instances/helpers.ts — impersonates nvim for PI2_NVIM_BIN. +import { appendFileSync, readFileSync, writeFileSync } from "node:fs"; +import { connect } from "node:net"; + +const opts = ${literal}; +const argv = process.argv.slice(2); +const listenIndex = argv.indexOf("--listen"); +const listenAddr = listenIndex >= 0 ? argv[listenIndex + 1] : null; + +function log(entry) { + if (!opts.runLog) return; + try { + appendFileSync(opts.runLog, JSON.stringify({ pid: process.pid, at: Date.now(), ...entry }) + "\\n"); + } catch { + // ignore + } +} + +log({ + kind: "start", + argv, + cwd: process.cwd(), + listenAddr, + env: { + PI2_RUNTIME_DIR: process.env.PI2_RUNTIME_DIR, + PI2_DAEMON_SOCKET: process.env.PI2_DAEMON_SOCKET, + PI2_DAEMON_TOKEN_PATH: process.env.PI2_DAEMON_TOKEN_PATH, + PI2_WORKSPACE_ID: process.env.PI2_WORKSPACE_ID, + }, +}); + +if (opts.mode === "exit-immediately") process.exit(opts.exitCode ?? 3); + +if (opts.mode === "exit-first-run") { + let runs = 0; + try { + runs = Number(readFileSync(opts.counterFile, "utf8")) || 0; + } catch { + runs = 0; + } + runs += 1; + writeFileSync(opts.counterFile, String(runs)); + log({ kind: "run", runs }); + if (runs <= (opts.failRuns ?? 1)) process.exit(opts.exitCode ?? 3); +} + +if (opts.ignoreShutdown || opts.ignoreSigterm) { + // Keep the event loop alive after the daemon drops the socket so the test can + // observe the SIGTERM -> SIGKILL escalation. + setInterval(() => {}, 1_000); + process.on("SIGTERM", () => log({ kind: "sigterm" })); +} + +const token = + opts.mode === "bad-token" + ? "0".repeat(64) + : readFileSync(process.env.PI2_DAEMON_TOKEN_PATH, "utf8").trim(); +const workspaceId = opts.workspaceId ?? process.env.PI2_WORKSPACE_ID; +const instanceId = opts.instanceId ?? ("i-fake-" + process.pid); +const socket = connect(process.env.PI2_DAEMON_SOCKET); +socket.setEncoding("utf8"); + +let buffer = ""; +let seq = 0; +let closed = false; + +function rawSend(record) { + if (closed || socket.destroyed) return; + socket.write(JSON.stringify({ v: 1, ...record }) + "\\n"); +} + +socket.on("connect", () => { + if (opts.mode === "no-hello") { + log({ kind: "silent" }); + return; + } + rawSend({ + type: "hello", + v: opts.mode === "wrong-version" ? 2 : 1, + token, + instanceId, + workspaceId, + cwd: process.cwd(), + pid: process.pid, + hasUI: opts.hasUI ?? false, + listenAddr, + pluginVersion: opts.pluginVersion ?? "9.9.9-fake", + capabilities: ["snapshot", "attention"], + }); + log({ kind: "hello-sent", instanceId }); + if (opts.mode === "bad-token" || opts.mode === "wrong-version") return; + + setTimeout(() => { + if (opts.sessions) { + rawSend({ + type: "instance_state", + payload: { + status: "ready", + sessions: opts.sessions.map((sessionId) => ({ sessionId })), + }, + }); + } + if (opts.snapshots) { + for (const snapshot of opts.snapshots) { + const state = snapshot.state ?? { ...(opts.snapshotState ?? {}), sessionId: snapshot.sessionId }; + rawSend({ + type: "snapshot", + sessionId: snapshot.sessionId, + epoch: snapshot.epoch ?? instanceId, + seq: snapshot.seq ?? ++seq, + payload: { state }, + }); + } + } + }, 0); + + if (opts.crashAfterMs !== undefined) { + setTimeout(() => { + log({ kind: "crash" }); + process.exit(opts.crashExitCode ?? 0); + }, opts.crashAfterMs); + } +}); + +function handleCmd(record) { + log({ kind: "cmd", id: record.id, method: record.payload?.method }); + if (opts.cmdMode === "silent") return; + const send = () => { + if (opts.cmdMode === "error") { + rawSend({ type: "error", id: record.id, payload: { code: "E_INTERNAL", message: "fake failure", retryable: false } }); + } else { + rawSend({ type: "ack", id: record.id, seq: ++seq, payload: { disposition: "started" } }); + } + }; + if (opts.ackDelayMs) setTimeout(send, opts.ackDelayMs); + else send(); +} + +socket.on("data", (chunk) => { + buffer += chunk; + let newline = buffer.indexOf("\\n"); + while (newline >= 0) { + const line = buffer.slice(0, newline); + buffer = buffer.slice(newline + 1); + newline = buffer.indexOf("\\n"); + if (!line.trim()) continue; + let record; + try { + record = JSON.parse(line); + } catch { + continue; + } + log({ kind: "record", record }); + if (record.type === "hello_ack") { + log({ kind: "hello-ack", rejected: record.rejected ?? null }); + if (record.rejected) { + closed = true; + socket.end(); + return; + } + continue; + } + if (record.type === "cmd") handleCmd(record); + if (record.type === "sub.subscribe" && opts.snapshotState) { + rawSend({ + type: "snapshot", + sessionId: record.sessionId, + epoch: instanceId, + seq: ++seq, + payload: { state: { ...opts.snapshotState, sessionId: record.sessionId } }, + }); + } + if (record.type === "instance.shutdown") { + log({ kind: "shutdown", mode: record.payload?.mode }); + if (!opts.ignoreShutdown) { + rawSend({ type: "bye" }); + setTimeout(() => { + closed = true; + socket.end(); + process.exit(0); + }, 10); + } + } + if (record.type === "test.exit") process.exit(record.payload?.code ?? 0); + } +}); + +socket.on("error", () => { + // the daemon may be gone; tests observe the run log +}); +`; +} diff --git a/test/instances/plugin-server.test.ts b/test/instances/plugin-server.test.ts new file mode 100644 index 0000000..cb2a8a7 --- /dev/null +++ b/test/instances/plugin-server.test.ts @@ -0,0 +1,330 @@ +import { readFileSync, statSync } from "node:fs"; +import { describe, expect, it, afterEach, beforeEach } from "vitest"; +import { daemonSocketPath, daemonTokenPath } from "../../src/core/paths.js"; +import { parseHello, PluginServer, type PluginServerOptions } from "../../src/instances/plugin-server.js"; +import type { PluginHello } from "../../src/instances/connection.js"; +import { + FakeBus, + PluginClient, + delay, + makeHello, + makeTempEnv, + waitFor, + type TempEnv, +} from "./helpers.js"; + +function asRecord(value: unknown): Record { + return value as Record; +} + +describe("PluginServer", () => { + let env: TempEnv; + let bus: FakeBus; + let servers: PluginServer[]; + + beforeEach(() => { + env = makeTempEnv(); + bus = new FakeBus(); + servers = []; + }); + + afterEach(async () => { + for (const server of servers.splice(0)) await server.close(); + env.cleanup(); + }); + + async function start(options: Partial = {}): Promise { + const server = new PluginServer({ bus, daemonId: "d-test", ...options }); + await server.start(); + servers.push(server); + return server; + } + + async function connect(overrides: Record = {}): Promise { + return PluginClient.connect({ socketPath: daemonSocketPath(), hello: makeHello(overrides) }); + } + + it("writes a 32-byte hex token with mode 0600 before accepting connections", async () => { + const server = await start(); + const token = readFileSync(daemonTokenPath(), "utf8").trim(); + + expect(token).toMatch(/^[0-9a-f]{64}$/); + expect(token).toBe(server.token); + expect(statSync(daemonTokenPath()).mode & 0o777).toBe(0o600); + expect(statSync(server.path).mode & 0o777).toBe(0o600); + }); + + it("accepts a valid hello and replies with hello_ack limits and policy", async () => { + const server = await start({ daemonId: "d-test", policy: { attention: "all" } }); + const client = await connect(); + const ack = await client.next("hello_ack"); + + expect(ack.v).toBe(1); + expect(ack.type).toBe("hello_ack"); + expect(ack.daemonId).toBe("d-test"); + expect(asRecord(ack.limits).maxFrameBytes).toBe(8 * 1024 * 1024); + expect(asRecord(ack.policy).attention).toBe("all"); + expect(ack.rejected).toBeUndefined(); + expect(server.connectionCount).toBe(1); + expect(server.connection("ws-test")?.instanceId).toBe("i-test-1"); + expect(client.isClosed).toBe(false); + + await waitFor(() => + bus.published.find( + (record) => + record.type === "instance_state" && asRecord(record.payload).status === "ready", + ), + ); + client.close(); + }); + + it("rejects a bad token with E_UNAUTHORIZED and closes the socket", async () => { + await start(); + const client = await connect({ token: "0".repeat(64) }); + const error = await client.next("error"); + + expect(asRecord(error.payload).code).toBe("E_UNAUTHORIZED"); + expect(asRecord(error.payload).retryable).toBe(false); + await client.waitForClosed(); + }); + + it("rejects an unsupported protocol version with E_PROTOCOL_VERSION", async () => { + await start(); + const client = await connect({ v: 2 }); + const error = await client.next("error"); + + expect(asRecord(error.payload).code).toBe("E_PROTOCOL_VERSION"); + await client.waitForClosed(); + }); + + it("rejects a hello with missing fields as E_BAD_REQUEST", async () => { + await start(); + const hello = makeHello(); + delete hello.cwd; + const client = await PluginClient.connect({ socketPath: daemonSocketPath(), hello }); + const error = await client.next("error"); + + expect(asRecord(error.payload).code).toBe("E_BAD_REQUEST"); + await client.waitForClosed(); + }); + + it("rejects a first record that is not hello", async () => { + await start(); + const client = await PluginClient.connect({ socketPath: daemonSocketPath(), hello: false }); + client.send({ v: 1, type: "event", sessionId: "s1", seq: 1 }); + const error = await client.next("error"); + + expect(asRecord(error.payload).code).toBe("E_BAD_REQUEST"); + await client.waitForClosed(); + }); + + it("rejects malformed JSON", async () => { + await start(); + const client = await PluginClient.connect({ socketPath: daemonSocketPath(), hello: false }); + client.sendRaw("{not json}\n"); + const error = await client.next("error"); + + expect(asRecord(error.payload).code).toBe("E_BAD_REQUEST"); + await client.waitForClosed(); + }); + + it("rejects a second instance for an already-managed workspace with E_LEASE", async () => { + const server = await start(); + const rejected: { hello: PluginHello; code: string; message: string }[] = []; + server.setHandlers({ + onRejected: (hello, rejection) => rejected.push({ hello, code: rejection.code, message: rejection.message }), + }); + + const first = await connect({ instanceId: "i-first", workspaceId: "ws-1" }); + await first.next("hello_ack"); + + const second = await connect({ instanceId: "i-second", workspaceId: "ws-1" }); + const ack = await second.next("hello_ack"); + + expect(asRecord(ack.rejected).code).toBe("E_LEASE"); + expect(asRecord(ack.rejected).message).toBe("workspace already managed by i-first"); + await second.waitForClosed(); + expect(server.connectionCount).toBe(1); + expect(server.connection("ws-1")?.instanceId).toBe("i-first"); + expect(rejected).toHaveLength(1); + expect(rejected[0]?.hello.instanceId).toBe("i-second"); + expect(rejected[0]?.code).toBe("E_LEASE"); + expect(first.isClosed).toBe(false); + first.close(); + }); + + it("accepts a new instance once the previous one disconnected", async () => { + const server = await start(); + const first = await connect({ instanceId: "i-first", workspaceId: "ws-1" }); + await first.next("hello_ack"); + first.close(); + await first.waitForClosed(); + await waitFor(() => server.connectionCount === 0); + + const second = await connect({ instanceId: "i-second", workspaceId: "ws-1" }); + const ack = await second.next("hello_ack"); + + expect(ack.rejected).toBeUndefined(); + expect(server.connection("ws-1")?.instanceId).toBe("i-second"); + second.close(); + }); + + it("supports several workspaces at once", async () => { + const server = await start(); + const one = await connect({ instanceId: "i-1", workspaceId: "ws-1" }); + const two = await connect({ instanceId: "i-2", workspaceId: "ws-2" }); + await one.next("hello_ack"); + await two.next("hello_ack"); + + expect(server.connectionCount).toBe(2); + expect(server.connection("ws-1")?.instanceId).toBe("i-1"); + expect(server.connection("ws-2")?.instanceId).toBe("i-2"); + one.close(); + two.close(); + }); + + it("frames on newline only, tolerates CRLF and split writes", async () => { + const server = await start(); + const client = await PluginClient.connect({ socketPath: daemonSocketPath(), hello: false }); + const hello = `${JSON.stringify(makeHello())}\r\n`; + client.sendRaw(hello.slice(0, 12)); + await delay(5); + client.sendRaw(hello.slice(12, 40)); + await delay(5); + client.sendRaw(hello.slice(40)); + + await client.next("hello_ack"); + const connection = server.connection("ws-test"); + expect(connection).toBeDefined(); + + const event = JSON.stringify({ + v: 1, + type: "event", + sessionId: "s1", + epoch: "e1", + seq: 4, + ts: 123, + payload: { event: { type: "agent_start", ts: 123 } }, + }); + client.sendRaw(event.slice(0, 25)); + await delay(5); + client.sendRaw(`${event.slice(25)}\r\n`); + + await waitFor(() => bus.published.find((record) => record.type === "event")); + const published = bus.published.find((record) => record.type === "event"); + expect(published?.sessionId).toBe("s1"); + expect(published?.seq).toBe(4); + client.close(); + }); + + it("rejects a frame larger than maxFrameBytes with E_PAYLOAD_TOO_LARGE", async () => { + await start({ maxFrameBytes: 512 }); + const client = await PluginClient.connect({ socketPath: daemonSocketPath(), hello: false }); + client.sendRaw("x".repeat(1024)); + const error = await client.next("error"); + + expect(asRecord(error.payload).code).toBe("E_PAYLOAD_TOO_LARGE"); + await client.waitForClosed(); + }); + + it("closes sockets that stay quiet past the heartbeat limit", async () => { + const server = await start({ heartbeatMs: 120, heartbeatCheckMs: 10 }); + const client = await connect({ instanceId: "i-hb", workspaceId: "ws-hb" }); + await client.next("hello_ack"); + + await client.waitForClosed(3_000); + await waitFor(() => server.connectionCount === 0); + }); + + it("keeps sockets alive while any record arrives", async () => { + const server = await start({ heartbeatMs: 120, heartbeatCheckMs: 10 }); + const client = await connect({ instanceId: "i-hb", workspaceId: "ws-hb" }); + await client.next("hello_ack"); + + const timer = setInterval(() => { + client.send({ v: 1, type: "instance_state", payload: { status: "ready", sessions: [] } }); + }, 30); + await delay(400); + expect(client.isClosed).toBe(false); + expect(server.connectionCount).toBe(1); + + clearInterval(timer); + await client.waitForClosed(3_000); + }); + + it("publishes a degraded instance_state when a plugin disconnects", async () => { + await start(); + const client = await connect({ instanceId: "i-1", workspaceId: "ws-1" }); + await client.next("hello_ack"); + client.close(); + + await waitFor(() => + bus.published.find( + (record) => + record.type === "instance_state" && + record.instanceId === "i-1" && + asRecord(record.payload).status === "degraded", + ), + ); + }); + + it("calls onClose with the disconnect reason", async () => { + const server = await start(); + const closes: { instanceId: string; reason: string }[] = []; + server.setHandlers({ + onClose: (connection, reason) => closes.push({ instanceId: connection.instanceId, reason }), + }); + const client = await connect({ instanceId: "i-1", workspaceId: "ws-1" }); + await client.next("hello_ack"); + client.close(); + + await waitFor(() => closes.length === 1); + expect(closes[0]?.instanceId).toBe("i-1"); + expect(closes[0]?.reason).toBe("socket closed"); + }); + + it("stops accepting connections after close()", async () => { + const server = await start(); + const client = await connect(); + await client.next("hello_ack"); + await server.close(); + await client.waitForClosed(); + + await expect( + PluginClient.connect({ socketPath: daemonSocketPath(), hello: makeHello() }), + ).rejects.toThrow(); + }); +}); + +describe("parseHello", () => { + const baseHello: Record = { + v: 1, + type: "hello", + token: "a".repeat(64), + instanceId: "i-test-1", + workspaceId: "ws-test", + cwd: "/repo/ws-test", + pid: 42, + hasUI: false, + listenAddr: "/tmp/i-test.sock", + pluginVersion: "1.8.0", + }; + + it("normalizes optional fields", () => { + const hello = parseHello({ ...baseHello, listenAddr: "" }); + expect(hello).toMatchObject({ + instanceId: "i-test-1", + workspaceId: "ws-test", + hasUI: false, + listenAddr: null, + pluginVersion: "1.8.0", + }); + }); + + it("rejects invalid pids and missing required fields", () => { + expect(parseHello({ ...baseHello, pid: -1 })).toBeUndefined(); + expect(parseHello({ ...baseHello, hasUI: "yes" })).toBeUndefined(); + expect(parseHello({ ...baseHello, pluginVersion: "" })).toBeUndefined(); + expect(parseHello({ ...baseHello, instanceId: "" })).toBeUndefined(); + }); +}); diff --git a/test/instances/supervisor.test.ts b/test/instances/supervisor.test.ts new file mode 100644 index 0000000..34d35f3 --- /dev/null +++ b/test/instances/supervisor.test.ts @@ -0,0 +1,518 @@ +import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { daemonSocketPath, daemonTokenPath, stateDir } from "../../src/core/paths.js"; +import { + createInstanceManager, + parseProcRss, + parsePsRss, + summarizeResources, + type InstanceManagerDeps, + type InstanceManagerHandle, +} from "../../src/instances/supervisor.js"; +import type { InstanceState } from "../../src/protocol/types.js"; +import { makeSessionState } from "../daemon/fakes.js"; +import { + FakeBus, + PluginClient, + delay, + makeHello, + makeTempEnv, + readRunLog, + startRecords, + waitFor, + writeFakeNvim, + type TempEnv, +} from "./helpers.js"; + +function asRecord(value: unknown): Record { + return value as Record; +} + +function isRunning(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +function processExits(bus: FakeBus): Record[] { + return bus.published.filter( + (record) => + record.type === "event" && asRecord(asRecord(record.payload).event).type === "pi2:process_exit", + ); +} + +describe("InstanceManager", () => { + let env: TempEnv; + let bus: FakeBus; + let manager: InstanceManagerHandle | undefined; + const workspaces = new Map(); + + beforeEach(() => { + env = makeTempEnv(); + bus = new FakeBus(); + workspaces.clear(); + }); + + afterEach(async () => { + if (manager) await manager.close(); + manager = undefined; + env.cleanup(); + }); + + function addWorkspace(id = "ws-1"): string { + const cwd = join(env.dir, "repo", id); + mkdirSync(cwd, { recursive: true }); + workspaces.set(id, cwd); + return cwd; + } + + async function create(options: { + bin?: string; + deps?: Partial; + } = {}): Promise { + const instance = await createInstanceManager({ + bus, + resolveCwd: (workspaceId) => workspaces.get(workspaceId), + ensureTimeoutMs: 4_000, + shutdownGraceMs: 300, + sigtermGraceMs: 200, + minSpawnIntervalMs: 300, + maxSpawnIntervalMs: 1_000, + ...(options.bin === undefined ? {} : { nvimBin: options.bin }), + ...(options.deps ?? {}), + }); + manager = instance; + return instance; + } + + it("spawns one nvim with the right argv/env and resolves with a ready state", async () => { + const cwd = addWorkspace(); + const fake = writeFakeNvim(env.dir, { sessions: ["s1"] }); + const mgr = await create({ bin: fake.bin }); + + const state = await mgr.ensure("ws-1"); + + expect(state.status).toBe("ready"); + expect(state.instanceId).toMatch(/^i-fake-\d+$/); + expect(state.pluginVersion).toBe("9.9.9-fake"); + expect(state.nvimPid).toBeGreaterThan(0); + expect(state.hasUI).toBe(false); + expect(state.attachedClients).toBe(0); + expect(state.startedAt).toBeGreaterThan(0); + expect(state.listenAddr).toMatch(/\/i\/[0-9a-f]{16}\.sock$/); + expect(mgr.get("ws-1")?.instanceId).toBe(state.instanceId); + + const starts = startRecords(fake.runLog); + expect(starts).toHaveLength(1); + const start = starts[0]!; + const argv = start.argv as string[]; + expect(argv.slice(0, 2)).toEqual(["--headless", "--listen"]); + expect(argv[2]).toBe(state.listenAddr); + expect(argv.slice(3)).toEqual(["-c", 'lua require("pi.host").start()']); + expect(start.cwd).toBe(cwd); + const spawnedEnv = start.env as Record; + expect(spawnedEnv.PI2_WORKSPACE_ID).toBe("ws-1"); + expect(spawnedEnv.PI2_RUNTIME_DIR).toBe(env.runtime); + expect(spawnedEnv.PI2_DAEMON_SOCKET).toBe(daemonSocketPath()); + expect(spawnedEnv.PI2_DAEMON_TOKEN_PATH).toBe(daemonTokenPath()); + + // Starting -> ready both surfaced on the bus. + const statuses = bus.published + .filter((record) => record.type === "instance_state" && record.workspaceId === "ws-1") + .map((record) => asRecord(record.payload).status); + expect(statuses).toContain("starting"); + expect(statuses).toContain("ready"); + }); + + it("passes PI2_NVIM_INIT as -u only when configured", async () => { + addWorkspace(); + const init = join(env.dir, "init.lua"); + const fake = writeFakeNvim(env.dir); + const mgr = await create({ bin: fake.bin, deps: { nvimInit: init } }); + + await mgr.ensure("ws-1"); + + const argv = startRecords(fake.runLog)[0]?.argv as string[]; + expect(argv.slice(3, 5)).toEqual(["-u", init]); + expect(argv.slice(5)).toEqual(["-c", 'lua require("pi.host").start()']); + }); + + it("is idempotent and reports state changes to handlers", async () => { + addWorkspace(); + const fake = writeFakeNvim(env.dir); + const mgr = await create({ bin: fake.bin }); + const seen: InstanceState[] = []; + mgr.onInstanceChange((state) => seen.push(state)); + + const first = await mgr.ensure("ws-1"); + const second = await mgr.ensure("ws-1"); + + expect(second.instanceId).toBe(first.instanceId); + expect(startRecords(fake.runLog)).toHaveLength(1); + expect(seen.some((state) => state.status === "ready")).toBe(true); + }); + + it("lets concurrent ensure() calls share one spawn", async () => { + addWorkspace(); + const fake = writeFakeNvim(env.dir); + const mgr = await create({ bin: fake.bin }); + + const states = await Promise.all([mgr.ensure("ws-1"), mgr.ensure("ws-1"), mgr.ensure("ws-1")]); + + expect(new Set(states.map((state) => state.instanceId)).size).toBe(1); + expect(startRecords(fake.runLog)).toHaveLength(1); + }); + + it("adopts an already connected plugin instead of spawning", async () => { + const cwd = addWorkspace(); + const fake = writeFakeNvim(env.dir); + const mgr = await create({ bin: fake.bin }); + + const plugin = await PluginClient.connect({ + socketPath: daemonSocketPath(), + hello: makeHello({ instanceId: "i-adopt", workspaceId: "ws-1", cwd }), + }); + await plugin.next("hello_ack"); + + const state = await mgr.ensure("ws-1"); + expect(state.instanceId).toBe("i-adopt"); + expect(state.status).toBe("ready"); + expect(startRecords(fake.runLog)).toHaveLength(0); + plugin.close(); + }); + + it("times out a silent instance with E_INSTANCE_STARTING and kills it", async () => { + addWorkspace(); + const fake = writeFakeNvim(env.dir, { mode: "no-hello" }); + const mgr = await create({ bin: fake.bin }); + + await expect(mgr.ensure("ws-1", { timeoutMs: 250 })).rejects.toMatchObject({ + code: "E_INSTANCE_STARTING", + retryable: true, + }); + + const starts = startRecords(fake.runLog); + expect(starts).toHaveLength(1); + const pid = starts[0]?.pid as number; + await waitFor(() => !isRunning(pid), 3_000); + expect(mgr.list().find((state) => state.workspaceId === "ws-1")?.status).toBe("stopped"); + // A failed start backs off the next attempt. + await expect(mgr.ensure("ws-1")).rejects.toMatchObject({ + code: "E_INSTANCE_UNAVAILABLE", + message: expect.stringContaining("backing off"), + }); + }); + + it("reports E_INSTANCE_UNAVAILABLE when the nvim binary cannot be spawned", async () => { + addWorkspace(); + const mgr = await create({ deps: { nvimBin: join(env.dir, "no-such-nvim") } }); + + await expect(mgr.ensure("ws-1")).rejects.toMatchObject({ + code: "E_INSTANCE_UNAVAILABLE", + message: expect.stringContaining("failed to spawn"), + }); + + const logDir = join(stateDir(), "instances"); + await waitFor(() => { + if (!existsSync(logDir)) return false; + const logFile = readdirSync(logDir)[0]; + if (logFile === undefined) return false; + return readFileSync(join(logDir, logFile), "utf8").includes("spawn error"); + }); + }); + + it("backs off after a failed start, then succeeds on a later ensure", async () => { + addWorkspace(); + const fake = writeFakeNvim(env.dir, { mode: "exit-first-run", failRuns: 1 }); + const mgr = await create({ + bin: fake.bin, + deps: { minSpawnIntervalMs: 150, maxSpawnIntervalMs: 500 }, + }); + + await expect(mgr.ensure("ws-1")).rejects.toMatchObject({ code: "E_INSTANCE_UNAVAILABLE" }); + expect(startRecords(fake.runLog)).toHaveLength(1); + + const started = Date.now(); + await expect(mgr.ensure("ws-1")).rejects.toMatchObject({ + code: "E_INSTANCE_UNAVAILABLE", + message: expect.stringContaining("backing off"), + }); + expect(Date.now() - started).toBeLessThan(150); + expect(startRecords(fake.runLog)).toHaveLength(1); + + await delay(220); + const state = await mgr.ensure("ws-1"); + expect(state.status).toBe("ready"); + expect(startRecords(fake.runLog)).toHaveLength(2); + }); + + it("rejects a second instance as unmanaged while the managed one keeps serving", async () => { + const cwd = addWorkspace(); + const fake = writeFakeNvim(env.dir); + const mgr = await create({ bin: fake.bin }); + const first = await mgr.ensure("ws-1"); + + const intruder = await PluginClient.connect({ + socketPath: daemonSocketPath(), + hello: makeHello({ instanceId: "i-intruder", workspaceId: "ws-1", cwd }), + }); + const ack = await intruder.next("hello_ack"); + + expect(asRecord(ack.rejected).code).toBe("E_LEASE"); + expect(asRecord(ack.rejected).message).toBe(`workspace already managed by ${first.instanceId}`); + await intruder.waitForClosed(); + + const unmanaged = await waitFor(() => + mgr.list().find((state) => state.instanceId === "i-intruder"), + ); + expect(unmanaged.status).toBe("unmanaged"); + expect(unmanaged.workspaceId).toBe("ws-1"); + expect(unmanaged.reason).toContain("already managed"); + + expect(mgr.instanceStates().map((state) => state.instanceId)).toEqual([first.instanceId]); + expect((await mgr.ensure("ws-1")).instanceId).toBe(first.instanceId); + expect(startRecords(fake.runLog)).toHaveLength(1); + }); + + it("degrades on socket close and fans pi2:process_exit out to known sessions", async () => { + addWorkspace(); + const fake = writeFakeNvim(env.dir, { sessions: ["s1", "s2"], crashAfterMs: 150 }); + const mgr = await create({ + bin: fake.bin, + deps: { minSpawnIntervalMs: 800, maxSpawnIntervalMs: 2_000 }, + }); + const state = await mgr.ensure("ws-1"); + await waitFor(() => mgr.get("ws-1")?.hasSession("s2"), 3_000); + + const degraded = await waitFor( + () => mgr.list().find((candidate) => candidate.status === "degraded"), + 4_000, + ); + expect(degraded.instanceId).toBe(state.instanceId); + expect(degraded.nvimPid).toBeNull(); + expect(mgr.get("ws-1")).toBeUndefined(); + expect(mgr.findWorkspaceBySession("s1")).toBeUndefined(); + + const exits = processExits(bus); + expect(exits.map((record) => record.sessionId).sort()).toEqual(["s1", "s2"]); + for (const record of exits) { + expect(record.workspaceId).toBe("ws-1"); + expect(record.epoch).toBe(state.instanceId); + expect(asRecord(record.payload).event).toMatchObject({ + type: "pi2:process_exit", + code: null, + reason: "instance died", + }); + } + + // Never auto-restarted... + await delay(400); + expect(startRecords(fake.runLog)).toHaveLength(1); + // ...and the next ensure backs off, then spawns a fresh instance. + await expect(mgr.ensure("ws-1")).rejects.toMatchObject({ code: "E_INSTANCE_UNAVAILABLE" }); + await delay(500); + const respawned = await mgr.ensure("ws-1"); + expect(respawned.instanceId).not.toBe(state.instanceId); + expect(startRecords(fake.runLog)).toHaveLength(2); + }); + + it("drains an instance on shutdown, reports stopped and does not emit process_exit", async () => { + addWorkspace(); + const fake = writeFakeNvim(env.dir, { sessions: ["s1"] }); + const mgr = await create({ bin: fake.bin }); + const state = await mgr.ensure("ws-1"); + const pid = state.nvimPid as number; + const exitsBefore = processExits(bus).length; + + await mgr.shutdown("ws-1", "drain"); + + const stopped = mgr.list().find((candidate) => candidate.workspaceId === "ws-1"); + expect(stopped?.status).toBe("stopped"); + expect(stopped?.nvimPid).toBeNull(); + expect(mgr.get("ws-1")).toBeUndefined(); + expect(processExits(bus)).toHaveLength(exitsBefore); + expect( + readRunLog(fake.runLog).some( + (entry) => entry.kind === "shutdown" && asRecord(entry).mode === "drain", + ), + ).toBe(true); + await waitFor(() => !isRunning(pid), 3_000); + + const respawned = await mgr.ensure("ws-1"); + expect(respawned.instanceId).not.toBe(state.instanceId); + expect(startRecords(fake.runLog)).toHaveLength(2); + }); + + it("escalates SIGTERM to SIGKILL when the instance ignores shutdown", async () => { + addWorkspace(); + const fake = writeFakeNvim(env.dir, { ignoreShutdown: true }); + const mgr = await create({ + bin: fake.bin, + deps: { shutdownGraceMs: 150, sigtermGraceMs: 150 }, + }); + const state = await mgr.ensure("ws-1"); + const pid = state.nvimPid as number; + + const started = Date.now(); + await mgr.shutdown("ws-1", "stop"); + const elapsed = Date.now() - started; + + expect(elapsed).toBeGreaterThanOrEqual(250); + expect(mgr.list().find((candidate) => candidate.workspaceId === "ws-1")?.status).toBe("stopped"); + expect(readRunLog(fake.runLog).some((entry) => entry.kind === "sigterm")).toBe(true); + await waitFor(() => !isRunning(pid), 3_000); + }); + + it("treats shutdown of an unknown workspace as a no-op", async () => { + addWorkspace(); + const fake = writeFakeNvim(env.dir); + const mgr = await create({ bin: fake.bin }); + await expect(mgr.shutdown("ws-missing", "stop")).resolves.toBeUndefined(); + expect(startRecords(fake.runLog)).toHaveLength(0); + }); + + it("resolves workspace ownership from live sessions and snapshot caches", async () => { + addWorkspace(); + const snapshotState = makeSessionState("s9", "ws-1"); + const fake = writeFakeNvim(env.dir, { + sessions: ["s1"], + snapshots: [{ sessionId: "s9", state: snapshotState }], + }); + const mgr = await create({ bin: fake.bin }); + + await mgr.ensure("ws-1"); + + await waitFor(() => mgr.findWorkspaceBySession("s1") === "ws-1"); + await waitFor(() => mgr.findWorkspaceBySession("s9") === "ws-1"); + expect(mgr.findWorkspaceBySession("unknown")).toBeUndefined(); + }); + + it("unsubscribes the plugin when the last browser subscriber goes away", async () => { + addWorkspace(); + const fake = writeFakeNvim(env.dir); + const mgr = await create({ bin: fake.bin }); + await mgr.ensure("ws-1"); + + mgr.get("ws-1")?.subscribe("s1"); + mgr.maybeUnsubscribe("ws-1", "s1"); + + await waitFor(() => + readRunLog(fake.runLog).some((entry) => { + if (entry.kind !== "record") return false; + const record = asRecord(asRecord(entry).record); + return record.type === "sub.unsubscribe" && record.sessionId === "s1"; + }), + ); + const received = readRunLog(fake.runLog) + .filter((entry) => entry.kind === "record") + .map((entry) => asRecord(entry.record).type); + expect(received).toContain("sub.subscribe"); + expect(received).toContain("sub.unsubscribe"); + }); + + it("reports E_NOT_FOUND for unknown workspaces without spawning", async () => { + const fake = writeFakeNvim(env.dir); + const mgr = await create({ bin: fake.bin }); + + await expect(mgr.ensure("no-such-workspace")).rejects.toMatchObject({ code: "E_NOT_FOUND" }); + expect(startRecords(fake.runLog)).toHaveLength(0); + }); + + it("reports per-instance RSS and totals for /api/v1/resources", async () => { + addWorkspace(); + const fake = writeFakeNvim(env.dir, { sessions: ["s1"] }); + const mgr = await create({ + bin: fake.bin, + deps: { + readRss: async () => 123 * 1024 * 1024, + totalMemory: () => 16 * 1024 ** 3, + }, + }); + const state = await mgr.ensure("ws-1"); + await waitFor(() => mgr.get("ws-1")?.hasSession("s1")); + + const snapshot = await mgr.resources(); + + expect(snapshot.instances).toHaveLength(1); + expect(snapshot.instances[0]).toMatchObject({ + workspaceId: "ws-1", + instanceId: state.instanceId, + nvimPid: state.nvimPid, + rssBytes: 123 * 1024 * 1024, + sessions: 1, + hasUI: false, + }); + expect(snapshot.totalRssBytes).toBe(123 * 1024 * 1024); + expect(snapshot.physicalMemoryBytes).toBe(16 * 1024 ** 3); + expect(snapshot.warn).toBe(false); + expect(snapshot.reason).toBeUndefined(); + }); + + it("closes the server and kills spawned instances", async () => { + addWorkspace(); + const fake = writeFakeNvim(env.dir); + const mgr = await create({ bin: fake.bin }); + const state = await mgr.ensure("ws-1"); + const pid = state.nvimPid as number; + + await mgr.close(); + + await waitFor(() => !isRunning(pid), 3_000); + await expect(mgr.ensure("ws-1")).rejects.toMatchObject({ code: "E_INSTANCE_UNAVAILABLE" }); + expect(existsSync(daemonSocketPath())).toBe(false); + }); +}); + +describe("resources helpers", () => { + it("parses /proc//status VmRSS", () => { + expect(parseProcRss("Name:\tnvim\nVmRSS:\t 102400 kB\nVmSize:\t 204800 kB\n")).toBe(102400 * 1024); + expect(parseProcRss("VmRSS: 0 kB")).toBe(0); + expect(parseProcRss("Name: nvim\n")).toBeNull(); + expect(parseProcRss("VmRSS: not-a-number kB")).toBeNull(); + }); + + it("parses ps -o rss= output", () => { + expect(parsePsRss(" 204800\n")).toBe(204800 * 1024); + expect(parsePsRss("204800 12\n")).toBe(204800 * 1024); + expect(parsePsRss("")).toBeNull(); + expect(parsePsRss("not-a-number")).toBeNull(); + }); + + const instance = (index: number, rssBytes: number | null = 1024) => ({ + workspaceId: `ws-${index}`, + instanceId: `i-${index}`, + nvimPid: 1000 + index, + rssBytes, + sessions: 0, + hasUI: false, + }); + + it("warns above eight instances", () => { + const snapshot = summarizeResources(Array.from({ length: 9 }, (_, index) => instance(index)), 16 * 1024 ** 3); + expect(snapshot.warn).toBe(true); + expect(snapshot.reason).toContain("9 instances"); + expect(snapshot.totalRssBytes).toBe(9 * 1024); + }); + + it("warns when RSS exceeds 60% of physical memory", () => { + const snapshot = summarizeResources([instance(1, 11 * 1024 ** 3)], 16 * 1024 ** 3); + expect(snapshot.warn).toBe(true); + expect(snapshot.reason).toContain("RSS"); + }); + + it("does not warn at exactly eight instances and 60% RSS", () => { + const snapshot = summarizeResources([instance(1, 9.6 * 1024 ** 3)], 16 * 1024 ** 3); + expect(snapshot.warn).toBe(false); + expect(snapshot.reason).toBeUndefined(); + }); + + it("ignores missing RSS in the total", () => { + const snapshot = summarizeResources([instance(1, null), instance(2, 2048)], 16 * 1024 ** 3); + expect(snapshot.totalRssBytes).toBe(2048); + expect(snapshot.warn).toBe(false); + }); +});