From 74f297dafdc79306a665fd5f6d4afda90faf1054 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 18 Sep 2026 13:17:12 -0500 Subject: [PATCH 01/10] test: pick the child-process command from the host runtime MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The exit test spawns a probe and asserts it dies on its own, and the contract files run unchanged on three runtimes — so the argv has to be decided at run time rather than written for Node and skipped elsewhere. Signed-off-by: Diego Resendez --- test/helpers.test.ts | 11 +++++++++++ test/helpers.ts | 25 +++++++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 test/helpers.test.ts diff --git a/test/helpers.test.ts b/test/helpers.test.ts new file mode 100644 index 0000000..aa812e9 --- /dev/null +++ b/test/helpers.test.ts @@ -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'); +}); diff --git a/test/helpers.ts b/test/helpers.ts index e48cfb2..ab4fee4 100644 --- a/test/helpers.ts +++ b/test/helpers.ts @@ -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] }; +} From b15ce293151d93b99e6d607e9b6d8aec58e78b19 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 18 Sep 2026 13:17:45 -0500 Subject: [PATCH 02/10] feat(rate-limit): declare the package and the runtimes it claims No workerd: the default store counts per isolate, and an edge deployment has many, so the limit it would enforce is not the one configured. The README says so rather than leaving someone to find out. Signed-off-by: Diego Resendez --- deno.json | 2 +- packages/rate-limit/CHANGELOG.md | 10 ++++++ packages/rate-limit/README.md | 53 ++++++++++++++++++++++++++++++++ packages/rate-limit/deno.json | 12 ++++++++ packages/rate-limit/package.json | 25 +++++++++++++++ 5 files changed, 101 insertions(+), 1 deletion(-) create mode 100644 packages/rate-limit/CHANGELOG.md create mode 100644 packages/rate-limit/README.md create mode 100644 packages/rate-limit/deno.json create mode 100644 packages/rate-limit/package.json diff --git a/deno.json b/deno.json index 2a1b9db..ae9d196 100644 --- a/deno.json +++ b/deno.json @@ -1,5 +1,5 @@ { - "workspace": ["./packages/jwt"], + "workspace": ["./packages/jwt", "./packages/rate-limit"], "nodeModulesDir": "manual", "compilerOptions": { "experimentalDecorators": true, diff --git a/packages/rate-limit/CHANGELOG.md b/packages/rate-limit/CHANGELOG.md new file mode 100644 index 0000000..dff35d8 --- /dev/null +++ b/packages/rate-limit/CHANGELOG.md @@ -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`. diff --git a/packages/rate-limit/README.md b/packages/rate-limit/README.md new file mode 100644 index 0000000..e601aac --- /dev/null +++ b/packages/rate-limit/README.md @@ -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. diff --git a/packages/rate-limit/deno.json b/packages/rate-limit/deno.json new file mode 100644 index 0000000..692cafb --- /dev/null +++ b/packages/rate-limit/deno.json @@ -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"] + } +} diff --git a/packages/rate-limit/package.json b/packages/rate-limit/package.json new file mode 100644 index 0000000..3fa3c1b --- /dev/null +++ b/packages/rate-limit/package.json @@ -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 ", + "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" + } +} From 66afb59103a1b625188583cf423c2abdcd7b7947 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 18 Sep 2026 13:18:26 -0500 Subject: [PATCH 03/10] feat(rate-limit): sweep expired windows instead of walking the map MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- packages/rate-limit/src/memory-store.ts | 80 +++++++++++++++++++++ packages/rate-limit/src/types.ts | 59 +++++++++++++++ packages/rate-limit/test/rate-limit.test.ts | 68 ++++++++++++++++++ 3 files changed, 207 insertions(+) create mode 100644 packages/rate-limit/src/memory-store.ts create mode 100644 packages/rate-limit/src/types.ts create mode 100644 packages/rate-limit/test/rate-limit.test.ts diff --git a/packages/rate-limit/src/memory-store.ts b/packages/rate-limit/src/memory-store.ts new file mode 100644 index 0000000..e6322b5 --- /dev/null +++ b/packages/rate-limit/src/memory-store.ts @@ -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(); + private readonly sweepMs: number; + private timer: ReturnType | 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); + } + } +} diff --git a/packages/rate-limit/src/types.ts b/packages/rate-limit/src/types.ts new file mode 100644 index 0000000..3caac9d --- /dev/null +++ b/packages/rate-limit/src/types.ts @@ -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; + /** Drop every counter. Used by tests and by operators clearing a lockout. */ + reset(): Promise | 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; +} + +/** The function a handler receives from `@needs('rateLimit')`. */ +export type RateLimiter = (rule: string, override?: Partial) => Promise; + +/** The slice of the green-tea request context this plugin reads. */ +export interface RateLimitContext { + ip?: string; + headers?: Record; +} + +export interface RateLimitOptions { + /** Named rules, addressed by handlers as `limit('signin')`. */ + rules: Record; + /** 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; +} diff --git a/packages/rate-limit/test/rate-limit.test.ts b/packages/rate-limit/test/rate-limit.test.ts new file mode 100644 index 0000000..81465b5 --- /dev/null +++ b/packages/rate-limit/test/rate-limit.test.ts @@ -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 => 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()); +}); From 14ed9c38be6c30ffa61e000e9438f334dfc13e57 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 18 Sep 2026 13:18:49 -0500 Subject: [PATCH 04/10] feat(rate-limit): carry the error brand instead of extending core The original extended core's HttpError, which is a value import and makes the published plugin need core at run time. The brand is a registry-wide symbol, so core renders the 429 without this package depending on it, and it survives two copies of core in one tree where instanceof would not. The fields asserted here are exactly the ones HttpErrorLike declares. That core really renders them is proven end to end in the limiter's own tests, which read a 429 and its Retry-After back out of app.fetch. Signed-off-by: Diego Resendez --- packages/rate-limit/src/errors.ts | 33 +++++++++++++++++++++ packages/rate-limit/test/rate-limit.test.ts | 16 ++++++++++ 2 files changed, 49 insertions(+) create mode 100644 packages/rate-limit/src/errors.ts diff --git a/packages/rate-limit/src/errors.ts b/packages/rate-limit/src/errors.ts new file mode 100644 index 0000000..366d8d2 --- /dev/null +++ b/packages/rate-limit/src/errors.ts @@ -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; + + constructor(message: string, retryAfterSeconds: number) { + super(message); + this.name = 'TooManyRequests'; + this.body = { message, status: 429 }; + this.headers = { 'retry-after': String(retryAfterSeconds) }; + } +} diff --git a/packages/rate-limit/test/rate-limit.test.ts b/packages/rate-limit/test/rate-limit.test.ts index 81465b5..ac43e5e 100644 --- a/packages/rate-limit/test/rate-limit.test.ts +++ b/packages/rate-limit/test/rate-limit.test.ts @@ -1,6 +1,7 @@ import { strict as assert } from 'node:assert'; import { test } from 'node:test'; +import { TooManyRequests } from '../src/errors.ts'; import { MemoryStore } from '../src/memory-store.ts'; const sleep = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); @@ -66,3 +67,18 @@ test('close is idempotent, because close() is called more than once in real apps 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.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); +}); From 8ac46fed61553d3db284bf8bbba4e697b70a11b8 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 18 Sep 2026 13:22:45 -0500 Subject: [PATCH 05/10] feat(rate-limit): publish the limiter as a named plugin MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- packages/rate-limit/src/index.ts | 96 +++++++++++++++ packages/rate-limit/test/rate-limit.test.ts | 125 ++++++++++++++++++++ 2 files changed, 221 insertions(+) create mode 100644 packages/rate-limit/src/index.ts diff --git a/packages/rate-limit/src/index.ts b/packages/rate-limit/src/index.ts new file mode 100644 index 0000000..2a51a0e --- /dev/null +++ b/packages/rate-limit/src/index.ts @@ -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): 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 In a handler. + * ⁣@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?.()); + }, + }; +} diff --git a/packages/rate-limit/test/rate-limit.test.ts b/packages/rate-limit/test/rate-limit.test.ts index ac43e5e..970dc30 100644 --- a/packages/rate-limit/test/rate-limit.test.ts +++ b/packages/rate-limit/test/rate-limit.test.ts @@ -1,7 +1,13 @@ import { strict as assert } from 'node:assert'; 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 { rateLimit } from '../src/index.ts'; +import type { RateLimiter } from '../src/index.ts'; import { MemoryStore } from '../src/memory-store.ts'; const sleep = (ms: number): Promise => 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. 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): Promise { + 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'); +}); From f72c391646d6514f80775cc3c4e741deaab935e3 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 18 Sep 2026 13:25:17 -0500 Subject: [PATCH 06/10] test(rate-limit): measure that close() lets the process exit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rule 7 says nothing a plugin opens outlives close(), and the only portable probe is a process: a leaked interval keeps all three runtimes alive, a cleared one lets each exit in well under a second. Verified the test fails with onShutdown removed — it reports the process still alive after 2s — because a leak test that passes while leaking is worth nothing. Signed-off-by: Diego Resendez --- packages/rate-limit/test/_exit-probe.ts | 35 +++++++++++++++++++++ packages/rate-limit/test/rate-limit.test.ts | 35 ++++++++++++++++++++- 2 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 packages/rate-limit/test/_exit-probe.ts diff --git a/packages/rate-limit/test/_exit-probe.ts b/packages/rate-limit/test/_exit-probe.ts new file mode 100644 index 0000000..7a55761 --- /dev/null +++ b/packages/rate-limit/test/_exit-probe.ts @@ -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 { + 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(); diff --git a/packages/rate-limit/test/rate-limit.test.ts b/packages/rate-limit/test/rate-limit.test.ts index 970dc30..344f9e4 100644 --- a/packages/rate-limit/test/rate-limit.test.ts +++ b/packages/rate-limit/test/rate-limit.test.ts @@ -1,10 +1,11 @@ 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 } from '../../../test/helpers.ts'; +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'; @@ -207,3 +208,35 @@ 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'); +}); From 22e77ee4520927399500a353555cef11839bc2e4 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 18 Sep 2026 13:25:48 -0500 Subject: [PATCH 07/10] feat(metrics): declare the package and what it refuses to label The README carries the cardinality rule up front: label on route, which the route table bounds, never on name, which nothing bounds. That is the mistake issue #65 was filed for and the one a collector makes by default. Signed-off-by: Diego Resendez --- deno.json | 2 +- packages/metrics/CHANGELOG.md | 10 +++++++ packages/metrics/README.md | 50 +++++++++++++++++++++++++++++++++++ packages/metrics/deno.json | 12 +++++++++ packages/metrics/package.json | 25 ++++++++++++++++++ 5 files changed, 98 insertions(+), 1 deletion(-) create mode 100644 packages/metrics/CHANGELOG.md create mode 100644 packages/metrics/README.md create mode 100644 packages/metrics/deno.json create mode 100644 packages/metrics/package.json diff --git a/deno.json b/deno.json index ae9d196..e98dcdf 100644 --- a/deno.json +++ b/deno.json @@ -1,5 +1,5 @@ { - "workspace": ["./packages/jwt", "./packages/rate-limit"], + "workspace": ["./packages/jwt", "./packages/metrics", "./packages/rate-limit"], "nodeModulesDir": "manual", "compilerOptions": { "experimentalDecorators": true, diff --git a/packages/metrics/CHANGELOG.md b/packages/metrics/CHANGELOG.md new file mode 100644 index 0000000..bfc90ac --- /dev/null +++ b/packages/metrics/CHANGELOG.md @@ -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. diff --git a/packages/metrics/README.md b/packages/metrics/README.md new file mode 100644 index 0000000..c494398 --- /dev/null +++ b/packages/metrics/README.md @@ -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 (`` 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. diff --git a/packages/metrics/deno.json b/packages/metrics/deno.json new file mode 100644 index 0000000..58e8705 --- /dev/null +++ b/packages/metrics/deno.json @@ -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"] + } +} diff --git a/packages/metrics/package.json b/packages/metrics/package.json new file mode 100644 index 0000000..f94d34d --- /dev/null +++ b/packages/metrics/package.json @@ -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 ", + "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" + } +} From 5a74cad793d2d2935ef8a8a909208dc53051b0b3 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 18 Sep 2026 13:26:32 -0500 Subject: [PATCH 08/10] feat(metrics): count request:end, and only request:end MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A failed request emits three lifecycle events. request:end is the terminal and universal one, so it is the request counter; request:failed is additional and gets its own series. Counting both as requests is the double count issue #64 was filed for. Labels come from route, which the route table bounds, never from name, which carries the arriving path and is bounded by nothing — issue #65. Signed-off-by: Diego Resendez --- packages/metrics/src/collector.ts | Bin 0 -> 4973 bytes packages/metrics/src/types.ts | 19 ++++++ packages/metrics/test/metrics.test.ts | 82 ++++++++++++++++++++++++++ 3 files changed, 101 insertions(+) create mode 100644 packages/metrics/src/collector.ts create mode 100644 packages/metrics/src/types.ts create mode 100644 packages/metrics/test/metrics.test.ts diff --git a/packages/metrics/src/collector.ts b/packages/metrics/src/collector.ts new file mode 100644 index 0000000000000000000000000000000000000000..25a9f41986b7e43d430fd38d02b7b863862079e4 GIT binary patch literal 4973 zcmbtY+ioMd5zVu|qT)56OFC^2kmSK$d9oWgNRYW)=e~KUlT$i#8PWK|7=UPCU|kJpFJLr4`@su7n)q# z1^lns1YOg5p)Dy(nysKpIniQUt4o~VL*KWZts$vwO||jC*eXOT#WGLr+S2sf&MsA` z7P>y47SL*{1ueC*o(^rBE=>Z5B@8h*XLS_eTMh$ki$>I@Cff$`YIB%XL0sYX`CL1; zbFN?m8?=TO3z}(TuSv}sO`)Zrn}*a%xxg+QA5^XNfj+(Y+ncw4e{=Qz?Wd0yG@$`3 zzOk_VT!L$ZcF?Nn`>wjtf$k0{T760$k+#=oc(K%B(boHKd{CkDFHgyK%b9j8bgP<9 z-@n*O^yxdO5d&}ZhUTpk?;ACPt%$9cN=Emx}pxFkYe*rUZTV$Do9J9kwne4lq)n*q*9NH+WzX%Giae$31uXPyW zJR~4u<}}O#Be{SmKbMjk`ppDph%iztA!6O|AE#NLkNOJKro`=`DMd~(oY~^ml;I0s zDO4PADrwybsp`fz$}bA4+m0dnW7nbr8NF7o8^nc_18{-=ut3$zCm;mX0`q{3TaCil=Ak=#_S zI=>iBqXesppKvooMh4{pI4-JCg2yh3?Cj#&B`Sv4yE8eXZ+D!LX9tz zslJTaLy?!!*3p)blUS%*&PgiFJ^k62rvr7Roon5raIF`u*R(*$@uk1J<{&GK@Ya*`F7$ES>$h!cDul)fsnn!kxse zE+Lb!MzjaC=_4RtJyI`e|LO%IwGZdqW^j@_K^eQuCED!v(#Bz&DBGX7COrrh%AFC~ zn7OVt6~+i!zE;b`90Xf zXty+67CfXnYi_mkc>3?Z|HBl`ZJ4lSSb)7`<$7sgs{R6U)@+#I6sh9SpD^0MwF+oU zEHE}G@I_LMxzVDWuQSmC*xcGiZn~$Y8@86+iOoVjR*hjs=yauFXI;|H|G6^YR#TcA zj8PgJ@Z41JW5zNr;u3{AcE>B=JvoAQ)W%5heKSOfl+R!C2j9*eOR|lY>}rF zbC4bln#wGhZ!q3>n!fqN?`RF_Iorkt#8j|TuoFDBYQYGr0Lzr!FhyQF6JY-Whm0^< zRwl#WLpWDy9G@7ImNOJ9cWU9(lq15Ne}{#f08}-)J+psA-NVnw^TBFTOyn2|Z9Su? zOawdAqz!=0h8pw+_M4Xnq~HmKp!1A039KT}7i+a+Kh~XsdzS|^N?sGSJ`y|DFg6<5^L-om=i@14Pec}g$mApGg)AqDsq;<(5P>@+>XG)4dv=}=Cnk~3F(J&~ zW+pt?`SXNAyW#@Usq|OP3gdYZ&Pi4g9_JSG~o{+03 zf8R&VpV5Fjr*rs!3OT#%#_B3|UPmxJ1ke5V`$*yGk~Yo0myCT05#|`T@>&H|NcUHG zZxLuAg=k@G#nUz}^XT+wZSfl`brSR!85-!I$8!hSf4j6AQbNjpDACXVhQr~5@Riqs!Fu+ZYZP<*!&$(TKr zyZaE5C6bMZ`he3!%o#)+-ght+zmDh*gOH=djo1sj<~U2h;N2~F27+v4VrZJKcBiHk i9DXfgS)H3t+^{&balK7GC-U@Q{}Oxe(~$tMJ@_9mqm{e> literal 0 HcmV?d00001 diff --git a/packages/metrics/src/types.ts b/packages/metrics/src/types.ts new file mode 100644 index 0000000..701be42 --- /dev/null +++ b/packages/metrics/src/types.ts @@ -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; +} diff --git a/packages/metrics/test/metrics.test.ts b/packages/metrics/test/metrics.test.ts new file mode 100644 index 0000000..d2adcdd --- /dev/null +++ b/packages/metrics/test/metrics.test.ts @@ -0,0 +1,82 @@ +import { strict as assert } from 'node:assert'; +import { test } from 'node:test'; + +import { Metrics } from '../src/collector.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 '' 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: '', + method: 'GET', + status: 404, + durationMs: 1, + } as never); + } + + const { requests } = collector.snapshot(); + + assert.equal(requests.length, 1); + assert.equal(requests[0].route, ''); + 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, ''); +}); From de0081ddaec30157106c9092784f087aa87f0f39 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 18 Sep 2026 13:27:08 -0500 Subject: [PATCH 09/10] feat(metrics): publish the collector and a transformer to serve it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The transformer is exported instead of a route: the path, the auth and whether the endpoint exists are the application's decisions, and a plugin that mounted /metrics itself would be taking them. No onShutdown — a bus subscription is an entry in a set and keeps nothing alive, which is what rule 7 asks about. Closes green-tea#68. Signed-off-by: Diego Resendez --- packages/metrics/src/index.ts | 49 +++++++++++++++++++++++++++ packages/metrics/src/prometheus.ts | 22 ++++++++++++ packages/metrics/test/metrics.test.ts | 48 ++++++++++++++++++++++++++ 3 files changed, 119 insertions(+) create mode 100644 packages/metrics/src/index.ts create mode 100644 packages/metrics/src/prometheus.ts diff --git a/packages/metrics/src/index.ts b/packages/metrics/src/index.ts new file mode 100644 index 0000000..a8df10a --- /dev/null +++ b/packages/metrics/src/index.ts @@ -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 Exposed on a route the application owns. + * ⁣@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 }), + }); + }, + }; +} diff --git a/packages/metrics/src/prometheus.ts b/packages/metrics/src/prometheus.ts new file mode 100644 index 0000000..d63958d --- /dev/null +++ b/packages/metrics/src/prometheus.ts @@ -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), +}); diff --git a/packages/metrics/test/metrics.test.ts b/packages/metrics/test/metrics.test.ts index d2adcdd..174f6ac 100644 --- a/packages/metrics/test/metrics.test.ts +++ b/packages/metrics/test/metrics.test.ts @@ -1,7 +1,10 @@ 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; @@ -80,3 +83,48 @@ test('an event with no route is attributed rather than dropped or left blank', ( assert.equal(collector.snapshot().requests[0].route, ''); }); + +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'); +}); From e1773ae1e078fec947075e50e9bff58001411425 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 18 Sep 2026 13:33:39 -0500 Subject: [PATCH 10/10] build: record the two new packages in the lockfile npm ci verifies the lockfile against every workspace package.json and refuses to install when they disagree, so adding rate-limit and metrics without refreshing the lock failed all four CI jobs at their first step. Nothing caught it locally: the contract tests import through relative paths (../src/index.ts) rather than by package name, so the new workspaces never needed to be linked into node_modules for the suite to pass. Verified now by running npm ci itself rather than npm install. Signed-off-by: Diego Resendez --- package-lock.json | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/package-lock.json b/package-lock.json index 57a4435..7ee4325 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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" + } } } }