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

GitHubApi.ts

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