Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

processRunner.ts

242 lines6.8 KB

1import { spawn } from "node:child_process";
2​
3export interface ProcessRunOptions {
4 cwd?: string | undefined;
5 timeoutMs?: number | undefined;
6 env?: NodeJS.ProcessEnv | undefined;
7 stdin?: string | undefined;
8 allowNonZeroExit?: boolean | undefined;
9 maxBufferBytes?: number | undefined;
10 outputMode?: "error" | "truncate" | undefined;
12​
13export interface ProcessRunResult {
14 stdout: string;
15 stderr: string;
16 code: number | null;
17 signal: NodeJS.Signals | null;
18 timedOut: boolean;
19 stdoutTruncated?: boolean | undefined;
20 stderrTruncated?: boolean | undefined;
22​
23function commandLabel(command: string, args: readonly string[]): string {
24 return [command, ...args].join(" ");
26​
27function normalizeSpawnError(command: string, args: readonly string[], error: unknown): Error {
28 if (!(error instanceof Error)) {
29 return new Error(`Failed to run ${commandLabel(command, args)}.`);
30 }
31​
32 const maybeCode = (error as NodeJS.ErrnoException).code;
33 if (maybeCode === "ENOENT") {
34 return new Error(`Command not found: ${command}`);
35 }
36​
37 return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
39​
40function normalizeExitError(
41 command: string,
42 args: readonly string[],
43 result: ProcessRunResult,
44): Error {
45 const reason = result.timedOut
46 ? "timed out"
47 : `failed (code=${result.code ?? "null"}, signal=${result.signal ?? "null"})`;
48 const stderr = result.stderr.trim();
49 const detail = stderr.length > 0 ? ` ${stderr}` : "";
50 return new Error(`${commandLabel(command, args)} ${reason}.${detail}`);
52​
53function normalizeStdinError(command: string, args: readonly string[], error: unknown): Error {
54 if (!(error instanceof Error)) {
55 return new Error(`Failed to write stdin for ${commandLabel(command, args)}.`);
56 }
57 return new Error(`Failed to write stdin for ${commandLabel(command, args)}: ${error.message}`);
59​
60function normalizeBufferError(
61 command: string,
62 args: readonly string[],
63 stream: "stdout" | "stderr",
64 maxBufferBytes: number,
65): Error {
66 return new Error(
67 `${commandLabel(command, args)} exceeded ${stream} buffer limit (${maxBufferBytes} bytes).`,
68 );
70​
71const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
72​
73function appendChunkWithinLimit(
74 target: string,
75 currentBytes: number,
76 chunk: Buffer,
77 maxBytes: number,
78): {
79 next: string;
80 nextBytes: number;
81 truncated: boolean;
82} {
83 const remaining = maxBytes - currentBytes;
84 if (remaining <= 0) {
85 return { next: target, nextBytes: currentBytes, truncated: true };
86 }
87 if (chunk.length <= remaining) {
88 return {
89 next: `${target}${chunk.toString()}`,
90 nextBytes: currentBytes + chunk.length,
91 truncated: false,
92 };
93 }
94 return {
95 next: `${target}${chunk.subarray(0, remaining).toString()}`,
96 nextBytes: currentBytes + remaining,
97 truncated: true,
98 };
100​
101export async function runProcess(
102 command: string,
103 args: readonly string[],
104 options: ProcessRunOptions = {},
105): Promise<ProcessRunResult> {
106 const timeoutMs = options.timeoutMs ?? 60_000;
107 const maxBufferBytes = options.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;
108 const outputMode = options.outputMode ?? "error";
109​
110 return new Promise<ProcessRunResult>((resolve, reject) => {
111 const child = spawn(command, args, {
112 cwd: options.cwd,
113 env: options.env,
114 stdio: "pipe",
115 });
116​
117 let stdout = "";
118 let stderr = "";
119 let stdoutBytes = 0;
120 let stderrBytes = 0;
121 let stdoutTruncated = false;
122 let stderrTruncated = false;
123 let timedOut = false;
124 let settled = false;
125 let forceKillTimer: ReturnType<typeof setTimeout> | null = null;
126​
127 const timeoutTimer = setTimeout(() => {
128 timedOut = true;
129 child.kill("SIGTERM");
130 forceKillTimer = setTimeout(() => {
131 child.kill("SIGKILL");
132 }, 1_000);
133 }, timeoutMs);
134​
135 const finalize = (callback: () => void): void => {
136 if (settled) return;
137 settled = true;
138 clearTimeout(timeoutTimer);
139 if (forceKillTimer) {
140 clearTimeout(forceKillTimer);
141 }
142 callback();
143 };
144​
145 const fail = (error: Error): void => {
146 child.kill("SIGTERM");
147 finalize(() => {
148 reject(error);
149 });
150 };
151​
152 const appendOutput = (stream: "stdout" | "stderr", chunk: Buffer | string): Error | null => {
153 const chunkBuffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
154 const text = chunkBuffer.toString();
155 const byteLength = chunkBuffer.length;
156 if (stream === "stdout") {
157 if (outputMode === "truncate") {
158 const appended = appendChunkWithinLimit(stdout, stdoutBytes, chunkBuffer, maxBufferBytes);
159 stdout = appended.next;
160 stdoutBytes = appended.nextBytes;
161 stdoutTruncated = stdoutTruncated || appended.truncated;
162 return null;
163 }
164 stdout += text;
165 stdoutBytes += byteLength;
166 if (stdoutBytes > maxBufferBytes) {
167 return normalizeBufferError(command, args, "stdout", maxBufferBytes);
168 }
169 } else {
170 if (outputMode === "truncate") {
171 const appended = appendChunkWithinLimit(stderr, stderrBytes, chunkBuffer, maxBufferBytes);
172 stderr = appended.next;
173 stderrBytes = appended.nextBytes;
174 stderrTruncated = stderrTruncated || appended.truncated;
175 return null;
176 }
177 stderr += text;
178 stderrBytes += byteLength;
179 if (stderrBytes > maxBufferBytes) {
180 return normalizeBufferError(command, args, "stderr", maxBufferBytes);
181 }
182 }
183 return null;
184 };
185​
186 child.stdout.on("data", (chunk: Buffer | string) => {
187 const error = appendOutput("stdout", chunk);
188 if (error) {
189 fail(error);
190 }
191 });
192​
193 child.stderr.on("data", (chunk: Buffer | string) => {
194 const error = appendOutput("stderr", chunk);
195 if (error) {
196 fail(error);
197 }
198 });
199​
200 child.once("error", (error) => {
201 finalize(() => {
202 reject(normalizeSpawnError(command, args, error));
203 });
204 });
205​
206 child.once("close", (code, signal) => {
207 const result: ProcessRunResult = {
208 stdout,
209 stderr,
210 code,
211 signal,
212 timedOut,
213 stdoutTruncated,
214 stderrTruncated,
215 };
216​
217 finalize(() => {
218 if (!options.allowNonZeroExit && (timedOut || (code !== null && code !== 0))) {
219 reject(normalizeExitError(command, args, result));
220 return;
221 }
222 resolve(result);
223 });
224 });
225​
226 child.stdin.once("error", (error) => {
227 fail(normalizeStdinError(command, args, error));
228 });
229​
230 if (options.stdin !== undefined) {
231 child.stdin.write(options.stdin, (error) => {
232 if (error) {
233 fail(normalizeStdinError(command, args, error));
234 return;
235 }
236 child.stdin.end();
237 });
238 return;
239 }
240 child.stdin.end();
241 });