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