embeprom 0.3.0

Heapless Prometheus metrics for no_std embedded systems
Documentation
//! The central metrics registry: a fixed-capacity list of registered
//! [`MetricGroup`]s. Groups can be added explicitly via [`register`], or
//! self-register lazily on first access via [`OnceRegister`] (used by the
//! accessor function generated by [`crate::metrics!`]).

use core::cell::RefCell;
use core::fmt;

use critical_section::Mutex;
use heapless::Vec;
use portable_atomic::{AtomicBool, Ordering};

use crate::erased::MetricGroup;

fn same_group(a: &dyn MetricGroup, b: &dyn MetricGroup) -> bool {
    core::ptr::addr_eq(a, b)
}

/// Returned by [`Registry::register`] when the registry is already at
/// capacity `N`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RegistryFull;

impl fmt::Display for RegistryFull {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("the metrics registry is full")
    }
}

impl core::error::Error for RegistryFull {}

/// A snapshot of the groups registered with a [`Registry`] at a point in time.
pub type GroupSnapshot<const N: usize = { crate::config::MAX_GROUPS }> =
    Vec<&'static dyn MetricGroup, N>;

/// A fixed-capacity registry of metric groups, holding at most `N` groups.
pub struct Registry<const N: usize = { crate::config::MAX_GROUPS }> {
    groups: Mutex<RefCell<Vec<&'static dyn MetricGroup, N>>>,
}

impl<const N: usize> Registry<N> {
    /// Create an empty registry.
    pub const fn new() -> Self {
        Self {
            groups: Mutex::new(RefCell::new(Vec::new())),
        }
    }

    /// Register a metric group. Registering the same group (by static
    /// identity) more than once is a no-op, so explicit [`register`] calls can
    /// coexist with a group that also self-registers via [`OnceRegister`].
    ///
    /// # Errors
    ///
    /// Returns [`RegistryFull`] if the registry already contains `N`
    /// distinct groups.
    pub fn register(&self, group: &'static dyn MetricGroup) -> Result<(), RegistryFull> {
        critical_section::with(|cs| {
            let mut groups = self.groups.borrow_ref_mut(cs);
            if groups.iter().any(|g| same_group(*g, group)) {
                return Ok(());
            }
            groups.push(group).map_err(|_| RegistryFull)
        })
    }

    /// Copy out the currently registered groups.
    pub fn snapshot(&self) -> Vec<&'static dyn MetricGroup, N> {
        critical_section::with(|cs| self.groups.borrow_ref(cs).clone())
    }
}

impl<const N: usize> Default for Registry<N> {
    fn default() -> Self {
        Self::new()
    }
}

// Keep the singleton private so all global access goes through the small
// registration and snapshot API. Caller-owned registries are ordinary
// `Registry<N>` statics and can be rendered directly.
static GLOBAL: Registry = Registry::new();

/// Register a metric group with the global registry.
///
/// Call this once per crate/library at startup, e.g.:
///
/// ```
/// # mod metrics {
/// #     embeprom::metrics! {
/// #         /// Total requests.
/// #         requests: Counter,
/// #     }
/// # }
/// embeprom::register(&metrics::METRICS).unwrap();
/// ```
///
/// Metrics groups declared with [`crate::metrics!`] self-register on first
/// access (see [`OnceRegister`]), so calling this explicitly is optional for
/// them. Explicit registration makes every metric visible from boot and lets
/// startup code decide how to handle insufficient registry capacity.
///
/// # Errors
///
/// Returns [`RegistryFull`] if the global registry is already at capacity.
pub fn register(group: &'static dyn MetricGroup) -> Result<(), RegistryFull> {
    GLOBAL.register(group)
}

/// Copy out the groups currently registered with the global registry.
pub fn snapshot() -> GroupSnapshot {
    GLOBAL.snapshot()
}

/// A one-shot guard that registers a metric group with the global registry
/// on the first call to [`ensure`](Self::ensure), and does nothing on every
/// subsequent call. Used by the accessor function generated by
/// [`crate::metrics!`] so that recording a metric for the first time
/// self-registers its group, with no explicit `main()`-side call needed.
///
/// The uncontended one-time cost is a single [`register`] call; every
/// later call is one `Acquire` load of an atomic state. A caller concurrent
/// with the first registration may repeat the deduplicated registration
/// attempt rather than returning while another caller is still working. If
/// the registry is full, the failure is reported at most once per `OnceRegister`
/// (i.e. at most once per metrics group, not once per metric write) via a
/// `log::error!` when the `log` feature is enabled, and silently otherwise —
/// either way, the group's metrics are simply absent from the render output
/// rather than causing a panic deep in a hot path.
pub struct OnceRegister {
    registered: AtomicBool,
}

impl OnceRegister {
    /// Create a new, not-yet-registered guard.
    pub const fn new() -> Self {
        Self {
            registered: AtomicBool::new(false),
        }
    }

