Skip to content

Commit 942858f

Browse files
committed
fix(plugin-sdk): abort interrupted API diffs
1 parent 9c6757c commit 942858f

2 files changed

Lines changed: 181 additions & 33 deletions

File tree

‎scripts/plugin-sdk-api-diff.mts‎

Lines changed: 83 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#!/usr/bin/env node
2-
import { spawnSync } from "node:child_process";
2+
import { spawn, spawnSync } from "node:child_process";
33
import fs from "node:fs/promises";
44
import os from "node:os";
55
import path from "node:path";
@@ -122,32 +122,67 @@ function git(repoRoot: string, args: string[]): string {
122122
return result.stdout.trim();
123123
}
124124

125-
function installRevisionDependencies(repoRoot: string): void {
126-
const result = spawnSync(
127-
"pnpm",
128-
["install", "--frozen-lockfile", "--ignore-scripts", "--filter", "openclaw"],
129-
{
130-
cwd: repoRoot,
131-
encoding: "utf8",
132-
maxBuffer: GIT_MAX_BUFFER,
133-
},
134-
);
135-
if (result.status !== 0) {
136-
throw new Error(
137-
result.stderr.trim() || result.stdout.trim() || "Plugin SDK revision install failed",
138-
);
139-
}
125+
async function runAbortableChild(params: {
126+
args: string[];
127+
command: string;
128+
cwd: string;
129+
failureMessage: string;
130+
signal: AbortSignal;
131+
}): Promise<void> {
132+
let stdout = "";
133+
let stderr = "";
134+
let spawnError: Error | undefined;
135+
await new Promise<void>((resolve, reject) => {
136+
const child = spawn(params.command, params.args, {
137+
cwd: params.cwd,
138+
signal: params.signal,
139+
stdio: ["ignore", "pipe", "pipe"],
140+
});
141+
child.stdout.setEncoding("utf8");
142+
child.stderr.setEncoding("utf8");
143+
child.stdout.on("data", (chunk: string) => {
144+
stdout += chunk.slice(0, Math.max(0, GIT_MAX_BUFFER - stdout.length));
145+
});
146+
child.stderr.on("data", (chunk: string) => {
147+
stderr += chunk.slice(0, Math.max(0, GIT_MAX_BUFFER - stderr.length));
148+
});
149+
child.on("error", (error) => {
150+
spawnError = error;
151+
});
152+
child.on("close", (code) => {
153+
if (code === 0) {
154+
resolve();
155+
return;
156+
}
157+
reject(spawnError ?? new Error(stderr.trim() || stdout.trim() || params.failureMessage));
158+
});
159+
});
160+
}
161+
162+
async function installRevisionDependencies(repoRoot: string, signal: AbortSignal): Promise<void> {
163+
await runAbortableChild({
164+
command: "pnpm",
165+
args: ["install", "--frozen-lockfile", "--ignore-scripts", "--filter", "openclaw"],
166+
cwd: repoRoot,
167+
failureMessage: "Plugin SDK revision install failed",
168+
signal,
169+
});
140170
}
141171

142172
async function writeFile(filePath: string, content: string): Promise<void> {
143173
await fs.mkdir(path.dirname(filePath), { recursive: true });
144174
await fs.writeFile(filePath, content, "utf8");
145175
}
146176

147-
function renderRevision(repoRoot: string, revisionRoot: string, outputPath: string): void {
148-
const result = spawnSync(
149-
process.execPath,
150-
[
177+
async function renderRevision(
178+
repoRoot: string,
179+
revisionRoot: string,
180+
outputPath: string,
181+
signal: AbortSignal,
182+
): Promise<void> {
183+
await runAbortableChild({
184+
command: process.execPath,
185+
args: [
151186
"--max-old-space-size=6144",
152187
"--import",
153188
"tsx",
@@ -157,15 +192,10 @@ function renderRevision(repoRoot: string, revisionRoot: string, outputPath: stri
157192
"--output",
158193
outputPath,
159194
],
160-
{
161-
cwd: repoRoot,
162-
encoding: "utf8",
163-
maxBuffer: GIT_MAX_BUFFER,
164-
},
165-
);
166-
if (result.status !== 0) {
167-
throw new Error(result.stderr.trim() || result.stdout.trim() || "Plugin SDK API render failed");
168-
}
195+
cwd: repoRoot,
196+
failureMessage: "Plugin SDK API render failed",
197+
signal,
198+
});
169199
}
170200

171201
async function renderWorker(argv: string[]): Promise<boolean> {
@@ -196,6 +226,8 @@ async function main(): Promise<void> {
196226
{ commit: headCommit, name: "head" },
197227
] as const;
198228
const addedWorktrees: string[] = [];
229+
const abortController = new AbortController();
230+
let interruptedExitCode: number | undefined;
199231
let cleanupPromise: Promise<void> | undefined;
200232
const cleanup = (): Promise<void> => {
201233
cleanupPromise ??= (async () => {
@@ -216,7 +248,8 @@ async function main(): Promise<void> {
216248
return cleanupPromise;
217249
};
218250
const stop = (exitCode: number): void => {
219-
void cleanup().finally(() => process.exit(exitCode));
251+
interruptedExitCode ??= exitCode;
252+
abortController.abort();
220253
};
221254
const stopOnInterrupt = (): void => stop(130);
222255
const stopOnTerminate = (): void => stop(143);
@@ -230,13 +263,23 @@ async function main(): Promise<void> {
230263
addedWorktrees.push(worktree);
231264
git(worktree, ["sparse-checkout", "set", "src", "packages", "patches", "scripts"]);
232265
git(worktree, ["checkout", "--detach", root.commit]);
233-
installRevisionDependencies(worktree);
266+
await installRevisionDependencies(worktree, abortController.signal);
234267
}
235268

236269
const baseRenderPath = path.join(temporaryRoot, "base.json");
237270
const headRenderPath = path.join(temporaryRoot, "head.json");
238-
renderRevision(repoRoot, path.join(temporaryRoot, "base"), baseRenderPath);
239-
renderRevision(repoRoot, path.join(temporaryRoot, "head"), headRenderPath);
271+
await renderRevision(
272+
repoRoot,
273+
path.join(temporaryRoot, "base"),
274+
baseRenderPath,
275+
abortController.signal,
276+
);
277+
await renderRevision(
278+
repoRoot,
279+
path.join(temporaryRoot, "head"),
280+
headRenderPath,
281+
abortController.signal,
282+
);
240283
const before = parsePluginSdkApiDiffSurface(await fs.readFile(baseRenderPath, "utf8"));
241284
const after = parsePluginSdkApiDiffSurface(await fs.readFile(headRenderPath, "utf8"));
242285
const diff = diffPluginSdkApi(before, after);
@@ -272,11 +315,18 @@ async function main(): Promise<void> {
272315
process.exitCode = 1;
273316
}
274317
}
318+
} catch (error) {
319+
if (interruptedExitCode === undefined) {
320+
throw error instanceof Error ? error : new Error("Plugin SDK API diff failed");
321+
}
275322
} finally {
276323
process.off("SIGINT", stopOnInterrupt);
277324
process.off("SIGTERM", stopOnTerminate);
278325
await cleanup();
279326
}
327+
if (interruptedExitCode !== undefined) {
328+
process.exitCode = interruptedExitCode;
329+
}
280330
}
281331

282332
const run = renderWorker(process.argv.slice(2)).then((handled) => (handled ? undefined : main()));
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
import { execFileSync, spawn } from "node:child_process";
2+
import { chmodSync, existsSync, readdirSync, writeFileSync } from "node:fs";
3+
import { delimiter, join, resolve } from "node:path";
4+
import { afterEach, describe, expect, it } from "vitest";
5+
import { useAutoCleanupTempDirTracker } from "../helpers/temp-dir.js";
6+
7+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
8+
9+
function git(repo: string, args: string[]): string {
10+
return execFileSync("git", args, { cwd: repo, encoding: "utf8" });
11+
}
12+
13+
async function waitFor(check: () => boolean, timeoutMs: number): Promise<void> {
14+
const deadline = Date.now() + timeoutMs;
15+
while (!check()) {
16+
if (Date.now() >= deadline) {
17+
throw new Error("timed out waiting for Plugin SDK API diff child");
18+
}
19+
await new Promise((resolveWait) => {
20+
setTimeout(resolveWait, 25);
21+
});
22+
}
23+
}
24+
25+
describe("Plugin SDK API diff CLI", () => {
26+
it("interrupts a running child and removes its registered worktree", async () => {
27+
const repo = git(process.cwd(), ["rev-parse", "--show-toplevel"]).trim();
28+
const runnerTemp = tempDirs.make("plugin-sdk-api-diff-temp-");
29+
const binDir = tempDirs.make("plugin-sdk-api-diff-bin-");
30+
const pnpmMarker = join(binDir, "pnpm-started");
31+
32+
const fakePnpm = join(binDir, "pnpm");
33+
writeFileSync(
34+
fakePnpm,
35+
"#!/bin/sh\n: > \"$PNPM_MARKER\"\ntrap 'exit 143' INT TERM\nwhile :; do sleep 1; done\n",
36+
);
37+
chmodSync(fakePnpm, 0o755);
38+
39+
const child = spawn(
40+
process.execPath,
41+
[
42+
"--import",
43+
import.meta.resolve("tsx"),
44+
resolve("scripts/plugin-sdk-api-diff.mts"),
45+
"--base",
46+
"HEAD",
47+
"--head",
48+
"HEAD",
49+
],
50+
{
51+
cwd: repo,
52+
env: {
53+
...process.env,
54+
PATH: `${binDir}${delimiter}${process.env.PATH ?? ""}`,
55+
PNPM_MARKER: pnpmMarker,
56+
RUNNER_TEMP: runnerTemp,
57+
},
58+
stdio: ["ignore", "ignore", "pipe"],
59+
},
60+
);
61+
62+
let closed = false;
63+
let stderr = "";
64+
child.stderr.setEncoding("utf8");
65+
child.stderr.on("data", (chunk: string) => {
66+
stderr += chunk;
67+
});
68+
const close = new Promise<number | null>((resolveClose) => {
69+
child.once("close", (code) => {
70+
closed = true;
71+
resolveClose(code);
72+
});
73+
});
74+
try {
75+
await waitFor(() => existsSync(pnpmMarker) || closed, 10_000);
76+
expect(closed, stderr).toBe(false);
77+
expect(git(repo, ["worktree", "list"])).toContain(runnerTemp);
78+
const interruptedAt = Date.now();
79+
child.kill("SIGTERM");
80+
const exitCode = await Promise.race([
81+
close,
82+
new Promise<never>((_, reject) => {
83+
setTimeout(() => reject(new Error("Plugin SDK API diff ignored SIGTERM")), 5_000);
84+
}),
85+
]);
86+
87+
expect(exitCode).toBe(143);
88+
expect(Date.now() - interruptedAt).toBeLessThan(5_000);
89+
expect(git(repo, ["worktree", "list"])).not.toContain(runnerTemp);
90+
expect(readdirSync(runnerTemp)).toEqual([]);
91+
} finally {
92+
if (!closed) {
93+
child.kill("SIGKILL");
94+
await close;
95+
}
96+
}
97+
}, 15_000);
98+
});

0 commit comments

Comments
 (0)