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((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
289const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
290 spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],
291 input: ProcessRunInput,
292): Effect.fn.Return<ProcessRunOutput, ProcessRunError, Scope.Scope> {
293 const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
294 const outputMode = input.outputMode ?? "error";
295 const truncatedMarker = input.truncatedMarker ?? "";
296 const extendEnv = input.env !== undefined;
297 const spawnCommand = yield* resolveSpawnCommand(
298 input.command,
299 input.args,
300 input.env === undefined ? {} : { env: input.env, extendEnv },
301 );
302
303 const child = yield* spawner
304 .spawn(
305 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
306 ...((input.spawnCwd ?? input.cwd) ? { cwd: input.spawnCwd ?? input.cwd } : {}),
307 ...(input.env !== undefined
308 ? {
309 env: input.env,
310 extendEnv,
311 }
312 : {}),
313 shell: spawnCommand.shell,
314 }),
315 )
316 .pipe(
317 Effect.mapError(
318 (cause) =>
319 new ProcessSpawnError({
320 command: input.command,
321 argumentCount: input.args.length,
322 cwd: input.cwd,
323 spawnCwd: input.spawnCwd,
324 resolvedCommand: spawnCommand.command,
325 resolvedArgumentCount: spawnCommand.args.length,
326 shell: spawnCommand.shell,
327 cause,
328 }),
329 ),
330 );
331
332 const stdin = input.stdin;
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: child.stdout,
359 maxOutputBytes,
360 outputMode,
361 truncatedMarker,
362 }),
363 collectText({
364 command: input.command,
365 args: input.args,
366 cwd: input.cwd,
367 spawnCwd: input.spawnCwd,
368 streamName: "stderr",
369 stream: child.stderr,
370 maxOutputBytes,
371 outputMode,
372 truncatedMarker,
373 }),
374 writeStdin,
375 ],
376 { concurrency: "unbounded" },
377 );
378
379 const exitCode = yield* child.exitCode.pipe(
380 Effect.mapError(
381 (cause) =>
382 new ProcessReadError({
383 command: input.command,
384 argumentCount: input.args.length,
385 cwd: input.cwd,
386 spawnCwd: input.spawnCwd,
387 stream: "exitCode",
388 cause,
389 }),
390 ),
391 );
392
393 return {
394 stdout: stdout.text,
395 stderr: stderr.text,
396 code: exitCode,
397 timedOut: false,
398 stdoutTruncated: stdout.truncated,
399 stderrTruncated: stderr.truncated,
400 stdoutInvalidUtf8: stdout.invalidUtf8,
401 stderrInvalidUtf8: stderr.invalidUtf8,
402 } satisfies ProcessRunOutput;
403});
404
405export const make = Effect.fn("ProcessRunner.make")(function* () {
406 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
407
408 const run: ProcessRunner["Service"]["run"] = (input) =>
409 finalizeRunProcess(runProcessCore(spawner, input), input);
410
411 return ProcessRunner.of({
412 run,
413 });
414});
415
416export const layer = Layer.effect(ProcessRunner, make());