indexbus_platform_obs/
metrics_init.rs

1//! Metrics wiring helpers.
2//!
3//! This crate intentionally keeps the metrics surface small:
4//! - With `metrics`, you can emit metrics via the `metrics` macros.
5//! - With `metrics-prometheus`, you can install a Prometheus recorder and get a handle
6//!   to render the current metrics snapshot.
7
8#[cfg(feature = "metrics")]
9use crate::errors::{Error, Result};
10
11#[cfg(feature = "metrics-prometheus")]
12use metrics_exporter_prometheus::PrometheusHandle;
13
14/// Install a Prometheus metrics recorder and return a handle to render metrics.
15///
16/// This does **not** start an HTTP server; applications can expose `handle.render()` on
17/// their own HTTP stack.
18#[cfg(feature = "metrics-prometheus")]
19pub fn init_prometheus_recorder() -> Result<PrometheusHandle> {
20    metrics_exporter_prometheus::PrometheusBuilder::new()
21        .install_recorder()
22        .map_err(|e| Error::MetricsInit(e.to_string()))
23}
24
25#[cfg(all(test, feature = "metrics-prometheus"))]
26mod tests {
27    use super::*;
28
29    #[test]
30    fn init_prometheus_recorder_fails_if_called_twice() {
31        let _ = init_prometheus_recorder().expect("first init");
32        let second = init_prometheus_recorder();
33        assert!(matches!(second, Err(crate::errors::Error::MetricsInit(_))));
34    }
35}