Files
rea/tests/support/cli/compiledCliWorker.mjs
647717c050 perf(javascript): reuse the source-analysis worker within a process (#5819)
* perf(javascript): reuse the source-analysis worker within a process

Each analyze-javascript-application call started a new Node worker.
That startup, not fixture IO or the shared CLI session, dominated the
slow loader-review and factory-completion files.

Park one healthy worker on the artifact resource scope and on the CLI
process. Stop it when the scope, session, or one-shot process ends.
Do not reuse after failure, cancellation, or a different heap or timeout.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(cli): close the JavaScript worker when dispatch throws

Minimal dispatcher runtimes now export a no-op closeCliJavaScriptResources,
and CLI dispatch plus output rendering always await that cleanup. A dispatch
failure and a cleanup failure are both reported.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(artifacts): report close-hook failures with retained cleanup

When retained cleanup and the scope close hook both fail, the close error
keeps both causes and both resource labels. The pending owners and the hook
stay registered so the next close retries each path.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(javascript): stop a replaced analysis worker before the next one starts

A heap or timeout change now closes the parked worker before constructing
its replacement. The scope retains that process only when the close fails.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* style: format worker-reuse close and launch helpers

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(cli): report a failed JavaScript worker shutdown before exit

Share one in-flight close and drop the CLI scope only after it succeeds,
so a later caller retries a worker that is still owned. The one-shot
exit callback writes that failure and exits non-zero, while a closed
stdout pipe still exits 141.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(javascript): keep a worker parked during an overlapping limit change

Claim the scope slot only when it is still empty after the replaced
worker closes. A concurrent analysis that parked another healthy worker
keeps that process, and the extra worker is closed through its own port.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(artifacts): run later close hooks when an earlier hook fails

Run every registered close hook on each close. One failure is returned
unchanged, and several failures are aggregated so a later hook is not
skipped.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(javascript): fail a limit change when the previous worker stays alive

A failed close used to be retained and then ignored, so MCP could return
a successful analysis while the old process and its replacement were
both owned. The request now fails before the replacement is constructed,
and the still-live worker stays owned for a later close.

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>
2026-10-21 19:01:20 +08:00

141 lines
4.0 KiB
JavaScript

import { Writable } from "node:stream";
import { createInterface } from "node:readline";
const { cliConfigurationError, closeCliJavaScriptResources, createCli } =
await import("../../../dist/cli-runtime/cli.js");
const { createCliResultOutput } =
await import("../../../dist/cli-runtime/cliResultOutput.js");
const {
normalizeCliArguments,
renderCliOutputArgumentError,
renderEmptyFilteredCliOutput,
validateCliOutputArguments,
} = await import("../../../dist/cli-runtime/cliOutput.js");
const MAX_STDOUT_CHARS = 16 * 1024 * 1024;
const writeMessage = (message) => {
process.stdout.write(`${JSON.stringify(message)}\n`);
};
// One CLI instance serves every command. A fresh instance per command retains
// its command registrations after the call returns; production exits instead.
const outputParts = [];
let outputCharacters = 0;
const destination = new Writable({
write(chunk, _encoding, callback) {
const text = Buffer.isBuffer(chunk)
? chunk.toString("utf8")
: String(chunk);
outputCharacters += text.length;
if (outputCharacters > MAX_STDOUT_CHARS) {
callback(new Error("Compiled CLI stdout exceeded 16 MiB"));
return;
}
outputParts.push(text);
callback();
},
});
Object.defineProperty(destination, "isTTY", { value: false });
const resultOutput = createCliResultOutput(["--json"], destination);
const cli = createCli(process.env, resultOutput);
const resetOutput = () => {
outputParts.length = 0;
outputCharacters = 0;
};
const runCommand = async (args) => {
const previousExitCode = process.exitCode;
process.exitCode = undefined;
resetOutput();
try {
const cliArgs = normalizeCliArguments(args);
const outputArguments = validateCliOutputArguments(cliArgs);
if (!outputArguments.ok)
return {
exitCode: 1,
stdout: renderCliOutputArgumentError(outputArguments),
};
const configurationError = cliConfigurationError(process.env);
if (configurationError !== undefined)
return { exitCode: 1, stdout: "", error: configurationError };
let wroteOutput = false;
let explicitExit;
try {
await cli.serve(cliArgs, {
stdout: (output) => {
if (resultOutput?.handled) return;
if (output.length === 0) return;
wroteOutput = true;
destination.write(output);
},
exit: (code) => {
explicitExit = code;
},
});
} catch (cause) {
return {
exitCode: 1,
stdout: outputParts.join(""),
error:
cause instanceof Error
? (cause.stack ?? cause.message)
: String(cause),
};
}
if (!wroteOutput && !resultOutput?.handled) {
const empty = renderEmptyFilteredCliOutput(cliArgs);
if (empty !== undefined) destination.write(empty);
}
// logCliCommand reports some failures only through process.exitCode.
return {
exitCode:
explicitExit ??
(typeof process.exitCode === "number" ? process.exitCode : 0),
stdout: outputParts.join(""),
};
} finally {
process.exitCode = previousExitCode;
}
};
const acceptRequest = async (line) => {
let request;
try {
request = JSON.parse(line);
} catch (cause) {
writeMessage({
id: -1,
exitCode: 1,
stdout: "",
error: cause instanceof Error ? cause.message : String(cause),
});
return;
}
const args = request?.args;
if (
typeof request?.id !== "number" ||
!Array.isArray(args) ||
args.some((argument) => typeof argument !== "string")
) {
writeMessage({
id: typeof request?.id === "number" ? request.id : -1,
exitCode: 1,
stdout: "",
error: "Compiled CLI session expected an id and string arguments",
});
return;
}
writeMessage({ id: request.id, ...(await runCommand(args)) });
};
const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
writeMessage({ ready: true });
for await (const line of lines) {
if (line.trim().length === 0) continue;
await acceptRequest(line);
}
await closeCliJavaScriptResources();