Skip to content

Commit 0cd1118

Browse files
fix(server): exit a plugin child on a corrupt IPC line and cover its failure paths
A line the child cannot parse now exits with code 1, the same way an oversized line does, instead of crashing on an uncaught exception. Adds focused tests for results with no JSON form, for the cleanup after a failed activation, and for the corrupt-line exit. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 4d4b221 commit 0cd1118

5 files changed

Lines changed: 140 additions & 1 deletion

File tree

‎apps/server/src/plugins/PluginSupervisor.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -510,6 +510,31 @@ it.layer(NodeServices.layer)("PluginSupervisor", (it) => {
510510
}),
511511
);
512512

513+
it.effect("fails results with no JSON form without stopping the plugin", () =>
514+
Effect.gen(function* () {
515+
const supervisor = yield* makeSupervisor();
516+
const { registration } = yield* preparePlugin("test.unserializable");
517+
const pluginId = registration.manifest.id;
518+
yield* supervisor.enable(registration);
519+
const pid = pidOf(yield* supervisor.invoke(pluginId, "ping", null));
520+
521+
for (const handler of ["functionResult", "symbolResult", "undefinedJsonResult"]) {
522+
const error = yield* supervisor.invoke(pluginId, handler, null).pipe(Effect.flip);
523+
expect(error._tag).toBe("PluginCallFailedError");
524+
expect(error.message).toBe(`Plugin ${pluginId} failed "${handler}": Result is not JSON.`);
525+
}
526+
// The serializer's own error is cut to the 2000 characters the server accepts.
527+
const thrown = yield* supervisor
528+
.invoke(pluginId, "throwingJsonResult", null)
529+
.pipe(Effect.flip);
530+
expect(thrown._tag).toBe("PluginCallFailedError");
531+
const prefix = `Plugin ${pluginId} failed "throwingJsonResult": `;
532+
expect(thrown.message.startsWith(`${prefix}Result is not JSON: xxx`)).toBe(true);
533+
expect(thrown.message.length).toBe(prefix.length + 2000);
534+
expect(pidOf(yield* supervisor.invoke(pluginId, "ping", null))).toBe(pid);
535+
}),
536+
);
537+
513538
it.effect("keeps one plugin's crash away from another", () =>
514539
Effect.gen(function* () {
515540
const supervisor = yield* makeSupervisor();
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
// @effect-diagnostics nodeBuiltinImport:off
2+
import * as NodeChildProcess from "node:child_process";
3+
import * as NodeReadline from "node:readline";
4+
import type * as NodeStream from "node:stream";
5+
6+
import { afterEach, describe, expect, it } from "@effect/vitest";
7+
8+
// Children run the real CLI entry, which routes `__plugin-host` to the child runtime.
9+
const BIN_PATH = `${import.meta.dirname}/../bin.ts`;
10+
const FIXTURE_DIR = `${import.meta.dirname}/testFixtures/plugin`;
11+
12+
const children = new Set<NodeChildProcess.ChildProcess>();
13+
afterEach(() => {
14+
for (const child of children) child.kill();
15+
children.clear();
16+
});
17+
18+
/** Speaks the raw fd 3 protocol with one plugin child, as the supervisor would. */
19+
const startChild = () => {
20+
const child = NodeChildProcess.spawn(process.execPath, [BIN_PATH, "__plugin-host"], {
21+
cwd: FIXTURE_DIR,
22+
stdio: ["ignore", "ignore", "ignore", "pipe"],
23+
});
24+
children.add(child);
25+
const exited = new Promise<[number | null, NodeJS.Signals | null]>((resolve) =>
26+
child.once("exit", (code, signal) => resolve([code, signal])),
27+
);
28+
const channel = child.stdio[3] as NodeStream.Duplex;
29+
const lines = NodeReadline.createInterface({ input: channel })[Symbol.asyncIterator]();
30+
return {
31+
exited,
32+
send: (line: string) => channel.write(`${line}\n`),
33+
read: async () => {
34+
const next = await lines.next();
35+
return next.done ? undefined : (JSON.parse(next.value) as Record<string, unknown>);
36+
},
37+
};
38+
};
39+
40+
const activateMessage = (entry: string) =>
41+
JSON.stringify({
42+
_tag: "Activate",
43+
pluginId: "test.child",
44+
version: "1.0.0",
45+
apiVersion: 1,
46+
entryPath: `${FIXTURE_DIR}/${entry}`,
47+
proposedApi: true,
48+
maxMessageBytes: 64 * 1024,
49+
capabilities: [],
50+
});
51+
52+
describe("plugin host child", () => {
53+
it("drops what a plugin registered before its activation failed", async () => {
54+
const child = startChild();
55+
child.send(activateMessage("registerThenFail.mjs"));
56+
// The activation signal aborts before the failure is reported.
57+
expect(await child.read()).toEqual({
58+
_tag: "Log",
59+
level: "info",
60+
message: "activation-aborted",
61+
});
62+
expect(await child.read()).toEqual({
63+
_tag: "ActivationFailed",
64+
message: "activation refused",
65+
});
66+
67+
child.send(JSON.stringify({ _tag: "Invoke", requestId: 1, handler: "leftover", input: null }));
68+
expect(await child.read()).toEqual({
69+
_tag: "Failed",
70+
requestId: 1,
71+
message: 'No handler named "leftover".',
72+
});
73+
74+
// Deactivation skips the module's deactivate: it never started.
75+
child.send(JSON.stringify({ _tag: "Deactivate" }));
76+
expect(await child.read()).toEqual({ _tag: "Deactivated" });
77+
expect(await child.read()).toBeUndefined();
78+
expect(await child.exited).toEqual([0, null]);
79+
});
80+
81+
it("exits with a failure on a line that is not JSON", async () => {
82+
const child = startChild();
83+
child.send("{not json");
84+
expect(await child.exited).toEqual([1, null]);
85+
});
86+
});

‎apps/server/src/plugins/pluginHostChild.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,13 @@ export const runPluginHostChild = (): void => {
169169
};
170170

171171
const receive = (line: string) => {
172-
const message = JSON.parse(line) as PluginHostMessage;
172+
let message: PluginHostMessage;
173+
try {
174+
message = JSON.parse(line) as PluginHostMessage;
175+
} catch {
176+
// A corrupt stream ends the child the same way an oversized line does.
177+
process.exit(1);
178+
}
173179
switch (message._tag) {
174180
case "Activate":
175181
void activate(message);

‎apps/server/src/plugins/testFixtures/plugin/main.mjs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,15 @@ export function activate(context) {
5555
for (;;) hog.push(Array.from({ length: 100_000 }, Math.random));
5656
});
5757
handle("bigResult", (input) => "x".repeat(input.bytes));
58+
// Results with no JSON form, which the child must answer with a failure.
59+
handle("functionResult", () => () => {});
60+
handle("symbolResult", () => Symbol("result"));
61+
handle("undefinedJsonResult", () => ({ toJSON: () => undefined }));
62+
handle("throwingJsonResult", () => ({
63+
toJSON() {
64+
throw new Error("x".repeat(3000));
65+
},
66+
}));
5867
handle("malformed", () => {
5968
NodeFS.writeSync(IPC_FD, "{not json}\n");
6069
return new Promise(() => {});
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// Registers a handler and watches its activation signal, then fails to activate.
2+
let log;
3+
4+
export function activate(context) {
5+
log = context.log;
6+
context.proposed.handle("leftover", () => "served after a failed activation");
7+
context.signal.addEventListener("abort", () => log.info("activation-aborted"));
8+
throw new Error("activation refused");
9+
}
10+
11+
export function deactivate() {
12+
log.info("deactivate-called");
13+
}

0 commit comments

Comments
 (0)