feat(rate-limit): sweep expired windows instead of walking the map
hit() called evictExpired on every new or expired key, which is a full walk of the map — O(N^2) over N callers, and a client rotating addresses drives it on purpose. A timer armed on the first hit does the same work off the hot path. It is not unref'ed, deliberately: the timer holds the process open so that failing to release it fails the exit test rather than leaking quietly. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
3 files changed
+207
No files matched your search
@@ -0,0 +1,80 @@
|
||||
import type { RateLimitHit, RateLimitStore } from './types.ts';
|
||||
|
||||
/** Fallback sweep period, for a store built without rules to derive one from. */
|
||||
const DEFAULT_SWEEP_MS = 60_000;
|
||||
|
||||
/**
|
||||
* Fixed-window counters held in this process.
|
||||
*
|
||||
* **One process, one set of counters.** Two replicas each enforce the limit separately, so the
|
||||
* effective ceiling is `max × replicas`. Implement `RateLimitStore` against Redis to share them.
|
||||
*
|
||||
* Expired windows are dropped by a timer rather than on the hot path. The version this replaces
|
||||
* walked the entire map from inside `hit()` whenever a key was new or expired — O(N²) over N
|
||||
* distinct callers, and a client rotating addresses drove it deliberately.
|
||||
*/
|
||||
export class MemoryStore implements RateLimitStore {
|
||||
private readonly windows = new Map<string, RateLimitHit>();
|
||||
private readonly sweepMs: number;
|
||||
private timer: ReturnType<typeof setInterval> | undefined;
|
||||
|
||||
constructor(options: { sweepMs?: number } = {}) {
|
||||
this.sweepMs = options.sweepMs ?? DEFAULT_SWEEP_MS;
|
||||
}
|
||||
|
||||
/** How many windows are held. Lets a test assert the sweep without reaching inside. */
|
||||
get size(): number {
|
||||
return this.windows.size;
|
||||
}
|
||||
|
||||
hit(key: string, windowMs: number): RateLimitHit {
|
||||
this.start();
|
||||
const now = Date.now();
|
||||
const current = this.windows.get(key);
|
||||
|
||||
if (!current || current.resetAt <= now) {
|
||||
const fresh: RateLimitHit = { count: 1, resetAt: now + windowMs };
|
||||
this.windows.set(key, fresh);
|
||||
|
||||
return fresh;
|
||||
}
|
||||
|
||||
current.count += 1;
|
||||
|
||||
return current;
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this.windows.clear();
|
||||
}
|
||||
|
||||
/** Stops the sweep. Safe to call twice — `close()` is reached more than once in real apps. */
|
||||
close(): void {
|
||||
if (!this.timer) return;
|
||||
|
||||
clearInterval(this.timer);
|
||||
this.timer = undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Arms the sweep on the first hit, not in the constructor.
|
||||
*
|
||||
* A store built and never used holds nothing, and starting a timer for it would keep a process
|
||||
* alive over an empty map. Deliberately **not** `unref`ed: the timer is meant to hold the process
|
||||
* open, so that failing to release it is a visible bug rather than a silent leak, and so that all
|
||||
* three runtimes behave the same.
|
||||
*/
|
||||
private start(): void {
|
||||
if (this.timer) return;
|
||||
|
||||
this.timer = setInterval(() => this.sweep(), this.sweepMs);
|
||||
}
|
||||
|
||||
private sweep(): void {
|
||||
const now = Date.now();
|
||||
|
||||
for (const [key, window] of this.windows) {
|
||||
if (window.resetAt <= now) this.windows.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/** A single named limit: how many hits are allowed inside a window. */
|
||||
export interface RateLimitRule {
|
||||
/** Window length in milliseconds. */
|
||||
windowMs: number;
|
||||
/** Maximum hits allowed per key inside the window. */
|
||||
max: number;
|
||||
/** Message returned in the 429 body. */
|
||||
message: string;
|
||||
}
|
||||
|
||||
/** What a store reports back for one hit. */
|
||||
export interface RateLimitHit {
|
||||
/** Hits recorded for this key inside the current window, including this one. */
|
||||
count: number;
|
||||
/** Epoch milliseconds at which the current window expires. */
|
||||
resetAt: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pluggable counter backend. The default is in-process memory; swap in Redis or Postgres by
|
||||
* implementing this and passing it to `rateLimit({ store })`.
|
||||
*/
|
||||
export interface RateLimitStore {
|
||||
/** Record one hit against `key` and return the resulting window state. */
|
||||
hit(key: string, windowMs: number): Promise<RateLimitHit> | RateLimitHit;
|
||||
/** Drop every counter. Used by tests and by operators clearing a lockout. */
|
||||
reset(): Promise<void> | void;
|
||||
/**
|
||||
* Release whatever the store holds open. Optional: a store that holds nothing needs none, and the
|
||||
* plugin's `onShutdown` calls it only if it exists.
|
||||
*/
|
||||
close?(): Promise<void> | void;
|
||||
}
|
||||
|
||||
/** The function a handler receives from `@needs('rateLimit')`. */
|
||||
export type RateLimiter = (rule: string, override?: Partial<RateLimitRule>) => Promise<void>;
|
||||
|
||||
/** The slice of the green-tea request context this plugin reads. */
|
||||
export interface RateLimitContext {
|
||||
ip?: string;
|
||||
headers?: Record<string, string | string[] | undefined>;
|
||||
}
|
||||
|
||||
export interface RateLimitOptions {
|
||||
/** Named rules, addressed by handlers as `limit('signin')`. */
|
||||
rules: Record<string, RateLimitRule>;
|
||||
/** Counter backend. Defaults to an in-process `MemoryStore`. */
|
||||
store?: RateLimitStore;
|
||||
/**
|
||||
* Derives the per-caller bucket from the request context. Defaults to `ctx.ip`.
|
||||
*
|
||||
* Returning `null` skips the limit for that request — use it to exempt health checks. Note that
|
||||
* `ctx.ip` is empty when the app is driven through `app.fetch()` rather than a socket, so the
|
||||
* default folds those into a single `unknown` bucket.
|
||||
*/
|
||||
keyOf?: (ctx: RateLimitContext) => string | null;
|
||||
/** Graph name the limiter is published under, and the plugin's name. Defaults to `rateLimit`. */
|
||||
provides?: string;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { strict as assert } from 'node:assert';
|
||||
import { test } from 'node:test';
|
||||
|
||||
import { MemoryStore } from '../src/memory-store.ts';
|
||||
|
||||
const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
test('counts hits inside a window and starts a new one after it expires', async () => {
|
||||
const store = new MemoryStore();
|
||||
|
||||
try {
|
||||
assert.equal(store.hit('a', 40).count, 1);
|
||||
assert.equal(store.hit('a', 40).count, 2);
|
||||
await sleep(60);
|
||||
assert.equal(store.hit('a', 40).count, 1);
|
||||
} finally {
|
||||
store.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('keeps separate counters per key', () => {
|
||||
const store = new MemoryStore();
|
||||
|
||||
try {
|
||||
store.hit('a', 1000);
|
||||
assert.equal(store.hit('b', 1000).count, 1);
|
||||
assert.equal(store.hit('a', 1000).count, 2);
|
||||
} finally {
|
||||
store.close();
|
||||
}
|
||||
});
|
||||
|
||||
// The defect this store replaces: `hit()` walked the whole map whenever a key was new or expired,
|
||||
// so N distinct callers cost N², and a client rotating addresses triggered it on purpose. The sweep
|
||||
// is what keeps the map bounded now, so it has to actually drop things.
|
||||
test('sweeps expired windows without being asked on the hot path', async () => {
|
||||
const store = new MemoryStore({ sweepMs: 20 });
|
||||
|
||||
try {
|
||||
for (let i = 0; i < 50; i++) store.hit(`caller-${i}`, 10);
|
||||
assert.equal(store.size, 50);
|
||||
await sleep(80);
|
||||
assert.equal(store.size, 0, 'expired windows were never swept');
|
||||
} finally {
|
||||
store.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('reset drops every counter', () => {
|
||||
const store = new MemoryStore();
|
||||
|
||||
try {
|
||||
store.hit('a', 1000);
|
||||
store.reset();
|
||||
assert.equal(store.size, 0);
|
||||
} finally {
|
||||
store.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('close is idempotent, because close() is called more than once in real apps', () => {
|
||||
const store = new MemoryStore();
|
||||
store.hit('a', 1000);
|
||||
|
||||
store.close();
|
||||
|
||||
assert.doesNotThrow(() => store.close());
|
||||
});
|
||||
Reference in new issue
Block a user