Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitHubQuota.ts

105 lines3.8 KB

1import { SourceControlProviderKind } from "@t3tools/contracts";
2import * as Clock from "effect/Clock";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Ref from "effect/Ref";
7​
8import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
9​
10const RESERVE_RATIO = 0.1;
11​
12type GitHubQuotaResource = string;
13​
14interface QuotaSnapshot {
15 readonly limit: number;
16 readonly remaining: number;
17 readonly resetAtMs: number;
19​
20function quotaFromHeaders(
21 headers: Readonly<Record<string, string | undefined>>,
22): (QuotaSnapshot & { readonly resource: GitHubQuotaResource }) | null {
23 const resource = headers["x-ratelimit-resource"]?.trim();
24 const limit = Number(headers["x-ratelimit-limit"]);
25 const remaining = Number(headers["x-ratelimit-remaining"]);
26 const reset = Number(headers["x-ratelimit-reset"]);
27 if (
28 !resource ||
29 !Number.isFinite(limit) ||
30 limit <= 0 ||
31 !Number.isFinite(remaining) ||
32 remaining < 0 ||
33 !Number.isFinite(reset)
34 ) {
35 return null;
36 }
37 return { resource, limit, remaining, resetAtMs: reset * 1_000 };
39​
40/**
41 * Nothing is debited locally, because a 304 or a request that never reached GitHub spends
42 * nothing, and a local count would drift below GitHub's for the rest of the window.
43 */
44export class GitHubQuota extends Context.Service<
45 GitHubQuota,
46 {
47 readonly admit: (
48 host: string,
49 resource: GitHubQuotaResource,
50 options?: { readonly allowReserve: boolean },
51 ) => Effect.Effect<void, SourceControlRateLimit.SourceControlRateLimitPausedError>;
52 readonly observe: (
53 host: string,
54 headers: Readonly<Record<string, string | undefined>>,
55 ) => Effect.Effect<void>;
56 }
57>()("@t3tools/source-control-github/server/GitHubQuota") {}
58​
59const make = Effect.gen(function* () {
60 const snapshots = yield* Ref.make<ReadonlyMap<string, QuotaSnapshot>>(new Map());
61 const keyOf = (host: string, resource: string, scope: string) =>
62 `${host.trim().toLowerCase()}\0${resource}\0${scope}`;
63​
64 const admit: GitHubQuota["Service"]["admit"] = Effect.fn("GitHubQuota.admit")(
65 function* (host, resource, options) {
66 const now = yield* Clock.currentTimeMillis;
67 const key = keyOf(host, resource, yield* SourceControlRateLimit.CredentialScope);
68 const snapshot = (yield* Ref.get(snapshots)).get(key);
69 if (snapshot === undefined || snapshot.resetAtMs <= now) return;
70 const floor = options?.allowReserve === true ? 1 : snapshot.limit * RESERVE_RATIO;
71 if (snapshot.remaining >= floor) return;
72 return yield* new SourceControlRateLimit.SourceControlRateLimitPausedError({
73 provider: SourceControlProviderKind.make("github"),
74 host: host.trim().toLowerCase(),
75 retryAt: snapshot.resetAtMs,
76 });
77 },
78 );
79​
80 const observe: GitHubQuota["Service"]["observe"] = Effect.fn("GitHubQuota.observe")(
81 function* (host, headers) {
82 const quota = quotaFromHeaders(headers);
83 if (quota === null) return;
84 const key = keyOf(host, quota.resource, yield* SourceControlRateLimit.CredentialScope);
85 yield* Ref.update(snapshots, (current) => {
86 const previous = current.get(key);
87 // GitHub serves requests from several regions, so a later answer can report
88 // more left in the same window, and keeping the lower one would hold background
89 // work at the reserve until the reset.
90 if (previous !== undefined && quota.resetAtMs < previous.resetAtMs) return current;
91 const next = new Map(current);
92 next.set(key, {
93 limit: quota.limit,
94 remaining: quota.remaining,
95 resetAtMs: quota.resetAtMs,
96 });
97 return next;
98 });
99 },
100 );
101​
102 return GitHubQuota.of({ admit, observe });
103});
104​
105export const layer = Layer.effect(GitHubQuota, make);