Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import * as Cause from "effect/Cause";
3import * as Clock from "effect/Clock";
4import * as Context from "effect/Context";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Layer from "effect/Layer";
8import * as Redacted from "effect/Redacted";
9import * as Schema from "effect/Schema";
10import * as Semaphore from "effect/Semaphore";
11import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
12
13import * as GitHubCredentials from "./GitHubCredentials.ts";
14import * as GitHubQuota from "./GitHubQuota.ts";
15
16const DEFAULT_TIMEOUT = Duration.seconds(30);
17/** Polite to GitHub's secondary limits, which punish bursts of concurrent requests. */
18const CONCURRENCY = 8;
19/** The headers every GitHub request carries besides its token. */
20const REQUEST_HEADERS = { "x-github-api-version": "2022-11-28", "user-agent": "t3code" };
21
22/**
23 * A credential already verified for one host. Every request made under it must target that
24 * host, so a page cannot read one account's data with another's token mid-flight. Server-local:
25 * never put its value in RPC payloads or cache keys.
26 */
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 }
42}
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 }
51}
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 }
64}
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 }
73}
74
75/**
76 * GitHub answered with a failure that is none of the above. `githubErrors` carries GitHub's own
77 * error messages, from a GraphQL `errors` list or a REST `message`/`errors` body: they name the
78 * field and the reason ("A pull request already exists for acme:feature"), never a token.
79 */
80export class GitHubApiResponseError extends Schema.TaggedError<GitHubApiResponseError>()(
81 "GitHubApiResponseError",
82 {
83 host: Schema.String,
84 operation: Schema.String,
85 status: Schema.Int,
86 githubErrors: Schema.optionalKey(Schema.Array(Schema.String)),
87 },
88) {
89 override get message(): string {
90 return this.githubErrors !== undefined && this.githubErrors.length > 0
91 ? `GitHub returned an error: ${this.githubErrors.join("; ")}`
92 : `GitHub returned HTTP ${this.status}.`;
93 }
94}
95
96export type GitHubApiError =
97 | GitHubCredentials.GitHubCredentialUnavailableError
98 | GitHubApiRequestError
99 | GitHubApiAuthenticationError
100 | GitHubApiRateLimitError
101 | GitHubApiNotFoundError
102 | GitHubApiResponseError
103 | SourceControlRateLimit.SourceControlRateLimitPausedError;
104
105export function normalizeHost(host: string): string {
106 return host.trim().toLowerCase();
107}
108
109/** Pins one credential before batching, so checkouts using the same account share a request. */
110export const withCredential =
111 (api: GitHubRequestPolicy["Service"], host: string) =>
112 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
113 Effect.gen(function* () {
114 const normalized = normalizeHost(host);
115 const pinned = yield* PinnedGitHubCredential;
116 const credential =
117 pinned?.host === normalized
118 ? pinned
119 : yield* api.credential(normalized).pipe(
120 Effect.map(({ token, fingerprint }) => ({
121 host: normalized,
122 token,
123 credentialFingerprint: fingerprint,
124 })),
125 );
126 return yield* effect.pipe(
127 Effect.provideService(PinnedGitHubCredential, credential),
128 Effect.provideService(
129 SourceControlRateLimit.CredentialScope,
130 credential.credentialFingerprint,
131 ),
132 );
133 });
134
135/**
136 * Where the API for a host lives. github.com and GHE.com data residency serve it from an `api.`
137 * subdomain; GitHub Enterprise Server serves it under `/api` on the instance itself.
138 */
139export function gitHubApiUrls(host: string): { readonly rest: string; readonly graphql: string } {
140 const normalized = normalizeHost(host);
141 if (normalized === "github.com") {
142 return { rest: "https://api.github.com", graphql: "https://api.github.com/graphql" };
143 }
144 if (normalized.endsWith(".ghe.com")) {
145 return {
146 rest: `https://api.${normalized}`,
147 graphql: `https://api.${normalized}/graphql`,
148 };
149 }
150 return { rest: `https://${normalized}/api/v3`, graphql: `https://${normalized}/api/graphql` };
151}
152
153/** The numeric rate-limit headers GitHub sends, as span attributes. */
154function rateLimitAttributes(
155 headers: Readonly<Record<string, string | undefined>>,
156): Record<string, number | string> {
157 const attributes: Record<string, number | string> = {};
158 for (const [header, name] of [
159 ["x-ratelimit-limit", "github.ratelimit.limit"],
160 ["x-ratelimit-remaining", "github.ratelimit.remaining"],
161 ["x-ratelimit-used", "github.ratelimit.used"],
162 ["x-ratelimit-reset", "github.ratelimit.reset"],
163 ] as const) {
164 const value = Number(headers[header]);
165 if (headers[header] !== undefined && Number.isFinite(value)) attributes[name] = value;
166 }
167 const resource = headers["x-ratelimit-resource"];
168 if (resource !== undefined) attributes["github.ratelimit.resource"] = resource;
169 return attributes;
170}
171
172/** The pause GitHub asked for, from `retry-after` or the primary limit's reset. */
173function retryAtFrom(
174 headers: Readonly<Record<string, string | undefined>>,
175 now: number,
176): number | undefined {
177 const fromRetryAfter = SourceControlRateLimit.retryAtFromHeader(headers["retry-after"], now);
178 if (fromRetryAfter !== undefined) return fromRetryAfter;
179 const reset = Number(headers["x-ratelimit-reset"]) * 1_000;
180 return Number.isFinite(reset) && reset > now ? reset : undefined;
181}
182
183/**
184 * Whether GitHub refused a request for its rate limit. A GraphQL answer can say so with HTTP 200:
185 * a `RATE_LIMITED` error, or an exhausted quota that answers an untyped "API rate limit already
186 * exceeded" error, which the headers confirm.
187 */
188export function isRateLimited(input: {
189 readonly status: number;
190 readonly headers: Readonly<Record<string, string | undefined>>;
191 /** The GraphQL `errors` list, when the answer is a GraphQL one and has any. */
192 readonly graphqlErrors?: ReadonlyArray<{ readonly type?: unknown; readonly message?: unknown }>;
193 readonly body?: string;
194}): boolean {
195 const { status, headers, graphqlErrors: errors } = input;
196 return (
197 status === 429 ||
198 (errors !== undefined &&
199 (headers["x-ratelimit-remaining"] === "0" ||
200 errors.some(
201 (error) =>
202 error.type === "RATE_LIMITED" ||
203 (typeof error.message === "string" &&
204 /rate limit (already )?exceeded/i.test(error.message)),
205 ))) ||
206 (status === 403 &&
207 (headers["x-ratelimit-remaining"] === "0" ||
208 headers["retry-after"] !== undefined ||
209 /rate limit/i.test(input.body ?? "")))
210 );
211}
212
213/**
214 * What one GitHub answer means, as the transport that read it decided: `Ok` carries what the
215 * request returns; every other verdict fails with the `GitHubApi*Error` that says why.
216 */
217export type GitHubAnswer<A> = {
218 /** Unset when the transport reported none. */
219 readonly status: number | undefined;
220 readonly headers: Readonly<Record<string, string | undefined>>;
221} & (
222 | { readonly _tag: "Ok"; readonly value: A }
223 | { readonly _tag: "RateLimited" | "Unauthorized" | "NotFound" }
224 | { readonly _tag: "Failed"; readonly messages?: ReadonlyArray<string> | undefined }
225);
226
227export interface GitHubRequest {
228 readonly host: string;
229 readonly operation: string;
230 /** The quota the request spends: `core` for REST, `graphql` for GraphQL. */
231 readonly resource: string;
232 readonly allowReserve: boolean;
233 /** Covers sending and reading the answer. Defaults to 30 seconds. */
234 readonly timeout?: Duration.Input | undefined;
235}
236
237/**
238 * What every GitHub request goes through, REST and GraphQL alike: the host's credential, one
239 * shared pool of request slots, the quota reserve and the host-wide pause before it is sent, and
240 * what GitHub's answer says about them after. Each transport only sends and reads its answer.
241 */
242export class GitHubRequestPolicy extends Context.Service<
243 GitHubRequestPolicy,
244 {
245 /**
246 * Sends one request. `send` receives the headers it must carry (the token and GitHub's API
247 * version) and reports the answer; a failure of its own passes through untouched.
248 */
249 readonly request: <A, E, R>(
250 input: GitHubRequest,
251 send: (headers: Readonly<Record<string, string>>) => Effect.Effect<GitHubAnswer<A>, E, R>,
252 ) => Effect.Effect<A, E | GitHubApiError, R>;
253 /** The credential a request to `host` would carry right now. */
254 readonly credential: (
255 host: string,
256 ) => Effect.Effect<
257 { readonly token: Redacted.Redacted<string>; readonly fingerprint: string },
258 GitHubApiError
259 >;
260 }
261>()("@t3tools/source-control-github/server/GitHubRequestPolicy") {}
262
263/** @public Service construction is part of the canonical Effect module API. */
264export const make = Effect.gen(function* () {
265 const credentials = yield* GitHubCredentials.GitHubCredentials;
266 const quota = yield* GitHubQuota.GitHubQuota;
267 const limits = yield* SourceControlRateLimit.SourceControlRateLimit;
268 const slots = yield* Semaphore.make(CONCURRENCY);
269
270 const credential: GitHubRequestPolicy["Service"]["credential"] = Effect.fn(
271 "GitHubRest.credential",
272 )(function* (host) {
273 const normalized = normalizeHost(host);
274 const pinned = yield* PinnedGitHubCredential;
275 if (pinned !== null) {
276 // A pinned page only ever talks to the host it verified.
277 if (pinned.host !== normalized) {
278 return yield* new GitHubApiAuthenticationError({
279 host: normalized,
280 operation: "credential",
281 });
282 }
283 return { token: pinned.token, fingerprint: pinned.credentialFingerprint };
284 }
285 const held = yield* credentials.get(normalized);
286 return { token: held.token, fingerprint: held.fingerprint };
287 });
288
289 // The REST/GraphQL transport span owns request and quota metadata.
290 const request: GitHubRequestPolicy["Service"]["request"] = Effect.fnUntraced(function* <A, E, R>(
291 input: GitHubRequest,
292 send: (headers: Readonly<Record<string, string>>) => Effect.Effect<GitHubAnswer<A>, E, R>,
293 ) {
294 const host = normalizeHost(input.host);
295 const context = { host, operation: input.operation };
296 yield* Effect.annotateCurrentSpan({
297 "github.host": host,
298 "github.operation": input.operation,
299 });
300 const { token, fingerprint } = yield* credential(host);
301 const scope = yield* SourceControlRateLimit.CredentialScope;
302 // A refusal pauses the whole host, whichever quota it spent: the key PullRequestService
303 // records its own backoff under.
304 const key = { provider: SourceControlProviderKind.make("github"), host };
305
306 // Settlement annotates the request span with status and rate-limit attributes.
307 const settle = Effect.fnUntraced(function* (lease: number, answer: GitHubAnswer<A>) {
308 yield* quota.observe(host, answer.headers);
309 yield* Effect.annotateCurrentSpan({
310 ...(answer.status === undefined ? {} : { "http.response.status_code": answer.status }),
311 ...rateLimitAttributes(answer.headers),
312 });
313 switch (answer._tag) {
314 case "Ok":
315 yield* limits.recordSuccess({ ...key, lease });
316 return answer.value;
317 case "RateLimited": {
318 const retryAt = retryAtFrom(answer.headers, yield* Clock.currentTimeMillis);
319 yield* limits.recordRateLimit({ ...key, lease, retryAt });
320 yield* Effect.annotateCurrentSpan({
321 "github.rate_limited": true,
322 ...(retryAt === undefined ? {} : { "github.retry_at": retryAt }),
323 });
324 return yield* new GitHubApiRateLimitError({
325 ...context,
326 ...(retryAt === undefined ? {} : { retryAt }),
327 });
328 }
329 case "Unauthorized":
330 // The source may hold a newer token than the one that was refused.
331 yield* credentials.invalidate(host);
332 return yield* new GitHubApiAuthenticationError(context);
333 case "NotFound":
334 return yield* new GitHubApiNotFoundError(context);
335 case "Failed":
336 return yield* new GitHubApiResponseError({
337 ...context,
338 status: answer.status ?? 200,
339 ...(answer.messages === undefined ? {} : { githubErrors: answer.messages }),
340 });
341 }
342 });
343
344 const run = Effect.gen(function* () {
345 const lease = yield* quota
346 .admit(host, input.resource, { allowReserve: input.allowReserve })
347 .pipe(
348 Effect.andThen(limits.check(key, input.allowReserve ? { allowPaused: true } : undefined)),
349 Effect.tapError((paused) =>
350 Effect.annotateCurrentSpan({
351 "github.paused": true,
352 "github.retry_at": paused.retryAt,
353 }),
354 ),
355 );
356 // One deadline covers the headers and the body: a host that answers headers and then
357 // stalls must not hold a shared slot for undici's own five-minute body timeout.
358 const answer = yield* send({
359 ...REQUEST_HEADERS,
360 authorization: `Bearer ${Redacted.value(token)}`,
361 }).pipe(
362 Effect.timeoutOrElse({
363 duration: input.timeout ?? DEFAULT_TIMEOUT,
364 orElse: () =>
365 Effect.fail(new GitHubApiRequestError({ ...context, cause: new Cause.TimeoutError() })),
366 }),
367 );
368 return yield* settle(lease, answer);
369 });
370 // The rate-limit scope follows the credential, so a pause on one account never blocks another.
371 return yield* slots
372 .withPermit(run)
373 .pipe(Effect.provideService(SourceControlRateLimit.CredentialScope, scope || fingerprint));
374 });
375
376 return GitHubRequestPolicy.of({ request, credential });
377});
378
379export const layer = Layer.effect(GitHubRequestPolicy, make);