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";
6import * as Predicate from "effect/Predicate";
7
8import * as SourceControlRateLimit from "./SourceControlRateLimit.ts";
9
10const GRAPHQL_RESERVE_RATIO = 0.1;
11const RATE_LIMIT_SELECTION = "rateLimit { cost limit remaining resetAt }";
12
13interface GraphQlBudgetSnapshot {
14 readonly cost: number;
15 readonly limit: number;
16 readonly remaining: number;
17 readonly resetAtMs: number;
18}
19
20export class GitHubGraphQlBudget extends Context.Service<
21 GitHubGraphQlBudget,
22 {
23 readonly query: (
24 host: string,
25 document: string,
26 options?: { readonly allowReserve: boolean },
27 ) => Effect.Effect<string, SourceControlRateLimit.SourceControlRateLimitPausedError>;
28 readonly observe: (host: string, raw: string) => Effect.Effect<void>;
29 }
30>()("t3/sourceControl/githubGraphQlBudget") {}
31
32function hostKey(host: string): string {
33 return host.trim().toLowerCase();
34}
35
36function snapshotFrom(raw: string): GraphQlBudgetSnapshot | null {
37 try {
38 const parsed: unknown = JSON.parse(raw);
39 if (
40 !Predicate.isObject(parsed) ||
41 !Predicate.isObject(parsed.data) ||
42 !Predicate.isObject(parsed.data.rateLimit)
43 ) {
44 return null;
45 }
46 const { cost, limit, remaining, resetAt } = parsed.data.rateLimit;
47 if (
48 typeof cost !== "number" ||
49 !Number.isFinite(cost) ||
50 cost < 0 ||
51 typeof limit !== "number" ||
52 !Number.isFinite(limit) ||
53 limit <= 0 ||
54 typeof remaining !== "number" ||
55 !Number.isFinite(remaining) ||
56 remaining < 0 ||
57 typeof resetAt !== "string"
58 ) {
59 return null;
60 }
61 const resetAtMs = Date.parse(resetAt);
62 return Number.isFinite(resetAtMs) ? { cost, limit, remaining, resetAtMs } : null;
63 } catch {
64 return null;
65 }
66}
67
68function isReadOperation(document: string): boolean {
69 const operation = document.trimStart();
70 return operation.startsWith("query") || operation.startsWith("{");
71}
72
73function withRateLimit(document: string): string {
74 if (!isReadOperation(document)) return document;
75 const end = document.lastIndexOf("}");
76 if (end === -1 || document.includes(RATE_LIMIT_SELECTION)) return document;
77 return `${document.slice(0, end)}\n ${RATE_LIMIT_SELECTION}\n${document.slice(end)}`;
78}
79
80/** @public Service construction is part of the canonical Effect module API. */
81export const make = Effect.gen(function* () {
82 const snapshots = yield* Ref.make<ReadonlyMap<string, GraphQlBudgetSnapshot>>(new Map());
83
84 const query: GitHubGraphQlBudget["Service"]["query"] = Effect.fn("GitHubGraphQlBudget.query")(
85 function* (host, document, options) {
86 if (!isReadOperation(document)) return document;
87 const now = yield* Clock.currentTimeMillis;
88 const key = `${hostKey(host)}\0${yield* SourceControlRateLimit.CredentialScope}`;
89 const retryAt = yield* Ref.modify(snapshots, (current) => {
90 const snapshot = current.get(key);
91 if (snapshot === undefined) return [null, current] as const;
92 if (snapshot.resetAtMs <= now) {
93 const next = new Map(current);
94 next.delete(key);
95 return [null, next] as const;
96 }
97 const remaining = snapshot.remaining - Math.max(1, snapshot.cost);
98 if (
99 remaining < 0 ||
100 (options?.allowReserve !== true && remaining < snapshot.limit * GRAPHQL_RESERVE_RATIO)
101 ) {
102 return [snapshot.resetAtMs, current] as const;
103 }
104 const next = new Map(current);
105 next.set(key, { ...snapshot, remaining });
106 return [null, next] as const;
107 });
108 if (retryAt !== null) {
109 return yield* new SourceControlRateLimit.SourceControlRateLimitPausedError({
110 provider: "github",
111 host: hostKey(host),
112 retryAt,
113 });
114 }
115 return withRateLimit(document);
116 },
117 );
118
119 const observe: GitHubGraphQlBudget["Service"]["observe"] = Effect.fn(
120 "GitHubGraphQlBudget.observe",
121 )(function* (host, raw) {
122 const snapshot = snapshotFrom(raw);
123 if (snapshot === null) return;
124 const key = `${hostKey(host)}\0${yield* SourceControlRateLimit.CredentialScope}`;
125 yield* Ref.update(snapshots, (current) => {
126 const previous = current.get(key);
127 // Concurrent reads can finish out of order. Quota only falls within one reset window, and
128 // an answer from an older window must not replace the current one.
129 if (previous !== undefined && snapshot.resetAtMs < previous.resetAtMs) {
130 return current;
131 }
132 const next = new Map(current);
133 // Keep the conservative balance, but learn the observed cost even when our reservation
134 // was larger. Otherwise one expensive read makes every later cheap read spend its cost.
135 next.set(
136 key,
137 previous !== undefined &&
138 snapshot.resetAtMs === previous.resetAtMs &&
139 snapshot.remaining >= previous.remaining
140 ? { ...previous, cost: snapshot.cost }
141 : snapshot,
142 );
143 return next;
144 });
145 });
146
147 return GitHubGraphQlBudget.of({ query, observe });
148});
149
150export const layer = Layer.effect(GitHubGraphQlBudget, make);