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

GitHubApi.test.ts

525 lines19.8 KB

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