Skip to content

Commit 88c1af0

Browse files
committed
fix(tooling): bound generated formatter execution
1 parent 6a0fdea commit 88c1af0

2 files changed

Lines changed: 187 additions & 11 deletions

File tree

‎scripts/lib/format-generated-module.mjs‎

Lines changed: 62 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@ import os from "node:os";
55
import path from "node:path";
66
import { resolvePnpmRunner } from "../pnpm-runner.mjs";
77

8+
export const GENERATED_MODULE_FORMAT_TIMEOUT_MS = 30_000;
9+
export const GENERATED_MODULE_FORMAT_MAX_BUFFER_BYTES = 1024 * 1024;
10+
const FORMATTER_OUTPUT_TAIL_BYTES = 16 * 1024;
11+
812
/** Resolve the fastest available oxfmt command for a generated module path. */
913
export function resolveGeneratedModuleFormatter(params) {
1014
const platform = params.platform ?? process.platform;
@@ -28,8 +32,59 @@ export function resolveGeneratedModuleFormatter(params) {
2832
});
2933
}
3034

35+
function outputText(value) {
36+
if (typeof value === "string") {
37+
return value;
38+
}
39+
if (Buffer.isBuffer(value)) {
40+
return value.toString("utf8");
41+
}
42+
return "";
43+
}
44+
45+
function outputTail(value) {
46+
const text = outputText(value).trim();
47+
if (!text) {
48+
return "";
49+
}
50+
const bytes = Buffer.from(text, "utf8");
51+
if (bytes.byteLength <= FORMATTER_OUTPUT_TAIL_BYTES) {
52+
return text;
53+
}
54+
return bytes.subarray(bytes.byteLength - FORMATTER_OUTPUT_TAIL_BYTES).toString("utf8");
55+
}
56+
57+
function formatterFailureDetails(formatter) {
58+
const details = [];
59+
const errorCode = formatter.error?.code;
60+
if (errorCode === "ETIMEDOUT") {
61+
details.push(`formatter timed out after ${GENERATED_MODULE_FORMAT_TIMEOUT_MS}ms`);
62+
} else if (errorCode === "ENOBUFS") {
63+
details.push(`formatter output exceeded ${GENERATED_MODULE_FORMAT_MAX_BUFFER_BYTES} bytes`);
64+
} else if (formatter.error?.message) {
65+
details.push(formatter.error.message);
66+
}
67+
if (formatter.status !== null && formatter.status !== undefined && formatter.status !== 0) {
68+
details.push(`formatter exited with status ${formatter.status}`);
69+
}
70+
if (formatter.signal) {
71+
details.push(`formatter exited with signal ${formatter.signal}`);
72+
}
73+
const stderrTail = outputTail(formatter.stderr);
74+
if (stderrTail) {
75+
details.push(`stderr tail:\n${stderrTail}`);
76+
}
77+
const stdoutTail = outputTail(formatter.stdout);
78+
if (stdoutTail) {
79+
details.push(`stdout tail:\n${stdoutTail}`);
80+
}
81+
return details.join("\n") || "unknown formatter failure";
82+
}
83+
3184
/** Format generated source in a temporary file and return the formatter output. */
32-
export function formatGeneratedModule(source, { repoRoot, outputPath, errorLabel }) {
85+
export function formatGeneratedModule(source, { repoRoot, outputPath, errorLabel }, deps = {}) {
86+
const spawnSyncImpl = deps.spawnSync ?? spawnSync;
87+
const resolveFormatter = deps.resolveFormatter ?? resolveGeneratedModuleFormatter;
3388
const resolvedRepoRoot = path.resolve(repoRoot);
3489
const resolvedOutputPath = path.resolve(
3590
resolvedRepoRoot,
@@ -40,24 +95,22 @@ export function formatGeneratedModule(source, { repoRoot, outputPath, errorLabel
4095

4196
try {
4297
fs.writeFileSync(tempOutputPath, source, "utf8");
43-
const command = resolveGeneratedModuleFormatter({
98+
const command = resolveFormatter({
4499
existsSync: fs.existsSync,
45100
outputPath: tempOutputPath,
46101
repoRoot: resolvedRepoRoot,
47102
});
48-
const formatter = spawnSync(command.command, command.args, {
103+
const formatter = spawnSyncImpl(command.command, command.args, {
49104
cwd: resolvedRepoRoot,
50105
encoding: "utf8",
51106
env: command.env ?? process.env,
107+
maxBuffer: GENERATED_MODULE_FORMAT_MAX_BUFFER_BYTES,
52108
shell: command.shell,
109+
timeout: GENERATED_MODULE_FORMAT_TIMEOUT_MS,
53110
windowsVerbatimArguments: command.windowsVerbatimArguments,
54111
});
55-
if (formatter.status !== 0) {
56-
const details =
57-
formatter.stderr?.trim() ||
58-
formatter.stdout?.trim() ||
59-
formatter.error?.message ||
60-
"unknown formatter failure";
112+
if (formatter.error || formatter.status !== 0) {
113+
const details = formatterFailureDetails(formatter);
61114
throw new Error(`failed to format generated ${errorLabel}: ${details}`);
62115
}
63116
return fs.readFileSync(tempOutputPath, "utf8");

‎test/scripts/format-generated-module.test.ts‎

Lines changed: 125 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,31 @@
11
// Format Generated Module tests cover format generated module script behavior.
2+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3+
import os from "node:os";
24
import path from "node:path";
3-
import { describe, expect, it } from "vitest";
4-
import { resolveGeneratedModuleFormatter } from "../../scripts/lib/format-generated-module.mjs";
5+
import { afterEach, describe, expect, it } from "vitest";
6+
import {
7+
formatGeneratedModule,
8+
GENERATED_MODULE_FORMAT_MAX_BUFFER_BYTES,
9+
GENERATED_MODULE_FORMAT_TIMEOUT_MS,
10+
resolveGeneratedModuleFormatter,
11+
} from "../../scripts/lib/format-generated-module.mjs";
12+
13+
const tempDirs: string[] = [];
14+
15+
function makeRepoRoot() {
16+
const repoRoot = mkdtempSync(path.join(os.tmpdir(), "openclaw-format-generated-module-"));
17+
tempDirs.push(repoRoot);
18+
const formatterDir = path.join(repoRoot, "node_modules", ".bin");
19+
mkdirSync(formatterDir, { recursive: true });
20+
writeFileSync(path.join(formatterDir, "oxfmt"), "#!/bin/sh\n", "utf8");
21+
return repoRoot;
22+
}
23+
24+
afterEach(() => {
25+
for (const dir of tempDirs.splice(0)) {
26+
rmSync(dir, { force: true, recursive: true });
27+
}
28+
});
529

630
describe("resolveGeneratedModuleFormatter", () => {
731
it("uses the direct formatter binary on non-Windows when available", () => {
@@ -43,4 +67,103 @@ describe("resolveGeneratedModuleFormatter", () => {
4367
windowsVerbatimArguments: true,
4468
});
4569
});
70+
71+
it("runs generated module formatting with bounded child execution", () => {
72+
const repoRoot = makeRepoRoot();
73+
const calls: unknown[] = [];
74+
75+
const formatted = formatGeneratedModule(
76+
"export const value=1;",
77+
{
78+
errorLabel: "test module",
79+
outputPath: "generated.ts",
80+
repoRoot,
81+
},
82+
{
83+
resolveFormatter: ({ outputPath }: { outputPath: string }) => ({
84+
args: ["--write", outputPath],
85+
command: "oxfmt",
86+
shell: false,
87+
}),
88+
spawnSync: (_command: string, args: string[], options: unknown) => {
89+
calls.push(options);
90+
writeFileSync(args[1] ?? "", "export const value = 1;\n", "utf8");
91+
return { status: 0, stderr: "", stdout: "" };
92+
},
93+
},
94+
);
95+
96+
expect(formatted).toBe("export const value = 1;\n");
97+
expect(calls).toHaveLength(1);
98+
expect(calls[0]).toMatchObject({
99+
cwd: repoRoot,
100+
encoding: "utf8",
101+
maxBuffer: GENERATED_MODULE_FORMAT_MAX_BUFFER_BYTES,
102+
shell: false,
103+
timeout: GENERATED_MODULE_FORMAT_TIMEOUT_MS,
104+
});
105+
});
106+
107+
it("reports formatter timeouts with bounded output tails", () => {
108+
const repoRoot = makeRepoRoot();
109+
const timeoutError = Object.assign(new Error("spawnSync oxfmt ETIMEDOUT"), {
110+
code: "ETIMEDOUT",
111+
});
112+
113+
expect(() =>
114+
formatGeneratedModule(
115+
"export const value=1;",
116+
{
117+
errorLabel: "test module",
118+
outputPath: "generated.ts",
119+
repoRoot,
120+
},
121+
{
122+
resolveFormatter: ({ outputPath }: { outputPath: string }) => ({
123+
args: ["--write", outputPath],
124+
command: "oxfmt",
125+
shell: false,
126+
}),
127+
spawnSync: () => ({
128+
error: timeoutError,
129+
signal: "SIGTERM",
130+
status: null,
131+
stderr: `DO_NOT_DUMP_OLD_STDERR${"x".repeat(20 * 1024)}\nrecent stderr tail`,
132+
stdout: `DO_NOT_DUMP_OLD_STDOUT${"x".repeat(20 * 1024)}\nrecent stdout tail`,
133+
}),
134+
},
135+
),
136+
).toThrow(
137+
/formatter timed out after 30000ms[\s\S]*recent stderr tail[\s\S]*recent stdout tail/u,
138+
);
139+
140+
try {
141+
formatGeneratedModule(
142+
"export const value=1;",
143+
{
144+
errorLabel: "test module",
145+
outputPath: "generated.ts",
146+
repoRoot,
147+
},
148+
{
149+
resolveFormatter: ({ outputPath }: { outputPath: string }) => ({
150+
args: ["--write", outputPath],
151+
command: "oxfmt",
152+
shell: false,
153+
}),
154+
spawnSync: () => ({
155+
error: timeoutError,
156+
signal: "SIGTERM",
157+
status: null,
158+
stderr: `DO_NOT_DUMP_OLD_STDERR${"x".repeat(20 * 1024)}\nrecent stderr tail`,
159+
stdout: `DO_NOT_DUMP_OLD_STDOUT${"x".repeat(20 * 1024)}\nrecent stdout tail`,
160+
}),
161+
},
162+
);
163+
} catch (error) {
164+
const message = error instanceof Error ? error.message : String(error);
165+
expect(message).not.toContain("DO_NOT_DUMP_OLD_STDERR");
166+
expect(message).not.toContain("DO_NOT_DUMP_OLD_STDOUT");
167+
}
168+
});
46169
});

0 commit comments

Comments
 (0)