embeprom 0.3.0

Heapless Prometheus metrics for no_std embedded systems
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//! Histograms with fixed, compile-time-declared bucket boundaries.

use portable_atomic::{AtomicU64, Ordering};

use crate::erased::ErasedHistogram;
#[cfg(feature = "consistent-histograms")]
use crate::erased::{HistogramSnapshot, HistogramSnapshotError, snapshot_bucket_prefix};
#[cfg(feature = "float")]
use crate::series::HistSeries;
use crate::series::IntHistSeries;
use crate::value::Value;

pub(crate) const fn validate_u64_bounds<const B: usize>(bounds: &[u64]) {
    assert!(
        bounds.len() == B,
        "embeprom: histogram bounds.len() must equal B"
    );
    let mut i = 1;
    while i < B {
        assert!(
            bounds[i - 1] < bounds[i],
            "embeprom: histogram bounds must be strictly increasing"
        );
        i += 1;
    }
}

#[cfg(feature = "float")]
pub(crate) const fn validate_f64_bounds<const B: usize>(bounds: &[f64]) {
    assert!(
        bounds.len() == B,
        "embeprom: histogram bounds.len() must equal B"
    );
    let mut i = 0;
    while i < B {
        assert!(
            bounds[i].is_finite(),
            "embeprom: histogram bounds must be finite"
        );
        if i > 0 {
            assert!(
                bounds[i - 1] < bounds[i],
                "embeprom: histogram bounds must be strictly increasing"
            );
        }
        i += 1;
    }
}

/// A Prometheus histogram over `u64` observations, with `B` finite buckets
/// plus an implicit `+Inf` bucket (represented by `count`).
///
/// [`Self::series`] returns the same handle type as
/// [`crate::IntHistogramVec::with`].
///
/// Bucket counts are stored non-cumulatively and accumulated with one rolling
/// total at render time. Each finite bucket is read once, so both observation
/// and rendering are linear scans with `observe` performing exactly 3 atomic
/// ops regardless of `B`.
///
/// The `_bucket`, `_sum`, and `_count` values are independent atomics. A
/// concurrent line-by-line render can therefore combine values from different
/// instants: `_count` may lead the rendered finite buckets, or a finite bucket
/// may briefly exceed the subsequently read `_count`. Enable the
/// `consistent-histograms` feature to serialize observations and let the
/// renderer take one coherent snapshot for every histogram family when that
/// matters.
pub struct IntHistogram<const B: usize> {
    bounds: &'static [u64],
    buckets: [AtomicU64; B],
    sum: AtomicU64,
    count: AtomicU64,
}

impl<const B: usize> IntHistogram<B> {
    /// Create a histogram with strictly increasing bucket upper bounds
    /// (exclusive of the implicit `+Inf` bucket). `bounds.len()` must equal
    /// `B`; invalid bounds panic, including during const evaluation.
    pub const fn new(bounds: &'static [u64]) -> Self {
        validate_u64_bounds::<B>(bounds);
        Self {
            bounds,
            buckets: [const { AtomicU64::new(0) }; B],
            sum: AtomicU64::new(0),
            count: AtomicU64::new(0),
        }
    }

    /// Record an observation.
    #[cfg(not(feature = "consistent-histograms"))]
    #[inline]
    pub fn observe(&self, v: u64) {
        self.observe_inner(v);
    }

    /// Record an observation. Wrapped in a critical section so `_bucket`,
    /// `_sum`, and `_count` are always mutually consistent under a concurrent
    /// render (feature `consistent-histograms`).
    #[cfg(feature = "consistent-histograms")]
    #[inline]
    pub fn observe(&self, v: u64) {
        critical_section::with(|_cs| self.observe_inner(v));
    }

    #[inline]
    fn observe_inner(&self, v: u64) {
        if let Some(i) = self.bounds.iter().position(|bound| v <= *bound) {
            self.buckets[i].fetch_add(1, Ordering::Relaxed);
        }
        self.sum.fetch_add(v, Ordering::Relaxed);
        self.count.fetch_add(1, Ordering::Relaxed);
    }

    /// The bucket upper bounds, ascending, excluding the implicit `+Inf` bucket.
    pub fn bounds(&self) -> &'static [u64] {
        self.bounds
    }

    /// The non-cumulative count for bucket `i` (i.e. observations that fell
    /// into `(bounds[i-1], bounds[i]]`, or `[0, bounds[0]]` for `i == 0`).
    pub fn bucket(&self, i: usize) -> u64 {
        self.buckets[i].load(Ordering::Relaxed)
    }

    /// Total number of observations (equal to the cumulative `+Inf` bucket).
    pub fn count(&self) -> u64 {
        self.count.load(Ordering::Relaxed)
    }

    /// Sum of all observed values.
    pub fn sum(&self) -> u64 {
        self.sum.load(Ordering::Relaxed)
    }

    /// A series handle for this histogram. Same type as
    /// [`crate::IntHistogramVec::with`], so one helper can accept both an
    /// unlabeled histogram and a bound labeled series.
    ///
    /// ```
    /// fn observe_us<'a>(metric: impl Into<embeprom::IntHistSeries<'a>>, v: u64) {
    ///     metric.into().observe(v);
    /// }
    ///
    /// let scalar = embeprom::IntHistogram::<2>::new(&[100, 1000]);
    /// static PEER: [&str; 1] = ["peer"];
    /// let labeled = embeprom::IntHistogramVec::<4, 2>::new(&PEER, &[100, 1000]);
    ///
    /// observe_us(&scalar, 50);
    /// observe_us(labeled.with(&["ap-1"]), 50);
    /// assert_eq!(scalar.count(), 1);
    /// assert_eq!(labeled.with(&["ap-1"]).count(), 1);
    /// ```
    pub fn series(&self) -> IntHistSeries<'_> {
        IntHistSeries::bound(self.bounds, &self.buckets, &self.sum, &self.count)
    }
}

