feat(rate-limit): publish the limiter as a named plugin

Extracted from patitas-peludas onto the object contract. The node now takes the
name it provides — the original registered 'rate-limit' while providing
'rateLimit', so two instances shared a node name and rule 2 could not hold.

onShutdown closes the store this plugin built. One passed in owns its own
lifecycle, and is closed only if it offers a close().

Every test that builds an app closes it, through a helper that says why: the
sweep timer is deliberately not unref'ed, so an app left open keeps the test
runner alive after its assertions have passed. That is the same behaviour the
exit test measures, so these exercise the shutdown path in passing.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-09-18 13:22:45 -05:00
1 parent 14ed9c38be
commit 8ac46fed61
2 files changed
+221

No files matched your search

+96
View File
@@ -0,0 +1,96 @@
import type { Plugin } from '@green-tea/core';
import { TooManyRequests } from './errors.ts';
import { MemoryStore } from './memory-store.ts';
import type { RateLimitContext, RateLimiter, RateLimitOptions, RateLimitRule } from './types.ts';
export { MemoryStore } from './memory-store.ts';
export { TooManyRequests } from './errors.ts';
export type {
RateLimitContext,
RateLimiter,
RateLimitHit,
RateLimitOptions,
RateLimitRule,
RateLimitStore,
} from './types.ts';
function defaultKeyOf(ctx: RateLimitContext): string {
return ctx.ip !== undefined && ctx.ip !== '' ? ctx.ip : 'unknown';
}
/**
* The sweep period for a store this plugin builds: the shortest window any rule configures.
*
* Sweeping less often than the shortest window would let a generation of expired counters sit in the
* map for longer than they can possibly be useful, which is the growth the sweep exists to bound.
*/
function sweepPeriod(rules: Record<string, RateLimitRule>): number | undefined {
const windows = Object.values(rules).map((rule) => rule.windowMs);
return windows.length ? Math.min(...windows) : undefined;
}
/**
* Publishes a per-request rate limiter into the graph.
*
* Rules live in one place; a handler opts in by asking for the limiter and naming a rule. Nothing is
* enforced on routes that do not ask — green-tea runs a step only for the routes that depend on it —
* so the limit is visible in the handler's signature rather than hidden in a middleware chain.
*
* The default store holds a sweep timer, which this releases in `onShutdown` (convention rule 7). A
* store passed in owns its own lifecycle, and is closed only if it offers a `close()`.
*
* @example
* const app = createApp({
* modules: [AuthModule],
* plugins: [rateLimit({ rules: { signin: { windowMs: 900_000, max: 5, message: 'too many' } } })],
* });
*
* @example <caption>In a handler.</caption>
* ⁣@Post('/signin')
* async signIn(@needs('rateLimit') limit: RateLimiter) {
* await limit('signin');
* }
*/
export function rateLimit(options: RateLimitOptions): Plugin {
const provides = options.provides ?? 'rateLimit';
const store = options.store ?? new MemoryStore({ sweepMs: sweepPeriod(options.rules) });
const keyOf = options.keyOf ?? defaultKeyOf;
const limiterFor = (ctx: RateLimitContext): RateLimiter => {
return async (name, override) => {
const configured = options.rules[name];
if (!configured) throw new Error(`Unknown rate limit rule: "${name}"`);
const rule: RateLimitRule = { ...configured, ...override };
const bucket = keyOf(ctx);
if (bucket === null) return;
const { count, resetAt } = await store.hit(`${bucket}:${name}`, rule.windowMs);
if (count > rule.max) {
throw new TooManyRequests(rule.message, Math.max(1, Math.ceil((resetAt - Date.now()) / 1000)));
}
};
};
return {
// Rule 2: plugin name, node name and provided token are one string. The original registered the
// node as 'rate-limit' while providing 'rateLimit', so two instances shared a node name.
name: provides,
mount({ scope, onShutdown }) {
scope.add({
kind: 'step',
name: provides,
// `ip` and `headers` ride on the seed context rather than being graph nodes, so `req` is the
// only declarable dependency here.
needs: ['req'],
provides: [provides],
run: (ctx: RateLimitContext) => ({ [provides]: limiterFor(ctx) }),
});
onShutdown(() => store.close?.());
},
};
}
+125
View File
@@ -1,7 +1,13 @@
import { strict as assert } from 'node:assert'; import { strict as assert } from 'node:assert';
import { test } from 'node:test'; import { test } from 'node:test';
import { createApp } from '@green-tea/core';
import type { App } from '@green-tea/core';
import { probeModule } from '../../../test/helpers.ts';
import { TooManyRequests } from '../src/errors.ts'; import { TooManyRequests } from '../src/errors.ts';
import { rateLimit } from '../src/index.ts';
import type { RateLimiter } from '../src/index.ts';
import { MemoryStore } from '../src/memory-store.ts'; import { MemoryStore } from '../src/memory-store.ts';
const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms)); const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
@@ -82,3 +88,122 @@ test('carries the brand core recognises, and the fields core reads off it', () =
// Still an Error: a throw that is not one loses the stack, and core rethrows before rendering. // Still an Error: a throw that is not one loses the stack, and core rethrows before rendering.
assert.ok(error instanceof Error); assert.ok(error instanceof Error);
}); });
const RULES = { signin: { windowMs: 60_000, max: 2, message: 'too many' } };
/**
* Runs `body` against `app` and always closes it.
*
* Closing is not housekeeping here. The default store's sweep timer is deliberately not `unref`ed —
* that is what makes the exit test in this file mean something — so an app left open keeps the test
* runner alive long after its assertions passed. `close()` runs the plugin's `onShutdown`, which is
* the same path the exit test measures, so every test here exercises it in passing.
*/
async function withApp(app: App, body: () => Promise<void>): Promise<void> {
try {
await body();
} finally {
await app.close();
}
}
test('allows up to the limit and then answers 429 with retry-after', async () => {
const app = createApp({
modules: [
probeModule('rateLimit', async (limit: RateLimiter) => {
await limit('signin');
return 'ok';
}),
],
plugins: [rateLimit({ rules: RULES, keyOf: () => 'one-caller' })],
});
await withApp(app, async () => {
const hit = () => app.fetch(new Request('http://plugin.test/rateLimit/probe'));
assert.equal((await hit()).status, 200);
assert.equal((await hit()).status, 200);
const refused = await hit();
assert.equal(refused.status, 429);
assert.ok(Number(refused.headers.get('retry-after')) >= 1);
});
});
test('keeps separate budgets per caller', async () => {
let caller = 'a';
const app = createApp({
modules: [
probeModule('rateLimit', async (limit: RateLimiter) => {
await limit('signin');
return 'ok';
}),
],
plugins: [rateLimit({ rules: RULES, keyOf: () => caller })],
});
await withApp(app, async () => {
const hit = () => app.fetch(new Request('http://plugin.test/rateLimit/probe'));
await hit();
await hit();
assert.equal((await hit()).status, 429);
caller = 'b';
assert.equal((await hit()).status, 200);
});
});
test('a keyOf returning null exempts the request entirely', async () => {
const app = createApp({
modules: [
probeModule('rateLimit', async (limit: RateLimiter) => {
await limit('signin');
return 'ok';
}),
],
plugins: [rateLimit({ rules: RULES, keyOf: () => null })],
});
await withApp(app, async () => {
for (let i = 0; i < 5; i++) {
assert.equal((await app.fetch(new Request('http://plugin.test/rateLimit/probe'))).status, 200);
}
});
});
test('names an unknown rule rather than silently allowing it', async () => {
const app = createApp({
modules: [
probeModule('rateLimit', async (limit: RateLimiter) => {
await limit('nope');
return 'ok';
}),
],
plugins: [rateLimit({ rules: RULES })],
});
await withApp(app, async () => {
assert.equal((await app.fetch(new Request('http://plugin.test/rateLimit/probe'))).status, 500);
});
});
// Convention rule 2: the plugin's name, the node's name and the provided token are one string, so
// two instances collide on none of the three.
test('two instances with different provides both answer, without colliding', async () => {
const app = createApp({
modules: [probeModule('userLimit', () => 'user'), probeModule('adminLimit', () => 'admin')],
plugins: [rateLimit({ rules: RULES, provides: 'userLimit' }), rateLimit({ rules: RULES, provides: 'adminLimit' })],
});
await withApp(app, async () => {
assert.equal((await app.fetch(new Request('http://plugin.test/userLimit/probe'))).status, 200);
assert.equal((await app.fetch(new Request('http://plugin.test/adminLimit/probe'))).status, 200);
});
});
test('the plugin is named after what it provides', () => {
assert.equal(rateLimit({ rules: RULES }).name, 'rateLimit');
assert.equal(rateLimit({ rules: RULES, provides: 'adminLimit' }).name, 'adminLimit');
});