Files
plugins/packages/metrics/src/collector.ts
T
chrnx 5a74cad793 feat(metrics): count request:end, and only request:end
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 <diego.resendez@zero-oneit.com>
2026-09-18 13:26:32 -05:00

138 lines
4.9 KiB
TypeScript

import type { EventPayload } from '@green-tea/core';
import type { MetricsSnapshot, Series } from './types.ts';
/**
* The route reported when an event carries none.
*
* Bounded and distinct from core's own `<unmatched>`, which means "no route matched". This one means
* "the event did not say", which is a different fact and worth being able to tell apart.
*/
const UNKNOWN_ROUTE = '<unknown>';
interface Bucket {
route: string;
method: string;
status?: number;
value: number;
}
/** A stable key for one labelled series. */
function keyOf(route: string, method: string, status?: number): string {
return `${route}${method}${status ?? ''}`;
}
function add(into: Map<string, Bucket>, route: string, method: string, status: number | undefined, by = 1): void {
const key = keyOf(route, method, status);
const existing = into.get(key);
if (existing) {
existing.value += by;
return;
}
into.set(key, { route, method, status, value: by });
}
/** Escapes a label value: backslash, double quote and newline are the three the format reserves. */
function escapeLabel(value: string): string {
return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
}
function labels(route: string, method: string, status?: number): string {
const pairs = [`route="${escapeLabel(route)}"`, `method="${escapeLabel(method)}"`];
if (status !== undefined) pairs.push(`status="${status}"`);
return `{${pairs.join(',')}}`;
}
function renderSnapshot(snapshot: MetricsSnapshot): string {
const lines: string[] = [
'# HELP green_tea_requests_total Requests that completed, by route, method and status.',
'# TYPE green_tea_requests_total counter',
];
for (const s of snapshot.requests) {
lines.push(`green_tea_requests_total${labels(s.route, s.method, s.status)} ${s.value}`);
}
lines.push(
'# HELP green_tea_request_errors_total Requests whose handler threw. Additional to the count above.',
'# TYPE green_tea_request_errors_total counter',
);
for (const s of snapshot.errors) {
lines.push(`green_tea_request_errors_total${labels(s.route, s.method)} ${s.value}`);
}
lines.push(
'# HELP green_tea_request_duration_seconds Time from dispatch to the handler returning.',
'# TYPE green_tea_request_duration_seconds summary',
);
for (const d of snapshot.duration) {
lines.push(`green_tea_request_duration_seconds_sum${labels(d.route, d.method)} ${d.sum}`);
lines.push(`green_tea_request_duration_seconds_count${labels(d.route, d.method)} ${d.count}`);
}
return `${lines.join('\n')}\n`;
}
/**
* Counts what the lifecycle stream reports.
*
* **`request:end` is the request counter, and nothing else is.** It is terminal and universal — every
* dispatched request emits exactly one, handled, thrown, unmatched and shed alike — and it is the only
* event carrying the status the client received. `request:failed` fires *in addition* to it for the
* same request, so counting both as requests reports one request as two. That is the defect core
* issue #64 was filed for, and the first collector anyone writes has it.
*
* Labels come from `route`, never from `name`. `route` is the matched pattern and is bounded by the
* route table; `name` is built from the path that arrived and is bounded by nothing, so a scanner
* walking `/aaa`, `/aab`, `/aac` would mint one series per URL — issue #65.
*/
export class Metrics {
private readonly requests = new Map<string, Bucket>();
private readonly errors = new Map<string, Bucket>();
private readonly duration = new Map<string, { route: string; method: string; sum: number; count: number }>();
/** Subscribe to `request:end`. The request counter and the latency accumulator. */
observeEnd(payload: EventPayload): void {
const route = payload.route ?? UNKNOWN_ROUTE;
const method = payload.method ?? '';
add(this.requests, route, method, payload.status);
if (payload.durationMs === undefined) return;
const key = keyOf(route, method, undefined);
const seen = this.duration.get(key) ?? { route, method, sum: 0, count: 0 };
seen.sum += payload.durationMs / 1000;
seen.count += 1;
this.duration.set(key, seen);
}
/** Subscribe to `request:failed`. An error counter, never a second request counter. */
observeFailure(payload: EventPayload): void {
add(this.errors, payload.route ?? UNKNOWN_ROUTE, payload.method ?? '', undefined);
}
/** The counters as data, for a consumer that wants numbers rather than the text format. */
snapshot(): MetricsSnapshot {
const series = (from: Map<string, Bucket>): Series[] => [...from.values()];
return {
requests: series(this.requests),
errors: series(this.errors),
duration: [...this.duration.values()],
};
}
/** The Prometheus text exposition format. Serve it with the `prometheus` transformer. */
render(): string {
return renderSnapshot(this.snapshot());
}
}