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

GitHubApi.ts

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