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

GitHubRequestPolicy.ts

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