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/** GitHub's secondary limits penalize concurrent bursts. */
18const CONCURRENCY = 8;
19const REQUEST_HEADERS = { "x-github-api-version": "2022-11-28", "user-agent": "t3code" };
20
21/** Pin requests to this host's credential across account switches. Keep it out of RPCs/cache keys. */
22export const PinnedGitHubCredential = Context.Reference<{
23 readonly host: string;
24 readonly token: Redacted.Redacted<string>;
25 readonly credentialFingerprint: string;
26} | null>("@t3tools/source-control-github/server/GitHubRequestPolicy/PinnedGitHubCredential", {
27 defaultValue: () => null,
28});
29
30export class GitHubApiRequestError extends Schema.TaggedError<GitHubApiRequestError>()(
31 "GitHubApiRequestError",
32 { host: Schema.String, operation: Schema.String, cause: Schema.Defect() },
33) {
34 override get message(): string {
35 return `Could not reach GitHub at ${this.host}.`;
36 }
37}
38
39export class GitHubApiAuthenticationError extends Schema.TaggedError<GitHubApiAuthenticationError>()(
40 "GitHubApiAuthenticationError",
41 { host: Schema.String, operation: Schema.String },
42) {
43 override get message(): string {
44 return `GitHub refused the credential for ${this.host}. Run \`gh auth login --hostname ${this.host}\` and retry.`;
45 }
46}
47
48export class GitHubApiRateLimitError extends Schema.TaggedError<GitHubApiRateLimitError>()(
49 "GitHubApiRateLimitError",
50 {
51 host: Schema.String,
52 operation: Schema.String,
53 retryAt: Schema.optionalKey(Schema.Finite),
54 },
55) {
56 override get message(): string {
57 return "GitHub API rate limit exceeded.";
58 }
59}
60
61export class GitHubApiNotFoundError extends Schema.TaggedError<GitHubApiNotFoundError>()(
62 "GitHubApiNotFoundError",
63 { host: Schema.String, operation: Schema.String },
64) {
65 override get message(): string {
66 return "GitHub could not find the requested resource, or the credential cannot see it.";
67 }
68}
69
70export class GitHubApiResponseError extends Schema.TaggedError<GitHubApiResponseError>()(
71 "GitHubApiResponseError",
72 {
73 host: Schema.String,
74 operation: Schema.String,
75 status: Schema.Int,
76 githubErrors: Schema.optionalKey(Schema.Array(Schema.String)),
77 },
78) {
79 override get message(): string {
80 return this.githubErrors !== undefined && this.githubErrors.length > 0
81 ? `GitHub returned an error: ${this.githubErrors.join("; ")}`
82 : `GitHub returned HTTP ${this.status}.`;
83 }
84}
85
86export type GitHubApiError =
87 | GitHubCredentials.GitHubCredentialUnavailableError
88 | GitHubApiRequestError
89 | GitHubApiAuthenticationError
90 | GitHubApiRateLimitError
91 | GitHubApiNotFoundError
92 | GitHubApiResponseError
93 | SourceControlRateLimit.SourceControlRateLimitPausedError;
94
95export function normalizeHost(host: string): string {
96 return host.trim().toLowerCase();
97}
98
99export function gitHubApiUrls(host: string): { readonly rest: string; readonly graphql: string } {
100 const normalized = normalizeHost(host);
101 if (normalized === "github.com") {
102 return { rest: "https://api.github.com", graphql: "https://api.github.com/graphql" };
103 }
104 if (normalized.endsWith(".ghe.com")) {
105 return {
106 rest: `https://api.${normalized}`,
107 graphql: `https://api.${normalized}/graphql`,
108 };
109 }
110 return { rest: `https://${normalized}/api/v3`, graphql: `https://${normalized}/api/graphql` };
111}
112
113function rateLimitAttributes(
114 headers: Readonly<Record<string, string | undefined>>,
115): Record<string, number | string> {
116 const attributes: Record<string, number | string> = {};
117 for (const [header, name] of [
118 ["x-ratelimit-limit", "github.ratelimit.limit"],
119 ["x-ratelimit-remaining", "github.ratelimit.remaining"],
120 ["x-ratelimit-used", "github.ratelimit.used"],
121 ["x-ratelimit-reset", "github.ratelimit.reset"],
122 ] as const) {
123 const value = Number(headers[header]);
124 if (headers[header] !== undefined && Number.isFinite(value)) attributes[name] = value;
125 }
126 const resource = headers["x-ratelimit-resource"];
127 if (resource !== undefined) attributes["github.ratelimit.resource"] = resource;
128 return attributes;
129}
130
131function retryAtFrom(
132 headers: Readonly<Record<string, string | undefined>>,
133 now: number,
134): number | undefined {
135 const fromRetryAfter = SourceControlRateLimit.retryAtFromHeader(headers["retry-after"], now);
136 if (fromRetryAfter !== undefined) return fromRetryAfter;
137 const reset = Number(headers["x-ratelimit-reset"]) * 1_000;
138 return Number.isFinite(reset) && reset > now ? reset : undefined;
139}
140
141/** HTTP 200 GraphQL rate limits use RATE_LIMITED or untyped errors with quota headers. */
142export function isRateLimited(input: {
143 readonly status: number;
144 readonly headers: Readonly<Record<string, string | undefined>>;
145 readonly graphqlErrors?: ReadonlyArray<{ readonly type?: unknown; readonly message?: unknown }>;
146 readonly body?: string;
147}): boolean {
148 const { status, headers, graphqlErrors: errors } = input;
149 return (
150 status === 429 ||
151 (errors !== undefined &&
152 (headers["x-ratelimit-remaining"] === "0" ||
153 errors.some(
154 (error) =>
155 error.type === "RATE_LIMITED" ||
156 (typeof error.message === "string" &&
157 /rate limit (already )?exceeded/i.test(error.message)),
158 ))) ||
159 (status === 403 &&
160 (headers["x-ratelimit-remaining"] === "0" ||
161 headers["retry-after"] !== undefined ||
162 /rate limit/i.test(input.body ?? "")))
163 );
164}
165
166export type GitHubAnswer<A> = {
167 readonly status: number | undefined;
168 readonly headers: Readonly<Record<string, string | undefined>>;
169} & (
170 | { readonly _tag: "Ok"; readonly value: A }
171 | { readonly _tag: "RateLimited" | "Unauthorized" | "NotFound" }
172 | { readonly _tag: "Failed"; readonly messages?: ReadonlyArray<string> | undefined }
173);
174
175export interface GitHubRequest {
176 readonly host: string;
177 readonly operation: string;
178 /** The quota the request spends: `core` for REST, `graphql` for GraphQL. */
179 readonly resource: string;
180 readonly allowReserve: boolean;
181 /** Covers sending and reading the answer. Defaults to 30 seconds. */
182 readonly timeout?: Duration.Input | undefined;
183}
184
185/** REST/GraphQL share credentials, slots, quota reserves and host-wide pauses. */
186export class GitHubRequestPolicy extends Context.Service<
187 GitHubRequestPolicy,
188 {
189 /** send receives auth/version headers; its failures pass through unchanged. */
190 readonly request: <A, E, R>(
191 input: GitHubRequest,
192 send: (headers: Readonly<Record<string, string>>) => Effect.Effect<GitHubAnswer<A>, E, R>,
193 ) => Effect.Effect<A, E | GitHubApiError, R>;
194 readonly credential: (
195 host: string,
196 ) => Effect.Effect<
197 { readonly token: Redacted.Redacted<string>; readonly fingerprint: string },
198 GitHubApiError
199 >;
200 }
201>()("@t3tools/source-control-github/server/GitHubRequestPolicy") {}
202
203/** @public */
204export const make = Effect.gen(function* () {
205 const credentials = yield* GitHubCredentials.GitHubCredentials;
206 const quota = yield* GitHubQuota.GitHubQuota;
207 const limits = yield* SourceControlRateLimit.SourceControlRateLimit;
208 const slots = yield* Semaphore.make(CONCURRENCY);
209
210 const credential: GitHubRequestPolicy["Service"]["credential"] = Effect.fn(
211 "GitHubRest.credential",
212 )(function* (host) {
213 const normalized = normalizeHost(host);
214 const pinned = yield* PinnedGitHubCredential;
215 if (pinned !== null) {
216 if (pinned.host !== normalized) {
217 return yield* new GitHubApiAuthenticationError({
218 host: normalized,
219 operation: "credential",
220 });
221 }
222 return { token: pinned.token, fingerprint: pinned.credentialFingerprint };
223 }
224 const held = yield* credentials.get(normalized);
225 return { token: held.token, fingerprint: held.fingerprint };
226 });
227
228 // The REST/GraphQL transport span owns request and quota metadata.
229 const request: GitHubRequestPolicy["Service"]["request"] = Effect.fnUntraced(function* <A, E, R>(
230 input: GitHubRequest,
231 send: (headers: Readonly<Record<string, string>>) => Effect.Effect<GitHubAnswer<A>, E, R>,
232 ) {
233 const host = normalizeHost(input.host);
234 const context = { host, operation: input.operation };
235 yield* Effect.annotateCurrentSpan({
236 "github.host": host,
237 "github.operation": input.operation,
238 });
239 const { token, fingerprint } = yield* credential(host);
240 const scope = yield* SourceControlRateLimit.CredentialScope;
241 // A refusal pauses the whole host, whichever quota it spent: the key PullRequestService
242 // records its own backoff under.
243 const key = { provider: SourceControlProviderKind.make("github"), host };
244
245 // Settlement annotates the request span with status and rate-limit attributes.
246 const settle = Effect.fnUntraced(function* (lease: number, answer: GitHubAnswer<A>) {
247 yield* quota.observe(host, answer.headers);
248 yield* Effect.annotateCurrentSpan({
249 ...(answer.status === undefined ? {} : { "http.response.status_code": answer.status }),
250 ...rateLimitAttributes(answer.headers),
251 });
252 switch (answer._tag) {
253 case "Ok":
254 yield* limits.recordSuccess({ ...key, lease });
255 return answer.value;
256 case "RateLimited": {
257 const retryAt = retryAtFrom(answer.headers, yield* Clock.currentTimeMillis);
258 yield* limits.recordRateLimit({ ...key, lease, retryAt });
259 yield* Effect.annotateCurrentSpan({
260 "github.rate_limited": true,
261 ...(retryAt === undefined ? {} : { "github.retry_at": retryAt }),
262 });
263 return yield* new GitHubApiRateLimitError({
264 ...context,
265 ...(retryAt === undefined ? {} : { retryAt }),
266 });
267 }
268 case "Unauthorized":
269 // The source may hold a newer token than the one that was refused.
270 yield* credentials.invalidate(host);
271 return yield* new GitHubApiAuthenticationError(context);
272 case "NotFound":
273 return yield* new GitHubApiNotFoundError(context);
274 case "Failed":
275 return yield* new GitHubApiResponseError({
276 ...context,
277 status: answer.status ?? 200,
278 ...(answer.messages === undefined ? {} : { githubErrors: answer.messages }),
279 });
280 }
281 });
282
283 const run = Effect.gen(function* () {
284 const lease = yield* quota
285 .admit(host, input.resource, { allowReserve: input.allowReserve })
286 .pipe(
287 Effect.andThen(limits.check(key, input.allowReserve ? { allowPaused: true } : undefined)),
288 Effect.tapError((paused) =>
289 Effect.annotateCurrentSpan({
290 "github.paused": true,
291 "github.retry_at": paused.retryAt,
292 }),
293 ),
294 );
295 // One deadline covers the headers and the body: a host that answers headers and then
296 // stalls must not hold a shared slot for undici's own five-minute body timeout.
297 const answer = yield* send({
298 ...REQUEST_HEADERS,
299 authorization: `Bearer ${Redacted.value(token)}`,
300 }).pipe(
301 Effect.timeoutOrElse({
302 duration: input.timeout ?? DEFAULT_TIMEOUT,
303 orElse: () =>
304 Effect.fail(new GitHubApiRequestError({ ...context, cause: new Cause.TimeoutError() })),
305 }),
306 );
307 return yield* settle(lease, answer);
308 });
309 // The rate-limit scope follows the credential, so a pause on one account never blocks another.
310 return yield* slots
311 .withPermit(run)
312 .pipe(Effect.provideService(SourceControlRateLimit.CredentialScope, scope || fingerprint));
313 });
314
315 return GitHubRequestPolicy.of({ request, credential });
316});
317
318export const layer = Layer.effect(GitHubRequestPolicy, make);