Open History to see the last commit
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 GitHubQuota from "./githubQuota.ts";
16import * as SourceControlRateLimit from "./SourceControlRateLimit.ts";
17import * as VcsProcess from "../vcs/VcsProcess.ts";
18import * as ServerSettings from "../serverSettings.ts";
19
20const NOW = Date.parse("2026-10-05T12:00:00.000Z");
21
22function harness(respond: (request: HttpClientRequest.HttpClientRequest) => Response) {
23 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
24 let tokens = ["first", "second"];
25 let invalidations = 0;
26 const credentials = Layer.succeed(
27 GitHubCredentials.GitHubCredentials,
28 GitHubCredentials.GitHubCredentials.of({
29 get: (host) =>
30 Effect.sync(() => ({
31 host,
32 token: Redacted.make(tokens[0]!),
33 source: "gh" as const,
34 fingerprint: `${host}:${tokens[0]}`,
35 })),
36 invalidate: () =>
37 Effect.sync(() => {
38 invalidations++;
39 tokens = tokens.slice(1);
40 }),
41 }),
42 );
43 const http = Layer.succeed(
44 HttpClient.HttpClient,
45 HttpClient.make((request) => {
46 requests.push(request);
47 return Effect.succeed(HttpClientResponse.fromWeb(request, respond(request)));
48 }),
49 );
50 const layer = GitHubApi.layer.pipe(
51 Layer.provide(Layer.mergeAll(credentials, http)),
52 Layer.provideMerge(GitHubQuota.layer),
53 Layer.provideMerge(SourceControlRateLimit.layer),
54 );
55 return { layer, requests, invalidations: () => invalidations };
56}
57
58const json = (body: unknown, init?: ResponseInit) =>
59 new Response(JSON.stringify(body), {
60 ...init,
61 headers: { "content-type": "application/json", ...init?.headers },
62 });
63
64describe("gitHubApiUrls", () => {
65 it("maps github.com, GHE.com and GitHub Enterprise Server", () => {
66 expect(GitHubApi.gitHubApiUrls("GitHub.com")).toEqual({
67 rest: "https://api.github.com",
68 graphql: "https://api.github.com/graphql",
69 });
70 expect(GitHubApi.gitHubApiUrls("acme.ghe.com").graphql).toBe(
71 "https://api.acme.ghe.com/graphql",
72 );
73 expect(GitHubApi.gitHubApiUrls("git.acme.internal")).toEqual({
74 rest: "https://git.acme.internal/api/v3",
75 graphql: "https://git.acme.internal/api/graphql",
76 });
77 });
78});
79
80describe("environmentToken", () => {
81 it("follows gh's precedence per kind of host", () => {
82 const env = { GH_TOKEN: "gh", GITHUB_TOKEN: "github", GH_ENTERPRISE_TOKEN: "ghe" };
83 expect(GitHubCredentials.environmentToken("github.com", env)).toBe("gh");
84 expect(GitHubCredentials.environmentToken("acme.ghe.com", { GITHUB_TOKEN: "github" })).toBe(
85 "github",
86 );
87 // An enterprise token only goes to the host GH_HOST names, never to whatever a remote says.
88 expect(GitHubCredentials.environmentToken("git.acme.internal", env)).toBeNull();
89 expect(
90 GitHubCredentials.environmentToken("git.acme.internal", {
91 ...env,
92 GH_HOST: "git.acme.internal",
93 }),
94 ).toBe("ghe");
95 expect(GitHubCredentials.environmentToken("git.acme.internal", { GH_TOKEN: "gh" })).toBeNull();
96 });
97});
98
99describe("GitHubApi", () => {
100 it.effect("sends GraphQL with the token, and the document as written", () => {
101 const { layer, requests } = harness(() => json({ data: { viewer: { login: "julius" } } }));
102 return Effect.gen(function* () {
103 yield* TestClock.setTime(NOW);
104 const api = yield* GitHubApi.GitHubApi;
105 const body = yield* api.graphql({
106 host: "github.com",
107 operation: "viewer",
108 query: "query { viewer { login } }",
109 });
110 expect(body).toContain('"login":"julius"');
111 expect(requests[0]!.url).toBe("https://api.github.com/graphql");
112 expect(requests[0]!.headers.authorization).toBe("Bearer first");
113 // No `rateLimit` selection is added: the quota is read off the response headers.
114 const sent = requests[0]!.body;
115 expect(sent._tag === "Uint8Array" ? new TextDecoder().decode(sent.body) : "").toContain(
116 '"query":"query { viewer { login } }"',
117 );
118 }).pipe(Effect.provide(layer));
119 });
120
121 it.effect(
122 "traces the operation, path, query and quota, never the query string or variables",
123 () => {
124 const spans: Array<Tracer.NativeSpan> = [];
125 const tracer = Tracer.make({
126 span: (options) => {
127 const span = new Tracer.NativeSpan(options);
128 spans.push(span);
129 return span;
130 },
131 });
132 const { layer } = harness((request) =>
133 request.url.endsWith("/graphql")
134 ? json(
135 { data: { viewer: { login: "julius" } } },
136 { headers: { "x-ratelimit-remaining": "4990", "x-ratelimit-resource": "graphql" } },
137 )
138 : json({ ok: true }, { headers: { "x-ratelimit-remaining": "4800" } }),
139 );
140 return Effect.gen(function* () {
141 yield* TestClock.setTime(NOW);
142 const api = yield* GitHubApi.GitHubApi;
143 yield* api.graphql({
144 host: "github.com",
145 operation: "getPullRequestDetail",
146 query: "query($body: String!) { viewer { login } }",
147 variables: { body: "secret user text" },
148 });
149 yield* api.rest({
150 host: "github.com",
151 operation: "listWorkflowRuns",
152 path: "repos/acme/web/actions/runs?head_sha=abc123&branch=feat%2Fx",
153 });
154 const byName = (name: string) => spans.filter((span) => span.name === name);
155 const graphql = Object.fromEntries(byName("GitHubApi.graphql")[0]!.attributes);
156 expect(graphql).toMatchObject({
157 "github.operation": "getPullRequestDetail",
158 "github.graphql.query": "query($body: String!) { viewer { login } }",
159 });
160 expect(Object.fromEntries(byName("GitHubApi.send")[0]!.attributes)).toMatchObject({
161 "github.ratelimit.remaining": 4990,
162 "github.ratelimit.resource": "graphql",
163 });
164 expect(String(graphql["github.graphql.query_hash"])).toMatch(/^[0-9a-f]{8}$/);
165 const rest = Object.fromEntries(byName("GitHubApi.send")[1]!.attributes);
166 expect(rest).toMatchObject({
167 "github.operation": "listWorkflowRuns",
168 "github.kind": "rest",
169 "url.path": "/repos/acme/web/actions/runs",
170 "http.response.status_code": 200,
171 "github.ratelimit.remaining": 4800,
172 });
173 // Nothing recorded carries the query string, the variables, or the token.
174 const everything = spans
175 .flatMap((span) => [...span.attributes].map(([key, value]) => `${key}=${String(value)}`))
176 .join("\n");
177 expect(everything).not.toContain("head_sha");
178 expect(everything).not.toContain("secret user text");
179 expect(everything).not.toContain("first");
180 expect(spans.some((span) => span.attributes.has("url.full"))).toBe(false);
181 }).pipe(Effect.provide(layer), Effect.withTracer(tracer));
182 },
183 );
184
185 it.effect("fails a GraphQL answer that carries errors, naming GitHub's reason", () => {
186 const { layer } = harness(() =>
187 json({ data: null, errors: [{ type: "FORBIDDEN", message: "Resource not accessible" }] }),
188 );
189 return Effect.gen(function* () {
190 const api = yield* GitHubApi.GitHubApi;
191 const error = yield* Effect.flip(
192 api.graphql({ host: "github.com", operation: "detail", query: "query { viewer { id } }" }),
193 );
194 expect(error._tag).toBe("GitHubApiResponseError");
195 expect(error.message).toContain("Resource not accessible");
196 }).pipe(Effect.provide(layer));
197 });
198
199 it.effect(
200 "reads a NOT_FOUND answer with another error as a failure, not a missing resource",
201 () => {
202 const { layer } = harness(() =>
203 json({
204 data: null,
205 errors: [
206 { type: "NOT_FOUND", message: "Could not resolve" },
207 { message: "Something went wrong" },
208 ],
209 }),
210 );
211 return Effect.gen(function* () {
212 const api = yield* GitHubApi.GitHubApi;
213 const error = yield* Effect.flip(
214 api.graphql({
215 host: "github.com",
216 operation: "detail",
217 query: "query { viewer { id } }",
218 }),
219 );
220 expect(error._tag).toBe("GitHubApiResponseError");
221 }).pipe(Effect.provide(layer));
222 },
223 );
224
225 it.effect("pauses the host after a GraphQL RATE_LIMITED answer until the reset", () => {
226 const reset = Math.floor(NOW / 1000) + 600;
227 const { layer, requests } = harness(() =>
228 json(
229 { errors: [{ type: "RATE_LIMITED", message: "API rate limit exceeded" }] },
230 { headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) } },
231 ),
232 );
233 return Effect.gen(function* () {
234 yield* TestClock.setTime(NOW);
235 const api = yield* GitHubApi.GitHubApi;
236 const first = yield* Effect.flip(
237 api.graphql({ host: "github.com", operation: "summary", query: "query { viewer { id } }" }),
238 );
239 expect(first).toMatchObject({ _tag: "GitHubApiRateLimitError", retryAt: reset * 1000 });
240 const second = yield* Effect.flip(
241 api.rest({ host: "github.com", operation: "stack", path: "repos/acme/web/stacks" }),
242 );
243 expect(second).toMatchObject({
244 _tag: "SourceControlRateLimitPausedError",
245 retryAt: reset * 1000,
246 });
247 expect(requests).toHaveLength(1);
248 }).pipe(Effect.provide(layer));
249 });
250
251 it.effect("keeps the last tenth of a quota for interactive requests until it resets", () => {
252 const reset = Math.floor(NOW / 1000) + 600;
253 const quota = (remaining: number) => ({
254 "x-ratelimit-resource": "core",
255 "x-ratelimit-limit": "5000",
256 "x-ratelimit-remaining": String(remaining),
257 "x-ratelimit-reset": String(reset),
258 });
259 let remaining = 499;
260 const { layer, requests } = harness((request) =>
261 request.url.endsWith("/graphql")
262 ? json({ data: { viewer: { id: "1" } } })
263 : json({ ok: true }, { headers: quota(remaining--) }),
264 );
265 return Effect.gen(function* () {
266 yield* TestClock.setTime(NOW);
267 const api = yield* GitHubApi.GitHubApi;
268 const read = { host: "github.com", operation: "sweep", path: "repos/acme/web/pulls" };
269 // The first answer leaves 499 of 5000, under the last tenth; the next background read waits.
270 yield* api.rest(read);
271 const refused = yield* Effect.flip(api.rest(read));
272 expect(refused).toMatchObject({
273 _tag: "SourceControlRateLimitPausedError",
274 retryAt: reset * 1000,
275 });
276 // A user's own request may spend the reserve, and GraphQL has a quota of its own.
277 yield* api.rest(read).pipe(Effect.provideService(GitHubApi.AllowGitHubReserve, true));
278 yield* api.graphql({ host: "github.com", operation: "x", query: "query { viewer { id } }" });
279 expect(requests).toHaveLength(3);
280 // The reset gives the background its quota back.
281 yield* TestClock.setTime(reset * 1000);
282 yield* api.rest(read);
283 expect(requests).toHaveLength(4);
284 }).pipe(Effect.provide(layer));
285 });
286
287 it.effect("carries GitHub's own reason for a refused REST request", () => {
288 const { layer } = harness(() =>
289 json(
290 {
291 message: "Validation Failed",
292 errors: [
293 {
294 resource: "PullRequest",
295 code: "custom",
296 message: "A pull request already exists for acme:feature.",
297 },
298 ],
299 },
300 { status: 422 },
301 ),
302 );
303 return Effect.gen(function* () {
304 const api = yield* GitHubApi.GitHubApi;
305 const error = yield* Effect.flip(
306 api.rest({
307 host: "github.com",
308 operation: "createPullRequest",
309 method: "POST",
310 path: "repos/acme/web/pulls",
311 }),
312 );
313 expect(error.message).toBe(
314 "GitHub returned an error: Validation Failed; A pull request already exists for acme:feature.",
315 );
316 }).pipe(Effect.provide(layer));
317 });
318
319 it.effect("lets an interactive request through a pause a background read recorded", () => {
320 const reset = Math.floor(NOW / 1000) + 600;
321 let call = 0;
322 const { layer, requests } = harness(() =>
323 ++call === 1
324 ? json(
325 { message: "API rate limit exceeded" },
326 {
327 status: 403,
328 headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) },
329 },
330 )
331 : json({ ok: true }),
332 );
333 return Effect.gen(function* () {
334 yield* TestClock.setTime(NOW);
335 const api = yield* GitHubApi.GitHubApi;
336 const read = { host: "github.com", operation: "sweep", path: "repos/acme/web/pulls" };
337 yield* Effect.flip(api.rest(read));
338 expect((yield* Effect.flip(api.rest(read)))._tag).toBe("SourceControlRateLimitPausedError");
339 const merged = yield* api
340 .rest({
341 host: "github.com",
342 operation: "merge",
343 method: "PUT",
344 path: "repos/acme/web/pulls/7/merge",
345 })
346 .pipe(Effect.provideService(GitHubApi.AllowGitHubReserve, true));
347 expect(merged.status).toBe(200);
348 expect(requests).toHaveLength(2);
349 }).pipe(Effect.provide(layer));
350 });
351
352 it.effect("reads an untyped GraphQL quota error as a rate limit", () => {
353 const reset = Math.floor(NOW / 1000) + 900;
354 const { layer } = harness(() =>
355 json(
356 { errors: [{ message: "API rate limit already exceeded for user ID 1." }] },
357 { headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) } },
358 ),
359 );
360 return Effect.gen(function* () {
361 yield* TestClock.setTime(NOW);
362 const api = yield* GitHubApi.GitHubApi;
363 const error = yield* Effect.flip(
364 api.graphql({ host: "github.com", operation: "lookup", query: "query { viewer { id } }" }),
365 );
366 expect(error).toMatchObject({ _tag: "GitHubApiRateLimitError", retryAt: reset * 1000 });
367 }).pipe(Effect.provide(layer));
368 });
369
370 it.effect("maps REST 403 with an exhausted quota to a rate limit, and 304 to an answer", () => {
371 let call = 0;
372 const { layer } = harness(() =>
373 ++call === 1
374 ? new Response(null, { status: 304 })
375 : json(
376 { message: "API rate limit exceeded" },
377 {
378 status: 403,
379 headers: { "retry-after": "60" },
380 },
381 ),
382 );
383 return Effect.gen(function* () {
384 yield* TestClock.setTime(NOW);
385 const api = yield* GitHubApi.GitHubApi;
386 const notModified = yield* api.rest({
387 host: "github.com",
388 operation: "checks",
389 path: "repos/acme/web/pulls/7",
390 ifNoneMatch: '"abc"',
391 });
392 expect(notModified.status).toBe(304);
393 const error = yield* Effect.flip(
394 api.rest({ host: "github.com", operation: "checks", path: "repos/acme/web/pulls/7" }),
395 );
396 expect(error).toMatchObject({ _tag: "GitHubApiRateLimitError", retryAt: NOW + 60_000 });
397 }).pipe(Effect.provide(layer));
398 });
399
400 it.effect("drops a refused token so the next request asks the source again", () => {
401 const { layer, requests, invalidations } = harness((request) =>
402 request.headers.authorization === "Bearer first"
403 ? new Response(null, { status: 401 })
404 : json({ ok: true }),
405 );
406 return Effect.gen(function* () {
407 const api = yield* GitHubApi.GitHubApi;
408 const refused = yield* Effect.flip(
409 api.rest({ host: "github.com", operation: "user", path: "user" }),
410 );
411 expect(refused._tag).toBe("GitHubApiAuthenticationError");
412 expect(invalidations()).toBe(1);
413 const answered = yield* api.rest({ host: "github.com", operation: "user", path: "user" });
414 expect(answered.status).toBe(200);
415 expect(requests.map((request) => request.headers.authorization)).toEqual([
416 "Bearer first",
417 "Bearer second",
418 ]);
419 }).pipe(Effect.provide(layer));
420 });
421
422 it.effect("refuses to send a pinned credential to another host", () => {
423 const { layer, requests } = harness(() => json({}));
424 return Effect.gen(function* () {
425 const api = yield* GitHubApi.GitHubApi;
426 const error = yield* Effect.flip(
427 api.rest({ host: "git.acme.internal", operation: "user", path: "user" }),
428 ).pipe(
429 Effect.provideService(GitHubApi.PinnedGitHubCredential, {
430 host: "github.com",
431 token: Redacted.make("pinned"),
432 credentialFingerprint: "github.com:pinned",
433 }),
434 );
435 expect(error._tag).toBe("GitHubApiAuthenticationError");
436 expect(requests).toHaveLength(0);
437 }).pipe(Effect.provide(layer));
438 });
439});
440
441describe("GitHubCredentials", () => {
442 const credentialsWith = (run: VcsProcess.VcsProcess["Service"]["run"]) =>
443 GitHubCredentials.layer.pipe(
444 Layer.provide(Layer.mock(VcsProcess.VcsProcess)({ run })),
445 Layer.provide(NodeServices.layer),
446 Layer.provide(ServerSettings.layerTest()),
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});
526
527describe("GitHubApi accounts", () => {
528 it.effect("sends every request under GitHubAccount with that account's token", () => {
529 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
530 const invalidated: Array<string | null | undefined> = [];
531 const credentials = Layer.succeed(
532 GitHubCredentials.GitHubCredentials,
533 GitHubCredentials.GitHubCredentials.of({
534 get: (host, account) =>
535 Effect.succeed({
536 host,
537 token: Redacted.make(account ?? "host"),
538 source: "gh" as const,
539 fingerprint: `${host}:${account ?? "host"}`,
540 }),
541 invalidate: (_host, account) => Effect.sync(() => void invalidated.push(account)),
542 }),
543 );
544 const http = Layer.succeed(
545 HttpClient.HttpClient,
546 HttpClient.make((request) => {
547 requests.push(request);
548 return Effect.succeed(
549 HttpClientResponse.fromWeb(
550 request,
551 request.url.endsWith("/refused") ? json({}, { status: 401 }) : json({}),
552 ),
553 );
554 }),
555 );
556 const layer = GitHubApi.layer.pipe(
557 Layer.provide(Layer.mergeAll(credentials, http)),
558 Layer.provideMerge(GitHubQuota.layer),
559 Layer.provideMerge(SourceControlRateLimit.layer),
560 );
561 return Effect.gen(function* () {
562 yield* TestClock.setTime(NOW);
563 const api = yield* GitHubApi.GitHubApi;
564 yield* api.rest({ host: "github.com", operation: "read", path: "repos/acme/web" });
565 const asWork = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
566 effect.pipe(Effect.provideService(GitHubApi.GitHubAccount, "work"));
567 yield* asWork(api.rest({ host: "github.com", operation: "read", path: "repos/acme/web" }));
568 yield* asWork(
569 api.rest({ host: "github.com", operation: "read", path: "refused" }).pipe(Effect.flip),
570 );
571 expect(requests.map((request) => request.headers.authorization)).toEqual([
572 "Bearer host",
573 "Bearer work",
574 "Bearer work",
575 ]);
576 expect(invalidated).toEqual(["work"]);
577 }).pipe(Effect.provide(layer));
578 });
579});