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

gitHubGraphQlClient.test.ts

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