Open History to see the last commit
1import * as Clock from "effect/Clock";
2import * as Context from "effect/Context";
3import * as Data from "effect/Data";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Redacted from "effect/Redacted";
9import * as Schema from "effect/Schema";
10import * as Semaphore from "effect/Semaphore";
11import { HttpClient, HttpClientRequest, type HttpClientResponse } from "effect/http";
12
13import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
14import * as GitHubCredentials from "./GitHubCredentials.ts";
15import * as GitHubQuota from "./githubQuota.ts";
16import * as SourceControlRateLimit from "./SourceControlRateLimit.ts";
17
18const DEFAULT_TIMEOUT = Duration.seconds(30);
19const DEFAULT_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
20/** Polite to GitHub's secondary limits, which punish bursts of concurrent requests. */
21const CONCURRENCY = 8;
22const API_VERSION = "2022-11-28";
23
24/**
25 * A credential already verified for one host. Every request made under it must target that
26 * host, so a page cannot read one account's data with another's token mid-flight. Server-local:
27 * never put its value in RPC payloads or cache keys.
28 */
29export const PinnedGitHubCredential = Context.Reference<{
30 readonly host: string;
31 readonly token: Redacted.Redacted<string>;
32 readonly credentialFingerprint: string;
33} | null>("t3/sourceControl/PinnedGitHubCredential", { defaultValue: () => null });
34
35/**
36 * Set by interactive callers (a user's read or write, not a background sweep). Requests made
37 * under it may spend the GraphQL reserve and go through a rate-limit pause: a user acting on a
38 * pull request should not be refused because a background read exhausted the quota.
39 */
40export const AllowGitHubReserve = Context.Reference<boolean>(
41 "t3/sourceControl/AllowGitHubReserve",
42 { defaultValue: () => false },
43);
44
45export class GitHubApiRequestError extends Schema.TaggedError<GitHubApiRequestError>()(
46 "GitHubApiRequestError",
47 { host: Schema.String, operation: Schema.String, cause: Schema.Defect() },
48) {
49 override get message(): string {
50 return `Could not reach GitHub at ${this.host}.`;
51 }
52}
53
54export class GitHubApiAuthenticationError extends Schema.TaggedError<GitHubApiAuthenticationError>()(
55 "GitHubApiAuthenticationError",
56 { host: Schema.String, operation: Schema.String },
57) {
58 override get message(): string {
59 return `GitHub refused the credential for ${this.host}. Run \`gh auth login --hostname ${this.host}\` and retry.`;
60 }
61}
62
63export class GitHubApiRateLimitError extends Schema.TaggedError<GitHubApiRateLimitError>()(
64 "GitHubApiRateLimitError",
65 {
66 host: Schema.String,
67 operation: Schema.String,
68 retryAt: Schema.optionalKey(Schema.Finite),
69 },
70) {
71 override get message(): string {
72 return "GitHub API rate limit exceeded.";
73 }
74}
75
76export class GitHubApiNotFoundError extends Schema.TaggedError<GitHubApiNotFoundError>()(
77 "GitHubApiNotFoundError",
78 { host: Schema.String, operation: Schema.String },
79) {
80 override get message(): string {
81 return "GitHub could not find the requested resource, or the credential cannot see it.";
82 }
83}
84
85/**
86 * GitHub answered with a failure that is none of the above. `githubErrors` carries GitHub's own
87 * error messages, from a GraphQL `errors` list or a REST `message`/`errors` body: they name the
88 * field and the reason ("A pull request already exists for acme:feature"), never a token.
89 */
90export class GitHubApiResponseError extends Schema.TaggedError<GitHubApiResponseError>()(
91 "GitHubApiResponseError",
92 {
93 host: Schema.String,
94 operation: Schema.String,
95 status: Schema.Int,
96 githubErrors: Schema.optionalKey(Schema.Array(Schema.String)),
97 },
98) {
99 override get message(): string {
100 return this.githubErrors !== undefined && this.githubErrors.length > 0
101 ? `GitHub returned an error: ${this.githubErrors.join("; ")}`
102 : `GitHub returned HTTP ${this.status}.`;
103 }
104}
105
106export type GitHubApiError =
107 | GitHubCredentials.GitHubCredentialUnavailableError
108 | GitHubApiRequestError
109 | GitHubApiAuthenticationError
110 | GitHubApiRateLimitError
111 | GitHubApiNotFoundError
112 | GitHubApiResponseError
113 | SourceControlRateLimit.SourceControlRateLimitPausedError;
114
115export interface GitHubRestResponse {
116 readonly status: number;
117 readonly headers: Readonly<Record<string, string | undefined>>;
118 readonly body: string;
119 readonly truncated: boolean;
120 /** The body was not valid UTF-8, which a raw file read takes to mean binary. */
121 readonly invalidUtf8: boolean;
122}
123
124export interface GitHubRestInput {
125 readonly host: string;
126 readonly operation: string;
127 readonly method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
128 /** Relative to the API root, e.g. `repos/acme/web/pulls/7`; query string included. */
129 readonly path: string;
130 readonly body?: unknown;
131 /** Defaults to `application/vnd.github+json`. */
132 readonly accept?: string;
133 /** Revalidates a cached answer. A 304 is returned rather than failed, and is free. */
134 readonly ifNoneMatch?: string;
135 readonly maxResponseBytes?: number;
136 /** Defaults to 30 seconds; a whole pull request's patch may need longer. */
137 readonly timeout?: Duration.Input;
138 /** Overrides `AllowGitHubReserve` for this one request. */
139 readonly allowReserve?: boolean;
140}
141
142export interface GitHubGraphQlInput {
143 readonly host: string;
144 readonly operation: string;
145 readonly query: string;
146 readonly variables?: Readonly<Record<string, unknown>>;
147 readonly allowReserve?: boolean;
148 readonly maxResponseBytes?: number;
149}
150
151export class GitHubApi extends Context.Service<
152 GitHubApi,
153 {
154 /** The raw JSON body of a successful GraphQL answer, with `rateLimit` recorded. */
155 readonly graphql: (input: GitHubGraphQlInput) => Effect.Effect<string, GitHubApiError>;
156 readonly rest: (input: GitHubRestInput) => Effect.Effect<GitHubRestResponse, GitHubApiError>;
157 /** The credential a request to `host` would carry right now. */
158 readonly credential: (
159 host: string,
160 ) => Effect.Effect<
161 { readonly token: Redacted.Redacted<string>; readonly fingerprint: string },
162 GitHubApiError
163 >;
164 }
165>()("t3/sourceControl/GitHubApi") {}
166
167function normalizeHost(host: string): string {
168 return host.trim().toLowerCase();
169}
170
171/**
172 * Where the API for a host lives. github.com and GHE.com data residency serve it from an `api.`
173 * subdomain; GitHub Enterprise Server serves it under `/api` on the instance itself.
174 */
175export function gitHubApiUrls(host: string): { readonly rest: string; readonly graphql: string } {
176 const normalized = normalizeHost(host);
177 if (normalized === "github.com") {
178 return { rest: "https://api.github.com", graphql: "https://api.github.com/graphql" };
179 }
180 if (normalized.endsWith(".ghe.com")) {
181 return {
182 rest: `https://api.${normalized}`,
183 graphql: `https://api.${normalized}/graphql`,
184 };
185 }
186 return { rest: `https://${normalized}/api/v3`, graphql: `https://${normalized}/api/graphql` };
187}
188
189/** GraphQL documents longer than this are cut in traces; the hash still identifies them. */
190const TRACED_QUERY_MAX_CHARS = 4_000;
191
192/** A stable short id for a GraphQL document, so traces group by query without its text. */
193function queryHash(query: string): string {
194 let hash = 0x811c9dc5;
195 for (let index = 0; index < query.length; index++) {
196 hash ^= query.charCodeAt(index);
197 hash = Math.imul(hash, 0x01000193);
198 }
199 return (hash >>> 0).toString(16).padStart(8, "0");
200}
201
202/** The numeric rate-limit headers GitHub sends, as span attributes. */
203function rateLimitAttributes(
204 headers: Readonly<Record<string, string | undefined>>,
205): Record<string, number | string> {
206 const attributes: Record<string, number | string> = {};
207 for (const [header, name] of [
208 ["x-ratelimit-limit", "github.ratelimit.limit"],
209 ["x-ratelimit-remaining", "github.ratelimit.remaining"],
210 ["x-ratelimit-used", "github.ratelimit.used"],
211 ["x-ratelimit-reset", "github.ratelimit.reset"],
212 ] as const) {
213 const value = Number(headers[header]);
214 if (headers[header] !== undefined && Number.isFinite(value)) attributes[name] = value;
215 }
216 const resource = headers["x-ratelimit-resource"];
217 if (resource !== undefined) attributes["github.ratelimit.resource"] = resource;
218 return attributes;
219}
220
221/** The pause GitHub asked for, from `retry-after` or the primary limit's reset. */
222function retryAtFrom(
223 headers: Readonly<Record<string, string | undefined>>,
224 now: number,
225): number | undefined {
226 const fromRetryAfter = SourceControlRateLimit.retryAtFromHeader(headers["retry-after"], now);
227 if (fromRetryAfter !== undefined) return fromRetryAfter;
228 const reset = Number(headers["x-ratelimit-reset"]) * 1_000;
229 return Number.isFinite(reset) && reset > now ? reset : undefined;
230}
231
232const decodeGraphQlErrors = Schema.decodeUnknownOption(
233 Schema.fromJsonString(
234 Schema.Struct({
235 errors: Schema.NonEmptyArray(
236 Schema.Struct({
237 type: Schema.optional(Schema.String),
238 message: Schema.optional(Schema.String),
239 }),
240 ),
241 }),
242 ),
243);
244
245/** A REST failure body: `{ message, errors: [{ message } | { resource, field, code }] }`. */
246const decodeRestErrors = Schema.decodeUnknownOption(
247 Schema.fromJsonString(
248 Schema.Struct({
249 message: Schema.optional(Schema.String),
250 errors: Schema.optional(
251 Schema.Array(
252 Schema.Union([
253 Schema.String,
254 Schema.Struct({
255 message: Schema.optional(Schema.String),
256 field: Schema.optional(Schema.String),
257 code: Schema.optional(Schema.String),
258 }),
259 ]),
260 ),
261 ),
262 }),
263 ),
264);
265
266function restErrorMessages(body: string): ReadonlyArray<string> | undefined {
267 return Option.match(decodeRestErrors(body), {
268 onNone: () => undefined,
269 onSome: (decoded) => {
270 const details = (decoded.errors ?? []).flatMap((error) =>
271 typeof error === "string"
272 ? [error]
273 : error.message !== undefined
274 ? [error.message]
275 : error.field !== undefined && error.code !== undefined
276 ? [`${error.field} ${error.code}`]
277 : [],
278 );
279 const messages = [...(decoded.message === undefined ? [] : [decoded.message]), ...details];
280 return messages.length > 0 ? messages : undefined;
281 },
282 });
283}
284
285/** What one GitHub answer means, decided once from its status, headers and body. */
286type Answer = Data.TaggedEnum<{
287 Ok: {};
288 RateLimited: {};
289 Unauthorized: {};
290 NotFound: {};
291 Failed: { readonly messages: ReadonlyArray<string> | undefined };
292}>;
293const Answer = Data.taggedEnum<Answer>();
294
295/**
296 * GitHub reports a failed GraphQL document with HTTP 200 and an `errors` list, so a GraphQL body
297 * is read for its error types as well as its status. `gh api graphql` failed those too, and
298 * callers rely on that to fall back to narrower reads.
299 */
300function classify(input: {
301 readonly status: number;
302 readonly headers: Readonly<Record<string, string | undefined>>;
303 readonly body: string;
304 readonly graphql: boolean;
305 readonly acceptNotModified: boolean;
306}): Answer {
307 const { status, headers, body } = input;
308 const errors = input.graphql
309 ? Option.getOrUndefined(decodeGraphQlErrors(body))?.errors
310 : undefined;
311 const types = errors?.flatMap((error) => (error.type === undefined ? [] : [error.type])) ?? [];
312 const messages = errors?.flatMap((error) => (error.message === undefined ? [] : [error.message]));
313 if (
314 status === 429 ||
315 types.includes("RATE_LIMITED") ||
316 // An exhausted GraphQL quota can answer HTTP 200 with an untyped "API rate limit already
317 // exceeded" error; the headers say the same thing.
318 (input.graphql && errors !== undefined && headers["x-ratelimit-remaining"] === "0") ||
319 (input.graphql &&
320 messages !== undefined &&
321 messages.some((message) => /rate limit (already )?exceeded/i.test(message))) ||
322 (status === 403 &&
323 (headers["x-ratelimit-remaining"] === "0" ||
324 headers["retry-after"] !== undefined ||
325 /rate limit/i.test(body)))
326 ) {
327 return Answer.RateLimited();
328 }
329 if (status === 401) return Answer.Unauthorized();
330 if (
331 status === 404 ||
332 (errors !== undefined && errors.every((error) => error.type === "NOT_FOUND"))
333 ) {
334 return Answer.NotFound();
335 }
336 if (errors !== undefined) return Answer.Failed({ messages });
337 if ((status >= 200 && status < 300) || (status === 304 && input.acceptNotModified)) {
338 return Answer.Ok();
339 }
340 return Answer.Failed({ messages: input.graphql ? undefined : restErrorMessages(body) });
341}
342
343/** @public Service construction is part of the canonical Effect module API. */
344export const make = Effect.gen(function* () {
345 const httpClient = yield* HttpClient.HttpClient;
346 const credentials = yield* GitHubCredentials.GitHubCredentials;
347 const quota = yield* GitHubQuota.GitHubQuota;
348 const limits = yield* SourceControlRateLimit.SourceControlRateLimit;
349 const gate = yield* Semaphore.make(CONCURRENCY);
350
351 const credential: GitHubApi["Service"]["credential"] = Effect.fn("GitHubApi.credential")(
352 function* (host) {
353 const normalized = normalizeHost(host);
354 const pinned = yield* PinnedGitHubCredential;
355 if (pinned !== null) {
356 // A pinned page only ever talks to the host it verified.
357 if (pinned.host !== normalized) {
358 return yield* new GitHubApiAuthenticationError({
359 host: normalized,
360 operation: "credential",
361 });
362 }
363 return { token: pinned.token, fingerprint: pinned.credentialFingerprint };
364 }
365 const held = yield* credentials.get(normalized);
366 return { token: held.token, fingerprint: held.fingerprint };
367 },
368 );
369
370 /**
371 * Sends one request under the host's rate-limit pause and fails a refusal with the error that
372 * says why. `onSuccess` sees the answer only once it is known to be one.
373 */
374 const send = Effect.fn("GitHubApi.send")(function* (input: {
375 readonly host: string;
376 readonly operation: string;
377 readonly request: HttpClientRequest.HttpClientRequest;
378 readonly maxResponseBytes: number;
379 readonly timeout?: Duration.Input | undefined;
380 readonly allowReserve: boolean;
381 readonly acceptNotModified: boolean;
382 /** Reads the body for GraphQL `errors`, which GitHub sends with HTTP 200. */
383 readonly graphql?: boolean;
384 }) {
385 const host = normalizeHost(input.host);
386 // Only the path: a query string can carry a SHA or a branch, and never needs to be in a trace.
387 yield* Effect.annotateCurrentSpan({
388 "github.host": host,
389 "github.operation": input.operation,
390 "github.kind": input.graphql === true ? "graphql" : "rest",
391 "http.request.method": input.request.method,
392 "url.path": new URL(input.request.url).pathname,
393 });
394 const { token, fingerprint } = yield* credential(host);
395 const scope = yield* SourceControlRateLimit.CredentialScope;
396 // REST spends `core` and GraphQL its own quota, each with its own reserve. Every REST path
397 // this reads today is `core`; a `search/` read would need its own resource here. A refusal
398 // still pauses the whole host, the key PullRequestService records its own backoff under.
399 const resource = input.graphql === true ? "graphql" : "core";
400 const key = { provider: "github" as const, host };
401 const run = Effect.gen(function* () {
402 const lease = yield* quota
403 .admit(host, resource, { allowReserve: input.allowReserve })
404 .pipe(
405 Effect.andThen(limits.check(key, input.allowReserve ? { allowPaused: true } : undefined)),
406 )
407 .pipe(
408 Effect.tapError((paused) =>
409 Effect.annotateCurrentSpan({
410 "github.paused": true,
411 "github.retry_at": paused.retryAt,
412 }),
413 ),
414 );
415 // One deadline covers the headers and the body: a host that answers headers and then stalls
416 // must not hold a slot of the shared gate for undici's own five-minute body timeout.
417 const { response, collected } = yield* Effect.gen(function* () {
418 const response: HttpClientResponse.HttpClientResponse = yield* httpClient
419 .execute(
420 input.request.pipe(
421 HttpClientRequest.bearerToken(Redacted.value(token)),
422 HttpClientRequest.setHeaders({
423 "x-github-api-version": API_VERSION,
424 "user-agent": "t3code",
425 }),
426 ),
427 )
428 .pipe(
429 // `GitHubApi.send` is the request's span. The client's own span would add `url.full`
430 // and `url.query`, which can carry SHAs and branch names, so it is off for GitHub.
431 Effect.provideService(HttpClient.TracerDisabledWhen, () => true),
432 );
433 const collected = yield* collectUint8StreamText({
434 stream: response.stream,
435 maxBytes: input.maxResponseBytes,
436 }).pipe(
437 // 204, 304 and many refusals carry no body at all, which is an empty answer.
438 Effect.catchIf(
439 (error) => error.reason._tag === "EmptyBodyError",
440 () => Effect.succeed({ text: "", truncated: false, invalidUtf8: false }),
441 ),
442 );
443 return { response, collected };
444 }).pipe(
445 Effect.timeout(input.timeout ?? DEFAULT_TIMEOUT),
446 Effect.mapError(
447 (cause) => new GitHubApiRequestError({ host, operation: input.operation, cause }),
448 ),
449 );
450 const headers = response.headers;
451 const status = response.status;
452 yield* quota.observe(host, headers);
453 yield* Effect.annotateCurrentSpan({
454 "http.response.status_code": status,
455 ...rateLimitAttributes(headers),
456 });
457 const context = { host, operation: input.operation };
458 return yield* Answer.$match(
459 classify({
460 status,
461 headers,
462 body: collected.text,
463 graphql: input.graphql === true,
464 acceptNotModified: input.acceptNotModified,
465 }),
466 {
467 Ok: () =>
468 limits.recordSuccess({ ...key, lease }).pipe(
469 Effect.as({
470 status,
471 headers,
472 body: collected.text,
473 truncated: collected.truncated,
474 invalidUtf8: collected.invalidUtf8,
475 }),
476 ),
477 RateLimited: () =>
478 Effect.gen(function* () {
479 const retryAt = retryAtFrom(headers, yield* Clock.currentTimeMillis);
480 yield* limits.recordRateLimit({ ...key, lease, retryAt });
481 yield* Effect.annotateCurrentSpan({
482 "github.rate_limited": true,
483 ...(retryAt === undefined ? {} : { "github.retry_at": retryAt }),
484 });
485 return yield* new GitHubApiRateLimitError({
486 ...context,
487 ...(retryAt === undefined ? {} : { retryAt }),
488 });
489 }),
490 // The source may hold a newer token than the one that was refused.
491 Unauthorized: () =>
492 credentials
493 .invalidate(host)
494 .pipe(Effect.andThen(Effect.fail(new GitHubApiAuthenticationError(context)))),
495 NotFound: () => Effect.fail(new GitHubApiNotFoundError(context)),
496 Failed: ({ messages }) =>
497 Effect.fail(
498 new GitHubApiResponseError({
499 ...context,
500 status,
501 ...(messages === undefined ? {} : { githubErrors: messages }),
502 }),
503 ),
504 },
505 );
506 });
507 // The rate-limit scope follows the credential, so a pause on one account never blocks another.
508 return yield* gate
509 .withPermit(run)
510 .pipe(Effect.provideService(SourceControlRateLimit.CredentialScope, scope || fingerprint));
511 });
512
513 const rest: GitHubApi["Service"]["rest"] = (input) => {
514 const url = `${gitHubApiUrls(input.host).rest}/${input.path.replace(/^\/+/, "")}`;
515 const base = HttpClientRequest.make(input.method ?? "GET")(url).pipe(
516 HttpClientRequest.setHeader("accept", input.accept ?? "application/vnd.github+json"),
517 );
518 const withEtag =
519 input.ifNoneMatch === undefined
520 ? base
521 : base.pipe(HttpClientRequest.setHeader("if-none-match", input.ifNoneMatch));
522 const request =
523 input.body === undefined
524 ? withEtag
525 : withEtag.pipe(HttpClientRequest.bodyJsonUnsafe(input.body));
526 return AllowGitHubReserve.pipe(
527 Effect.flatMap((interactive) =>
528 send({
529 host: input.host,
530 operation: input.operation,
531 request,
532 maxResponseBytes: input.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
533 timeout: input.timeout,
534 allowReserve: input.allowReserve ?? interactive,
535 acceptNotModified: input.ifNoneMatch !== undefined,
536 }),
537 ),
538 );
539 };
540
541 const graphql: GitHubApi["Service"]["graphql"] = Effect.fn("GitHubApi.graphql")(
542 function* (input) {
543 const host = normalizeHost(input.host);
544 const { fingerprint } = yield* credential(host);
545 const scope = (yield* SourceControlRateLimit.CredentialScope) || fingerprint;
546 const allowReserve = input.allowReserve ?? (yield* AllowGitHubReserve);
547 // The document, never its variables: user text (bodies, search terms) travels as variables.
548 yield* Effect.annotateCurrentSpan({
549 "github.operation": input.operation,
550 "github.graphql.query_hash": queryHash(input.query),
551 "github.graphql.query":
552 input.query.length > TRACED_QUERY_MAX_CHARS
553 ? `${input.query.slice(0, TRACED_QUERY_MAX_CHARS)}…`
554 : input.query,
555 });
556 return yield* Effect.gen(function* () {
557 const response = yield* send({
558 host,
559 operation: input.operation,
560 request: HttpClientRequest.post(gitHubApiUrls(host).graphql).pipe(
561 HttpClientRequest.acceptJson,
562 HttpClientRequest.bodyJsonUnsafe({
563 query: input.query,
564 variables: input.variables ?? {},
565 }),
566 ),
567 maxResponseBytes: input.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
568 allowReserve,
569 acceptNotModified: false,
570 graphql: true,
571 });
572 // A body cut at the byte cap hides any `errors` past the cut and cannot be decoded.
573 if (response.truncated) {
574 return yield* new GitHubApiResponseError({
575 host,
576 operation: input.operation,
577 status: response.status,
578 });
579 }
580 return response.body;
581 }).pipe(Effect.provideService(SourceControlRateLimit.CredentialScope, scope));
582 },
583 );
584
585 return GitHubApi.of({ graphql, rest, credential });
586});
587
588export const layer = Layer.effect(GitHubApi, make);
589
590/**
591 * The transport with the credential, quota reserve and rate-limit pause it reads through. An
592 * application builds this once so every GitHub reader shares one view of each quota per host.
593 */
594export const layerWithDependencies = layer.pipe(
595 Layer.provideMerge(GitHubCredentials.layer),
596 Layer.provideMerge(GitHubQuota.layer),
597 Layer.provideMerge(SourceControlRateLimit.layer),
598);