embeprom 0.3.0

Heapless Prometheus metrics for no_std embedded systems
Documentation
#![no_std]
#![forbid(unsafe_code)]

//! Prometheus-style metrics for `no_std` embedded devices, with no heap
//! allocation.
//!
//! # Declaring metrics
//!
//! Each crate/binary declares the metrics it exports with [`metrics!`],
//! inside a dedicated module. It expands to a real `Metrics` struct (one field
//! per metric, so IDE autocomplete and find-usages work at call sites), a
//! `METRICS` static, a `get()` accessor, and the internal registration metadata
//! used by the renderer.
//!
//! ```
//! /// Wi-Fi driver metrics.
//! pub mod metrics {
//!     embeprom::metrics! {
//!         namespace = "wifi";
//!
//!         /// Total Wi-Fi frames transmitted.
//!         packets_sent: Counter,
//!         /// Last measured RSSI in dBm.
//!         rssi_dbm: Gauge,
//!         /// Disconnects, by reason.
//!         #[labels("reason")]
//!         disconnects_total: CounterVec<4>,
//!         /// TX completion latency in microseconds.
//!         #[buckets(100, 500, 1000, 5000)]
//!         tx_latency_us: IntHistogram,
//!     }
//! }
//!
//! // Anywhere in the crate, with no collector object to thread through, and
//! // no separate registration step: the first call to `metrics::get()`
//! // registers the group with the global registry (see "Registration" below).
//! metrics::get().packets_sent.inc();
//! metrics::get().disconnects_total.inc(&["beacon_timeout"]);
//! metrics::get().tx_latency_us.observe(42);
//! ```
//!
//! # Interrupt-context safety
//!
//! > **Warning:** metric access is not interrupt-safe on targets that have
//! > pointer-width atomic compare-and-swap but lack native 64-bit atomics.
//!
//! On those targets, `portable-atomic` implements the `u64`, `i64`, and `f64`
//! storage used by metrics with global locks. `thumbv7em-none-eabihf` is one
//! affected target. If foreground code is preempted while it holds one of
//! those locks and an interrupt handler accesses the same metric — or another
//! metric mapped to the same fallback lock — the interrupt handler spins while
//! the foreground code cannot resume to release the lock, causing a deadlock.
//!
//! The `cs-atomics` feature supplies atomic compare-and-swap through
//! `critical-section` on targets that lack it, such as
//! `thumbv6m-none-eabi`. It does **not** replace the global-lock 64-bit
//! fallback on targets such as `thumbv7em-none-eabihf`, which already have
//! pointer-width compare-and-swap. No `embeprom` feature currently removes
//! this restriction on those targets.
//!
//! Until the storage implementation changes, do not access or render metrics
//! from an interrupt handler on an affected target when foreground code can
//! also access metrics. See the
//! [`portable-atomic` fallback documentation](https://docs.rs/portable-atomic/latest/portable_atomic/)
//! for the underlying implementation choices and their system-level safety
//! requirements.
//!
//! # Registration
//!
//! The `get()` accessor generated by [`metrics!`] (`metrics::get()` above)
//! self-registers its group with the global registry the first time it's
//! called — via [`OnceRegister`], a one-shot guard, so this costs one atomic
//! load on every call after registration completes. A caller concurrent with
//! the first registration may make a harmless deduplicated attempt of its
//! own. No explicit step is required in `main()`, but one is available when
//! the application wants eager registration or explicit capacity handling.
//!
//! This means a metrics group that's declared but never recorded stays
//! absent from scrapes until first touched (it isn't visible at `0` from
//! boot the way an eagerly-registered metric would be). If a group's first
//! recording happens to occur when the global registry is already at
//! capacity (see [`MAX_GROUPS`]), that group's metrics are
//! silently dropped from future scrapes rather than panicking — logged once
//! per group via `log::error!` if the `log` feature is enabled.
//!
//! To register a group eagerly instead (so it's visible at `0` from boot),
//! or to make a full registry a hard startup failure rather than a silent
//! one, call [`register`] explicitly, e.g. in `main()`:
//!
//! ```
//! # mod metrics {
//! #     embeprom::metrics! {
//! #         /// Total Wi-Fi frames transmitted.
//! #         packets_sent: Counter,
//! #     }
//! # }
//! embeprom::register(&metrics::METRICS).unwrap();
//! ```
//!
//! Calling [`register`] for a group that already self-registered (or vice
//! versa) is safe: [`Registry::register`] dedups by static identity, so
//! a group is never counted twice.
//!
//! A caller-owned registry can have any capacity and does not need to be
//! visible to the crates declaring metrics. The final application can
//! explicitly register their public `METRICS` statics and render its registry
//! directly:
//!
//! ```
//! mod dependency_metrics {
//!     embeprom::metrics! {
//!         /// Completed jobs.
//!         jobs_completed: Counter,
//!     }
//! }
//!
//! static REGISTRY: embeprom::Registry<8> = embeprom::Registry::new();
//! REGISTRY.register(&dependency_metrics::METRICS).unwrap();
//! dependency_metrics::get().jobs_completed.inc();
//! let mut renderer = embeprom::Renderer::<8>::from_registry(&REGISTRY);
//! assert!(renderer.next_line().unwrap().is_some());
//! ```
//!
//! The same group may coexist in the global and caller-owned registries; each
//! registry deduplicates it independently. A declaration can instead use
//! `metrics! { registry = PATH; ... }` to lazily target a visible registry, or
//! `metrics! { registration = manual; ... }` to opt that group out of global
//! self-registration entirely.
//!
//! # Exporting
//!
//! [`Renderer`] is a pull-based cursor over every registered group's
//! metrics, rendered into Prometheus text exposition format. It's
//! deliberately synchronous and `no_std` so it has no opinion about how
//! bytes reach the network; the caller drives it, awaiting between lines as
//! needed:
//!
//! ```
//! let mut renderer = embeprom::Renderer::new();
//! while let Some(line) = renderer.next_line().unwrap() {
//!     // send `line.as_bytes()` to whatever sink you have.
//! }
//! ```
//!
//! [`Renderer::new`] snapshots the built-in global registry. Render a specific
//! caller-owned registry with [`Renderer::from_registry`]:
//!
//! ```
//! let registry = embeprom::Registry::<4>::new();
//! let mut renderer = embeprom::Renderer::<4>::from_registry(&registry);
//! assert_eq!(renderer.next_line(), Ok(None));
//! ```
//!
//! The default renderer holds one line of at most [`MAX_LINE`] bytes. Select a
//! different bound with `Renderer::with_line_capacity::<512>()`.
//! [`RenderError::LineTooLong`] reports the exact required capacity and is
//! returned once; the cursor skips that line, so the caller can report the
//! error and continue calling [`Renderer::next_line`] through the end of the
//! exposition. A histogram snapshot-capacity error similarly skips the
//! affected metric family.
//! When `consistent-histograms` is enabled, the renderer also holds reusable
//! scratch for [`MAX_HISTOGRAM_BUCKETS`] finite buckets. Tune both bounds with
//! `Renderer::with_capacities::<LINE, HIST_BUCKETS>()`.
//!
//! For a synchronous sink implementing [`core::fmt::Write`], use
//! [`write_all`] instead.
//!
//! ## Serving over HTTP with `picoserve`
//!
//! `embeprom` has no dependency on `picoserve` (or any HTTP server), but its
//! pull-based renderer is a direct match for `picoserve`'s chunked response
//! body: a `Chunks` implementation writes one rendered line per HTTP chunk
//! and awaits between lines.
//!
//! ```ignore
//! use picoserve::response::chunked::{ChunkWriter, Chunks, ChunksWritten};
//!
//! struct MetricsResponse;
//!
//! impl Chunks for MetricsResponse {
//!     fn content_type(&self) -> &'static str {
//!         embeprom::CONTENT_TYPE
//!     }
//!
//!     async fn write_chunks<W: picoserve::io::Write>(
//!         self,
//!         mut chunk_writer: ChunkWriter<W>,
//!     ) -> Result<ChunksWritten, W::Error> {
//!         let mut renderer = embeprom::Renderer::new();
//!         while let Some(line) = renderer
//!             .next_line()
//!             .expect("increase the Renderer line capacity")
//!         {
//!             chunk_writer.write_chunk(line.as_bytes()).await?;
//!         }
//!         chunk_writer.finalize().await
//!     }
//! }
//!
//! // route:
//! // picoserve::routing::get(|| async {
//! //     picoserve::response::chunked::ChunkedResponse::new(MetricsResponse)
//! // })
//! ```
//!
//! [`Content`](https://docs.rs/picoserve/latest/picoserve/response/trait.Content.html)
//! (picoserve's fixed-length response body trait) is deliberately not used
//! here: it requires knowing the total body length up front. A discarded
//! render pass cannot provide that guarantee because metrics and labeled
//! series can change before the response body is rendered.
//!
//! # Labeled metrics and cardinality
//!
//! [`CounterVec`], [`GaugeVec`], [`IntHistogramVec`] (and, with the `float`
//! feature, `GaugeF64Vec` and `HistogramVec`) each declare a maximum number of
//! distinct label-value combinations via a const generic (e.g. `CounterVec<4>`
//! for up to 4 series). Once that capacity is exhausted, newly observed label
//! combinations are silently routed to unrendered sink handles whose updates
//! are no-ops, while existing series keep updating normally. Oversized
//! rendered label blocks use the same sink behavior.
//!
//! For stable label values, call `with` once during initialization and retain
//! its series handle. Updating that handle accesses the metric storage
//! directly, avoiding repeated label construction and label-map lookup. The
//! convenience methods that accept label values perform a lookup on every
//! call and are best reserved for dynamic or infrequent labels. Bound series
//! handles are readable the same way as the corresponding scalar types
//! (`get` on counters/gauges; `bounds` / `bucket` / `count` / `sum` on
//! histograms). Sink handles read as zero.
//!
//! [`IntHistogram::series`] and [`IntHistogramVec::with`] both return
//! [`IntHistSeries`] (and the same for the `float` histogram types), so a
//! helper can take `impl Into<IntHistSeries<'a>>` and accept either an
//! unlabeled histogram or a bound labeled series.

