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

GitHubApi.ts

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