refactor: return complete tool results inline
This commit is contained in:
+155
-36
@@ -22,6 +22,9 @@ import {
|
||||
} from "./LinuxPrivateDisplayProbe.js";
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
|
||||
import { acquireHopperTargetLease } from "./HopperTargetLease.js";
|
||||
import type { HopperTargetLease } from "./HopperTargetLease.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const HOPPER_BACKGROUND_STARTUP_MS = 5_000;
|
||||
|
||||
@@ -74,6 +77,8 @@ export type HopperApplicationLauncherOptions =
|
||||
});
|
||||
|
||||
export interface HopperApplicationLauncherDependencies {
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly acquireTargetLease?: typeof acquireHopperTargetLease;
|
||||
readonly selectPrivateDisplay?: (options: {
|
||||
readonly helperPath: string;
|
||||
readonly signal?: AbortSignal;
|
||||
@@ -109,65 +114,89 @@ export class HopperApplicationLauncher implements BridgeLauncher {
|
||||
HopperStartError | HopperCancelledError | HopperProcessError
|
||||
>
|
||||
> {
|
||||
const bootstrapPath = `${session.directory}/bootstrap.py`;
|
||||
const ownsProcessLifetime = usesLinuxDemo(this.options);
|
||||
const source = [
|
||||
`REA_SOCKET = ${JSON.stringify(session.socketPath)}`,
|
||||
`REA_TOKEN = ${JSON.stringify(session.token)}`,
|
||||
`REA_RUN_ID = ${JSON.stringify(session.runId)}`,
|
||||
`REA_TARGET_PATH = ${JSON.stringify(this.options.targetPath)}`,
|
||||
`REA_OWNS_PROCESS_LIFETIME = ${ownsProcessLifetime ? "True" : "False"}`,
|
||||
`exec(compile(open(${JSON.stringify(this.options.bridgeScriptPath)}, 'rb').read(), ${JSON.stringify(this.options.bridgeScriptPath)}, 'exec'))`,
|
||||
"",
|
||||
].join("\n");
|
||||
const leaseResult = await this.#acquireTargetLease(session.runId);
|
||||
if (!leaseResult.ok) return leaseResult;
|
||||
const lease = leaseResult.value;
|
||||
let leaseTransferred = false;
|
||||
try {
|
||||
await writeFile(bootstrapPath, source, { encoding: "utf8", mode: 0o600 });
|
||||
await chmod(bootstrapPath, 0o600);
|
||||
} catch (cause: unknown) {
|
||||
return err(new HopperStartError({ cause }));
|
||||
const ownsProcessLifetime = usesLinuxDemo(this.options);
|
||||
const bootstrap = await this.#writeBootstrap(
|
||||
session,
|
||||
ownsProcessLifetime,
|
||||
);
|
||||
if (!bootstrap.ok) return bootstrap;
|
||||
const launched = await this.#launchPreparedTarget({
|
||||
session,
|
||||
signal: options.signal,
|
||||
bootstrapPath: bootstrap.value,
|
||||
ownsProcessLifetime,
|
||||
lease,
|
||||
});
|
||||
leaseTransferred = launched.ok;
|
||||
return launched;
|
||||
} finally {
|
||||
if (!leaseTransferred) await lease?.release();
|
||||
}
|
||||
}
|
||||
|
||||
async #launchPreparedTarget(input: {
|
||||
readonly session: BridgeSession;
|
||||
readonly signal: AbortSignal | undefined;
|
||||
readonly bootstrapPath: string;
|
||||
readonly ownsProcessLifetime: boolean;
|
||||
readonly lease: HopperTargetLease | undefined;
|
||||
}): Promise<
|
||||
Result<
|
||||
BridgeLaunch,
|
||||
HopperStartError | HopperCancelledError | HopperProcessError
|
||||
>
|
||||
> {
|
||||
const { session, signal, bootstrapPath, ownsProcessLifetime, lease } =
|
||||
input;
|
||||
const action =
|
||||
this.options.targetKind === "database" ? "--database" : "--executable";
|
||||
const args = [
|
||||
const argumentsForTarget = [
|
||||
...this.options.loaderArgs,
|
||||
"--analysis",
|
||||
"--python",
|
||||
"-Y",
|
||||
bootstrapPath,
|
||||
action,
|
||||
this.options.targetPath,
|
||||
];
|
||||
try {
|
||||
if (options.signal?.aborted === true)
|
||||
return err(new HopperCancelledError());
|
||||
const display = await this.#privateDisplay(options.signal);
|
||||
if (signal?.aborted === true) return err(new HopperCancelledError());
|
||||
const display = await this.#privateDisplay(signal);
|
||||
if (!display.ok) return err(display.error);
|
||||
const prepared = await prepareHopperApplication(
|
||||
this.options.launcherPath,
|
||||
options.signal,
|
||||
signal,
|
||||
);
|
||||
if (!prepared) return err(new HopperCancelledError());
|
||||
const linuxDemo = linuxDemoLaunch(
|
||||
this.options,
|
||||
session,
|
||||
args,
|
||||
argumentsForTarget,
|
||||
display.strategy,
|
||||
);
|
||||
const ownershipCommand =
|
||||
linuxDemo?.ownershipCommand ?? this.options.launcherPath;
|
||||
const started = await spawnOwnedProviderProcess({
|
||||
command: linuxDemo?.command ?? this.options.launcherPath,
|
||||
arguments: linuxDemo?.args ?? args,
|
||||
runId: session.runId,
|
||||
expectedCommand: ownershipCommand,
|
||||
const started = await launchHopperProcess({
|
||||
options: this.options,
|
||||
session,
|
||||
bootstrapPath,
|
||||
ownsProcessLifetime,
|
||||
argumentsForTarget,
|
||||
linuxDemo,
|
||||
signal,
|
||||
});
|
||||
const child = started.process;
|
||||
const pid = started.ownership.leaderPid;
|
||||
if (started === null) return err(new HopperCancelledError());
|
||||
const cleanup = () =>
|
||||
cleanupOwnedProcessGroup(started.ownership).finally(() =>
|
||||
lease?.release(),
|
||||
);
|
||||
const ownership = {
|
||||
schema_version: 1,
|
||||
run_id: session.runId,
|
||||
pid,
|
||||
process_group_id: pid,
|
||||
pid: started.ownership.leaderPid,
|
||||
process_group_id: started.ownership.leaderPid,
|
||||
parent_pid: process.pid,
|
||||
launcher: linuxDemo?.command ?? this.options.launcherPath,
|
||||
created_at: new Date().toISOString(),
|
||||
@@ -183,16 +212,63 @@ export class HopperApplicationLauncher implements BridgeLauncher {
|
||||
return err(new HopperStartError({ cause }));
|
||||
}
|
||||
return ok({
|
||||
process: child,
|
||||
process: started.process,
|
||||
ownsProcessLifetime: true,
|
||||
ownership: started.ownership,
|
||||
shutdownMode: ownsProcessLifetime
|
||||
? "process-cleanup"
|
||||
: "bridge-request",
|
||||
cleanup: () => cleanupOwnedProcessGroup(started.ownership),
|
||||
cleanup,
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
return err(hopperLaunchFailure(cause, options.signal));
|
||||
return err(hopperLaunchFailure(cause, signal));
|
||||
}
|
||||
}
|
||||
|
||||
async #acquireTargetLease(
|
||||
runId: string,
|
||||
): Promise<Result<HopperTargetLease | undefined, HopperStartError>> {
|
||||
if ((this.dependencies.platform ?? process.platform) !== "darwin")
|
||||
return ok(undefined);
|
||||
try {
|
||||
const acquisition = await (
|
||||
this.dependencies.acquireTargetLease ?? acquireHopperTargetLease
|
||||
)({
|
||||
targetPath: this.options.targetPath,
|
||||
targetKind: this.options.targetKind,
|
||||
loaderArgs: this.options.loaderArgs,
|
||||
runId,
|
||||
});
|
||||
if (!acquisition.acquired)
|
||||
return err(
|
||||
new HopperStartError({
|
||||
ownerRunId: acquisition.owner.runId,
|
||||
userMessage:
|
||||
`This Hopper target is already open in REA session ${acquisition.owner.runId}. ` +
|
||||
"Use that REA session or close it before opening this target again.",
|
||||
}),
|
||||
);
|
||||
return ok(acquisition.lease);
|
||||
} catch (cause: unknown) {
|
||||
return err(new HopperStartError({ cause }));
|
||||
}
|
||||
}
|
||||
|
||||
async #writeBootstrap(
|
||||
session: BridgeSession,
|
||||
ownsProcessLifetime: boolean,
|
||||
): Promise<Result<string, HopperStartError>> {
|
||||
const bootstrapPath = `${session.directory}/bootstrap.py`;
|
||||
try {
|
||||
await writeFile(
|
||||
bootstrapPath,
|
||||
bridgeBootstrapSource(session, this.options, ownsProcessLifetime),
|
||||
{ encoding: "utf8", mode: 0o600 },
|
||||
);
|
||||
await chmod(bootstrapPath, 0o600);
|
||||
return ok(bootstrapPath);
|
||||
} catch (cause: unknown) {
|
||||
return err(new HopperStartError({ cause }));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,6 +304,49 @@ export class HopperApplicationLauncher implements BridgeLauncher {
|
||||
}
|
||||
}
|
||||
|
||||
const bridgeBootstrapSource = (
|
||||
session: BridgeSession,
|
||||
options: SharedHopperApplicationLauncherOptions,
|
||||
ownsProcessLifetime: boolean,
|
||||
): string =>
|
||||
[
|
||||
`REA_SOCKET = ${JSON.stringify(session.socketPath)}`,
|
||||
`REA_TOKEN = ${JSON.stringify(session.token)}`,
|
||||
`REA_RUN_ID = ${JSON.stringify(session.runId)}`,
|
||||
`REA_TARGET_PATH = ${JSON.stringify(options.targetPath)}`,
|
||||
`REA_OWNS_PROCESS_LIFETIME = ${ownsProcessLifetime ? "True" : "False"}`,
|
||||
`exec(compile(open(${JSON.stringify(options.bridgeScriptPath)}, 'rb').read(), ${JSON.stringify(options.bridgeScriptPath)}, 'exec'))`,
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
const launchHopperProcess = async (input: {
|
||||
readonly options: HopperApplicationLauncherOptions;
|
||||
readonly session: BridgeSession;
|
||||
readonly bootstrapPath: string;
|
||||
readonly ownsProcessLifetime: boolean;
|
||||
readonly argumentsForTarget: readonly string[];
|
||||
readonly linuxDemo: ReturnType<typeof linuxDemoLaunch>;
|
||||
readonly signal: AbortSignal | undefined;
|
||||
}): Promise<Awaited<ReturnType<typeof spawnOwnedProviderProcess>> | null> => {
|
||||
const ownershipCommand =
|
||||
input.linuxDemo?.ownershipCommand ?? input.options.launcherPath;
|
||||
const spawn = (arguments_: readonly string[]) =>
|
||||
spawnOwnedProviderProcess({
|
||||
command: input.options.launcherPath,
|
||||
arguments: arguments_,
|
||||
runId: input.session.runId,
|
||||
expectedCommand: ownershipCommand,
|
||||
});
|
||||
if (input.linuxDemo !== undefined)
|
||||
return spawnOwnedProviderProcess({
|
||||
command: input.linuxDemo.command,
|
||||
arguments: input.linuxDemo.args,
|
||||
runId: input.session.runId,
|
||||
expectedCommand: ownershipCommand,
|
||||
});
|
||||
return spawn(input.argumentsForTarget);
|
||||
};
|
||||
|
||||
export const linuxDemoLaunch = (
|
||||
options: HopperApplicationLauncherOptions,
|
||||
session: BridgeSession,
|
||||
|
||||
@@ -48,7 +48,7 @@ export const resolveHopperAnalysisProfile = async (
|
||||
version: `launcher-sha256:${launcherDigest.value}`,
|
||||
};
|
||||
return ok({
|
||||
profile: createAnalysisProfile(provider, 1, {
|
||||
profile: createAnalysisProfile(provider, {
|
||||
target_kind: target.kind,
|
||||
target_format: target.format,
|
||||
architecture: target.architecture ?? null,
|
||||
|
||||
@@ -40,6 +40,7 @@ export interface HopperCleanupInput {
|
||||
readonly processSupervisor: ProviderProcessSupervisor | undefined;
|
||||
readonly runtimeRoot: PrivateRuntimeRoot | undefined;
|
||||
readonly activeRequest: HopperRequestActivity | null;
|
||||
readonly retainDocument: boolean;
|
||||
readonly progress: ProgressReporter | undefined;
|
||||
readonly logger: Logger;
|
||||
readonly onDiagnostic: ((event: HopperDiagnostic) => void) | undefined;
|
||||
@@ -59,7 +60,13 @@ export const cleanupHopperSession = async (
|
||||
cleanupResult: undefined,
|
||||
shutdownConfirmed: false,
|
||||
};
|
||||
await report(input.progress, 0, "requesting Hopper document shutdown");
|
||||
await report(
|
||||
input.progress,
|
||||
0,
|
||||
input.retainDocument
|
||||
? "detaching REA from the Hopper document"
|
||||
: "requesting Hopper document shutdown",
|
||||
);
|
||||
await requestShutdown(input, state);
|
||||
await report(input.progress, 0.35, "releasing Hopper bridge transport");
|
||||
input.releaseTransport(input.socket);
|
||||
@@ -90,7 +97,11 @@ const requestShutdown = async (
|
||||
return;
|
||||
}
|
||||
const shutdown = await input
|
||||
.request("shutdown")
|
||||
.request(
|
||||
input.retainDocument || input.launch?.shutdownMode === "process-cleanup"
|
||||
? "shutdown"
|
||||
: "shutdown_document",
|
||||
)
|
||||
.catch(() => err(new HopperProcessError(null)));
|
||||
if (
|
||||
shutdown.ok &&
|
||||
|
||||
@@ -51,7 +51,6 @@ import {
|
||||
export type { HopperServerInfo } from "./HopperSessionValues.js";
|
||||
|
||||
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. */
|
||||
@@ -64,6 +63,11 @@ export interface HopperClientOptions {
|
||||
readonly logger?: Logger;
|
||||
}
|
||||
|
||||
type HopperClientCloseOptions = {
|
||||
readonly progress?: ProgressReporter;
|
||||
readonly retainDocument?: boolean;
|
||||
};
|
||||
|
||||
/** Safe launcher telemetry; stderr content is intentionally never exposed. */
|
||||
/**
|
||||
* Owns one authenticated NDJSON-over-Unix-socket bridge session.
|
||||
@@ -112,7 +116,6 @@ export class HopperClient {
|
||||
startupTimeoutMs: options.startupTimeoutMs ?? 120_000,
|
||||
};
|
||||
this.#requests = new HopperRequestQueue(
|
||||
MAX_QUEUED_REQUESTS,
|
||||
({ id, method, params }, failed) => {
|
||||
const socket = this.#socket;
|
||||
const token = this.#token;
|
||||
@@ -308,7 +311,7 @@ export class HopperClient {
|
||||
|
||||
/** Stop the bridge and report whether every owned resource was verified clean. */
|
||||
closeWithOutcome(
|
||||
options: { readonly progress?: ProgressReporter } = {},
|
||||
options: HopperClientCloseOptions = {},
|
||||
): Promise<Result<null, AnalysisError>> {
|
||||
const starting = this.#startPromise;
|
||||
const controller = this.#startupController;
|
||||
@@ -322,7 +325,7 @@ export class HopperClient {
|
||||
async #close(
|
||||
starting: Promise<Result<HopperServerInfo, HopperError>> | undefined,
|
||||
controller: AbortController | undefined,
|
||||
options: { readonly progress?: ProgressReporter },
|
||||
options: HopperClientCloseOptions,
|
||||
): Promise<Result<null, AnalysisError>> {
|
||||
try {
|
||||
await starting?.catch(() => undefined);
|
||||
@@ -337,7 +340,7 @@ export class HopperClient {
|
||||
}
|
||||
|
||||
async #cleanup(
|
||||
options: { readonly progress?: ProgressReporter } = {},
|
||||
options: HopperClientCloseOptions = {},
|
||||
): Promise<Result<null, AnalysisError>> {
|
||||
this.#closing = true;
|
||||
try {
|
||||
@@ -352,6 +355,7 @@ export class HopperClient {
|
||||
onDiagnostic: this.#options.onDiagnostic,
|
||||
request: (method) =>
|
||||
this.#request(method, {}, { timeoutMs: SHUTDOWN_TIMEOUT_MS }),
|
||||
retainDocument: options.retainDocument === true,
|
||||
releaseTransport: (socket) => {
|
||||
this.#failAll(new HopperProcessError(null));
|
||||
if (socket !== undefined) this.#detachSocket(socket);
|
||||
@@ -419,14 +423,14 @@ export class HopperClient {
|
||||
readonly progress?: ProgressReporter;
|
||||
},
|
||||
): Promise<Result<JsonValue, HopperError>> {
|
||||
const id = this.#nextId++;
|
||||
const socket = this.#socket;
|
||||
const token = this.#token;
|
||||
if (socket === undefined || socket.destroyed || token === undefined) {
|
||||
return err(new HopperProcessError(null));
|
||||
return err(new HopperProcessError(null, undefined, method, id));
|
||||
}
|
||||
if (options.signal?.aborted === true)
|
||||
return err(new HopperCancelledError());
|
||||
const id = this.#nextId++;
|
||||
const startedAt = performance.now();
|
||||
const timeoutMs = options.timeoutMs ?? this.#options.requestTimeoutMs;
|
||||
const result = await this.#requests.run(id, method, params, {
|
||||
|
||||
@@ -19,15 +19,13 @@ describe("Hopper provider capabilities", () => {
|
||||
for (const descriptor of capabilities) {
|
||||
expect(descriptor.provider).toEqual(provider.identity());
|
||||
expect(descriptor).toMatchObject({
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
});
|
||||
}
|
||||
expect(
|
||||
capabilities.find(({ operation }) => operation === "list_procedures"),
|
||||
).toMatchObject({ pagination: "offset" });
|
||||
).toMatchObject({ pagination: "none" });
|
||||
expect(
|
||||
capabilities.find(({ operation }) => operation === "set_comment"),
|
||||
).toMatchObject({
|
||||
|
||||
@@ -58,8 +58,6 @@ const CAPABILITIES: readonly CapabilityDescriptor[] = Object.freeze(
|
||||
return Object.freeze({
|
||||
provider: IDENTITY,
|
||||
operation,
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination:
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
type HopperError,
|
||||
HopperProcessError,
|
||||
HopperProtocolError,
|
||||
HopperRemoteError,
|
||||
HopperTimeoutError,
|
||||
} from "../domain/errors.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
@@ -58,15 +59,12 @@ interface QueuedRequest {
|
||||
heartbeat: NodeJS.Timeout | undefined;
|
||||
}
|
||||
|
||||
/** Bounded FIFO that keeps the wire serialized until Hopper actually replies. */
|
||||
/** 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,
|
||||
) {}
|
||||
constructor(private readonly send: RequestSender) {}
|
||||
|
||||
/** Queue one request, counting queue wait against its caller deadline. */
|
||||
run(
|
||||
@@ -78,14 +76,8 @@ export class HopperRequestQueue {
|
||||
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`,
|
||||
),
|
||||
),
|
||||
err(new HopperTimeoutError(options.timeoutMs, method, id)),
|
||||
);
|
||||
return new Promise((resolve) => {
|
||||
let entry: QueuedRequest;
|
||||
@@ -125,7 +117,23 @@ export class HopperRequestQueue {
|
||||
const entry = this.#active;
|
||||
if (entry === undefined || entry.id !== id) return false;
|
||||
this.#releaseWire(entry);
|
||||
if (!entry.callerSettled) this.#settleCaller(entry, result, "waiting");
|
||||
if (!entry.callerSettled) {
|
||||
const contextual =
|
||||
!result.ok && result.error instanceof HopperRemoteError
|
||||
? err(
|
||||
new HopperRemoteError(
|
||||
result.error.code,
|
||||
result.error.safeMessage,
|
||||
{
|
||||
diagnosticType: result.error.diagnosticType,
|
||||
operation: entry.method,
|
||||
requestId: entry.id,
|
||||
},
|
||||
),
|
||||
)
|
||||
: result;
|
||||
this.#settleCaller(entry, contextual, "waiting");
|
||||
}
|
||||
this.#active = undefined;
|
||||
this.#drain();
|
||||
return true;
|
||||
@@ -160,10 +168,18 @@ export class HopperRequestQueue {
|
||||
if (active !== undefined) {
|
||||
this.#releaseWire(active);
|
||||
if (!active.callerSettled)
|
||||
this.#settleCaller(active, err(error), "waiting");
|
||||
this.#settleCaller(
|
||||
active,
|
||||
err(withRequestContext(error, active)),
|
||||
"waiting",
|
||||
);
|
||||
}
|
||||
for (const entry of this.#queue.splice(0))
|
||||
this.#settleCaller(entry, err(error), "waiting");
|
||||
this.#settleCaller(
|
||||
entry,
|
||||
err(withRequestContext(error, entry)),
|
||||
"waiting",
|
||||
);
|
||||
}
|
||||
|
||||
/** Snapshot the one request still occupying Hopper's serial Python thread. */
|
||||
@@ -204,7 +220,9 @@ export class HopperRequestQueue {
|
||||
entry,
|
||||
entry.signal?.aborted === true
|
||||
? err(new HopperCancelledError())
|
||||
: err(new HopperTimeoutError(entry.timeoutMs)),
|
||||
: err(
|
||||
new HopperTimeoutError(entry.timeoutMs, entry.method, entry.id),
|
||||
),
|
||||
entry.signal?.aborted === true ? "cancelled" : "timed_out",
|
||||
);
|
||||
this.#drain();
|
||||
@@ -239,7 +257,14 @@ export class HopperRequestQueue {
|
||||
if (this.#active === entry) {
|
||||
this.#settleCaller(
|
||||
entry,
|
||||
err(new HopperTimeoutError(entry.timeoutMs)),
|
||||
err(
|
||||
new HopperTimeoutError(
|
||||
entry.timeoutMs,
|
||||
entry.method,
|
||||
entry.id,
|
||||
"busy",
|
||||
),
|
||||
),
|
||||
"timed_out",
|
||||
);
|
||||
return;
|
||||
@@ -249,7 +274,7 @@ export class HopperRequestQueue {
|
||||
this.#queue.splice(index, 1);
|
||||
this.#settleCaller(
|
||||
entry,
|
||||
err(new HopperTimeoutError(entry.timeoutMs)),
|
||||
err(new HopperTimeoutError(entry.timeoutMs, entry.method, entry.id)),
|
||||
"timed_out",
|
||||
);
|
||||
}
|
||||
@@ -311,3 +336,16 @@ export class HopperRequestQueue {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const withRequestContext = (
|
||||
error: HopperError,
|
||||
entry: QueuedRequest,
|
||||
): HopperError =>
|
||||
error instanceof HopperProcessError
|
||||
? new HopperProcessError(
|
||||
error.exitCode,
|
||||
error.diagnostic,
|
||||
entry.method,
|
||||
entry.id,
|
||||
)
|
||||
: error;
|
||||
|
||||
@@ -25,12 +25,15 @@ export const parseHopperServerInfo = (
|
||||
return err(new HopperProtocolError("Hopper bridge health result is invalid"));
|
||||
};
|
||||
|
||||
/** Require Hopper to confirm both analysis and document shutdown. */
|
||||
/** Require confirmation that the REA bridge detached or its document closed. */
|
||||
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;
|
||||
return (
|
||||
(value.analysis_stopped === true && value.document_closed === true) ||
|
||||
(value.document_closed === false && value.document_retained === true)
|
||||
);
|
||||
};
|
||||
|
||||
/** Detect the verified Linux bridge response that requires group cleanup. */
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { acquireHopperTargetLease } from "./HopperTargetLease.js";
|
||||
|
||||
const directories: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
directories
|
||||
.splice(0)
|
||||
.map((directory) => rm(directory, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("Hopper target leases", () => {
|
||||
it("reports the owning REA session for a duplicate target and profile", async () => {
|
||||
const directory = await temporaryDirectory();
|
||||
const first = await acquireHopperTargetLease({
|
||||
...leaseInput,
|
||||
directory,
|
||||
runId: "session-first",
|
||||
});
|
||||
expect(first.acquired).toBe(true);
|
||||
if (!first.acquired) return;
|
||||
|
||||
const duplicate = await acquireHopperTargetLease({
|
||||
...leaseInput,
|
||||
directory,
|
||||
runId: "session-second",
|
||||
});
|
||||
expect(duplicate).toMatchObject({
|
||||
acquired: false,
|
||||
owner: { runId: "session-first", processId: process.pid },
|
||||
});
|
||||
|
||||
await first.lease.release();
|
||||
const reopened = await acquireHopperTargetLease({
|
||||
...leaseInput,
|
||||
directory,
|
||||
runId: "session-third",
|
||||
});
|
||||
expect(reopened.acquired).toBe(true);
|
||||
if (reopened.acquired) await reopened.lease.release();
|
||||
});
|
||||
|
||||
it("keeps different Hopper profiles independent", async () => {
|
||||
const directory = await temporaryDirectory();
|
||||
const first = await acquireHopperTargetLease({
|
||||
...leaseInput,
|
||||
directory,
|
||||
runId: "session-one",
|
||||
});
|
||||
const second = await acquireHopperTargetLease({
|
||||
...leaseInput,
|
||||
directory,
|
||||
loaderArgs: ["--aarch64"],
|
||||
runId: "session-two",
|
||||
});
|
||||
expect(first.acquired).toBe(true);
|
||||
expect(second.acquired).toBe(true);
|
||||
if (first.acquired) await first.lease.release();
|
||||
if (second.acquired) await second.lease.release();
|
||||
});
|
||||
});
|
||||
|
||||
const leaseInput = {
|
||||
targetPath: "/tmp/sample-binary",
|
||||
targetKind: "executable" as const,
|
||||
loaderArgs: [],
|
||||
};
|
||||
|
||||
const temporaryDirectory = async (): Promise<string> => {
|
||||
const directory = await mkdtemp(join("/tmp", "rea-hl-"));
|
||||
directories.push(directory);
|
||||
return directory;
|
||||
};
|
||||
@@ -0,0 +1,159 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { chmod, lstat, mkdir, realpath, rm } from "node:fs/promises";
|
||||
import {
|
||||
createConnection,
|
||||
createServer,
|
||||
type Server,
|
||||
type Socket,
|
||||
} from "node:net";
|
||||
import { join, resolve } from "node:path";
|
||||
|
||||
interface HopperTargetLeaseOwner {
|
||||
readonly runId: string;
|
||||
readonly processId: number;
|
||||
}
|
||||
|
||||
export interface HopperTargetLease {
|
||||
readonly release: () => Promise<void>;
|
||||
}
|
||||
|
||||
export type HopperTargetLeaseAcquisition =
|
||||
| { readonly acquired: true; readonly lease: HopperTargetLease }
|
||||
| { readonly acquired: false; readonly owner: HopperTargetLeaseOwner };
|
||||
|
||||
const leaseDirectory = join("/tmp", `rea-hopper-${process.getuid?.() ?? 0}`);
|
||||
|
||||
/** Keep two REA processes from opening duplicate Hopper documents for one target/profile. */
|
||||
export const acquireHopperTargetLease = async (input: {
|
||||
readonly targetPath: string;
|
||||
readonly targetKind: "executable" | "database";
|
||||
readonly loaderArgs: readonly string[];
|
||||
readonly runId: string;
|
||||
readonly directory?: string;
|
||||
}): Promise<HopperTargetLeaseAcquisition> => {
|
||||
const directory = input.directory ?? leaseDirectory;
|
||||
await ensureLeaseDirectory(directory);
|
||||
const targetPath = await realpath(input.targetPath).catch(() =>
|
||||
resolve(input.targetPath),
|
||||
);
|
||||
const key = createHash("sha256")
|
||||
.update(
|
||||
JSON.stringify({
|
||||
targetPath,
|
||||
targetKind: input.targetKind,
|
||||
loaderArgs: input.loaderArgs,
|
||||
}),
|
||||
)
|
||||
.digest("hex")
|
||||
.slice(0, 32);
|
||||
const socketPath = join(directory, `${key}.sock`);
|
||||
const owner = { runId: input.runId, processId: process.pid };
|
||||
|
||||
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||||
const server = createServer((socket) => sendOwner(socket, owner));
|
||||
const bound = await bind(server, socketPath);
|
||||
if (bound) {
|
||||
await chmod(socketPath, 0o600);
|
||||
let released = false;
|
||||
return {
|
||||
acquired: true,
|
||||
lease: {
|
||||
release: async () => {
|
||||
if (released) return;
|
||||
released = true;
|
||||
await closeServer(server);
|
||||
await rm(socketPath, { force: true });
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const existingOwner = await readOwner(socketPath);
|
||||
if (existingOwner !== undefined)
|
||||
return { acquired: false, owner: existingOwner };
|
||||
await rm(socketPath, { force: true });
|
||||
}
|
||||
|
||||
throw new Error("Could not acquire the Hopper target lease");
|
||||
};
|
||||
|
||||
const ensureLeaseDirectory = async (directory: string): Promise<void> => {
|
||||
await mkdir(directory, { recursive: true, mode: 0o700 });
|
||||
const directoryStat = await lstat(directory);
|
||||
if (
|
||||
directoryStat.isSymbolicLink() ||
|
||||
directoryStat.isDirectory() === false ||
|
||||
(process.getuid !== undefined && directoryStat.uid !== process.getuid())
|
||||
)
|
||||
throw new Error("Hopper target lease directory is not private");
|
||||
if ((directoryStat.mode & 0o077) !== 0) await chmod(directory, 0o700);
|
||||
};
|
||||
|
||||
const bind = (server: Server, socketPath: string): Promise<boolean> =>
|
||||
new Promise((resolveBind, reject) => {
|
||||
const onError = (error: NodeJS.ErrnoException): void => {
|
||||
server.removeListener("listening", onListening);
|
||||
if (error.code === "EADDRINUSE") resolveBind(false);
|
||||
else reject(error);
|
||||
};
|
||||
const onListening = (): void => {
|
||||
server.removeListener("error", onError);
|
||||
resolveBind(true);
|
||||
};
|
||||
server.once("error", onError);
|
||||
server.once("listening", onListening);
|
||||
server.listen(socketPath);
|
||||
});
|
||||
|
||||
const sendOwner = (socket: Socket, owner: HopperTargetLeaseOwner): void => {
|
||||
socket.end(`${JSON.stringify(owner)}\n`);
|
||||
};
|
||||
|
||||
const readOwner = (
|
||||
socketPath: string,
|
||||
): Promise<HopperTargetLeaseOwner | undefined> =>
|
||||
new Promise((resolveOwner) => {
|
||||
const socket = createConnection(socketPath);
|
||||
let response = "";
|
||||
const timer = setTimeout(() => {
|
||||
socket.destroy();
|
||||
resolveOwner(undefined);
|
||||
}, 250);
|
||||
const finish = (owner: HopperTargetLeaseOwner | undefined): void => {
|
||||
clearTimeout(timer);
|
||||
socket.destroy();
|
||||
resolveOwner(owner);
|
||||
};
|
||||
socket.on("data", (chunk: Buffer) => {
|
||||
response += chunk.toString("utf8");
|
||||
const newline = response.indexOf("\n");
|
||||
if (newline < 0) return;
|
||||
try {
|
||||
const value: unknown = JSON.parse(response.slice(0, newline));
|
||||
if (
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
typeof Reflect.get(value, "runId") === "string" &&
|
||||
typeof Reflect.get(value, "processId") === "number"
|
||||
)
|
||||
finish({
|
||||
runId: Reflect.get(value, "runId") as string,
|
||||
processId: Reflect.get(value, "processId") as number,
|
||||
});
|
||||
else finish(undefined);
|
||||
} catch {
|
||||
finish(undefined);
|
||||
}
|
||||
});
|
||||
socket.on("error", () => finish(undefined));
|
||||
socket.on("end", () => finish(undefined));
|
||||
});
|
||||
|
||||
const closeServer = (server: Server): Promise<void> =>
|
||||
new Promise((resolveClose, reject) => {
|
||||
if (!server.listening) {
|
||||
resolveClose();
|
||||
return;
|
||||
}
|
||||
server.close((error) => (error ? reject(error) : resolveClose()));
|
||||
});
|
||||
@@ -108,10 +108,8 @@ export const responseResult = (
|
||||
): Result<JsonValue, HopperRemoteError> =>
|
||||
"error" in response
|
||||
? err(
|
||||
new HopperRemoteError(
|
||||
response.error.code,
|
||||
response.error.message,
|
||||
response.error.type,
|
||||
),
|
||||
new HopperRemoteError(response.error.code, response.error.message, {
|
||||
diagnosticType: response.error.type,
|
||||
}),
|
||||
)
|
||||
: ok(response.result);
|
||||
|
||||
Reference in New Issue
Block a user