Open History to see the last commit
1import * as Data from "effect/Data";
2import * as Context from "effect/Context";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as PlatformError from "effect/PlatformError";
8import * as Scope from "effect/Scope";
9import * as Stream from "effect/Stream";
10import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
11import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
12import { resolveSpawnCommand } from "@t3tools/shared/shell";
13import {
14 collectUint8StreamText,
15 type CollectedUint8StreamText,
16} from "./stream/collectUint8StreamText.ts";
17
18export interface ProcessRunInput {
19 readonly command: string;
20 readonly args: ReadonlyArray<string>;
21 readonly cwd?: string | undefined;
22 readonly spawnCwd?: string | undefined;
23 readonly timeout?: Duration.Input | undefined;
24 readonly env?: NodeJS.ProcessEnv | undefined;
25 readonly stdin?: string | undefined;
26 readonly maxOutputBytes?: number | undefined;
27 readonly outputMode?: "error" | "truncate" | undefined;
28 readonly truncatedMarker?: string | undefined;
29 /**
30 * On timeout, return a synthetic timedOut result.
31 * Partial stdout/stderr are not preserved.
32 */
33 readonly timeoutBehavior?: "error" | "timedOutResult" | undefined;
34}
35
36export interface ProcessRunOutput {
37 readonly stdout: string;
38 readonly stderr: string;
39 readonly code: ChildProcessSpawner.ExitCode | null;
40 readonly timedOut: boolean;
41 readonly stdoutTruncated: boolean;
42 readonly stderrTruncated: boolean;
43}
44
45export class ProcessSpawnError extends Data.TaggedError("ProcessSpawnError")<{
46 readonly command: string;
47 readonly args: ReadonlyArray<string>;
48 readonly cwd?: string | undefined;
49 readonly cause: unknown;
50}> {}
51
52export class ProcessStdinError extends Data.TaggedError("ProcessStdinError")<{
53 readonly command: string;
54 readonly args: ReadonlyArray<string>;
55 readonly cwd?: string | undefined;
56 readonly cause: unknown;
57}> {}
58
59export class ProcessOutputLimitError extends Data.TaggedError("ProcessOutputLimitError")<{
60 readonly command: string;
61 readonly args: ReadonlyArray<string>;
62 readonly cwd?: string | undefined;
63 readonly stream: "stdout" | "stderr";
64 readonly maxBytes: number;
65}> {}
66
67export class ProcessReadError extends Data.TaggedError("ProcessReadError")<{
68 readonly command: string;
69 readonly args: ReadonlyArray<string>;
70 readonly cwd?: string | undefined;
71 readonly stream: "stdout" | "stderr" | "exitCode";
72 readonly cause: unknown;
73}> {}
74
75export class ProcessTimeoutError extends Data.TaggedError("ProcessTimeoutError")<{
76 readonly command: string;
77 readonly args: ReadonlyArray<string>;
78 readonly cwd?: string | undefined;
79 readonly timeoutMs: number;
80}> {}
81
82export type ProcessRunError =
83 | ProcessSpawnError
84 | ProcessStdinError
85 | ProcessOutputLimitError
86 | ProcessReadError
87 | ProcessTimeoutError;
88
89export interface ProcessRunnerShape {
90 readonly run: (input: ProcessRunInput) => Effect.Effect<ProcessRunOutput, ProcessRunError>;
91}
92
93export class ProcessRunner extends Context.Service<ProcessRunner, ProcessRunnerShape>()(
94 "t3/processRunner",
95) {}
96
97const DEFAULT_TIMEOUT = "60 seconds";
98const DEFAULT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
99
100const WINDOWS_COMMAND_NOT_FOUND_PATTERNS = [
101 /is not recognized as an internal or external command/i,
102 /n.o . reconhecido como um comando interno/i,
103 /non . riconosciuto come comando interno o esterno/i,
104 /n.est pas reconnu en tant que commande interne/i,
105 /no se reconoce como un comando interno o externo/i,
106 /wird nicht als interner oder externer befehl/i,
107] as const;
108
109function hasWindowsCommandNotFoundMessage(output: string): boolean {
110 return WINDOWS_COMMAND_NOT_FOUND_PATTERNS.some((pattern) => pattern.test(output));
111}
112
113export const isWindowsCommandNotFound = Effect.fn("processRunner.isWindowsCommandNotFound")(
114 function* (code: number | null, stderr: string) {
115 const platform = yield* HostProcessPlatform;
116 if (platform !== "win32") return false;
117 if (code === 9009) return true;
118 return hasWindowsCommandNotFoundMessage(stderr);
119 },
120);
121
122const collectText = Effect.fn("processRunner.collectText")(function* (input: {
123 readonly command: string;
124 readonly args: ReadonlyArray<string>;
125 readonly cwd?: string | undefined;
126 readonly streamName: "stdout" | "stderr";
127 readonly stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
128 readonly maxOutputBytes: number;
129 readonly outputMode: "error" | "truncate";
130 readonly truncatedMarker: string;
131}) {
132 const stream = input.stream.pipe(
133 Stream.mapError(
134 (cause) =>
135 new ProcessReadError({
136 command: input.command,
137 args: input.args,
138 cwd: input.cwd,
139 stream: input.streamName,
140 cause,
141 }),
142 ),
143 );
144
145 if (input.outputMode === "truncate") {
146 return yield* collectUint8StreamText({
147 stream,
148 maxBytes: input.maxOutputBytes,
149 truncatedMarker: input.truncatedMarker,
150 });
151 }
152
153 return yield* stream.pipe(
154 Stream.runFoldEffect<
155 {
156 readonly chunks: Uint8Array<ArrayBufferLike>[];
157 readonly bytes: number;
158 },
159 Uint8Array<ArrayBufferLike>,
160 ProcessOutputLimitError | ProcessReadError,
161 never
162 >(
163 () => ({ chunks: [], bytes: 0 }),
164 (state, chunk) => {
165 const remainingBytes = input.maxOutputBytes - state.bytes;
166 if (remainingBytes <= 0 || chunk.byteLength > remainingBytes) {
167 return Effect.fail(
168 new ProcessOutputLimitError({
169 command: input.command,
170 args: input.args,
171 cwd: input.cwd,
172 stream: input.streamName,
173 maxBytes: input.maxOutputBytes,
174 }),
175 );
176 }
177
178 state.chunks.push(chunk);
179 return Effect.succeed({
180 chunks: state.chunks,
181 bytes: state.bytes + chunk.byteLength,
182 });
183 },
184 ),
185 Effect.map(
186 (state): CollectedUint8StreamText => ({
187 text: Buffer.concat(state.chunks, state.bytes).toString("utf8"),
188 bytes: state.bytes,
189 truncated: false,
190 }),
191 ),
192 );
193});
194
195function finalizeRunProcess<R>(
196 effect: Effect.Effect<ProcessRunOutput, ProcessRunError, R | Scope.Scope>,
197 input: ProcessRunInput,
198): Effect.Effect<ProcessRunOutput, ProcessRunError, Exclude<R, Scope.Scope>> {
199 const timeout = Duration.fromInputUnsafe(input.timeout ?? DEFAULT_TIMEOUT);
200 const timeoutBehavior = input.timeoutBehavior ?? "error";
201
202 return effect.pipe(
203 Effect.scoped,
204 Effect.timeoutOption(timeout),
205 Effect.flatMap((result) => {
206 if (Option.isSome(result)) {
207 return Effect.succeed(result.value);
208 }
209 if (timeoutBehavior === "timedOutResult") {
210 return Effect.succeed({
211 stdout: "",
212 stderr: "",
213 code: null,
214 timedOut: true,
215 stdoutTruncated: false,
216 stderrTruncated: false,
217 } satisfies ProcessRunOutput);
218 }
219 return Effect.fail(
220 new ProcessTimeoutError({
221 command: input.command,
222 args: input.args,
223 cwd: input.cwd,
224 timeoutMs: Duration.toMillis(timeout),
225 }),
226 );
227 }),
228 );
229}
230
231const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
232 spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],
233 input: ProcessRunInput,
234): Effect.fn.Return<ProcessRunOutput, ProcessRunError, Scope.Scope> {
235 const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
236 const outputMode = input.outputMode ?? "error";
237 const truncatedMarker = input.truncatedMarker ?? "";
238 const extendEnv = input.env !== undefined;
239 const spawnCommand = yield* resolveSpawnCommand(
240 input.command,
241 input.args,
242 input.env === undefined ? {} : { env: input.env, extendEnv },
243 );
244
245 const child = yield* spawner
246 .spawn(
247 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
248 ...((input.spawnCwd ?? input.cwd) ? { cwd: input.spawnCwd ?? input.cwd } : {}),
249 ...(input.env !== undefined
250 ? {
251 env: input.env,
252 extendEnv,
253 }
254 : {}),
255 shell: spawnCommand.shell,
256 }),
257 )
258 .pipe(
259 Effect.mapError(
260 (cause) =>
261 new ProcessSpawnError({
262 command: input.command,
263 args: input.args,
264 cwd: input.cwd,
265 cause,
266 }),
267 ),
268 );
269
270 const writeStdin =
271 input.stdin === undefined
272 ? Effect.void
273 : Stream.run(Stream.encodeText(Stream.make(input.stdin)), child.stdin).pipe(
274 Effect.mapError(
275 (cause) =>
276 new ProcessStdinError({
277 command: input.command,
278 args: input.args,
279 cwd: input.cwd,
280 cause,
281 }),
282 ),
283 );
284
285 const [stdout, stderr] = yield* Effect.all(
286 [
287 collectText({
288 command: input.command,
289 args: input.args,
290 cwd: input.cwd,
291 streamName: "stdout",
292 stream: child.stdout,
293 maxOutputBytes,
294 outputMode,
295 truncatedMarker,
296 }),
297 collectText({
298 command: input.command,
299 args: input.args,
300 cwd: input.cwd,
301 streamName: "stderr",
302 stream: child.stderr,
303 maxOutputBytes,
304 outputMode,
305 truncatedMarker,
306 }),
307 writeStdin,
308 ],
309 { concurrency: "unbounded" },
310 );
311
312 const exitCode = yield* child.exitCode.pipe(
313 Effect.mapError(
314 (cause) =>
315 new ProcessReadError({
316 command: input.command,
317 args: input.args,
318 cwd: input.cwd,
319 stream: "exitCode",
320 cause,
321 }),
322 ),
323 );
324
325 return {
326 stdout: stdout.text,
327 stderr: stderr.text,
328 code: exitCode,
329 timedOut: false,
330 stdoutTruncated: stdout.truncated,
331 stderrTruncated: stderr.truncated,
332 } satisfies ProcessRunOutput;
333});
334
335export const make = Effect.fn("makeProcessRunner")(function* () {
336 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
337
338 const run: ProcessRunnerShape["run"] = (input) =>
339 finalizeRunProcess(runProcessCore(spawner, input), input);
340
341 return ProcessRunner.of({
342 run,
343 });
344});
345
346export const layer = Layer.effect(ProcessRunner, make());