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