import { Injectable } from '@nestjs/common'; const LATENCY_SAMPLE_CAPACITY = 4096; type LatencySnapshot = { count: number; sample_count: number; p50: number; p95: number; p99: number; max: number; }; @Injectable() export class MetricsService { private readonly counters: Record = {}; private readonly latencies: number[] = []; private latencyCount = 0; private maximumLatency = 0; private nextSample = 0; increment(name: string): void { this.counters[name] = (this.counters[name] ?? 0) + 1; } observeLatency(milliseconds: number): void { if (!Number.isFinite(milliseconds) || milliseconds < 0) return; this.latencyCount += 1; this.maximumLatency = Math.max(this.maximumLatency, milliseconds); this.latencies[this.nextSample] = milliseconds; this.nextSample = (this.nextSample + 1) % LATENCY_SAMPLE_CAPACITY; } snapshot(): { counters: Record; latency_ms: LatencySnapshot; } { const sorted = [...this.latencies].sort((left, right) => left - right); return { counters: { ...this.counters }, latency_ms: { count: this.latencyCount, sample_count: sorted.length, p50: this.percentile(sorted, 0.5), p95: this.percentile(sorted, 0.95), p99: this.percentile(sorted, 0.99), max: this.maximumLatency, }, }; } reset(): void { for (const name of Object.keys(this.counters)) delete this.counters[name]; this.latencies.length = 0; this.latencyCount = 0; this.maximumLatency = 0; this.nextSample = 0; } private percentile(sorted: number[], percentile: number): number { if (sorted.length === 0) return 0; const index = Math.min( sorted.length - 1, Math.ceil(sorted.length * percentile) - 1, ); return sorted[index]; } }