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

GitHubApi.ts

599 lines22.6 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 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;
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;
149​
150export class GitHubApi extends Context.Service<
151 GitHubApi,
152 {
153 /** The raw JSON body of a successful GraphQL answer, with `rateLimit` recorded. */
154 readonly graphql: (input: GitHubGraphQlInput) => Effect.Effect<string, GitHubApiError>;
155 readonly rest: (input: GitHubRestInput) => Effect.Effect<GitHubRestResponse, GitHubApiError>;
156 /** The credential a request to `host` would carry right now. */
157 readonly credential: (
158 host: string,
159 ) => Effect.Effect<
160 { readonly token: Redacted.Redacted<string>; readonly fingerprint: string },
161 GitHubApiError
162 >;
163 }
164>()("t3/sourceControl/GitHubApi") {}
165​
166function normalizeHost(host: string): string {
167 return host.trim().toLowerCase();
169​
170/**
171 * Where the API for a host lives. github.com and GHE.com data residency serve it from an `api.`
172 * subdomain; GitHub Enterprise Server serves it under `/api` on the instance itself.
173 */
174export function gitHubApiUrls(host: string): { readonly rest: string; readonly graphql: string } {
175 const normalized = normalizeHost(host);
176 if (normalized === "github.com") {
177 return { rest: "https://api.github.com", graphql: "https://api.github.com/graphql" };
178 }
179 if (normalized.endsWith(".ghe.com")) {
180 return {
181 rest: `https://api.${normalized}`,
182 graphql: `https://api.${normalized}/graphql`,
183 };
184 }
185 return { rest: `https://${normalized}/api/v3`, graphql: `https://${normalized}/api/graphql` };
187​
188/** GraphQL documents longer than this are cut in traces; the hash still identifies them. */
189const TRACED_QUERY_MAX_CHARS = 4_000;
190​
191/** A stable short id for a GraphQL document, so traces group by query without its text. */
192function queryHash(query: string): string {
193 let hash = 0x811c9dc5;
194 for (let index = 0; index < query.length; index++) {
195 hash ^= query.charCodeAt(index);
196 hash = Math.imul(hash, 0x01000193);
197 }
198 return (hash >>> 0).toString(16).padStart(8, "0");
200​
201/** The numeric rate-limit headers GitHub sends, as span attributes. */
202function rateLimitAttributes(
203 headers: Readonly<Record<string, string | undefined>>,
204): Record<string, number | string> {
205 const attributes: Record<string, number | string> = {};
206 for (const [header, name] of [
207 ["x-ratelimit-limit", "github.ratelimit.limit"],
208 ["x-ratelimit-remaining", "github.ratelimit.remaining"],
209 ["x-ratelimit-used", "github.ratelimit.used"],
210 ["x-ratelimit-reset", "github.ratelimit.reset"],
211 ] as const) {
212 const value = Number(headers[header]);
213 if (headers[header] !== undefined && Number.isFinite(value)) attributes[name] = value;
214 }
215 const resource = headers["x-ratelimit-resource"];
216 if (resource !== undefined) attributes["github.ratelimit.resource"] = resource;
217 return attributes;
219​
220const decodeGraphQlCost = Schema.decodeUnknownOption(
221 Schema.fromJsonString(
222 Schema.Struct({
223 data: Schema.Struct({
224 rateLimit: Schema.Struct({ cost: Schema.Number, remaining: Schema.Number }),
225 }),
226 }),
227 ),
228);
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 budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;
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);
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 const key = { provider: "github" as const, host };
406 const run = Effect.gen(function* () {
407 const lease = yield* limits
408 .check(key, input.allowReserve ? { allowPaused: true } : undefined)
409 .pipe(
410 Effect.tapError((paused) =>
411 Effect.annotateCurrentSpan({
412 "github.paused": true,
413 "github.retry_at": paused.retryAt,
414 }),
415 ),
416 );
417 // One deadline covers the headers and the body: a host that answers headers and then stalls
418 // must not hold a slot of the shared gate for undici's own five-minute body timeout.
419 const { response, collected } = yield* Effect.gen(function* () {
420 const response: HttpClientResponse.HttpClientResponse = yield* httpClient
421 .execute(
422 input.request.pipe(
423 HttpClientRequest.bearerToken(Redacted.value(token)),
424 HttpClientRequest.setHeaders({
425 "x-github-api-version": API_VERSION,
426 "user-agent": "t3code",
427 }),
428 ),
429 )
430 .pipe(
431 // `GitHubApi.send` is the request's span. The client's own span would add `url.full`
432 // and `url.query`, which can carry SHAs and branch names, so it is off for GitHub.
433 Effect.provideService(HttpClient.TracerDisabledWhen, () => true),
434 );
435 const collected = yield* collectUint8StreamText({
436 stream: response.stream,
437 maxBytes: input.maxResponseBytes,
438 }).pipe(
439 // 204, 304 and many refusals carry no body at all, which is an empty answer.
440 Effect.catchIf(
441 (error) => error.reason._tag === "EmptyBodyError",
442 () => Effect.succeed({ text: "", truncated: false, invalidUtf8: false }),
443 ),
444 );
445 return { response, collected };
446 }).pipe(
447 Effect.timeout(input.timeout ?? DEFAULT_TIMEOUT),
448 Effect.mapError(
449 (cause) => new GitHubApiRequestError({ host, operation: input.operation, cause }),
450 ),
451 );
452 const headers = response.headers;
453 const status = response.status;
454 yield* Effect.annotateCurrentSpan({
455 "http.response.status_code": status,
456 ...rateLimitAttributes(headers),
457 });
458 const context = { host, operation: input.operation };
459 return yield* Answer.$match(
460 classify({
461 status,
462 headers,
463 body: collected.text,
464 graphql: input.graphql === true,
465 acceptNotModified: input.acceptNotModified,
466 }),
467 {
468 Ok: () =>
469 limits.recordSuccess({ ...key, lease }).pipe(
470 Effect.as({
471 status,
472 headers,
473 body: collected.text,
474 truncated: collected.truncated,
475 invalidUtf8: collected.invalidUtf8,
476 }),
477 ),
478 RateLimited: () =>
479 Effect.gen(function* () {
480 const retryAt = retryAtFrom(headers, yield* Clock.currentTimeMillis);
481 yield* limits.recordRateLimit({ ...key, lease, retryAt });
482 yield* Effect.annotateCurrentSpan({
483 "github.rate_limited": true,
484 ...(retryAt === undefined ? {} : { "github.retry_at": retryAt }),
485 });
486 return yield* new GitHubApiRateLimitError({
487 ...context,
488 ...(retryAt === undefined ? {} : { retryAt }),
489 });
490 }),
491 // The source may hold a newer token than the one that was refused.
492 Unauthorized: () =>
493 credentials
494 .invalidate(host)
495 .pipe(Effect.andThen(Effect.fail(new GitHubApiAuthenticationError(context)))),
496 NotFound: () => Effect.fail(new GitHubApiNotFoundError(context)),
497 Failed: ({ messages }) =>
498 Effect.fail(
499 new GitHubApiResponseError({
500 ...context,
501 status,
502 ...(messages === undefined ? {} : { githubErrors: messages }),
503 }),
504 ),
505 },
506 );
507 });
508 // The rate-limit scope follows the credential, so a pause on one account never blocks another.
509 return yield* gate
510 .withPermit(run)
511 .pipe(Effect.provideService(SourceControlRateLimit.CredentialScope, scope || fingerprint));
512 });
513​
514 const rest: GitHubApi["Service"]["rest"] = (input) => {
515 const url = `${gitHubApiUrls(input.host).rest}/${input.path.replace(/^\/+/, "")}`;
516 const base = HttpClientRequest.make(input.method ?? "GET")(url).pipe(
517 HttpClientRequest.setHeader("accept", input.accept ?? "application/vnd.github+json"),
518 );
519 const withEtag =
520 input.ifNoneMatch === undefined
521 ? base
522 : base.pipe(HttpClientRequest.setHeader("if-none-match", input.ifNoneMatch));
523 const request =
524 input.body === undefined
525 ? withEtag
526 : withEtag.pipe(HttpClientRequest.bodyJsonUnsafe(input.body));
527 return AllowGitHubReserve.pipe(
528 Effect.flatMap((interactive) =>
529 send({
530 host: input.host,
531 operation: input.operation,
532 request,
533 maxResponseBytes: input.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
534 timeout: input.timeout,
535 allowReserve: input.allowReserve ?? interactive,
536 acceptNotModified: input.ifNoneMatch !== undefined,
537 }),
538 ),
539 );
540 };
541​
542 const graphql: GitHubApi["Service"]["graphql"] = Effect.fn("GitHubApi.graphql")(
543 function* (input) {
544 const host = normalizeHost(input.host);
545 const { fingerprint } = yield* credential(host);
546 const scope = (yield* SourceControlRateLimit.CredentialScope) || fingerprint;
547 const allowReserve = input.allowReserve ?? (yield* AllowGitHubReserve);
548 // The document, never its variables: user text (bodies, search terms) travels as variables.
549 yield* Effect.annotateCurrentSpan({
550 "github.operation": input.operation,
551 "github.graphql.query_hash": queryHash(input.query),
552 "github.graphql.query":
553 input.query.length > TRACED_QUERY_MAX_CHARS
554 ? `${input.query.slice(0, TRACED_QUERY_MAX_CHARS)}…`
555 : input.query,
556 });
557 return yield* Effect.gen(function* () {
558 const query = yield* budget.query(
559 host,
560 input.query,
561 allowReserve ? { allowReserve: true } : undefined,
562 );
563 const response = yield* send({
564 host,
565 operation: input.operation,
566 request: HttpClientRequest.post(gitHubApiUrls(host).graphql).pipe(
567 HttpClientRequest.acceptJson,
568 HttpClientRequest.bodyJsonUnsafe({ query, variables: input.variables ?? {} }),
569 ),
570 maxResponseBytes: DEFAULT_MAX_RESPONSE_BYTES,
571 allowReserve,
572 acceptNotModified: false,
573 graphql: true,
574 });
575 // A body cut at the byte cap hides any `errors` past the cut and cannot be decoded.
576 if (response.truncated) {
577 return yield* new GitHubApiResponseError({
578 host,
579 operation: input.operation,
580 status: response.status,
581 });
582 }
583 yield* budget.observe(host, response.body);
584 const cost = Option.getOrUndefined(decodeGraphQlCost(response.body));
585 if (cost !== undefined) {
586 yield* Effect.annotateCurrentSpan({
587 "github.graphql.cost": cost.data.rateLimit.cost,
588 "github.graphql.remaining": cost.data.rateLimit.remaining,
589 });
590 }
591 return response.body;
592 }).pipe(Effect.provideService(SourceControlRateLimit.CredentialScope, scope));
593 },
594 );
595​
596 return GitHubApi.of({ graphql, rest, credential });
597});
598​
599export const layer = Layer.effect(GitHubApi, make);