1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
//! 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(®ISTRY);
//! 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(®istry);
//! 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.
pub use ;
pub use Counter;
pub use ;
pub use ;
pub use ;
pub use Gauge;
pub use IntHistogram;
pub use ;
pub use ;
pub use IntHistSeries;
pub use Value;
pub use ;
pub use GaugeF64;
pub use Histogram;
pub use HistSeries;
pub use ;