fix(hopper): add bounded analysis recovery

This commit is contained in:
N0zoM1z0
2026-07-24 00:33:29 +09:00
committed by N0zoM1z0
parent 161377a505
commit e0bc7fd973
68 changed files with 1750 additions and 368 deletions
+265
View File
@@ -0,0 +1,265 @@
import type { Socket } from "node:net";
import type { ProgressReporter } from "../application/ProgressReporter.js";
import type { AnalysisError, HopperError } from "../domain/errors.js";
import { HopperProcessError } from "../domain/errors.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { err, ok, type Result } from "../domain/result.js";
import type { Logger } from "../logger.js";
import type { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
import type { ProcessCleanupResult } from "../process/ProcessOwnership.js";
import type { ProviderProcessSupervisor } from "../process/ProviderProcess.js";
import type { BridgeLaunch } from "./BridgeLauncher.js";
import {
createOwnedHopperShutdownDiagnostic,
type HopperDiagnostic,
providerCleanupFailure,
} from "./HopperDiagnostics.js";
import type { HopperRequestActivity } from "./HopperRequestQueue.js";
import {
isHopperCleanupRequired,
isHopperShutdownAcknowledgement,
} from "./HopperSessionValues.js";
interface CleanupIssue {
readonly resource: string;
readonly reason: string;
}
interface CleanupState {
readonly issues: CleanupIssue[];
readonly resources: Set<string>;
cleanupResult: ProcessCleanupResult | undefined;
shutdownConfirmed: boolean;
ownedProcessStopped: boolean;
}
export interface HopperCleanupInput {
readonly socket: Socket | undefined;
readonly launch: BridgeLaunch | undefined;
readonly processSupervisor: ProviderProcessSupervisor | undefined;
readonly runtimeRoot: PrivateRuntimeRoot | undefined;
readonly activeRequest: HopperRequestActivity | null;
readonly progress: ProgressReporter | undefined;
readonly logger: Logger;
readonly onDiagnostic: ((event: HopperDiagnostic) => void) | undefined;
request(
method: "shutdown" | "shutdown_document",
): Promise<Result<JsonValue, HopperError>>;
releaseTransport(socket: Socket | undefined): void;
}
/** Close Hopper phases and retain every resource whose cleanup is unverified. */
export const cleanupHopperSession = async (
input: HopperCleanupInput,
): Promise<Result<null, AnalysisError>> => {
const state: CleanupState = {
issues: [],
resources: new Set(),
cleanupResult: undefined,
shutdownConfirmed: false,
ownedProcessStopped: false,
};
await report(input.progress, 0, "requesting Hopper document shutdown");
await requestShutdown(input, state);
await report(input.progress, 0.35, "releasing Hopper bridge transport");
input.releaseTransport(input.socket);
await stopProcess(input, state);
recordUnconfirmedDocument(input, state);
await report(input.progress, 0.75, "removing Hopper private runtime files");
await closeRuntimeRoot(input.runtimeRoot, state);
return cleanupOutcome(input, state);
};
const requestShutdown = async (
input: HopperCleanupInput,
state: CleanupState,
): Promise<void> => {
if (
input.socket === undefined ||
input.socket.destroyed ||
input.activeRequest !== null
) {
if (input.activeRequest !== null)
input.logger.warn(
{
method: input.activeRequest.operation,
callerState: input.activeRequest.callerState,
},
"Hopper shutdown skipped because a bridge operation remained active",
);
return;
}
const shutdown = await input
.request("shutdown")
.catch(() => err(new HopperProcessError(null)));
if (
shutdown.ok &&
isHopperCleanupRequired(shutdown.value) &&
input.launch?.shutdownByCleanup === true &&
input.launch.cleanup !== undefined
) {
state.cleanupResult = await input.launch
.cleanup()
.catch(providerCleanupFailure);
if (!state.cleanupResult.cleaned) {
state.shutdownConfirmed = await fallbackDocumentShutdown(input);
state.cleanupResult = await input.launch
.cleanup()
.catch(providerCleanupFailure);
}
} else if (shutdown.ok) {
state.shutdownConfirmed = isHopperShutdownAcknowledgement(shutdown.value);
}
if (
!shutdown.ok ||
(!state.shutdownConfirmed && state.cleanupResult === undefined)
)
input.logger.warn(
{ status: shutdown.ok ? "invalid-acknowledgement" : "failed" },
"Hopper document shutdown was not confirmed",
);
};
const fallbackDocumentShutdown = async (
input: HopperCleanupInput,
): Promise<boolean> => {
const fallback = await input
.request("shutdown_document")
.catch(() => err(new HopperProcessError(null)));
const confirmed =
fallback.ok && isHopperShutdownAcknowledgement(fallback.value);
if (!confirmed)
input.logger.warn(
{ status: fallback.ok ? "invalid-acknowledgement" : "failed" },
"Hopper document shutdown fallback was not confirmed",
);
return confirmed;
};
const stopProcess = async (
input: HopperCleanupInput,
state: CleanupState,
): Promise<void> => {
const supervisor = input.processSupervisor;
if (supervisor === undefined) return;
const stopped = await supervisor.stop(
state.cleanupResult === undefined
? {}
: { cleanupResult: state.cleanupResult },
);
const diagnostic = createOwnedHopperShutdownDiagnostic(
supervisor.launch,
stopped,
state.cleanupResult,
);
try {
input.onDiagnostic?.(diagnostic);
} catch {
// Diagnostic consumers cannot change the already-observed cleanup result.
}
input.logger.info(diagnostic, "Owned Hopper launcher shutdown completed");
if (stopped.status !== "incomplete") {
state.ownedProcessStopped = stopped.status !== "not-owned";
return;
}
const processGroupId = supervisor.launch.ownership?.processGroupId;
const resource =
processGroupId === undefined
? "hopper-process"
: `process-group:${String(processGroupId)}`;
state.resources.add(resource);
state.issues.push({ resource, reason: stopped.reason });
input.logger.warn(
{ reason: stopped.reason },
"Owned launcher cleanup failed closed",
);
};
const recordUnconfirmedDocument = (
input: HopperCleanupInput,
state: CleanupState,
): void => {
if (
(input.socket === undefined && input.launch === undefined) ||
state.shutdownConfirmed ||
state.ownedProcessStopped
)
return;
state.resources.add("hopper-document");
state.issues.push({
resource: "hopper-document",
reason:
input.activeRequest === null
? "authenticated shutdown acknowledgement was not observed"
: `bridge operation ${input.activeRequest.operation} remained active after caller ${input.activeRequest.callerState}`,
});
};
const closeRuntimeRoot = async (
runtimeRoot: PrivateRuntimeRoot | undefined,
state: CleanupState,
): Promise<void> => {
try {
await runtimeRoot?.close();
} catch (cause: unknown) {
const resource = runtimeRoot?.path ?? "hopper-runtime-root";
state.resources.add(resource);
state.issues.push({
resource,
reason:
cause instanceof Error
? cause.message
: "private runtime root cleanup failed",
});
}
};
const cleanupOutcome = (
input: HopperCleanupInput,
state: CleanupState,
): Result<null, AnalysisError> => {
if (state.issues.length === 0) return ok(null);
return err(
new ProviderCleanupError("hopper", [...state.resources], {
issues: cleanupIssueDetails(state.issues),
...(input.runtimeRoot === undefined
? {}
: { runtime_root: input.runtimeRoot.path }),
...(input.activeRequest === null
? {}
: { active_request: activityDetails(input.activeRequest) }),
}),
);
};
const cleanupIssueDetails = (issues: readonly CleanupIssue[]): JsonValue =>
issues.map((issue) => ({
resource: issue.resource,
reason: issue.reason,
}));
const activityDetails = (activity: HopperRequestActivity): JsonValue => ({
request_id: activity.requestId,
operation: activity.operation,
elapsed_ms: activity.elapsedMs,
timeout_ms: activity.timeoutMs,
caller_state: activity.callerState,
queued_requests: activity.queuedRequests,
});
const report = async (
progress: ProgressReporter | undefined,
completed: number,
message: string,
): Promise<void> => {
await progress
?.report({
phase: "hopper_cleanup",
completed,
total: 1,
message,
})
.catch(() => undefined);
};
+86 -140
View File
@@ -6,6 +6,7 @@ import { join } from "node:path";
import {
HopperCancelledError,
type AnalysisError,
type HopperError,
HopperProcessError,
HopperProtocolError,
@@ -16,36 +17,35 @@ import {
} from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { ProgressReporter } from "../application/ProgressReporter.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 { ProviderRunLineage } from "../process/ProviderRunLineage.js";
import {
type ProviderProcessDiagnostic,
ProviderProcessSupervisor,
} from "../process/ProviderProcess.js";
import type { BridgeLaunch, BridgeLauncher } from "./BridgeLauncher.js";
import type { HopperDiagnostic } from "./HopperDiagnostics.js";
import { cleanupHopperSession } from "./HopperCleanup.js";
import {
createOwnedHopperShutdownDiagnostic,
type HopperDiagnostic,
providerCleanupFailure,
} from "./HopperDiagnostics.js";
import {
isHopperCleanupRequired,
isHopperShutdownAcknowledgement,
parseHopperServerInfo,
type HopperServerInfo,
} from "./HopperSessionValues.js";
import { connectHopperSocketOnce } from "./HopperSocketConnection.js";
import { hopperLauncherFailureDiagnostic } from "./HopperProcessDiagnostic.js";
import { parseResponseLine, responseResult } from "./protocol.js";
import {
HopperRequestQueue,
type HopperRequestActivity,
} from "./HopperRequestQueue.js";
import { HopperResponseStream } from "./HopperResponseStream.js";
import { responseResult } from "./protocol.js";
export type { HopperServerInfo } from "./HopperSessionValues.js";
const MAX_LINE_BYTES = 10 * 1024 * 1024;
const SHUTDOWN_TIMEOUT_MS = 30_000;
const MAX_QUEUED_REQUESTS = 64;
const SESSION_ROOT = process.platform === "darwin" ? "/tmp" : tmpdir();
/** Dependencies, deadlines, and redacted diagnostics for one bridge client. */
@@ -72,10 +72,8 @@ export class HopperClient {
Pick<HopperClientOptions, "requestTimeoutMs" | "startupTimeoutMs">
> &
HopperClientOptions;
readonly #pending = new PendingOperations<
number,
Result<JsonValue, HopperError>
>();
readonly #requests: HopperRequestQueue;
readonly #responses: HopperResponseStream;
readonly #logger: Logger;
#socket: Socket | undefined;
#launch: BridgeLaunch | undefined;
@@ -84,15 +82,14 @@ export class HopperClient {
#token: string | undefined;
readonly #lineage = new ProviderRunLineage();
#nextId = 1;
#buffer = "";
#closing = false;
#launcherExitCode: number | null | undefined;
#launcherFailureDiagnostic: HopperStartupDiagnostic | undefined;
#startupController: AbortController | undefined;
#startPromise: Promise<Result<HopperServerInfo, HopperError>> | undefined;
#closePromise: Promise<void> | undefined;
#closePromise: Promise<Result<null, AnalysisError>> | undefined;
readonly #onSocketData = (chunk: string): void => {
this.#onData(chunk);
this.#responses.push(chunk);
};
readonly #onSocketError = (): void => {
this.#failAll(new HopperProcessError(null));
@@ -108,6 +105,30 @@ export class HopperClient {
requestTimeoutMs: options.requestTimeoutMs ?? 30_000,
startupTimeoutMs: options.startupTimeoutMs ?? 120_000,
};
this.#requests = new HopperRequestQueue(
MAX_QUEUED_REQUESTS,
({ id, method, params }, failed) => {
const socket = this.#socket;
const token = this.#token;
if (socket === undefined || socket.destroyed || token === undefined) {
failed();
return;
}
socket.write(
`${JSON.stringify({ id, token, method, params })}\n`,
(cause) => {
if (cause !== undefined && cause !== null) failed();
},
);
},
);
this.#responses = new HopperResponseStream({
accept: (response) =>
this.#requests.accept(response.id, responseResult(response)),
hasQueued: (id) => this.#requests.hasQueued(id),
nextRequestId: () => this.#nextId,
abort: (message, cause) => this.#abortProtocol(message, cause),
});
}
/** Latest token-verified launcher lineage for the active run. */
@@ -115,6 +136,11 @@ export class HopperClient {
return this.#lineage.snapshot();
}
/** Observe a request that still occupies Hopper after caller timeout/cancel. */
requestActivity(): HopperRequestActivity | null {
return this.#requests.activity();
}
/** Launch the bridge once and complete its authenticated health handshake. */
start(signal?: AbortSignal): Promise<Result<HopperServerInfo, HopperError>> {
if (this.#closePromise !== undefined) {
@@ -251,6 +277,7 @@ export class HopperClient {
options: {
readonly signal?: AbortSignal;
readonly timeoutMs?: number;
readonly progress?: ProgressReporter;
} = {},
): Promise<Result<JsonValue, HopperError>> {
const started = await this.start(options.signal);
@@ -260,11 +287,18 @@ export class HopperClient {
/** Stop the bridge, settle outstanding requests, and remove session artifacts. */
close(): Promise<void> {
return this.closeWithOutcome().then(() => undefined);
}
/** Stop the bridge and report whether every owned resource was verified clean. */
closeWithOutcome(
options: { readonly progress?: ProgressReporter } = {},
): Promise<Result<null, AnalysisError>> {
const starting = this.#startPromise;
const controller = this.#startupController;
controller?.abort();
this.#closePromise ??= Promise.resolve().then(() =>
this.#close(starting, controller),
this.#close(starting, controller, options),
);
return this.#closePromise;
}
@@ -272,10 +306,11 @@ export class HopperClient {
async #close(
starting: Promise<Result<HopperServerInfo, HopperError>> | undefined,
controller: AbortController | undefined,
): Promise<void> {
options: { readonly progress?: ProgressReporter },
): Promise<Result<null, AnalysisError>> {
try {
await starting?.catch(() => undefined);
await this.#cleanup();
return await this.#cleanup(options);
} finally {
if (this.#startPromise === starting) this.#startPromise = undefined;
if (this.#startupController === controller) {
@@ -285,92 +320,41 @@ export class HopperClient {
}
}
async #cleanup(): Promise<void> {
async #cleanup(
options: { readonly progress?: ProgressReporter } = {},
): Promise<Result<null, AnalysisError>> {
this.#closing = true;
try {
const socket = this.#socket;
let cleanupResult: ProcessCleanupResult | undefined;
if (socket !== undefined && !socket.destroyed) {
const shutdown = await this.#request(
"shutdown",
{},
{ timeoutMs: SHUTDOWN_TIMEOUT_MS },
).catch(() => err(new HopperProcessError(null)));
if (
shutdown.ok &&
isHopperCleanupRequired(shutdown.value) &&
this.#launch?.shutdownByCleanup === true &&
this.#launch.cleanup !== undefined
) {
cleanupResult = await this.#launch
.cleanup()
.catch(providerCleanupFailure);
if (!cleanupResult.cleaned) {
await this.#fallbackDocumentShutdown();
cleanupResult = await this.#launch
.cleanup()
.catch(providerCleanupFailure);
}
} 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();
return await cleanupHopperSession({
socket: this.#socket,
launch: this.#launch,
processSupervisor: this.#process,
runtimeRoot: this.#runtimeRoot,
activeRequest: this.#requests.activity(),
progress: options.progress,
logger: this.#logger,
onDiagnostic: this.#options.onDiagnostic,
request: (method) =>
this.#request(method, {}, { timeoutMs: SHUTDOWN_TIMEOUT_MS }),
releaseTransport: (socket) => {
this.#failAll(new HopperProcessError(null));
if (socket !== undefined) this.#detachSocket(socket);
socket?.destroy();
},
});
} finally {
this.#socket = undefined;
if (this.#process !== undefined) {
const stopped = await this.#process.stop(
cleanupResult === undefined ? {} : { cleanupResult },
);
const diagnostic = createOwnedHopperShutdownDiagnostic(
this.#process.launch,
stopped,
cleanupResult,
);
this.#options.onDiagnostic?.(diagnostic);
this.#logger.info(
diagnostic,
"Owned Hopper launcher shutdown completed",
);
if (stopped.status === "incomplete")
this.#logger.warn(
{ reason: stopped.reason },
"Owned launcher cleanup failed closed",
);
}
this.#process = undefined;
this.#launch = undefined;
const runtimeRoot = this.#runtimeRoot;
this.#runtimeRoot = undefined;
await runtimeRoot?.close();
this.#token = undefined;
this.#buffer = "";
this.#responses.reset();
this.#launcherExitCode = undefined;
this.#launcherFailureDiagnostic = undefined;
} finally {
this.#closing = false;
}
}
async #fallbackDocumentShutdown(): Promise<void> {
const fallback = await this.#request(
"shutdown_document",
{},
{ timeoutMs: SHUTDOWN_TIMEOUT_MS },
).catch(() => err(new HopperProcessError(null)));
if (!fallback.ok || !isHopperShutdownAcknowledgement(fallback.value))
this.#logger.warn(
{ status: fallback.ok ? "invalid-acknowledgement" : "failed" },
"Hopper document shutdown fallback was not confirmed",
);
}
async #connect(
socketPath: string,
deadline: ProviderStartupDeadline,
@@ -413,7 +397,11 @@ export class HopperClient {
async #request(
method: string,
params: JsonValue,
options: { readonly signal?: AbortSignal; readonly timeoutMs?: number },
options: {
readonly signal?: AbortSignal;
readonly timeoutMs?: number;
readonly progress?: ProgressReporter;
},
): Promise<Result<JsonValue, HopperError>> {
const socket = this.#socket;
const token = this.#token;
@@ -425,20 +413,11 @@ export class HopperClient {
const id = this.#nextId++;
const startedAt = performance.now();
const timeoutMs = options.timeoutMs ?? this.#options.requestTimeoutMs;
const response = this.#pending.wait(id, {
const result = await this.#requests.run(id, method, params, {
timeoutMs,
...(options.signal === undefined ? {} : { signal: options.signal }),
timeoutValue: () => err(new HopperTimeoutError(timeoutMs)),
cancelledValue: () => err(new HopperCancelledError()),
...(options.progress !== undefined ? { progress: options.progress } : {}),
});
socket.write(
`${JSON.stringify({ id, token, method, params })}\n`,
(cause) => {
if (cause !== undefined && cause !== null)
this.#pending.settle(id, err(new HopperProcessError(null)));
},
);
const result = await response;
this.#logger[result.ok ? "debug" : "warn"](
{
method,
@@ -501,46 +480,13 @@ export class HopperClient {
);
}
#onData(chunk: string): void {
this.#buffer += chunk;
let newline = this.#buffer.indexOf("\n");
while (newline >= 0) {
const line = this.#buffer.slice(0, newline).trim();
this.#buffer = this.#buffer.slice(newline + 1);
if (Buffer.byteLength(line) > MAX_LINE_BYTES) {
this.#abortProtocol("Hopper response exceeded the maximum line size");
return;
}
if (line.length > 0) this.#onLine(line);
newline = this.#buffer.indexOf("\n");
}
if (Buffer.byteLength(this.#buffer) > MAX_LINE_BYTES) {
this.#abortProtocol("Hopper response exceeded the maximum line size");
}
}
#onLine(line: string): void {
const parsed = parseResponseLine(line);
if (!parsed.ok) {
this.#abortProtocol(parsed.error.message, parsed.error);
return;
}
if (!this.#pending.has(parsed.value.id)) {
if (parsed.value.id >= this.#nextId) {
this.#abortProtocol("Hopper returned an unknown response id");
}
return;
}
this.#pending.settle(parsed.value.id, responseResult(parsed.value));
}
#abortProtocol(message: string, cause?: Error): void {
this.#failAll(new HopperProtocolError(message, { cause }));
this.#socket?.destroy();
}
#failAll(error: HopperError): void {
this.#pending.failAll(() => err(error));
this.#requests.failAll(error);
}
}
+20
View File
@@ -255,6 +255,26 @@ export class HopperProvider implements AnalysisProviderCandidate {
? []
: [{ provider: executionProvider, observation }];
},
requestActivitySnapshots: () => {
const activity = client.requestActivity();
return [
{
provider: executionProvider,
active:
activity === null
? null
: {
requestId: activity.requestId,
operation: activity.operation,
elapsedMs: activity.elapsedMs,
timeoutMs: activity.timeoutMs,
callerState: activity.callerState,
},
queuedRequests: activity?.queuedRequests ?? 0,
},
];
},
closeWithOutcome: (options) => client.closeWithOutcome(options),
close: () => client.close(),
};
}
+279
View File
@@ -0,0 +1,279 @@
import { performance } from "node:perf_hooks";
import type { ProgressReporter } from "../application/ProgressReporter.js";
import {
HopperCancelledError,
type HopperError,
HopperProcessError,
HopperProtocolError,
HopperTimeoutError,
} from "../domain/errors.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { err, type Result } from "../domain/result.js";
export type HopperRequestResult = Result<JsonValue, HopperError>;
export interface HopperRequestQueueOptions {
readonly signal?: AbortSignal;
readonly timeoutMs: number;
readonly progress?: ProgressReporter;
}
export interface HopperRequestActivity {
readonly requestId: number;
readonly operation: string;
readonly elapsedMs: number;
readonly timeoutMs: number;
readonly callerState: "waiting" | "timed_out" | "cancelled";
readonly queuedRequests: number;
}
type RequestSender = (
request: {
readonly id: number;
readonly method: string;
readonly params: JsonValue;
},
failed: () => void,
) => void;
interface QueuedRequest {
readonly id: number;
readonly method: string;
readonly params: JsonValue;
readonly signal: AbortSignal | undefined;
readonly timeoutMs: number;
readonly deadline: number;
readonly progress: ProgressReporter | undefined;
readonly resolve: (result: HopperRequestResult) => void;
readonly timer: NodeJS.Timeout;
readonly onAbort: (() => void) | undefined;
callerState: "waiting" | "timed_out" | "cancelled";
callerSettled: boolean;
startedAt: number | undefined;
heartbeat: NodeJS.Timeout | undefined;
}
/** Bounded FIFO that keeps the wire serialized until Hopper actually replies. */
export class HopperRequestQueue {
readonly #queue: QueuedRequest[] = [];
#active: QueuedRequest | undefined;
constructor(
private readonly maximum: number,
private readonly send: RequestSender,
) {}
/** Queue one request, counting queue wait against its caller deadline. */
run(
id: number,
method: string,
params: JsonValue,
options: HopperRequestQueueOptions,
): Promise<HopperRequestResult> {
if (options.signal?.aborted === true)
return Promise.resolve(err(new HopperCancelledError()));
if (options.timeoutMs <= 0)
return Promise.resolve(err(new HopperTimeoutError(options.timeoutMs)));
if (this.#size() >= this.maximum)
return Promise.resolve(
err(
new HopperProtocolError(
`Hopper serial request queue reached its ${String(this.maximum)}-request limit`,
),
),
);
return new Promise((resolve) => {
let entry: QueuedRequest;
const onAbort =
options.signal === undefined ? undefined : () => this.#cancel(entry);
const timer = setTimeout(() => this.#timeout(entry), options.timeoutMs);
entry = {
id,
method,
params,
signal: options.signal,
timeoutMs: options.timeoutMs,
deadline: performance.now() + options.timeoutMs,
progress: options.progress,
resolve,
timer,
onAbort,
callerState: "waiting",
callerSettled: false,
startedAt: undefined,
heartbeat: undefined,
};
this.#queue.push(entry);
if (onAbort !== undefined)
options.signal?.addEventListener("abort", onAbort, { once: true });
if (this.#active !== undefined || this.#queue.length > 1)
this.#report(
entry,
`${method} queued behind ${String(this.#size() - 1)} Hopper request(s)`,
);
this.#drain();
});
}
/** Settle the active wire request. False identifies an unexpected response id. */
accept(id: number, result: HopperRequestResult): boolean {
const entry = this.#active;
if (entry === undefined || entry.id !== id) return false;
this.#releaseWire(entry);
if (!entry.callerSettled) this.#settleCaller(entry, result, "waiting");
this.#active = undefined;
this.#drain();
return true;
}
/** Fail the active wire request and every request still waiting in the FIFO. */
failAll(error: HopperError): void {
const active = this.#active;
this.#active = undefined;
if (active !== undefined) {
this.#releaseWire(active);
if (!active.callerSettled)
this.#settleCaller(active, err(error), "waiting");
}
for (const entry of this.#queue.splice(0))
this.#settleCaller(entry, err(error), "waiting");
}
/** Snapshot the one request still occupying Hopper's serial Python thread. */
activity(): HopperRequestActivity | null {
const active = this.#active;
if (active === undefined || active.startedAt === undefined) return null;
return {
requestId: active.id,
operation: active.method,
elapsedMs: Math.max(0, Math.round(performance.now() - active.startedAt)),
timeoutMs: active.timeoutMs,
callerState: active.callerState,
queuedRequests: this.#queue.length,
};
}
/** Return whether an id belongs to a request that has not crossed the wire. */
hasQueued(id: number): boolean {
return this.#queue.some((entry) => entry.id === id);
}
/** Number of caller requests waiting behind the active bridge operation. */
queuedCount(): number {
return this.#queue.length;
}
#size(): number {
return this.#queue.length + (this.#active === undefined ? 0 : 1);
}
#drain(): void {
if (this.#active !== undefined) return;
const entry = this.#queue.shift();
if (entry === undefined) return;
const remaining = entry.deadline - performance.now();
if (entry.signal?.aborted === true || remaining <= 0) {
this.#settleCaller(
entry,
entry.signal?.aborted === true
? err(new HopperCancelledError())
: err(new HopperTimeoutError(entry.timeoutMs)),
entry.signal?.aborted === true ? "cancelled" : "timed_out",
);
this.#drain();
return;
}
this.#active = entry;
entry.startedAt = performance.now();
this.#report(entry, `${entry.method} started on Hopper's serial bridge`);
entry.heartbeat = setInterval(() => {
if (entry.callerSettled || entry.startedAt === undefined) return;
const elapsed = Math.round(performance.now() - entry.startedAt);
this.#report(
entry,
`${entry.method} is still running in Hopper (${String(elapsed)} ms elapsed)`,
);
}, 1_000);
try {
this.send(
{ id: entry.id, method: entry.method, params: entry.params },
() => this.accept(entry.id, err(new HopperProcessError(null))),
);
} catch (cause: unknown) {
this.accept(
entry.id,
err(new HopperProtocolError("Hopper socket write failed", { cause })),
);
}
}
#timeout(entry: QueuedRequest): void {
if (entry.callerSettled) return;
if (this.#active === entry) {
this.#settleCaller(
entry,
err(new HopperTimeoutError(entry.timeoutMs)),
"timed_out",
);
return;
}
const index = this.#queue.indexOf(entry);
if (index < 0) return;
this.#queue.splice(index, 1);
this.#settleCaller(
entry,
err(new HopperTimeoutError(entry.timeoutMs)),
"timed_out",
);
}
#cancel(entry: QueuedRequest): void {
if (entry.callerSettled) return;
if (this.#active === entry) {
this.#settleCaller(entry, err(new HopperCancelledError()), "cancelled");
return;
}
const index = this.#queue.indexOf(entry);
if (index < 0) return;
this.#queue.splice(index, 1);
this.#settleCaller(entry, err(new HopperCancelledError()), "cancelled");
}
#settleCaller(
entry: QueuedRequest,
result: HopperRequestResult,
callerState: QueuedRequest["callerState"],
): void {
if (entry.callerSettled) return;
entry.callerSettled = true;
entry.callerState = callerState;
if (this.#active === entry && entry.heartbeat !== undefined) {
clearInterval(entry.heartbeat);
entry.heartbeat = undefined;
}
clearTimeout(entry.timer);
if (entry.signal !== undefined && entry.onAbort !== undefined)
entry.signal.removeEventListener("abort", entry.onAbort);
entry.resolve(result);
}
#releaseWire(entry: QueuedRequest): void {
if (entry.heartbeat !== undefined) clearInterval(entry.heartbeat);
entry.heartbeat = undefined;
clearTimeout(entry.timer);
if (entry.signal !== undefined && entry.onAbort !== undefined)
entry.signal.removeEventListener("abort", entry.onAbort);
}
#report(entry: QueuedRequest, message: string): void {
void entry.progress
?.report({
phase: "hopper_request",
completed: 0,
total: 1,
message,
})
.catch(() => undefined);
}
}
+56
View File
@@ -0,0 +1,56 @@
import { parseResponseLine, type HopperResponse } from "./protocol.js";
const MAX_LINE_BYTES = 10 * 1024 * 1024;
export interface HopperResponseStreamOptions {
readonly accept: (response: HopperResponse) => boolean;
readonly hasQueued: (id: number) => boolean;
readonly nextRequestId: () => number;
readonly abort: (message: string, cause?: Error) => void;
}
/** Incrementally validates bounded Hopper NDJSON response frames. */
export class HopperResponseStream {
#buffer = "";
constructor(readonly options: HopperResponseStreamOptions) {}
push(chunk: string): void {
this.#buffer += chunk;
let newline = this.#buffer.indexOf("\n");
while (newline >= 0) {
const line = this.#buffer.slice(0, newline).trim();
this.#buffer = this.#buffer.slice(newline + 1);
if (Buffer.byteLength(line) > MAX_LINE_BYTES) {
this.options.abort("Hopper response exceeded the maximum line size");
return;
}
if (line.length > 0 && !this.#acceptLine(line)) return;
newline = this.#buffer.indexOf("\n");
}
if (Buffer.byteLength(this.#buffer) > MAX_LINE_BYTES) {
this.options.abort("Hopper response exceeded the maximum line size");
}
}
reset(): void {
this.#buffer = "";
}
#acceptLine(line: string): boolean {
const parsed = parseResponseLine(line);
if (!parsed.ok) {
this.options.abort(parsed.error.message, parsed.error);
return false;
}
if (this.options.accept(parsed.value)) return true;
if (
parsed.value.id >= this.options.nextRequestId() ||
this.options.hasQueued(parsed.value.id)
) {
this.options.abort("Hopper returned an unknown response id");
return false;
}
return true;
}
}