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

VcsProcess.ts

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