Skip to content

Commit f8aeb7f

Browse files
feat(server): GitHub API transport that uses gh only for the token
Adds GitHubCredentials (env token, else `gh auth token`, cached and dropped on a 401) and GitHubApi (REST and GraphQL over HttpClient with the per-host rate-limit pause, GraphQL budget, ETag revalidation and GHE/GHE.com host mapping). Nothing calls it yet. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 8bd7745 commit f8aeb7f

4 files changed

Lines changed: 813 additions & 5 deletions

File tree

Lines changed: 218 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,218 @@
1+
import { describe, expect, it } from "@effect/vitest";
2+
import * as Effect from "effect/Effect";
3+
import * as Layer from "effect/Layer";
4+
import * as Redacted from "effect/Redacted";
5+
import * as TestClock from "effect/testing/TestClock";
6+
import { HttpClient, HttpClientResponse, type HttpClientRequest } from "effect/http";
7+
8+
import * as GitHubApi from "./GitHubApi.ts";
9+
import * as GitHubCredentials from "./GitHubCredentials.ts";
10+
import * as GitHubGraphQlBudget from "./githubGraphQlBudget.ts";
11+
import * as SourceControlRateLimit from "./SourceControlRateLimit.ts";
12+
13+
const NOW = Date.parse("2026-10-05T12:00:00.000Z");
14+
15+
function harness(respond: (request: HttpClientRequest.HttpClientRequest) => Response) {
16+
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
17+
let tokens = ["first", "second"];
18+
let invalidations = 0;
19+
const credentials = Layer.succeed(
20+
GitHubCredentials.GitHubCredentials,
21+
GitHubCredentials.GitHubCredentials.of({
22+
get: (host) =>
23+
Effect.sync(() => ({
24+
host,
25+
token: Redacted.make(tokens[0]!),
26+
source: "gh" as const,
27+
fingerprint: `${host}:${tokens[0]}`,
28+
})),
29+
invalidate: () =>
30+
Effect.sync(() => {
31+
invalidations++;
32+
tokens = tokens.slice(1);
33+
}),
34+
}),
35+
);
36+
const http = Layer.succeed(
37+
HttpClient.HttpClient,
38+
HttpClient.make((request) => {
39+
requests.push(request);
40+
return Effect.succeed(HttpClientResponse.fromWeb(request, respond(request)));
41+
}),
42+
);
43+
const layer = GitHubApi.layer.pipe(
44+
Layer.provide(Layer.mergeAll(credentials, http)),
45+
Layer.provideMerge(GitHubGraphQlBudget.layer),
46+
Layer.provideMerge(SourceControlRateLimit.layer),
47+
);
48+
return { layer, requests, invalidations: () => invalidations };
49+
}
50+
51+
const json = (body: unknown, init?: ResponseInit) =>
52+
new Response(JSON.stringify(body), {
53+
...init,
54+
headers: { "content-type": "application/json", ...init?.headers },
55+
});
56+
57+
describe("gitHubApiUrls", () => {
58+
it("maps github.com, GHE.com and GitHub Enterprise Server", () => {
59+
expect(GitHubApi.gitHubApiUrls("GitHub.com")).toEqual({
60+
rest: "https://api.github.com",
61+
graphql: "https://api.github.com/graphql",
62+
});
63+
expect(GitHubApi.gitHubApiUrls("acme.ghe.com").graphql).toBe(
64+
"https://api.acme.ghe.com/graphql",
65+
);
66+
expect(GitHubApi.gitHubApiUrls("git.acme.internal")).toEqual({
67+
rest: "https://git.acme.internal/api/v3",
68+
graphql: "https://git.acme.internal/api/graphql",
69+
});
70+
});
71+
});
72+
73+
describe("environmentToken", () => {
74+
it("follows gh's precedence per kind of host", () => {
75+
const env = { GH_TOKEN: "gh", GITHUB_TOKEN: "github", GH_ENTERPRISE_TOKEN: "ghe" };
76+
expect(GitHubCredentials.environmentToken("github.com", env)).toBe("gh");
77+
expect(GitHubCredentials.environmentToken("acme.ghe.com", { GITHUB_TOKEN: "github" })).toBe(
78+
"github",
79+
);
80+
expect(GitHubCredentials.environmentToken("git.acme.internal", env)).toBe("ghe");
81+
expect(GitHubCredentials.environmentToken("git.acme.internal", { GH_TOKEN: "gh" })).toBeNull();
82+
});
83+
});
84+
85+
describe("GitHubApi", () => {
86+
it.effect("sends GraphQL with the token and records the reported budget", () => {
87+
const { layer, requests } = harness(() =>
88+
json({
89+
data: {
90+
viewer: { login: "julius" },
91+
rateLimit: { cost: 1, limit: 5000, remaining: 4999, resetAt: "2026-10-05T13:00:00Z" },
92+
},
93+
}),
94+
);
95+
return Effect.gen(function* () {
96+
yield* TestClock.setTime(NOW);
97+
const api = yield* GitHubApi.GitHubApi;
98+
const body = yield* api.graphql({
99+
host: "github.com",
100+
operation: "viewer",
101+
query: "query { viewer { login } }",
102+
});
103+
expect(body).toContain('"login":"julius"');
104+
expect(requests[0]!.url).toBe("https://api.github.com/graphql");
105+
expect(requests[0]!.headers.authorization).toBe("Bearer first");
106+
}).pipe(Effect.provide(layer));
107+
});
108+
109+
it.effect("fails a GraphQL answer that carries errors, naming GitHub's reason", () => {
110+
const { layer } = harness(() =>
111+
json({ data: null, errors: [{ type: "FORBIDDEN", message: "Resource not accessible" }] }),
112+
);
113+
return Effect.gen(function* () {
114+
const api = yield* GitHubApi.GitHubApi;
115+
const error = yield* Effect.flip(
116+
api.graphql({ host: "github.com", operation: "detail", query: "query { viewer { id } }" }),
117+
);
118+
expect(error._tag).toBe("GitHubApiResponseError");
119+
expect(error.message).toContain("Resource not accessible");
120+
}).pipe(Effect.provide(layer));
121+
});
122+
123+
it.effect("pauses the host after a GraphQL RATE_LIMITED answer until the reset", () => {
124+
const reset = Math.floor(NOW / 1000) + 600;
125+
const { layer, requests } = harness(() =>
126+
json(
127+
{ errors: [{ type: "RATE_LIMITED", message: "API rate limit exceeded" }] },
128+
{ headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) } },
129+
),
130+
);
131+
return Effect.gen(function* () {
132+
yield* TestClock.setTime(NOW);
133+
const api = yield* GitHubApi.GitHubApi;
134+
const first = yield* Effect.flip(
135+
api.graphql({ host: "github.com", operation: "summary", query: "query { viewer { id } }" }),
136+
);
137+
expect(first).toMatchObject({ _tag: "GitHubApiRateLimitError", retryAt: reset * 1000 });
138+
const second = yield* Effect.flip(
139+
api.rest({ host: "github.com", operation: "stack", path: "repos/acme/web/stacks" }),
140+
);
141+
expect(second).toMatchObject({
142+
_tag: "SourceControlRateLimitPausedError",
143+
retryAt: reset * 1000,
144+
});
145+
expect(requests).toHaveLength(1);
146+
}).pipe(Effect.provide(layer));
147+
});
148+
149+
it.effect("maps REST 403 with an exhausted quota to a rate limit, and 304 to an answer", () => {
150+
let call = 0;
151+
const { layer } = harness(() =>
152+
++call === 1
153+
? new Response(null, { status: 304 })
154+
: json(
155+
{ message: "API rate limit exceeded" },
156+
{
157+
status: 403,
158+
headers: { "retry-after": "60" },
159+
},
160+
),
161+
);
162+
return Effect.gen(function* () {
163+
yield* TestClock.setTime(NOW);
164+
const api = yield* GitHubApi.GitHubApi;
165+
const notModified = yield* api.rest({
166+
host: "github.com",
167+
operation: "checks",
168+
path: "repos/acme/web/pulls/7",
169+
ifNoneMatch: '"abc"',
170+
});
171+
expect(notModified.status).toBe(304);
172+
const error = yield* Effect.flip(
173+
api.rest({ host: "github.com", operation: "checks", path: "repos/acme/web/pulls/7" }),
174+
);
175+
expect(error).toMatchObject({ _tag: "GitHubApiRateLimitError", retryAt: NOW + 60_000 });
176+
}).pipe(Effect.provide(layer));
177+
});
178+
179+
it.effect("drops a refused token so the next request asks the source again", () => {
180+
const { layer, requests, invalidations } = harness((request) =>
181+
request.headers.authorization === "Bearer first"
182+
? new Response(null, { status: 401 })
183+
: json({ ok: true }),
184+
);
185+
return Effect.gen(function* () {
186+
const api = yield* GitHubApi.GitHubApi;
187+
const refused = yield* Effect.flip(
188+
api.rest({ host: "github.com", operation: "user", path: "user" }),
189+
);
190+
expect(refused._tag).toBe("GitHubApiAuthenticationError");
191+
expect(invalidations()).toBe(1);
192+
const answered = yield* api.rest({ host: "github.com", operation: "user", path: "user" });
193+
expect(answered.status).toBe(200);
194+
expect(requests.map((request) => request.headers.authorization)).toEqual([
195+
"Bearer first",
196+
"Bearer second",
197+
]);
198+
}).pipe(Effect.provide(layer));
199+
});
200+
201+
it.effect("refuses to send a pinned credential to another host", () => {
202+
const { layer, requests } = harness(() => json({}));
203+
return Effect.gen(function* () {
204+
const api = yield* GitHubApi.GitHubApi;
205+
const error = yield* Effect.flip(
206+
api.rest({ host: "git.acme.internal", operation: "user", path: "user" }),
207+
).pipe(
208+
Effect.provideService(GitHubApi.PinnedGitHubCredential, {
209+
host: "github.com",
210+
token: Redacted.make("pinned"),
211+
credentialFingerprint: "github.com:pinned",
212+
}),
213+
);
214+
expect(error._tag).toBe("GitHubApiAuthenticationError");
215+
expect(requests).toHaveLength(0);
216+
}).pipe(Effect.provide(layer));
217+
});
218+
});

0 commit comments

Comments
 (0)