feat(metrics): publish the collector and a transformer to serve it
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 <diego.resendez@zero-oneit.com>
This commit is contained in:
3 files changed
+119
No files matched your search
@@ -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 }),
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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),
|
||||
});
|
||||
@@ -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, '<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');
|
||||
});
|
||||
Reference in new issue
Block a user