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:
chrnx committed 2026-09-18 13:18:26 -05:00
1 parent b15ce29315
commit 66afb59103
3 files changed
+207

No files matched your search

@@ -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());
});