Skip to content

Commit 740b93f

Browse files
refactor(server): GitHub credential and API failures are tagged errors, not reasons switched on
GitHubCredentialUnavailableError's reason becomes GitHubCliMissingError and GitHubNotSignedInError, and gh's output is no longer folded into a sentinel string. GitHubApi classifies each answer once into a tagged enum and matches on it, instead of re-reading the status and GraphQL error types in each branch. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent f8aeb7f commit 740b93f

3 files changed

Lines changed: 182 additions & 103 deletions

File tree

‎apps/server/src/sourceControl/GitHubApi.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,17 @@ import { describe, expect, it } from "@effect/vitest";
22
import * as Effect from "effect/Effect";
33
import * as Layer from "effect/Layer";
44
import * as Redacted from "effect/Redacted";
5+
import * as PlatformError from "effect/PlatformError";
56
import * as TestClock from "effect/testing/TestClock";
7+
import { ChildProcessSpawner } from "effect/process";
8+
import { VcsProcessSpawnError } from "@t3tools/contracts";
69
import { HttpClient, HttpClientResponse, type HttpClientRequest } from "effect/http";
710

811
import * as GitHubApi from "./GitHubApi.ts";
912
import * as GitHubCredentials from "./GitHubCredentials.ts";
1013
import * as GitHubGraphQlBudget from "./githubGraphQlBudget.ts";
1114
import * as SourceControlRateLimit from "./SourceControlRateLimit.ts";
15+
import * as VcsProcess from "../vcs/VcsProcess.ts";
1216

1317
const NOW = Date.parse("2026-10-05T12:00:00.000Z");
1418

@@ -216,3 +220,53 @@ describe("GitHubApi", () => {
216220
}).pipe(Effect.provide(layer));
217221
});
218222
});
223+
224+
describe("GitHubCredentials", () => {
225+
const credentialsWith = (run: VcsProcess.VcsProcess["Service"]["run"]) =>
226+
GitHubCredentials.layer.pipe(Layer.provide(Layer.mock(VcsProcess.VcsProcess)({ run })));
227+
228+
it.effect("fails with GitHubCliMissingError when gh is not on PATH", () =>
229+
Effect.gen(function* () {
230+
const credentials = yield* GitHubCredentials.GitHubCredentials;
231+
const error = yield* Effect.flip(credentials.get("git.acme.internal"));
232+
expect(error._tag).toBe("GitHubCliMissingError");
233+
}).pipe(
234+
Effect.provide(
235+
credentialsWith(() =>
236+
Effect.fail(
237+
new VcsProcessSpawnError({
238+
operation: "GitHubCredentials.get",
239+
command: "gh",
240+
cwd: "/",
241+
cause: PlatformError.systemError({
242+
_tag: "NotFound",
243+
module: "ChildProcess",
244+
method: "spawn",
245+
}),
246+
}),
247+
),
248+
),
249+
),
250+
),
251+
);
252+
253+
it.effect("fails with GitHubNotSignedInError when gh prints no token", () =>
254+
Effect.gen(function* () {
255+
const credentials = yield* GitHubCredentials.GitHubCredentials;
256+
const error = yield* Effect.flip(credentials.get("git.acme.internal"));
257+
expect(error._tag).toBe("GitHubNotSignedInError");
258+
}).pipe(
259+
Effect.provide(
260+
credentialsWith(() =>
261+
Effect.succeed({
262+
exitCode: ChildProcessSpawner.ExitCode(0),
263+
stdout: "\n",
264+
stderr: "",
265+
stdoutTruncated: false,
266+
stderrTruncated: false,
267+
}),
268+
),
269+
),
270+
),
271+
);
272+
});

‎apps/server/src/sourceControl/GitHubApi.ts‎

Lines changed: 96 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import * as Clock from "effect/Clock";
22
import * as Context from "effect/Context";
3+
import * as Data from "effect/Data";
34
import * as Duration from "effect/Duration";
45
import * as Effect from "effect/Effect";
56
import * as Layer from "effect/Layer";
@@ -200,25 +201,6 @@ function retryAtFrom(
200201
return Number.isFinite(reset) && reset > now ? reset : undefined;
201202
}
202203

