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
174// Untraced: no attributes, and its time is the runProcessCore span. Errors fail that span.
175const collectText = Effect.fnUntraced(function* (input: {
176 readonly command: string;
177 readonly args: ReadonlyArray<string>;
178 readonly cwd?: string | undefined;
179 readonly spawnCwd?: string | undefined;
180 readonly streamName: "stdout" | "stderr";
181 readonly stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
182 readonly maxOutputBytes: number;
183 readonly outputMode: "error" | "truncate";
184 readonly truncatedMarker: string;
185}) {
186 const stream = input.stream.pipe(
187 Stream.mapError(
188 (cause) =>
189 new ProcessReadError({
190 command: input.command,
191 argumentCount: input.args.length,
192 cwd: input.cwd,
193 spawnCwd: input.spawnCwd,
194 stream: input.streamName,
195 cause,
196 }),
197 ),
198 );
199
200 if (input.outputMode === "truncate") {
201 return yield* collectUint8StreamText({
202 stream,
203 maxBytes: input.maxOutputBytes,
204 truncatedMarker: input.truncatedMarker,
205 });
206 }
207
208 return yield* stream.pipe(
209 Stream.runFoldEffect<
210 {
211 readonly chunks: Uint8Array<ArrayBufferLike>[];
212 readonly bytes: number;
213 },
214 Uint8Array<ArrayBufferLike>,
215 ProcessOutputLimitError | ProcessReadError,
216 never
217 >(
218 () => ({ chunks: [], bytes: 0 }),
219 (state, chunk) => {
220 const remainingBytes = input.maxOutputBytes - state.bytes;
221 if (chunk.byteLength > remainingBytes) {
222 return Effect.fail(
223 new ProcessOutputLimitError({
224 command: input.command,
225 argumentCount: input.args.length,
226 cwd: input.cwd,
227 spawnCwd: input.spawnCwd,
228 stream: input.streamName,
229 maxBytes: input.maxOutputBytes,
230 observedBytes: state.bytes + chunk.byteLength,
231 }),
232 );
233 }
234
235 state.chunks.push(chunk);
236 return Effect.succeed({
237 chunks: state.chunks,
238 bytes: state.bytes + chunk.byteLength,
239 });
240 },
241 ),
242 Effect.map((state): CollectedUint8StreamText => ({
243 ...decodeUtf8(Buffer.concat(state.chunks, state.bytes)),
244 bytes: state.bytes,
245 truncated: false,
246 })),
247 );
248});
249
250function finalizeRunProcess<R>(
251 effect: Effect.Effect<ProcessRunOutput, ProcessRunError, R | Scope.Scope>,
252 input: ProcessRunInput,
253): Effect.Effect<ProcessRunOutput, ProcessRunError, Exclude<R, Scope.Scope>> {
254 const timeout = Duration.fromInputUnsafe(input.timeout ?? DEFAULT_TIMEOUT);
255 const timeoutBehavior = input.timeoutBehavior ?? "error";
256
257 return effect.pipe(
258 Effect.scoped,
259 Effect.timeoutOption(timeout),
260 Effect.flatMap((result) => {
261 if (Option.isSome(result)) {
262 return Effect.succeed(result.value);
263 }
264 if (timeoutBehavior === "timedOutResult") {
265 return Effect.succeed({
266 stdout: "",
267 stderr: "",
268 code: null,
269 timedOut: true,
270 stdoutTruncated: false,
271 stderrTruncated: false,
272 stdoutInvalidUtf8: false,
273 stderrInvalidUtf8: false,
274 } satisfies ProcessRunOutput);
275 }
276 return Effect.fail(
277 new ProcessTimeoutError({
278 command: input.command,
279 argumentCount: input.args.length,
280 cwd: input.cwd,
281 spawnCwd: input.spawnCwd,
282 timeoutMs: Duration.toMillis(timeout),
283 }),
284 );
285 }),
286 );
287}
288
289/** The executable name without its directory, recorded as `process.command` on process spans. */
290export const commandName = (command: string) => command.replace(/^.*[\\/]/, "");
291
292const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
293 spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],
294 input: ProcessRunInput,
295): Effect.fn.Return<ProcessRunOutput, ProcessRunError, Scope.Scope> {
296 yield* Effect.annotateCurrentSpan("process.command", commandName(input.command));
297 const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
298 const outputMode = input.outputMode ?? "error";
299 const truncatedMarker = input.truncatedMarker ?? "";
300 const extendEnv = input.env !== undefined;
301 const spawnCommand = yield* resolveSpawnCommand(
302 input.command,
303 input.args,
304 input.env === undefined ? {} : { env: input.env, extendEnv },
305 );
306
307 const child = yield* spawner
308 .spawn(
309 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
310 ...((input.spawnCwd ?? input.cwd) ? { cwd: input.spawnCwd ?? input.cwd } : {}),
311 ...(input.env !== undefined
312 ? {
313 env: input.env,
314 extendEnv,
315 }
316 : {}),
317 shell: spawnCommand.shell,
318 }),
319 )
320 .pipe(
321 Effect.mapError(
322 (cause) =>
323 new ProcessSpawnError({
324 command: input.command,
325 argumentCount: input.args.length,
326 cwd: input.cwd,
327 spawnCwd: input.spawnCwd,
328 resolvedCommand: spawnCommand.command,
329 resolvedArgumentCount: spawnCommand.args.length,
330 shell: spawnCommand.shell,
331 cause,
332 }),
333 ),
334 );
335
336 const stdin = input.stdin;
337 const onStdoutChunk = input.onStdoutChunk;
338 const writeStdin =
339 stdin === undefined
340 ? Effect.void
341 : Stream.run(Stream.encodeText(Stream.make(stdin)), child.stdin).pipe(
342 Effect.mapError(
343 (cause) =>
344 new ProcessStdinError({
345 command: input.command,
346 argumentCount: input.args.length,
347 cwd: input.cwd,
348 spawnCwd: input.spawnCwd,
349 stdinBytes: Buffer.byteLength(stdin),
350 cause,
351 }),
352 ),
353 );
354
355 const [stdout, stderr] = yield* Effect.all(
356 [
357 collectText({
358 command: input.command,
359 args: input.args,
360 cwd: input.cwd,
361 spawnCwd: input.spawnCwd,
362 streamName: "stdout",
363 stream: onStdoutChunk
364 ? child.stdout.pipe(Stream.tap((chunk) => Effect.sync(() => onStdoutChunk(chunk))))
365 : child.stdout,
366 maxOutputBytes,
367 outputMode,
368 truncatedMarker,
369 }),
370 collectText({
371 command: input.command,
372 args: input.args,
373 cwd: input.cwd,
374 spawnCwd: input.spawnCwd,
375 streamName: "stderr",
376 stream: child.stderr,
377 maxOutputBytes,
378 outputMode,
379 truncatedMarker,
380 }),
381 writeStdin,
382 ],
383 { concurrency: "unbounded" },
384 );
385
386 const exitCode = yield* child.exitCode.pipe(
387 Effect.mapError(
388 (cause) =>
389 new ProcessReadError({
390 command: input.command,
391 argumentCount: input.args.length,
392 cwd: input.cwd,
393 spawnCwd: input.spawnCwd,
394 stream: "exitCode",
395 cause,
396 }),
397 ),
398 );
399
400 return {
401 stdout: stdout.text,
402 stderr: stderr.text,
403 code: exitCode,
404 timedOut: false,
405 stdoutTruncated: stdout.truncated,
406 stderrTruncated: stderr.truncated,
407 stdoutInvalidUtf8: stdout.invalidUtf8,
408 stderrInvalidUtf8: stderr.invalidUtf8,
409 } satisfies ProcessRunOutput;
410});
411
412/** @public Service construction is part of the canonical Effect module API. */
413export const make = Effect.fn("ProcessRunner.make")(function* () {
414 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
415
416 const run: ProcessRunner["Service"]["run"] = (input) =>
417 finalizeRunProcess(runProcessCore(spawner, input), input);
418
419 return ProcessRunner.of({
420 run,
421 });
422});
423
424export const layer = Layer.effect(ProcessRunner, make());