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

VcsProcess.ts

228 lines7.3 KB

1import { Duration, Context, Effect, Layer, Option, PlatformError, Sink, Stream } from "effect";
2import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
3​
4import {
5 VcsOutputDecodeError,
6 type VcsError,
7 VcsProcessExitError,
8 VcsProcessSpawnError,
9 VcsProcessTimeoutError,
10} from "@t3tools/contracts";
11import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
12​
13export interface VcsProcessInput {
14 readonly operation: string;
15 readonly command: string;
16 readonly args: ReadonlyArray<string>;
17 readonly cwd: string;
18 readonly stdin?: string;
19 readonly env?: NodeJS.ProcessEnv;
20 readonly allowNonZeroExit?: boolean;
21 readonly timeoutMs?: number;
22 readonly maxOutputBytes?: number;
23 readonly truncateOutputAtMaxBytes?: boolean;
25​
26export interface VcsProcessOutput {
27 readonly exitCode: ChildProcessSpawner.ExitCode;
28 readonly stdout: string;
29 readonly stderr: string;
30 readonly stdoutTruncated: boolean;
31 readonly stderrTruncated: boolean;
33​
34export interface VcsProcessCollectedText {
35 readonly text: string;
36 readonly truncated: boolean;
38​
39export interface VcsProcessHandle {
40 readonly pid: ChildProcessSpawner.ProcessId;
41 readonly stdin: Sink.Sink<void, Uint8Array, never, VcsError>;
42 readonly stdout: Stream.Stream<Uint8Array, VcsError>;
43 readonly stderr: Stream.Stream<Uint8Array, VcsError>;
44 readonly exitCode: Effect.Effect<ChildProcessSpawner.ExitCode, VcsError>;
45 readonly writeStdin: (input: string) => Effect.Effect<void, VcsError>;
47​
48export interface VcsProcessShape {
49 readonly withProcess: <A, E, R>(
50 input: VcsProcessInput,
51 use: (handle: VcsProcessHandle) => Effect.Effect<A, E, R>,
52 ) => Effect.Effect<A, E | VcsError, R>;
53 readonly run: (input: VcsProcessInput) => Effect.Effect<VcsProcessOutput, VcsError>;
55​
56export class VcsProcess extends Context.Service<VcsProcess, VcsProcessShape>()(
57 "t3/vcs/VcsProcess",
58) {}
59​
60const DEFAULT_TIMEOUT_MS = 30_000;
61const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
62const OUTPUT_TRUNCATED_MARKER = "\n\n[truncated]";
63​
64function commandLabel(command: string, args: ReadonlyArray<string>): string {
65 return [command, ...args].join(" ");
67​
68function outputDecodeError(
69 input: VcsProcessInput,
70 detail: string,
71 cause: unknown,
72): VcsOutputDecodeError {
73 return new VcsOutputDecodeError({
74 operation: input.operation,
75 command: commandLabel(input.command, input.args),
76 cwd: input.cwd,
77 detail,
78 cause,
79 });
81​
82export const collectText = Effect.fn("VcsProcess.collectText")(function* (input: {
83 readonly operation: string;
84 readonly command: string;
85 readonly cwd: string;
86 readonly stream: Stream.Stream<Uint8Array, VcsError>;
87 readonly maxOutputBytes?: number;
88 readonly truncateOutputAtMaxBytes?: boolean;
89}) {
90 const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
91 return yield* collectUint8StreamText({
92 stream: input.stream,
93 maxBytes: maxOutputBytes,
94 truncatedMarker: input.truncateOutputAtMaxBytes ? OUTPUT_TRUNCATED_MARKER : null,
95 });
96});
97​
98export const make = Effect.fn("makeVcsProcess")(function* () {
99 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
100​
101 const spawn = Effect.fn("VcsProcess.spawn")(function* (input: VcsProcessInput) {
102 const label = commandLabel(input.command, input.args);
103 const child = yield* spawner
104 .spawn(
105 ChildProcess.make(input.command, [...input.args], {
106 cwd: input.cwd,
107 env: {
108 ...process.env,
109 ...input.env,
110 },
111 }),
112 )
113 .pipe(
114 Effect.mapError(
115 (cause) =>
116 new VcsProcessSpawnError({
117 operation: input.operation,
118 command: label,
119 cwd: input.cwd,
120 cause,
121 }),
122 ),
123 );
124 yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));
125​
126 const mapStreamError = (streamName: "stdout" | "stderr") =>
127 Stream.mapError((cause: PlatformError.PlatformError) =>
128 outputDecodeError(input, `failed to read process ${streamName}`, cause),
129 );
130 const mapEffectError = (detail: string) =>
131 Effect.mapError((cause: PlatformError.PlatformError) =>
132 outputDecodeError(input, detail, cause),
133 );
134 const writeStdin = (stdin: string) =>
135 Stream.run(Stream.encodeText(Stream.make(stdin)), child.stdin).pipe(
136 mapEffectError("failed to write process stdin"),
137 );
138​
139 return {
140 pid: child.pid,
141 stdin: child.stdin.pipe(
142 Sink.mapError((cause) => outputDecodeError(input, "failed to write process stdin", cause)),
143 ),
144 stdout: child.stdout.pipe(mapStreamError("stdout")),
145 stderr: child.stderr.pipe(mapStreamError("stderr")),
146 exitCode: child.exitCode.pipe(mapEffectError("failed to read process exit code")),
147 writeStdin,
148 } satisfies VcsProcessHandle;
149 });
150​
151 const withProcess: VcsProcessShape["withProcess"] = (input, use) =>
152 Effect.scoped(spawn(input).pipe(Effect.flatMap(use)));
153​
154 const run = Effect.fn("VcsProcess.run")(function* (input: VcsProcessInput) {
155 const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
156 const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
157 const label = commandLabel(input.command, input.args);
158​
159 const runProcess = Effect.gen(function* () {
160 const [stdout, stderr, exitCode] = yield* withProcess(input, (child) =>
161 Effect.all(
162 [
163 collectText({
164 operation: input.operation,
165 command: label,
166 cwd: input.cwd,
167 stream: child.stdout,
168 maxOutputBytes,
169 truncateOutputAtMaxBytes: input.truncateOutputAtMaxBytes ?? false,
170 }),
171 collectText({
172 operation: input.operation,
173 command: label,
174 cwd: input.cwd,
175 stream: child.stderr,
176 maxOutputBytes,
177 truncateOutputAtMaxBytes: input.truncateOutputAtMaxBytes ?? false,
178 }),
179 child.exitCode,
180 input.stdin === undefined ? Effect.void : child.writeStdin(input.stdin),
181 ],
182 { concurrency: "unbounded" },
183 ),
184 ).pipe(Effect.map(([stdout, stderr, exitCode]) => [stdout, stderr, exitCode] as const));
185​
186 if (!input.allowNonZeroExit && exitCode !== 0) {
187 return yield* new VcsProcessExitError({
188 operation: input.operation,
189 command: label,
190 cwd: input.cwd,
191 exitCode,
192 detail: stderr.text.trim() || `${label} exited with code ${exitCode}.`,
193 });
194 }
195​
196 return {
197 exitCode,
198 stdout: stdout.text,
199 stderr: stderr.text,
200 stdoutTruncated: stdout.truncated,
201 stderrTruncated: stderr.truncated,
202 } satisfies VcsProcessOutput;
203 });
204​
205 return yield* runProcess.pipe(
206 Effect.scoped,
207 Effect.timeoutOption(Duration.millis(timeoutMs)),
208 Effect.flatMap((result) =>
209 Option.match(result, {
210 onSome: Effect.succeed,
211 onNone: () =>
212 Effect.fail(
213 new VcsProcessTimeoutError({
214 operation: input.operation,
215 command: label,
216 cwd: input.cwd,
217 timeoutMs,
218 }),
219 ),
220 }),
221 ),
222 );
223 });
224​
225 return VcsProcess.of({ withProcess, run });
226});
227​
228export const layer = Layer.effect(VcsProcess, make());