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

VcsProcess.ts

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