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

GitHubRequestPolicy.ts

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