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/**
110 * Where the API for a host lives. github.com and GHE.com data residency serve it from an `api.`
111 * subdomain; GitHub Enterprise Server serves it under `/api` on the instance itself.
112 */
113export function gitHubApiUrls(host: string): { readonly rest: string; readonly graphql: string } {
114 const normalized = normalizeHost(host);
115 if (normalized === "github.com") {
116 return { rest: "https://api.github.com", graphql: "https://api.github.com/graphql" };
117 }
118 if (normalized.endsWith(".ghe.com")) {
119 return {
120 rest: `https://api.${normalized}`,
121 graphql: `https://api.${normalized}/graphql`,
122 };
123 }
124 return { rest: `https://${normalized}/api/v3`, graphql: `https://${normalized}/api/graphql` };
125}
126
127/** The numeric rate-limit headers GitHub sends, as span attributes. */
128function rateLimitAttributes(
129 headers: Readonly<Record<string, string | undefined>>,
130): Record<string, number | string> {
131 const attributes: Record<string, number | string> = {};
132 for (const [header, name] of [
133 ["x-ratelimit-limit", "github.ratelimit.limit"],
134 ["x-ratelimit-remaining", "github.ratelimit.remaining"],
135 ["x-ratelimit-used", "github.ratelimit.used"],
136 ["x-ratelimit-reset", "github.ratelimit.reset"],
137 ] as const) {
138 const value = Number(headers[header]);
139 if (headers[header] !== undefined && Number.isFinite(value)) attributes[name] = value;
140 }
141 const resource = headers["x-ratelimit-resource"];
142 if (resource !== undefined) attributes["github.ratelimit.resource"] = resource;
143 return attributes;
144}
145
146/** The pause GitHub asked for, from `retry-after` or the primary limit's reset. */
147function retryAtFrom(
148 headers: Readonly<Record<string, string | undefined>>,
149 now: number,
150): number | undefined {
151 const fromRetryAfter = SourceControlRateLimit.retryAtFromHeader(headers["retry-after"], now);
152 if (fromRetryAfter !== undefined) return fromRetryAfter;
153 const reset = Number(headers["x-ratelimit-reset"]) * 1_000;
154 return Number.isFinite(reset) && reset > now ? reset : undefined;
155}
156
157/**
158 * Whether GitHub refused a request for its rate limit. A GraphQL answer can say so with HTTP 200:
159 * a `RATE_LIMITED` error, or an exhausted quota that answers an untyped "API rate limit already
160 * exceeded" error, which the headers confirm.
161 */
162export function isRateLimited(input: {
163 readonly status: number;
164 readonly headers: Readonly<Record<string, string | undefined>>;
165 /** The GraphQL `errors` list, when the answer is a GraphQL one and has any. */
166 readonly graphqlErrors?: ReadonlyArray<{ readonly type?: unknown; readonly message?: unknown }>;
167 readonly body?: string;
168}): boolean {
169 const { status, headers, graphqlErrors: errors } = input;
170 return (
171 status === 429 ||
172 (errors !== undefined &&
173 (headers["x-ratelimit-remaining"] === "0" ||
174 errors.some(
175 (error) =>
176 error.type === "RATE_LIMITED" ||
177 (typeof error.message === "string" &&
178 /rate limit (already )?exceeded/i.test(error.message)),
179 ))) ||
180 (status === 403 &&
181 (headers["x-ratelimit-remaining"] === "0" ||
182 headers["retry-after"] !== undefined ||
183 /rate limit/i.test(input.body ?? "")))
184 );
185}
186
187/**
188 * What one GitHub answer means, as the transport that read it decided: `Ok` carries what the
189 * request returns; every other verdict fails with the `GitHubApi*Error` that says why.
190 */
191export type GitHubAnswer<A> = {
192 /** Unset when the transport reported none. */
193 readonly status: number | undefined;
194 readonly headers: Readonly<Record<string, string | undefined>>;
195} & (
196 | { readonly _tag: "Ok"; readonly value: A }
197 | { readonly _tag: "RateLimited" | "Unauthorized" | "NotFound" }
198 | { readonly _tag: "Failed"; readonly messages?: ReadonlyArray<string> | undefined }
199);
200
201export interface GitHubRequest {
202 readonly host: string;
203 readonly operation: string;
204 /** The quota the request spends: `core` for REST, `graphql` for GraphQL. */
205 readonly resource: string;
206 readonly allowReserve: boolean;
207 /** Covers sending and reading the answer. Defaults to 30 seconds. */
208 readonly timeout?: Duration.Input | undefined;
209}
210
211/**
212 * What every GitHub request goes through, REST and GraphQL alike: the host's credential, one
213 * shared pool of request slots, the quota reserve and the host-wide pause before it is sent, and
214 * what GitHub's answer says about them after. Each transport only sends and reads its answer.
215 */
216export class GitHubRequestPolicy extends Context.Service<
217 GitHubRequestPolicy,
218 {
219 /**
220 * Sends one request. `send` receives the headers it must carry (the token and GitHub's API
221 * version) and reports the answer; a failure of its own passes through untouched.
222 */
223 readonly request: <A, E, R>(
224 input: GitHubRequest,
225 send: (headers: Readonly<Record<string, string>>) => Effect.Effect<GitHubAnswer<A>, E, R>,
226 ) => Effect.Effect<A, E | GitHubApiError, R>;
227 /** The credential a request to `host` would carry right now. */
228 readonly credential: (
229 host: string,
230 ) => Effect.Effect<
231 { readonly token: Redacted.Redacted<string>; readonly fingerprint: string },
232 GitHubApiError
233 >;
234 }
235>()("@t3tools/source-control-github/server/GitHubRequestPolicy") {}
236
237/** @public Service construction is part of the canonical Effect module API. */
238export const make = Effect.gen(function* () {
239 const credentials = yield* GitHubCredentials.GitHubCredentials;
240 const quota = yield* GitHubQuota.GitHubQuota;
241 const limits = yield* SourceControlRateLimit.SourceControlRateLimit;
242 const slots = yield* Semaphore.make(CONCURRENCY);
243
244 const credential: GitHubRequestPolicy["Service"]["credential"] = Effect.fn(
245 "GitHubRest.credential",
246 )(function* (host) {
247 const normalized = normalizeHost(host);
248 const pinned = yield* PinnedGitHubCredential;
249 if (pinned !== null) {
250 // A pinned page only ever talks to the host it verified.
251 if (pinned.host !== normalized) {
252 return yield* new GitHubApiAuthenticationError({
253 host: normalized,
254 operation: "credential",
255 });
256 }
257 return { token: pinned.token, fingerprint: pinned.credentialFingerprint };
258 }
259 const held = yield* credentials.get(normalized);
260 return { token: held.token, fingerprint: held.fingerprint };
261 });
262
263 // The REST/GraphQL transport span owns request and quota metadata.
264 const request: GitHubRequestPolicy["Service"]["request"] = Effect.fnUntraced(function* <A, E, R>(
265 input: GitHubRequest,
266 send: (headers: Readonly<Record<string, string>>) => Effect.Effect<GitHubAnswer<A>, E, R>,
267 ) {
268 const host = normalizeHost(input.host);
269 const context = { host, operation: input.operation };
270 yield* Effect.annotateCurrentSpan({
271 "github.host": host,
272 "github.operation": input.operation,
273 });
274 const { token, fingerprint } = yield* credential(host);
275 const scope = yield* SourceControlRateLimit.CredentialScope;
276 // A refusal pauses the whole host, whichever quota it spent: the key PullRequestService
277 // records its own backoff under.
278 const key = { provider: SourceControlProviderKind.make("github"), host };
279
280 // Settlement annotates the request span with status and rate-limit attributes.
281 const settle = Effect.fnUntraced(function* (lease: number, answer: GitHubAnswer<A>) {
282 yield* quota.observe(host, answer.headers);
283 yield* Effect.annotateCurrentSpan({
284 ...(answer.status === undefined ? {} : { "http.response.status_code": answer.status }),
285 ...rateLimitAttributes(answer.headers),
286 });
287 switch (answer._tag) {
288 case "Ok":
289 yield* limits.recordSuccess({ ...key, lease });
290 return answer.value;
291 case "RateLimited": {
292 const retryAt = retryAtFrom(answer.headers, yield* Clock.currentTimeMillis);
293 yield* limits.recordRateLimit({ ...key, lease, retryAt });
294 yield* Effect.annotateCurrentSpan({
295 "github.rate_limited": true,
296 ...(retryAt === undefined ? {} : { "github.retry_at": retryAt }),
297 });
298 return yield* new GitHubApiRateLimitError({
299 ...context,
300 ...(retryAt === undefined ? {} : { retryAt }),
301 });
302 }
303 case "Unauthorized":
304 // The source may hold a newer token than the one that was refused.
305 yield* credentials.invalidate(host);
306 return yield* new GitHubApiAuthenticationError(context);
307 case "NotFound":
308 return yield* new GitHubApiNotFoundError(context);
309 case "Failed":
310 return yield* new GitHubApiResponseError({
311 ...context,
312 status: answer.status ?? 200,
313 ...(answer.messages === undefined ? {} : { githubErrors: answer.messages }),
314 });
315 }
316 });
317
318 const run = Effect.gen(function* () {
319 const lease = yield* quota
320 .admit(host, input.resource, { allowReserve: input.allowReserve })
321 .pipe(
322 Effect.andThen(limits.check(key, input.allowReserve ? { allowPaused: true } : undefined)),
323 Effect.tapError((paused) =>
324 Effect.annotateCurrentSpan({
325 "github.paused": true,
326 "github.retry_at": paused.retryAt,
327 }),
328 ),
329 );
330 // One deadline covers the headers and the body: a host that answers headers and then
331 // stalls must not hold a shared slot for undici's own five-minute body timeout.
332 const answer = yield* send({
333 ...REQUEST_HEADERS,
334 authorization: `Bearer ${Redacted.value(token)}`,
335 }).pipe(
336 Effect.timeoutOrElse({
337 duration: input.timeout ?? DEFAULT_TIMEOUT,
338 orElse: () =>
339 Effect.fail(new GitHubApiRequestError({ ...context, cause: new Cause.TimeoutError() })),
340 }),
341 );
342 return yield* settle(lease, answer);
343 });
344 // The rate-limit scope follows the credential, so a pause on one account never blocks another.
345 return yield* slots
346 .withPermit(run)
347 .pipe(Effect.provideService(SourceControlRateLimit.CredentialScope, scope || fingerprint));
348 });
349
350 return GitHubRequestPolicy.of({ request, credential });
351});
352
353export const layer = Layer.effect(GitHubRequestPolicy, make);