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

SourceControlRateLimit.ts

162 lines5.4 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​
16interface RateLimitKey {
17 readonly provider: SourceControlProviderKind;
18 readonly host: string;
20​
21interface RateLimitLease extends RateLimitKey {
22 readonly lease: number;
24​
25interface RateLimitEntry {
26 readonly attempt: number;
27 readonly generation: number;
28 readonly retryAt: number;
30​
31export class SourceControlRateLimitPausedError extends Schema.TaggedErrorClass<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 }
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()}`;
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 );
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;
84​
85export const make = Effect.gen(function* () {
86 const entries = yield* Ref.make<ReadonlyMap<string, RateLimitEntry>>(new Map());
87​
88 const check: SourceControlRateLimit["Service"]["check"] = Effect.fn(
89 "SourceControlRateLimit.check",
90 )(function* (input, options) {
91 const now = yield* Clock.currentTimeMillis;
92 const entry = (yield* Ref.get(entries)).get(normalizedKey(input));
93 if (entry !== undefined && entry.retryAt > now && options?.allowPaused !== true) {
94 return yield* new SourceControlRateLimitPausedError({
95 provider: input.provider,
96 host: input.host.trim().toLowerCase(),
97 retryAt: entry.retryAt,
98 });
99 }
100 return entry?.generation ?? 0;
101 });
102​
103 const recordRateLimit: SourceControlRateLimit["Service"]["recordRateLimit"] = Effect.fn(
104 "SourceControlRateLimit.recordRateLimit",
105 )(function* (input) {
106 const now = yield* Clock.currentTimeMillis;
107 yield* Ref.update(entries, (current) => {
108 const key = normalizedKey(input);
109 const previous = current.get(key);
110 if (previous !== undefined && previous.generation > input.lease) {
111 if (previous.retryAt <= now && (input.retryAt === undefined || input.retryAt <= now)) {
112 return current;
113 }
114 const retryAt =
115 input.retryAt !== undefined && input.retryAt > previous.retryAt
116 ? input.retryAt
117 : previous.retryAt;
118 if (retryAt === previous.retryAt) return current;
119 const next = new Map(current);
120 next.set(key, { ...previous, retryAt });
121 return next;
122 }
123​
124 const attempt = (previous?.attempt ?? 0) + 1;
125 const proposedRetryAt =
126 input.retryAt !== undefined && input.retryAt > now
127 ? input.retryAt
128 : now + fallbackCooldownMs(attempt);
129 const retryAt =
130 previous !== undefined && previous.retryAt > now
131 ? Math.max(previous.retryAt, proposedRetryAt)
132 : proposedRetryAt;
133 const next = new Map(current);
134 next.set(key, {
135 attempt,
136 generation: Math.max(previous?.generation ?? 0, input.lease) + 1,
137 retryAt,
138 });
139 return next;
140 });
141 });
142​
143 const recordSuccess: SourceControlRateLimit["Service"]["recordSuccess"] = Effect.fn(
144 "SourceControlRateLimit.recordSuccess",
145 )(function* (input) {
146 const now = yield* Clock.currentTimeMillis;
147 yield* Ref.update(entries, (current) => {
148 const key = normalizedKey(input);
149 const previous = current.get(key);
150 if (previous === undefined || previous.generation !== input.lease || previous.retryAt > now) {
151 return current;
152 }
153 const next = new Map(current);
154 next.set(key, { attempt: 0, generation: previous.generation, retryAt: 0 });
155 return next;
156 });
157 });
158​
159 return SourceControlRateLimit.of({ check, recordRateLimit, recordSuccess });
160});
161​
162export const layer = Layer.effect(SourceControlRateLimit, make);