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

processRunner.ts

411 lines12.2 KB

1import * as Context from "effect/Context";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as PlatformError from "effect/PlatformError";
7import * as Schema from "effect/Schema";
8import * as Scope from "effect/Scope";
9import * as Stream from "effect/Stream";
10import * as ChildProcess from "effect/unstable/process/ChildProcess";
11import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
12import { HostProcessPlatform } from "@v12/shared/hostProcess";
13import { resolveSpawnCommand } from "@v12/shared/shell";
14import {
15 collectUint8StreamText,
16 type CollectedUint8StreamText,
17} from "./stream/collectUint8StreamText.ts";
18​
19export interface ProcessRunInput {
20 readonly command: string;
21 readonly args: ReadonlyArray<string>;
22 readonly cwd?: string | undefined;
23 readonly spawnCwd?: string | undefined;
24 readonly timeout?: Duration.Input | undefined;
25 readonly env?: NodeJS.ProcessEnv | undefined;
26 readonly stdin?: string | undefined;
27 readonly maxOutputBytes?: number | undefined;
28 readonly outputMode?: "error" | "truncate" | undefined;
29 readonly truncatedMarker?: string | undefined;
30 /**
31 * On timeout, return a synthetic timedOut result.
32 * Partial stdout/stderr are not preserved.
33 */
34 readonly timeoutBehavior?: "error" | "timedOutResult" | undefined;
36​
37export interface ProcessRunOutput {
38 readonly stdout: string;
39 readonly stderr: string;
40 readonly code: ChildProcessSpawner.ExitCode | null;
41 readonly timedOut: boolean;
42 readonly stdoutTruncated: boolean;
43 readonly stderrTruncated: boolean;
45​
46const ProcessInvocationFields = {
47 command: Schema.String,
48 argumentCount: Schema.Number,
49 cwd: Schema.optional(Schema.String),
50 spawnCwd: Schema.optional(Schema.String),
51};
52​
53const formatProcessInvocation = (input: {
54 readonly command: string;
55 readonly cwd?: string | undefined;
56 readonly spawnCwd?: string | undefined;
57}): string => {
58 const executionCwd = input.spawnCwd ?? input.cwd;
59 return executionCwd === undefined
60 ? `'${input.command}'`
61 : `'${input.command}' in '${executionCwd}'`;
62};
63​
64export class ProcessSpawnError extends Schema.TaggedErrorClass<ProcessSpawnError>()(
65 "ProcessSpawnError",
66 {
67 ...ProcessInvocationFields,
68 resolvedCommand: Schema.optional(Schema.String),
69 resolvedArgumentCount: Schema.optional(Schema.Number),
70 shell: Schema.optional(Schema.Boolean),
71 cause: Schema.Defect(),
72 },
73) {
74 override get message(): string {
75 return `Failed to spawn process ${formatProcessInvocation(this)}`;
76 }
78​
79export class ProcessStdinError extends Schema.TaggedErrorClass<ProcessStdinError>()(
80 "ProcessStdinError",
81 {
82 ...ProcessInvocationFields,
83 stdinBytes: Schema.Number,
84 cause: Schema.Defect(),
85 },
86) {
87 override get message(): string {
88 return `Failed to write stdin for process ${formatProcessInvocation(this)}`;
89 }
91​
92export class ProcessOutputLimitError extends Schema.TaggedErrorClass<ProcessOutputLimitError>()(
93 "ProcessOutputLimitError",
94 {
95 ...ProcessInvocationFields,
96 stream: Schema.Literals(["stdout", "stderr"]),
97 maxBytes: Schema.Number,
98 observedBytes: Schema.Number,
99 },
100) {
101 override get message(): string {
102 return `Process ${formatProcessInvocation(this)} ${this.stream} produced ${this.observedBytes} bytes, exceeding the ${this.maxBytes} byte limit`;
103 }
105​
106export class ProcessReadError extends Schema.TaggedErrorClass<ProcessReadError>()(
107 "ProcessReadError",
108 {
109 ...ProcessInvocationFields,
110 stream: Schema.Literals(["stdout", "stderr", "exitCode"]),
111 cause: Schema.Defect(),
112 },
113) {
114 override get message(): string {
115 return `Failed to read ${this.stream} for process ${formatProcessInvocation(this)}`;
116 }
118​
119export class ProcessTimeoutError extends Schema.TaggedErrorClass<ProcessTimeoutError>()(
120 "ProcessTimeoutError",
121 {
122 ...ProcessInvocationFields,
123 timeoutMs: Schema.Number,
124 },
125) {
126 override get message(): string {
127 return `Process ${formatProcessInvocation(this)} timed out after ${this.timeoutMs}ms`;
128 }
130​
131export const ProcessRunError = Schema.Union([
132 ProcessSpawnError,
133 ProcessStdinError,
134 ProcessOutputLimitError,
135 ProcessReadError,
136 ProcessTimeoutError,
137]);
138export type ProcessRunError = typeof ProcessRunError.Type;
139​
140export class ProcessRunner extends Context.Service<
141 ProcessRunner,
142 {
143 readonly run: (input: ProcessRunInput) => Effect.Effect<ProcessRunOutput, ProcessRunError>;
144 }
145>()("v12/processRunner") {}
146​
147const DEFAULT_TIMEOUT = "60 seconds";
148const DEFAULT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
149​
150const WINDOWS_COMMAND_NOT_FOUND_PATTERNS = [
151 /is not recognized as an internal or external command/i,
152 /n.o . reconhecido como um comando interno/i,
153 /non . riconosciuto come comando interno o esterno/i,
154 /n.est pas reconnu en tant que commande interne/i,
155 /no se reconoce como un comando interno o externo/i,
156 /wird nicht als interner oder externer befehl/i,
157] as const;
158​
159function hasWindowsCommandNotFoundMessage(output: string): boolean {
160 return WINDOWS_COMMAND_NOT_FOUND_PATTERNS.some((pattern) => pattern.test(output));
162​
163export const isWindowsCommandNotFound = Effect.fn("processRunner.isWindowsCommandNotFound")(
164 function* (code: number | null, stderr: string) {
165 const platform = yield* HostProcessPlatform;
166 if (platform !== "win32") return false;
167 if (code === 9009) return true;
168 return hasWindowsCommandNotFoundMessage(stderr);
169 },
170);
171​
172const collectText = Effect.fn("processRunner.collectText")(function* (input: {
173 readonly command: string;
174 readonly args: ReadonlyArray<string>;
175 readonly cwd?: string | undefined;
176 readonly spawnCwd?: string | undefined;
177 readonly streamName: "stdout" | "stderr";
178 readonly stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
179 readonly maxOutputBytes: number;
180 readonly outputMode: "error" | "truncate";
181 readonly truncatedMarker: string;
182}) {
183 const stream = input.stream.pipe(
184 Stream.mapError(
185 (cause) =>
186 new ProcessReadError({
187 command: input.command,
188 argumentCount: input.args.length,
189 cwd: input.cwd,
190 spawnCwd: input.spawnCwd,
191 stream: input.streamName,
192 cause,
193 }),
194 ),
195 );
196​
197 if (input.outputMode === "truncate") {
198 return yield* collectUint8StreamText({
199 stream,
200 maxBytes: input.maxOutputBytes,
201 truncatedMarker: input.truncatedMarker,
202 });
203 }
204​
205 return yield* stream.pipe(
206 Stream.runFoldEffect<
207 {
208 readonly chunks: Uint8Array<ArrayBufferLike>[];
209 readonly bytes: number;
210 },
211 Uint8Array<ArrayBufferLike>,
212 ProcessOutputLimitError | ProcessReadError,
213 never
214 >(
215 () => ({ chunks: [], bytes: 0 }),
216 (state, chunk) => {
217 const remainingBytes = input.maxOutputBytes - state.bytes;
218 if (chunk.byteLength > remainingBytes) {
219 return Effect.fail(
220 new ProcessOutputLimitError({
221 command: input.command,
222 argumentCount: input.args.length,
223 cwd: input.cwd,
224 spawnCwd: input.spawnCwd,
225 stream: input.streamName,
226 maxBytes: input.maxOutputBytes,
227 observedBytes: state.bytes + chunk.byteLength,
228 }),
229 );
230 }
231​
232 state.chunks.push(chunk);
233 return Effect.succeed({
234 chunks: state.chunks,
235 bytes: state.bytes + chunk.byteLength,
236 });
237 },
238 ),
239 Effect.map(
240 (state): CollectedUint8StreamText => ({
241 text: Buffer.concat(state.chunks, state.bytes).toString("utf8"),
242 bytes: state.bytes,
243 truncated: false,
244 }),
245 ),
246 );
247});
248​
249function finalizeRunProcess<R>(
250 effect: Effect.Effect<ProcessRunOutput, ProcessRunError, R | Scope.Scope>,
251 input: ProcessRunInput,
252): Effect.Effect<ProcessRunOutput, ProcessRunError, Exclude<R, Scope.Scope>> {
253 const timeout = Duration.fromInputUnsafe(input.timeout ?? DEFAULT_TIMEOUT);
254 const timeoutBehavior = input.timeoutBehavior ?? "error";
255​
256 return effect.pipe(
257 Effect.scoped,
258 Effect.timeoutOption(timeout),
259 Effect.flatMap((result) => {
260 if (Option.isSome(result)) {
261 return Effect.succeed(result.value);
262 }
263 if (timeoutBehavior === "timedOutResult") {
264 return Effect.succeed({
265 stdout: "",
266 stderr: "",
267 code: null,
268 timedOut: true,
269 stdoutTruncated: false,
270 stderrTruncated: false,
271 } satisfies ProcessRunOutput);
272 }
273 return Effect.fail(
274 new ProcessTimeoutError({
275 command: input.command,
276 argumentCount: input.args.length,
277 cwd: input.cwd,
278 spawnCwd: input.spawnCwd,
279 timeoutMs: Duration.toMillis(timeout),
280 }),
281 );
282 }),
283 );
285​
286const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
287 spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],
288 input: ProcessRunInput,
289): Effect.fn.Return<ProcessRunOutput, ProcessRunError, Scope.Scope> {
290 const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
291 const outputMode = input.outputMode ?? "error";
292 const truncatedMarker = input.truncatedMarker ?? "";
293 const extendEnv = input.env !== undefined;
294 const spawnCommand = yield* resolveSpawnCommand(
295 input.command,
296 input.args,
297 input.env === undefined ? {} : { env: input.env, extendEnv },
298 );
299​
300 const child = yield* spawner
301 .spawn(
302 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
303 ...((input.spawnCwd ?? input.cwd) ? { cwd: input.spawnCwd ?? input.cwd } : {}),
304 ...(input.env !== undefined
305 ? {
306 env: input.env,
307 extendEnv,
308 }
309 : {}),
310 shell: spawnCommand.shell,
311 }),
312 )
313 .pipe(
314 Effect.mapError(
315 (cause) =>
316 new ProcessSpawnError({
317 command: input.command,
318 argumentCount: input.args.length,
319 cwd: input.cwd,
320 spawnCwd: input.spawnCwd,
321 resolvedCommand: spawnCommand.command,
322 resolvedArgumentCount: spawnCommand.args.length,
323 shell: spawnCommand.shell,
324 cause,
325 }),
326 ),
327 );
328​
329 const stdin = input.stdin;
330 const writeStdin =
331 stdin === undefined
332 ? Effect.void
333 : Stream.run(Stream.encodeText(Stream.make(stdin)), child.stdin).pipe(
334 Effect.mapError(
335 (cause) =>
336 new ProcessStdinError({
337 command: input.command,
338 argumentCount: input.args.length,
339 cwd: input.cwd,
340 spawnCwd: input.spawnCwd,
341 stdinBytes: Buffer.byteLength(stdin),
342 cause,
343 }),
344 ),
345 );
346​
347 const [stdout, stderr] = yield* Effect.all(
348 [
349 collectText({
350 command: input.command,
351 args: input.args,
352 cwd: input.cwd,
353 spawnCwd: input.spawnCwd,
354 streamName: "stdout",
355 stream: child.stdout,
356 maxOutputBytes,
357 outputMode,
358 truncatedMarker,
359 }),
360 collectText({
361 command: input.command,
362 args: input.args,
363 cwd: input.cwd,
364 spawnCwd: input.spawnCwd,
365 streamName: "stderr",
366 stream: child.stderr,
367 maxOutputBytes,
368 outputMode,
369 truncatedMarker,
370 }),
371 writeStdin,
372 ],
373 { concurrency: "unbounded" },
374 );
375​
376 const exitCode = yield* child.exitCode.pipe(
377 Effect.mapError(
378 (cause) =>
379 new ProcessReadError({
380 command: input.command,
381 argumentCount: input.args.length,
382 cwd: input.cwd,
383 spawnCwd: input.spawnCwd,
384 stream: "exitCode",
385 cause,
386 }),
387 ),
388 );
389​
390 return {
391 stdout: stdout.text,
392 stderr: stderr.text,
393 code: exitCode,
394 timedOut: false,
395 stdoutTruncated: stdout.truncated,
396 stderrTruncated: stderr.truncated,
397 } satisfies ProcessRunOutput;
398});
399​
400export const make = Effect.fn("ProcessRunner.make")(function* () {
401 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
402​
403 const run: ProcessRunner["Service"]["run"] = (input) =>
404 finalizeRunProcess(runProcessCore(spawner, input), input);
405​
406 return ProcessRunner.of({
407 run,
408 });
409});
410​
411export const layer = Layer.effect(ProcessRunner, make());