impl<'a, const B: usize> From<&'a IntHistogram<B>> for IntHistSeries<'a> {
    fn from(histogram: &'a IntHistogram<B>) -> Self {
        histogram.series()
    }
}

impl<const B: usize> ErasedHistogram for IntHistogram<B> {
    fn bucket_count(&self) -> usize {
        B
    }
    fn bound(&self, b: usize) -> Value {
        Value::U64(self.bounds[b])
    }
    fn bucket(&self, b: usize) -> u64 {
        IntHistogram::bucket(self, b)
    }
    fn total_count(&self) -> u64 {
        self.count()
    }
    fn sum(&self) -> Value {
        Value::U64(IntHistogram::sum(self))
    }
    #[cfg(feature = "consistent-histograms")]
    fn snapshot<'a>(
        &self,
        buckets: &'a mut [u64],
    ) -> Result<HistogramSnapshot<'a>, HistogramSnapshotError> {
        let buckets = snapshot_bucket_prefix(buckets, B)?;
        critical_section::with(|_cs| {
            for (snapshot_bucket, bucket) in buckets.iter_mut().zip(&self.buckets) {
                *snapshot_bucket = bucket.load(Ordering::Relaxed);
            }
            Ok(HistogramSnapshot {
                buckets,
                sum: Value::U64(self.sum.load(Ordering::Relaxed)),
                count: self.count.load(Ordering::Relaxed),
            })
        })
    }
}

/// A Prometheus histogram over `f64` observations. See [`IntHistogram`] for
/// the storage and consistency model; prefer `IntHistogram` when values are
/// naturally integral, since `f64` atomics have no native CAS on most
/// Cortex-M cores.
#[cfg(feature = "float")]
pub struct Histogram<const B: usize> {
    bounds: &'static [f64],
    buckets: [AtomicU64; B],
    sum: portable_atomic::AtomicF64,
    count: AtomicU64,
}

#[cfg(feature = "float")]
impl<const B: usize> Histogram<B> {
    /// Create a histogram with strictly increasing, finite bucket upper bounds
    /// (exclusive of the implicit `+Inf` bucket). `bounds.len()` must equal
    /// `B`; invalid bounds panic, including during const evaluation.
    pub const fn new(bounds: &'static [f64]) -> Self {
        validate_f64_bounds::<B>(bounds);
        Self {
            bounds,
            buckets: [const { AtomicU64::new(0) }; B],
            sum: portable_atomic::AtomicF64::new(0.0),
            count: AtomicU64::new(0),
        }
    }

    /// Record an observation.
    #[cfg(not(feature = "consistent-histograms"))]
    #[inline]
    pub fn observe(&self, v: f64) {
        self.observe_inner(v);
    }

    /// Record an observation, wrapped in a critical section for consistency
    /// (feature `consistent-histograms`). See [`IntHistogram::observe`].
    #[cfg(feature = "consistent-histograms")]
    #[inline]
    pub fn observe(&self, v: f64) {
        critical_section::with(|_cs| self.observe_inner(v));
    }

    #[inline]
    fn observe_inner(&self, v: f64) {
        // NaN is not <= any finite bound. Match Prometheus client behavior by
        // counting it only in the implicit +Inf bucket (while the sum becomes
        // NaN), rather than accidentally assigning it to the first bucket.
        if let Some(i) = self.bounds.iter().position(|bound| v <= *bound) {
            self.buckets[i].fetch_add(1, Ordering::Relaxed);
        }
        self.sum.fetch_add(v, Ordering::Relaxed);
        self.count.fetch_add(1, Ordering::Relaxed);
    }

    /// The bucket upper bounds, ascending, excluding the implicit `+Inf` bucket.
    pub fn bounds(&self) -> &'static [f64] {
        self.bounds
    }

    /// The non-cumulative count for bucket `i`.
    pub fn bucket(&self, i: usize) -> u64 {
        self.buckets[i].load(Ordering::Relaxed)
    }

    /// Total number of observations (equal to the cumulative `+Inf` bucket).
    pub fn count(&self) -> u64 {
        self.count.load(Ordering::Relaxed)
    }

    /// Sum of all observed values.
    pub fn sum(&self) -> f64 {
        self.sum.load(Ordering::Relaxed)
    }

    /// A series handle for this histogram. Same type as [`crate::HistogramVec::with`].
    pub fn series(&self) -> HistSeries<'_> {
        HistSeries::bound(self.bounds, &self.buckets, &self.sum, &self.count)
    }
}

