* fix(reconstruction): dedupe residual unknown ids with uniqueSorted Current main calls uniqueBy, which is not defined, so typecheck fails. Residual unknown ids are strings, and the adjacent lists already use uniqueSorted. Co-authored-by: morluto <morluto@users.noreply.github.com> * feat(config): make the bridge request ceiling configurable REA_BRIDGE_MAX_REQUEST_BYTES replaces the hard-coded 16 MiB Hopper and Cutter request payload ceiling. The default stays 16777216 bytes. Values outside 7464 to 268435456 bytes are configuration_invalid. Part of #6176. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(cutter): keep cleanup ownership when a sent command's reply is oversized An authenticated command may already have changed the Cutter document when its reply exceeds the frame ceiling. Return the existing unknown execution, with the ceiling diagnostic in the message, so receipt cleanup still waits. A frame that overflows before the command is sent remains a resource constraint. Co-authored-by: morluto <morluto@users.noreply.github.com> * style: format the bridge request ceiling sources oxfmt --check failed on the five files that set and test REA_BRIDGE_MAX_REQUEST_BYTES. Formatting only; an oversized Cutter reply still stays an unknown execution. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(cutter): exclude the LF from the response frame budget REA_BRIDGE_MAX_REQUEST_BYTES counts payload bytes. The Cutter response reader and authenticated encoder were reserving one byte for the terminating LF, so an exact-limit response was rejected. A reply that exceeds the ceiling after the command was sent still stays an unknown execution. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(bridge): measure escaped JSON before allocating the request A command of U+0001 characters can expand sixfold. JSON.stringify of that expansion can throw past Node's string ceiling before the payload check. Count the escaped size within REA_BRIDGE_MAX_REQUEST_BYTES first and refuse it as a resource constraint. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(config): derive the bridge request maximum from JSON expansion A 256 MiB ceiling still lets a shorter U+0001 command expand past Node's 536870888-character string limit. The maximum is now floor((536870888 - 296) / 7) = 76695798, the longest such command whose authenticated frame fits in one string. Requests are still measured before JSON.stringify. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(bridge): size the Cutter frame deadline and send the measured Hopper payload The authenticated Cutter command is encoded after the challenge, so a one-second read rejected an in-budget frame. That read now allows one second per mebibyte of the ceiling and never waits longer than 25 seconds. Hello stays at one second. Hopper writes the payload it already measured instead of serializing the same request again. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(config): bound the bridge request maximum by the serialized string The ceiling already measures escaped JSON, so dividing Node's string limit by the seven-byte expansion rejected encoded payloads that still fit. The maximum is 536870887, one byte under that string ceiling, leaving room for the framing LF. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(hopper): serialize a bridge request when it reaches the wire The queue kept each encoded frame, plus the caller's params, until Hopper finished the active request. A raised ceiling made a few waiting calls enough to exhaust the heap. The FIFO now keeps the params, and the frame is encoded only for the request being written. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(cutter): hash the bridge proof prefix and payload separately An exact-limit Cutter frame plus the HMAC prefix exceeds Node's single-string ceiling, so the client threw before sending an admitted command. The prefix and payload are now separate HMAC updates, including the response proof. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(cutter): keep recovery fields when a status path exceeds the frame A long current_file made the status reply miss the ceiling, and the fallback then dropped session_id and the completion receipts. The status now omits the path and version and still returns the session, connection proof, and up to 64 receipts. That required recovery frame is smaller than the 7464 floor. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(cutter): report an unknown path when status identity does not fit A bounded status kept the new document generation and omitted the path, so the client filled in the descriptor's older path. The observed path is sent when it fits. When it does not, current_file is null and is not replaced with that stale path. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(cutter): count structured replies by their encoded JSON size The response guard charged 16 bytes per primitive and two bytes per list slot, so a dense array under the configured ceiling was replaced with output_truncated. Numbers, booleans, null, and container punctuation now use their JSON lengths. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(cutter): stream authenticated responses in bounded chunks A fitting reply was signed from retained raw bytes, escaped bytes, and a joined frame, so a ceiling near 512 MiB could exhaust Cutter before send. Measure and sign JSON pieces, then write the same frame in 64 KiB chunks. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(bridge): keep Cutter admission from stalling or hiding sessions Read an unauthenticated frame off the accept loop. A command reply that does not fit keeps completion and generation and reports an oversized path as null. Discovery reports a ceiling mismatch instead of an absent session. The maximum HMAC proof is opt-in, and both bridges reject non-ASCII digits. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(cutter): bound frame scans and client response copies Search only newly read bytes for the framing LF. Unescape each socket chunk into one response string, check the proof, and then parse it. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(cutter): keep completion, admission, and dense replies bounded Report completed_connection only through connections that have terminated. Cap connection threads and keep the listener up if one fails to start. Batch scalar JSON and fail discovery when any ceiling mismatches. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(cutter): hash requests in parts and scan escapes once Update the client-proof prefix and request separately. Stop the response decoder at the first quote or backslash instead of rescanning the tail. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(cutter): confirm live ceiling mismatches and omitted output A stale descriptor from a previous ceiling is not a discovery mismatch until its hello proves a live authenticated bridge. A response discarded for the frame ceiling after dispatch reports output_truncated. Co-authored-by: morluto <morluto@users.noreply.github.com> * test(cutter): close the unauthenticated ceiling-mismatch fixture The listener that fails the hello proof is destroyed after its challenge so discovery cleanup does not wait on that socket. Co-authored-by: morluto <morluto@users.noreply.github.com> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: morluto <morluto@users.noreply.github.com>
414 lines
12 KiB
TypeScript
414 lines
12 KiB
TypeScript
import type {
|
|
ProgressReporter,
|
|
ProgressUpdate,
|
|
} from "../application/ProgressReporter.js";
|
|
import { hopperOperationStage } from "./HopperOperationStage.js";
|
|
import type { HopperBridgeEvent } from "./protocol.js";
|
|
import {
|
|
hopperCancelledBySignal,
|
|
type HopperError,
|
|
HopperProcessError,
|
|
HopperProtocolError,
|
|
HopperRemoteError,
|
|
HopperTimeoutError,
|
|
} from "../domain/hopperErrors.js";
|
|
import type { JsonValue } from "../domain/jsonValue.js";
|
|
import { err, type Result } from "../domain/result.js";
|
|
|
|
export type HopperRequestResult = Result<JsonValue, HopperError>;
|
|
|
|
/** Node timer ceiling; larger deadlines would be clamped instead of honored. */
|
|
const MAX_TIMEOUT_MS = 2_147_483_647;
|
|
|
|
export interface HopperRequestQueueOptions {
|
|
readonly signal?: AbortSignal;
|
|
/** Caller deadline from admission, including time waiting in the FIFO. */
|
|
readonly timeoutMs?: number;
|
|
readonly progress?: ProgressReporter;
|
|
}
|
|
|
|
export interface HopperRequestActivity {
|
|
readonly requestId: number;
|
|
readonly operation: string;
|
|
readonly elapsedMs: number;
|
|
readonly callerState: "waiting" | "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 progress: ProgressReporter | undefined;
|
|
readonly resolve: (result: HopperRequestResult) => void;
|
|
readonly onAbort: (() => void) | undefined;
|
|
callerState: "waiting" | "cancelled";
|
|
callerSettled: boolean;
|
|
transmitted: boolean;
|
|
startedAt: number | undefined;
|
|
heartbeat: NodeJS.Timeout | undefined;
|
|
deadline: NodeJS.Timeout | undefined;
|
|
readonly deadlineAt: number | undefined;
|
|
readonly timeoutMs: number | undefined;
|
|
}
|
|
|
|
/** FIFO that keeps the wire serialized until Hopper actually replies. */
|
|
export class HopperRequestQueue {
|
|
readonly #queue: QueuedRequest[] = [];
|
|
#active: QueuedRequest | undefined;
|
|
|
|
constructor(private readonly send: RequestSender) {}
|
|
|
|
/** Settle the caller on reply, cancellation, or deadline; retain active wire work. */
|
|
run(
|
|
id: number,
|
|
method: string,
|
|
params: JsonValue,
|
|
options: HopperRequestQueueOptions,
|
|
): Promise<HopperRequestResult> {
|
|
if (options.signal?.aborted === true)
|
|
return Promise.resolve(err(hopperCancelledBySignal(options.signal)));
|
|
const timeoutMs = options.timeoutMs;
|
|
if (
|
|
timeoutMs !== undefined &&
|
|
(!Number.isInteger(timeoutMs) ||
|
|
timeoutMs < 0 ||
|
|
timeoutMs > MAX_TIMEOUT_MS)
|
|
)
|
|
return Promise.resolve(
|
|
err(
|
|
new HopperProtocolError(
|
|
`Hopper timeoutMs must be an integer between 0 and ${String(MAX_TIMEOUT_MS)}`,
|
|
),
|
|
),
|
|
);
|
|
if (timeoutMs === 0)
|
|
return Promise.resolve(
|
|
err(
|
|
new HopperTimeoutError(
|
|
0,
|
|
method,
|
|
id,
|
|
"not_started",
|
|
hopperOperationStage(method),
|
|
),
|
|
),
|
|
);
|
|
return new Promise((resolve) => {
|
|
let entry: QueuedRequest;
|
|
const onAbort =
|
|
options.signal === undefined ? undefined : () => this.#cancel(entry);
|
|
entry = {
|
|
id,
|
|
method,
|
|
params,
|
|
signal: options.signal,
|
|
progress: options.progress,
|
|
resolve,
|
|
onAbort,
|
|
callerState: "waiting",
|
|
callerSettled: false,
|
|
transmitted: false,
|
|
startedAt: undefined,
|
|
heartbeat: undefined,
|
|
deadline: undefined,
|
|
deadlineAt:
|
|
timeoutMs === undefined ? undefined : performance.now() + timeoutMs,
|
|
timeoutMs,
|
|
};
|
|
this.#queue.push(entry);
|
|
if (onAbort !== undefined)
|
|
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
if (timeoutMs !== undefined)
|
|
entry.deadline = setTimeout(
|
|
() => this.#cancel(entry, this.#timeoutError(entry, timeoutMs)),
|
|
timeoutMs,
|
|
);
|
|
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.#expireIfElapsed(entry);
|
|
this.#releaseWire(entry);
|
|
if (!entry.callerSettled)
|
|
this.#settleCaller(
|
|
entry,
|
|
result.ok ? result : err(withRequestContext(result.error, entry)),
|
|
"waiting",
|
|
);
|
|
this.#active = undefined;
|
|
this.#drain();
|
|
return true;
|
|
}
|
|
|
|
/** Forward one correlated bridge event without releasing the wire request. */
|
|
acceptEvent(event: HopperBridgeEvent): boolean {
|
|
const entry = this.#active;
|
|
if (entry === undefined || entry.id !== event.id) return false;
|
|
if (event.event.type === "progress" && !entry.callerSettled) {
|
|
if (event.event.terminal === true && entry.heartbeat !== undefined) {
|
|
clearInterval(entry.heartbeat);
|
|
entry.heartbeat = undefined;
|
|
}
|
|
this.#reportUpdate(entry, {
|
|
phase: event.event.phase,
|
|
completed: event.event.completed,
|
|
total: event.event.total,
|
|
message: event.event.message,
|
|
...(event.event.terminal === undefined
|
|
? {}
|
|
: { terminal: event.event.terminal }),
|
|
});
|
|
}
|
|
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(withRequestContext(error, active)),
|
|
"waiting",
|
|
);
|
|
}
|
|
for (const entry of this.#queue.splice(0))
|
|
this.#settleCaller(
|
|
entry,
|
|
err(withRequestContext(error, entry)),
|
|
"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)),
|
|
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;
|
|
if (this.#expireIfElapsed(entry)) {
|
|
this.#drain();
|
|
return;
|
|
}
|
|
if (entry.signal?.aborted === true) {
|
|
this.#settleCaller(
|
|
entry,
|
|
err(hopperCancelledBySignal(entry.signal)),
|
|
"cancelled",
|
|
);
|
|
this.#drain();
|
|
return;
|
|
}
|
|
this.#active = entry;
|
|
entry.startedAt = performance.now();
|
|
this.#report(entry, `${entry.method} started on Hopper's serial bridge`);
|
|
this.#expireIfElapsed(entry);
|
|
// A progress observer may cancel or tear down synchronously before send.
|
|
// No native work exists yet, so it is safe to release this reserved slot.
|
|
if (this.#active !== entry || entry.callerSettled) {
|
|
if (this.#active === entry) {
|
|
this.#active = undefined;
|
|
this.#releaseWire(entry);
|
|
this.#drain();
|
|
}
|
|
return;
|
|
}
|
|
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 {
|
|
entry.transmitted = true;
|
|
this.send(
|
|
{
|
|
id: entry.id,
|
|
method: entry.method,
|
|
params: entry.params,
|
|
},
|
|
() =>
|
|
this.accept(
|
|
entry.id,
|
|
err(
|
|
new HopperProcessError(null, {
|
|
operation: entry.method,
|
|
requestId: entry.id,
|
|
providerState: "unreachable",
|
|
stage: hopperOperationStage(entry.method),
|
|
}),
|
|
),
|
|
),
|
|
);
|
|
} catch (cause: unknown) {
|
|
this.accept(
|
|
entry.id,
|
|
err(new HopperProtocolError("Hopper socket write failed", { cause })),
|
|
);
|
|
}
|
|
}
|
|
|
|
#timeoutError(entry: QueuedRequest, timeoutMs: number): HopperTimeoutError {
|
|
return new HopperTimeoutError(
|
|
timeoutMs,
|
|
entry.method,
|
|
entry.id,
|
|
entry.transmitted ? "busy" : "not_started",
|
|
hopperOperationStage(entry.method),
|
|
);
|
|
}
|
|
|
|
#expireIfElapsed(entry: QueuedRequest): boolean {
|
|
if (
|
|
entry.deadlineAt !== undefined &&
|
|
entry.timeoutMs !== undefined &&
|
|
performance.now() >= entry.deadlineAt
|
|
)
|
|
this.#settleCaller(
|
|
entry,
|
|
err(this.#timeoutError(entry, entry.timeoutMs)),
|
|
"cancelled",
|
|
);
|
|
return entry.callerSettled;
|
|
}
|
|
|
|
#cancel(
|
|
entry: QueuedRequest,
|
|
error: HopperError = hopperCancelledBySignal(entry.signal),
|
|
): void {
|
|
if (entry.callerSettled) return;
|
|
if (this.#active === entry) {
|
|
this.#settleCaller(entry, err(error), "cancelled");
|
|
return;
|
|
}
|
|
const index = this.#queue.indexOf(entry);
|
|
if (index < 0) return;
|
|
this.#queue.splice(index, 1);
|
|
this.#settleCaller(entry, err(error), "cancelled");
|
|
}
|
|
|
|
#settleCaller(
|
|
entry: QueuedRequest,
|
|
result: HopperRequestResult,
|
|
callerState: QueuedRequest["callerState"],
|
|
): void {
|
|
if (entry.callerSettled) return;
|
|
entry.callerSettled = true;
|
|
entry.callerState = callerState;
|
|
if (entry.deadline !== undefined) clearTimeout(entry.deadline);
|
|
entry.deadline = undefined;
|
|
if (this.#active === entry && entry.heartbeat !== undefined) {
|
|
clearInterval(entry.heartbeat);
|
|
entry.heartbeat = undefined;
|
|
}
|
|
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;
|
|
if (entry.signal !== undefined && entry.onAbort !== undefined)
|
|
entry.signal.removeEventListener("abort", entry.onAbort);
|
|
}
|
|
|
|
#report(entry: QueuedRequest, message: string): void {
|
|
this.#reportUpdate(entry, {
|
|
phase: "hopper_request",
|
|
completed: 0,
|
|
total: 1,
|
|
message,
|
|
});
|
|
}
|
|
|
|
#reportUpdate(entry: QueuedRequest, update: ProgressUpdate): void {
|
|
try {
|
|
void Promise.resolve(entry.progress?.report(update)).catch(
|
|
(cause: unknown) => {
|
|
// best-effort cleanup: progress rejection bookkeeping only.
|
|
void cause;
|
|
},
|
|
);
|
|
} catch (cause: unknown) {
|
|
// Progress observation cannot change the request outcome.
|
|
void cause;
|
|
}
|
|
}
|
|
}
|
|
|
|
const withRequestContext = (
|
|
error: HopperError,
|
|
entry: QueuedRequest,
|
|
): HopperError => {
|
|
if (error instanceof HopperProcessError)
|
|
return new HopperProcessError(error.exitCode, {
|
|
...error,
|
|
cause: error.cause,
|
|
operation: error.operation ?? entry.method,
|
|
requestId: error.requestId ?? entry.id,
|
|
stage:
|
|
error.operation === undefined && error.stage === "connection"
|
|
? hopperOperationStage(entry.method)
|
|
: error.stage,
|
|
});
|
|
if (error instanceof HopperRemoteError)
|
|
return new HopperRemoteError(error.code, error.safeMessage, {
|
|
...error,
|
|
cause: error.cause,
|
|
operation: error.operation ?? entry.method,
|
|
requestId: error.requestId ?? entry.id,
|
|
});
|
|
return error;
|
|
};
|