Merge pull request 'feat: rate-limit and metrics plugins' (#2) from feature/rate-limit-metrics into develop
CI / dco (push) Has been skipped
CI / build (push) Successful in 13s
CI / runtimes (bun) (push) Successful in 12s
CI / runtimes (edge) (push) Successful in 7s
CI / runtimes (deno) (push) Successful in 13s

This commit was merged in pull request #2.
This commit is contained in:
chrnx committed 2026-09-19 16:58:41 +00:00
commit a7253196dc
23 files changed
+1033 -1

No files matched your search

+1 -1
View File
@@ -1,5 +1,5 @@
{
"workspace": ["./packages/jwt"],
"workspace": ["./packages/jwt", "./packages/metrics", "./packages/rate-limit"],
"nodeModulesDir": "manual",
"compilerOptions": {
"experimentalDecorators": true,
+34
View File
@@ -639,6 +639,14 @@
"resolved": "packages/jwt",
"link": true
},
"node_modules/@green-tea/metrics": {
"resolved": "packages/metrics",
"link": true
},
"node_modules/@green-tea/rate-limit": {
"resolved": "packages/rate-limit",
"link": true
},
"node_modules/@humanfs/core": {
"version": "0.19.2",
"resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz",
@@ -2936,6 +2944,32 @@
"deno": ">=2",
"node": ">=22"
}
},
"packages/metrics": {
"name": "@green-tea/metrics",
"version": "26.9.0-beta.0",
"license": "MIT",
"devDependencies": {
"@green-tea/core": "26.9.0-beta.2"
},
"engines": {
"bun": ">=1.3",
"deno": ">=2",
"node": ">=22"
}
},
"packages/rate-limit": {
"name": "@green-tea/rate-limit",
"version": "26.9.0-beta.0",
"license": "MIT",
"devDependencies": {
"@green-tea/core": "26.9.0-beta.2"
},
"engines": {
"bun": ">=1.3",
"deno": ">=2",
"node": ">=22"
}
}
}
}
+10
View File
@@ -0,0 +1,10 @@
# Changelog
## [Unreleased]
### Added
- `metrics({ provides? })`: subscribes to the lifecycle stream and publishes a `Metrics` with
`render()`. Counts `request:end` as requests and `request:failed` separately, labelled on the
bounded `route` rather than on the caller-controlled `name`. `prometheus` is a `TransformerFn` for
serving `render()` from a route the application owns. Closes green-tea#68.
+50
View File
@@ -0,0 +1,50 @@
# @green-tea/metrics
Subscribes to green-tea's lifecycle stream and counts what happened. You expose it on a route you
own, with the transformer this package ships.
## Runtimes
| Runtime | Supported | Why not |
|---|---|---|
| Node | ✅ | |
| Deno | ✅ | |
| Bun | ✅ | |
| workerd (edge) | ❌ | Counters live in one isolate, and an edge deployment has many, so a scrape reports whichever isolate answered it. Supported once the counters can be shared. |
## Usage
```ts
import { createApp } from '@green-tea/core';
import { metrics } from '@green-tea/metrics';
const app = createApp({ modules: [ApiModule], plugins: [metrics()] });
```
```ts
import { prometheus, type Metrics } from '@green-tea/metrics';
@Get('/metrics')
@Transformer(prometheus)
scrape(@needs('metrics') metrics: Metrics) {
return metrics.render();
}
```
The route is yours, so its path, its auth and whether it is exposed at all stay your decisions.
## What it counts, and what it refuses to
One failed request emits **three** lifecycle events, and a collector that counts them as three
outcomes reports one request as several. The division this package follows:
| Series | From | Meaning |
|---|---|---|
| `green_tea_requests_total` | `request:end` | Every dispatched request. Terminal and universal — this is *the* request counter |
| `green_tea_request_errors_total` | `request:failed` | Handler code threw. **Additional** to the request above, never a second request |
| `green_tea_request_duration_seconds` | `request:end` | Sum and count, so an average is available without buckets |
Labels are `route`, `method` and `status` — never the event's `name`. `route` is the matched
*pattern* and is bounded by your route table (`<unmatched>` when nothing matched); `name` carries the
path that arrived, which is bounded by nothing, so a scanner walking `/aaa`, `/aab`, `/aac` would
mint a label per URL. That is a memory leak with a metrics backend attached.
+12
View File
@@ -0,0 +1,12 @@
{
"name": "@green-tea/metrics",
"version": "26.9.0-beta.0",
"license": "MIT",
"exports": "./src/index.ts",
"imports": {
"@green-tea/core": "npm:@green-tea/core@26.9.0-beta.2"
},
"publish": {
"include": ["src", "README.md", "CHANGELOG.md", "deno.json"]
}
}
+25
View File
@@ -0,0 +1,25 @@
{
"name": "@green-tea/metrics",
"version": "26.9.0-beta.0",
"private": true,
"description": "Counts green-tea's lifecycle events and renders them in the Prometheus text format.",
"license": "MIT",
"author": "green-tea contributors <projects@expressive-tea.io>",
"type": "module",
"repository": {
"type": "git",
"url": "git+https://github.com/Expressive-Tea/green-tea-plugins.git",
"directory": "packages/metrics"
},
"engines": {
"node": ">=22",
"deno": ">=2",
"bun": ">=1.3"
},
"exports": {
".": "./src/index.ts"
},
"devDependencies": {
"@green-tea/core": "26.9.0-beta.2"
}
}
Binary file not shown.
+49
View File
@@ -0,0 +1,49 @@
import type { Plugin } from '@green-tea/core';
import { Metrics } from './collector.ts';
import type { MetricsOptions } from './types.ts';
export { Metrics } from './collector.ts';
export { prometheus } from './prometheus.ts';
export type { MetricsOptions, MetricsSnapshot, Series } from './types.ts';
/**
* Subscribes to the lifecycle stream and publishes the counters into the graph.
*
* There is no `onShutdown` (convention rule 7): a bus subscription is an entry in a set, and holds
* no timer, socket or handle that could keep a process alive. Nothing to release.
*
* The collector is built at mount time rather than in the provider's `run`, because the subscription
* has to exist before the first request — a provider runs on boot, which is late enough to miss it.
*
* @example
* const app = createApp({ modules: [ApiModule], plugins: [metrics()] });
*
* @example <caption>Exposed on a route the application owns.</caption>
* ⁣@Get('/metrics')
* ⁣@Transformer(prometheus)
* scrape(@needs('metrics') collector: Metrics) {
* return collector.render();
* }
*/
export function metrics(options: MetricsOptions = {}): Plugin {
const provides = options.provides ?? 'metrics';
const collector = new Metrics();
return {
// Rule 2: plugin name, node name and provided token are one string.
name: provides,
mount({ bus, scope }) {
bus.on('request:end', (payload) => collector.observeEnd(payload));
bus.on('request:failed', (payload) => collector.observeFailure(payload));
scope.add({
kind: 'provider',
name: provides,
needs: [],
provides: [provides],
run: () => ({ [provides]: collector }),
});
},
};
}
+22
View File
@@ -0,0 +1,22 @@
import type { TransformerFn } from '@green-tea/core';
/**
* Serves a rendered scrape as the Prometheus text exposition format.
*
* A `TransformerFn` rather than a route: the path, the auth and whether the endpoint exists at all
* are the application's decisions, and a plugin that mounted `/metrics` itself would be taking them.
* The version is part of the content type — Prometheus reads it, and omitting it makes a scrape fall
* back to a guess.
*
* @example
* ⁣@Get('/metrics')
* ⁣@Transformer(prometheus)
* scrape(@needs('metrics') collector: Metrics) {
* return collector.render();
* }
*/
export const prometheus: TransformerFn = (value) => ({
status: 200,
headers: { 'content-type': 'text/plain; version=0.0.4; charset=utf-8' },
body: String(value),
});
+19
View File
@@ -0,0 +1,19 @@
/** One labelled series and its accumulated value. */
export interface Series {
route: string;
method: string;
status?: number;
value: number;
}
/** What the collector holds, for a consumer that wants numbers rather than text. */
export interface MetricsSnapshot {
requests: Series[];
errors: Series[];
duration: Array<{ route: string; method: string; sum: number; count: number }>;
}
export interface MetricsOptions {
/** Graph name the collector is published under, and the plugin's name. Defaults to `metrics`. */
provides?: string;
}
+130
View File
@@ -0,0 +1,130 @@
import { strict as assert } from 'node:assert';
import { test } from 'node:test';
import { createApp, Get, Module, Route, Transformer, needs } from '@green-tea/core';
import { Metrics } from '../src/collector.ts';
import { metrics, prometheus } from '../src/index.ts';
const end = (route: string, method: string, status: number, durationMs = 5) =>
({ name: route, route, method, status, durationMs }) as never;
test('counts one request per request:end, keyed by route, method and status', () => {
const collector = new Metrics();
collector.observeEnd(end('/users/:id', 'GET', 200));
collector.observeEnd(end('/users/:id', 'GET', 200));
collector.observeEnd(end('/users/:id', 'GET', 404));
const { requests } = collector.snapshot();
assert.equal(requests.find((s) => s.status === 200)?.value, 2);
assert.equal(requests.find((s) => s.status === 404)?.value, 1);
});
// The defect issue #64 was filed for: a failed request emits request:start, request:failed and
// request:end. Counting the failure as a request reports one request as two.
test('a failure counts once as a request and once as an error, not twice as a request', () => {
const collector = new Metrics();
collector.observeFailure({ name: '/boom', route: '/boom', method: 'GET' } as never);
collector.observeEnd(end('/boom', 'GET', 500));
const { requests, errors } = collector.snapshot();
assert.equal(
requests.reduce((total, s) => total + s.value, 0),
1,
);
assert.equal(
errors.reduce((total, s) => total + s.value, 0),
1,
);
});
// Issue #65: `name` is the path that arrived and is bounded by nothing. `route` is the matched
// pattern, and is '<unmatched>' when nothing matched.
test('labels on the bounded route, so a scanner cannot mint a series per URL', () => {
const collector = new Metrics();
for (const probe of ['/aaa', '/aab', '/aac']) {
collector.observeEnd({
name: `GET ${probe}`,
route: '<unmatched>',
method: 'GET',
status: 404,
durationMs: 1,
} as never);
}
const { requests } = collector.snapshot();
assert.equal(requests.length, 1);
assert.equal(requests[0].route, '<unmatched>');
assert.equal(requests[0].value, 3);
});
test('accumulates duration as a sum and a count, in seconds', () => {
const collector = new Metrics();
collector.observeEnd(end('/x', 'GET', 200, 1500));
collector.observeEnd(end('/x', 'GET', 200, 500));
const [duration] = collector.snapshot().duration;
assert.equal(duration.count, 2);
assert.equal(duration.sum, 2);
});
test('an event with no route is attributed rather than dropped or left blank', () => {
const collector = new Metrics();
collector.observeEnd({ name: 'GET /x', method: 'GET', status: 200, durationMs: 1 } as never);
assert.equal(collector.snapshot().requests[0].route, '<unknown>');
});
test('the transformer serves the text format with the content type Prometheus expects', () => {
const rendered = prometheus('green_tea_requests_total{route="/x",method="GET",status="200"} 1\n');
assert.equal(rendered.status, 200);
assert.match(rendered.headers!['content-type'], /text\/plain/);
assert.match(rendered.body, /green_tea_requests_total/);
});
test('an application serves its own /metrics route from the published collector', async () => {
@Route('/')
class Ops {
@Get('/metrics')
@Transformer(prometheus)
scrape(@needs('metrics') collector: Metrics) {
return collector.render();
}
@Get('/hello')
hello() {
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [Ops] })
class OpsModule {}
const app = createApp({ modules: [OpsModule], plugins: [metrics()] });
try {
await app.fetch(new Request('http://plugin.test/hello'));
const scrape = await app.fetch(new Request('http://plugin.test/metrics'));
const body = await scrape.text();
assert.equal(scrape.status, 200);
assert.match(body, /green_tea_requests_total\{route="\/hello",method="GET",status="200"\} 1/);
} finally {
await app.close();
}
});
test('the plugin is named after what it provides', () => {
assert.equal(metrics().name, 'metrics');
assert.equal(metrics({ provides: 'opsMetrics' }).name, 'opsMetrics');
});
+10
View File
@@ -0,0 +1,10 @@
# Changelog
## [Unreleased]
### Added
- `rateLimit({ rules, store?, keyOf?, provides? })`: publishes a `RateLimiter` under `provides`
(default `rateLimit`). Exceeding a rule throws `TooManyRequests`, a branded 429 carrying
`Retry-After`. The default `MemoryStore` sweeps expired windows on an interval and is released by
the plugin's `onShutdown`.
+53
View File
@@ -0,0 +1,53 @@
# @green-tea/rate-limit
Publishes a per-request rate limiter into the graph. A handler opts in by asking for it and naming a
rule, so the limit is visible in the handler's signature rather than hidden in a middleware chain —
and green-tea runs the step only for the routes that depend on it.
## Runtimes
| Runtime | Supported | Why not |
|---|---|---|
| Node | ✅ | |
| Deno | ✅ | |
| Bun | ✅ | |
| workerd (edge) | ❌ | The default store counts per isolate, and an edge deployment has many, so a shared limit is not one. Supported once a store that shares state ships. |
## Usage
```ts
import { createApp } from '@green-tea/core';
import { rateLimit } from '@green-tea/rate-limit';
const app = createApp({
modules: [AuthModule],
plugins: [
rateLimit({
rules: {
signin: { windowMs: 15 * 60 * 1000, max: 5, message: 'Too many attempts, try again later.' },
},
}),
],
});
```
```ts
@Post('/signin')
async signIn(@needs('rateLimit') limit: RateLimiter) {
await limit('signin');
// ...
}
```
Exceeding a rule throws a `429` carrying `Retry-After`. The error is recognised by green-tea through
a registered symbol rather than by extending its `HttpError`, so this package never imports core at
runtime.
## The store
The default `MemoryStore` keeps fixed windows in this process and sweeps expired ones on an interval.
**One process, one set of counters:** two replicas each enforce the limit separately, so the real
ceiling is `max × replicas`. Implement `RateLimitStore` against Redis when you scale past one.
The sweep timer keeps the process alive on purpose, and the plugin's `onShutdown` clears it. A custom
store owns its own lifecycle; `close()` is called on it if it has one.
+12
View File
@@ -0,0 +1,12 @@
{
"name": "@green-tea/rate-limit",
"version": "26.9.0-beta.0",
"license": "MIT",
"exports": "./src/index.ts",
"imports": {
"@green-tea/core": "npm:@green-tea/core@26.9.0-beta.2"
},
"publish": {
"include": ["src", "README.md", "CHANGELOG.md", "deno.json"]
}
}
+25
View File
@@ -0,0 +1,25 @@
{
"name": "@green-tea/rate-limit",
"version": "26.9.0-beta.0",
"private": true,
"description": "A per-request rate limiter published into the green-tea graph, with a branded 429 and a swept in-memory store.",
"license": "MIT",
"author": "green-tea contributors <projects@expressive-tea.io>",
"type": "module",
"repository": {
"type": "git",
"url": "git+https://github.com/Expressive-Tea/green-tea-plugins.git",
"directory": "packages/rate-limit"
},
"engines": {
"node": ">=22",
"deno": ">=2",
"bun": ">=1.3"
},
"exports": {
".": "./src/index.ts"
},
"devDependencies": {
"@green-tea/core": "26.9.0-beta.2"
}
}
+33
View File
@@ -0,0 +1,33 @@
/**
* Core's error brand, as the public protocol rather than as an import.
*
* `Symbol.for` is registry-wide, so this resolves to the same symbol core registered, in this copy
* of the process and in any other. That is what lets a plugin throw something core renders without
* depending on core at runtime — and it survives two copies of core in one tree, which `instanceof`
* does not, since each copy has its own class identity.
*
* The string is the contract (design spec 1.2). `unique symbol` is what TypeScript needs for a
* computed class field, and a `const` annotated with it satisfies that.
*/
const HTTP_ERROR: unique symbol = Symbol.for('green-tea.http-error');
/**
* Thrown when a caller exceeds a rule. Carries `Retry-After` so a client can back off rather than
* retry immediately and spend the next window too.
*
* Extends `Error`, not core's `HttpError`: core reads `status`, `message`, `body` and `headers` off
* whatever carries the brand, and never uses `instanceof`.
*/
export class TooManyRequests extends Error {
readonly [HTTP_ERROR] = true;
readonly status = 429;
readonly body: { message: string; status: number };
readonly headers: Record<string, string>;
constructor(message: string, retryAfterSeconds: number) {
super(message);
this.name = 'TooManyRequests';
this.body = { message, status: 429 };
this.headers = { 'retry-after': String(retryAfterSeconds) };
}
}
+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?.());
},
};
}
+80
View File
@@ -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);
}
}
}
+59
View File
@@ -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;
}
+35
View File
@@ -0,0 +1,35 @@
// Not a test — the child the exit test spawns. Named with a leading underscore so no runner picks it
// up: `node --test`, `deno test` and `bun test` all discover by filename, and this matches none.
//
// It boots an app that has taken a hit (so the sweep timer is armed), closes it, and prints one line.
// Nothing here calls process.exit: whether the process ends is the measurement.
import { createApp, Get, Module, Route, needs } from '@green-tea/core';
import { rateLimit } from '../src/index.ts';
import type { RateLimiter } from '../src/index.ts';
@Route('/')
class Probe {
@Get('/probe')
async probe(@needs('rateLimit') limit: RateLimiter) {
await limit('signin');
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [Probe] })
class ProbeModule {}
async function main(): Promise<void> {
const app = createApp({
modules: [ProbeModule],
plugins: [rateLimit({ rules: { signin: { windowMs: 60_000, max: 10, message: 'too many' } } })],
});
await app.fetch(new Request('http://probe.test/probe'));
await app.close();
console.log('closed');
}
void main();
+242
View File
@@ -0,0 +1,242 @@
import { strict as assert } from 'node:assert';
import { spawn } from 'node:child_process';
import { test } from 'node:test';
import { createApp } from '@green-tea/core';
import type { App } from '@green-tea/core';
import { probeModule, runtimeCommand } from '../../../test/helpers.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';
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());
});
// Convention rule 8, checked where it bites. The class never extends core's HttpError — it carries a
// registry-wide symbol, which is what lets a plugin throw a 429 that core renders without importing
// core, and what keeps working when two copies of core are in one tree (`instanceof` does not).
test('carries the brand core recognises, and the fields core reads off it', () => {
const error = new TooManyRequests('slow down', 30);
assert.equal((error as unknown as Record<symbol, unknown>)[Symbol.for('green-tea.http-error')], true);
assert.equal(error.status, 429);
assert.equal(error.message, 'slow down');
assert.equal(error.headers['retry-after'], '30');
assert.deepEqual(error.body, { message: 'slow down', status: 429 });
// Still an Error: a throw that is not one loses the stack, and core rethrows before rendering.
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');
});
/** Runs the probe and reports how it ended. `timeoutMs` elapsing means it never exited. */
function runProbe(timeoutMs: number): Promise<{ exited: boolean; output: string }> {
const { command, args } = runtimeCommand('packages/rate-limit/test/_exit-probe.ts');
return new Promise((resolve) => {
const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'inherit'] });
let output = '';
child.stdout.on('data', (chunk: Buffer) => (output += chunk.toString()));
const timer = setTimeout(() => {
child.kill('SIGKILL');
resolve({ exited: false, output });
}, timeoutMs);
child.on('exit', () => {
clearTimeout(timer);
resolve({ exited: true, output });
});
});
}
// Convention rule 7, and the only test in the repository that measures it rather than asserting it.
// A leaked setInterval keeps Node, Deno and Bun alive indefinitely; a cleared one lets each exit in
// well under a second. The process is the probe, which is what makes this portable.
test('the app exits on its own after close(), because onShutdown cleared the sweep', async () => {
const { exited, output } = await runProbe(2_000);
assert.ok(output.includes('closed'), `the probe never reached close(): ${output}`);
assert.ok(exited, 'the process was still alive 2s after close() — a timer outlived onShutdown');
});
+11
View File
@@ -0,0 +1,11 @@
import { strict as assert } from 'node:assert';
import { test } from 'node:test';
import { runtimeCommand } from './helpers.ts';
test('runtimeCommand names an executable and passes the script last', () => {
const { command, args } = runtimeCommand('some/probe.ts');
assert.ok(command.length > 0, 'no command');
assert.equal(args.at(-1), 'some/probe.ts');
});
+25
View File
@@ -22,3 +22,28 @@ export function probeModule(token: string, read: (value: any) => unknown) {
return ProbeModule;
}
/** The globals each runtime defines, for picking the argv that re-runs a script under it. */
interface RuntimeGlobals {
Deno?: { execPath(): string };
Bun?: unknown;
process?: { execPath: string };
}
/**
* The command that runs `script` on whichever runtime is hosting this test.
*
* A contract file runs unchanged on three runtimes, so a test that spawns a child cannot hardcode
* one. Deno needs its permission flag, Bun runs TypeScript directly, and Node needs tsx to load it.
*/
export function runtimeCommand(script: string): { command: string; args: string[] } {
const globals = globalThis as RuntimeGlobals;
// `--no-check` for the same reason `npm run test:deno` passes it: Deno type-checks the whole
// reachable graph, which here reaches core's Node-only modules and their ambient `Buffer`. The
// child is a runtime probe, and `npm run typecheck` already covers the types.
if (globals.Deno) return { command: globals.Deno.execPath(), args: ['run', '--allow-all', '--no-check', script] };
if (globals.Bun) return { command: 'bun', args: ['run', script] };
return { command: globals.process!.execPath, args: ['--import', 'tsx', script] };
}