import { describe, expect, it } from 'vitest'; import { MetricsService } from './metrics.service.js'; describe('MetricsService', () => { it('computes nearest-rank percentiles from observed latencies', () => { const metrics = new MetricsService(); metrics.increment('cache_hit'); metrics.increment('cache_hit'); metrics.observeLatency(30); metrics.observeLatency(10); metrics.observeLatency(20); expect(metrics.snapshot()).toEqual({ counters: { cache_hit: 2 }, latency_ms: { count: 3, sample_count: 3, p50: 20, p95: 30, p99: 30, max: 30, }, }); }); it('keeps snapshots isolated from callers and later observations', () => { const metrics = new MetricsService(); metrics.increment('cache_hit'); const snapshot = metrics.snapshot(); snapshot.counters.cache_hit = 99; metrics.increment('cache_hit'); expect(metrics.snapshot().counters.cache_hit).toBe(2); expect(snapshot.latency_ms.count).toBe(0); }); it('bounds retained samples but keeps cumulative count and maximum', () => { const metrics = new MetricsService(); metrics.observeLatency(9000); for (let index = 0; index < 4096; index += 1) metrics.observeLatency(10); expect(metrics.snapshot().latency_ms).toEqual({ count: 4097, sample_count: 4096, p50: 10, p95: 10, p99: 10, max: 9000, }); }); it('ignores invalid latency observations', () => { const metrics = new MetricsService(); for (const value of [-1, NaN, Infinity]) metrics.observeLatency(value); expect(metrics.snapshot().latency_ms).toEqual({ count: 0, sample_count: 0, p50: 0, p95: 0, p99: 0, max: 0, }); }); });