mod config;
mod counter;
mod erased;
mod escape;
mod gauge;
mod histogram;
mod labels;
mod macros;
mod registry;
mod render;
mod series;
mod value;
mod vec;

pub use config::{LABEL_VALUE_LEN, MAX_GROUPS, MAX_HISTOGRAM_BUCKETS, MAX_LINE};
pub use counter::Counter;
#[doc(hidden)]
pub use erased::{
    ErasedCounterVec, ErasedGaugeVec, ErasedHistogram, ErasedHistogramVec, MetricDesc, MetricGroup,
    MetricRef,
};
#[cfg(feature = "consistent-histograms")]
pub use erased::{HistogramSnapshot, HistogramSnapshotError};
pub use escape::{valid_label_name, valid_metric_name};
pub use gauge::Gauge;
pub use histogram::IntHistogram;
pub use registry::{GroupSnapshot, OnceRegister, Registry, RegistryFull, register, snapshot};
pub use render::{CONTENT_TYPE, RenderError, Renderer, write_all};
pub use series::IntHistSeries;
pub use value::Value;
pub use vec::{CounterSeries, CounterVec, GaugeSeries, GaugeVec, IntHistogramVec};

#[cfg(feature = "float")]
pub use gauge::GaugeF64;
#[cfg(feature = "float")]
pub use histogram::Histogram;
#[cfg(feature = "float")]
pub use series::HistSeries;
#[cfg(feature = "float")]
pub use vec::{GaugeF64Series, GaugeF64Vec, HistogramVec};