Open History to see the last commit
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 }
52}
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 }
61}
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 }
74}
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 }
83}
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 }
104}
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;
122}
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;
140}
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;
148 readonly maxResponseBytes?: number;
149}
150
151export class GitHubApi extends Context.Service<
152 GitHubApi,
153 {
154 /** The raw JSON body of a successful GraphQL answer, with `rateLimit` recorded. */
155 readonly graphql: (input: GitHubGraphQlInput) => Effect.Effect<string, GitHubApiError>;
156 readonly rest: (input: GitHubRestInput) => Effect.Effect<GitHubRestResponse, GitHubApiError>;
157 /** The credential a request to `host` would carry right now. */
158 readonly credential: (
159 host: string,
160 ) => Effect.Effect<
161 { readonly token: Redacted.Redacted<string>; readonly fingerprint: string },
162 GitHubApiError
163 >;
164 }
165>()("t3/sourceControl/GitHubApi") {}
166
167function normalizeHost(host: string): string {
168 return host.trim().toLowerCase();
169}
170
171/**
172 * Where the API for a host lives. github.com and GHE.com data residency serve it from an `api.`
173 * subdomain; GitHub Enterprise Server serves it under `/api` on the instance itself.
174 */
175export function gitHubApiUrls(host: string): { readonly rest: string; readonly graphql: string } {
176 const normalized = normalizeHost(host);
177 if (normalized === "github.com") {
178 return { rest: "https://api.github.com", graphql: "https://api.github.com/graphql" };
179 }
180 if (normalized.endsWith(".ghe.com")) {
181 return {
182 rest: `https://api.${normalized}`,
183 graphql: `https://api.${normalized}/graphql`,
184 };
185 }
186 return { rest: `https://${normalized}/api/v3`, graphql: `https://${normalized}/api/graphql` };
187}
188
189/** GraphQL documents longer than this are cut in traces; the hash still identifies them. */
190const TRACED_QUERY_MAX_CHARS = 4_000;
191
192/** A stable short id for a GraphQL document, so traces group by query without its text. */
193function queryHash(query: string): string {
194 let hash = 0x811c9dc5;
195 for (let index = 0; index < query.length; index++) {
196 hash ^= query.charCodeAt(index);
197 hash = Math.imul(hash, 0x01000193);
198 }
199 return (hash >>> 0).toString(16).padStart(8, "0");
200}
201
202/** The numeric rate-limit headers GitHub sends, as span attributes. */
203function rateLimitAttributes(
204 headers: Readonly<Record<string, string | undefined>>,
205): Record<string, number | string> {
206 const attributes: Record<string, number | string> = {};
207 for (const [header, name] of [
208 ["x-ratelimit-limit", "github.ratelimit.limit"],
209 ["x-ratelimit-remaining", "github.ratelimit.remaining"],
210 ["x-ratelimit-used", "github.ratelimit.used"],
211 ["x-ratelimit-reset", "github.ratelimit.reset"],
212 ] as const) {
213 const value = Number(headers[header]);
214 if (headers[header] !== undefined && Number.isFinite(value)) attributes[name] = value;
215 }
216 const resource = headers["x-ratelimit-resource"];
217 if (resource !== undefined) attributes["github.ratelimit.resource"] = resource;
218 return attributes;
219}
220
221const decodeGraphQlCost = Schema.decodeUnknownOption(
222 Schema.fromJsonString(
223 Schema.Struct({
224 data: Schema.Struct({
225 rateLimit: Schema.Struct({ cost: Schema.Number, remaining: Schema.Number }),
226 }),
227 }),
228 ),
229);
230
231/** The pause GitHub asked for, from `retry-after` or the primary limit's reset. */
232function retryAtFrom(
233 headers: Readonly<Record<string, string | undefined>>,
234 now: number,
235): number | undefined {
236 const fromRetryAfter = SourceControlRateLimit.retryAtFromHeader(headers["retry-after"], now);
237 if (fromRetryAfter !== undefined) return fromRetryAfter;
238 const reset = Number(headers["x-ratelimit-reset"]) * 1_000;
239 return Number.isFinite(reset) && reset > now ? reset : undefined;
240}
241
242const decodeGraphQlErrors = Schema.decodeUnknownOption(
243 Schema.fromJsonString(
244 Schema.Struct({
245 errors: Schema.NonEmptyArray(
246 Schema.Struct({
247 type: Schema.optional(Schema.String),
248 message: Schema.optional(Schema.String),
249 }),
250 ),
251 }),
252 ),
253);
254
255/** A REST failure body: `{ message, errors: [{ message } | { resource, field, code }] }`. */
256const decodeRestErrors = Schema.decodeUnknownOption(
257 Schema.fromJsonString(
258 Schema.Struct({
259 message: Schema.optional(Schema.String),
260 errors: Schema.optional(
261 Schema.Array(
262 Schema.Union([
263 Schema.String,
264 Schema.Struct({
265 message: Schema.optional(Schema.String),
266 field: Schema.optional(Schema.String),
267 code: Schema.optional(Schema.String),
268 }),
269 ]),
270 ),
271 ),
272 }),
273 ),
274);
275
276function restErrorMessages(body: string): ReadonlyArray<string> | undefined {
277 return Option.match(decodeRestErrors(body), {
278 onNone: () => undefined,
279 onSome: (decoded) => {
280 const details = (decoded.errors ?? []).flatMap((error) =>
281 typeof error === "string"
282 ? [error]
283 : error.message !== undefined
284 ? [error.message]
285 : error.field !== undefined && error.code !== undefined
286 ? [`${error.field} ${error.code}`]
287 : [],
288 );
289 const messages = [...(decoded.message === undefined ? [] : [decoded.message]), ...details];
290 return messages.length > 0 ? messages : undefined;
291 },
292 });
293}
294
295/** What one GitHub answer means, decided once from its status, headers and body. */
296type Answer = Data.TaggedEnum<{
297 Ok: {};
298 RateLimited: {};
299 Unauthorized: {};
300 NotFound: {};
301 Failed: { readonly messages: ReadonlyArray<string> | undefined };
302}>;
303const Answer = Data.taggedEnum<Answer>();
304
305/**
306 * GitHub reports a failed GraphQL document with HTTP 200 and an `errors` list, so a GraphQL body
307 * is read for its error types as well as its status. `gh api graphql` failed those too, and
308 * callers rely on that to fall back to narrower reads.
309 */
310function classify(input: {
311 readonly status: number;
312 readonly headers: Readonly<Record<string, string | undefined>>;
313 readonly body: string;
314 readonly graphql: boolean;
315 readonly acceptNotModified: boolean;
316}): Answer {
317 const { status, headers, body } = input;
318 const errors = input.graphql
319 ? Option.getOrUndefined(decodeGraphQlErrors(body))?.errors
320 : undefined;
321 const types = errors?.flatMap((error) => (error.type === undefined ? [] : [error.type])) ?? [];
322 const messages = errors?.flatMap((error) => (error.message === undefined ? [] : [error.message]));
323 if (
324 status === 429 ||
325 types.includes("RATE_LIMITED") ||
326 // An exhausted GraphQL quota can answer HTTP 200 with an untyped "API rate limit already
327 // exceeded" error; the headers say the same thing.
328 (input.graphql && errors !== undefined && headers["x-ratelimit-remaining"] === "0") ||
329 (input.graphql &&
330 messages !== undefined &&
331 messages.some((message) => /rate limit (already )?exceeded/i.test(message))) ||
332 (status === 403 &&
333 (headers["x-ratelimit-remaining"] === "0" ||
334 headers["retry-after"] !== undefined ||
335 /rate limit/i.test(body)))
336 ) {
337 return Answer.RateLimited();
338 }
339 if (status === 401) return Answer.Unauthorized();
340 if (
341 status === 404 ||
342 (errors !== undefined && errors.every((error) => error.type === "NOT_FOUND"))
343 ) {
344 return Answer.NotFound();
345 }
346 if (errors !== undefined) return Answer.Failed({ messages });
347 if ((status >= 200 && status < 300) || (status === 304 && input.acceptNotModified)) {
348 return Answer.Ok();
349 }
350 return Answer.Failed({ messages: input.graphql ? undefined : restErrorMessages(body) });
351}
352
353/** @public Service construction is part of the canonical Effect module API. */
354export const make = Effect.gen(function* () {
355 const httpClient = yield* HttpClient.HttpClient;
356 const credentials = yield* GitHubCredentials.GitHubCredentials;
357 const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;
358 const limits = yield* SourceControlRateLimit.SourceControlRateLimit;
359 const gate = yield* Semaphore.make(CONCURRENCY);
360
361 const credential: GitHubApi["Service"]["credential"] = Effect.fn("GitHubApi.credential")(
362 function* (host) {
363 const normalized = normalizeHost(host);
364 const pinned = yield* PinnedGitHubCredential;
365 if (pinned !== null) {
366 // A pinned page only ever talks to the host it verified.
367 if (pinned.host !== normalized) {
368 return yield* new GitHubApiAuthenticationError({
369 host: normalized,
370 operation: "credential",
371 });
372 }
373 return { token: pinned.token, fingerprint: pinned.credentialFingerprint };
374 }
375 const held = yield* credentials.get(normalized);
376 return { token: held.token, fingerprint: held.fingerprint };
377 },
378 );
379
380 /**
381 * Sends one request under the host's rate-limit pause and fails a refusal with the error that
382 * says why. `onSuccess` sees the answer only once it is known to be one.
383 */
384 const send = Effect.fn("GitHubApi.send")(function* (input: {
385 readonly host: string;
386 readonly operation: string;
387 readonly request: HttpClientRequest.HttpClientRequest;
388 readonly maxResponseBytes: number;
389 readonly timeout?: Duration.Input | undefined;
390 readonly allowReserve: boolean;
391 readonly acceptNotModified: boolean;
392 /** Reads the body for GraphQL `errors`, which GitHub sends with HTTP 200. */
393 readonly graphql?: boolean;
394 }) {
395 const host = normalizeHost(input.host);
396 // Only the path: a query string can carry a SHA or a branch, and never needs to be in a trace.
397 yield* Effect.annotateCurrentSpan({
398 "github.host": host,
399 "github.operation": input.operation,
400 "github.kind": input.graphql === true ? "graphql" : "rest",
401 "http.request.method": input.request.method,
402 "url.path": new URL(input.request.url).pathname,
403 });
404 const { token, fingerprint } = yield* credential(host);
405 const scope = yield* SourceControlRateLimit.CredentialScope;
406 const key = { provider: "github" as const, host };
407 const run = Effect.gen(function* () {
408 const lease = yield* limits
409 .check(key, input.allowReserve ? { allowPaused: true } : undefined)
410 .pipe(
411 Effect.tapError((paused) =>
412 Effect.annotateCurrentSpan({
413 "github.paused": true,
414 "github.retry_at": paused.retryAt,
415 }),
416 ),
417 );
418 // One deadline covers the headers and the body: a host that answers headers and then stalls
419 // must not hold a slot of the shared gate for undici's own five-minute body timeout.
420 const { response, collected } = yield* Effect.gen(function* () {
421 const response: HttpClientResponse.HttpClientResponse = yield* httpClient
422 .execute(
423 input.request.pipe(
424 HttpClientRequest.bearerToken(Redacted.value(token)),
425 HttpClientRequest.setHeaders({
426 "x-github-api-version": API_VERSION,
427 "user-agent": "t3code",
428 }),
429 ),
430 )
431 .pipe(
432 // `GitHubApi.send` is the request's span. The client's own span would add `url.full`
433 // and `url.query`, which can carry SHAs and branch names, so it is off for GitHub.
434 Effect.provideService(HttpClient.TracerDisabledWhen, () => true),
435 );
436 const collected = yield* collectUint8StreamText({
437 stream: response.stream,
438 maxBytes: input.maxResponseBytes,
439 }).pipe(
440 // 204, 304 and many refusals carry no body at all, which is an empty answer.
441 Effect.catchIf(
442 (error) => error.reason._tag === "EmptyBodyError",
443 () => Effect.succeed({ text: "", truncated: false, invalidUtf8: false }),
444 ),
445 );
446 return { response, collected };
447 }).pipe(
448 Effect.timeout(input.timeout ?? DEFAULT_TIMEOUT),
449 Effect.mapError(
450 (cause) => new GitHubApiRequestError({ host, operation: input.operation, cause }),
451 ),
452 );
453 const headers = response.headers;
454 const status = response.status;
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 query = yield* budget.query(
560 host,
561 input.query,
562 allowReserve ? { allowReserve: true } : undefined,
563 );
564 const response = yield* send({
565 host,
566 operation: input.operation,
567 request: HttpClientRequest.post(gitHubApiUrls(host).graphql).pipe(
568 HttpClientRequest.acceptJson,
569 HttpClientRequest.bodyJsonUnsafe({ query, variables: input.variables ?? {} }),
570 ),
571 maxResponseBytes: input.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
572 allowReserve,
573 acceptNotModified: false,
574 graphql: true,
575 });
576 // A body cut at the byte cap hides any `errors` past the cut and cannot be decoded.
577 if (response.truncated) {
578 return yield* new GitHubApiResponseError({
579 host,
580 operation: input.operation,
581 status: response.status,
582 });
583 }
584 yield* budget.observe(host, response.body);
585 const cost = Option.getOrUndefined(decodeGraphQlCost(response.body));
586 if (cost !== undefined) {
587 yield* Effect.annotateCurrentSpan({
588 "github.graphql.cost": cost.data.rateLimit.cost,
589 "github.graphql.remaining": cost.data.rateLimit.remaining,
590 });
591 }
592 return response.body;
593 }).pipe(Effect.provideService(SourceControlRateLimit.CredentialScope, scope));
594 },
595 );
596
597 return GitHubApi.of({ graphql, rest, credential });
598});
599
600export const layer = Layer.effect(GitHubApi, make);