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

VcsProcess.ts

197 lines6.5 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Match from "effect/Match";
5import * as Semaphore from "effect/Semaphore";
6import { ChildProcessSpawner } from "effect/unstable/process";
7​
8import {
9 type VcsError,
10 VcsProcessExitError,
11 type VcsProcessExitFailureKind,
12 VcsProcessMissingExitCodeError,
13 VcsProcessOutputLimitError,
14 VcsProcessOutputReadError,
15 VcsProcessSpawnError,
16 VcsProcessStdinWriteError,
17 VcsProcessTimeoutError,
18} from "@t3tools/contracts";
19import * as ProcessRunner from "../processRunner.ts";
20​
21export interface VcsProcessInput {
22 readonly operation: string;
23 readonly command: string;
24 readonly args: ReadonlyArray<string>;
25 readonly cwd: string;
26 readonly spawnCwd?: string;
27 readonly stdin?: string;
28 readonly env?: NodeJS.ProcessEnv;
29 readonly allowNonZeroExit?: boolean;
30 readonly timeoutMs?: number;
31 readonly maxOutputBytes?: number;
32 readonly appendTruncationMarker?: boolean;
34​
35export interface VcsProcessOutput {
36 readonly exitCode: ChildProcessSpawner.ExitCode;
37 readonly stdout: string;
38 readonly stderr: string;
39 readonly stdoutTruncated: boolean;
40 readonly stderrTruncated: boolean;
41 /** Present on real process output; optional so narrow test doubles remain lightweight. */
42 readonly stdoutInvalidUtf8?: boolean;
43 readonly stderrInvalidUtf8?: boolean;
45​
46export class VcsProcess extends Context.Service<
47 VcsProcess,
48 {
49 readonly run: (input: VcsProcessInput) => Effect.Effect<VcsProcessOutput, VcsError>;
50 }
51>()("t3/vcs/VcsProcess") {}
52​
53const DEFAULT_TIMEOUT_MS = 30_000;
54const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
55const OUTPUT_TRUNCATED_MARKER = "\n\n[truncated]";
56const VCS_PROCESS_CONCURRENCY = 8;
57const GITHUB_PROCESS_CONCURRENCY = 4;
58​
59const classifyNonZeroExit = (command: string, stderr: string): VcsProcessExitFailureKind => {
60 const normalized = stderr.toLowerCase();
61​
62 if (
63 normalized.includes("authentication failed") ||
64 normalized.includes("not logged in") ||
65 normalized.includes("gh auth login") ||
66 normalized.includes("glab auth login") ||
67 normalized.includes("az devops login") ||
68 normalized.includes("please run az login") ||
69 normalized.includes("no oauth token") ||
70 normalized.includes("unauthorized")
71 ) {
72 return "authentication";
73 }
74​
75 if (
76 normalized.includes("api rate limit") ||
77 normalized.includes("rate limit exceeded") ||
78 normalized.includes("secondary rate limit") ||
79 normalized.includes("too many requests") ||
80 normalized.includes("http 429")
81 ) {
82 return "rate-limited";
83 }
84​
85 if (
86 (command === "gh" &&
87 (normalized.includes("could not resolve to a pullrequest") ||
88 normalized.includes("repository.pullrequest") ||
89 normalized.includes("no pull requests found for branch") ||
90 normalized.includes("pull request not found"))) ||
91 (command === "glab" &&
92 (normalized.includes("merge request not found") ||
93 normalized.includes("not found") ||
94 normalized.includes("404"))) ||
95 (command === "az" &&
96 normalized.includes("pull request") &&
97 (normalized.includes("not found") || normalized.includes("does not exist")))
98 ) {
99 return "not-found";
100 }
101​
102 return "command-failed";
103};
104​
105export const make = Effect.gen(function* () {
106 const processRunner = yield* ProcessRunner.ProcessRunner;
107 const vcsProcesses = yield* Semaphore.make(VCS_PROCESS_CONCURRENCY);
108 const githubProcesses = yield* Semaphore.make(GITHUB_PROCESS_CONCURRENCY);
109​
110 const runUnbounded = Effect.fn("VcsProcess.runUnbounded")(function* (input: VcsProcessInput) {
111 const baseError = {
112 operation: input.operation,
113 command: input.command,
114 cwd: input.cwd,
115 argumentCount: input.args.length,
116 };
117​
118 const result = yield* processRunner
119 .run({
120 command: input.command,
121 args: input.args,
122 cwd: input.cwd,
123 ...(input.spawnCwd !== undefined ? { spawnCwd: input.spawnCwd } : {}),
124 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
125 ...(input.env !== undefined ? { env: input.env } : {}),
126 timeout: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
127 maxOutputBytes: input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
128 outputMode: "truncate",
129 truncatedMarker: input.appendTruncationMarker ? OUTPUT_TRUNCATED_MARKER : "",
130 timeoutBehavior: "error",
131 })
132 .pipe(
133 Effect.mapError(
134 Match.valueTags({
135 ProcessSpawnError: (error) =>
136 VcsProcessSpawnError.fromProcessSpawnError(baseError, error),
137 ProcessOutputLimitError: (error) =>
138 new VcsProcessOutputLimitError({
139 ...baseError,
140 stream: error.stream,
141 maxBytes: error.maxBytes,
142 observedBytes: error.observedBytes,
143 }),
144 ProcessTimeoutError: (error) =>
145 VcsProcessTimeoutError.fromProcessTimeoutError(baseError, error),
146 ProcessStdinError: (error) =>
147 new VcsProcessStdinWriteError({
148 ...baseError,
149 stdinBytes: error.stdinBytes,
150 cause: error.cause,
151 }),
152 ProcessReadError: (error) =>
153 new VcsProcessOutputReadError({
154 ...baseError,
155 stream: error.stream,
156 cause: error.cause,
157 }),
158 }),
159 ),
160 );
161​
162 if (result.code === null) {
163 return yield* new VcsProcessMissingExitCodeError(baseError);
164 }
165​
166 if (!input.allowNonZeroExit && result.code !== 0) {
167 return yield* VcsProcessExitError.fromProcessExit(
168 baseError,
169 {
170 exitCode: result.code,
171 stderr: result.stderr,
172 stderrTruncated: result.stderrTruncated,
173 },
174 classifyNonZeroExit(input.command, result.stderr),
175 );
176 }
177​
178 return {
179 exitCode: result.code,
180 stdout: result.stdout,
181 stderr: result.stderr,
182 stdoutTruncated: result.stdoutTruncated,
183 stderrTruncated: result.stderrTruncated,
184 stdoutInvalidUtf8: result.stdoutInvalidUtf8 ?? false,
185 stderrInvalidUtf8: result.stderrInvalidUtf8 ?? false,
186 } satisfies VcsProcessOutput;
187 });
188​
189 const run = Effect.fn("VcsProcess.run")(function* (input: VcsProcessInput) {
190 const bounded = vcsProcesses.withPermits(1)(runUnbounded(input));
191 return yield* input.command === "gh" ? githubProcesses.withPermits(1)(bounded) : bounded;
192 });
193​
194 return VcsProcess.of({ run });
195});
196​
197export const layer = Layer.effect(VcsProcess, make).pipe(Layer.provide(ProcessRunner.layer));