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

GitHubApi.test.ts

497 lines18.0 KB

1import { describe, expect, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Redacted from "effect/Redacted";
6import * as PlatformError from "effect/PlatformError";
7import * as TestClock from "effect/testing/TestClock";
8import * as Tracer from "effect/Tracer";
9import { ChildProcessSpawner } from "effect/process";
10import { VcsProcessSpawnError, VcsProcessTimeoutError } from "@t3tools/contracts";
11import { HttpClient, HttpClientResponse, type HttpClientRequest } from "effect/http";
12​
13import * as GitHubApi from "./GitHubApi.ts";
14import * as GitHubCredentials from "./GitHubCredentials.ts";
15import * as GitHubGraphQlBudget from "./githubGraphQlBudget.ts";
16import * as SourceControlRateLimit from "./SourceControlRateLimit.ts";
17import * as VcsProcess from "../vcs/VcsProcess.ts";
18​
19const NOW = Date.parse("2026-10-05T12:00:00.000Z");
20​
21function harness(respond: (request: HttpClientRequest.HttpClientRequest) => Response) {
22 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
23 let tokens = ["first", "second"];
24 let invalidations = 0;
25 const credentials = Layer.succeed(
26 GitHubCredentials.GitHubCredentials,
27 GitHubCredentials.GitHubCredentials.of({
28 get: (host) =>
29 Effect.sync(() => ({
30 host,
31 token: Redacted.make(tokens[0]!),
32 source: "gh" as const,
33 fingerprint: `${host}:${tokens[0]}`,
34 })),
35 invalidate: () =>
36 Effect.sync(() => {
37 invalidations++;
38 tokens = tokens.slice(1);
39 }),
40 }),
41 );
42 const http = Layer.succeed(
43 HttpClient.HttpClient,
44 HttpClient.make((request) => {
45 requests.push(request);
46 return Effect.succeed(HttpClientResponse.fromWeb(request, respond(request)));
47 }),
48 );
49 const layer = GitHubApi.layer.pipe(
50 Layer.provide(Layer.mergeAll(credentials, http)),
51 Layer.provideMerge(GitHubGraphQlBudget.layer),
52 Layer.provideMerge(SourceControlRateLimit.layer),
53 );
54 return { layer, requests, invalidations: () => invalidations };
56​
57const json = (body: unknown, init?: ResponseInit) =>
58 new Response(JSON.stringify(body), {
59 ...init,
60 headers: { "content-type": "application/json", ...init?.headers },
61 });
62​
63describe("gitHubApiUrls", () => {
64 it("maps github.com, GHE.com and GitHub Enterprise Server", () => {
65 expect(GitHubApi.gitHubApiUrls("GitHub.com")).toEqual({
66 rest: "https://api.github.com",
67 graphql: "https://api.github.com/graphql",
68 });
69 expect(GitHubApi.gitHubApiUrls("acme.ghe.com").graphql).toBe(
70 "https://api.acme.ghe.com/graphql",
71 );
72 expect(GitHubApi.gitHubApiUrls("git.acme.internal")).toEqual({
73 rest: "https://git.acme.internal/api/v3",
74 graphql: "https://git.acme.internal/api/graphql",
75 });
76 });
77});
78​
79describe("environmentToken", () => {
80 it("follows gh's precedence per kind of host", () => {
81 const env = { GH_TOKEN: "gh", GITHUB_TOKEN: "github", GH_ENTERPRISE_TOKEN: "ghe" };
82 expect(GitHubCredentials.environmentToken("github.com", env)).toBe("gh");
83 expect(GitHubCredentials.environmentToken("acme.ghe.com", { GITHUB_TOKEN: "github" })).toBe(
84 "github",
85 );
86 // An enterprise token only goes to the host GH_HOST names, never to whatever a remote says.
87 expect(GitHubCredentials.environmentToken("git.acme.internal", env)).toBeNull();
88 expect(
89 GitHubCredentials.environmentToken("git.acme.internal", {
90 ...env,
91 GH_HOST: "git.acme.internal",
92 }),
93 ).toBe("ghe");
94 expect(GitHubCredentials.environmentToken("git.acme.internal", { GH_TOKEN: "gh" })).toBeNull();
95 });
96});
97​
98describe("GitHubApi", () => {
99 it.effect("sends GraphQL with the token and records the reported budget", () => {
100 const { layer, requests } = harness(() =>
101 json({
102 data: {
103 viewer: { login: "julius" },
104 rateLimit: { cost: 1, limit: 5000, remaining: 4999, resetAt: "2026-10-05T13:00:00Z" },
105 },
106 }),
107 );
108 return Effect.gen(function* () {
109 yield* TestClock.setTime(NOW);
110 const api = yield* GitHubApi.GitHubApi;
111 const body = yield* api.graphql({
112 host: "github.com",
113 operation: "viewer",
114 query: "query { viewer { login } }",
115 });
116 expect(body).toContain('"login":"julius"');
117 expect(requests[0]!.url).toBe("https://api.github.com/graphql");
118 expect(requests[0]!.headers.authorization).toBe("Bearer first");
119 }).pipe(Effect.provide(layer));
120 });
121​
122 it.effect(
123 "traces the operation, path, query and cost, never the query string or variables",
124 () => {
125 const spans: Array<Tracer.NativeSpan> = [];
126 const tracer = Tracer.make({
127 span: (options) => {
128 const span = new Tracer.NativeSpan(options);
129 spans.push(span);
130 return span;
131 },
132 });
133 const { layer } = harness((request) =>
134 request.url.endsWith("/graphql")
135 ? json(
136 {
137 data: {
138 viewer: { login: "julius" },
139 rateLimit: {
140 cost: 3,
141 limit: 5000,
142 remaining: 4990,
143 resetAt: "2026-10-05T13:00:00Z",
144 },
145 },
146 },
147 { headers: { "x-ratelimit-remaining": "4990", "x-ratelimit-resource": "graphql" } },
148 )
149 : json({ ok: true }, { headers: { "x-ratelimit-remaining": "4800" } }),
150 );
151 return Effect.gen(function* () {
152 yield* TestClock.setTime(NOW);
153 const api = yield* GitHubApi.GitHubApi;
154 yield* api.graphql({
155 host: "github.com",
156 operation: "getPullRequestDetail",
157 query: "query($body: String!) { viewer { login } }",
158 variables: { body: "secret user text" },
159 });
160 yield* api.rest({
161 host: "github.com",
162 operation: "listWorkflowRuns",
163 path: "repos/acme/web/actions/runs?head_sha=abc123&branch=feat%2Fx",
164 });
165 const byName = (name: string) => spans.filter((span) => span.name === name);
166 const graphql = Object.fromEntries(byName("GitHubApi.graphql")[0]!.attributes);
167 expect(graphql).toMatchObject({
168 "github.operation": "getPullRequestDetail",
169 "github.graphql.query": "query($body: String!) { viewer { login } }",
170 "github.graphql.cost": 3,
171 "github.graphql.remaining": 4990,
172 });
173 expect(String(graphql["github.graphql.query_hash"])).toMatch(/^[0-9a-f]{8}$/);
174 const rest = Object.fromEntries(byName("GitHubApi.send")[1]!.attributes);
175 expect(rest).toMatchObject({
176 "github.operation": "listWorkflowRuns",
177 "github.kind": "rest",
178 "url.path": "/repos/acme/web/actions/runs",
179 "http.response.status_code": 200,
180 "github.ratelimit.remaining": 4800,
181 });
182 // Nothing recorded carries the query string, the variables, or the token.
183 const everything = spans
184 .flatMap((span) => [...span.attributes].map(([key, value]) => `${key}=${String(value)}`))
185 .join("\n");
186 expect(everything).not.toContain("head_sha");
187 expect(everything).not.toContain("secret user text");
188 expect(everything).not.toContain("first");
189 expect(spans.some((span) => span.attributes.has("url.full"))).toBe(false);
190 }).pipe(Effect.provide(layer), Effect.withTracer(tracer));
191 },
192 );
193​
194 it.effect("fails a GraphQL answer that carries errors, naming GitHub's reason", () => {
195 const { layer } = harness(() =>
196 json({ data: null, errors: [{ type: "FORBIDDEN", message: "Resource not accessible" }] }),
197 );
198 return Effect.gen(function* () {
199 const api = yield* GitHubApi.GitHubApi;
200 const error = yield* Effect.flip(
201 api.graphql({ host: "github.com", operation: "detail", query: "query { viewer { id } }" }),
202 );
203 expect(error._tag).toBe("GitHubApiResponseError");
204 expect(error.message).toContain("Resource not accessible");
205 }).pipe(Effect.provide(layer));
206 });
207​
208 it.effect(
209 "reads a NOT_FOUND answer with another error as a failure, not a missing resource",
210 () => {
211 const { layer } = harness(() =>
212 json({
213 data: null,
214 errors: [
215 { type: "NOT_FOUND", message: "Could not resolve" },
216 { message: "Something went wrong" },
217 ],
218 }),
219 );
220 return Effect.gen(function* () {
221 const api = yield* GitHubApi.GitHubApi;
222 const error = yield* Effect.flip(
223 api.graphql({
224 host: "github.com",
225 operation: "detail",
226 query: "query { viewer { id } }",
227 }),
228 );
229 expect(error._tag).toBe("GitHubApiResponseError");
230 }).pipe(Effect.provide(layer));
231 },
232 );
233​
234 it.effect("pauses the host after a GraphQL RATE_LIMITED answer until the reset", () => {
235 const reset = Math.floor(NOW / 1000) + 600;
236 const { layer, requests } = harness(() =>
237 json(
238 { errors: [{ type: "RATE_LIMITED", message: "API rate limit exceeded" }] },
239 { headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) } },
240 ),
241 );
242 return Effect.gen(function* () {
243 yield* TestClock.setTime(NOW);
244 const api = yield* GitHubApi.GitHubApi;
245 const first = yield* Effect.flip(
246 api.graphql({ host: "github.com", operation: "summary", query: "query { viewer { id } }" }),
247 );
248 expect(first).toMatchObject({ _tag: "GitHubApiRateLimitError", retryAt: reset * 1000 });
249 const second = yield* Effect.flip(
250 api.rest({ host: "github.com", operation: "stack", path: "repos/acme/web/stacks" }),
251 );
252 expect(second).toMatchObject({
253 _tag: "SourceControlRateLimitPausedError",
254 retryAt: reset * 1000,
255 });
256 expect(requests).toHaveLength(1);
257 }).pipe(Effect.provide(layer));
258 });
259​
260 it.effect("carries GitHub's own reason for a refused REST request", () => {
261 const { layer } = harness(() =>
262 json(
263 {
264 message: "Validation Failed",
265 errors: [
266 {
267 resource: "PullRequest",
268 code: "custom",
269 message: "A pull request already exists for acme:feature.",
270 },
271 ],
272 },
273 { status: 422 },
274 ),
275 );
276 return Effect.gen(function* () {
277 const api = yield* GitHubApi.GitHubApi;
278 const error = yield* Effect.flip(
279 api.rest({
280 host: "github.com",
281 operation: "createPullRequest",
282 method: "POST",
283 path: "repos/acme/web/pulls",
284 }),
285 );
286 expect(error.message).toBe(
287 "GitHub returned an error: Validation Failed; A pull request already exists for acme:feature.",
288 );
289 }).pipe(Effect.provide(layer));
290 });
291​
292 it.effect("lets an interactive request through a pause a background read recorded", () => {
293 const reset = Math.floor(NOW / 1000) + 600;
294 let call = 0;
295 const { layer, requests } = harness(() =>
296 ++call === 1
297 ? json(
298 { message: "API rate limit exceeded" },
299 {
300 status: 403,
301 headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) },
302 },
303 )
304 : json({ ok: true }),
305 );
306 return Effect.gen(function* () {
307 yield* TestClock.setTime(NOW);
308 const api = yield* GitHubApi.GitHubApi;
309 const read = { host: "github.com", operation: "sweep", path: "repos/acme/web/pulls" };
310 yield* Effect.flip(api.rest(read));
311 expect((yield* Effect.flip(api.rest(read)))._tag).toBe("SourceControlRateLimitPausedError");
312 const merged = yield* api
313 .rest({
314 host: "github.com",
315 operation: "merge",
316 method: "PUT",
317 path: "repos/acme/web/pulls/7/merge",
318 })
319 .pipe(Effect.provideService(GitHubApi.AllowGitHubReserve, true));
320 expect(merged.status).toBe(200);
321 expect(requests).toHaveLength(2);
322 }).pipe(Effect.provide(layer));
323 });
324​
325 it.effect("reads an untyped GraphQL quota error as a rate limit", () => {
326 const reset = Math.floor(NOW / 1000) + 900;
327 const { layer } = harness(() =>
328 json(
329 { errors: [{ message: "API rate limit already exceeded for user ID 1." }] },
330 { headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) } },
331 ),
332 );
333 return Effect.gen(function* () {
334 yield* TestClock.setTime(NOW);
335 const api = yield* GitHubApi.GitHubApi;
336 const error = yield* Effect.flip(
337 api.graphql({ host: "github.com", operation: "lookup", query: "query { viewer { id } }" }),
338 );
339 expect(error).toMatchObject({ _tag: "GitHubApiRateLimitError", retryAt: reset * 1000 });
340 }).pipe(Effect.provide(layer));
341 });
342​
343 it.effect("maps REST 403 with an exhausted quota to a rate limit, and 304 to an answer", () => {
344 let call = 0;
345 const { layer } = harness(() =>
346 ++call === 1
347 ? new Response(null, { status: 304 })
348 : json(
349 { message: "API rate limit exceeded" },
350 {
351 status: 403,
352 headers: { "retry-after": "60" },
353 },
354 ),
355 );
356 return Effect.gen(function* () {
357 yield* TestClock.setTime(NOW);
358 const api = yield* GitHubApi.GitHubApi;
359 const notModified = yield* api.rest({
360 host: "github.com",
361 operation: "checks",
362 path: "repos/acme/web/pulls/7",
363 ifNoneMatch: '"abc"',
364 });
365 expect(notModified.status).toBe(304);
366 const error = yield* Effect.flip(
367 api.rest({ host: "github.com", operation: "checks", path: "repos/acme/web/pulls/7" }),
368 );
369 expect(error).toMatchObject({ _tag: "GitHubApiRateLimitError", retryAt: NOW + 60_000 });
370 }).pipe(Effect.provide(layer));
371 });
372​
373 it.effect("drops a refused token so the next request asks the source again", () => {
374 const { layer, requests, invalidations } = harness((request) =>
375 request.headers.authorization === "Bearer first"
376 ? new Response(null, { status: 401 })
377 : json({ ok: true }),
378 );
379 return Effect.gen(function* () {
380 const api = yield* GitHubApi.GitHubApi;
381 const refused = yield* Effect.flip(
382 api.rest({ host: "github.com", operation: "user", path: "user" }),
383 );
384 expect(refused._tag).toBe("GitHubApiAuthenticationError");
385 expect(invalidations()).toBe(1);
386 const answered = yield* api.rest({ host: "github.com", operation: "user", path: "user" });
387 expect(answered.status).toBe(200);
388 expect(requests.map((request) => request.headers.authorization)).toEqual([
389 "Bearer first",
390 "Bearer second",
391 ]);
392 }).pipe(Effect.provide(layer));
393 });
394​
395 it.effect("refuses to send a pinned credential to another host", () => {
396 const { layer, requests } = harness(() => json({}));
397 return Effect.gen(function* () {
398 const api = yield* GitHubApi.GitHubApi;
399 const error = yield* Effect.flip(
400 api.rest({ host: "git.acme.internal", operation: "user", path: "user" }),
401 ).pipe(
402 Effect.provideService(GitHubApi.PinnedGitHubCredential, {
403 host: "github.com",
404 token: Redacted.make("pinned"),
405 credentialFingerprint: "github.com:pinned",
406 }),
407 );
408 expect(error._tag).toBe("GitHubApiAuthenticationError");
409 expect(requests).toHaveLength(0);
410 }).pipe(Effect.provide(layer));
411 });
412});
413​
414describe("GitHubCredentials", () => {
415 const credentialsWith = (run: VcsProcess.VcsProcess["Service"]["run"]) =>
416 GitHubCredentials.layer.pipe(
417 Layer.provide(Layer.mock(VcsProcess.VcsProcess)({ run })),
418 Layer.provide(NodeServices.layer),
419 );
420​
421 it.effect("fails with GitHubCliMissingError when gh is not on PATH", () =>
422 Effect.gen(function* () {
423 const credentials = yield* GitHubCredentials.GitHubCredentials;
424 const error = yield* Effect.flip(credentials.get("git.acme.internal"));
425 expect(error._tag).toBe("GitHubCliMissingError");
426 }).pipe(
427 Effect.provide(
428 credentialsWith(() =>
429 Effect.fail(
430 new VcsProcessSpawnError({
431 operation: "GitHubCredentials.get",
432 command: "gh",
433 cwd: "/",
434 cause: PlatformError.systemError({
435 _tag: "NotFound",
436 module: "ChildProcess",
437 method: "spawn",
438 }),
439 }),
440 ),
441 ),
442 ),
443 ),
444 );
445​
446 it.effect("does not cache a gh failure that is not about signing in", () => {
447 let calls = 0;
448 return Effect.gen(function* () {
449 const credentials = yield* GitHubCredentials.GitHubCredentials;
450 const first = yield* Effect.flip(credentials.get("github.com"));
451 expect(first._tag).toBe("GitHubCliFailedError");
452 expect((yield* credentials.get("github.com")).source).toBe("gh");
453 expect(calls).toBe(2);
454 }).pipe(
455 Effect.provide(
456 credentialsWith(() =>
457 ++calls === 1
458 ? Effect.fail(
459 new VcsProcessTimeoutError({
460 operation: "GitHubCredentials.get",
461 command: "gh",
462 cwd: "/",
463 timeoutMs: 10_000,
464 }),
465 )
466 : Effect.succeed({
467 exitCode: ChildProcessSpawner.ExitCode(0),
468 stdout: "token\n",
469 stderr: "",
470 stdoutTruncated: false,
471 stderrTruncated: false,
472 }),
473 ),
474 ),
475 );
476 });
477​
478 it.effect("fails with GitHubNotSignedInError when gh prints no token", () =>
479 Effect.gen(function* () {
480 const credentials = yield* GitHubCredentials.GitHubCredentials;
481 const error = yield* Effect.flip(credentials.get("git.acme.internal"));
482 expect(error._tag).toBe("GitHubNotSignedInError");
483 }).pipe(
484 Effect.provide(
485 credentialsWith(() =>
486 Effect.succeed({
487 exitCode: ChildProcessSpawner.ExitCode(0),
488 stdout: "\n",
489 stderr: "",
490 stdoutTruncated: false,
491 stderrTruncated: false,
492 }),
493 ),
494 ),
495 ),
496 );
497});