Skip to main content

rtflow_core/metrics/
histogram.rs

1//! Bounded histogram for latency and distribution metrics.
2//!
3//! Uses fixed bucket boundaries for zero-allocation recording.
4//! All operations use `Ordering::Relaxed` for minimal contention.
5
6use std::sync::atomic::{AtomicU64, Ordering};
7
8/// Fixed-boundary histogram for latency metrics.
9///
10/// Bucket boundaries are in microseconds. Recording is O(bucket_count) but
11/// bucket_count is small (typically 12-15) and all operations are lock-free.
12pub struct Histogram {
13    buckets: Vec<AtomicU64>,
14    boundaries: Vec<f64>,
15    sum: AtomicU64,
16    count: AtomicU64,
17}
18
19impl Histogram {
20    /// Create a histogram with the given bucket boundaries (in the unit of the recorded values).
21    pub fn new(boundaries: &[f64]) -> Self {
22        Self {
23            buckets: (0..=boundaries.len()).map(|_| AtomicU64::new(0)).collect(),
24            boundaries: boundaries.to_vec(),
25            sum: AtomicU64::new(0),
26            count: AtomicU64::new(0),
27        }
28    }
29
30    /// Create a histogram with latency-oriented boundaries (in milliseconds).
31    ///
32    /// Boundaries: 1ms, 5ms, 10ms, 25ms, 50ms, 100ms, 250ms, 500ms, 1s, 5s, +Inf
33    pub fn latency_ms() -> Self {
34        Self::new(&[
35            1.0, 5.0, 10.0, 25.0, 50.0, 100.0, 250.0, 500.0, 1000.0, 5000.0,
36        ])
37    }
38
39    /// Record a value into the histogram.
40    pub fn record(&self, value: f64) {
41        let bucket = self
42            .boundaries
43            .iter()
44            .position(|&b| value <= b)
45            .unwrap_or(self.boundaries.len());
46        self.buckets[bucket].fetch_add(1, Ordering::Relaxed);
47        // Store value * 1000 for microsecond precision in the sum.
48        self.sum
49            .fetch_add((value * 1000.0) as u64, Ordering::Relaxed);
50        self.count.fetch_add(1, Ordering::Relaxed);
51    }
52
53    /// Get the total number of recorded values.
54    pub fn count(&self) -> u64 {
55        self.count.load(Ordering::Relaxed)
56    }
57
58    /// Get the sum of all recorded values.
59    pub fn sum(&self) -> f64 {
60        self.sum.load(Ordering::Relaxed) as f64 / 1000.0
61    }
62
63    /// Get the approximate mean of all recorded values.
64    pub fn mean(&self) -> f64 {
65        let count = self.count();
66        if count == 0 {
67            0.0
68        } else {
69            self.sum() / count as f64
70        }
71    }
72
73    /// Get the count for each bucket (including the +Inf bucket).
74    pub fn bucket_counts(&self) -> Vec<(f64, u64)> {
75        let mut result = Vec::with_capacity(self.buckets.len());
76        for (i, boundary) in self.boundaries.iter().enumerate() {
77            result.push((*boundary, self.buckets[i].load(Ordering::Relaxed)));
78        }
79        // +Inf bucket.
80        result.push((
81            f64::INFINITY,
82            self.buckets[self.boundaries.len()].load(Ordering::Relaxed),
83        ));
84        result
85    }
86
87    /// Get the cumulative count up to and including each bucket.
88    /// This is the format used by Prometheus histograms.
89    pub fn cumulative_counts(&self) -> Vec<(f64, u64)> {
90        let mut result = Vec::with_capacity(self.buckets.len());
91        let mut cumulative = 0u64;
92        for (i, boundary) in self.boundaries.iter().enumerate() {
93            cumulative += self.buckets[i].load(Ordering::Relaxed);
94            result.push((*boundary, cumulative));
95        }
96        cumulative += self.buckets[self.boundaries.len()].load(Ordering::Relaxed);
97        result.push((f64::INFINITY, cumulative));
98        result
99    }
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105
106    #[test]
107    fn record_and_count() {
108        let h = Histogram::latency_ms();
109        assert_eq!(h.count(), 0);
110        h.record(0.5);
111        h.record(15.0);
112        h.record(100.0);
113        assert_eq!(h.count(), 3);
114    }
115
116    #[test]
117    fn buckets_are_correct() {
118        let h = Histogram::new(&[10.0, 20.0, 30.0]);
119        h.record(5.0); // bucket 0 (<=10)
120        h.record(15.0); // bucket 1 (<=20)
121        h.record(25.0); // bucket 2 (<=30)
122        h.record(35.0); // bucket 3 (+Inf)
123        let counts = h.bucket_counts();
124        assert_eq!(counts[0], (10.0, 1));
125        assert_eq!(counts[1], (20.0, 1));
126        assert_eq!(counts[2], (30.0, 1));
127        assert_eq!(counts[3], (f64::INFINITY, 1));
128    }
129
130    #[test]
131    fn cumulative_counts() {
132        let h = Histogram::new(&[10.0, 20.0]);
133        h.record(5.0);
134        h.record(5.0);
135        h.record(15.0);
136        h.record(25.0);
137        let cum = h.cumulative_counts();
138        assert_eq!(cum[0], (10.0, 2));
139        assert_eq!(cum[1], (20.0, 3));
140        assert_eq!(cum[2], (f64::INFINITY, 4));
141    }
142
143    #[test]
144    fn mean_computation() {
145        let h = Histogram::new(&[100.0]);
146        h.record(10.0);
147        h.record(20.0);
148        h.record(30.0);
149        let mean = h.mean();
150        assert!((mean - 20.0).abs() < 0.01);
151    }
152}