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