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 * as WindowsSpawn from "./process/WindowsSpawn.ts";
14import {
15 collectUint8StreamText,
16 decodeUtf8,
17 type CollectedUint8StreamText,
18} from "@t3tools/provider-core/server/collectStreamText";
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 /** Receives every stdout chunk, including bytes beyond the buffered output limit. */
29 readonly onStdoutChunk?: ((chunk: Uint8Array) => void) | undefined;
30 readonly maxOutputBytes?: number | undefined;
31 readonly outputMode?: "error" | "truncate" | undefined;
32 readonly truncatedMarker?: string | undefined;
33 /** Timed-out results discard partial stdout/stderr. */
34 readonly timeoutBehavior?: "error" | "timedOutResult" | undefined;
35}
36
37export interface ProcessRunOutput {
38 readonly stdout: string;
39 readonly stderr: string;
40 readonly code: ChildProcessSpawner.ExitCode | null;
41 readonly timedOut: boolean;
42 readonly stdoutTruncated: boolean;
43 readonly stderrTruncated: boolean;
44 readonly stdoutInvalidUtf8: boolean;
45 readonly stderrInvalidUtf8: boolean;
46}
47
48const ProcessInvocationFields = {
49 command: Schema.String,
50 argumentCount: Schema.Number,
51 cwd: Schema.optional(Schema.String),
52 spawnCwd: Schema.optional(Schema.String),
53};
54
55const formatProcessInvocation = (input: {
56 readonly command: string;
57 readonly cwd?: string | undefined;
58 readonly spawnCwd?: string | undefined;
59}): string => {
60 const executionCwd = input.spawnCwd ?? input.cwd;
61 return executionCwd === undefined
62 ? `'${input.command}'`
63 : `'${input.command}' in '${executionCwd}'`;
64};
65
66export class ProcessSpawnError extends Schema.TaggedError<ProcessSpawnError>()(
67 "ProcessSpawnError",
68 {
69 ...ProcessInvocationFields,
70 resolvedCommand: Schema.optional(Schema.String),
71 resolvedArgumentCount: Schema.optional(Schema.Number),
72 shell: Schema.optional(Schema.Boolean),
73 cause: Schema.Defect(),
74 },
75) {
76 override get message(): string {
77 return `Failed to spawn process ${formatProcessInvocation(this)}`;
78 }
79}
80
81export class ProcessStdinError extends Schema.TaggedError<ProcessStdinError>()(
82 "ProcessStdinError",
83 {
84 ...ProcessInvocationFields,
85 stdinBytes: Schema.Number,
86 cause: Schema.Defect(),
87 },
88) {
89 override get message(): string {
90 return `Failed to write stdin for process ${formatProcessInvocation(this)}`;
91 }
92}
93
94export class ProcessOutputLimitError extends Schema.TaggedError<ProcessOutputLimitError>()(
95 "ProcessOutputLimitError",
96 {
97 ...ProcessInvocationFields,
98 stream: Schema.Literals(["stdout", "stderr"]),
99 maxBytes: Schema.Number,
100 observedBytes: Schema.Number,
101 },
102) {
103 override get message(): string {
104 return `Process ${formatProcessInvocation(this)} ${this.stream} produced ${this.observedBytes} bytes, exceeding the ${this.maxBytes} byte limit`;
105 }
106}
107
108export class ProcessReadError extends Schema.TaggedError<ProcessReadError>()("ProcessReadError", {
109 ...ProcessInvocationFields,
110 stream: Schema.Literals(["stdout", "stderr", "exitCode"]),
111 cause: Schema.Defect(),
112}) {
113 override get message(): string {
114 return `Failed to read ${this.stream} for process ${formatProcessInvocation(this)}`;
115 }
116}
117
118export class ProcessTimeoutError extends Schema.TaggedError<ProcessTimeoutError>()(
119 "ProcessTimeoutError",
120 {
121 ...ProcessInvocationFields,
122 timeoutMs: Schema.Number,
123 },
124) {
125 override get message(): string {
126 return `Process ${formatProcessInvocation(this)} timed out after ${this.timeoutMs}ms`;
127 }
128}
129
130export const ProcessRunError = Schema.Union([
131 ProcessSpawnError,
132 ProcessStdinError,
133 ProcessOutputLimitError,
134 ProcessReadError,
135 ProcessTimeoutError,
136]);
137export type ProcessRunError = typeof ProcessRunError.Type;
138
139export class ProcessRunner extends Context.Service<
140 ProcessRunner,
141 {
142 readonly run: (input: ProcessRunInput) => Effect.Effect<ProcessRunOutput, ProcessRunError>;
143 }
144>()("t3/processRunner") {}
145
146const DEFAULT_TIMEOUT = "60 seconds";
147// Keep SIGTERM-ignoring helpers from blocking timeouts or graceful shutdown.
148const FORCE_KILL_AFTER = "1 second";
149const DEFAULT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
150
151const collectText = Effect.fnUntraced(function* (input: {
152 readonly command: string;
153 readonly args: ReadonlyArray<string>;
154 readonly cwd?: string | undefined;
155 readonly spawnCwd?: string | undefined;
156 readonly streamName: "stdout" | "stderr";
157 readonly stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
158 readonly maxOutputBytes: number;
159 readonly outputMode: "error" | "truncate";
160 readonly truncatedMarker: string;
161}) {
162 const stream = input.stream.pipe(
163 Stream.mapError(
164 (cause) =>
165 new ProcessReadError({
166 command: input.command,
167 argumentCount: input.args.length,
168 cwd: input.cwd,
169 spawnCwd: input.spawnCwd,
170 stream: input.streamName,
171 cause,
172 }),
173 ),
174 );
175
176 if (input.outputMode === "truncate") {
177 return yield* collectUint8StreamText({
178 stream,
179 maxBytes: input.maxOutputBytes,
180 truncatedMarker: input.truncatedMarker,
181 });
182 }
183
184 return yield* stream.pipe(
185 Stream.runFoldEffect<
186 {
187 readonly chunks: Uint8Array<ArrayBufferLike>[];
188 readonly bytes: number;
189 },
190 Uint8Array<ArrayBufferLike>,
191 ProcessOutputLimitError | ProcessReadError,
192 never
193 >(
194 () => ({ chunks: [], bytes: 0 }),
195 (state, chunk) => {
196 const remainingBytes = input.maxOutputBytes - state.bytes;
197 if (chunk.byteLength > remainingBytes) {
198 return Effect.fail(
199 new ProcessOutputLimitError({
200 command: input.command,
201 argumentCount: input.args.length,
202 cwd: input.cwd,
203 spawnCwd: input.spawnCwd,
204 stream: input.streamName,
205 maxBytes: input.maxOutputBytes,
206 observedBytes: state.bytes + chunk.byteLength,
207 }),
208 );
209 }
210
211 state.chunks.push(chunk);
212 return Effect.succeed({
213 chunks: state.chunks,
214 bytes: state.bytes + chunk.byteLength,
215 });
216 },
217 ),
218 Effect.map((state): CollectedUint8StreamText => ({
219 ...decodeUtf8(Buffer.concat(state.chunks, state.bytes)),
220 bytes: state.bytes,
221 truncated: false,
222 })),
223 );
224});
225
226function finalizeRunProcess<R>(
227 effect: Effect.Effect<ProcessRunOutput, ProcessRunError, R | Scope.Scope>,
228 input: ProcessRunInput,
229): Effect.Effect<ProcessRunOutput, ProcessRunError, Exclude<R, Scope.Scope>> {
230 const timeout = Duration.fromInputUnsafe(input.timeout ?? DEFAULT_TIMEOUT);
231 const timeoutBehavior = input.timeoutBehavior ?? "error";
232
233 return effect.pipe(
234 Effect.scoped,
235 Effect.timeoutOption(timeout),
236 Effect.flatMap((result) => {
237 if (Option.isSome(result)) {
238 return Effect.succeed(result.value);
239 }
240 if (timeoutBehavior === "timedOutResult") {
241 return Effect.succeed({
242 stdout: "",
243 stderr: "",
244 code: null,
245 timedOut: true,
246 stdoutTruncated: false,
247 stderrTruncated: false,
248 stdoutInvalidUtf8: false,
249 stderrInvalidUtf8: false,
250 } satisfies ProcessRunOutput);
251 }
252 return Effect.fail(
253 new ProcessTimeoutError({
254 command: input.command,
255 argumentCount: input.args.length,
256 cwd: input.cwd,
257 spawnCwd: input.spawnCwd,
258 timeoutMs: Duration.toMillis(timeout),
259 }),
260 );
261 }),
262 );
263}
264
265const commandName = (command: string) => command.replace(/^.*[\\/]/, "");
266
267type Spawn = (
268 command: ChildProcess.StandardCommand,
269) => Effect.Effect<
270 Pick<ChildProcessSpawner.ChildProcessHandle, "stdin" | "stdout" | "stderr" | "exitCode">,
271 PlatformError.PlatformError,
272 Scope.Scope
273>;
274
275const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
276 spawn: Spawn,
277 input: ProcessRunInput,
278): Effect.fn.Return<ProcessRunOutput, ProcessRunError, Scope.Scope> {
279 yield* Effect.annotateCurrentSpan("process.command", commandName(input.command));
280 const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
281 const outputMode = input.outputMode ?? "error";
282 const truncatedMarker = input.truncatedMarker ?? "";
283 const extendEnv = input.env !== undefined;
284 const spawnCommand = yield* resolveSpawnCommand(
285 input.command,
286 input.args,
287 input.env === undefined ? {} : { env: input.env, extendEnv },
288 );
289
290 const toSpawnError = (cause: unknown) =>
291 new ProcessSpawnError({
292 command: input.command,
293 argumentCount: input.args.length,
294 cwd: input.cwd,
295 spawnCwd: input.spawnCwd,
296 resolvedCommand: spawnCommand.command,
297 resolvedArgumentCount: spawnCommand.args.length,
298 shell: spawnCommand.shell,
299 cause,
300 });
301
302 const child = yield* spawn(
303 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
304 ...((input.spawnCwd ?? input.cwd) ? { cwd: input.spawnCwd ?? input.cwd } : {}),
305 ...(input.env !== undefined
306 ? {
307 env: input.env,
308 extendEnv,
309 }
310 : {}),
311 shell: spawnCommand.shell,
312 forceKillAfter: FORCE_KILL_AFTER,
313 }),
314 ).pipe(
315 Effect.mapError(toSpawnError),
316 // Synchronous spawn throws arrive as defects; recover them too so callers see typed spawn failures.
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 */
397export const make = Effect.fn("ProcessRunner.make")(function* () {
398 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
399 const spawn = (yield* WindowsSpawn.WindowsSpawn) ?? spawner.spawn;
400
401 const run = Effect.fn("ProcessRunner.run")((input: ProcessRunInput) =>
402 finalizeRunProcess(runProcessCore(spawn, input), input),
403 );
404
405 return ProcessRunner.of({
406 run,
407 });
408});
409
410export const layer = Layer.effect(ProcessRunner, make()).pipe(Layer.provide(WindowsSpawn.layer));