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