nmbrs-metrics 0.7.4

Metrics collection and reporting for nmbrs
Documentation
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! Gauge: instantaneous value, either settable or function-based.

use crate::labels::Labels;
use std::sync::atomic::{AtomicU64, Ordering};

/// A gauge backed by a closure (sampled at capture time).
pub struct FnGauge {
    labels: Labels,
    f: Box<dyn Fn() -> f64 + Send + Sync>,
}

impl FnGauge {
    pub fn new(labels: Labels, f: impl Fn() -> f64 + Send + Sync + 'static) -> Self {
        Self {
            labels,
            f: Box::new(f),
        }
    }

    pub fn sample(&self) -> f64 {
        (self.f)()
    }

    pub fn labels(&self) -> &Labels {
        &self.labels
    }
}

/// A gauge backed by a settable atomic value.
///
/// Beside the value it keeps the least, the greatest, the sum and the
/// count of what was set since the window was last taken (SRD-42
/// ยง"Streaming coalesce semantics"), each in its own atomic. A `set`
/// that races [`ValueGauge::take_window`] is counted once, in that
/// window or the next; its count and its sum may fall on different
/// sides, which moves each window's mean by at most that one
/// observation.
pub struct ValueGauge {
    labels: Labels,
    /// Stored as f64 bits in a u64 for atomic access.
    bits: AtomicU64,
    /// The window's least and greatest set value, as f64 bits.
    min_bits: AtomicU64,
    max_bits: AtomicU64,
    /// The sum of the window's set values, as f64 bits.
    sum_bits: AtomicU64,
    /// How many values were set in the window.
    count: AtomicU64,
    /// True once a value has been set. Until then the gauge reads
    /// 0.0, which nothing wrote and which is no observation.
    written: std::sync::atomic::AtomicBool,
}

/// Replace the f64 an atomic holds with `update` of it.
fn update_f64(bits: &AtomicU64, update: impl Fn(f64) -> f64) {
    let _ = bits.try_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
        Some(update(f64::from_bits(current)).to_bits())
    });
}

impl ValueGauge {
    pub fn new(labels: Labels) -> Self {
        Self {
            labels,
            bits: AtomicU64::new(0.0f64.to_bits()),
            min_bits: AtomicU64::new(f64::INFINITY.to_bits()),
            max_bits: AtomicU64::new(f64::NEG_INFINITY.to_bits()),
            sum_bits: AtomicU64::new(0.0f64.to_bits()),
            count: AtomicU64::new(0),
            written: std::sync::atomic::AtomicBool::new(false),
        }
    }

    pub fn set(&self, value: f64) {
        self.bits.store(value.to_bits(), Ordering::Relaxed);
        update_f64(&self.min_bits, |min| min.min(value));
        update_f64(&self.max_bits, |max| max.max(value));
        update_f64(&self.sum_bits, |sum| sum + value);
        self.count.fetch_add(1, Ordering::Relaxed);
        self.written.store(true, Ordering::Relaxed);
    }

    /// The gauge's point for the window that ends now, and the start
    /// of the next window: the last value set, with the statistics of
    /// what was set since this was last called. A window in which
    /// nothing was set observes the standing value once, unless
    /// nothing has ever been set: then it has no observation.
    ///
    /// For the one reader that closes windows (the scheduler's
    /// capture). A reader that only looks uses [`ValueGauge::get`].
    pub fn take_window(&self) -> crate::snapshot::GaugeValue {
        use crate::snapshot::{GaugeStats, GaugeValue};
        let value = self.get();
        let count = self.count.swap(0, Ordering::Relaxed);
        let sum = f64::from_bits(self.sum_bits.swap(0.0f64.to_bits(), Ordering::Relaxed));
        let min = f64::from_bits(
            self.min_bits
                .swap(f64::INFINITY.to_bits(), Ordering::Relaxed),
        );
        let max = f64::from_bits(
            self.max_bits
                .swap(f64::NEG_INFINITY.to_bits(), Ordering::Relaxed),
        );
        // A count with no least or greatest yet is a set caught half
        // way; its value is the standing one.
        if count == 0 || min > max {
            return if self.written.load(Ordering::Relaxed) {
                GaugeValue::new(value)
            } else {
                GaugeValue::observed(value, GaugeStats::EMPTY)
            };
        }
        GaugeValue::observed(
            value,
            GaugeStats {
                min,
                max,
                sum,
                count,
            },
        )
    }

    pub fn get(&self) -> f64 {
        f64::from_bits(self.bits.load(Ordering::Relaxed))
    }

    pub fn labels(&self) -> &Labels {
        &self.labels
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use std::sync::atomic::AtomicU64;

    #[test]
    fn fn_gauge_samples() {
        let counter = Arc::new(AtomicU64::new(42));
        let c = counter.clone();
        let g = FnGauge::new(Labels::of("name", "active"), move || {
            c.load(Ordering::Relaxed) as f64
        });
        assert_eq!(g.sample(), 42.0);
        counter.store(100, Ordering::Relaxed);
        assert_eq!(g.sample(), 100.0);
    }

    /// A window holds the statistics of what was set in it, and the
    /// next window starts empty: with nothing set it observes the
    /// standing value once.
    #[test]
    fn a_window_keeps_the_least_greatest_and_mean_of_what_was_set() {
        use crate::snapshot::GaugeStats;
        let g = ValueGauge::new(Labels::of("name", "depth"));
        // Before anything is set there is nothing to observe.
        assert_eq!(g.take_window().stats, GaugeStats::EMPTY);
        for value in [3.0, 9.0, 1.0, 5.0] {
            g.set(value);
        }
        let window = g.take_window();
        assert_eq!(window.value, 5.0, "the value is the last one set");
        assert_eq!(
            window.stats,
            GaugeStats {
                min: 1.0,
                max: 9.0,
                sum: 18.0,
                count: 4,
            }
        );
        assert_eq!(window.stats.mean(), 4.5);

        let quiet = g.take_window();
        assert_eq!(quiet.value, 5.0);
        assert_eq!(quiet.stats, GaugeStats::of(5.0));
        // Looking does not close a window.
        g.set(7.0);
        assert_eq!(g.get(), 7.0);
        assert_eq!(g.take_window().stats, GaugeStats::of(7.0));
    }

    #[test]
    fn value_gauge_set_get() {
        let g = ValueGauge::new(Labels::of("name", "temp"));
        assert_eq!(g.get(), 0.0);
        g.set(72.5);
        assert_eq!(g.get(), 72.5);
    }
}