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

GitHubRequestPolicy.ts

471 lines17.9 KB

1import { normalizeHost } from "@t3tools/source-control-core/server/pullRequestUtils";
2import { SourceControlProviderKind } from "@t3tools/contracts";
3import * as Cause from "effect/Cause";
4import * as Clock from "effect/Clock";
5import * as Context from "effect/Context";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as Layer from "effect/Layer";
9import * as Redacted from "effect/Redacted";
10import * as Schema from "effect/Schema";
11import * as Semaphore from "effect/Semaphore";
12import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
13​
14import * as Option from "effect/Option";
15import * as Result from "effect/Result";
16​
17import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
18import * as GitHubCredentials from "./GitHubCredentials.ts";
19import * as GitHubQuota from "./GitHubQuota.ts";
20​
21const DEFAULT_TIMEOUT = Duration.seconds(30);
22/** GitHub's secondary limits penalize concurrent bursts. */
23const CONCURRENCY = 8;
24const REQUEST_HEADERS = { "x-github-api-version": "2022-11-28", "user-agent": "t3code" };
25​
26/** Pin requests to this host's credential across account switches. Keep it out of RPCs/cache keys. */
27export const PinnedGitHubCredential = Context.Reference<{
28 readonly host: string;
29 readonly token: Redacted.Redacted<string>;
30 readonly credentialFingerprint: string;
31 readonly source?: GitHubCredentials.GitHubCredentialSource;
32} | null>("@t3tools/source-control-github/server/GitHubRequestPolicy/PinnedGitHubCredential", {
33 defaultValue: () => null,
34});
35​
36export class GitHubApiRequestError extends Schema.TaggedError<GitHubApiRequestError>()(
37 "GitHubApiRequestError",
38 { host: Schema.String, operation: Schema.String, cause: Schema.Defect() },
39) {
40 override get message(): string {
41 return `Could not reach GitHub at ${this.host}.`;
42 }
44​
45export class GitHubApiAuthenticationError extends Schema.TaggedError<GitHubApiAuthenticationError>()(
46 "GitHubApiAuthenticationError",
47 { host: Schema.String, operation: Schema.String },
48) {
49 override get message(): string {
50 return `GitHub refused the credential for ${this.host}. Run \`gh auth login --hostname ${this.host}\` and retry.`;
51 }
53​
54export class GitHubApiRateLimitError extends Schema.TaggedError<GitHubApiRateLimitError>()(
55 "GitHubApiRateLimitError",
56 {
57 host: Schema.String,
58 operation: Schema.String,
59 retryAt: Schema.optionalKey(Schema.Finite),
60 },
61) {
62 override get message(): string {
63 return "GitHub API rate limit exceeded.";
64 }
66​
67export class GitHubApiNotFoundError extends Schema.TaggedError<GitHubApiNotFoundError>()(
68 "GitHubApiNotFoundError",
69 {
70 host: Schema.String,
71 operation: Schema.String,
72 /** The source of the credential the refused request carried, when known. */
73 credential: Schema.optionalKey(GitHubCredentials.GitHubCredentialSource),
74 },
75) {
76 override get message(): string {
77 return "GitHub could not find the requested resource, or the credential cannot see it.";
78 }
80​
81export class GitHubApiResponseError extends Schema.TaggedError<GitHubApiResponseError>()(
82 "GitHubApiResponseError",
83 {
84 host: Schema.String,
85 operation: Schema.String,
86 status: Schema.Int,
87 githubErrors: Schema.optionalKey(Schema.Array(Schema.String)),
88 githubErrorTypes: Schema.optionalKey(Schema.Array(Schema.NullOr(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 | GitHubAppSignIn.GitHubAppSessionError
101 | GitHubApiRequestError
102 | GitHubApiAuthenticationError
103 | GitHubApiRateLimitError
104 | GitHubApiNotFoundError
105 | GitHubApiResponseError
106 | SourceControlRateLimit.SourceControlRateLimitPausedError;
107​
108export function gitHubApiUrls(host: string): { readonly rest: string; readonly graphql: string } {
109 const normalized = normalizeHost(host);
110 if (normalized === "github.com") {
111 return { rest: "https://api.github.com", graphql: "https://api.github.com/graphql" };
112 }
113 if (normalized.endsWith(".ghe.com")) {
114 return {
115 rest: `https://api.${normalized}`,
116 graphql: `https://api.${normalized}/graphql`,
117 };
118 }
119 return { rest: `https://${normalized}/api/v3`, graphql: `https://${normalized}/api/graphql` };
121​
122function rateLimitAttributes(
123 headers: Readonly<Record<string, string | undefined>>,
124): Record<string, number | string> {
125 const attributes: Record<string, number | string> = {};
126 for (const [header, name] of [
127 ["x-ratelimit-limit", "github.ratelimit.limit"],
128 ["x-ratelimit-remaining", "github.ratelimit.remaining"],
129 ["x-ratelimit-used", "github.ratelimit.used"],
130 ["x-ratelimit-reset", "github.ratelimit.reset"],
131 ] as const) {
132 const value = Number(headers[header]);
133 if (headers[header] !== undefined && Number.isFinite(value)) attributes[name] = value;
134 }
135 const resource = headers["x-ratelimit-resource"];
136 if (resource !== undefined) attributes["github.ratelimit.resource"] = resource;
137 return attributes;
139​
140function retryAtFrom(
141 headers: Readonly<Record<string, string | undefined>>,
142 now: number,
143): number | undefined {
144 const fromRetryAfter = SourceControlRateLimit.retryAtFromHeader(headers["retry-after"], now);
145 if (fromRetryAfter !== undefined) return fromRetryAfter;
146 const reset = Number(headers["x-ratelimit-reset"]) * 1_000;
147 return Number.isFinite(reset) && reset > now ? reset : undefined;
149​
150/**
151 * HTTP 200 GraphQL rate limits use RATE_LIMITED or untyped errors with quota headers. A 403 is a
152 * limit only when its quota, body or GraphQL errors name one (older hosts say "abuse detection
153 * mechanism"): a proxy in front of GitHub Enterprise can refuse with `Retry-After` alone.
154 */
155export function isRateLimited(input: {
156 readonly status: number;
157 readonly headers: Readonly<Record<string, string | undefined>>;
158 readonly graphqlErrors?: ReadonlyArray<{ readonly type?: unknown; readonly message?: unknown }>;
159 readonly body?: string;
160}): boolean {
161 const { status, headers, graphqlErrors: errors } = input;
162 return (
163 status === 429 ||
164 (errors !== undefined &&
165 (headers["x-ratelimit-remaining"] === "0" ||
166 errors.some(
167 (error) =>
168 error.type === "RATE_LIMITED" ||
169 (typeof error.message === "string" &&
170 /rate limit (already )?exceeded/i.test(error.message)),
171 ))) ||
172 (status === 403 &&
173 (headers["x-ratelimit-remaining"] === "0" ||
174 namesLimit(input.body) ||
175 (errors ?? []).some((error) => namesLimit(error.message))))
176 );
178​
179function namesLimit(text: unknown): boolean {
180 return typeof text === "string" && /rate limit|abuse detection mechanism/i.test(text);
182​
183export type GitHubAnswer<A> = {
184 readonly status: number | undefined;
185 readonly headers: Readonly<Record<string, string | undefined>>;
186} & (
187 | {
188 readonly _tag: "Ok";
189 readonly value: A;
190 /** GitHub left part of the answer out as not found or forbidden for this credential. */
191 readonly withheld?: boolean;
192 }
193 | { readonly _tag: "RateLimited" | "Unauthorized" | "NotFound" }
194 | { readonly _tag: "Failed"; readonly messages?: ReadonlyArray<string> | undefined }
195);
196​
197export interface GitHubRequest {
198 readonly host: string;
199 /** The checkout the request is for; a directory-aware `gh` picks its login from here. */
200 readonly cwd?: string | undefined;
201 readonly operation: string;
202 /** The quota the request spends: `core` for REST, `graphql` for GraphQL. */
203 readonly resource: string;
204 readonly allowReserve: boolean;
205 /** Covers sending and reading the answer. Defaults to 30 seconds. */
206 readonly timeout?: Duration.Input | undefined;
208​
209/** REST/GraphQL share credentials, slots, quota reserves and host-wide pauses. */
210export class GitHubRequestPolicy extends Context.Service<
211 GitHubRequestPolicy,
212 {
213 /**
214 * send receives auth/version headers and the source of the credential they carry; its
215 * failures pass through unchanged.
216 */
217 readonly request: <A, E, R>(
218 input: GitHubRequest,
219 send: (
220 headers: Readonly<Record<string, string>>,
221 source: GitHubCredentials.GitHubCredentialSource | undefined,
222 ) => Effect.Effect<GitHubAnswer<A>, E, R>,
223 ) => Effect.Effect<A, E | GitHubApiError, R>;
224 /**
225 * The credential requests to `host` use: a token saved in Settings, else the app sign-in,
226 * else `GH_TOKEN` or `gh` as run in checkout `cwd`. `personal` skips the app, for
227 * repositories it cannot reach.
228 */
229 readonly credential: (
230 host: string,
231 options?: { readonly personal?: boolean; readonly cwd?: string | undefined },
232 ) => Effect.Effect<GitHubHeldCredential, GitHubApiError>;
233 /** The app sign-in's own credential, whatever else outranks it; none when not signed in. */
234 readonly appCredential: (
235 host: string,
236 ) => Effect.Effect<Option.Option<GitHubHeldCredential>, GitHubAppSignIn.GitHubAppSessionError>;
237 }
238>()("@t3tools/source-control-github/server/GitHubRequestPolicy") {}
239​
240export interface GitHubHeldCredential {
241 readonly source?: GitHubCredentials.GitHubCredentialSource;
242 readonly token: Redacted.Redacted<string>;
243 readonly fingerprint: string;
245​
246interface ChosenCredential extends GitHubHeldCredential {
247 readonly fromApp: boolean;
249​
250/**
251 * The app reaches only repositories where it is installed. A not-found or "not accessible by
252 * integration" answer to its token is worth one more try with the user's own credential.
253 */
254function refusedToApp<A>(answer: GitHubAnswer<A>): boolean {
255 switch (answer._tag) {
256 case "NotFound":
257 return true;
258 case "Ok":
259 return answer.withheld === true;
260 case "Failed":
261 return (
262 answer.status === 403 &&
263 (answer.messages ?? []).some((message) => /not accessible by integration/i.test(message))
264 );
265 default:
266 return false;
267 }
269​
270/** @public */
271export const make = Effect.gen(function* () {
272 const credentials = yield* GitHubCredentials.GitHubCredentials;
273 const appSignIn = yield* GitHubAppSignIn.GitHubAppSignIn;
274 const quota = yield* GitHubQuota.GitHubQuota;
275 const limits = yield* SourceControlRateLimit.SourceControlRateLimit;
276 const slots = yield* Semaphore.make(CONCURRENCY);
277​
278 const personalCredential = (host: string, cwd: string | undefined) =>
279 credentials.get(host, cwd).pipe(
280 Effect.map((held): ChosenCredential => ({
281 token: held.token,
282 fingerprint: held.fingerprint,
283 source: held.source,
284 fromApp: false,
285 })),
286 );
287​
288 const appCredential: GitHubRequestPolicy["Service"]["appCredential"] = Effect.fn(
289 "GitHubRest.appCredential",
290 )(function* (host) {
291 const token = yield* appSignIn.token(normalizeHost(host));
292 if (Option.isNone(token)) return Option.none();
293 return Option.some({
294 source: "app" as const,
295 token: Redacted.make(token.value),
296 fingerprint: yield* credentials.fingerprint(normalizeHost(host), token.value),
297 });
298 });
299​
300 const choose = Effect.fn("GitHubRest.credential")(function* (
301 host: string,
302 personal: boolean,
303 cwd: string | undefined,
304 ) {
305 const pinned = yield* PinnedGitHubCredential;
306 if (pinned !== null) {
307 if (pinned.host !== host) {
308 return yield* new GitHubApiAuthenticationError({ host, operation: "credential" });
309 }
310 return {
311 token: pinned.token,
312 fingerprint: pinned.credentialFingerprint,
313 ...(pinned.source === undefined ? {} : { source: pinned.source }),
314 fromApp: false,
315 } satisfies ChosenCredential;
316 }
317 const saved = yield* credentials.saved(host);
318 if (Option.isSome(saved)) {
319 return {
320 token: saved.value.token,
321 fingerprint: saved.value.fingerprint,
322 source: saved.value.source,
323 fromApp: false,
324 };
325 }
326 if (personal) return yield* personalCredential(host, cwd);
327 const app = yield* Effect.result(appCredential(host));
328 // An app session that cannot refresh right now steps aside for the user's own credential.
329 if (Result.isFailure(app)) {
330 return yield* personalCredential(host, cwd).pipe(Effect.mapError(() => app.failure));
331 }
332 if (Option.isNone(app.success)) return yield* personalCredential(host, cwd);
333 return { ...app.success.value, fromApp: true } satisfies ChosenCredential;
334 });
335​
336 const credential: GitHubRequestPolicy["Service"]["credential"] = (host, options) =>
337 choose(normalizeHost(host), options?.personal === true, options?.cwd).pipe(
338 Effect.map(({ token, fingerprint, source }) => ({
339 token,
340 fingerprint,
341 ...(source === undefined ? {} : { source }),
342 })),
343 );
344​
345 // The REST/GraphQL transport span owns request and quota metadata.
346 const request: GitHubRequestPolicy["Service"]["request"] = Effect.fnUntraced(function* <A, E, R>(
347 input: GitHubRequest,
348 send: (
349 headers: Readonly<Record<string, string>>,
350 source: GitHubCredentials.GitHubCredentialSource | undefined,
351 ) => Effect.Effect<GitHubAnswer<A>, E, R>,
352 ) {
353 const host = normalizeHost(input.host);
354 const context = { host, operation: input.operation };
355 yield* Effect.annotateCurrentSpan({
356 "github.host": host,
357 "github.operation": input.operation,
358 });
359 const scope = yield* SourceControlRateLimit.CredentialScope;
360 // A refusal pauses the whole host, whichever quota it spent: the key PullRequestService
361 // records its own backoff under.
362 const key = { provider: SourceControlProviderKind.make("github"), host };
363​
364 // Settlement annotates the request span with status and rate-limit attributes.
365 const settle = Effect.fnUntraced(function* (
366 lease: number,
367 answer: GitHubAnswer<A>,
368 held: ChosenCredential,
369 ) {
370 yield* quota.observe(host, answer.headers);
371 yield* Effect.annotateCurrentSpan({
372 ...(answer.status === undefined ? {} : { "http.response.status_code": answer.status }),
373 ...rateLimitAttributes(answer.headers),
374 });
375 switch (answer._tag) {
376 case "Ok":
377 yield* limits.recordSuccess({ ...key, lease });
378 return answer.value;
379 case "RateLimited": {
380 const retryAt = retryAtFrom(answer.headers, yield* Clock.currentTimeMillis);
381 yield* limits.recordRateLimit({ ...key, lease, retryAt });
382 yield* Effect.annotateCurrentSpan({
383 "github.rate_limited": true,
384 ...(retryAt === undefined ? {} : { "github.retry_at": retryAt }),
385 });
386 return yield* new GitHubApiRateLimitError({
387 ...context,
388 ...(retryAt === undefined ? {} : { retryAt }),
389 });
390 }
391 case "Unauthorized":
392 // The source may hold a newer token than the one that was refused.
393 yield* appSignIn.invalidate(host, Redacted.value(held.token));
394 yield* credentials.invalidate(host, input.cwd);
395 return yield* new GitHubApiAuthenticationError(context);
396 case "NotFound":
397 return yield* new GitHubApiNotFoundError({
398 ...context,
399 ...(held.source === undefined ? {} : { credential: held.source }),
400 });
401 case "Failed":
402 return yield* new GitHubApiResponseError({
403 ...context,
404 status: answer.status ?? 200,
405 ...(answer.messages === undefined ? {} : { githubErrors: answer.messages }),
406 });
407 }
408 });
409​
410 /** One send under `held`; `Retry` hands an app-refused request to the user's credential. */
411 const attempt = (held: ChosenCredential) =>
412 slots
413 .withPermit(
414 Effect.gen(function* () {
415 const lease = yield* quota
416 .admit(host, input.resource, { allowReserve: input.allowReserve })
417 .pipe(
418 Effect.andThen(
419 limits.check(key, input.allowReserve ? { allowPaused: true } : undefined),
420 ),
421 Effect.tapError((paused) =>
422 Effect.annotateCurrentSpan({
423 "github.paused": true,
424 "github.retry_at": paused.retryAt,
425 }),
426 ),
427 );
428 // One deadline covers the headers and the body: a host that answers headers and then
429 // stalls must not hold a shared slot for undici's own five-minute body timeout.
430 const answer = yield* send(
431 { ...REQUEST_HEADERS, authorization: `Bearer ${Redacted.value(held.token)}` },
432 held.source,
433 ).pipe(
434 Effect.timeoutOrElse({
435 duration: input.timeout ?? DEFAULT_TIMEOUT,
436 orElse: () =>
437 Effect.fail(
438 new GitHubApiRequestError({ ...context, cause: new Cause.TimeoutError() }),
439 ),
440 }),
441 );
442 if (held.fromApp && refusedToApp(answer)) {
443 const personal = yield* Effect.option(personalCredential(host, input.cwd));
444 if (Option.isSome(personal)) {
445 yield* quota.observe(host, answer.headers);
446 yield* limits.recordSuccess({ ...key, lease });
447 yield* Effect.annotateCurrentSpan({ "github.app_refused": true });
448 return { _tag: "Retry", with: personal.value } as const;
449 }
450 }
451 return { _tag: "Done", value: yield* settle(lease, answer, held) } as const;
452 }),
453 )
454 // The rate-limit scope follows the credential, so a pause on one account never blocks another.
455 .pipe(
456 Effect.provideService(SourceControlRateLimit.CredentialScope, scope || held.fingerprint),
457 );
458​
459 // Only an app credential is handed on, so this runs at most twice.
460 let held = yield* choose(host, false, input.cwd);
461 while (true) {
462 const outcome = yield* attempt(held);
463 if (outcome._tag === "Done") return outcome.value;
464 held = outcome.with;
465 }
466 });
467​
468 return GitHubRequestPolicy.of({ request, credential, appCredential });
469});
470​
471export const layer = Layer.effect(GitHubRequestPolicy, make);