The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { describe, expect, it } from "@effect/vitest"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import * as Layer from "effect/Layer"; |
| 4 | import * as Redacted from "effect/Redacted"; |
| 5 | import * as TestClock from "effect/testing/TestClock"; |
| 6 | import * as Tracer from "effect/Tracer"; |
| 7 | import { HttpClient, HttpClientResponse, type HttpClientRequest } from "effect/http"; |
| 8 | import { GraphQLClient, GraphQLResolver } from "effect/graphql"; |
| 9 | import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; |
| 10 | |
| 11 | import * as GitHubRest from "./GitHubRest.ts"; |
| 12 | import * as GitHubCredentials from "./GitHubCredentials.ts"; |
| 13 | import * as GitHubGraphQlClient from "./gitHubGraphQlClient.ts"; |
| 14 | import * as GitHubQuota from "./GitHubQuota.ts"; |
| 15 | import { PullRequestBatchesGraphQLGroup } from "./pullRequestBatches.graphql.ts"; |
| 16 | import * as GitHubAppSignIn from "./GitHubAppSignIn.ts"; |
| 17 | |
| 18 | const appSignedOut = Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({ |
| 19 | enabled: false, |
| 20 | token: () => Effect.succeedNone, |
| 21 | invalidate: () => Effect.void, |
| 22 | }); |
| 23 | |
| 24 | const NOW = Date.parse("2026-10-05T12:00:00.000Z"); |
| 25 | |
| 26 | function 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 }; |
| 67 | } |
| 68 | |
| 69 | const json = (body: unknown, init?: ResponseInit) => |
| 70 | new Response(JSON.stringify(body), { |
| 71 | ...init, |
| 72 | headers: { "content-type": "application/json", ...init?.headers }, |
| 73 | }); |
| 74 | |
| 75 | const 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 | |
| 93 | const stats = { additions: 3, deletions: 1 }; |
| 94 | |
| 95 | describe("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 | json( |
| 227 | { data: null, errors: [{ message: "You have exceeded a secondary rate limit." }] }, |
| 228 | { status: 403, headers: { "retry-after": "60" } }, |
| 229 | ), |
| 230 | ]; |
| 231 | const { layer, invalidations } = harness(() => answers.shift()!); |
| 232 | return Effect.gen(function* () { |
| 233 | yield* TestClock.setTime(NOW); |
| 234 | expect((yield* Effect.flip(readStats("github.com")))._tag).toBe("GitHubApiRateLimitError"); |
| 235 | expect((yield* Effect.flip(readStats("github.example")))._tag).toBe( |
| 236 | "GitHubApiAuthenticationError", |
| 237 | ); |
| 238 | expect(yield* Effect.flip(readStats("github.acme.test"))).toMatchObject({ |
| 239 | _tag: "GitHubApiRateLimitError", |
| 240 | retryAt: NOW + 60_000, |
| 241 | }); |
| 242 | expect(invalidations()).toBe(1); |
| 243 | }).pipe(Effect.provide(layer)); |
| 244 | }); |
| 245 | |
| 246 | it.effect("keeps the quota reserve for interactive requests", () => { |
| 247 | const reset = Math.floor(NOW / 1000) + 600; |
| 248 | const { layer, requests } = harness(() => |
| 249 | json( |
| 250 | { data: { _0_repository: { pullRequest: stats } } }, |
| 251 | { |
| 252 | headers: { |
| 253 | "x-ratelimit-resource": "graphql", |
| 254 | "x-ratelimit-limit": "5000", |
| 255 | "x-ratelimit-remaining": "100", |
| 256 | "x-ratelimit-reset": String(reset), |
| 257 | }, |
| 258 | }, |
| 259 | ), |
| 260 | ); |
| 261 | return Effect.gen(function* () { |
| 262 | yield* TestClock.setTime(NOW); |
| 263 | yield* readStats("github.com", 1).pipe( |
| 264 | Effect.provideService(SourceControlRateLimit.Interactive, true), |
| 265 | ); |
| 266 | const background = yield* Effect.flip(readStats("github.com", 2)); |
| 267 | expect(background._tag).toBe("SourceControlRateLimitPausedError"); |
| 268 | expect(requests).toHaveLength(1); |
| 269 | const api = yield* GitHubRest.GitHubRest; |
| 270 | yield* api.rest({ host: "github.com", operation: "user", path: "user" }); |
| 271 | expect(requests).toHaveLength(2); |
| 272 | }).pipe(Effect.provide(layer)); |
| 273 | }); |
| 274 | }); |
| 275 | |
| 276 | const callStats = (target: Partial<GitHubGraphQlClient.GitHubGraphQlTarget["Service"]> = {}) => |
| 277 | Effect.gen(function* () { |
| 278 | const client = yield* GraphQLClient.make( |
| 279 | PullRequestBatchesGraphQLGroup.middleware(GitHubGraphQlClient.GitHubGraphQlAuth), |
| 280 | ).pipe(Effect.provide(GitHubGraphQlClient.layer)); |
| 281 | return yield* client |
| 282 | .PullRequestStats({ owner: "acme", name: "web", number: 7 }) |
| 283 | .pipe(GitHubGraphQlClient.call({ host: "github.com", operation: "stats", ...target })); |
| 284 | }); |
| 285 | |
| 286 | describe("call", () => { |
| 287 | it.effect("fails an answer whose errors all say NOT_FOUND as a missing resource", () => { |
| 288 | const { layer } = harness(() => |
| 289 | json({ |
| 290 | data: { repository: null }, |
| 291 | errors: [ |
| 292 | { type: "NOT_FOUND", path: ["repository"], message: "Could not resolve to a Repository" }, |
| 293 | ], |
| 294 | }), |
| 295 | ); |
| 296 | return Effect.gen(function* () { |
| 297 | const error = yield* Effect.flip(callStats()); |
| 298 | expect(error).toMatchObject({ |
| 299 | _tag: "GitHubApiNotFoundError", |
| 300 | host: "github.com", |
| 301 | operation: "stats", |
| 302 | githubErrors: ["Could not resolve to a Repository (at repository)"], |
| 303 | }); |
| 304 | }).pipe(Effect.provide(layer)); |
| 305 | }); |
| 306 | |
| 307 | it.effect( |
| 308 | "fails a NOT_FOUND below the pull request as GitHub's reason, not a missing one", |
| 309 | () => { |
| 310 | const { layer } = harness(() => |
| 311 | json({ |
| 312 | data: { repository: { pullRequest: stats } }, |
| 313 | errors: [ |
| 314 | { |
| 315 | type: "NOT_FOUND", |
| 316 | path: ["repository", "pullRequest", "baseRef", "compare"], |
| 317 | message: "Could not resolve head ref 'refs/pull/7/head'.", |
| 318 | }, |
| 319 | ], |
| 320 | }), |
| 321 | ); |
| 322 | return Effect.gen(function* () { |
| 323 | const error = yield* Effect.flip(callStats()); |
| 324 | expect(error).toMatchObject({ |
| 325 | _tag: "GitHubApiResponseError", |
| 326 | status: 200, |
| 327 | githubErrors: [ |
| 328 | "Could not resolve head ref 'refs/pull/7/head'. (at repository.pullRequest.baseRef.compare)", |
| 329 | ], |
| 330 | }); |
| 331 | }).pipe(Effect.provide(layer)); |
| 332 | }, |
| 333 | ); |
| 334 | |
| 335 | it.effect( |
| 336 | "fails NOT_FOUND alongside another error as a failure carrying GitHub's reasons", |
| 337 | () => { |
| 338 | const { layer } = harness(() => |
| 339 | json({ |
| 340 | data: null, |
| 341 | errors: [ |
| 342 | { type: "NOT_FOUND", message: "Could not resolve" }, |
| 343 | { type: "FORBIDDEN", message: "Resource not accessible" }, |
| 344 | { message: "Unknown error" }, |
| 345 | ], |
| 346 | }), |
| 347 | ); |
| 348 | return Effect.gen(function* () { |
| 349 | const error = yield* Effect.flip(callStats()); |
| 350 | expect(error).toMatchObject({ |
| 351 | _tag: "GitHubApiResponseError", |
| 352 | status: 200, |
| 353 | githubErrors: ["Could not resolve", "Resource not accessible", "Unknown error"], |
| 354 | githubErrorTypes: ["NOT_FOUND", "FORBIDDEN", null], |
| 355 | }); |
| 356 | }).pipe(Effect.provide(layer)); |
| 357 | }, |
| 358 | ); |
| 359 | |
| 360 | it.effect("fails an answer past the byte cap with its status", () => { |
| 361 | const { layer } = harness(() => |
| 362 | json({ data: { repository: { pullRequest: { ...stats, padding: "x".repeat(200) } } } }), |
| 363 | ); |
| 364 | return Effect.gen(function* () { |
| 365 | const error = yield* Effect.flip(callStats({ maxResponseBytes: 64 })); |
| 366 | expect(error).toMatchObject({ _tag: "GitHubApiResponseError", status: 200 }); |
| 367 | }).pipe(Effect.provide(layer)); |
| 368 | }); |
| 369 | }); |