#[cfg(feature = "float")]
impl<'a, const B: usize> From<&'a Histogram<B>> for HistSeries<'a> {
    fn from(histogram: &'a Histogram<B>) -> Self {
        histogram.series()
    }
}

#[cfg(feature = "float")]
impl<const B: usize> ErasedHistogram for Histogram<B> {
    fn bucket_count(&self) -> usize {
        B
    }
    fn bound(&self, b: usize) -> Value {
        Value::F64(self.bounds[b])
    }
    fn bucket(&self, b: usize) -> u64 {
        Histogram::bucket(self, b)
    }
    fn total_count(&self) -> u64 {
        self.count()
    }
    fn sum(&self) -> Value {
        Value::F64(Histogram::sum(self))
    }
    #[cfg(feature = "consistent-histograms")]
    fn snapshot<'a>(
        &self,
        buckets: &'a mut [u64],
    ) -> Result<HistogramSnapshot<'a>, HistogramSnapshotError> {
        let buckets = snapshot_bucket_prefix(buckets, B)?;
        critical_section::with(|_cs| {
            for (snapshot_bucket, bucket) in buckets.iter_mut().zip(&self.buckets) {
                *snapshot_bucket = bucket.load(Ordering::Relaxed);
            }
            Ok(HistogramSnapshot {
                buckets,
                sum: Value::F64(self.sum.load(Ordering::Relaxed)),
                count: self.count.load(Ordering::Relaxed),
            })
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn buckets_and_sum_and_count() {
        let h: IntHistogram<4> = IntHistogram::new(&[100, 500, 1000, 5000]);
        for v in [12, 480, 480, 999, 4999, 4999, 10_000] {
            h.observe(v);
        }
        assert_eq!(h.bucket(0), 1); // <= 100
        assert_eq!(h.bucket(1), 2); // (100, 500]
        assert_eq!(h.bucket(2), 1); // (500, 1000]
        assert_eq!(h.bucket(3), 2); // (1000, 5000]
        assert_eq!(h.count(), 7); // includes the 10_000 +Inf observation
        assert_eq!(h.sum(), 12 + 480 + 480 + 999 + 4999 + 4999 + 10_000);
    }

    #[cfg(feature = "consistent-histograms")]
    #[test]
    fn coherent_snapshot_names_values_and_reports_a_short_buffer() {
        let h: IntHistogram<2> = IntHistogram::new(&[100, 500]);
        h.observe(50);
        h.observe(250);
        h.observe(1_000);

        let error = ErasedHistogram::snapshot(&h, &mut [0; 1]).unwrap_err();
        assert_eq!(
            error,
            HistogramSnapshotError {
                required: 2,
                capacity: 1,
            }
        );

        let mut buckets = [0; 3];
        let snapshot = ErasedHistogram::snapshot(&h, &mut buckets).unwrap();
        assert_eq!(snapshot.buckets, &[1, 1]);
        assert_eq!(snapshot.sum, Value::U64(1_300));
        assert_eq!(snapshot.count, 3);
    }

    #[test]
    #[should_panic(expected = "histogram bounds must be strictly increasing")]
    fn integer_histogram_rejects_duplicate_bounds() {
        let _ = IntHistogram::<3>::new(&[10, 10, 20]);
    }

    #[test]
    #[should_panic(expected = "histogram bounds must be strictly increasing")]
    fn integer_histogram_rejects_descending_bounds() {
        let _ = IntHistogram::<3>::new(&[10, 30, 20]);
    }

    #[cfg(feature = "float")]
    #[test]
    fn float_histogram_buckets() {
        let h: Histogram<2> = Histogram::new(&[0.5, 1.0]);
        h.observe(0.25);
        h.observe(0.75);
        h.observe(2.0);
        assert_eq!(h.bucket(0), 1);
        assert_eq!(h.bucket(1), 1);
        assert_eq!(h.count(), 3);
        assert_eq!(h.sum().to_bits(), 3.0_f64.to_bits());
    }

    #[cfg(feature = "float")]
    #[test]
    fn float_histogram_routes_nan_only_to_the_implicit_infinite_bucket() {
        let h: Histogram<2> = Histogram::new(&[0.5, 1.0]);
        h.observe(f64::NAN);

        assert_eq!(h.bucket(0), 0);
        assert_eq!(h.bucket(1), 0);
        assert_eq!(h.count(), 1);
        assert!(h.sum().is_nan());
    }

    #[cfg(feature = "float")]
    #[test]
    #[should_panic(expected = "histogram bounds must be finite")]
    fn float_histogram_rejects_nan_bounds() {
        let _ = Histogram::<2>::new(&[0.5, f64::NAN]);
    }

    #[cfg(feature = "float")]
    #[test]
    #[should_panic(expected = "histogram bounds must be finite")]
    fn float_histogram_rejects_infinite_bounds() {
        let _ = Histogram::<2>::new(&[0.5, f64::INFINITY]);
    }
}