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

githubGraphQlBudget.ts

147 lines5.0 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​
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 retryAt = yield* Ref.modify(snapshots, (current) => {
89 const key = hostKey(host);
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 = Math.max(0, snapshot.remaining - Math.max(1, snapshot.cost));
98 if (options?.allowReserve !== true && remaining < snapshot.limit * GRAPHQL_RESERVE_RATIO) {
99 return [snapshot.resetAtMs, current] as const;
100 }
101 const next = new Map(current);
102 next.set(key, { ...snapshot, remaining });
103 return [null, next] as const;
104 });
105 if (retryAt !== null) {
106 return yield* new SourceControlRateLimit.SourceControlRateLimitPausedError({
107 provider: "github",
108 host: hostKey(host),
109 retryAt,
110 });
111 }
112 return withRateLimit(document);
113 },
114 );
115​
116 const observe: GitHubGraphQlBudget["Service"]["observe"] = Effect.fn(
117 "GitHubGraphQlBudget.observe",
118 )(function* (host, raw) {
119 const snapshot = snapshotFrom(raw);
120 if (snapshot === null) return;
121 yield* Ref.update(snapshots, (current) => {
122 const key = hostKey(host);
123 const previous = current.get(key);
124 // Concurrent reads can finish out of order. Quota only falls within one reset window, and
125 // an answer from an older window must not replace the current one.
126 if (previous !== undefined && snapshot.resetAtMs < previous.resetAtMs) {
127 return current;
128 }
129 const next = new Map(current);
130 // Keep the conservative balance, but learn the observed cost even when our reservation
131 // was larger. Otherwise one expensive read makes every later cheap read spend its cost.
132 next.set(
133 key,
134 previous !== undefined &&
135 snapshot.resetAtMs === previous.resetAtMs &&
136 snapshot.remaining >= previous.remaining
137 ? { ...previous, cost: snapshot.cost }
138 : snapshot,
139 );
140 return next;
141 });
142 });
143​
144 return GitHubGraphQlBudget.of({ query, observe });
145});
146​
147export const layer = Layer.effect(GitHubGraphQlBudget, make);