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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<ProcessReadError>()(
110 "ProcessReadError",
111 {
112 ...ProcessInvocationFields,
113 stream: Schema.Literals(["stdout", "stderr", "exitCode"]),
114 cause: Schema.Defect(),
115 },
116) {
117 override get message(): string {
118 return `Failed to read ${this.stream} for process ${formatProcessInvocation(this)}`;
119 }
120}
121
122export class ProcessTimeoutError extends Schema.TaggedErrorClass<ProcessTimeoutError>()(
123 "ProcessTimeoutError",
124 {
125 ...ProcessInvocationFields,
126 timeoutMs: Schema.Number,
127 },
128) {
129 override get message(): string {
130 return `Process ${formatProcessInvocation(this)} timed out after ${this.timeoutMs}ms`;
131 }
132}
133
134export const ProcessRunError = Schema.Union([
135 ProcessSpawnError,
136 ProcessStdinError,
137 ProcessOutputLimitError,
138 ProcessReadError,
139 ProcessTimeoutError,
140]);
141export type ProcessRunError = typeof ProcessRunError.Type;
142
143export class ProcessRunner extends Context.Service<
144 ProcessRunner,
145 {
146 readonly run: (input: ProcessRunInput) => Effect.Effect<ProcessRunOutput, ProcessRunError>;
147 }
148>()("t3/processRunner") {}
149
150const DEFAULT_TIMEOUT = "60 seconds";
151const DEFAULT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
152
153const WINDOWS_COMMAND_NOT_FOUND_PATTERNS = [
154 /is not recognized as an internal or external command/i,
155 /n.o . reconhecido como um comando interno/i,
156 /non . riconosciuto come comando interno o esterno/i,
157 /n.est pas reconnu en tant que commande interne/i,
158 /no se reconoce como un comando interno o externo/i,
159 /wird nicht als interner oder externer befehl/i,
160] as const;
161
162function hasWindowsCommandNotFoundMessage(output: string): boolean {
163 return WINDOWS_COMMAND_NOT_FOUND_PATTERNS.some((pattern) => pattern.test(output));
164}
165
166export const isWindowsCommandNotFound = Effect.fn("processRunner.isWindowsCommandNotFound")(
167 function* (code: number | null, stderr: string) {
168 const platform = yield* HostProcessPlatform;
169 if (platform !== "win32") return false;
170 if (code === 9009) return true;
171 return hasWindowsCommandNotFoundMessage(stderr);
172 },
173);
174
175const collectText = Effect.fn("processRunner.collectText")(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(
243 (state): CollectedUint8StreamText => ({
244 ...decodeUtf8(Buffer.concat(state.chunks, state.bytes)),
245 bytes: state.bytes,
246 truncated: false,
247 }),
248 ),
249 );
250});
251
252function finalizeRunProcess<R>(
253 effect: Effect.Effect<ProcessRunOutput, ProcessRunError, R | Scope.Scope>,
254 input: ProcessRunInput,
255): Effect.Effect<ProcessRunOutput, ProcessRunError, Exclude<R, Scope.Scope>> {
256 const timeout = Duration.fromInputUnsafe(input.timeout ?? DEFAULT_TIMEOUT);
257 const timeoutBehavior = input.timeoutBehavior ?? "error";
258
259 return effect.pipe(
260 Effect.scoped,
261 Effect.timeoutOption(timeout),
262 Effect.flatMap((result) => {
263 if (Option.isSome(result)) {
264 return Effect.succeed(result.value);
265 }
266 if (timeoutBehavior === "timedOutResult") {
267 return Effect.succeed({
268 stdout: "",
269 stderr: "",
270 code: null,
271 timedOut: true,
272 stdoutTruncated: false,
273 stderrTruncated: false,
274 stdoutInvalidUtf8: false,
275 stderrInvalidUtf8: false,
276 } satisfies ProcessRunOutput);
277 }
278 return Effect.fail(
279 new ProcessTimeoutError({
280 command: input.command,
281 argumentCount: input.args.length,
282 cwd: input.cwd,
283 spawnCwd: input.spawnCwd,
284 timeoutMs: Duration.toMillis(timeout),
285 }),
286 );
287 }),
288 );
289}
290
291const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
292 spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],
293 input: ProcessRunInput,
294): Effect.fn.Return<ProcessRunOutput, ProcessRunError, Scope.Scope> {
295 const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
296 const outputMode = input.outputMode ?? "error";
297 const truncatedMarker = input.truncatedMarker ?? "";
298 const extendEnv = input.env !== undefined;
299 const spawnCommand = yield* resolveSpawnCommand(
300 input.command,
301 input.args,
302 input.env === undefined ? {} : { env: input.env, extendEnv },
303 );
304
305 const child = yield* spawner
306 .spawn(
307 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
308 ...((input.spawnCwd ?? input.cwd) ? { cwd: input.spawnCwd ?? input.cwd } : {}),
309 ...(input.env !== undefined
310 ? {
311 env: input.env,
312 extendEnv,
313 }
314 : {}),
315 shell: spawnCommand.shell,
316 }),
317 )
318 .pipe(
319 Effect.mapError(
320 (cause) =>
321 new ProcessSpawnError({
322 command: input.command,
323 argumentCount: input.args.length,
324 cwd: input.cwd,
325 spawnCwd: input.spawnCwd,
326 resolvedCommand: spawnCommand.command,
327 resolvedArgumentCount: spawnCommand.args.length,
328 shell: spawnCommand.shell,
329 cause,
330 }),
331 ),
332 );
333
334 const stdin = input.stdin;
335 const writeStdin =
336 stdin === undefined
337 ? Effect.void
338 : Stream.run(Stream.encodeText(Stream.make(stdin)), child.stdin).pipe(
339 Effect.mapError(
340 (cause) =>
341 new ProcessStdinError({
342 command: input.command,
343 argumentCount: input.args.length,
344 cwd: input.cwd,
345 spawnCwd: input.spawnCwd,
346 stdinBytes: Buffer.byteLength(stdin),
347 cause,
348 }),
349 ),
350 );
351
352 const [stdout, stderr] = yield* Effect.all(
353 [
354 collectText({
355 command: input.command,
356 args: input.args,
357 cwd: input.cwd,
358 spawnCwd: input.spawnCwd,
359 streamName: "stdout",
360 stream: 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
407export const make = Effect.fn("ProcessRunner.make")(function* () {
408 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
409
410 const run: ProcessRunner["Service"]["run"] = (input) =>
411 finalizeRunProcess(runProcessCore(spawner, input), input);
412
413 return ProcessRunner.of({
414 run,
415 });
416});
417
418export const layer = Layer.effect(ProcessRunner, make());