Open History to see the last commit
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 }
43}
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 }
52}
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 }
65}
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 }
79}
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 }
96}
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` };
120}
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;
138}
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;
148}
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 );
177}
178
179function namesLimit(text: unknown): boolean {
180 return typeof text === "string" && /rate limit|abuse detection mechanism/i.test(text);
181}
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 readonly operation: string;
200 /** The quota the request spends: `core` for REST, `graphql` for GraphQL. */
201 readonly resource: string;
202 readonly allowReserve: boolean;
203 /** Covers sending and reading the answer. Defaults to 30 seconds. */
204 readonly timeout?: Duration.Input | undefined;
205}
206
207/** REST/GraphQL share credentials, slots, quota reserves and host-wide pauses. */
208export class GitHubRequestPolicy extends Context.Service<
209 GitHubRequestPolicy,
210 {
211 /**
212 * send receives auth/version headers and the source of the credential they carry; its
213 * failures pass through unchanged.
214 */
215 readonly request: <A, E, R>(
216 input: GitHubRequest,
217 send: (
218 headers: Readonly<Record<string, string>>,
219 source: GitHubCredentials.GitHubCredentialSource | undefined,
220 ) => Effect.Effect<GitHubAnswer<A>, E, R>,
221 ) => Effect.Effect<A, E | GitHubApiError, R>;
222 /**
223 * The credential requests to `host` use: a token saved in Settings, else the app sign-in,
224 * else `GH_TOKEN` or `gh`. `personal` skips the app, for repositories it cannot reach.
225 */
226 readonly credential: (
227 host: string,
228 options?: { readonly personal?: boolean },
229 ) => Effect.Effect<GitHubHeldCredential, GitHubApiError>;
230 /** The app sign-in's own credential, whatever else outranks it; none when not signed in. */
231 readonly appCredential: (
232 host: string,
233 ) => Effect.Effect<Option.Option<GitHubHeldCredential>, GitHubAppSignIn.GitHubAppSessionError>;
234 }
235>()("@t3tools/source-control-github/server/GitHubRequestPolicy") {}
236
237export interface GitHubHeldCredential {
238 readonly source?: GitHubCredentials.GitHubCredentialSource;
239 readonly token: Redacted.Redacted<string>;
240 readonly fingerprint: string;
241}
242
243interface ChosenCredential extends GitHubHeldCredential {
244 readonly fromApp: boolean;
245}
246
247/**
248 * The app reaches only repositories where it is installed. A not-found or "not accessible by
249 * integration" answer to its token is worth one more try with the user's own credential.
250 */
251function refusedToApp<A>(answer: GitHubAnswer<A>): boolean {
252 switch (answer._tag) {
253 case "NotFound":
254 return true;
255 case "Ok":
256 return answer.withheld === true;
257 case "Failed":
258 return (
259 answer.status === 403 &&
260 (answer.messages ?? []).some((message) => /not accessible by integration/i.test(message))
261 );
262 default:
263 return false;
264 }
265}
266
267/** @public */
268export const make = Effect.gen(function* () {
269 const credentials = yield* GitHubCredentials.GitHubCredentials;
270 const appSignIn = yield* GitHubAppSignIn.GitHubAppSignIn;
271 const quota = yield* GitHubQuota.GitHubQuota;
272 const limits = yield* SourceControlRateLimit.SourceControlRateLimit;
273 const slots = yield* Semaphore.make(CONCURRENCY);
274
275 const personalCredential = (host: string) =>
276 credentials.get(host).pipe(
277 Effect.map((held): ChosenCredential => ({
278 token: held.token,
279 fingerprint: held.fingerprint,
280 source: held.source,
281 fromApp: false,
282 })),
283 );
284
285 const appCredential: GitHubRequestPolicy["Service"]["appCredential"] = Effect.fn(
286 "GitHubRest.appCredential",
287 )(function* (host) {
288 const token = yield* appSignIn.token(normalizeHost(host));
289 if (Option.isNone(token)) return Option.none();
290 return Option.some({
291 source: "app" as const,
292 token: Redacted.make(token.value),
293 fingerprint: yield* credentials.fingerprint(normalizeHost(host), token.value),
294 });
295 });
296
297 const choose = Effect.fn("GitHubRest.credential")(function* (host: string, personal: boolean) {
298 const pinned = yield* PinnedGitHubCredential;
299 if (pinned !== null) {
300 if (pinned.host !== host) {
301 return yield* new GitHubApiAuthenticationError({ host, operation: "credential" });
302 }
303 return {
304 token: pinned.token,
305 fingerprint: pinned.credentialFingerprint,
306 ...(pinned.source === undefined ? {} : { source: pinned.source }),
307 fromApp: false,
308 } satisfies ChosenCredential;
309 }
310 const saved = yield* credentials.saved(host);
311 if (Option.isSome(saved)) {
312 return {
313 token: saved.value.token,
314 fingerprint: saved.value.fingerprint,
315 source: saved.value.source,
316 fromApp: false,
317 };
318 }
319 if (personal) return yield* personalCredential(host);
320 const app = yield* Effect.result(appCredential(host));
321 // An app session that cannot refresh right now steps aside for the user's own credential.
322 if (Result.isFailure(app)) {
323 return yield* personalCredential(host).pipe(Effect.mapError(() => app.failure));
324 }
325 if (Option.isNone(app.success)) return yield* personalCredential(host);
326 return { ...app.success.value, fromApp: true } satisfies ChosenCredential;
327 });
328
329 const credential: GitHubRequestPolicy["Service"]["credential"] = (host, options) =>
330 choose(normalizeHost(host), options?.personal === true).pipe(
331 Effect.map(({ token, fingerprint, source }) => ({
332 token,
333 fingerprint,
334 ...(source === undefined ? {} : { source }),
335 })),
336 );
337
338 // The REST/GraphQL transport span owns request and quota metadata.
339 const request: GitHubRequestPolicy["Service"]["request"] = Effect.fnUntraced(function* <A, E, R>(
340 input: GitHubRequest,
341 send: (
342 headers: Readonly<Record<string, string>>,
343 source: GitHubCredentials.GitHubCredentialSource | undefined,
344 ) => Effect.Effect<GitHubAnswer<A>, E, R>,
345 ) {
346 const host = normalizeHost(input.host);
347 const context = { host, operation: input.operation };
348 yield* Effect.annotateCurrentSpan({
349 "github.host": host,
350 "github.operation": input.operation,
351 });
352 const scope = yield* SourceControlRateLimit.CredentialScope;
353 // A refusal pauses the whole host, whichever quota it spent: the key PullRequestService
354 // records its own backoff under.
355 const key = { provider: SourceControlProviderKind.make("github"), host };
356
357 // Settlement annotates the request span with status and rate-limit attributes.
358 const settle = Effect.fnUntraced(function* (
359 lease: number,
360 answer: GitHubAnswer<A>,
361 held: ChosenCredential,
362 ) {
363 yield* quota.observe(host, answer.headers);
364 yield* Effect.annotateCurrentSpan({
365 ...(answer.status === undefined ? {} : { "http.response.status_code": answer.status }),
366 ...rateLimitAttributes(answer.headers),
367 });
368 switch (answer._tag) {
369 case "Ok":
370 yield* limits.recordSuccess({ ...key, lease });
371 return answer.value;
372 case "RateLimited": {
373 const retryAt = retryAtFrom(answer.headers, yield* Clock.currentTimeMillis);
374 yield* limits.recordRateLimit({ ...key, lease, retryAt });
375 yield* Effect.annotateCurrentSpan({
376 "github.rate_limited": true,
377 ...(retryAt === undefined ? {} : { "github.retry_at": retryAt }),
378 });
379 return yield* new GitHubApiRateLimitError({
380 ...context,
381 ...(retryAt === undefined ? {} : { retryAt }),
382 });
383 }
384 case "Unauthorized":
385 // The source may hold a newer token than the one that was refused.
386 yield* appSignIn.invalidate(host, Redacted.value(held.token));
387 yield* credentials.invalidate(host);
388 return yield* new GitHubApiAuthenticationError(context);
389 case "NotFound":
390 return yield* new GitHubApiNotFoundError({
391 ...context,
392 ...(held.source === undefined ? {} : { credential: held.source }),
393 });
394 case "Failed":
395 return yield* new GitHubApiResponseError({
396 ...context,
397 status: answer.status ?? 200,
398 ...(answer.messages === undefined ? {} : { githubErrors: answer.messages }),
399 });
400 }
401 });
402
403 /** One send under `held`; `Retry` hands an app-refused request to the user's credential. */
404 const attempt = (held: ChosenCredential) =>
405 slots
406 .withPermit(
407 Effect.gen(function* () {
408 const lease = yield* quota
409 .admit(host, input.resource, { allowReserve: input.allowReserve })
410 .pipe(
411 Effect.andThen(
412 limits.check(key, input.allowReserve ? { allowPaused: true } : undefined),
413 ),
414 Effect.tapError((paused) =>
415 Effect.annotateCurrentSpan({
416 "github.paused": true,
417 "github.retry_at": paused.retryAt,
418 }),
419 ),
420 );
421 // One deadline covers the headers and the body: a host that answers headers and then
422 // stalls must not hold a shared slot for undici's own five-minute body timeout.
423 const answer = yield* send(
424 { ...REQUEST_HEADERS, authorization: `Bearer ${Redacted.value(held.token)}` },
425 held.source,
426 ).pipe(
427 Effect.timeoutOrElse({
428 duration: input.timeout ?? DEFAULT_TIMEOUT,
429 orElse: () =>
430 Effect.fail(
431 new GitHubApiRequestError({ ...context, cause: new Cause.TimeoutError() }),
432 ),
433 }),
434 );
435 if (held.fromApp && refusedToApp(answer)) {
436 const personal = yield* Effect.option(personalCredential(host));
437 if (Option.isSome(personal)) {
438 yield* quota.observe(host, answer.headers);
439 yield* limits.recordSuccess({ ...key, lease });
440 yield* Effect.annotateCurrentSpan({ "github.app_refused": true });
441 return { _tag: "Retry", with: personal.value } as const;
442 }
443 }
444 return { _tag: "Done", value: yield* settle(lease, answer, held) } as const;
445 }),
446 )
447 // The rate-limit scope follows the credential, so a pause on one account never blocks another.
448 .pipe(
449 Effect.provideService(SourceControlRateLimit.CredentialScope, scope || held.fingerprint),
450 );
451
452 // Only an app credential is handed on, so this runs at most twice.
453 let held = yield* choose(host, false);
454 while (true) {
455 const outcome = yield* attempt(held);
456 if (outcome._tag === "Done") return outcome.value;
457 held = outcome.with;
458 }
459 });
460
461 return GitHubRequestPolicy.of({ request, credential, appCredential });
462});
463
464export const layer = Layer.effect(GitHubRequestPolicy, make);