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";
149// Keep SIGTERM-ignoring helpers from blocking timeouts or graceful shutdown.
150const FORCE_KILL_AFTER = "1 second";
151const DEFAULT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
152
153export { isWindowsCommandNotFound } from "@t3tools/provider-core/server/snapshotProbe";
154
155const collectText = Effect.fnUntraced(function* (input: {
156 readonly command: string;
157 readonly args: ReadonlyArray<string>;
158 readonly cwd?: string | undefined;
159 readonly spawnCwd?: string | undefined;
160 readonly streamName: "stdout" | "stderr";
161 readonly stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
162 readonly maxOutputBytes: number;
163 readonly outputMode: "error" | "truncate";
164 readonly truncatedMarker: string;
165}) {
166 const stream = input.stream.pipe(
167 Stream.mapError(
168 (cause) =>
169 new ProcessReadError({
170 command: input.command,
171 argumentCount: input.args.length,
172 cwd: input.cwd,
173 spawnCwd: input.spawnCwd,
174 stream: input.streamName,
175 cause,
176 }),
177 ),
178 );
179
180 if (input.outputMode === "truncate") {
181 return yield* collectUint8StreamText({
182 stream,
183 maxBytes: input.maxOutputBytes,
184 truncatedMarker: input.truncatedMarker,
185 });
186 }
187
188 return yield* stream.pipe(
189 Stream.runFoldEffect<
190 {
191 readonly chunks: Uint8Array<ArrayBufferLike>[];
192 readonly bytes: number;
193 },
194 Uint8Array<ArrayBufferLike>,
195 ProcessOutputLimitError | ProcessReadError,
196 never
197 >(
198 () => ({ chunks: [], bytes: 0 }),
199 (state, chunk) => {
200 const remainingBytes = input.maxOutputBytes - state.bytes;
201 if (chunk.byteLength > remainingBytes) {
202 return Effect.fail(
203 new ProcessOutputLimitError({
204 command: input.command,
205 argumentCount: input.args.length,
206 cwd: input.cwd,
207 spawnCwd: input.spawnCwd,
208 stream: input.streamName,
209 maxBytes: input.maxOutputBytes,
210 observedBytes: state.bytes + chunk.byteLength,
211 }),
212 );
213 }
214
215 state.chunks.push(chunk);
216 return Effect.succeed({
217 chunks: state.chunks,
218 bytes: state.bytes + chunk.byteLength,
219 });
220 },
221 ),
222 Effect.map((state): CollectedUint8StreamText => ({
223 ...decodeUtf8(Buffer.concat(state.chunks, state.bytes)),
224 bytes: state.bytes,
225 truncated: false,
226 })),
227 );
228});
229
230function finalizeRunProcess<R>(
231 effect: Effect.Effect<ProcessRunOutput, ProcessRunError, R | Scope.Scope>,
232 input: ProcessRunInput,
233): Effect.Effect<ProcessRunOutput, ProcessRunError, Exclude<R, Scope.Scope>> {
234 const timeout = Duration.fromInputUnsafe(input.timeout ?? DEFAULT_TIMEOUT);
235 const timeoutBehavior = input.timeoutBehavior ?? "error";
236
237 return effect.pipe(
238 Effect.scoped,
239 Effect.timeoutOption(timeout),
240 Effect.flatMap((result) => {
241 if (Option.isSome(result)) {
242 return Effect.succeed(result.value);
243 }
244 if (timeoutBehavior === "timedOutResult") {
245 return Effect.succeed({
246 stdout: "",
247 stderr: "",
248 code: null,
249 timedOut: true,
250 stdoutTruncated: false,
251 stderrTruncated: false,
252 stdoutInvalidUtf8: false,
253 stderrInvalidUtf8: false,
254 } satisfies ProcessRunOutput);
255 }
256 return Effect.fail(
257 new ProcessTimeoutError({
258 command: input.command,
259 argumentCount: input.args.length,
260 cwd: input.cwd,
261 spawnCwd: input.spawnCwd,
262 timeoutMs: Duration.toMillis(timeout),
263 }),
264 );
265 }),
266 );
267}
268
269const commandName = (command: string) => command.replace(/^.*[\\/]/, "");
270
271const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
272 spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],
273 input: ProcessRunInput,
274): Effect.fn.Return<ProcessRunOutput, ProcessRunError, Scope.Scope> {
275 yield* Effect.annotateCurrentSpan("process.command", commandName(input.command));
276 const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
277 const outputMode = input.outputMode ?? "error";
278 const truncatedMarker = input.truncatedMarker ?? "";
279 const extendEnv = input.env !== undefined;
280 const spawnCommand = yield* resolveSpawnCommand(
281 input.command,
282 input.args,
283 input.env === undefined ? {} : { env: input.env, extendEnv },
284 );
285
286 const toSpawnError = (cause: unknown) =>
287 new ProcessSpawnError({
288 command: input.command,
289 argumentCount: input.args.length,
290 cwd: input.cwd,
291 spawnCwd: input.spawnCwd,
292 resolvedCommand: spawnCommand.command,
293 resolvedArgumentCount: spawnCommand.args.length,
294 shell: spawnCommand.shell,
295 cause,
296 });
297
298 const child = yield* spawner
299 .spawn(
300 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
301 ...((input.spawnCwd ?? input.cwd) ? { cwd: input.spawnCwd ?? input.cwd } : {}),
302 ...(input.env !== undefined
303 ? {
304 env: input.env,
305 extendEnv,
306 }
307 : {}),
308 shell: spawnCommand.shell,
309 forceKillAfter: FORCE_KILL_AFTER,
310 }),
311 )
312 .pipe(
313 Effect.mapError(toSpawnError),
314 // Node's spawn can also throw synchronously, e.g. ENOTDIR when a PATH
315 // entry is a file. That arrives as a defect, which `mapError` never sees,
316 // so callers that recover from spawn failures would be bypassed.
317 Effect.catchDefect((cause) => Effect.fail(toSpawnError(cause))),
318 );
319
320 const stdin = input.stdin;
321 const onStdoutChunk = input.onStdoutChunk;
322 const writeStdin =
323 stdin === undefined
324 ? Effect.void
325 : Stream.run(Stream.encodeText(Stream.make(stdin)), child.stdin).pipe(
326 Effect.mapError(
327 (cause) =>
328 new ProcessStdinError({
329 command: input.command,
330 argumentCount: input.args.length,
331 cwd: input.cwd,
332 spawnCwd: input.spawnCwd,
333 stdinBytes: Buffer.byteLength(stdin),
334 cause,
335 }),
336 ),
337 );
338
339 const [stdout, stderr] = yield* Effect.all(
340 [
341 collectText({
342 command: input.command,
343 args: input.args,
344 cwd: input.cwd,
345 spawnCwd: input.spawnCwd,
346 streamName: "stdout",
347 stream: onStdoutChunk
348 ? child.stdout.pipe(Stream.tap((chunk) => Effect.sync(() => onStdoutChunk(chunk))))
349 : child.stdout,
350 maxOutputBytes,
351 outputMode,
352 truncatedMarker,
353 }),
354 collectText({
355 command: input.command,
356 args: input.args,
357 cwd: input.cwd,
358 spawnCwd: input.spawnCwd,
359 streamName: "stderr",
360 stream: child.stderr,
361 maxOutputBytes,
362 outputMode,
363 truncatedMarker,
364 }),
365 writeStdin,
366 ],
367 { concurrency: "unbounded" },
368 );
369
370 const exitCode = yield* child.exitCode.pipe(
371 Effect.mapError(
372 (cause) =>
373 new ProcessReadError({
374 command: input.command,
375 argumentCount: input.args.length,
376 cwd: input.cwd,
377 spawnCwd: input.spawnCwd,
378 stream: "exitCode",
379 cause,
380 }),
381 ),
382 );
383
384 return {
385 stdout: stdout.text,
386 stderr: stderr.text,
387 code: exitCode,
388 timedOut: false,
389 stdoutTruncated: stdout.truncated,
390 stderrTruncated: stderr.truncated,
391 stdoutInvalidUtf8: stdout.invalidUtf8,
392 stderrInvalidUtf8: stderr.invalidUtf8,
393 } satisfies ProcessRunOutput;
394});
395
396/** @public Service construction is part of the canonical Effect module API. */
397export const make = Effect.fn("ProcessRunner.make")(function* () {
398 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
399
400 const run: ProcessRunner["Service"]["run"] = (input) =>
401 finalizeRunProcess(runProcessCore(spawner, input), input);
402
403 return ProcessRunner.of({
404 run,
405 });
406});
407
408export const layer = Layer.effect(ProcessRunner, make());