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'); +});