refactor(process): extract reusable provider lifecycle primitives

Introduce provider-neutral ownership, private runtime roots, absolute startup deadlines, pending-operation correlation, bounded output capture, and verified TERM-to-KILL process supervision.\n\nMigrate Hopper onto the shared lifecycle pieces while keeping its Unix-socket protocol and health/shutdown parsing adapter-specific. Preserve exact ownership checks and fail-closed cleanup, including descendant cleanup after the launcher leader exits.\n\nAdd reusable process fixtures and deterministic coverage for startup timeout, cancellation, output bounds, exit diagnostics, cleanup escalation, repeated close, spawn failure, and resource disposal. Update architecture, provider evaluation, contributor guidance, and generated API documentation.
This commit is contained in:
N0zoM1z0
2026-07-15 23:20:48 +09:00
committed by N0zoM1z0
parent a7621c2633
commit 70e1a0f532
82 changed files with 3400 additions and 436 deletions
+1 -1
View File
@@ -28,7 +28,7 @@ import type { LoopbackReplay } from "./LoopbackReplay.js";
import {
cleanupOwnedProcessGroup,
observeOwnedProcessGroup,
} from "./ProcessOwnership.js";
} from "../process/ProcessOwnership.js";
import {
classifyFilesystemEffects,
ProcessCheckpoints,
+1 -1
View File
@@ -25,7 +25,7 @@ import {
type CommandShimReplay,
} from "./CommandShimReplay.js";
import { normalizeProcessText } from "./ProcessNormalization.js";
import { selectCapturedProcessGroupIds } from "./ProcessOwnership.js";
import { selectCapturedProcessGroupIds } from "../process/ProcessOwnership.js";
import {
awaitTerminalExit,
buildCaptureResult,
+1 -1
View File
@@ -2,7 +2,7 @@ import { execFile } from "node:child_process";
import { readFile, readdir } from "node:fs/promises";
import { promisify } from "node:util";
import type { ProcessSample } from "../domain/processCapture.js";
import { readProcessRunId } from "./ProcessOwnership.js";
import { readProcessRunId } from "../process/ProcessOwnership.js";
const execFileAsync = promisify(execFile);
const PROC_READ_CONCURRENCY = 64;
+29 -83
View File
@@ -1,4 +1,3 @@
import { spawn, type ChildProcess } from "node:child_process";
import { execFile } from "node:child_process";
import { chmod, writeFile } from "node:fs/promises";
import { basename, dirname, extname, join } from "node:path";
@@ -6,10 +5,12 @@ import { promisify } from "node:util";
import { HopperCancelledError, HopperStartError } from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import { cleanupOwnedProcessGroup } from "../process/ProcessOwnership.js";
import {
cleanupOwnedProcessGroup,
type ProcessCleanupResult,
} from "../application/ProcessOwnership.js";
type ProviderProcessLaunch,
spawnOwnedProviderProcess,
} from "../process/ProviderProcess.js";
import { waitForAbortableDelay } from "../process/ProviderDeadline.js";
import writeFileAtomic from "write-file-atomic";
const execFileAsync = promisify(execFile);
@@ -24,12 +25,9 @@ export interface BridgeSession {
}
/** Process handle returned by a bridge launcher. */
export interface BridgeLaunch {
readonly process: ChildProcess;
readonly ownsProcessLifetime: boolean;
export interface BridgeLaunch extends ProviderProcessLaunch {
/** True when verified process cleanup completes bridge shutdown. */
readonly shutdownByCleanup?: boolean;
readonly cleanup?: () => Promise<ProcessCleanupResult>;
}
/** Application-owned capability that starts the in-Hopper bridge. */
@@ -119,18 +117,14 @@ export class HopperApplicationLauncher implements BridgeLauncher {
const linuxDemo = linuxDemoLaunch(this.options, session, args);
const ownershipCommand =
linuxDemo?.ownershipCommand ?? this.options.launcherPath;
const started = await spawnLauncher(
linuxDemo?.command ?? this.options.launcherPath,
linuxDemo?.args ?? args,
session.runId,
);
if (!started.ok) return started;
const child = started.value;
const pid = child.pid;
if (pid === undefined)
return err(
new HopperStartError({ cause: new Error("missing launcher PID") }),
);
const started = await spawnOwnedProviderProcess({
command: linuxDemo?.command ?? this.options.launcherPath,
arguments: linuxDemo?.args ?? args,
runId: session.runId,
expectedCommand: ownershipCommand,
});
const child = started.process;
const pid = started.ownership.leaderPid;
const ownership = {
schema_version: 1,
run_id: session.runId,
@@ -147,22 +141,17 @@ export class HopperApplicationLauncher implements BridgeLauncher {
{ encoding: "utf8", mode: 0o600 },
);
} catch (cause: unknown) {
await cleanupOwnedProcessGroup(
ownedProcessGroup(session, pid, ownershipCommand),
);
await cleanupOwnedProcessGroup(started.ownership);
return err(new HopperStartError({ cause }));
}
return ok({
process: child,
ownsProcessLifetime: true,
shutdownByCleanup: ownsProcessLifetime,
cleanup: () =>
cleanupOwnedProcessGroup(
ownedProcessGroup(session, pid, ownershipCommand),
),
cleanup: () => cleanupOwnedProcessGroup(started.ownership),
});
} catch (cause: unknown) {
return err(new HopperStartError({ cause }));
return err(hopperLaunchFailure(cause, options.signal));
}
}
}
@@ -196,6 +185,14 @@ const linuxDemoLaunch = (
};
};
const hopperLaunchFailure = (
cause: unknown,
signal: AbortSignal | undefined,
): HopperCancelledError | HopperStartError =>
signal?.aborted === true
? new HopperCancelledError()
: new HopperStartError({ cause });
/** Select the version-pinned adapter from the caller's explicit launch mode. */
export const usesLinuxDemo = (
options: HopperApplicationLauncherOptions,
@@ -204,42 +201,6 @@ export const usesLinuxDemo = (
readonly demoHelperPath: string;
} => options.launchMode === "verified_linux_demo";
const spawnLauncher = async (
command: string,
args: readonly string[],
runId: string,
): Promise<Result<ChildProcess, HopperStartError>> => {
const child = spawn(command, args, {
stdio: ["ignore", "ignore", "pipe"],
detached: process.platform !== "win32",
env: { ...process.env, REA_PROCESS_RUN_ID: runId },
});
return new Promise((resolve) => {
const onSpawn = (): void => {
child.off("error", onError);
resolve(ok(child));
};
const onError = (cause: Error): void => {
child.off("spawn", onSpawn);
resolve(err(new HopperStartError({ cause })));
};
child.once("spawn", onSpawn);
child.once("error", onError);
});
};
const ownedProcessGroup = (
session: BridgeSession,
pid: number,
launcherPath: string,
) => ({
runId: session.runId,
leaderPid: pid,
processGroupId: pid,
expectedCommand: launcherPath,
expectedParentPid: process.pid,
});
const prepareHopperApplication = async (
launcherPath: string,
signal?: AbortSignal,
@@ -256,25 +217,10 @@ const prepareHopperApplication = async (
"-a",
appBundle,
]);
return waitForDelay(HOPPER_BACKGROUND_STARTUP_MS, signal);
};
const waitForDelay = (
milliseconds: number,
signal?: AbortSignal,
): Promise<boolean> => {
if (signal?.aborted === true) return Promise.resolve(false);
return new Promise((resolve) => {
const timer = setTimeout(() => {
signal?.removeEventListener("abort", onAbort);
resolve(true);
}, milliseconds);
const onAbort = (): void => {
clearTimeout(timer);
resolve(false);
};
signal?.addEventListener("abort", onAbort, { once: true });
});
return (
(await waitForAbortableDelay(HOPPER_BACKGROUND_STARTUP_MS, signal)) ===
"elapsed"
);
};
const hopperApplicationBundle = (launcherPath: string): string | undefined => {
+204 -199
View File
@@ -1,6 +1,6 @@
import { randomBytes, randomUUID } from "node:crypto";
import { access, mkdtemp, rm } from "node:fs/promises";
import { createConnection, type Socket } from "node:net";
import { access } from "node:fs/promises";
import type { Socket } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -15,10 +15,27 @@ import {
} from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { BridgeLaunch, BridgeLauncher } from "./BridgeLauncher.js";
import { silentLogger, type Logger } from "../logger.js";
import { PendingOperations } from "../process/PendingOperations.js";
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
import { ProviderStartupDeadline } from "../process/ProviderDeadline.js";
import type { ProcessCleanupResult } from "../process/ProcessOwnership.js";
import {
type ProviderProcessDiagnostic,
ProviderProcessSupervisor,
} from "../process/ProviderProcess.js";
import type { BridgeLaunch, BridgeLauncher } from "./BridgeLauncher.js";
import {
isHopperCleanupRequired,
isHopperShutdownAcknowledgement,
parseHopperServerInfo,
type HopperServerInfo,
} from "./HopperSessionValues.js";
import { connectHopperSocketOnce } from "./HopperSocketConnection.js";
import { parseResponseLine, responseResult } from "./protocol.js";
export type { HopperServerInfo } from "./HopperSessionValues.js";
const MAX_LINE_BYTES = 10 * 1024 * 1024;
const SHUTDOWN_TIMEOUT_MS = 30_000;
const SESSION_ROOT = process.platform === "darwin" ? "/tmp" : tmpdir();
@@ -37,18 +54,6 @@ type HopperDiagnostic =
| { readonly type: "launcher-stderr"; readonly bytes: number }
| { readonly type: "launcher-exit"; readonly code: number | null };
export interface HopperServerInfo {
readonly name: string;
readonly version: string;
}
interface PendingRequest {
readonly resolve: (result: Result<JsonValue, HopperError>) => void;
readonly timer: NodeJS.Timeout;
readonly signal: AbortSignal | undefined;
readonly onAbort: (() => void) | undefined;
}
/**
* Owns one authenticated NDJSON-over-Unix-socket bridge session.
*
@@ -62,11 +67,15 @@ export class HopperClient {
Pick<HopperClientOptions, "requestTimeoutMs" | "startupTimeoutMs">
> &
HopperClientOptions;
readonly #pending = new Map<number, PendingRequest>();
readonly #pending = new PendingOperations<
number,
Result<JsonValue, HopperError>
>();
readonly #logger: Logger;
#socket: Socket | undefined;
#launch: BridgeLaunch | undefined;
#directory: string | undefined;
#process: ProviderProcessSupervisor | undefined;
#runtimeRoot: PrivateRuntimeRoot | undefined;
#token: string | undefined;
#nextId = 1;
#buffer = "";
@@ -75,6 +84,15 @@ export class HopperClient {
#startupController: AbortController | undefined;
#startPromise: Promise<Result<HopperServerInfo, HopperError>> | undefined;
#closePromise: Promise<void> | undefined;
readonly #onSocketData = (chunk: string): void => {
this.#onData(chunk);
};
readonly #onSocketError = (): void => {
this.#failAll(new HopperProcessError(null));
};
readonly #onSocketClose = (): void => {
if (!this.#closing) this.#failAll(new HopperProcessError(null));
};
constructor(options: HopperClientOptions) {
this.#logger = options.logger ?? silentLogger;
@@ -93,21 +111,33 @@ export class HopperClient {
if (this.#startPromise !== undefined) return this.#startPromise;
const controller = new AbortController();
const startupSignal =
signal === undefined
? controller.signal
: AbortSignal.any([signal, controller.signal]);
const started = this.#start(startupSignal);
const onAbort = (): void => controller.abort(signal?.reason);
if (signal?.aborted === true) onAbort();
else signal?.addEventListener("abort", onAbort, { once: true });
const started = this.#start(controller.signal);
this.#startupController = controller;
this.#startPromise = started;
void started.then((result) => {
if (!result.ok && this.#startPromise === started) {
const release = (): void => {
signal?.removeEventListener("abort", onAbort);
};
const reset = (): void => {
if (this.#startPromise === started) {
this.#startPromise = undefined;
if (this.#startupController === controller) {
this.#startupController = undefined;
}
}
});
};
void started.then(
(result) => {
release();
if (!result.ok) reset();
},
() => {
release();
reset();
},
);
return started;
}
@@ -115,55 +145,86 @@ export class HopperClient {
signal?: AbortSignal,
): Promise<Result<HopperServerInfo, HopperError>> {
if (isAborted(signal)) return err(new HopperCancelledError());
if (this.#socket !== undefined || this.#directory !== undefined) {
if (this.#socket !== undefined || this.#runtimeRoot !== undefined) {
return err(new HopperProtocolError("Hopper client is already started"));
}
const deadline = new ProviderStartupDeadline(
this.#options.startupTimeoutMs,
signal,
);
try {
this.#directory = await mkdtemp(join(SESSION_ROOT, "rea-"));
return await this.#startWithin(deadline);
} finally {
deadline.dispose();
}
}
async #startWithin(
deadline: ProviderStartupDeadline,
): Promise<Result<HopperServerInfo, HopperError>> {
try {
this.#runtimeRoot = await PrivateRuntimeRoot.create({
parent: SESSION_ROOT,
prefix: "rea-",
});
} catch (cause: unknown) {
return err(new HopperStartError({ cause }));
}
if (isAborted(signal)) {
if (deadline.signal.aborted) {
await this.#cleanup();
return err(new HopperCancelledError());
return err(startupInterruption(deadline));
}
const socketPath = join(this.#directory, "bridge.sock");
const socketPath = join(this.#runtimeRoot.path, "bridge.sock");
this.#token = randomBytes(32).toString("hex");
this.#launcherExitCode = undefined;
const runId = randomUUID();
const launched = await this.#options.launcher.launch(
{
directory: this.#directory,
socketPath,
token: this.#token,
runId,
},
signal === undefined ? {} : { signal },
);
const launched: Result<
BridgeLaunch,
HopperStartError | HopperCancelledError
> = await this.#options.launcher
.launch(
{
directory: this.#runtimeRoot.path,
socketPath,
token: this.#token,
runId,
},
{ signal: deadline.signal },
)
.catch((cause: unknown) => err(new HopperStartError({ cause })));
if (!launched.ok) {
await this.#cleanup();
return launched;
return deadline.signal.aborted
? err(startupInterruption(deadline))
: launched;
}
this.#launch = launched.value;
this.#attachLauncher(launched.value);
const connected = await this.#connect(socketPath, signal);
const connected = await this.#connect(socketPath, deadline);
if (!connected.ok) {
await this.#cleanup();
return connected;
}
const remainingMs = deadline.remainingMs();
if (remainingMs <= 0) {
await this.#cleanup();
return err(new HopperTimeoutError(this.#options.startupTimeoutMs));
}
const health = await this.#request(
"health",
{},
{
timeoutMs: this.#options.startupTimeoutMs,
...(signal === undefined ? {} : { signal }),
timeoutMs: remainingMs,
signal: deadline.signal,
},
);
if (!health.ok) {
await this.#cleanup();
return health;
return deadline.signal.aborted
? err(startupInterruption(deadline))
: health;
}
const parsed = parseServerInfo(health.value, runId);
const parsed = parseHopperServerInfo(health.value, runId);
if (!parsed.ok) await this.#cleanup();
return parsed;
}
@@ -213,7 +274,7 @@ export class HopperClient {
this.#closing = true;
try {
const socket = this.#socket;
let cleanupAttempted = false;
let cleanupResult: ProcessCleanupResult | undefined;
if (socket !== undefined && !socket.destroyed) {
const shutdown = await this.#request(
"shutdown",
@@ -222,46 +283,50 @@ export class HopperClient {
).catch(() => err(new HopperProcessError(null)));
if (
shutdown.ok &&
isCleanupRequired(shutdown.value) &&
isHopperCleanupRequired(shutdown.value) &&
this.#launch?.shutdownByCleanup === true &&
this.#launch.cleanup !== undefined
) {
cleanupAttempted = true;
const cleanup = await this.#launch.cleanup();
if (!cleanup.cleaned) {
cleanupResult = await this.#launch
.cleanup()
.catch(providerCleanupFailure);
if (!cleanupResult.cleaned) {
await this.#fallbackDocumentShutdown();
const retried = await this.#launch.cleanup();
if (!retried.cleaned)
this.#logger.warn(
{ reason: retried.reason },
"Owned launcher cleanup failed closed",
);
cleanupResult = await this.#launch
.cleanup()
.catch(providerCleanupFailure);
}
} else if (!shutdown.ok || !isShutdownAcknowledgement(shutdown.value))
} else if (
!shutdown.ok ||
!isHopperShutdownAcknowledgement(shutdown.value)
)
this.#logger.warn(
{ status: shutdown.ok ? "invalid-acknowledgement" : "failed" },
"Hopper document shutdown was not confirmed",
);
}
this.#failAll(new HopperProcessError(null));
if (socket !== undefined) this.#detachSocket(socket);
socket?.destroy();
this.#socket = undefined;
if (this.#launch?.ownsProcessLifetime === true) {
if (this.#launch.cleanup !== undefined && !cleanupAttempted) {
const cleanup = await this.#launch.cleanup();
if (!cleanup.cleaned)
this.#logger.warn(
{ reason: cleanup.reason },
"Owned launcher cleanup failed closed",
);
} else this.#launch.process.kill("SIGTERM");
if (this.#process !== undefined) {
const stopped = await this.#process.stop(
cleanupResult === undefined ? {} : { cleanupResult },
);
if (stopped.status === "incomplete")
this.#logger.warn(
{ reason: stopped.reason },
"Owned launcher cleanup failed closed",
);
}
this.#process = undefined;
this.#launch = undefined;
if (this.#directory !== undefined) {
await rm(this.#directory, { recursive: true, force: true });
this.#directory = undefined;
}
const runtimeRoot = this.#runtimeRoot;
this.#runtimeRoot = undefined;
await runtimeRoot?.close();
this.#token = undefined;
this.#buffer = "";
this.#launcherExitCode = undefined;
} finally {
this.#closing = false;
}
@@ -273,7 +338,7 @@ export class HopperClient {
{},
{ timeoutMs: SHUTDOWN_TIMEOUT_MS },
).catch(() => err(new HopperProcessError(null)));
if (!fallback.ok || !isShutdownAcknowledgement(fallback.value))
if (!fallback.ok || !isHopperShutdownAcknowledgement(fallback.value))
this.#logger.warn(
{ status: fallback.ok ? "invalid-acknowledgement" : "failed" },
"Hopper document shutdown fallback was not confirmed",
@@ -282,11 +347,10 @@ export class HopperClient {
async #connect(
socketPath: string,
signal?: AbortSignal,
deadline: ProviderStartupDeadline,
): Promise<Result<undefined, HopperError>> {
const deadline = Date.now() + this.#options.startupTimeoutMs;
while (Date.now() < deadline) {
if (signal?.aborted === true) return err(new HopperCancelledError());
while (deadline.remainingMs() > 0) {
if (deadline.signal.aborted) return err(startupInterruption(deadline));
if (this.#closing) return err(new HopperProcessError(null));
if (
this.#launcherExitCode !== undefined &&
@@ -296,18 +360,21 @@ export class HopperClient {
try {
await access(socketPath);
} catch {
if (!(await waitForDelay(50, signal)))
return err(new HopperCancelledError());
if ((await deadline.wait(50)) === "aborted")
return err(startupInterruption(deadline));
continue;
}
const attempt = await connectOnce(socketPath);
const attempt = await connectHopperSocketOnce(
socketPath,
deadline.signal,
);
if (attempt.ok) {
this.#socket = attempt.value;
this.#attachSocket(attempt.value);
return ok(undefined);
}
if (!(await waitForDelay(50, signal)))
return err(new HopperCancelledError());
if ((await deadline.wait(50)) === "aborted")
return err(startupInterruption(deadline));
}
return err(new HopperTimeoutError(this.#options.startupTimeoutMs));
}
@@ -327,31 +394,17 @@ export class HopperClient {
const id = this.#nextId++;
const startedAt = performance.now();
const timeoutMs = options.timeoutMs ?? this.#options.requestTimeoutMs;
const response = new Promise<Result<JsonValue, HopperError>>((resolve) => {
const onAbort =
options.signal === undefined
? undefined
: () => {
this.#abandon(id, err(new HopperCancelledError()));
};
const timer = setTimeout(() => {
this.#abandon(id, err(new HopperTimeoutError(timeoutMs)));
}, timeoutMs);
this.#pending.set(id, {
resolve,
timer,
signal: options.signal,
onAbort,
});
options.signal?.addEventListener("abort", onAbort ?? (() => undefined), {
once: true,
});
const response = this.#pending.wait(id, {
timeoutMs,
...(options.signal === undefined ? {} : { signal: options.signal }),
timeoutValue: () => err(new HopperTimeoutError(timeoutMs)),
cancelledValue: () => err(new HopperCancelledError()),
});
socket.write(
`${JSON.stringify({ id, token, method, params })}\n`,
(cause) => {
if (cause !== undefined && cause !== null)
this.#settle(id, err(new HopperProcessError(null)));
this.#pending.settle(id, err(new HopperProcessError(null)));
},
);
const result = await response;
@@ -369,31 +422,49 @@ export class HopperClient {
#attachSocket(socket: Socket): void {
socket.setEncoding("utf8");
socket.on("data", (chunk: string) => {
this.#onData(chunk);
});
socket.on("error", () => {
this.#failAll(new HopperProcessError(null));
});
socket.on("close", () => {
if (!this.#closing) this.#failAll(new HopperProcessError(null));
});
socket.on("data", this.#onSocketData);
socket.on("error", this.#onSocketError);
socket.on("close", this.#onSocketClose);
}
#detachSocket(socket: Socket): void {
socket.off("data", this.#onSocketData);
socket.off("error", this.#onSocketError);
socket.off("close", this.#onSocketClose);
}
#attachLauncher(launch: BridgeLaunch): void {
launch.process.stderr?.on("data", (chunk: Buffer) => {
this.#process = new ProviderProcessSupervisor(launch, {
onDiagnostic: (event) => this.#onLauncherDiagnostic(launch, event),
});
}
#onLauncherDiagnostic(
launch: BridgeLaunch,
event: ProviderProcessDiagnostic,
): void {
if (event.type === "output" && event.stream === "stderr") {
this.#options.onDiagnostic?.({
type: "launcher-stderr",
bytes: chunk.byteLength,
bytes: event.bytes,
});
return;
}
if (event.type === "error") {
this.#logger.warn(
{ message: event.message },
"Hopper launcher process emitted an error",
);
return;
}
if (event.type !== "exit") return;
this.#launcherExitCode = event.code;
this.#options.onDiagnostic?.({
type: "launcher-exit",
code: event.code,
});
launch.process.on("exit", (code) => {
this.#launcherExitCode = code;
this.#options.onDiagnostic?.({ type: "launcher-exit", code });
if (launch.ownsProcessLifetime && !this.#closing) {
this.#failAll(new HopperProcessError(code));
}
});
if (launch.ownsProcessLifetime && !this.#closing)
this.#failAll(new HopperProcessError(event.code));
}
#onData(chunk: string): void {
@@ -426,7 +497,7 @@ export class HopperClient {
}
return;
}
this.#settle(parsed.value.id, responseResult(parsed.value));
this.#pending.settle(parsed.value.id, responseResult(parsed.value));
}
#abortProtocol(message: string, cause?: Error): void {
@@ -434,90 +505,24 @@ export class HopperClient {
this.#socket?.destroy();
}
#settle(id: number, result: Result<JsonValue, HopperError>): void {
const pending = this.#pending.get(id);
if (pending === undefined) return;
this.#pending.delete(id);
clearTimeout(pending.timer);
if (pending.signal !== undefined && pending.onAbort !== undefined) {
pending.signal.removeEventListener("abort", pending.onAbort);
}
pending.resolve(result);
}
#abandon(id: number, result: Result<JsonValue, HopperError>): void {
if (!this.#pending.has(id)) return;
this.#settle(id, result);
}
#failAll(error: HopperError): void {
for (const id of this.#pending.keys()) this.#settle(id, err(error));
this.#pending.failAll(() => err(error));
}
}
const isAborted = (signal?: AbortSignal): boolean => signal?.aborted === true;
const waitForDelay = (
milliseconds: number,
signal?: AbortSignal,
): Promise<boolean> => {
if (signal?.aborted === true) return Promise.resolve(false);
return new Promise((resolve) => {
const timer = setTimeout(() => {
signal?.removeEventListener("abort", onAbort);
resolve(true);
}, milliseconds);
const onAbort = (): void => {
clearTimeout(timer);
resolve(false);
};
signal?.addEventListener("abort", onAbort, { once: true });
});
};
const startupInterruption = (
deadline: ProviderStartupDeadline,
): HopperCancelledError | HopperTimeoutError =>
deadline.cancelled
? new HopperCancelledError()
: new HopperTimeoutError(deadline.timeoutMs);
const connectOnce = async (
socketPath: string,
): Promise<Result<Socket, HopperStartError>> =>
new Promise((resolve) => {
const socket = createConnection(socketPath);
socket.once("connect", () => {
resolve(ok(socket));
});
socket.once("error", (cause: Error) => {
socket.destroy();
resolve(err(new HopperStartError({ cause })));
});
});
const isShutdownAcknowledgement = (value: JsonValue): boolean => {
if (typeof value !== "object" || value === null || Array.isArray(value))
return false;
if (value.shutdown !== true) return false;
if (value.analysis_stopped === true && value.document_closed === true)
return true;
return false;
};
const isCleanupRequired = (value: JsonValue): boolean =>
typeof value === "object" &&
value !== null &&
!Array.isArray(value) &&
value.shutdown === true &&
value.cleanup_required === true;
const parseServerInfo = (
value: JsonValue,
expectedRunId: string,
): Result<HopperServerInfo, HopperProtocolError> => {
if (
typeof value === "object" &&
value !== null &&
!Array.isArray(value) &&
value.name === "REA Hopper bridge" &&
typeof value.version === "string" &&
value.run_id === expectedRunId
) {
return ok({ name: value.name, version: value.version });
}
return err(new HopperProtocolError("Hopper bridge health result is invalid"));
};
const providerCleanupFailure = (cause: unknown): ProcessCleanupResult => ({
cleaned: false,
reason:
cause instanceof Error
? `owned provider cleanup failed: ${cause.message}`
: "owned provider cleanup failed",
});
+42
View File
@@ -0,0 +1,42 @@
import { HopperProtocolError } from "../domain/errors.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
/** Authenticated identity returned by the Hopper bridge health handshake. */
export interface HopperServerInfo {
readonly name: string;
readonly version: string;
}
/** Validate the bridge identity and exact per-launch run identifier. */
export const parseHopperServerInfo = (
value: JsonValue,
expectedRunId: string,
): Result<HopperServerInfo, HopperProtocolError> => {
if (
typeof value === "object" &&
value !== null &&
!Array.isArray(value) &&
value.name === "REA Hopper bridge" &&
typeof value.version === "string" &&
value.run_id === expectedRunId
)
return ok({ name: value.name, version: value.version });
return err(new HopperProtocolError("Hopper bridge health result is invalid"));
};
/** Require Hopper to confirm both analysis and document shutdown. */
export const isHopperShutdownAcknowledgement = (value: JsonValue): boolean => {
if (typeof value !== "object" || value === null || Array.isArray(value))
return false;
if (value.shutdown !== true) return false;
return value.analysis_stopped === true && value.document_closed === true;
};
/** Detect the verified Linux bridge response that requires group cleanup. */
export const isHopperCleanupRequired = (value: JsonValue): boolean =>
typeof value === "object" &&
value !== null &&
!Array.isArray(value) &&
value.shutdown === true &&
value.cleanup_required === true;
+36
View File
@@ -0,0 +1,36 @@
import { createConnection, type Socket } from "node:net";
import { HopperCancelledError, HopperStartError } from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
/** Open one abort-aware Hopper Unix-socket connection attempt. */
export const connectHopperSocketOnce = (
socketPath: string,
signal: AbortSignal,
): Promise<Result<Socket, HopperStartError | HopperCancelledError>> =>
new Promise((resolve) => {
const socket = createConnection(socketPath);
const detach = (): void => {
socket.off("connect", onConnect);
socket.off("error", onError);
signal.removeEventListener("abort", onAbort);
};
const onConnect = (): void => {
detach();
resolve(ok(socket));
};
const onError = (cause: Error): void => {
detach();
socket.destroy();
resolve(err(new HopperStartError({ cause })));
};
const onAbort = (): void => {
detach();
socket.destroy();
resolve(err(new HopperCancelledError()));
};
socket.once("connect", onConnect);
socket.once("error", onError);
signal.addEventListener("abort", onAbort, { once: true });
if (signal.aborted) onAbort();
});
+83
View File
@@ -0,0 +1,83 @@
/** Timeout and cancellation projections for one correlated operation. */
export interface PendingOperationOptions<Value> {
readonly timeoutMs: number;
readonly signal?: AbortSignal;
readonly timeoutValue: () => Value;
readonly cancelledValue: () => Value;
}
interface PendingOperation<Value> {
readonly resolve: (value: Value) => void;
readonly timer: NodeJS.Timeout;
readonly signal: AbortSignal | undefined;
readonly onAbort: (() => void) | undefined;
}
/**
* Correlates event-driven provider replies with bounded waits.
*
* The registry owns every request timer and abort listener. Settling, timing
* out, cancelling, or failing an operation removes both before resolution, so
* late protocol replies can be ignored without retaining request resources.
*/
export class PendingOperations<Key, Value> {
readonly #pending = new Map<Key, PendingOperation<Value>>();
/** Number of currently correlated operations. */
get size(): number {
return this.#pending.size;
}
/** Return whether an operation key is awaiting a protocol reply. */
has(key: Key): boolean {
return this.#pending.has(key);
}
/** Register one unique operation key and start its bounded wait. */
wait(key: Key, options: PendingOperationOptions<Value>): Promise<Value> {
if (this.#pending.has(key))
throw new Error("Pending operation key is already registered");
if (options.signal?.aborted === true)
return Promise.resolve(options.cancelledValue());
return new Promise((resolve) => {
const onAbort =
options.signal === undefined
? undefined
: () => this.#finish(key, options.cancelledValue());
const timer = setTimeout(
() => this.#finish(key, options.timeoutValue()),
options.timeoutMs,
);
this.#pending.set(key, {
resolve,
timer,
signal: options.signal,
onAbort,
});
if (onAbort !== undefined)
options.signal?.addEventListener("abort", onAbort, { once: true });
});
}
/** Settle one correlated reply; returns false for late or unknown keys. */
settle(key: Key, value: Value): boolean {
return this.#finish(key, value);
}
/** Fail every active operation while releasing all timers and listeners. */
failAll(valueFor: (key: Key) => Value): void {
for (const key of this.#pending.keys()) this.#finish(key, valueFor(key));
}
#finish(key: Key, value: Value): boolean {
const pending = this.#pending.get(key);
if (pending === undefined) return false;
this.#pending.delete(key);
clearTimeout(pending.timer);
if (pending.signal !== undefined && pending.onAbort !== undefined)
pending.signal.removeEventListener("abort", pending.onAbort);
pending.resolve(value);
return true;
}
}
+43
View File
@@ -0,0 +1,43 @@
import { chmod, mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
/** Filesystem coordinates for one provider-owned private runtime directory. */
export interface PrivateRuntimeRootOptions {
readonly parent?: string;
readonly prefix?: string;
}
/**
* Owns one mode-0700 temporary runtime root and removes it idempotently.
*
* Protocol adapters decide what belongs inside the directory; this primitive
* only establishes a private filesystem boundary and deterministic cleanup.
*/
export class PrivateRuntimeRoot {
#closePromise: Promise<void> | undefined;
private constructor(readonly path: string) {}
/** Allocate a new private runtime root without performing protocol work. */
static async create(
options: PrivateRuntimeRootOptions = {},
): Promise<PrivateRuntimeRoot> {
const path = await mkdtemp(
join(options.parent ?? tmpdir(), options.prefix ?? "rea-provider-"),
);
try {
await chmod(path, 0o700);
return new PrivateRuntimeRoot(path);
} catch (cause: unknown) {
await rm(path, { recursive: true, force: true });
throw cause;
}
}
/** Remove the runtime root; concurrent and repeated callers share cleanup. */
close(): Promise<void> {
this.#closePromise ??= rm(this.path, { recursive: true, force: true });
return this.#closePromise;
}
}
@@ -1,11 +1,10 @@
import { execFile } from "node:child_process";
import { readFile } from "node:fs/promises";
import { promisify } from "node:util";
import type { ProcessSample } from "../domain/processCapture.js";
const execFileAsync = promisify(execFile);
/** Identity proof required before REA may signal a captured process group. */
/** Identity proof required before REA may signal an owned process group. */
export interface OwnedProcessGroup {
readonly runId: string;
readonly leaderPid: number;
@@ -16,6 +15,7 @@ export interface OwnedProcessGroup {
readonly expectedParentPid?: number;
}
/** One operating-system observation of a process-group member. */
interface ProcessGroupMember {
readonly pid: number;
readonly parentPid: number;
@@ -26,12 +26,20 @@ interface ProcessGroupMember {
/** Narrow operating-system seam used to inspect and signal process groups. */
export interface ProcessOwnershipHost {
listMembers(processGroupId: number): Promise<readonly ProcessGroupMember[]>;
listMembers(processGroupId: number): Promise<
readonly {
readonly pid: number;
readonly parentPid: number;
readonly processGroupId: number;
readonly state: string;
readonly command: string;
}[]
>;
environment(pid: number): Promise<Readonly<Record<string, string>>>;
signalGroup(processGroupId: number, signal: NodeJS.Signals): void;
}
/** Cleanup succeeds only when the group is absent or every member is owned. */
/** Per-member reason that token-verified cleanup failed closed. */
interface ProcessOwnershipValidationFailure {
readonly pid: number;
readonly reason: "environment-unreadable" | "run-token-mismatch";
@@ -43,7 +51,10 @@ export type ProcessCleanupResult =
| {
readonly cleaned: false;
readonly reason: string;
readonly failures?: readonly ProcessOwnershipValidationFailure[];
readonly failures?: readonly {
readonly pid: number;
readonly reason: "environment-unreadable" | "run-token-mismatch";
}[];
};
/** Token-verified liveness result used by post-root-exit settlement. */
@@ -55,7 +66,10 @@ export type ProcessGroupObservation =
/** Select the PTY root group and groups led by an observed captured process. */
export const selectCapturedProcessGroupIds = (
rootPid: number,
samples: readonly Pick<ProcessSample, "pid" | "process_group_id">[],
samples: readonly {
readonly pid: number;
readonly process_group_id: number | null;
}[],
): readonly number[] => {
const processGroupIds = new Set<number>([rootPid]);
for (const sample of samples) {
+120
View File
@@ -0,0 +1,120 @@
/** Result of an abort-aware interval wait. */
export type AbortableWaitResult = "elapsed" | "aborted";
/** Wait for an interval while removing the supplied abort listener on settle. */
export const waitForAbortableDelay = (
milliseconds: number,
signal?: AbortSignal,
): Promise<AbortableWaitResult> => {
if (signal?.aborted === true) return Promise.resolve("aborted");
return new Promise((resolve) => {
const settle = (result: AbortableWaitResult): void => {
clearTimeout(timer);
signal?.removeEventListener("abort", onAbort);
resolve(result);
};
const onAbort = (): void => settle("aborted");
const timer = setTimeout(
() => settle("elapsed"),
Math.max(0, milliseconds),
);
signal?.addEventListener("abort", onAbort, { once: true });
});
};
/**
* One absolute deadline shared by every phase of a provider startup handshake.
*
* The deadline owns its timer and the listener attached to an optional caller
* signal. Adapters must dispose it after startup succeeds or fails.
*/
export class ProviderStartupDeadline {
readonly #controller = new AbortController();
readonly #deadlineAt: number;
readonly #externalSignal: AbortSignal | undefined;
readonly #onExternalAbort: () => void;
#timer: NodeJS.Timeout | undefined;
#timedOut = false;
#cancelled = false;
constructor(
readonly timeoutMs: number,
signal?: AbortSignal,
) {
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
throw new RangeError("Provider startup timeout must be positive");
this.#deadlineAt = Date.now() + timeoutMs;
this.#externalSignal = signal;
this.#onExternalAbort = () => {
if (this.#controller.signal.aborted) return;
if (Date.now() >= this.#deadlineAt) {
this.#timedOut = true;
this.#abort(
new DOMException("Provider startup deadline elapsed", "TimeoutError"),
);
return;
}
this.#cancelled = true;
this.#abort(signal?.reason);
};
if (signal?.aborted === true) {
this.#onExternalAbort();
return;
}
signal?.addEventListener("abort", this.#onExternalAbort, { once: true });
this.#timer = setTimeout(() => {
if (this.#controller.signal.aborted) return;
this.#timedOut = true;
this.#abort(
new DOMException("Provider startup deadline elapsed", "TimeoutError"),
);
}, timeoutMs);
}
/** Composite signal aborted by either the caller or the absolute deadline. */
get signal(): AbortSignal {
return this.#controller.signal;
}
/** True only when the external caller signal initiated cancellation. */
get cancelled(): boolean {
return this.#cancelled;
}
/** True when the absolute startup deadline has elapsed. */
get timedOut(): boolean {
return (
this.#timedOut || (!this.#cancelled && Date.now() >= this.#deadlineAt)
);
}
/** Milliseconds still available to the next startup phase. */
remainingMs(): number {
return Math.max(0, this.#deadlineAt - Date.now());
}
/** Wait for at most one polling interval under the shared deadline signal. */
wait(milliseconds: number): Promise<AbortableWaitResult> {
return waitForAbortableDelay(
Math.min(milliseconds, this.remainingMs()),
this.signal,
);
}
/** Release the deadline timer and external abort listener. */
dispose(): void {
this.#clearTimer();
this.#externalSignal?.removeEventListener("abort", this.#onExternalAbort);
}
#abort(reason: unknown): void {
this.#clearTimer();
this.#externalSignal?.removeEventListener("abort", this.#onExternalAbort);
this.#controller.abort(reason);
}
#clearTimer(): void {
if (this.#timer !== undefined) clearTimeout(this.#timer);
this.#timer = undefined;
}
}
+404
View File
@@ -0,0 +1,404 @@
import { spawn, type ChildProcess } from "node:child_process";
import type { Readable } from "node:stream";
import type {
OwnedProcessGroup,
ProcessCleanupResult,
} from "./ProcessOwnership.js";
const DEFAULT_OUTPUT_BYTES = 64 * 1024;
const DEFAULT_TERMINATION_GRACE_MS = 250;
const DEFAULT_KILL_GRACE_MS = 1_000;
/** Spawn coordinates shared by owned, long-lived provider processes. */
export interface OwnedProviderProcessSpawnOptions {
readonly command: string;
readonly arguments: readonly string[];
readonly runId: string;
readonly expectedCommand?: string;
readonly cwd?: string;
readonly env?: NodeJS.ProcessEnv;
}
/** Spawned process paired with the identity proof required for group cleanup. */
export interface SpawnedOwnedProviderProcess {
readonly process: ChildProcess;
readonly ownership: OwnedProcessGroup;
}
/** Process handle returned by a provider-specific launcher. */
export interface ProviderProcessLaunch {
readonly process: ChildProcess;
readonly ownsProcessLifetime: boolean;
readonly cleanup?: () => Promise<ProcessCleanupResult>;
}
/** Detached diagnostics captured for one supervised provider process. */
export interface ProviderProcessSnapshot {
readonly stdout: {
readonly text: string;
readonly bytes: number;
readonly retainedBytes: number;
readonly truncated: boolean;
};
readonly stderr: {
readonly text: string;
readonly bytes: number;
readonly retainedBytes: number;
readonly truncated: boolean;
};
readonly exitCode: number | null | undefined;
readonly signal: NodeJS.Signals | null | undefined;
}
/** Resource-safe events emitted without imposing provider protocol semantics. */
export type ProviderProcessDiagnostic =
| {
readonly type: "output";
readonly stream: "stdout" | "stderr";
readonly bytes: number;
readonly totalBytes: number;
readonly truncated: boolean;
}
| {
readonly type: "exit";
readonly code: number | null;
readonly signal: NodeJS.Signals | null;
readonly snapshot: ProviderProcessSnapshot;
}
| { readonly type: "error"; readonly message: string };
/** Options for bounded capture and lifecycle diagnostics. */
export interface ProviderProcessSupervisorOptions {
readonly maxOutputBytesPerStream?: number;
readonly onDiagnostic?: (event: ProviderProcessDiagnostic) => void;
}
/** Optional result of provider-specific cleanup performed before stop. */
export interface ProviderProcessStopOptions {
readonly cleanupResult?: ProcessCleanupResult;
readonly terminationGraceMs?: number;
readonly killGraceMs?: number;
}
/** Exact disposition of one owned process stop attempt. */
export type ProviderProcessStopResult =
| {
readonly status:
| "not-owned"
| "already-exited"
| "verified-cleanup"
| "terminated"
| "killed";
}
| { readonly status: "incomplete"; readonly reason: string };
/**
* Spawn a provider in a dedicated POSIX process group with an ownership token.
*
* The caller remains responsible for persisting any ownership manifest and for
* selecting provider-specific command arguments or environment values.
*/
export const spawnOwnedProviderProcess = async (
options: OwnedProviderProcessSpawnOptions,
): Promise<SpawnedOwnedProviderProcess> => {
const child = spawn(options.command, [...options.arguments], {
shell: false,
stdio: ["ignore", "pipe", "pipe"],
detached: process.platform !== "win32",
env: {
...process.env,
...options.env,
REA_PROCESS_RUN_ID: options.runId,
},
...(options.cwd === undefined ? {} : { cwd: options.cwd }),
});
await waitForSpawn(child);
const pid = child.pid;
if (pid === undefined) throw new Error("Provider launcher has no process ID");
const ownership: OwnedProcessGroup = {
runId: options.runId,
leaderPid: pid,
processGroupId: pid,
expectedCommand: options.expectedCommand ?? options.command,
expectedParentPid: process.pid,
};
return { process: child, ownership };
};
/**
* Supervises only generic process resources; wire protocol remains adapter-owned.
*
* Output retention is bounded per stream while byte totals remain exact. Stop
* first honors token-verified group cleanup when supplied, otherwise it uses a
* bounded TERM-to-KILL escalation for a directly owned child.
*/
export class ProviderProcessSupervisor {
readonly #options: ProviderProcessSupervisorOptions;
readonly #stdout: BoundedByteCapture;
readonly #stderr: BoundedByteCapture;
readonly #exit = deferred<{
readonly code: number | null;
readonly signal: NodeJS.Signals | null;
}>();
readonly #onStdout = (chunk: Buffer | string): void => {
this.#capture("stdout", this.#stdout, chunk);
};
readonly #onStderr = (chunk: Buffer | string): void => {
this.#capture("stderr", this.#stderr, chunk);
};
readonly #onExit = (
code: number | null,
signal: NodeJS.Signals | null,
): void => {
this.#recordExit(code, signal);
};
readonly #onClose = (
code: number | null,
signal: NodeJS.Signals | null,
): void => {
this.#recordExit(code, signal);
};
readonly #onError = (cause: Error): void => {
this.#options.onDiagnostic?.({ type: "error", message: cause.message });
};
#exitObservation:
| { readonly code: number | null; readonly signal: NodeJS.Signals | null }
| undefined;
#stopPromise: Promise<ProviderProcessStopResult> | undefined;
#disposed = false;
constructor(
readonly launch: ProviderProcessLaunch,
options: ProviderProcessSupervisorOptions = {},
) {
this.#options = options;
const limit = options.maxOutputBytesPerStream ?? DEFAULT_OUTPUT_BYTES;
if (!Number.isSafeInteger(limit) || limit <= 0)
throw new RangeError("Provider output limit must be a positive integer");
this.#stdout = new BoundedByteCapture(limit);
this.#stderr = new BoundedByteCapture(limit);
this.#attach(launch.process.stdout, "stdout");
this.#attach(launch.process.stderr, "stderr");
launch.process.once("exit", this.#onExit);
launch.process.once("close", this.#onClose);
launch.process.on("error", this.#onError);
if (launch.process.exitCode !== null || launch.process.signalCode !== null)
this.#recordExit(launch.process.exitCode, launch.process.signalCode);
}
/** Latest bounded output and exit observation. */
snapshot(): ProviderProcessSnapshot {
return {
stdout: this.#stdout.snapshot(),
stderr: this.#stderr.snapshot(),
exitCode: this.#exitObservation?.code,
signal: this.#exitObservation?.signal,
};
}
/** Wait for process exit up to a caller-owned bounded interval. */
async waitForExit(timeoutMs: number): Promise<boolean> {
if (this.#exitObservation !== undefined) return true;
let timer: NodeJS.Timeout | undefined;
try {
return await Promise.race([
this.#exit.promise.then(() => true),
new Promise<boolean>((resolve) => {
timer = setTimeout(() => resolve(false), Math.max(0, timeoutMs));
}),
]);
} finally {
if (timer !== undefined) clearTimeout(timer);
}
}
/** Stop an owned process once; concurrent callers share the same escalation. */
stop(
options: ProviderProcessStopOptions = {},
): Promise<ProviderProcessStopResult> {
this.#stopPromise ??= this.#stop(options);
return this.#stopPromise;
}
/** Detach capture and process listeners after an adapter releases ownership. */
dispose(): void {
if (this.#disposed) return;
this.#disposed = true;
this.launch.process.stdout?.off("data", this.#onStdout);
this.launch.process.stderr?.off("data", this.#onStderr);
this.launch.process.off("exit", this.#onExit);
this.launch.process.off("close", this.#onClose);
this.launch.process.off("error", this.#onError);
}
async #stop(
options: ProviderProcessStopOptions,
): Promise<ProviderProcessStopResult> {
try {
if (!this.launch.ownsProcessLifetime) return { status: "not-owned" };
if (this.launch.cleanup !== undefined) {
const cleanup = await this.#ownedCleanup(options.cleanupResult);
if (!cleanup.cleaned)
return { status: "incomplete", reason: cleanup.reason };
const graceMs = options.killGraceMs ?? DEFAULT_KILL_GRACE_MS;
if (await this.waitForExit(graceMs))
return { status: "verified-cleanup" };
const retried = await this.launch.cleanup();
if (!retried.cleaned)
return { status: "incomplete", reason: retried.reason };
if (await this.waitForExit(graceMs))
return { status: "verified-cleanup" };
return {
status: "incomplete",
reason: "verified process-group cleanup did not stop the launcher",
};
}
if (this.#exitObservation !== undefined)
return { status: "already-exited" };
this.#signal("SIGTERM");
if (
await this.waitForExit(
options.terminationGraceMs ?? DEFAULT_TERMINATION_GRACE_MS,
)
)
return { status: "terminated" };
this.#signal("SIGKILL");
if (await this.waitForExit(options.killGraceMs ?? DEFAULT_KILL_GRACE_MS))
return { status: "killed" };
return {
status: "incomplete",
reason: "owned provider process did not exit after SIGKILL",
};
} catch (cause: unknown) {
return {
status: "incomplete",
reason:
cause instanceof Error
? cause.message
: "owned provider process cleanup failed",
};
} finally {
this.dispose();
}
}
#ownedCleanup(
supplied: ProcessCleanupResult | undefined,
): Promise<ProcessCleanupResult> {
if (supplied !== undefined) return Promise.resolve(supplied);
const cleanup = this.launch.cleanup;
return cleanup === undefined
? Promise.resolve({
cleaned: false,
reason: "owned provider process has no cleanup capability",
})
: cleanup();
}
#signal(signal: NodeJS.Signals): void {
if (this.#exitObservation !== undefined) return;
this.launch.process.kill(signal);
}
#attach(stream: Readable | null, name: "stdout" | "stderr"): void {
if (name === "stdout") stream?.on("data", this.#onStdout);
else stream?.on("data", this.#onStderr);
}
#capture(
stream: "stdout" | "stderr",
capture: BoundedByteCapture,
chunk: Buffer | string,
): void {
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
capture.append(bytes);
this.#options.onDiagnostic?.({
type: "output",
stream,
bytes: bytes.byteLength,
totalBytes: capture.bytes,
truncated: capture.truncated,
});
}
#recordExit(code: number | null, signal: NodeJS.Signals | null): void {
if (this.#exitObservation !== undefined) return;
this.#exitObservation = { code, signal };
this.#exit.resolve(this.#exitObservation);
this.#options.onDiagnostic?.({
type: "exit",
code,
signal,
snapshot: this.snapshot(),
});
}
}
class BoundedByteCapture {
readonly #chunks: Buffer[] = [];
#bytes = 0;
#retainedBytes = 0;
constructor(readonly limit: number) {}
get bytes(): number {
return this.#bytes;
}
get truncated(): boolean {
return this.#bytes > this.#retainedBytes;
}
append(chunk: Buffer): void {
this.#bytes += chunk.byteLength;
const remaining = this.limit - this.#retainedBytes;
if (remaining <= 0) return;
const retained = Buffer.from(chunk.subarray(0, remaining));
this.#chunks.push(retained);
this.#retainedBytes += retained.byteLength;
}
snapshot(): ProviderProcessSnapshot["stdout"] {
return {
text: Buffer.concat(this.#chunks, this.#retainedBytes).toString("utf8"),
bytes: this.#bytes,
retainedBytes: this.#retainedBytes,
truncated: this.truncated,
};
}
}
interface Deferred<Value> {
readonly promise: Promise<Value>;
readonly resolve: (value: Value) => void;
}
const deferred = <Value>(): Deferred<Value> => {
let resolver: ((value: Value) => void) | undefined;
const promise = new Promise<Value>((resolve) => {
resolver = resolve;
});
return {
promise,
resolve: (value) => {
resolver?.(value);
},
};
};
const waitForSpawn = (child: ChildProcess): Promise<void> =>
new Promise((resolve, reject) => {
const onSpawn = (): void => {
child.off("error", onError);
resolve();
};
const onError = (cause: Error): void => {
child.off("spawn", onSpawn);
reject(cause);
};
child.once("spawn", onSpawn);
child.once("error", onError);
});