-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathratelimit.js
More file actions
44 lines (41 loc) · 1.66 KB
/
Copy pathratelimit.js
File metadata and controls
44 lines (41 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Fixed-window per-key failure counter. In-memory, single-process — pairs with a
// CDN/edge limiter (see docs/deploy.md), it is not a substitute for one. Only
// failures consume budget; a successful auth never counts against a key.
export function createRateLimiter({ windowMs, max, sweepMs = 60_000, maxEntries = 10_000 }) {
const hits = new Map(); // key -> { count, resetAt }
let lastSweep = 0;
function sweep(now) {
if (now - lastSweep < sweepMs) return;
lastSweep = now;
for (const [k, v] of hits) if (v.resetAt <= now) hits.delete(k);
// Hard cap so the limiter itself cannot be turned into a memory DoS.
if (hits.size > maxEntries) {
let excess = hits.size - maxEntries;
for (const k of hits.keys()) {
if (excess-- <= 0) break;
hits.delete(k);
}
}
}
function record(key, now = Date.now()) {
const e = hits.get(key);
if (e && e.resetAt > now) e.count++;
else hits.set(key, { count: 1, resetAt: now + windowMs });
}
return {
check(key, now = Date.now()) {
sweep(now);
const e = hits.get(key);
if (e && e.resetAt > now && e.count >= max) {
return { limited: true, retryAfter: Math.ceil((e.resetAt - now) / 1000) };
}
return { limited: false, retryAfter: 0 };
},
// One counter, two names. The login and unlock gates spend budget only on a failure, so
// `fail` reads right there. The publish gate spends it on every large body, because what it
// is capping is the memory the body costs, which a request that goes on to succeed costs
// too; `count` says that without pretending a publish failed.
fail: record,
count: record,
};
}