203-
function isRateLimited(
204-
status: number,
205-
headers: Readonly<Record<string, string | undefined>>,
206-
body: string,
207-
) {
208-
return (
209-
status === 429 ||
210-
(status === 403 &&
211-
(headers["x-ratelimit-remaining"] === "0" ||
212-
headers["retry-after"] !== undefined ||
213-
/rate limit/i.test(body)))
214-
);
215-
}
216-
217-
interface GraphQlErrors {
218-
readonly messages: ReadonlyArray<string>;
219-
readonly types: ReadonlyArray<string>;
220-
}
221-
222204
const decodeGraphQlErrors = Schema.decodeUnknownOption(
223205
Schema.fromJsonString(
224206
Schema.Struct({
@@ -232,14 +214,53 @@ const decodeGraphQlErrors = Schema.decodeUnknownOption(
232214
),
233215
);
234216

235-
function graphqlErrors(body: string): GraphQlErrors | null {
236-
return Option.match(decodeGraphQlErrors(body), {
237-
onNone: () => null,
238-
onSome: ({ errors }) => ({
239-
messages: errors.flatMap((error) => (error.message === undefined ? [] : [error.message])),
240-
types: errors.flatMap((error) => (error.type === undefined ? [] : [error.type])),
241-
}),
242-
});
217+
/** What one GitHub answer means, decided once from its status, headers and body. */
218+
type Answer = Data.TaggedEnum<{
219+
Ok: {};
220+
RateLimited: {};
221+
Unauthorized: {};
222+
NotFound: {};
223+
Failed: { readonly messages: ReadonlyArray<string> | undefined };
224+
}>;
225+
const Answer = Data.taggedEnum<Answer>();
226+
227+
/**
228+
* GitHub reports a failed GraphQL document with HTTP 200 and an `errors` list, so a GraphQL body
229+
* is read for its error types as well as its status. `gh api graphql` failed those too, and
230+
* callers rely on that to fall back to narrower reads.
231+
*/
232+
function classify(input: {
233+
readonly status: number;
234+
readonly headers: Readonly<Record<string, string | undefined>>;
235+
readonly body: string;
236+
readonly graphql: boolean;
237+
readonly acceptNotModified: boolean;
238+
}): Answer {
239+
const { status, headers, body } = input;
240+
const errors = input.graphql
241+
? Option.getOrUndefined(decodeGraphQlErrors(body))?.errors
242+
: undefined;
243+
const types = errors?.flatMap((error) => (error.type === undefined ? [] : [error.type])) ?? [];
244+
const messages = errors?.flatMap((error) => (error.message === undefined ? [] : [error.message]));
245+
if (
246+
status === 429 ||
247+
types.includes("RATE_LIMITED") ||
248+
(status === 403 &&
249+
(headers["x-ratelimit-remaining"] === "0" ||
250+
headers["retry-after"] !== undefined ||
251+
/rate limit/i.test(body)))
252+
) {
253+
return Answer.RateLimited();
254+
}
255+
if (status === 401) return Answer.Unauthorized();
256+
if (status === 404 || (types.length > 0 && types.every((type) => type === "NOT_FOUND"))) {
257+
return Answer.NotFound();
258+
}
259+
if (errors !== undefined) return Answer.Failed({ messages });
260+
if ((status >= 200 && status < 300) || (status === 304 && input.acceptNotModified)) {
261+
return Answer.Ok();
262+
}
263+
return Answer.Failed({ messages: undefined });
243264
}
244265

245266
/** @public Service construction is part of the canonical Effect module API. */
@@ -280,7 +301,7 @@ export const make = Effect.gen(function* () {
280301
readonly maxResponseBytes: number;
281302
readonly allowReserve: boolean;
282303
readonly acceptNotModified: boolean;
283-
/** GitHub answers a throttled GraphQL document with HTTP 200 and a `RATE_LIMITED` error. */
304+
/** Reads the body for GraphQL `errors`, which GitHub sends with HTTP 200. */
284305
readonly graphql?: boolean;
285306
}) {
286307
const host = normalizeHost(input.host);
@@ -323,41 +344,52 @@ export const make = Effect.gen(function* () {
323344
);
324345
const headers = response.headers;
325346
const status = response.status;
326-
const throttled =
327-
input.graphql === true &&
328-
status === 200 &&
329-
(graphqlErrors(collected.text)?.types.includes("RATE_LIMITED") ?? false);
330-
if (
331-
!throttled &&
332-
((status >= 200 && status < 300) || (status === 304 && input.acceptNotModified))
333-
) {
334-
yield* limits.recordSuccess({ ...key, lease });
335-
return { status, headers, body: collected.text, truncated: collected.truncated };
336-
}
337-
if (throttled || isRateLimited(status, headers, collected.text)) {
338-
const retryAt = retryAtFrom(headers, yield* Clock.currentTimeMillis);
339-
yield* limits.recordRateLimit({ ...key, lease, retryAt });
340-
return yield* new GitHubApiRateLimitError({
341-
host,
342-
operation: input.operation,
343-
...(retryAt === undefined ? {} : { retryAt }),
344-
});
345-
}
346-
if (status === 401) {
347-
// The source may hold a newer token than the one that was refused.
348-
yield* credentials.invalidate(host);
349-
return yield* new GitHubApiAuthenticationError({ host, operation: input.operation });
350-
}
351-
if (status === 404) {
352-
return yield* new GitHubApiNotFoundError({ host, operation: input.operation });
353-
}
354-
const errors = graphqlErrors(collected.text);
355-
return yield* new GitHubApiResponseError({
356-
host,
357-
operation: input.operation,
358-
status,
359-
...(errors === null ? {} : { graphqlErrors: errors.messages }),
360-
});
347+
const context = { host, operation: input.operation };
348+
return yield* Answer.$match(
349+
classify({
350+
status,
351+
headers,
352+
body: collected.text,
353+
graphql: input.graphql === true,
354+
acceptNotModified: input.acceptNotModified,
355+
}),
356+
{
357+
Ok: () =>
358+
limits
359+
.recordSuccess({ ...key, lease })
360+
.pipe(
361+
Effect.as({
362+
status,
363+
headers,
364+
body: collected.text,
365+
truncated: collected.truncated,
366+
}),
367+
),
368+
RateLimited: () =>
369+
Effect.gen(function* () {
370+
const retryAt = retryAtFrom(headers, yield* Clock.currentTimeMillis);
371+
yield* limits.recordRateLimit({ ...key, lease, retryAt });
372+
return yield* new GitHubApiRateLimitError({
373+
...context,
374+
...(retryAt === undefined ? {} : { retryAt }),
375+
});
376+
}),
377+
// The source may hold a newer token than the one that was refused.
378+
Unauthorized: () =>
379+
credentials
380+
.invalidate(host)
381+
.pipe(Effect.andThen(Effect.fail(new GitHubApiAuthenticationError(context)))),
382+
NotFound: () => Effect.fail(new GitHubApiNotFoundError(context)),
383+
Failed: ({ messages }) =>
384+
Effect.fail(
385+
new GitHubApiResponseError({
386+
...context,
387+
status,
388+
...(messages === undefined ? {} : { graphqlErrors: messages }),
389+
}),
390+
),
391+
},
392+
);
361393
});
362394
// The rate-limit scope follows the credential, so a pause on one account never blocks another.
363395
return yield* gate
@@ -412,19 +444,7 @@ export const make = Effect.gen(function* () {
412444
graphql: true,
413445
});
414446
yield* budget.observe(host, response.body);
415-
// GitHub answers a failed GraphQL document with HTTP 200 and an `errors` list. `gh api
416-
// graphql` fails those, and callers rely on that to fall back to narrower reads.
417-
const errors = graphqlErrors(response.body);
418-
if (errors === null) return response.body;
419-
if (errors.types.length > 0 && errors.types.every((type) => type === "NOT_FOUND")) {
420-
return yield* new GitHubApiNotFoundError({ host, operation: input.operation });
421-
}
422-
return yield* new GitHubApiResponseError({
423-
host,
424-
operation: input.operation,
425-
status: response.status,
426-
graphqlErrors: errors.messages,
427-
});
447+
return response.body;
428448
}).pipe(Effect.provideService(SourceControlRateLimit.CredentialScope, scope));
429449
},
430450
);

