metrics_collector_prometheus/lib.rs
1//! Collects Prometheus-compatible metrics and returns them as structured Rust values.
2//!
3//! `metrics-collector-prometheus` implements [`metrics::Recorder`], aggregating counters,
4//! gauges, summaries, classic histograms, and Prometheus native histograms as an application
5//! records them through the [`metrics`][metrics] facade. Calling [`collect`](CollectorHandle::collect)
6//! hands back an owned, deterministically ordered
7//! [`MetricSnapshot`](snapshot::MetricSnapshot).
8//!
9//! ## What this crate is not
10//!
11//! - **Not an exporter.** It renders no bytes: no Prometheus text exposition format, no
12//! protobuf encoding. `MetricSnapshot` is the product; encoding it onto a wire is left to
13//! the caller.
14//! - **Not a transport.** There is no HTTP listener and no push gateway.
15//! - **Not a runtime.** [`build`](PrometheusCollectorBuilder::build) and
16//! [`install`](PrometheusCollectorBuilder::install) return synchronously and spawn nothing.
17//! The one place a background thread exists at all is opt-in and explicit -- see "Upkeep"
18//! below.
19//!
20//! This is a fork of [`metrics-exporter-prometheus`], which does all three. See the
21//! [README] for why this fork exists and for the full list of behavioral divergences from it.
22//!
23//! [`metrics-exporter-prometheus`]: https://docs.rs/metrics-exporter-prometheus
24//! [README]: https://github.com/demosdemon/metrics-collector-prometheus#readme
25//!
26//! ## Usage
27//!
28//! ```
29//! use metrics_collector_prometheus::PrometheusCollectorBuilder;
30//!
31//! // Install sets the process-global `metrics::Recorder`; call it once, near your
32//! // program's entry point. `handle` is how you read data back out later.
33//! let handle = PrometheusCollectorBuilder::new().install().expect("failed to install collector");
34//!
35//! metrics::counter!("requests").increment(1);
36//!
37//! let snapshot = handle.collect();
38//! let family = &snapshot.families[0];
39//! assert_eq!(family.name, "requests"); // raw -- see "Names and labels are raw" below
40//! ```
41//!
42//! Prefer not to touch the global recorder? Build one directly and pass it to
43//! [`metrics::with_local_recorder`], or combine it with other recorders yourself:
44//!
45//! ```
46//! use metrics_collector_prometheus::PrometheusCollectorBuilder;
47//!
48//! let recorder = PrometheusCollectorBuilder::new().build();
49//! let handle = recorder.handle();
50//! metrics::with_local_recorder(&recorder, || {
51//! metrics::gauge!("in_flight_requests").set(3.0);
52//! });
53//! assert_eq!(handle.collect().families.len(), 1);
54//! ```
55//!
56//! ## Names and labels are raw
57//!
58//! [`MetricFamily::name`](snapshot::MetricFamily::name) and
59//! [`LabelPair`](snapshot::LabelPair)'s fields hold exactly what was registered: sanitized to
60//! be *valid* Prometheus identifiers, but not decorated. Nothing here appends `_total`, inserts
61//! a unit, or escapes a label value. That is [`naming::exposition_name`]'s job for names, and
62//! [`LabelPair::exposition_label`](snapshot::LabelPair::exposition_label) /
63//! [`exposition_value`](snapshot::LabelPair::exposition_value)'s job for labels -- applied on
64//! demand by whichever consumer needs Prometheus's rules. A consumer targeting a different wire
65//! format is never forced to undo them.
66//!
67//! ## Upkeep
68//!
69//! Nothing here spawns a background task on its own. Histogram samples accumulate in a bounded
70//! queue and are aggregated into a snapshot-ready form only when drained, which
71//! [`collect`](CollectorHandle::collect) does as a side effect. A process that collects
72//! regularly needs nothing else. A process that collects rarely, or not at all, should call
73//! [`CollectorHandle::run_upkeep`] on its own schedule, or use
74//! [`CollectorHandle::spawn_upkeep`] to run it on a dedicated thread -- see that method and
75//! [`UpkeepGuard`] for what dropping the returned guard costs.
76//!
77//! ## The `serde` feature
78//!
79//! With `serde` enabled, every type in [`snapshot`] implements `Serialize` and `Deserialize`,
80//! under a compatibility contract meant to outlive any one version of this crate:
81//!
82//! - Adding a **field** to an existing struct is not a breaking change in either direction. New
83//! fields are `#[serde(default)]`; an older reader skips fields it does not know.
84//! - Adding a **variant** to [`MetricValue`](snapshot::MetricValue) or
85//! [`MetricKind`](snapshot::MetricKind) is not a breaking change to compile against, but an
86//! *older* reader's deserializer fails with a hard `unknown variant` error on a payload
87//! containing the new variant, rather than silently discarding the sample. See
88//! `MetricValue`'s own documentation for why a fallback variant was rejected.
89//! - An unrecognized [`metrics::Unit`] string on [`MetricFamily::unit`](snapshot::MetricFamily::unit)
90//! is also a hard error, and it fails the *entire* snapshot's deserialization, not just the one
91//! family carrying it -- `Unit` has no fallback variant to fall back to.
92//!
93//! In short: a snapshot stored today always parses with a newer version of this crate; a
94//! *newer* snapshot parses with an older version only if it used no variant, and no unit, the
95//! older version lacks.
96//!
97//! **This contract holds only for self-describing formats** -- JSON, YAML, CBOR, and similar,
98//! where the wire format itself encodes each value's type. [`MetricValue::Gauge`](snapshot::MetricValue::Gauge)
99//! and every other non-finite-capable `f64` field ([`Bucket::upper_bound`](snapshot::Bucket::upper_bound),
100//! summary/histogram sums, and native-histogram thresholds) round-trip through a
101//! `#[serde(untagged)]` bridge that encodes a non-finite value as a string (`"NaN"`,
102//! `"Infinity"`, `"-Infinity"`) instead of a number, so the deserializer can accept either shape.
103//! `#[serde(untagged)]` requires `Deserializer::deserialize_any`, which non-self-describing
104//! binary formats -- `bincode`, `postcard`, `MessagePack` in its compact/non-human-readable
105//! mode -- do not implement. Against one of those, deserializing a `MetricSnapshot` **fails
106//! outright**, and, worse, *serializing* one **silently succeeds** while producing a byte
107//! stream whose per-value shape (number vs. string) depends on whether that particular value
108//! happened to be finite -- not a stable schema. Stick to a self-describing format for anything
109//! serialized with this crate's `serde` support.
110//!
111//! [metrics]: https://docs.rs/metrics/latest/metrics/
112#![deny(clippy::all)]
113#![deny(clippy::pedantic)]
114#![allow(clippy::must_use_candidate)]
115#![allow(clippy::module_name_repetitions)]
116#![deny(missing_docs)]
117#![cfg_attr(docsrs, feature(doc_cfg), deny(rustdoc::broken_intra_doc_links))]
118mod builder;
119mod collector;
120mod distribution;
121mod error;
122mod matcher;
123pub mod naming;
124mod native_histogram;
125mod registry;
126pub mod snapshot;
127mod upkeep;
128
129pub use self::builder::PrometheusCollectorBuilder;
130pub use self::collector::{CollectorHandle, PrometheusCollector};
131pub use self::error::BuildError;
132pub use self::matcher::Matcher;
133pub use self::native_histogram::NativeHistogramConfig;
134pub use self::upkeep::UpkeepGuard;