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/process/ChildProcess";
11import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
12import { resolveSpawnCommand } from "@t3tools/shared/shell";
13import {
14 collectUint8StreamText,
15 decodeUtf8,
16 type CollectedUint8StreamText,
17} from "@t3tools/provider-core/server/collectStreamText";
18
19export interface ProcessRunInput {
20 readonly command: string;
21 readonly args: ReadonlyArray<string>;
22 readonly cwd?: string | undefined;
23 readonly spawnCwd?: string | undefined;
24 readonly timeout?: Duration.Input | undefined;
25 readonly env?: NodeJS.ProcessEnv | undefined;
26 readonly stdin?: string | undefined;
27 /** Receives every stdout chunk, including bytes beyond the buffered output limit. */
28 readonly onStdoutChunk?: ((chunk: Uint8Array) => void) | undefined;
29 readonly maxOutputBytes?: number | undefined;
30 readonly outputMode?: "error" | "truncate" | undefined;
31 readonly truncatedMarker?: string | undefined;
32 /**
33 * On timeout, return a synthetic timedOut result.
34 * Partial stdout/stderr are not preserved.
35 */
36 readonly timeoutBehavior?: "error" | "timedOutResult" | undefined;
37}
38
39export interface ProcessRunOutput {
40 readonly stdout: string;
41 readonly stderr: string;
42 readonly code: ChildProcessSpawner.ExitCode | null;
43 readonly timedOut: boolean;
44 readonly stdoutTruncated: boolean;
45 readonly stderrTruncated: boolean;
46 readonly stdoutInvalidUtf8: boolean;
47 readonly stderrInvalidUtf8: boolean;
48}
49
50const ProcessInvocationFields = {
51 command: Schema.String,
52 argumentCount: Schema.Number,
53 cwd: Schema.optional(Schema.String),
54 spawnCwd: Schema.optional(Schema.String),
55};
56
57const formatProcessInvocation = (input: {
58 readonly command: string;
59 readonly cwd?: string | undefined;
60 readonly spawnCwd?: string | undefined;
61}): string => {
62 const executionCwd = input.spawnCwd ?? input.cwd;
63 return executionCwd === undefined
64 ? `'${input.command}'`
65 : `'${input.command}' in '${executionCwd}'`;
66};
67
68export class ProcessSpawnError extends Schema.TaggedError<ProcessSpawnError>()(
69 "ProcessSpawnError",
70 {
71 ...ProcessInvocationFields,
72 resolvedCommand: Schema.optional(Schema.String),
73 resolvedArgumentCount: Schema.optional(Schema.Number),
74 shell: Schema.optional(Schema.Boolean),
75 cause: Schema.Defect(),
76 },
77) {
78 override get message(): string {
79 return `Failed to spawn process ${formatProcessInvocation(this)}`;
80 }
81}
82
83export class ProcessStdinError extends Schema.TaggedError<ProcessStdinError>()(
84 "ProcessStdinError",
85 {
86 ...ProcessInvocationFields,
87 stdinBytes: Schema.Number,
88 cause: Schema.Defect(),
89 },
90) {
91 override get message(): string {
92 return `Failed to write stdin for process ${formatProcessInvocation(this)}`;
93 }
94}
95
96export class ProcessOutputLimitError extends Schema.TaggedError<ProcessOutputLimitError>()(
97 "ProcessOutputLimitError",
98 {
99 ...ProcessInvocationFields,
100 stream: Schema.Literals(["stdout", "stderr"]),
101 maxBytes: Schema.Number,
102 observedBytes: Schema.Number,
103 },
104) {
105 override get message(): string {
106 return `Process ${formatProcessInvocation(this)} ${this.stream} produced ${this.observedBytes} bytes, exceeding the ${this.maxBytes} byte limit`;
107 }
108}
109
110export class ProcessReadError extends Schema.TaggedError<ProcessReadError>()("ProcessReadError", {
111 ...ProcessInvocationFields,
112 stream: Schema.Literals(["stdout", "stderr", "exitCode"]),
113 cause: Schema.Defect(),
114}) {
115 override get message(): string {
116 return `Failed to read ${this.stream} for process ${formatProcessInvocation(this)}`;
117 }
118}
119
120export class ProcessTimeoutError extends Schema.TaggedError<ProcessTimeoutError>()(
121 "ProcessTimeoutError",
122 {
123 ...ProcessInvocationFields,
124 timeoutMs: Schema.Number,
125 },
126) {
127 override get message(): string {
128 return `Process ${formatProcessInvocation(this)} timed out after ${this.timeoutMs}ms`;
129 }
130}
131
132export const ProcessRunError = Schema.Union([
133 ProcessSpawnError,
134 ProcessStdinError,
135 ProcessOutputLimitError,
136 ProcessReadError,
137 ProcessTimeoutError,
138]);
139export type ProcessRunError = typeof ProcessRunError.Type;
140
141export class ProcessRunner extends Context.Service<
142 ProcessRunner,
143 {
144 readonly run: (input: ProcessRunInput) => Effect.Effect<ProcessRunOutput, ProcessRunError>;
145 }
146>()("t3/processRunner") {}
147
148const DEFAULT_TIMEOUT = "60 seconds";
149const DEFAULT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
150
151export { isWindowsCommandNotFound } from "@t3tools/provider-core/server/snapshotProbe";
152
153const collectText = Effect.fnUntraced(function* (input: {
154 readonly command: string;
155 readonly args: ReadonlyArray<string>;
156 readonly cwd?: string | undefined;
157 readonly spawnCwd?: string | undefined;
158 readonly streamName: "stdout" | "stderr";
159 readonly stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
160 readonly maxOutputBytes: number;
161 readonly outputMode: "error" | "truncate";
162 readonly truncatedMarker: string;
163}) {
164 const stream = input.stream.pipe(
165 Stream.mapError(
166 (cause) =>
167 new ProcessReadError({
168 command: input.command,
169 argumentCount: input.args.length,
170 cwd: input.cwd,
171 spawnCwd: input.spawnCwd,
172 stream: input.streamName,
173 cause,
174 }),
175 ),
176 );
177
178 if (input.outputMode === "truncate") {
179 return yield* collectUint8StreamText({
180 stream,
181 maxBytes: input.maxOutputBytes,
182 truncatedMarker: input.truncatedMarker,
183 });
184 }
185
186 return yield* stream.pipe(
187 Stream.runFoldEffect<
188 {
189 readonly chunks: Uint8Array<ArrayBufferLike>[];
190 readonly bytes: number;
191 },
192 Uint8Array<ArrayBufferLike>,
193 ProcessOutputLimitError | ProcessReadError,
194 never
195 >(
196 () => ({ chunks: [], bytes: 0 }),
197 (state, chunk) => {
198 const remainingBytes = input.maxOutputBytes - state.bytes;
199 if (chunk.byteLength > remainingBytes) {
200 return Effect.fail(
201 new ProcessOutputLimitError({
202 command: input.command,
203 argumentCount: input.args.length,
204 cwd: input.cwd,
205 spawnCwd: input.spawnCwd,
206 stream: input.streamName,
207 maxBytes: input.maxOutputBytes,
208 observedBytes: state.bytes + chunk.byteLength,
209 }),
210 );
211 }
212
213 state.chunks.push(chunk);
214 return Effect.succeed({
215 chunks: state.chunks,
216 bytes: state.bytes + chunk.byteLength,
217 });
218 },
219 ),
220 Effect.map((state): CollectedUint8StreamText => ({
221 ...decodeUtf8(Buffer.concat(state.chunks, state.bytes)),
222 bytes: state.bytes,
223 truncated: false,
224 })),
225 );
226});
227
228function finalizeRunProcess<R>(
229 effect: Effect.Effect<ProcessRunOutput, ProcessRunError, R | Scope.Scope>,
230 input: ProcessRunInput,
231): Effect.Effect<ProcessRunOutput, ProcessRunError, Exclude<R, Scope.Scope>> {
232 const timeout = Duration.fromInputUnsafe(input.timeout ?? DEFAULT_TIMEOUT);
233 const timeoutBehavior = input.timeoutBehavior ?? "error";
234
235 return effect.pipe(
236 Effect.scoped,
237 Effect.timeoutOption(timeout),
238 Effect.flatMap((result) => {
239 if (Option.isSome(result)) {
240 return Effect.succeed(result.value);
241 }
242 if (timeoutBehavior === "timedOutResult") {
243 return Effect.succeed({
244 stdout: "",
245 stderr: "",
246 code: null,
247 timedOut: true,
248 stdoutTruncated: false,
249 stderrTruncated: false,
250 stdoutInvalidUtf8: false,
251 stderrInvalidUtf8: false,
252 } satisfies ProcessRunOutput);
253 }
254 return Effect.fail(
255 new ProcessTimeoutError({
256 command: input.command,
257 argumentCount: input.args.length,
258 cwd: input.cwd,
259 spawnCwd: input.spawnCwd,
260 timeoutMs: Duration.toMillis(timeout),
261 }),
262 );
263 }),
264 );
265}
266
267export const commandName = (command: string) => command.replace(/^.*[\\/]/, "");
268
269const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
270 spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],
271 input: ProcessRunInput,
272): Effect.fn.Return<ProcessRunOutput, ProcessRunError, Scope.Scope> {
273 yield* Effect.annotateCurrentSpan("process.command", commandName(input.command));
274 const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
275 const outputMode = input.outputMode ?? "error";
276 const truncatedMarker = input.truncatedMarker ?? "";
277 const extendEnv = input.env !== undefined;
278 const spawnCommand = yield* resolveSpawnCommand(
279 input.command,
280 input.args,
281 input.env === undefined ? {} : { env: input.env, extendEnv },
282 );
283
284 const toSpawnError = (cause: unknown) =>
285 new ProcessSpawnError({
286 command: input.command,
287 argumentCount: input.args.length,
288 cwd: input.cwd,
289 spawnCwd: input.spawnCwd,
290 resolvedCommand: spawnCommand.command,
291 resolvedArgumentCount: spawnCommand.args.length,
292 shell: spawnCommand.shell,
293 cause,
294 });
295
296 const child = yield* spawner
297 .spawn(
298 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
299 ...((input.spawnCwd ?? input.cwd) ? { cwd: input.spawnCwd ?? input.cwd } : {}),
300 ...(input.env !== undefined
301 ? {
302 env: input.env,
303 extendEnv,
304 }
305 : {}),
306 shell: spawnCommand.shell,
307 }),
308 )
309 .pipe(
310 Effect.mapError(toSpawnError),
311 // Node's spawn can also throw synchronously, e.g. ENOTDIR when a PATH
312 // entry is a file. That arrives as a defect, which `mapError` never sees,
313 // so callers that recover from spawn failures would be bypassed.
314 Effect.catchDefect((cause) => Effect.fail(toSpawnError(cause))),
315 );
316
317 const stdin = input.stdin;
318 const onStdoutChunk = input.onStdoutChunk;
319 const writeStdin =
320 stdin === undefined
321 ? Effect.void
322 : Stream.run(Stream.encodeText(Stream.make(stdin)), child.stdin).pipe(
323 Effect.mapError(
324 (cause) =>
325 new ProcessStdinError({
326 command: input.command,
327 argumentCount: input.args.length,
328 cwd: input.cwd,
329 spawnCwd: input.spawnCwd,
330 stdinBytes: Buffer.byteLength(stdin),
331 cause,
332 }),
333 ),
334 );
335
336 const [stdout, stderr] = yield* Effect.all(
337 [
338 collectText({
339 command: input.command,
340 args: input.args,
341 cwd: input.cwd,
342 spawnCwd: input.spawnCwd,
343 streamName: "stdout",
344 stream: onStdoutChunk
345 ? child.stdout.pipe(Stream.tap((chunk) => Effect.sync(() => onStdoutChunk(chunk))))
346 : child.stdout,
347 maxOutputBytes,
348 outputMode,
349 truncatedMarker,
350 }),
351 collectText({
352 command: input.command,
353 args: input.args,
354 cwd: input.cwd,
355 spawnCwd: input.spawnCwd,
356 streamName: "stderr",
357 stream: child.stderr,
358 maxOutputBytes,
359 outputMode,
360 truncatedMarker,
361 }),
362 writeStdin,
363 ],
364 { concurrency: "unbounded" },
365 );
366
367 const exitCode = yield* child.exitCode.pipe(
368 Effect.mapError(
369 (cause) =>
370 new ProcessReadError({
371 command: input.command,
372 argumentCount: input.args.length,
373 cwd: input.cwd,
374 spawnCwd: input.spawnCwd,
375 stream: "exitCode",
376 cause,
377 }),
378 ),
379 );
380
381 return {
382 stdout: stdout.text,
383 stderr: stderr.text,
384 code: exitCode,
385 timedOut: false,
386 stdoutTruncated: stdout.truncated,
387 stderrTruncated: stderr.truncated,
388 stdoutInvalidUtf8: stdout.invalidUtf8,
389 stderrInvalidUtf8: stderr.invalidUtf8,
390 } satisfies ProcessRunOutput;
391});
392
393/** @public Service construction is part of the canonical Effect module API. */
394export const make = Effect.fn("ProcessRunner.make")(function* () {
395 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
396
397 const run: ProcessRunner["Service"]["run"] = (input) =>
398 finalizeRunProcess(runProcessCore(spawner, input), input);
399
400 return ProcessRunner.of({
401 run,
402 });
403});
404
405export const layer = Layer.effect(ProcessRunner, make());