|
| 1 | +import { Counter, Gauge, Registry } from "prom-client"; |
| 2 | +import { getAuthMetricsSnapshot as getAuthMiddlewareMetricsSnapshot } from "../auth/middleware-metrics.js"; |
| 3 | +import { getSessionMetricsSnapshot } from "../auth/session-metrics.js"; |
| 4 | +import { getAuthMetricsSnapshot as getAuthRouteMetricsSnapshot } from "../routes/auth-metrics.js"; |
| 5 | +import { getBillingMetricsSnapshot } from "../routes/billing-metrics.js"; |
| 6 | +import { getDiagnosticsMetricsSnapshot } from "../routes/diagnostics-metrics.js"; |
| 7 | +import { getStarknetMetricsSnapshot } from "../starknet/client-metrics.js"; |
| 8 | + |
| 9 | +type Snapshot = { counters: Record<string, number>; gauges?: Record<string, number> }; |
| 10 | +type Metric = Counter<string> | Gauge<string>; |
| 11 | + |
| 12 | +export const metricsRegistry = new Registry(); |
| 13 | +const metrics = new Map<string, Metric>(); |
| 14 | + |
| 15 | +function metricName(name: string): string { |
| 16 | + const normalized = name.toLowerCase().replace(/[^a-z0-9_:]/g, "_"); |
| 17 | + return normalized.endsWith("_total") ? normalized.slice(0, -6) : normalized; |
| 18 | +} |
| 19 | + |
| 20 | +function updateSnapshot(snapshot: Snapshot): void { |
| 21 | + for (const [name, value] of Object.entries(snapshot.counters)) { |
| 22 | + const key = `counter:${name}`; |
| 23 | + let metric = metrics.get(key) as Counter<string> | undefined; |
| 24 | + if (!metric) { |
| 25 | + metric = new Counter({ |
| 26 | + name: metricName(name), |
| 27 | + help: `${name} counter`, |
| 28 | + registers: [metricsRegistry], |
| 29 | + }); |
| 30 | + metrics.set(key, metric); |
| 31 | + } |
| 32 | + metric.reset(); |
| 33 | + metric.inc(value); |
| 34 | + } |
| 35 | + |
| 36 | + for (const [name, value] of Object.entries(snapshot.gauges ?? {})) { |
| 37 | + const key = `gauge:${name}`; |
| 38 | + let metric = metrics.get(key) as Gauge<string> | undefined; |
| 39 | + if (!metric) { |
| 40 | + metric = new Gauge({ |
| 41 | + name: metricName(name), |
| 42 | + help: `${name} gauge`, |
| 43 | + registers: [metricsRegistry], |
| 44 | + }); |
| 45 | + metrics.set(key, metric); |
| 46 | + } |
| 47 | + metric.set(value); |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +/** Refreshes the shared registry from the existing snapshot-based metrics API. */ |
| 52 | +export function refreshMetrics(): void { |
| 53 | + updateSnapshot(getAuthMiddlewareMetricsSnapshot()); |
| 54 | + updateSnapshot(getSessionMetricsSnapshot()); |
| 55 | + updateSnapshot(getAuthRouteMetricsSnapshot()); |
| 56 | + updateSnapshot(getBillingMetricsSnapshot()); |
| 57 | + updateSnapshot(getDiagnosticsMetricsSnapshot()); |
| 58 | + updateSnapshot(getStarknetMetricsSnapshot()); |
| 59 | +} |
| 60 | + |
| 61 | +export async function renderMetrics(): Promise<string> { |
| 62 | + refreshMetrics(); |
| 63 | + return metricsRegistry.metrics(); |
| 64 | +} |
0 commit comments