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

SourceControlRateLimit.ts

168 lines5.7 KB

1import * as Clock from "effect/Clock";
2import * as Context from "effect/Context";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Ref from "effect/Ref";
7import * as Schema from "effect/Schema";
8import {
9 SourceControlProviderKind as SourceControlProviderKindSchema,
10 type SourceControlProviderKind,
11} from "@t3tools/contracts";
12​
13const FALLBACK_COOLDOWN = Duration.seconds(30);
14const MAX_FALLBACK_COOLDOWN = Duration.minutes(15);
15​
16export const CredentialScope = Context.Reference<string>("t3/sourceControl/CredentialScope", {
17 defaultValue: () => "",
18});
19​
20interface RateLimitKey {
21 readonly provider: SourceControlProviderKind;
22 readonly host: string;
24​
25interface RateLimitLease extends RateLimitKey {
26 readonly lease: number;
28​
29interface RateLimitEntry {
30 readonly attempt: number;
31 readonly generation: number;
32 readonly retryAt: number;
34​
35export class SourceControlRateLimitPausedError extends Schema.TaggedError<SourceControlRateLimitPausedError>()(
36 "SourceControlRateLimitPausedError",
37 {
38 provider: SourceControlProviderKindSchema,
39 host: Schema.String,
40 retryAt: Schema.Number,
41 },
42) {
43 get detail(): string {
44 return `${this.provider} requests to ${this.host} are paused until the rate limit resets.`;
45 }
46​
47 override get message(): string {
48 return this.detail;
49 }
51​
52export class SourceControlRateLimit extends Context.Service<
53 SourceControlRateLimit,
54 {
55 readonly check: (
56 key: RateLimitKey,
57 options?: { readonly allowPaused: boolean },
58 ) => Effect.Effect<number, SourceControlRateLimitPausedError>;
59 readonly recordRateLimit: (
60 input: RateLimitLease & { readonly retryAt?: number | undefined },
61 ) => Effect.Effect<void>;
62 readonly recordSuccess: (input: RateLimitLease) => Effect.Effect<void>;
63 }
64>()("t3/sourceControl/SourceControlRateLimit") {}
65​
66function normalizedKey(key: RateLimitKey, scope: string): string {
67 return `${key.provider}\0${key.host.trim().toLowerCase()}\0${scope}`;
69​
70function fallbackCooldownMs(attempt: number): number {
71 return Math.min(
72 Duration.toMillis(FALLBACK_COOLDOWN) * 2 ** Math.max(0, attempt - 1),
73 Duration.toMillis(MAX_FALLBACK_COOLDOWN),
74 );
76​
77export function retryAtFromHeader(value: string | undefined, now: number): number | undefined {
78 if (value === undefined) return undefined;
79 const normalized = value.trim();
80 if (/^\d+$/u.test(normalized)) {
81 const seconds = Number(normalized);
82 const retryAt = now + seconds * 1_000;
83 return Number.isSafeInteger(retryAt) ? retryAt : undefined;
84 }
85 const retryAt = Date.parse(normalized);
86 return Number.isFinite(retryAt) && retryAt > now ? retryAt : undefined;
88​
89/** @public Service construction is part of the canonical Effect module API. */
90export const make = Effect.gen(function* () {
91 const entries = yield* Ref.make<ReadonlyMap<string, RateLimitEntry>>(new Map());
92​
93 const check: SourceControlRateLimit["Service"]["check"] = Effect.fn(
94 "SourceControlRateLimit.check",
95 )(function* (input, options) {
96 const now = yield* Clock.currentTimeMillis;
97 const key = normalizedKey(input, yield* CredentialScope);
98 const entry = (yield* Ref.get(entries)).get(key);
99 if (entry !== undefined && entry.retryAt > now && options?.allowPaused !== true) {
100 return yield* new SourceControlRateLimitPausedError({
101 provider: input.provider,
102 host: input.host.trim().toLowerCase(),
103 retryAt: entry.retryAt,
104 });
105 }
106 return entry?.generation ?? 0;
107 });
108​
109 const recordRateLimit: SourceControlRateLimit["Service"]["recordRateLimit"] = Effect.fn(
110 "SourceControlRateLimit.recordRateLimit",
111 )(function* (input) {
112 const now = yield* Clock.currentTimeMillis;
113 const key = normalizedKey(input, yield* CredentialScope);
114 yield* Ref.update(entries, (current) => {
115 const previous = current.get(key);
116 if (previous !== undefined && previous.generation > input.lease) {
117 if (previous.retryAt <= now && (input.retryAt === undefined || input.retryAt <= now)) {
118 return current;
119 }
120 const retryAt =
121 input.retryAt !== undefined && input.retryAt > previous.retryAt
122 ? input.retryAt
123 : previous.retryAt;
124 if (retryAt === previous.retryAt) return current;
125 const next = new Map(current);
126 next.set(key, { ...previous, retryAt });
127 return next;
128 }
129​
130 const attempt = (previous?.attempt ?? 0) + 1;
131 const proposedRetryAt =
132 input.retryAt !== undefined && input.retryAt > now
133 ? input.retryAt
134 : now + fallbackCooldownMs(attempt);
135 const retryAt =
136 previous !== undefined && previous.retryAt > now
137 ? Math.max(previous.retryAt, proposedRetryAt)
138 : proposedRetryAt;
139 const next = new Map(current);
140 next.set(key, {
141 attempt,
142 generation: Math.max(previous?.generation ?? 0, input.lease) + 1,
143 retryAt,
144 });
145 return next;
146 });
147 });
148​
149 const recordSuccess: SourceControlRateLimit["Service"]["recordSuccess"] = Effect.fn(
150 "SourceControlRateLimit.recordSuccess",
151 )(function* (input) {
152 const now = yield* Clock.currentTimeMillis;
153 const key = normalizedKey(input, yield* CredentialScope);
154 yield* Ref.update(entries, (current) => {
155 const previous = current.get(key);
156 if (previous === undefined || previous.generation !== input.lease || previous.retryAt > now) {
157 return current;
158 }
159 const next = new Map(current);
160 next.set(key, { attempt: 0, generation: previous.generation, retryAt: 0 });
161 return next;
162 });
163 });
164​
165 return SourceControlRateLimit.of({ check, recordRateLimit, recordSuccess });
166});
167​
168export const layer = Layer.effect(SourceControlRateLimit, make);