Propagate ACP child exits through protocol termination
- Thread child-process exit codes into protocol shutdown - Distinguish stream end, decode failure, and process exit errors - Add protocol coverage for pending requests and late responses
This commit is contained in:
1 parent
19f0e8a083
commit
e43002eaf1
5 files changed
+306
-45
No files matched your search
@@ -284,6 +284,15 @@ export const fromChildProcess = Effect.fnUntraced(function* (
|
||||
const handlers = options.handlers ?? {};
|
||||
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
||||
stdio: makeStdioFromChildProcess(handle),
|
||||
processExit: handle.exitCode.pipe(
|
||||
Effect.map(Number),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AcpError.AcpProcessExitedError({
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
serverRequestMethods: new Set(AcpRpcs.ClientRpcs.requests.keys()),
|
||||
...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),
|
||||
...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),
|
||||
|
||||
@@ -22,8 +22,8 @@ export class AcpProcessExitedError extends Schema.TaggedErrorClass<AcpProcessExi
|
||||
) {
|
||||
override get message() {
|
||||
return this.code === undefined
|
||||
? "ACP process exited unexpectedly"
|
||||
: `ACP process exited unexpectedly with code ${this.code}`;
|
||||
? "ACP process exited"
|
||||
: `ACP process exited with code ${this.code}`;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import * as Path from "effect/Path";
|
||||
import * as AcpError from "./errors";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
@@ -7,6 +9,8 @@ import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stdio from "effect/Stdio";
|
||||
import * as Ref from "effect/Ref";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { it, assert } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
@@ -22,7 +26,7 @@ const decodeJson = Schema.decodeUnknownSync(UnknownJson);
|
||||
|
||||
function makeInMemoryStdio() {
|
||||
return Effect.gen(function* () {
|
||||
const input = yield* Queue.unbounded<Uint8Array>();
|
||||
const input = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>();
|
||||
const output = yield* Queue.unbounded<string>();
|
||||
|
||||
return {
|
||||
@@ -41,6 +45,48 @@ function makeInMemoryStdio() {
|
||||
});
|
||||
}
|
||||
|
||||
const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
|
||||
path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
|
||||
);
|
||||
|
||||
const makeHandle = (env?: Record<string, string>) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const path = yield* Path.Path;
|
||||
const command = ChildProcess.make("bun", ["run", yield* mockPeerPath], {
|
||||
cwd: path.join(import.meta.dirname, ".."),
|
||||
shell: process.platform === "win32",
|
||||
...(env ? { env: { ...process.env, ...env } } : {}),
|
||||
});
|
||||
return yield* spawner.spawn(command);
|
||||
});
|
||||
|
||||
function makeChildStdio(handle: ChildProcessSpawner.ChildProcessHandle) {
|
||||
return Stdio.make({
|
||||
args: Effect.succeed([]),
|
||||
stdin: handle.stdout,
|
||||
stdout: () =>
|
||||
Sink.mapInput(handle.stdin, (chunk: string | Uint8Array) =>
|
||||
typeof chunk === "string" ? encoder.encode(chunk) : chunk,
|
||||
),
|
||||
stderr: () => Sink.drain,
|
||||
});
|
||||
}
|
||||
|
||||
function makeProcessExit(
|
||||
handle: ChildProcessSpawner.ChildProcessHandle,
|
||||
): Effect.Effect<number, AcpError.AcpProcessExitedError> {
|
||||
return handle.exitCode.pipe(
|
||||
Effect.map(Number),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AcpError.AcpProcessExitedError({
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
|
||||
it.effect(
|
||||
"emits exact JSON-RPC notifications and decodes inbound session/update and elicitation completion",
|
||||
@@ -218,4 +264,147 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
|
||||
assert.deepEqual(resolved, { ok: true });
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("cleans up interrupted extension requests before a late response arrives", () =>
|
||||
Effect.gen(function* () {
|
||||
const { stdio, input, output } = yield* makeInMemoryStdio();
|
||||
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
||||
stdio,
|
||||
serverRequestMethods: new Set(),
|
||||
});
|
||||
const lateResponse = yield* Deferred.make<unknown>();
|
||||
|
||||
yield* transport.clientProtocol
|
||||
.run((message) => Deferred.succeed(lateResponse, message).pipe(Effect.asVoid))
|
||||
.pipe(Effect.forkScoped);
|
||||
|
||||
const response = yield* transport
|
||||
.sendRequest("x/test", { hello: "world" })
|
||||
.pipe(Effect.forkScoped);
|
||||
const outbound = yield* Queue.take(output);
|
||||
assert.deepEqual(decodeJson(outbound), {
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
method: "x/test",
|
||||
params: {
|
||||
hello: "world",
|
||||
},
|
||||
headers: [],
|
||||
});
|
||||
|
||||
yield* Fiber.interrupt(response);
|
||||
yield* Queue.offer(
|
||||
input,
|
||||
encoder.encode(
|
||||
`${encodeJson({
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
result: {
|
||||
ok: true,
|
||||
},
|
||||
})}\n`,
|
||||
),
|
||||
);
|
||||
|
||||
const message = yield* Deferred.await(lateResponse);
|
||||
assert.deepEqual(message, {
|
||||
_tag: "Exit",
|
||||
requestId: "1",
|
||||
exit: {
|
||||
_tag: "Success",
|
||||
value: {
|
||||
ok: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("propagates the real child exit code when the input stream ends", () =>
|
||||
Effect.gen(function* () {
|
||||
const handle = yield* makeHandle({ ACP_MOCK_EXIT_IMMEDIATELY_CODE: "7" });
|
||||
const firstMessage = yield* Deferred.make<unknown>();
|
||||
const processExit = yield* Deferred.make<AcpError.AcpProcessExitedError>();
|
||||
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
||||
stdio: makeChildStdio(handle),
|
||||
processExit: makeProcessExit(handle),
|
||||
serverRequestMethods: new Set(),
|
||||
onProcessExit: (error) => Deferred.succeed(processExit, error).pipe(Effect.asVoid),
|
||||
});
|
||||
|
||||
yield* transport.clientProtocol
|
||||
.run((message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
|
||||
.pipe(Effect.forkScoped);
|
||||
|
||||
const message = yield* Deferred.await(firstMessage);
|
||||
const exitError = yield* Deferred.await(processExit);
|
||||
assert.instanceOf(exitError, AcpError.AcpProcessExitedError);
|
||||
assert.equal(exitError.code, 7);
|
||||
assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
|
||||
const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
|
||||
readonly _tag: string;
|
||||
readonly cause: unknown;
|
||||
};
|
||||
assert.equal(defect._tag, "RpcClientDefect");
|
||||
assert.instanceOf(defect.cause, AcpError.AcpProcessExitedError);
|
||||
assert.equal((defect.cause as AcpError.AcpProcessExitedError).code, 7);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not emit a second process-exit error after a decode failure", () =>
|
||||
Effect.gen(function* () {
|
||||
const handle = yield* makeHandle({
|
||||
ACP_MOCK_MALFORMED_OUTPUT: "1",
|
||||
ACP_MOCK_MALFORMED_OUTPUT_EXIT_CODE: "23",
|
||||
});
|
||||
const processExitCalls = yield* Ref.make(0);
|
||||
const firstMessage = yield* Deferred.make<unknown>();
|
||||
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
||||
stdio: makeChildStdio(handle),
|
||||
processExit: makeProcessExit(handle),
|
||||
serverRequestMethods: new Set(),
|
||||
onProcessExit: () => Ref.update(processExitCalls, (count) => count + 1),
|
||||
});
|
||||
|
||||
yield* transport.clientProtocol
|
||||
.run((message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
|
||||
.pipe(Effect.forkScoped);
|
||||
|
||||
const message = yield* Deferred.await(firstMessage);
|
||||
assert.equal(yield* Ref.get(processExitCalls), 0);
|
||||
assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
|
||||
const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
|
||||
readonly _tag: string;
|
||||
readonly cause: unknown;
|
||||
};
|
||||
assert.equal(defect._tag, "RpcClientDefect");
|
||||
assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails pending extension requests with the propagated exit code", () =>
|
||||
Effect.gen(function* () {
|
||||
const { stdio, input, output } = yield* makeInMemoryStdio();
|
||||
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
||||
stdio,
|
||||
processExit: Effect.succeed(0),
|
||||
serverRequestMethods: new Set(),
|
||||
});
|
||||
|
||||
const response = yield* transport
|
||||
.sendRequest("x/test", { hello: "world" })
|
||||
.pipe(Effect.forkScoped);
|
||||
yield* Queue.take(output);
|
||||
yield* Queue.end(input);
|
||||
|
||||
const error = yield* Fiber.join(response).pipe(
|
||||
Effect.match({
|
||||
onFailure: (error) => error,
|
||||
onSuccess: () => assert.fail("Expected request to fail after process exit"),
|
||||
}),
|
||||
);
|
||||
assert.instanceOf(error, AcpError.AcpProcessExitedError);
|
||||
assert.equal(error.code, 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -42,6 +42,7 @@ export type AcpIncomingNotification =
|
||||
|
||||
export interface AcpPatchedProtocolOptions {
|
||||
readonly stdio: Stdio.Stdio;
|
||||
readonly processExit?: Effect.Effect<number | null, AcpError.AcpProcessExitedError>;
|
||||
readonly serverRequestMethods: ReadonlySet<string>;
|
||||
readonly logIncoming?: boolean;
|
||||
readonly logOutgoing?: boolean;
|
||||
@@ -94,6 +95,7 @@ export const makeAcpPatchedProtocol = (
|
||||
const disconnects = yield* Queue.unbounded<number>();
|
||||
const outgoing = yield* Queue.unbounded<string | Uint8Array, Cause.Done<void>>();
|
||||
const nextRequestId = yield* Ref.make(1n);
|
||||
const terminationHandled = yield* Ref.make(false);
|
||||
const extPending = yield* Ref.make(
|
||||
new Map<string, Deferred.Deferred<unknown, AcpError.AcpError>>(),
|
||||
);
|
||||
@@ -152,6 +154,16 @@ export const makeAcpPatchedProtocol = (
|
||||
return [onFound(deferred), next] as const;
|
||||
}).pipe(Effect.flatten);
|
||||
|
||||
const removeExtPending = (requestId: string) =>
|
||||
Ref.update(extPending, (pending) => {
|
||||
if (!pending.has(requestId)) {
|
||||
return pending;
|
||||
}
|
||||
const next = new Map(pending);
|
||||
next.delete(requestId);
|
||||
return next;
|
||||
});
|
||||
|
||||
const completeExtPendingFailure = (requestId: string, error: AcpError.AcpError) =>
|
||||
resolveExtPending(requestId, (deferred) => Deferred.fail(deferred, error));
|
||||
|
||||
@@ -178,6 +190,47 @@ export const makeAcpPatchedProtocol = (
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
const emitClientProtocolError = (error: AcpError.AcpError) =>
|
||||
Queue.offer(clientQueue, {
|
||||
_tag: "ClientProtocolError",
|
||||
error: new RpcClientError.RpcClientError({
|
||||
reason: new RpcClientError.RpcClientDefect({
|
||||
message: error.message,
|
||||
cause: error,
|
||||
}),
|
||||
}),
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const handleTermination = (
|
||||
classify: () => Effect.Effect<
|
||||
| {
|
||||
readonly error: AcpError.AcpError;
|
||||
readonly processExitError?: AcpError.AcpProcessExitedError | undefined;
|
||||
}
|
||||
| undefined
|
||||
>,
|
||||
) =>
|
||||
Ref.modify(terminationHandled, (handled) => {
|
||||
if (handled) {
|
||||
return [Effect.void, true] as const;
|
||||
}
|
||||
return [
|
||||
Effect.gen(function* () {
|
||||
yield* Queue.offer(disconnects, 0);
|
||||
const terminated = yield* classify();
|
||||
if (!terminated) {
|
||||
return;
|
||||
}
|
||||
yield* failAllExtPending(terminated.error);
|
||||
yield* emitClientProtocolError(terminated.error);
|
||||
if (terminated.processExitError && options.onProcessExit) {
|
||||
yield* options.onProcessExit(terminated.processExitError);
|
||||
}
|
||||
}),
|
||||
true,
|
||||
] as const;
|
||||
}).pipe(Effect.flatten);
|
||||
|
||||
const respondWithSuccess = (requestId: string, value: unknown) =>
|
||||
offerOutgoing({
|
||||
_tag: "Exit",
|
||||
@@ -376,43 +429,46 @@ export const makeAcpPatchedProtocol = (
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.catch((error) => {
|
||||
const normalized: AcpError.AcpError = Schema.is(AcpError.AcpError)(error)
|
||||
? error
|
||||
: new AcpError.AcpTransportError({
|
||||
detail: error instanceof Error ? error.message : String(error),
|
||||
cause: error,
|
||||
});
|
||||
const rpcClientError = new RpcClientError.RpcClientError({
|
||||
reason: new RpcClientError.RpcClientDefect({
|
||||
message: normalized.message,
|
||||
cause: normalized,
|
||||
}),
|
||||
});
|
||||
return Queue.offer(clientQueue, {
|
||||
_tag: "ClientProtocolError",
|
||||
error: rpcClientError,
|
||||
}).pipe(Effect.asVoid);
|
||||
}),
|
||||
Effect.ensuring(
|
||||
Effect.gen(function* () {
|
||||
const error = new AcpError.AcpProcessExitedError({});
|
||||
yield* Queue.offer(disconnects, 0);
|
||||
yield* failAllExtPending(error);
|
||||
yield* Queue.offer(clientQueue, {
|
||||
_tag: "ClientProtocolError",
|
||||
error: new RpcClientError.RpcClientError({
|
||||
reason: new RpcClientError.RpcClientDefect({
|
||||
message: error.message,
|
||||
Effect.matchEffect({
|
||||
onFailure: (error) => {
|
||||
const normalized: AcpError.AcpError = Schema.is(AcpError.AcpError)(error)
|
||||
? error
|
||||
: new AcpError.AcpTransportError({
|
||||
detail: error instanceof Error ? error.message : String(error),
|
||||
cause: error,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
if (options.onProcessExit) {
|
||||
yield* options.onProcessExit(error);
|
||||
}
|
||||
}),
|
||||
),
|
||||
});
|
||||
return handleTermination(() => Effect.succeed({ error: normalized }));
|
||||
},
|
||||
onSuccess: () =>
|
||||
handleTermination(() =>
|
||||
options.processExit
|
||||
? options.processExit.pipe(
|
||||
Effect.match({
|
||||
onFailure: (processExitError) =>
|
||||
({
|
||||
error: processExitError,
|
||||
processExitError,
|
||||
}) as const,
|
||||
onSuccess: (code) => {
|
||||
const processExitError =
|
||||
code === null
|
||||
? new AcpError.AcpProcessExitedError({})
|
||||
: new AcpError.AcpProcessExitedError({ code });
|
||||
return {
|
||||
error: processExitError,
|
||||
processExitError,
|
||||
} as const;
|
||||
},
|
||||
}),
|
||||
)
|
||||
: Effect.succeed({
|
||||
error: new AcpError.AcpTransportError({
|
||||
detail: "ACP input stream ended",
|
||||
cause: new Error("ACP input stream ended"),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
@@ -473,14 +529,12 @@ export const makeAcpPatchedProtocol = (
|
||||
headers: [],
|
||||
}).pipe(
|
||||
Effect.catch((error) =>
|
||||
Ref.update(extPending, (pending) => {
|
||||
const next = new Map(pending);
|
||||
next.delete(String(requestId));
|
||||
return next;
|
||||
}).pipe(Effect.andThen(Effect.fail(error))),
|
||||
removeExtPending(String(requestId)).pipe(Effect.andThen(Effect.fail(error))),
|
||||
),
|
||||
);
|
||||
return yield* Deferred.await(deferred);
|
||||
return yield* Deferred.await(deferred).pipe(
|
||||
Effect.onInterrupt(() => removeExtPending(String(requestId))),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -5,6 +5,15 @@ const rl = createInterface({
|
||||
crlfDelay: Infinity,
|
||||
});
|
||||
|
||||
if (process.env.ACP_MOCK_MALFORMED_OUTPUT === "1") {
|
||||
process.stdout.write("{not-json}\n");
|
||||
process.exit(Number(process.env.ACP_MOCK_MALFORMED_OUTPUT_EXIT_CODE ?? "0"));
|
||||
}
|
||||
|
||||
if (process.env.ACP_MOCK_EXIT_IMMEDIATELY_CODE !== undefined) {
|
||||
process.exit(Number(process.env.ACP_MOCK_EXIT_IMMEDIATELY_CODE));
|
||||
}
|
||||
|
||||
let nextRequestId = 1000;
|
||||
const pending = new Map<
|
||||
number | string,
|
||||
|
||||
Reference in new issue
Block a user