Open History to see the last commit
1import * as Clock from "effect/Clock";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Ref from "effect/Ref";
6
7import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
8
9/** The share of each quota a background read leaves for a user's next click. */
10const RESERVE_RATIO = 0.1;
11
12/**
13 * GitHub's quotas: `core` for REST, `graphql` for GraphQL, and a few smaller ones (`search`, …).
14 * Each is spent and reset on its own, so each is tracked on its own.
15 */
16type GitHubQuotaResource = string;
17
18interface QuotaSnapshot {
19 readonly limit: number;
20 readonly remaining: number;
21 readonly resetAtMs: number;
22}
23
24/**
25 * What GitHub says is left of one quota, from the `x-ratelimit-*` headers every API answer
26 * carries. Null when the answer named no quota, which an Enterprise host with limits off does.
27 */
28function quotaFromHeaders(
29 headers: Readonly<Record<string, string | undefined>>,
30): (QuotaSnapshot & { readonly resource: GitHubQuotaResource }) | null {
31 const resource = headers["x-ratelimit-resource"]?.trim();
32 const limit = Number(headers["x-ratelimit-limit"]);
33 const remaining = Number(headers["x-ratelimit-remaining"]);
34 const reset = Number(headers["x-ratelimit-reset"]);
35 if (
36 !resource ||
37 !Number.isFinite(limit) ||
38 limit <= 0 ||
39 !Number.isFinite(remaining) ||
40 remaining < 0 ||
41 !Number.isFinite(reset)
42 ) {
43 return null;
44 }
45 return { resource, limit, remaining, resetAtMs: reset * 1_000 };
46}
47
48/**
49 * Keeps the last tenth of each GitHub quota for interactive requests. A background sweep that
50 * would dip below it is refused until the quota resets, so a user's next click still has budget.
51 *
52 * The balance is GitHub's own count from the latest answer's headers, so it already includes
53 * what anything else spent with the same token, such as an agent's `gh` commands. Requests in
54 * flight together all see that one balance; the reserve absorbs what they spend before their
55 * answers land. Nothing is debited locally, because a 304 or a request that never reached GitHub
56 * spends nothing, and a local count would drift below GitHub's for the rest of the window.
57 *
58 * Interactive requests may spend the reserve, but not a quota GitHub already reported empty.
59 */
60export class GitHubQuota extends Context.Service<
61 GitHubQuota,
62 {
63 readonly admit: (
64 host: string,
65 resource: GitHubQuotaResource,
66 options?: { readonly allowReserve: boolean },
67 ) => Effect.Effect<void, SourceControlRateLimit.SourceControlRateLimitPausedError>;
68 readonly observe: (
69 host: string,
70 headers: Readonly<Record<string, string | undefined>>,
71 ) => Effect.Effect<void>;
72 }
73>()("@t3tools/source-control-github/server/GitHubQuota") {}
74
75const make = Effect.gen(function* () {
76 const snapshots = yield* Ref.make<ReadonlyMap<string, QuotaSnapshot>>(new Map());
77 const keyOf = (host: string, resource: string, scope: string) =>
78 `${host.trim().toLowerCase()}\0${resource}\0${scope}`;
79
80 const admit: GitHubQuota["Service"]["admit"] = Effect.fn("GitHubQuota.admit")(
81 function* (host, resource, options) {
82 const now = yield* Clock.currentTimeMillis;
83 const key = keyOf(host, resource, yield* SourceControlRateLimit.CredentialScope);
84 const snapshot = (yield* Ref.get(snapshots)).get(key);
85 if (snapshot === undefined || snapshot.resetAtMs <= now) return;
86 const floor = options?.allowReserve === true ? 1 : snapshot.limit * RESERVE_RATIO;
87 if (snapshot.remaining >= floor) return;
88 return yield* new SourceControlRateLimit.SourceControlRateLimitPausedError({
89 provider: "github",
90 host: host.trim().toLowerCase(),
91 retryAt: snapshot.resetAtMs,
92 });
93 },
94 );
95
96 const observe: GitHubQuota["Service"]["observe"] = Effect.fn("GitHubQuota.observe")(
97 function* (host, headers) {
98 const quota = quotaFromHeaders(headers);
99 if (quota === null) return;
100 const key = keyOf(host, quota.resource, yield* SourceControlRateLimit.CredentialScope);
101 yield* Ref.update(snapshots, (current) => {
102 const previous = current.get(key);
103 // The latest answer wins. GitHub serves requests from several regions, so a later answer
104 // can report more left in the same window, and keeping the lower one would hold
105 // background work at the reserve until the reset. An answer from an older window says
106 // nothing of this one.
107 if (previous !== undefined && quota.resetAtMs < previous.resetAtMs) return current;
108 const next = new Map(current);
109 next.set(key, {
110 limit: quota.limit,
111 remaining: quota.remaining,
112 resetAtMs: quota.resetAtMs,
113 });
114 return next;
115 });
116 },
117 );
118
119 return GitHubQuota.of({ admit, observe });
120});
121
122export const layer = Layer.effect(GitHubQuota, make);