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
This commit is contained in:
1 parent
5b55e622ea
commit
a495f2ac71
9 files changed
+3583
No files matched your search
@@ -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<string, unknown>, connection: PluginSocketConnection) => void;
|
||||
}
|
||||
|
||||
export interface CommandRequest {
|
||||
id: string;
|
||||
sessionId?: string;
|
||||
method: string;
|
||||
params?: Record<string, unknown>;
|
||||
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<string, unknown> {
|
||||
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<void>;
|
||||
|
||||
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<string, unknown>, connection: PluginSocketConnection) => void)
|
||||
| undefined;
|
||||
|
||||
private readonly pending = new Map<string, PendingCommand>();
|
||||
private readonly snapshots = new Map<string, SnapshotCacheEntry>();
|
||||
/** Per session: the highest seq seen *within the current epoch*. */
|
||||
private readonly seqs = new Map<string, { epoch: string; seq: number }>();
|
||||
private readonly sessions = new Set<string>();
|
||||
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<void>((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<string, unknown>): 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<CommandAck> {
|
||||
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<CommandAck>((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<string, unknown>): 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<string, unknown>): 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<string, unknown>): 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<string, unknown>): 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<string, unknown>): 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<string, unknown>): 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;
|
||||
}
|
||||
}
|
||||
@@ -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<string, unknown> | undefined;
|
||||
|
||||
constructor(code: string, message: string, retryable = false, details?: Record<string, unknown>) {
|
||||
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<string, unknown>): InstanceError {
|
||||
return new InstanceError(ERROR_CODES.INSTANCE_UNAVAILABLE, message, true, details);
|
||||
}
|
||||
|
||||
static starting(message: string, details?: Record<string, unknown>): 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);
|
||||
}
|
||||
@@ -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";
|
||||
@@ -0,0 +1,543 @@
|
||||
/**
|
||||
* Plugin-facing unix-socket server (`<runtime>/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 `<runtime>/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<string, unknown>;
|
||||
policy?: Record<string, unknown>;
|
||||
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<string, unknown> {
|
||||
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<string, unknown>): 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<SocketState>();
|
||||
private readonly byWorkspace = new Map<string, PluginSocketConnection>();
|
||||
|
||||
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<void> {
|
||||
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<void>((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<void> {
|
||||
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<void>((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<void> {
|
||||
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<string, unknown>): 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<string, unknown>,
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<string | undefined>;
|
||||
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<number | null>;
|
||||
totalMemory?: () => number;
|
||||
}
|
||||
|
||||
export interface InstanceManagerHandle extends InstanceManager {
|
||||
/** Stop the plugin server and kill every spawned nvim (daemon/test shutdown). */
|
||||
close(): Promise<void>;
|
||||
/** The plugin-facing socket server (exposed for diagnostics). */
|
||||
readonly pluginServer: PluginServer;
|
||||
}
|
||||
|
||||
interface SpawnWaiter {
|
||||
promise: Promise<PluginSocketConnection>;
|
||||
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/<pid>/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 <pid>` 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<boolean> {
|
||||
if (child.exitCode !== null || child.signalCode !== null) return true;
|
||||
return new Promise<boolean>((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<boolean> {
|
||||
if (connection.isClosed) return Promise.resolve(true);
|
||||
return new Promise<boolean>((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<number | null>;
|
||||
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<string, InstanceState>();
|
||||
private readonly unmanaged = new Map<string, InstanceState>();
|
||||
private readonly connections = new Map<string, PluginSocketConnection>();
|
||||
private readonly spawning = new Map<string, Promise<InstanceState>>();
|
||||
private readonly waiters = new Map<string, SpawnWaiter>();
|
||||
private readonly children = new Map<string, ChildProcess>();
|
||||
private readonly failures = new Map<string, SpawnFailure>();
|
||||
private readonly shuttingDown = new Set<string>();
|
||||
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<void> {
|
||||
await this.pluginServer.start();
|
||||
}
|
||||
|
||||
async ensure(workspaceId: string, opts: { timeoutMs?: number } = {}): Promise<InstanceState> {
|
||||
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<void> {
|
||||
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<InstanceResourcesSnapshot> {
|
||||
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<void> {
|
||||
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<InstanceState> {
|
||||
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<PluginSocketConnection>((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<void> {
|
||||
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<number | null> {
|
||||
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<InstanceManagerHandle> {
|
||||
const manager = new ManagedInstanceManager(deps);
|
||||
await manager.start();
|
||||
return manager;
|
||||
}
|
||||
Reference in new issue
Block a user