()
| 26 | max: number; |
| 27 | }; |
| 28 | export function createStatsStore(): StatsStore { |
| 29 | const metrics = new Map<string, number>(); |
| 30 | const histograms = new Map<string, Histogram>(); |
| 31 | const sets = new Map<string, Set<string>>(); |
| 32 | return { |
| 33 | increment(name: string, value = 1) { |
| 34 | metrics.set(name, (metrics.get(name) ?? 0) + value); |
| 35 | }, |
| 36 | set(name: string, value: number) { |
| 37 | metrics.set(name, value); |
| 38 | }, |
| 39 | observe(name: string, value: number) { |
| 40 | let h = histograms.get(name); |
| 41 | if (!h) { |
| 42 | h = { |
| 43 | reservoir: [], |
| 44 | count: 0, |
| 45 | sum: 0, |
| 46 | min: value, |
| 47 | max: value |
| 48 | }; |
| 49 | histograms.set(name, h); |
| 50 | } |
| 51 | h.count++; |
| 52 | h.sum += value; |
| 53 | if (value < h.min) { |
| 54 | h.min = value; |
| 55 | } |
| 56 | if (value > h.max) { |
| 57 | h.max = value; |
| 58 | } |
| 59 | // Reservoir sampling (Algorithm R) |
| 60 | if (h.reservoir.length < RESERVOIR_SIZE) { |
| 61 | h.reservoir.push(value); |
| 62 | } else { |
| 63 | const j = Math.floor(Math.random() * h.count); |
| 64 | if (j < RESERVOIR_SIZE) { |
| 65 | h.reservoir[j] = value; |
| 66 | } |
| 67 | } |
| 68 | }, |
| 69 | add(name: string, value: string) { |
| 70 | let s = sets.get(name); |
| 71 | if (!s) { |
| 72 | s = new Set(); |
| 73 | sets.set(name, s); |
| 74 | } |
| 75 | s.add(value); |
| 76 | }, |
| 77 | getAll() { |
| 78 | const result: Record<string, number> = Object.fromEntries(metrics); |
| 79 | for (const [name, h] of histograms) { |
| 80 | if (h.count === 0) { |
| 81 | continue; |
| 82 | } |
| 83 | result[`${name}_count`] = h.count; |
| 84 | result[`${name}_min`] = h.min; |
| 85 | result[`${name}_max`] = h.max; |
no outgoing calls
no test coverage detected