Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

processRunner.ts

401 lines12.0 KB

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;
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;
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 }
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 }
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 }
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 }
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 }
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 );
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 child = yield* spawner
285 .spawn(
286 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
287 ...((input.spawnCwd ?? input.cwd) ? { cwd: input.spawnCwd ?? input.cwd } : {}),
288 ...(input.env !== undefined
289 ? {
290 env: input.env,
291 extendEnv,
292 }
293 : {}),
294 shell: spawnCommand.shell,
295 }),
296 )
297 .pipe(
298 Effect.mapError(
299 (cause) =>
300 new ProcessSpawnError({
301 command: input.command,
302 argumentCount: input.args.length,
303 cwd: input.cwd,
304 spawnCwd: input.spawnCwd,
305 resolvedCommand: spawnCommand.command,
306 resolvedArgumentCount: spawnCommand.args.length,
307 shell: spawnCommand.shell,
308 cause,
309 }),
310 ),
311 );
312​
313 const stdin = input.stdin;
314 const onStdoutChunk = input.onStdoutChunk;
315 const writeStdin =
316 stdin === undefined
317 ? Effect.void
318 : Stream.run(Stream.encodeText(Stream.make(stdin)), child.stdin).pipe(
319 Effect.mapError(
320 (cause) =>
321 new ProcessStdinError({
322 command: input.command,
323 argumentCount: input.args.length,
324 cwd: input.cwd,
325 spawnCwd: input.spawnCwd,
326 stdinBytes: Buffer.byteLength(stdin),
327 cause,
328 }),
329 ),
330 );
331​
332 const [stdout, stderr] = yield* Effect.all(
333 [
334 collectText({
335 command: input.command,
336 args: input.args,
337 cwd: input.cwd,
338 spawnCwd: input.spawnCwd,
339 streamName: "stdout",
340 stream: onStdoutChunk
341 ? child.stdout.pipe(Stream.tap((chunk) => Effect.sync(() => onStdoutChunk(chunk))))
342 : child.stdout,
343 maxOutputBytes,
344 outputMode,
345 truncatedMarker,
346 }),
347 collectText({
348 command: input.command,
349 args: input.args,
350 cwd: input.cwd,
351 spawnCwd: input.spawnCwd,
352 streamName: "stderr",
353 stream: child.stderr,
354 maxOutputBytes,
355 outputMode,
356 truncatedMarker,
357 }),
358 writeStdin,
359 ],
360 { concurrency: "unbounded" },
361 );
362​
363 const exitCode = yield* child.exitCode.pipe(
364 Effect.mapError(
365 (cause) =>
366 new ProcessReadError({
367 command: input.command,
368 argumentCount: input.args.length,
369 cwd: input.cwd,
370 spawnCwd: input.spawnCwd,
371 stream: "exitCode",
372 cause,
373 }),
374 ),
375 );
376​
377 return {
378 stdout: stdout.text,
379 stderr: stderr.text,
380 code: exitCode,
381 timedOut: false,
382 stdoutTruncated: stdout.truncated,
383 stderrTruncated: stderr.truncated,
384 stdoutInvalidUtf8: stdout.invalidUtf8,
385 stderrInvalidUtf8: stderr.invalidUtf8,
386 } satisfies ProcessRunOutput;
387});
388​
389/** @public Service construction is part of the canonical Effect module API. */
390export const make = Effect.fn("ProcessRunner.make")(function* () {
391 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
392​
393 const run: ProcessRunner["Service"]["run"] = (input) =>
394 finalizeRunProcess(runProcessCore(spawner, input), input);
395​
396 return ProcessRunner.of({
397 run,
398 });
399});
400​
401export const layer = Layer.effect(ProcessRunner, make());