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

GitHubApi.ts

607 lines23.3 KB

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