edge-throttle 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +249 -2
- package/dist/adapters/cloudflare-kv.cjs +40 -0
- package/dist/adapters/cloudflare-kv.cjs.map +1 -0
- package/dist/adapters/cloudflare-kv.d.cts +34 -0
- package/dist/adapters/cloudflare-kv.d.ts +34 -0
- package/dist/adapters/cloudflare-kv.js +38 -0
- package/dist/adapters/cloudflare-kv.js.map +1 -0
- package/dist/adapters/memory.cjs +67 -0
- package/dist/adapters/memory.cjs.map +1 -0
- package/dist/adapters/memory.d.cts +37 -0
- package/dist/adapters/memory.d.ts +37 -0
- package/dist/adapters/memory.js +65 -0
- package/dist/adapters/memory.js.map +1 -0
- package/dist/adapters/redis.cjs +76 -0
- package/dist/adapters/redis.cjs.map +1 -0
- package/dist/adapters/redis.d.cts +44 -0
- package/dist/adapters/redis.d.ts +44 -0
- package/dist/adapters/redis.js +74 -0
- package/dist/adapters/redis.js.map +1 -0
- package/dist/adapters/upstash.cjs +87 -0
- package/dist/adapters/upstash.cjs.map +1 -0
- package/dist/adapters/upstash.d.cts +35 -0
- package/dist/adapters/upstash.d.ts +35 -0
- package/dist/adapters/upstash.js +85 -0
- package/dist/adapters/upstash.js.map +1 -0
- package/dist/index.cjs +338 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +70 -0
- package/dist/index.d.ts +70 -0
- package/dist/index.js +333 -0
- package/dist/index.js.map +1 -0
- package/dist/types-Ca_Pa4mZ.d.cts +121 -0
- package/dist/types-Ca_Pa4mZ.d.ts +121 -0
- package/package.json +89 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
// src/utils/headers.ts
|
|
2
|
+
function buildRateLimitHeaders(result, now) {
|
|
3
|
+
const headers = {
|
|
4
|
+
"X-RateLimit-Limit": String(result.limit),
|
|
5
|
+
"X-RateLimit-Remaining": String(Math.max(0, Math.floor(result.remaining))),
|
|
6
|
+
"X-RateLimit-Reset": String(Math.ceil(result.reset / 1e3))
|
|
7
|
+
};
|
|
8
|
+
if (!result.success) {
|
|
9
|
+
const retryAfterSec = Math.max(1, Math.ceil((result.reset - now) / 1e3));
|
|
10
|
+
headers["Retry-After"] = String(retryAfterSec);
|
|
11
|
+
}
|
|
12
|
+
return headers;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// src/limiter.ts
|
|
16
|
+
function createRateLimiter(config) {
|
|
17
|
+
if (!config || !config.adapter) {
|
|
18
|
+
throw new TypeError('createRateLimiter requires a "adapter" in config.');
|
|
19
|
+
}
|
|
20
|
+
if (!config.algorithm) {
|
|
21
|
+
throw new TypeError('createRateLimiter requires an "algorithm" in config.');
|
|
22
|
+
}
|
|
23
|
+
if (config.timeoutMs !== void 0 && (!Number.isFinite(config.timeoutMs) || config.timeoutMs <= 0)) {
|
|
24
|
+
throw new RangeError(`createRateLimiter "timeoutMs" must be a positive finite number, got ${config.timeoutMs}.`);
|
|
25
|
+
}
|
|
26
|
+
const {
|
|
27
|
+
adapter,
|
|
28
|
+
algorithm,
|
|
29
|
+
prefix = "rl",
|
|
30
|
+
failOpen = false,
|
|
31
|
+
timeoutMs,
|
|
32
|
+
onError
|
|
33
|
+
} = config;
|
|
34
|
+
const pendingLocks = /* @__PURE__ */ new Map();
|
|
35
|
+
async function withKeyLock(key, fn) {
|
|
36
|
+
if (adapter.eval) {
|
|
37
|
+
return fn();
|
|
38
|
+
}
|
|
39
|
+
const previous = pendingLocks.get(key) ?? Promise.resolve();
|
|
40
|
+
let release;
|
|
41
|
+
const current = new Promise((resolve) => {
|
|
42
|
+
release = resolve;
|
|
43
|
+
});
|
|
44
|
+
pendingLocks.set(key, current);
|
|
45
|
+
try {
|
|
46
|
+
await previous;
|
|
47
|
+
return await fn();
|
|
48
|
+
} finally {
|
|
49
|
+
release();
|
|
50
|
+
if (pendingLocks.get(key) === current) {
|
|
51
|
+
pendingLocks.delete(key);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
async function withTimeout(promise) {
|
|
56
|
+
if (timeoutMs === void 0) {
|
|
57
|
+
return promise;
|
|
58
|
+
}
|
|
59
|
+
let timerId;
|
|
60
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
61
|
+
timerId = setTimeout(() => {
|
|
62
|
+
reject(new Error(`edge-throttle: storage operation timed out after ${timeoutMs}ms`));
|
|
63
|
+
}, timeoutMs);
|
|
64
|
+
});
|
|
65
|
+
try {
|
|
66
|
+
return await Promise.race([promise, timeoutPromise]);
|
|
67
|
+
} finally {
|
|
68
|
+
if (timerId !== void 0) {
|
|
69
|
+
clearTimeout(timerId);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return {
|
|
74
|
+
async limit(identifier, options) {
|
|
75
|
+
if (typeof identifier !== "string" || identifier.length === 0) {
|
|
76
|
+
throw new TypeError("limiter.limit() requires a non-empty string identifier.");
|
|
77
|
+
}
|
|
78
|
+
const cost = options?.cost ?? 1;
|
|
79
|
+
if (!Number.isFinite(cost) || cost < 0) {
|
|
80
|
+
throw new RangeError(`limiter.limit() "cost" must be a non-negative finite number, got ${cost}.`);
|
|
81
|
+
}
|
|
82
|
+
const key = prefix ? `${prefix}:${identifier}` : identifier;
|
|
83
|
+
const now = Date.now();
|
|
84
|
+
try {
|
|
85
|
+
const outcome = await withTimeout(
|
|
86
|
+
withKeyLock(
|
|
87
|
+
key,
|
|
88
|
+
() => algorithm.consume({
|
|
89
|
+
adapter,
|
|
90
|
+
key,
|
|
91
|
+
cost,
|
|
92
|
+
now
|
|
93
|
+
})
|
|
94
|
+
)
|
|
95
|
+
);
|
|
96
|
+
return {
|
|
97
|
+
...outcome,
|
|
98
|
+
headers: buildRateLimitHeaders(outcome, now)
|
|
99
|
+
};
|
|
100
|
+
} catch (error) {
|
|
101
|
+
onError?.(error, identifier);
|
|
102
|
+
if (failOpen) {
|
|
103
|
+
const fallback = {
|
|
104
|
+
success: true,
|
|
105
|
+
limit: algorithm.maxLimit,
|
|
106
|
+
remaining: algorithm.maxLimit,
|
|
107
|
+
reset: now
|
|
108
|
+
};
|
|
109
|
+
return {
|
|
110
|
+
...fallback,
|
|
111
|
+
headers: buildRateLimitHeaders(fallback, now)
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// src/utils/duration.ts
|
|
121
|
+
var UNIT_MS = {
|
|
122
|
+
ms: 1,
|
|
123
|
+
s: 1e3,
|
|
124
|
+
m: 6e4,
|
|
125
|
+
h: 36e5,
|
|
126
|
+
d: 864e5
|
|
127
|
+
};
|
|
128
|
+
var DURATION_REGEX = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i;
|
|
129
|
+
function parseDuration(duration) {
|
|
130
|
+
if (typeof duration === "number") {
|
|
131
|
+
if (!Number.isFinite(duration) || duration <= 0) {
|
|
132
|
+
throw new RangeError(`Invalid duration: ${String(duration)}. Expected a positive finite number.`);
|
|
133
|
+
}
|
|
134
|
+
return duration;
|
|
135
|
+
}
|
|
136
|
+
if (typeof duration === "string") {
|
|
137
|
+
const match = DURATION_REGEX.exec(duration.trim());
|
|
138
|
+
if (!match) {
|
|
139
|
+
throw new RangeError(
|
|
140
|
+
`Invalid duration string: "${duration}". Expected format like "500ms", "10s", "1m", "1h", or "1d".`
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
const value = Number(match[1]);
|
|
144
|
+
const unit = match[2].toLowerCase();
|
|
145
|
+
const ms = value * UNIT_MS[unit];
|
|
146
|
+
if (!Number.isFinite(ms) || ms <= 0) {
|
|
147
|
+
throw new RangeError(`Invalid duration: "${duration}". Result must be > 0ms.`);
|
|
148
|
+
}
|
|
149
|
+
return ms;
|
|
150
|
+
}
|
|
151
|
+
throw new RangeError(`Invalid duration type: ${typeof duration}.`);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// src/algorithms/sliding-window.ts
|
|
155
|
+
var SLIDING_WINDOW_LUA = `
|
|
156
|
+
local curr = tonumber(redis.call('GET', KEYS[1]) or '0')
|
|
157
|
+
local prev = tonumber(redis.call('GET', KEYS[2]) or '0')
|
|
158
|
+
local limit = tonumber(ARGV[1])
|
|
159
|
+
local cost = tonumber(ARGV[2])
|
|
160
|
+
local weight = tonumber(ARGV[3])
|
|
161
|
+
local ttl = tonumber(ARGV[4])
|
|
162
|
+
local estimated = prev * weight + curr
|
|
163
|
+
if estimated + cost <= limit then
|
|
164
|
+
local newCurr = tonumber(redis.call('INCRBYFLOAT', KEYS[1], cost))
|
|
165
|
+
if curr == 0 then
|
|
166
|
+
redis.call('PEXPIRE', KEYS[1], ttl)
|
|
167
|
+
end
|
|
168
|
+
local rem = math.max(0, math.floor(limit - (estimated + cost)))
|
|
169
|
+
return {1, rem}
|
|
170
|
+
else
|
|
171
|
+
local rem = math.max(0, math.floor(limit - estimated))
|
|
172
|
+
return {0, rem}
|
|
173
|
+
end
|
|
174
|
+
`.trim();
|
|
175
|
+
function slidingWindow(config) {
|
|
176
|
+
if (!Number.isFinite(config.limit) || config.limit <= 0) {
|
|
177
|
+
throw new RangeError(`slidingWindow "limit" must be a positive finite number, got ${config.limit}.`);
|
|
178
|
+
}
|
|
179
|
+
const limit = config.limit;
|
|
180
|
+
const windowMs = parseDuration(config.window);
|
|
181
|
+
const ttlMs = windowMs * 2;
|
|
182
|
+
return {
|
|
183
|
+
name: "sliding-window",
|
|
184
|
+
maxLimit: limit,
|
|
185
|
+
async consume(ctx) {
|
|
186
|
+
const { adapter, key, cost, now } = ctx;
|
|
187
|
+
const currentWindow = Math.floor(now / windowMs);
|
|
188
|
+
const prevWindow = currentWindow - 1;
|
|
189
|
+
const elapsedMs = now - currentWindow * windowMs;
|
|
190
|
+
const weight = (windowMs - elapsedMs) / windowMs;
|
|
191
|
+
const reset = (currentWindow + 1) * windowMs;
|
|
192
|
+
const currentKey = `${key}:${currentWindow}`;
|
|
193
|
+
const prevKey = `${key}:${prevWindow}`;
|
|
194
|
+
if (adapter.eval) {
|
|
195
|
+
const raw = await adapter.eval(
|
|
196
|
+
SLIDING_WINDOW_LUA,
|
|
197
|
+
[currentKey, prevKey],
|
|
198
|
+
[limit, cost, weight, ttlMs]
|
|
199
|
+
);
|
|
200
|
+
return {
|
|
201
|
+
success: raw[0] === 1,
|
|
202
|
+
limit,
|
|
203
|
+
remaining: Math.max(0, Number(raw[1] ?? 0)),
|
|
204
|
+
reset
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
const [prevCount, currCount] = await Promise.all([
|
|
208
|
+
adapter.get(prevKey),
|
|
209
|
+
adapter.get(currentKey)
|
|
210
|
+
]);
|
|
211
|
+
const prev = prevCount ?? 0;
|
|
212
|
+
const curr = currCount ?? 0;
|
|
213
|
+
const estimated = prev * weight + curr;
|
|
214
|
+
if (estimated + cost <= limit) {
|
|
215
|
+
await adapter.set(currentKey, curr + cost, ttlMs);
|
|
216
|
+
return {
|
|
217
|
+
success: true,
|
|
218
|
+
limit,
|
|
219
|
+
remaining: Math.max(0, Math.floor(limit - (estimated + cost))),
|
|
220
|
+
reset
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
return {
|
|
224
|
+
success: false,
|
|
225
|
+
limit,
|
|
226
|
+
remaining: Math.max(0, Math.floor(limit - estimated)),
|
|
227
|
+
reset
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// src/algorithms/token-bucket.ts
|
|
234
|
+
var TOKEN_BUCKET_LUA = `
|
|
235
|
+
local raw = redis.call('GET', KEYS[1])
|
|
236
|
+
local capacity = tonumber(ARGV[1])
|
|
237
|
+
local refillRate = tonumber(ARGV[2])
|
|
238
|
+
local refillInterval = tonumber(ARGV[3])
|
|
239
|
+
local cost = tonumber(ARGV[4])
|
|
240
|
+
local now = tonumber(ARGV[5])
|
|
241
|
+
local ttl = tonumber(ARGV[6])
|
|
242
|
+
|
|
243
|
+
local tokens = capacity
|
|
244
|
+
local lastRefill = now
|
|
245
|
+
|
|
246
|
+
if raw then
|
|
247
|
+
local sep = string.find(raw, ':')
|
|
248
|
+
if sep then
|
|
249
|
+
tokens = tonumber(string.sub(raw, 1, sep - 1)) or capacity
|
|
250
|
+
lastRefill = tonumber(string.sub(raw, sep + 1)) or now
|
|
251
|
+
end
|
|
252
|
+
end
|
|
253
|
+
|
|
254
|
+
local elapsed = math.max(0, now - lastRefill)
|
|
255
|
+
local added = (elapsed / refillInterval) * refillRate
|
|
256
|
+
tokens = math.min(capacity, tokens + added)
|
|
257
|
+
|
|
258
|
+
if tokens >= cost then
|
|
259
|
+
local newTokens = tokens - cost
|
|
260
|
+
redis.call('SET', KEYS[1], tostring(newTokens) .. ':' .. tostring(now), 'PX', ttl)
|
|
261
|
+
local reset = now + math.ceil(((capacity - newTokens) / refillRate) * refillInterval)
|
|
262
|
+
return {1, math.floor(newTokens), reset}
|
|
263
|
+
else
|
|
264
|
+
local deficit = cost - tokens
|
|
265
|
+
local reset = now + math.ceil((deficit / refillRate) * refillInterval)
|
|
266
|
+
return {0, math.floor(tokens), reset}
|
|
267
|
+
end
|
|
268
|
+
`.trim();
|
|
269
|
+
function tokenBucket(config) {
|
|
270
|
+
if (!Number.isFinite(config.capacity) || config.capacity <= 0) {
|
|
271
|
+
throw new RangeError(`tokenBucket "capacity" must be a positive finite number, got ${config.capacity}.`);
|
|
272
|
+
}
|
|
273
|
+
if (!Number.isFinite(config.refillRate) || config.refillRate <= 0) {
|
|
274
|
+
throw new RangeError(
|
|
275
|
+
`tokenBucket "refillRate" must be a positive finite number, got ${config.refillRate}.`
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
const capacity = config.capacity;
|
|
279
|
+
const refillRate = config.refillRate;
|
|
280
|
+
const refillIntervalMs = parseDuration(config.refillInterval);
|
|
281
|
+
const ttlMs = Math.max(refillIntervalMs * 2, Math.ceil(capacity / refillRate * refillIntervalMs) * 2);
|
|
282
|
+
return {
|
|
283
|
+
name: "token-bucket",
|
|
284
|
+
maxLimit: capacity,
|
|
285
|
+
async consume(ctx) {
|
|
286
|
+
const { adapter, key, cost, now } = ctx;
|
|
287
|
+
const bucketKey = `${key}:tb`;
|
|
288
|
+
if (adapter.eval) {
|
|
289
|
+
const raw = await adapter.eval(
|
|
290
|
+
TOKEN_BUCKET_LUA,
|
|
291
|
+
[bucketKey],
|
|
292
|
+
[capacity, refillRate, refillIntervalMs, cost, now, ttlMs]
|
|
293
|
+
);
|
|
294
|
+
return {
|
|
295
|
+
success: raw[0] === 1,
|
|
296
|
+
limit: capacity,
|
|
297
|
+
remaining: Math.max(0, Number(raw[1] ?? 0)),
|
|
298
|
+
reset: Number(raw[2] ?? now)
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
const existing = await adapter.get(bucketKey);
|
|
302
|
+
let tokens = capacity;
|
|
303
|
+
if (existing) {
|
|
304
|
+
const elapsed = Math.max(0, now - existing.lastRefill);
|
|
305
|
+
const added = elapsed / refillIntervalMs * refillRate;
|
|
306
|
+
tokens = Math.min(capacity, existing.tokens + added);
|
|
307
|
+
}
|
|
308
|
+
if (tokens >= cost) {
|
|
309
|
+
const newTokens = tokens - cost;
|
|
310
|
+
await adapter.set(bucketKey, { tokens: newTokens, lastRefill: now }, ttlMs);
|
|
311
|
+
const reset2 = now + Math.ceil((capacity - newTokens) / refillRate * refillIntervalMs);
|
|
312
|
+
return {
|
|
313
|
+
success: true,
|
|
314
|
+
limit: capacity,
|
|
315
|
+
remaining: Math.max(0, Math.floor(newTokens)),
|
|
316
|
+
reset: reset2
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
const deficit = cost - tokens;
|
|
320
|
+
const reset = now + Math.ceil(deficit / refillRate * refillIntervalMs);
|
|
321
|
+
return {
|
|
322
|
+
success: false,
|
|
323
|
+
limit: capacity,
|
|
324
|
+
remaining: Math.max(0, Math.floor(tokens)),
|
|
325
|
+
reset
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
export { createRateLimiter, parseDuration, slidingWindow, tokenBucket };
|
|
332
|
+
//# sourceMappingURL=index.js.map
|
|
333
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/headers.ts","../src/limiter.ts","../src/utils/duration.ts","../src/algorithms/sliding-window.ts","../src/algorithms/token-bucket.ts"],"names":["reset"],"mappings":";AAKO,SAAS,qBAAA,CACd,QACA,GAAA,EACwB;AACxB,EAAA,MAAM,OAAA,GAAkC;AAAA,IACtC,mBAAA,EAAqB,MAAA,CAAO,MAAA,CAAO,KAAK,CAAA;AAAA,IACxC,uBAAA,EAAyB,MAAA,CAAO,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,KAAK,KAAA,CAAM,MAAA,CAAO,SAAS,CAAC,CAAC,CAAA;AAAA,IACzE,qBAAqB,MAAA,CAAO,IAAA,CAAK,KAAK,MAAA,CAAO,KAAA,GAAQ,GAAI,CAAC;AAAA,GAC5D;AAEA,EAAA,IAAI,CAAC,OAAO,OAAA,EAAS;AACnB,IAAA,MAAM,aAAA,GAAgB,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,IAAA,CAAK,MAAM,MAAA,CAAO,KAAA,GAAQ,GAAA,IAAO,GAAI,CAAC,CAAA;AACxE,IAAA,OAAA,CAAQ,aAAa,CAAA,GAAI,MAAA,CAAO,aAAa,CAAA;AAAA,EAC/C;AAEA,EAAA,OAAO,OAAA;AACT;;;ACMO,SAAS,kBAAkB,MAAA,EAAwC;AACxE,EAAA,IAAI,CAAC,MAAA,IAAU,CAAC,MAAA,CAAO,OAAA,EAAS;AAC9B,IAAA,MAAM,IAAI,UAAU,mDAAmD,CAAA;AAAA,EACzE;AACA,EAAA,IAAI,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,MAAA,MAAM,UAAU,IAAA,GAAO,MAAA;AACvB,MAAA,MAAM,QAAQ,GAAA,GAAM,IAAA,CAAK,IAAA,CAAM,OAAA,GAAU,aAAc,gBAAgB,CAAA;AACvE,MAAA,OAAO;AAAA,QACL,OAAA,EAAS,KAAA;AAAA,QACT,KAAA,EAAO,QAAA;AAAA,QACP,WAAW,IAAA,CAAK,GAAA,CAAI,GAAG,IAAA,CAAK,KAAA,CAAM,MAAM,CAAC,CAAA;AAAA,QACzC;AAAA,OACF;AAAA,IACF;AAAA,GACF;AACF","file":"index.js","sourcesContent":["import type { RateLimitResult } from '../types.js';\n\n/**\n * Build standard HTTP rate-limit response headers from a rate-limit outcome.\n */\nexport function buildRateLimitHeaders(\n result: Omit<RateLimitResult, 'headers'>,\n now: number,\n): Record<string, string> {\n const headers: Record<string, string> = {\n 'X-RateLimit-Limit': String(result.limit),\n 'X-RateLimit-Remaining': String(Math.max(0, Math.floor(result.remaining))),\n 'X-RateLimit-Reset': String(Math.ceil(result.reset / 1000)),\n };\n\n if (!result.success) {\n const retryAfterSec = Math.max(1, Math.ceil((result.reset - now) / 1000));\n headers['Retry-After'] = String(retryAfterSec);\n }\n\n return headers;\n}\n","import type {\n LimitOptions,\n RateLimiter,\n RateLimiterConfig,\n RateLimitResult,\n} from './types.js';\nimport { buildRateLimitHeaders } from './utils/headers.js';\n\n/**\n * Create a rate limiter instance configured with a storage adapter and algorithm.\n *\n * @example\n * ```ts\n * import { createRateLimiter, slidingWindow } from 'edge-throttle';\n * import { MemoryAdapter } from 'edge-throttle/adapters/memory';\n *\n * const limiter = createRateLimiter({\n * adapter: new MemoryAdapter(),\n * algorithm: slidingWindow({ limit: 100, window: '1m' }),\n * prefix: 'rl:api',\n * failOpen: true,\n * timeoutMs: 2000,\n * });\n *\n * const result = await limiter.limit('user_123');\n * ```\n */\nexport function createRateLimiter(config: RateLimiterConfig): RateLimiter {\n if (!config || !config.adapter) {\n throw new TypeError('createRateLimiter requires a \"adapter\" in config.');\n }\n if (!config.algorithm) {\n throw new TypeError('createRateLimiter requires an \"algorithm\" in config.');\n }\n if (config.timeoutMs !== undefined && (!Number.isFinite(config.timeoutMs) || config.timeoutMs <= 0)) {\n throw new RangeError(`createRateLimiter \"timeoutMs\" must be a positive finite number, got ${config.timeoutMs}.`);\n }\n\n const {\n adapter,\n algorithm,\n prefix = 'rl',\n failOpen = false,\n timeoutMs,\n onError,\n } = config;\n\n // Serialize in-process updates per key when the adapter does not support atomic Lua `eval`.\n const pendingLocks = new Map<string, Promise<void>>();\n\n async function withKeyLock<T>(key: string, fn: () => Promise<T>): Promise<T> {\n if (adapter.eval) {\n return fn();\n }\n\n const previous = pendingLocks.get(key) ?? Promise.resolve();\n let release!: () => void;\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n\n pendingLocks.set(key, current);\n\n try {\n await previous;\n return await fn();\n } finally {\n release();\n if (pendingLocks.get(key) === current) {\n pendingLocks.delete(key);\n }\n }\n }\n\n async function withTimeout<T>(promise: Promise<T>): Promise<T> {\n if (timeoutMs === undefined) {\n return promise;\n }\n\n let timerId: ReturnType<typeof setTimeout> | undefined;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timerId = setTimeout(() => {\n reject(new Error(`edge-throttle: storage operation timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n });\n\n try {\n return await Promise.race([promise, timeoutPromise]);\n } finally {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n }\n }\n\n return {\n async limit(identifier: string, options?: LimitOptions): Promise<RateLimitResult> {\n if (typeof identifier !== 'string' || identifier.length === 0) {\n throw new TypeError('limiter.limit() requires a non-empty string identifier.');\n }\n\n const cost = options?.cost ?? 1;\n if (!Number.isFinite(cost) || cost < 0) {\n throw new RangeError(`limiter.limit() \"cost\" must be a non-negative finite number, got ${cost}.`);\n }\n\n const key = prefix ? `${prefix}:${identifier}` : identifier;\n const now = Date.now();\n\n try {\n const outcome = await withTimeout(\n withKeyLock(key, () =>\n algorithm.consume({\n adapter,\n key,\n cost,\n now,\n }),\n ),\n );\n\n return {\n ...outcome,\n headers: buildRateLimitHeaders(outcome, now),\n };\n } catch (error) {\n onError?.(error, identifier);\n\n if (failOpen) {\n const fallback = {\n success: true,\n limit: algorithm.maxLimit,\n remaining: algorithm.maxLimit,\n reset: now,\n };\n return {\n ...fallback,\n headers: buildRateLimitHeaders(fallback, now),\n };\n }\n\n throw error;\n }\n },\n };\n}\n","import type { Duration, DurationUnit } from '../types.js';\n\nconst UNIT_MS: Record<DurationUnit, number> = {\n ms: 1,\n s: 1_000,\n m: 60_000,\n h: 3_600_000,\n d: 86_400_000,\n};\n\nconst DURATION_REGEX = /^(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h|d)$/i;\n\n/**\n * Parse a `Duration` (milliseconds number or string like `\"10s\"`, `\"1m\"`, `\"1h\"`)\n * into a positive number of milliseconds.\n *\n * @throws {RangeError} If the duration is invalid, non-finite, or `<= 0`.\n */\nexport function parseDuration(duration: Duration): number {\n if (typeof duration === 'number') {\n if (!Number.isFinite(duration) || duration <= 0) {\n throw new RangeError(`Invalid duration: ${String(duration)}. Expected a positive finite number.`);\n }\n return duration;\n }\n\n if (typeof duration === 'string') {\n const match = DURATION_REGEX.exec(duration.trim());\n if (!match) {\n throw new RangeError(\n `Invalid duration string: \"${duration}\". Expected format like \"500ms\", \"10s\", \"1m\", \"1h\", or \"1d\".`,\n );\n }\n\n const value = Number(match[1]);\n const unit = match[2]!.toLowerCase() as DurationUnit;\n const ms = value * UNIT_MS[unit];\n\n if (!Number.isFinite(ms) || ms <= 0) {\n throw new RangeError(`Invalid duration: \"${duration}\". Result must be > 0ms.`);\n }\n\n return ms;\n }\n\n throw new RangeError(`Invalid duration type: ${typeof duration}.`);\n}\n","import type { AlgorithmContext, Duration, RateLimitAlgorithm, RateLimitResult } from '../types.js';\nimport { parseDuration } from '../utils/duration.js';\n\n/**\n * Configuration options for the `slidingWindow` algorithm.\n */\nexport interface SlidingWindowConfig {\n /** Maximum number of requests (or weighted cost) allowed per rolling window. */\n limit: number;\n /** Window duration as milliseconds or a duration string (e.g., `\"10s\"`, `\"1m\"`, `\"1h\"`). */\n window: Duration;\n}\n\nconst SLIDING_WINDOW_LUA = `\nlocal curr = tonumber(redis.call('GET', KEYS[1]) or '0')\nlocal prev = tonumber(redis.call('GET', KEYS[2]) or '0')\nlocal limit = tonumber(ARGV[1])\nlocal cost = tonumber(ARGV[2])\nlocal weight = tonumber(ARGV[3])\nlocal ttl = tonumber(ARGV[4])\nlocal estimated = prev * weight + curr\nif estimated + cost <= limit then\n local newCurr = tonumber(redis.call('INCRBYFLOAT', KEYS[1], cost))\n if curr == 0 then\n redis.call('PEXPIRE', KEYS[1], ttl)\n end\n local rem = math.max(0, math.floor(limit - (estimated + cost)))\n return {1, rem}\nelse\n local rem = math.max(0, math.floor(limit - estimated))\n return {0, rem}\nend\n`.trim();\n\n/**\n * Create a weighted Sliding Window Counter rate-limiting algorithm.\n *\n * Uses two adjacent fixed windows (previous and current) weighted by the elapsed\n * fraction of the current window to prevent boundary bursts while keeping storage\n * overhead constant at 2 keys per identifier.\n */\nexport function slidingWindow(config: SlidingWindowConfig): RateLimitAlgorithm {\n if (!Number.isFinite(config.limit) || config.limit <= 0) {\n throw new RangeError(`slidingWindow \"limit\" must be a positive finite number, got ${config.limit}.`);\n }\n\n const limit = config.limit;\n const windowMs = parseDuration(config.window);\n const ttlMs = windowMs * 2;\n\n return {\n name: 'sliding-window',\n maxLimit: limit,\n\n async consume(ctx: AlgorithmContext): Promise<Omit<RateLimitResult, 'headers'>> {\n const { adapter, key, cost, now } = ctx;\n\n const currentWindow = Math.floor(now / windowMs);\n const prevWindow = currentWindow - 1;\n const elapsedMs = now - currentWindow * windowMs;\n const weight = (windowMs - elapsedMs) / windowMs;\n const reset = (currentWindow + 1) * windowMs;\n\n const currentKey = `${key}:${currentWindow}`;\n const prevKey = `${key}:${prevWindow}`;\n\n if (adapter.eval) {\n const raw = (await adapter.eval(\n SLIDING_WINDOW_LUA,\n [currentKey, prevKey],\n [limit, cost, weight, ttlMs],\n )) as [number, number];\n\n return {\n success: raw[0] === 1,\n limit,\n remaining: Math.max(0, Number(raw[1] ?? 0)),\n reset,\n };\n }\n\n const [prevCount, currCount] = await Promise.all([\n adapter.get<number>(prevKey),\n adapter.get<number>(currentKey),\n ]);\n\n const prev = prevCount ?? 0;\n const curr = currCount ?? 0;\n const estimated = prev * weight + curr;\n\n if (estimated + cost <= limit) {\n await adapter.set(currentKey, curr + cost, ttlMs);\n return {\n success: true,\n limit,\n remaining: Math.max(0, Math.floor(limit - (estimated + cost))),\n reset,\n };\n }\n\n return {\n success: false,\n limit,\n remaining: Math.max(0, Math.floor(limit - estimated)),\n reset,\n };\n },\n };\n}\n","import type { AlgorithmContext, Duration, RateLimitAlgorithm, RateLimitResult } from '../types.js';\nimport { parseDuration } from '../utils/duration.js';\n\n/**\n * Configuration options for the `tokenBucket` algorithm.\n */\nexport interface TokenBucketConfig {\n /** Maximum number of tokens the bucket can hold (burst size). */\n capacity: number;\n /** Number of tokens added per `refillInterval`. */\n refillRate: number;\n /** Refill interval as milliseconds or a duration string (e.g., `\"1s\"`, `\"1m\"`). */\n refillInterval: Duration;\n}\n\ninterface TokenBucketState {\n tokens: number;\n lastRefill: number;\n}\n\nconst TOKEN_BUCKET_LUA = `\nlocal raw = redis.call('GET', KEYS[1])\nlocal capacity = tonumber(ARGV[1])\nlocal refillRate = tonumber(ARGV[2])\nlocal refillInterval = tonumber(ARGV[3])\nlocal cost = tonumber(ARGV[4])\nlocal now = tonumber(ARGV[5])\nlocal ttl = tonumber(ARGV[6])\n\nlocal tokens = capacity\nlocal lastRefill = now\n\nif raw then\n local sep = string.find(raw, ':')\n if sep then\n tokens = tonumber(string.sub(raw, 1, sep - 1)) or capacity\n lastRefill = tonumber(string.sub(raw, sep + 1)) or now\n end\nend\n\nlocal elapsed = math.max(0, now - lastRefill)\nlocal added = (elapsed / refillInterval) * refillRate\ntokens = math.min(capacity, tokens + added)\n\nif tokens >= cost then\n local newTokens = tokens - cost\n redis.call('SET', KEYS[1], tostring(newTokens) .. ':' .. tostring(now), 'PX', ttl)\n local reset = now + math.ceil(((capacity - newTokens) / refillRate) * refillInterval)\n return {1, math.floor(newTokens), reset}\nelse\n local deficit = cost - tokens\n local reset = now + math.ceil((deficit / refillRate) * refillInterval)\n return {0, math.floor(tokens), reset}\nend\n`.trim();\n\n/**\n * Create a continuous-refill Token Bucket rate-limiting algorithm.\n *\n * Allows bursts up to `capacity` and refills smoothly at `refillRate` tokens\n * per `refillInterval`. Supports variable request costs via `limit(id, { cost })`.\n */\nexport function tokenBucket(config: TokenBucketConfig): RateLimitAlgorithm {\n if (!Number.isFinite(config.capacity) || config.capacity <= 0) {\n throw new RangeError(`tokenBucket \"capacity\" must be a positive finite number, got ${config.capacity}.`);\n }\n if (!Number.isFinite(config.refillRate) || config.refillRate <= 0) {\n throw new RangeError(\n `tokenBucket \"refillRate\" must be a positive finite number, got ${config.refillRate}.`,\n );\n }\n\n const capacity = config.capacity;\n const refillRate = config.refillRate;\n const refillIntervalMs = parseDuration(config.refillInterval);\n const ttlMs = Math.max(refillIntervalMs * 2, Math.ceil((capacity / refillRate) * refillIntervalMs) * 2);\n\n return {\n name: 'token-bucket',\n maxLimit: capacity,\n\n async consume(ctx: AlgorithmContext): Promise<Omit<RateLimitResult, 'headers'>> {\n const { adapter, key, cost, now } = ctx;\n const bucketKey = `${key}:tb`;\n\n if (adapter.eval) {\n const raw = (await adapter.eval(\n TOKEN_BUCKET_LUA,\n [bucketKey],\n [capacity, refillRate, refillIntervalMs, cost, now, ttlMs],\n )) as [number, number, number];\n\n return {\n success: raw[0] === 1,\n limit: capacity,\n remaining: Math.max(0, Number(raw[1] ?? 0)),\n reset: Number(raw[2] ?? now),\n };\n }\n\n const existing = await adapter.get<TokenBucketState>(bucketKey);\n let tokens = capacity;\n if (existing) {\n const elapsed = Math.max(0, now - existing.lastRefill);\n const added = (elapsed / refillIntervalMs) * refillRate;\n tokens = Math.min(capacity, existing.tokens + added);\n }\n\n if (tokens >= cost) {\n const newTokens = tokens - cost;\n await adapter.set<TokenBucketState>(bucketKey, { tokens: newTokens, lastRefill: now }, ttlMs);\n const reset = now + Math.ceil(((capacity - newTokens) / refillRate) * refillIntervalMs);\n return {\n success: true,\n limit: capacity,\n remaining: Math.max(0, Math.floor(newTokens)),\n reset,\n };\n }\n\n const deficit = cost - tokens;\n const reset = now + Math.ceil((deficit / refillRate) * refillIntervalMs);\n return {\n success: false,\n limit: capacity,\n remaining: Math.max(0, Math.floor(tokens)),\n reset,\n };\n },\n };\n}\n"]}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Supported duration units for rate-limit windows and refill intervals.
|
|
3
|
+
*/
|
|
4
|
+
type DurationUnit = 'ms' | 's' | 'm' | 'h' | 'd';
|
|
5
|
+
/**
|
|
6
|
+
* Duration value specified either as milliseconds (`number`) or a human-readable
|
|
7
|
+
* duration string (e.g., `"500ms"`, `"10s"`, `"1m"`, `"2h"`, `"1d"`).
|
|
8
|
+
*/
|
|
9
|
+
type Duration = number | `${number}${DurationUnit}`;
|
|
10
|
+
/**
|
|
11
|
+
* Pluggable storage backend interface for `edge-throttle`.
|
|
12
|
+
* Implement this interface to integrate any custom key-value store or database.
|
|
13
|
+
*/
|
|
14
|
+
interface StorageAdapter {
|
|
15
|
+
/**
|
|
16
|
+
* Retrieve a stored value by key.
|
|
17
|
+
* Returns `null` if the key does not exist or has expired.
|
|
18
|
+
*/
|
|
19
|
+
get<T>(key: string): Promise<T | null>;
|
|
20
|
+
/**
|
|
21
|
+
* Store a value under `key` with a time-to-live in milliseconds.
|
|
22
|
+
*/
|
|
23
|
+
set<T>(key: string, value: T, ttlMs: number): Promise<void>;
|
|
24
|
+
/**
|
|
25
|
+
* Atomically increment a numeric key by `amount` and ensure its TTL is set to `ttlMs`.
|
|
26
|
+
* Optional; adapters that do not implement this will fall back to `get`/`set`.
|
|
27
|
+
*/
|
|
28
|
+
increment?(key: string, amount: number, ttlMs: number): Promise<number>;
|
|
29
|
+
/**
|
|
30
|
+
* Execute an atomic Lua script against the storage backend (e.g., Redis / Upstash).
|
|
31
|
+
* Optional; algorithms use this when available to guarantee race-free atomic updates.
|
|
32
|
+
*/
|
|
33
|
+
eval?(script: string, keys: string[], args: (string | number)[]): Promise<unknown>;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Options passed to `limiter.limit()`.
|
|
37
|
+
*/
|
|
38
|
+
interface LimitOptions {
|
|
39
|
+
/**
|
|
40
|
+
* Number of tokens or request weight to consume for this call.
|
|
41
|
+
* @default 1
|
|
42
|
+
*/
|
|
43
|
+
cost?: number;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Result returned by `limiter.limit()`.
|
|
47
|
+
*/
|
|
48
|
+
interface RateLimitResult {
|
|
49
|
+
/** Whether the request is allowed (`true`) or rate-limited (`false`). */
|
|
50
|
+
success: boolean;
|
|
51
|
+
/** Maximum number of requests or tokens allowed in the configured window/bucket. */
|
|
52
|
+
limit: number;
|
|
53
|
+
/** Remaining requests or tokens available after this call. */
|
|
54
|
+
remaining: number;
|
|
55
|
+
/** Unix epoch timestamp in milliseconds when the limit resets or the bucket refills. */
|
|
56
|
+
reset: number;
|
|
57
|
+
/**
|
|
58
|
+
* Standard HTTP rate-limit headers (`X-RateLimit-Limit`, `X-RateLimit-Remaining`,
|
|
59
|
+
* `X-RateLimit-Reset`, and `Retry-After` when `success` is `false`).
|
|
60
|
+
*/
|
|
61
|
+
headers: Record<string, string>;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Internal execution context passed to rate-limiting algorithms.
|
|
65
|
+
*/
|
|
66
|
+
interface AlgorithmContext {
|
|
67
|
+
adapter: StorageAdapter;
|
|
68
|
+
key: string;
|
|
69
|
+
cost: number;
|
|
70
|
+
now: number;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Rate-limiting algorithm contract implemented by `slidingWindow` and `tokenBucket`.
|
|
74
|
+
*/
|
|
75
|
+
interface RateLimitAlgorithm {
|
|
76
|
+
/** Algorithm identifier. */
|
|
77
|
+
readonly name: string;
|
|
78
|
+
/** Maximum capacity / limit exposed in `RateLimitResult.limit`. */
|
|
79
|
+
readonly maxLimit: number;
|
|
80
|
+
/** Evaluate and consume `ctx.cost` units for `ctx.key` at timestamp `ctx.now`. */
|
|
81
|
+
consume(ctx: AlgorithmContext): Promise<Omit<RateLimitResult, 'headers'>>;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Configuration options for `createRateLimiter()`.
|
|
85
|
+
*/
|
|
86
|
+
interface RateLimiterConfig {
|
|
87
|
+
/** Storage adapter instance used to persist rate-limit state. */
|
|
88
|
+
adapter: StorageAdapter;
|
|
89
|
+
/** Rate-limiting algorithm instance (`slidingWindow` or `tokenBucket`). */
|
|
90
|
+
algorithm: RateLimitAlgorithm;
|
|
91
|
+
/**
|
|
92
|
+
* Key prefix used to namespace rate-limit keys in storage.
|
|
93
|
+
* @default "rl"
|
|
94
|
+
*/
|
|
95
|
+
prefix?: string;
|
|
96
|
+
/**
|
|
97
|
+
* When `true`, requests are allowed if the storage backend throws an error or times out.
|
|
98
|
+
* @default false
|
|
99
|
+
*/
|
|
100
|
+
failOpen?: boolean;
|
|
101
|
+
/**
|
|
102
|
+
* Optional timeout in milliseconds for storage operations.
|
|
103
|
+
* If exceeded, the operation rejects with a timeout error (which triggers `failOpen` if enabled).
|
|
104
|
+
*/
|
|
105
|
+
timeoutMs?: number;
|
|
106
|
+
/**
|
|
107
|
+
* Optional error hook invoked whenever a storage error or timeout occurs.
|
|
108
|
+
*/
|
|
109
|
+
onError?: (error: unknown, identifier: string) => void;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Rate limiter instance returned by `createRateLimiter()`.
|
|
113
|
+
*/
|
|
114
|
+
interface RateLimiter {
|
|
115
|
+
/**
|
|
116
|
+
* Check and consume rate-limit capacity for the given `identifier` (e.g., user ID, IP, API key).
|
|
117
|
+
*/
|
|
118
|
+
limit(identifier: string, options?: LimitOptions): Promise<RateLimitResult>;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export type { AlgorithmContext as A, Duration as D, LimitOptions as L, RateLimiterConfig as R, StorageAdapter as S, RateLimiter as a, RateLimitAlgorithm as b, DurationUnit as c, RateLimitResult as d };
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Supported duration units for rate-limit windows and refill intervals.
|
|
3
|
+
*/
|
|
4
|
+
type DurationUnit = 'ms' | 's' | 'm' | 'h' | 'd';
|
|
5
|
+
/**
|
|
6
|
+
* Duration value specified either as milliseconds (`number`) or a human-readable
|
|
7
|
+
* duration string (e.g., `"500ms"`, `"10s"`, `"1m"`, `"2h"`, `"1d"`).
|
|
8
|
+
*/
|
|
9
|
+
type Duration = number | `${number}${DurationUnit}`;
|
|
10
|
+
/**
|
|
11
|
+
* Pluggable storage backend interface for `edge-throttle`.
|
|
12
|
+
* Implement this interface to integrate any custom key-value store or database.
|
|
13
|
+
*/
|
|
14
|
+
interface StorageAdapter {
|
|
15
|
+
/**
|
|
16
|
+
* Retrieve a stored value by key.
|
|
17
|
+
* Returns `null` if the key does not exist or has expired.
|
|
18
|
+
*/
|
|
19
|
+
get<T>(key: string): Promise<T | null>;
|
|
20
|
+
/**
|
|
21
|
+
* Store a value under `key` with a time-to-live in milliseconds.
|
|
22
|
+
*/
|
|
23
|
+
set<T>(key: string, value: T, ttlMs: number): Promise<void>;
|
|
24
|
+
/**
|
|
25
|
+
* Atomically increment a numeric key by `amount` and ensure its TTL is set to `ttlMs`.
|
|
26
|
+
* Optional; adapters that do not implement this will fall back to `get`/`set`.
|
|
27
|
+
*/
|
|
28
|
+
increment?(key: string, amount: number, ttlMs: number): Promise<number>;
|
|
29
|
+
/**
|
|
30
|
+
* Execute an atomic Lua script against the storage backend (e.g., Redis / Upstash).
|
|
31
|
+
* Optional; algorithms use this when available to guarantee race-free atomic updates.
|
|
32
|
+
*/
|
|
33
|
+
eval?(script: string, keys: string[], args: (string | number)[]): Promise<unknown>;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Options passed to `limiter.limit()`.
|
|
37
|
+
*/
|
|
38
|
+
interface LimitOptions {
|
|
39
|
+
/**
|
|
40
|
+
* Number of tokens or request weight to consume for this call.
|
|
41
|
+
* @default 1
|
|
42
|
+
*/
|
|
43
|
+
cost?: number;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Result returned by `limiter.limit()`.
|
|
47
|
+
*/
|
|
48
|
+
interface RateLimitResult {
|
|
49
|
+
/** Whether the request is allowed (`true`) or rate-limited (`false`). */
|
|
50
|
+
success: boolean;
|
|
51
|
+
/** Maximum number of requests or tokens allowed in the configured window/bucket. */
|
|
52
|
+
limit: number;
|
|
53
|
+
/** Remaining requests or tokens available after this call. */
|
|
54
|
+
remaining: number;
|
|
55
|
+
/** Unix epoch timestamp in milliseconds when the limit resets or the bucket refills. */
|
|
56
|
+
reset: number;
|
|
57
|
+
/**
|
|
58
|
+
* Standard HTTP rate-limit headers (`X-RateLimit-Limit`, `X-RateLimit-Remaining`,
|
|
59
|
+
* `X-RateLimit-Reset`, and `Retry-After` when `success` is `false`).
|
|
60
|
+
*/
|
|
61
|
+
headers: Record<string, string>;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Internal execution context passed to rate-limiting algorithms.
|
|
65
|
+
*/
|
|
66
|
+
interface AlgorithmContext {
|
|
67
|
+
adapter: StorageAdapter;
|
|
68
|
+
key: string;
|
|
69
|
+
cost: number;
|
|
70
|
+
now: number;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Rate-limiting algorithm contract implemented by `slidingWindow` and `tokenBucket`.
|
|
74
|
+
*/
|
|
75
|
+
interface RateLimitAlgorithm {
|
|
76
|
+
/** Algorithm identifier. */
|
|
77
|
+
readonly name: string;
|
|
78
|
+
/** Maximum capacity / limit exposed in `RateLimitResult.limit`. */
|
|
79
|
+
readonly maxLimit: number;
|
|
80
|
+
/** Evaluate and consume `ctx.cost` units for `ctx.key` at timestamp `ctx.now`. */
|
|
81
|
+
consume(ctx: AlgorithmContext): Promise<Omit<RateLimitResult, 'headers'>>;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Configuration options for `createRateLimiter()`.
|
|
85
|
+
*/
|
|
86
|
+
interface RateLimiterConfig {
|
|
87
|
+
/** Storage adapter instance used to persist rate-limit state. */
|
|
88
|
+
adapter: StorageAdapter;
|
|
89
|
+
/** Rate-limiting algorithm instance (`slidingWindow` or `tokenBucket`). */
|
|
90
|
+
algorithm: RateLimitAlgorithm;
|
|
91
|
+
/**
|
|
92
|
+
* Key prefix used to namespace rate-limit keys in storage.
|
|
93
|
+
* @default "rl"
|
|
94
|
+
*/
|
|
95
|
+
prefix?: string;
|
|
96
|
+
/**
|
|
97
|
+
* When `true`, requests are allowed if the storage backend throws an error or times out.
|
|
98
|
+
* @default false
|
|
99
|
+
*/
|
|
100
|
+
failOpen?: boolean;
|
|
101
|
+
/**
|
|
102
|
+
* Optional timeout in milliseconds for storage operations.
|
|
103
|
+
* If exceeded, the operation rejects with a timeout error (which triggers `failOpen` if enabled).
|
|
104
|
+
*/
|
|
105
|
+
timeoutMs?: number;
|
|
106
|
+
/**
|
|
107
|
+
* Optional error hook invoked whenever a storage error or timeout occurs.
|
|
108
|
+
*/
|
|
109
|
+
onError?: (error: unknown, identifier: string) => void;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Rate limiter instance returned by `createRateLimiter()`.
|
|
113
|
+
*/
|
|
114
|
+
interface RateLimiter {
|
|
115
|
+
/**
|
|
116
|
+
* Check and consume rate-limit capacity for the given `identifier` (e.g., user ID, IP, API key).
|
|
117
|
+
*/
|
|
118
|
+
limit(identifier: string, options?: LimitOptions): Promise<RateLimitResult>;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export type { AlgorithmContext as A, Duration as D, LimitOptions as L, RateLimiterConfig as R, StorageAdapter as S, RateLimiter as a, RateLimitAlgorithm as b, DurationUnit as c, RateLimitResult as d };
|