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

gitHubGraphQlClient.test.ts

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