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 readonly maxOutputBytes?: number | undefined;
29 readonly outputMode?: "error" | "truncate" | undefined;
30 readonly truncatedMarker?: string | undefined;
31 /**
32 * On timeout, return a synthetic timedOut result.
33 * Partial stdout/stderr are not preserved.
34 */
35 readonly timeoutBehavior?: "error" | "timedOutResult" | undefined;
36}
37
38export interface ProcessRunOutput {
39 readonly stdout: string;
40 readonly stderr: string;
41 readonly code: ChildProcessSpawner.ExitCode | null;
42 readonly timedOut: boolean;
43 readonly stdoutTruncated: boolean;
44 readonly stderrTruncated: boolean;
45 readonly stdoutInvalidUtf8: boolean;
46 readonly stderrInvalidUtf8: boolean;
47}
48
49const ProcessInvocationFields = {
50 command: Schema.String,
51 argumentCount: Schema.Number,
52 cwd: Schema.optional(Schema.String),
53 spawnCwd: Schema.optional(Schema.String),
54};
55
56const formatProcessInvocation = (input: {
57 readonly command: string;
58 readonly cwd?: string | undefined;
59 readonly spawnCwd?: string | undefined;
60}): string => {
61 const executionCwd = input.spawnCwd ?? input.cwd;
62 return executionCwd === undefined
63 ? `'${input.command}'`
64 : `'${input.command}' in '${executionCwd}'`;
65};
66
67export class ProcessSpawnError extends Schema.TaggedError<ProcessSpawnError>()(
68 "ProcessSpawnError",
69 {
70 ...ProcessInvocationFields,
71 resolvedCommand: Schema.optional(Schema.String),
72 resolvedArgumentCount: Schema.optional(Schema.Number),
73 shell: Schema.optional(Schema.Boolean),
74 cause: Schema.Defect(),
75 },
76) {
77 override get message(): string {
78 return `Failed to spawn process ${formatProcessInvocation(this)}`;
79 }
80}
81
82export class ProcessStdinError extends Schema.TaggedError<ProcessStdinError>()(
83 "ProcessStdinError",
84 {
85 ...ProcessInvocationFields,
86 stdinBytes: Schema.Number,
87 cause: Schema.Defect(),
88 },
89) {
90 override get message(): string {
91 return `Failed to write stdin for process ${formatProcessInvocation(this)}`;
92 }
93}
94
95export class ProcessOutputLimitError extends Schema.TaggedError<ProcessOutputLimitError>()(
96 "ProcessOutputLimitError",
97 {
98 ...ProcessInvocationFields,
99 stream: Schema.Literals(["stdout", "stderr"]),
100 maxBytes: Schema.Number,
101 observedBytes: Schema.Number,
102 },
103) {
104 override get message(): string {
105 return `Process ${formatProcessInvocation(this)} ${this.stream} produced ${this.observedBytes} bytes, exceeding the ${this.maxBytes} byte limit`;
106 }
107}
108
109export class ProcessReadError extends Schema.TaggedError<ProcessReadError>()("ProcessReadError", {
110 ...ProcessInvocationFields,
111 stream: Schema.Literals(["stdout", "stderr", "exitCode"]),
112 cause: Schema.Defect(),
113}) {
114 override get message(): string {
115 return `Failed to read ${this.stream} for process ${formatProcessInvocation(this)}`;
116 }
117}
118
119export class ProcessTimeoutError extends Schema.TaggedError<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 }
129}
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>()("t3/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));
161}
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((state): CollectedUint8StreamText => ({
240 ...decodeUtf8(Buffer.concat(state.chunks, state.bytes)),
241 bytes: state.bytes,
242 truncated: false,
243 })),
244 );
245});
246
247function finalizeRunProcess<R>(
248 effect: Effect.Effect<ProcessRunOutput, ProcessRunError, R | Scope.Scope>,
249 input: ProcessRunInput,
250): Effect.Effect<ProcessRunOutput, ProcessRunError, Exclude<R, Scope.Scope>> {
251 const timeout = Duration.fromInputUnsafe(input.timeout ?? DEFAULT_TIMEOUT);
252 const timeoutBehavior = input.timeoutBehavior ?? "error";
253
254 return effect.pipe(
255 Effect.scoped,
256 Effect.timeoutOption(timeout),
257 Effect.flatMap((result) => {
258 if (Option.isSome(result)) {
259 return Effect.succeed(result.value);
260 }
261 if (timeoutBehavior === "timedOutResult") {
262 return Effect.succeed({
263 stdout: "",
264 stderr: "",
265 code: null,
266 timedOut: true,
267 stdoutTruncated: false,
268 stderrTruncated: false,
269 stdoutInvalidUtf8: false,
270 stderrInvalidUtf8: 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 );
284}
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 stdoutInvalidUtf8: stdout.invalidUtf8,
398 stderrInvalidUtf8: stderr.invalidUtf8,
399 } satisfies ProcessRunOutput;
400});
401
402/** @public Service construction is part of the canonical Effect module API. */
403export const make = Effect.fn("ProcessRunner.make")(function* () {
404 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
405
406 const run: ProcessRunner["Service"]["run"] = (input) =>
407 finalizeRunProcess(runProcessCore(spawner, input), input);
408
409 return ProcessRunner.of({
410 run,
411 });
412});
413
414export const layer = Layer.effect(ProcessRunner, make());