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

gitHubGraphQlClient.test.ts

289 lines11.2 KB

1import { describe, expect, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Redacted from "effect/Redacted";
5import * as TestClock from "effect/testing/TestClock";
6import * as Tracer from "effect/Tracer";
7import { HttpClient, HttpClientResponse, type HttpClientRequest } from "effect/http";
8import { GraphQLClient, GraphQLResolver } from "effect/graphql";
9import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
10​
11import * as GitHubRest from "./GitHubRest.ts";
12import * as GitHubCredentials from "./GitHubCredentials.ts";
13import * as GitHubGraphQlClient from "./gitHubGraphQlClient.ts";
14import * as GitHubQuota from "./GitHubQuota.ts";
15import { PullRequestBatchesGraphQLGroup } from "./pullRequestBatches.graphql.ts";
16​
17const NOW = Date.parse("2026-10-05T12:00:00.000Z");
18​
19function harness(respond: (request: HttpClientRequest.HttpClientRequest) => Response) {
20 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
21 let invalidations = 0;
22 const services = Layer.mergeAll(
23 Layer.succeed(GitHubCredentials.GitHubCredentials, {
24 get: (host) =>
25 Effect.succeed({
26 host,
27 token: Redacted.make("secret"),
28 source: "gh" as const,
29 fingerprint: `${host}:secret`,
30 }),
31 invalidate: () =>
32 Effect.sync(() => {
33 invalidations++;
34 }),
35 }),
36 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 GitHubQuota.layer,
44 SourceControlRateLimit.layer,
45 );
46 const layer = GitHubRest.layer.pipe(Layer.provideMerge(services));
47 return { layer, requests, invalidations: () => invalidations };
49​
50const json = (body: unknown, init?: ResponseInit) =>
51 new Response(JSON.stringify(body), {
52 ...init,
53 headers: { "content-type": "application/json", ...init?.headers },
54 });
55​
56const readStats = (host: string, number = 7) =>
57 Effect.gen(function* () {
58 const client = yield* GraphQLClient.make(
59 PullRequestBatchesGraphQLGroup.middleware(GitHubGraphQlClient.GitHubGraphQlAuth),
60 ).pipe(Effect.provide(GitHubGraphQlClient.layer));
61 return yield* GraphQLResolver.request(
62 { owner: "acme", name: "web", number },
63 GraphQLResolver.aliased(client.PullRequestStats, {
64 batchKey: GitHubGraphQlClient.batchKey,
65 }),
66 ).pipe(
67 Effect.provideService(GitHubGraphQlClient.GitHubGraphQlTarget, {
68 host,
69 operation: "stats",
70 }),
71 );
72 });
73​
74const stats = { additions: 3, deletions: 1 };
75​
76describe("GitHubGraphQlAuth", () => {
77 it.effect(
78 "sends each host's lookups to its own endpoint with its token, never in one batch",
79 () => {
80 const { layer, requests } = harness(() =>
81 json({ data: { _0_repository: { pullRequest: stats } } }),
82 );
83 return Effect.gen(function* () {
84 const client = yield* GraphQLClient.make(
85 PullRequestBatchesGraphQLGroup.middleware(GitHubGraphQlClient.GitHubGraphQlAuth),
86 ).pipe(Effect.provide(GitHubGraphQlClient.layer));
87 const resolver = GraphQLResolver.aliased(client.PullRequestStats, {
88 batchKey: GitHubGraphQlClient.batchKey,
89 });
90 const lookup = (host: string) =>
91 GraphQLResolver.request({ owner: "acme", name: "web", number: 7 }, resolver).pipe(
92 Effect.provideService(GitHubGraphQlClient.GitHubGraphQlTarget, {
93 host,
94 operation: "stats",
95 }),
96 );
97 yield* Effect.all([lookup("github.com"), lookup("github.acme.test")], {
98 concurrency: "unbounded",
99 });
100 expect(requests.map((request) => request.url).toSorted()).toEqual([
101 "https://api.github.com/graphql",
102 "https://github.acme.test/api/graphql",
103 ]);
104 expect(requests[0]?.headers["authorization"]).toBe("Bearer secret");
105 expect(requests[0]?.headers["x-github-api-version"]).toBe("2022-11-28");
106 }).pipe(Effect.provide(layer));
107 },
108 );
109​
110 it.effect("pauses the host on a RATE_LIMITED answer sent with HTTP 200", () => {
111 const reset = Math.floor(NOW / 1000) + 600;
112 const { layer, requests } = harness(() =>
113 json(
114 { data: null, errors: [{ type: "RATE_LIMITED", message: "API rate limit exceeded" }] },
115 { headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) } },
116 ),
117 );
118 return Effect.gen(function* () {
119 yield* TestClock.setTime(NOW);
120 const first = yield* Effect.flip(readStats("github.com"));
121 expect(first).toMatchObject({ _tag: "GitHubApiRateLimitError", retryAt: reset * 1000 });
122 const api = yield* GitHubRest.GitHubRest;
123 const rest = yield* Effect.flip(
124 api.rest({ host: "github.com", operation: "stack", path: "repos/acme/web/stacks" }),
125 );
126 expect(rest).toMatchObject({ _tag: "SourceControlRateLimitPausedError" });
127 expect(requests).toHaveLength(1);
128 }).pipe(Effect.provide(layer));
129 });
130​
131 it.effect("reads an untyped exhausted-quota error sent with HTTP 200 as a rate limit", () => {
132 const reset = Math.floor(NOW / 1000) + 900;
133 const { layer } = harness(() =>
134 json(
135 { data: null, errors: [{ message: "API rate limit already exceeded for user ID 1." }] },
136 { headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) } },
137 ),
138 );
139 return Effect.gen(function* () {
140 yield* TestClock.setTime(NOW);
141 const error = yield* Effect.flip(readStats("github.com"));
142 expect(error).toMatchObject({ _tag: "GitHubApiRateLimitError", retryAt: reset * 1000 });
143 }).pipe(Effect.provide(layer));
144 });
145​
146 it.effect("traces the query hash and quota, never the variables, token or URL", () => {
147 const spans: Array<Tracer.NativeSpan> = [];
148 const tracer = Tracer.make({
149 span: (options) => {
150 const span = new Tracer.NativeSpan(options);
151 spans.push(span);
152 return span;
153 },
154 });
155 const { layer } = harness(() =>
156 json(
157 { data: { _0_repository: { pullRequest: stats } } },
158 { headers: { "x-ratelimit-remaining": "4990", "x-ratelimit-resource": "graphql" } },
159 ),
160 );
161 return Effect.gen(function* () {
162 yield* TestClock.setTime(NOW);
163 yield* readStats("github.com", 4242);
164 const execute = spans.find((span) => span.name === "GitHubGraphQlAuth.execute")!;
165 const attributes = Object.fromEntries(execute.attributes);
166 expect(attributes).toMatchObject({
167 "github.kind": "graphql",
168 "github.operation": "stats",
169 "http.response.status_code": 200,
170 "github.ratelimit.remaining": 4990,
171 "github.ratelimit.resource": "graphql",
172 });
173 expect(String(attributes["github.graphql.query_hash"])).toMatch(/^[0-9a-f]{8}$/);
174 const everything = spans
175 .flatMap((span) => [...span.attributes].map(([key, value]) => `${key}=${String(value)}`))
176 .join("\n");
177 expect(everything).not.toContain("4242");
178 expect(everything).not.toContain("secret");
179 expect(spans.some((span) => span.attributes.has("url.full"))).toBe(false);
180 }).pipe(Effect.provide(layer), Effect.withTracer(tracer));
181 });
182​
183 it.effect("reads a 403 secondary limit as a rate limit, and a 401 as a refused token", () => {
184 const answers = [
185 json({ message: "You have exceeded a secondary rate limit." }, { status: 403 }),
186 json({ message: "Bad credentials" }, { status: 401 }),
187 ];
188 const { layer, invalidations } = harness(() => answers.shift()!);
189 return Effect.gen(function* () {
190 yield* TestClock.setTime(NOW);
191 expect((yield* Effect.flip(readStats("github.com")))._tag).toBe("GitHubApiRateLimitError");
192 expect((yield* Effect.flip(readStats("github.example")))._tag).toBe(
193 "GitHubApiAuthenticationError",
194 );
195 expect(invalidations()).toBe(1);
196 }).pipe(Effect.provide(layer));
197 });
198​
199 it.effect("keeps the quota reserve for interactive requests", () => {
200 const reset = Math.floor(NOW / 1000) + 600;
201 const { layer, requests } = harness(() =>
202 json(
203 { data: { _0_repository: { pullRequest: stats } } },
204 {
205 headers: {
206 "x-ratelimit-resource": "graphql",
207 "x-ratelimit-limit": "5000",
208 "x-ratelimit-remaining": "100",
209 "x-ratelimit-reset": String(reset),
210 },
211 },
212 ),
213 );
214 return Effect.gen(function* () {
215 yield* TestClock.setTime(NOW);
216 yield* readStats("github.com", 1).pipe(
217 Effect.provideService(SourceControlRateLimit.Interactive, true),
218 );
219 const background = yield* Effect.flip(readStats("github.com", 2));
220 expect(background._tag).toBe("SourceControlRateLimitPausedError");
221 expect(requests).toHaveLength(1);
222 const api = yield* GitHubRest.GitHubRest;
223 yield* api.rest({ host: "github.com", operation: "user", path: "user" });
224 expect(requests).toHaveLength(2);
225 }).pipe(Effect.provide(layer));
226 });
227});
228​
229const callStats = (target: Partial<GitHubGraphQlClient.GitHubGraphQlTarget["Service"]> = {}) =>
230 Effect.gen(function* () {
231 const client = yield* GraphQLClient.make(
232 PullRequestBatchesGraphQLGroup.middleware(GitHubGraphQlClient.GitHubGraphQlAuth),
233 ).pipe(Effect.provide(GitHubGraphQlClient.layer));
234 return yield* client
235 .PullRequestStats({ owner: "acme", name: "web", number: 7 })
236 .pipe(GitHubGraphQlClient.call({ host: "github.com", operation: "stats", ...target }));
237 });
238​
239describe("call", () => {
240 it.effect("fails an answer whose errors all say NOT_FOUND as a missing resource", () => {
241 const { layer } = harness(() =>
242 json({
243 data: { repository: null },
244 errors: [{ type: "NOT_FOUND", message: "Could not resolve to a Repository" }],
245 }),
246 );
247 return Effect.gen(function* () {
248 const error = yield* Effect.flip(callStats());
249 expect(error).toMatchObject({
250 _tag: "GitHubApiNotFoundError",
251 host: "github.com",
252 operation: "stats",
253 });
254 }).pipe(Effect.provide(layer));
255 });
256​
257 it.effect(
258 "fails NOT_FOUND alongside another error as a failure carrying GitHub's reasons",
259 () => {
260 const { layer } = harness(() =>
261 json({
262 data: null,
263 errors: [
264 { type: "NOT_FOUND", message: "Could not resolve" },
265 { type: "FORBIDDEN", message: "Resource not accessible" },
266 ],
267 }),
268 );
269 return Effect.gen(function* () {
270 const error = yield* Effect.flip(callStats());
271 expect(error).toMatchObject({
272 _tag: "GitHubApiResponseError",
273 status: 200,
274 githubErrors: ["Could not resolve", "Resource not accessible"],
275 });
276 }).pipe(Effect.provide(layer));
277 },
278 );
279​
280 it.effect("fails an answer past the byte cap with its status", () => {
281 const { layer } = harness(() =>
282 json({ data: { repository: { pullRequest: { ...stats, padding: "x".repeat(200) } } } }),
283 );
284 return Effect.gen(function* () {
285 const error = yield* Effect.flip(callStats({ maxResponseBytes: 64 }));
286 expect(error).toMatchObject({ _tag: "GitHubApiResponseError", status: 200 });
287 }).pipe(Effect.provide(layer));
288 });
289});