‎apps/server/src/sourceControl/GitHubCredentials.ts‎

Lines changed: 32 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -27,28 +27,37 @@ export interface GitHubCredential {
2727
readonly fingerprint: string;
2828
}
2929

30-
/**
31-
* There is no token for the host. `cli-missing` means nothing in the environment and no `gh`
32-
* to ask; `unauthenticated` means `gh` is there but holds no login for the host.
33-
*/
34-
export class GitHubCredentialUnavailableError extends Schema.TaggedError<GitHubCredentialUnavailableError>()(
35-
"GitHubCredentialUnavailableError",
36-
{
37-
host: Schema.String,
38-
reason: Schema.Literals(["cli-missing", "unauthenticated"]),
39-
},
30+
/** Nothing in the environment, and no `gh` on PATH to ask. */
31+
export class GitHubCliMissingError extends Schema.TaggedError<GitHubCliMissingError>()(
32+
"GitHubCliMissingError",
33+
{ host: Schema.String },
34+
) {
35+
get detail(): string {
36+
return `No GitHub credential for ${this.host}: set GH_TOKEN, or install the GitHub CLI and run \`gh auth login\`.`;
37+
}
38+
39+
override get message(): string {
40+
return this.detail;
41+
}
42+
}
43+
44+
/** `gh` is installed but holds no login for the host. */
45+
export class GitHubNotSignedInError extends Schema.TaggedError<GitHubNotSignedInError>()(
46+
"GitHubNotSignedInError",
47+
{ host: Schema.String },
4048
) {
4149
get detail(): string {
42-
return this.reason === "cli-missing"
43-
? `No GitHub credential for ${this.host}: set GH_TOKEN or install the GitHub CLI and run \`gh auth login\`.`
44-
: `No GitHub credential for ${this.host}: run \`gh auth login --hostname ${this.host}\`.`;
50+
return `No GitHub credential for ${this.host}: run \`gh auth login --hostname ${this.host}\`.`;
4551
}
4652

4753
override get message(): string {
4854
return this.detail;
4955
}
5056
}
5157

58+
/** There is no token for the host. */
59+
export type GitHubCredentialUnavailableError = GitHubCliMissingError | GitHubNotSignedInError;
60+
5261
/**
5362
* Where GitHub tokens come from. Callers ask per host and never see how the token was found,
5463
* so another source (an in-app OAuth login) slots in here without touching any of them.
@@ -108,27 +117,23 @@ export const make = Effect.gen(function* () {
108117
timeoutMs: 10_000,
109118
})
110119
.pipe(
120+
Effect.mapError((error) =>
121+
error._tag === "VcsProcessSpawnError" &&
122+
error.cause instanceof PlatformError.PlatformError &&
123+
error.cause.reason._tag === "NotFound"
124+
? new GitHubCliMissingError({ host })
125+
: new GitHubNotSignedInError({ host }),
126+
),
111127
Effect.map((output) => output.stdout.trim()),
112-
Effect.catch((error) =>
113-
Effect.succeed(
114-
error._tag === "VcsProcessSpawnError" &&
115-
error.cause instanceof PlatformError.PlatformError &&
116-
error.cause.reason._tag === "NotFound"
117-
? ("cli-missing" as const)
118-
: "",
119-
),
128+
Effect.filterOrFail(
129+
(token) => token !== "",
130+
() => new GitHubNotSignedInError({ host }),
120131
),
121132
);
122133

123134
const lookup = Effect.fn("GitHubCredentials.lookup")(function* (host: string) {
124135
const fromEnv = environmentToken(host, globalThis.process.env);
125136
const token = fromEnv ?? (yield* fromGh(host));
126-
if (token === "cli-missing" || token === "") {
127-
return yield* new GitHubCredentialUnavailableError({
128-
host,
129-
reason: token === "cli-missing" ? "cli-missing" : "unauthenticated",
130-
});
131-
}
132137
return {
133138
host,
134139
token: Redacted.make(token),

0 commit comments

Comments
 (0)