    /// Register `group` with the global registry if this is the first call;
    /// a no-op on every later call.
    pub fn ensure(&self, group: &'static dyn MetricGroup) {
        self.ensure_with(group, || register(group));
    }

    /// Register `group` with `registry` if this is the first call; a no-op on
    /// every later call. This is used by `metrics! { registry = REGISTRY; ... }`
    /// to retain register-on-first-use with a caller-owned registry.
    pub fn ensure_in<const N: usize>(
        &self,
        registry: &Registry<N>,
        group: &'static dyn MetricGroup,
    ) {
        self.ensure_with(group, || registry.register(group));
    }

    fn ensure_with(
        &self,
        group: &'static dyn MetricGroup,
        register: impl FnOnce() -> Result<(), RegistryFull>,
    ) {
        if self.registered.load(Ordering::Acquire) {
            return;
        }

        // Concurrent first callers may all reach this point. Repeating the
        // attempt is safe because Registry::register deduplicates the group,
        // and it ensures that no caller returns before attempting registration.
        let result = register();
        if !self.registered.swap(true, Ordering::AcqRel) {
            #[cfg(feature = "log")]
            if result.is_err() {
                log::error!(
                    "embeprom: metric group \"{}\" did not self-register: registry is full \
                     (increase its capacity); its metrics will be absent from scrapes",
                    group.group_name()
                );
            }
        }

        #[cfg(not(feature = "log"))]
        let _ = (group, result);
    }
}

impl Default for OnceRegister {
    fn default() -> Self {
        Self::new()
    }
}

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

    mod a_metrics {
        crate::metrics! {
            registration = manual;
            namespace = "a";

            /// Test counter A.
            value: Counter,
        }
    }

    mod b_metrics {
        crate::metrics! {
            registration = manual;
            namespace = "b";

            /// Test counter B.
            value: Counter,
        }
    }

    mod c_metrics {
        crate::metrics! {
            registration = manual;
            namespace = "c";

            /// Test counter C.
            value: Counter,
        }
    }

    mod d_metrics {
        crate::metrics! {
            registration = manual;
            namespace = "d";

            /// Test counter D.
            value: Counter,
        }
    }

    #[test]
    fn registers_and_snapshots() {
        let r: Registry<2> = Registry::new();
        assert!(r.snapshot().is_empty());

        r.register(a_metrics::get()).unwrap();
        r.register(b_metrics::get()).unwrap();

        let snap = r.snapshot();
        assert_eq!(snap.len(), 2);
        assert_eq!(snap[0].group_name(), "a");
        assert_eq!(snap[1].group_name(), "b");
    }

    #[test]
    fn register_reports_full() {
        let r: Registry<1> = Registry::new();
        assert_eq!(r.register(a_metrics::get()), Ok(()));
        assert_eq!(r.register(b_metrics::get()), Err(RegistryFull));
        assert_eq!(r.snapshot().len(), 1);

        let mut message = heapless::String::<64>::new();
        core::fmt::Write::write_fmt(&mut message, format_args!("{RegistryFull}")).unwrap();
        assert_eq!(message, "the metrics registry is full");
    }

    #[test]
    fn registering_the_same_group_twice_is_a_no_op() {
        let r: Registry<1> = Registry::new();
        assert_eq!(r.register(a_metrics::get()), Ok(()));
        assert_eq!(r.register(a_metrics::get()), Ok(()));
        assert_eq!(r.snapshot().len(), 1);
    }

    #[test]
    fn global_registry_accepts_registration() {
        register(c_metrics::get()).unwrap();
        assert_eq!(
            snapshot()
                .iter()
                .filter(|g| core::ptr::addr_eq(**g, c_metrics::get()))
                .count(),
            1
        );
    }

    #[test]
    fn once_register_registers_exactly_once() {
        let once = OnceRegister::new();

        once.ensure(d_metrics::get());
        once.ensure(d_metrics::get());
        once.ensure(d_metrics::get());
        assert_eq!(
            snapshot()
                .iter()
                .filter(|g| core::ptr::addr_eq(**g, d_metrics::get()))
                .count(),
            1
        );
    }

    #[test]
    fn once_register_can_target_a_caller_owned_registry() {
        let registry: Registry<1> = Registry::new();
        let once = OnceRegister::new();

        once.ensure_in(&registry, a_metrics::get());
        once.ensure_in(&registry, a_metrics::get());
        assert_eq!(registry.snapshot().len(), 1);
    }

    #[test]
    fn completed_registration_skips_later_attempts() {
        let once = OnceRegister::new();
        let attempts = core::cell::Cell::new(0);

        once.ensure_with(a_metrics::get(), || {
            attempts.set(attempts.get() + 1);
            Ok(())
        });
        once.ensure_with(a_metrics::get(), || {
            attempts.set(attempts.get() + 1);
            Ok(())
        });

        assert_eq!(attempts.get(), 1);
    }
}