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

githubGraphQlBudget.ts

141 lines4.7 KB

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;
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();
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 }
67​
68function isReadOperation(document: string): boolean {
69 const operation = document.trimStart();
70 return operation.startsWith("query") || operation.startsWith("{");
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)}`;
79​
80export const make = Effect.gen(function* () {
81 const snapshots = yield* Ref.make<ReadonlyMap<string, GraphQlBudgetSnapshot>>(new Map());
82​
83 const query: GitHubGraphQlBudget["Service"]["query"] = Effect.fn("GitHubGraphQlBudget.query")(
84 function* (host, document, options) {
85 if (!isReadOperation(document)) return document;
86 const now = yield* Clock.currentTimeMillis;
87 const retryAt = yield* Ref.modify(snapshots, (current) => {
88 const key = hostKey(host);
89 const snapshot = current.get(key);
90 if (snapshot === undefined) return [null, current] as const;
91 if (snapshot.resetAtMs <= now) {
92 const next = new Map(current);
93 next.delete(key);
94 return [null, next] as const;
95 }
96 const remaining = Math.max(0, snapshot.remaining - Math.max(1, snapshot.cost));
97 if (options?.allowReserve !== true && remaining < snapshot.limit * GRAPHQL_RESERVE_RATIO) {
98 return [snapshot.resetAtMs, current] as const;
99 }
100 const next = new Map(current);
101 next.set(key, { ...snapshot, remaining });
102 return [null, next] as const;
103 });
104 if (retryAt !== null) {
105 return yield* new SourceControlRateLimit.SourceControlRateLimitPausedError({
106 provider: "github",
107 host: hostKey(host),
108 retryAt,
109 });
110 }
111 return withRateLimit(document);
112 },
113 );
114​
115 const observe: GitHubGraphQlBudget["Service"]["observe"] = Effect.fn(
116 "GitHubGraphQlBudget.observe",
117 )(function* (host, raw) {
118 const snapshot = snapshotFrom(raw);
119 if (snapshot === null) return;
120 yield* Ref.update(snapshots, (current) => {
121 const key = hostKey(host);
122 const previous = current.get(key);
123 // Concurrent reads can finish out of order. Quota only falls within one reset window, and
124 // an answer from an older window must not replace the current one.
125 if (
126 previous !== undefined &&
127 (snapshot.resetAtMs < previous.resetAtMs ||
128 (snapshot.resetAtMs === previous.resetAtMs && snapshot.remaining >= previous.remaining))
129 ) {
130 return current;
131 }
132 const next = new Map(current);
133 next.set(key, snapshot);
134 return next;
135 });
136 });
137​
138 return GitHubGraphQlBudget.of({ query, observe });
139});
140​
141export const layer = Layer.effect(GitHubGraphQlBudget, make);