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