Skip to main content

prometheus_client/encoding/
prometheus_text.rs

1//! Prometheus text format (version 0.0.4) implementation.
2//!
3//! ```
4//! # use prometheus_client::encoding::prometheus_text::encode;
5//! # use prometheus_client::metrics::counter::Counter;
6//! # use prometheus_client::registry::Registry;
7//! #
8//! # let mut registry = Registry::default();
9//! # let counter: Counter = Counter::default();
10//! # registry.register(
11//! #   "my_counter",
12//! #   "This is my counter",
13//! #   counter.clone(),
14//! # );
15//! # counter.inc();
16//! let mut buffer = String::new();
17//! encode(&mut buffer, &registry).unwrap();
18//!
19//! let expected = "# HELP my_counter_total This is my counter.\n".to_owned() +
20//!                "# TYPE my_counter_total counter\n" +
21//!                "my_counter_total 1\n";
22//! assert_eq!(expected, buffer);
23//! ```
24
25use crate::encoding::text::{LabelList, TextBuf};
26use crate::encoding::{
27    EncodeExemplarValue, EncodeLabelSet, EncodeLabelValue, LabelValueEncoder, NativeHistogram,
28    NoLabelSet,
29};
30use crate::metrics::exemplar::Exemplar;
31use crate::metrics::MetricType;
32use crate::registry::{Prefix, Registry, Unit};
33
34use std::borrow::Cow;
35use std::collections::HashMap;
36use std::fmt::Write;
37
38/// The `Content-Type` of the Prometheus text format (version 0.0.4).
39///
40/// Equivalent to `expfmt.FmtText` in Go's
41/// [`prometheus/common`](https://github.com/prometheus/common/blob/main/expfmt/expfmt.go).
42pub const CONTENT_TYPE: &str = "text/plain; version=0.0.4; charset=utf-8";
43
44/// Encode the metrics registered with the provided [`Registry`] into the
45/// provided [`Write`]r using the Prometheus text format (version 0.0.4).
46///
47/// # Examples
48///
49/// ```no_run
50/// # use prometheus_client::encoding::prometheus_text::encode;
51/// # use prometheus_client::metrics::counter::Counter;
52/// # use prometheus_client::registry::Registry;
53/// #
54/// let mut registry = Registry::default();
55/// let counter: Counter = Counter::default();
56/// registry.register("my_counter", "This is my counter", counter.clone());
57///
58/// let mut buffer = String::new();
59/// encode(&mut buffer, &registry)?;
60/// # Ok::<(), std::fmt::Error>(())
61/// ```
62pub fn encode<W>(writer: &mut W, registry: &Registry) -> Result<(), std::fmt::Error>
63where
64    W: Write,
65{
66    let mut buffer = TextBuf::new_buffer();
67    registry.encode(&mut DescriptorEncoder::new(TextBuf::new(&mut buffer, writer)).into())?;
68    writer.write_str(&buffer)
69}
70
71pub(crate) struct DescriptorEncoder<'a> {
72    writer: TextBuf<'a>,
73    prefix: Option<&'a Prefix>,
74    labels: &'a [(Cow<'static, str>, Cow<'static, str>)],
75}
76
77impl std::fmt::Debug for DescriptorEncoder<'_> {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        f.debug_struct("DescriptorEncoder").finish()
80    }
81}
82
83impl<'a> DescriptorEncoder<'a> {
84    pub(crate) fn new(writer: TextBuf<'a>) -> DescriptorEncoder<'a> {
85        DescriptorEncoder {
86            writer,
87            prefix: Default::default(),
88            labels: Default::default(),
89        }
90    }
91
92    pub(crate) fn with_prefix_and_labels<'s>(
93        &'s mut self,
94        prefix: Option<&'s Prefix>,
95        labels: &'s [(Cow<'static, str>, Cow<'static, str>)],
96    ) -> DescriptorEncoder<'s> {
97        DescriptorEncoder {
98            prefix,
99            labels,
100            writer: self.writer.reborrow(),
101        }
102    }
103
104    pub fn encode_descriptor<'s>(
105        &'s mut self,
106        name: &'s str,
107        help: &str,
108        unit: Option<&'s Unit>,
109        metric_type: MetricType,
110    ) -> Result<MetricEncoder<'s>, std::fmt::Error> {
111        self.writer.write_str("# HELP ")?;
112        self.metric_encoder(name, unit, metric_type)
113            .write_name("")?;
114        self.writer.write_str(" ")?;
115        let needs_escaping = help
116            .bytes()
117            .fold(false, |found, byte| found | matches!(byte, b'\\' | b'\n'));
118        if needs_escaping {
119            self.write_escaped(help)?;
120        } else {
121            self.writer.write_str(help)?;
122        }
123        self.writer.write_str("\n")?;
124
125        let mut encoder = self.metric_encoder(name, unit, metric_type);
126        encoder.writer.write_str("# TYPE ")?;
127        encoder.write_name("")?;
128        encoder.writer.write_str(match metric_type {
129            MetricType::Counter => " counter\n",
130            MetricType::Gauge | MetricType::Info => " gauge\n",
131            MetricType::Histogram => " histogram\n",
132            MetricType::Unknown => " untyped\n",
133        })?;
134
135        Ok(encoder)
136    }
137
138    fn metric_encoder<'s>(
139        &'s mut self,
140        name: &'s str,
141        unit: Option<&'s Unit>,
142        metric_type: MetricType,
143    ) -> MetricEncoder<'s> {
144        MetricEncoder {
145            writer: self.writer.reborrow(),
146            prefix: self.prefix,
147            name,
148            unit,
149            metric_type,
150            const_labels: self.labels,
151            family_labels: None,
152        }
153    }
154
155    #[cold]
156    fn write_escaped(&mut self, help: &str) -> Result<(), std::fmt::Error> {
157        let mut last = 0;
158        for (index, byte) in help.bytes().enumerate() {
159            let escaped = match byte {
160                b'\\' => "\\\\",
161                b'\n' => "\\n",
162                _ => continue,
163            };
164            self.writer.write_str(&help[last..index])?;
165            self.writer.write_str(escaped)?;
166            last = index + 1;
167        }
168        self.writer.write_str(&help[last..])
169    }
170}
171
172pub(crate) struct MetricEncoder<'a> {
173    writer: TextBuf<'a>,
174    prefix: Option<&'a Prefix>,
175    name: &'a str,
176    unit: Option<&'a Unit>,
177    metric_type: MetricType,
178    const_labels: &'a [(Cow<'static, str>, Cow<'static, str>)],
179    family_labels: Option<&'a dyn EncodeLabelSet>,
180}
181
182impl std::fmt::Debug for MetricEncoder<'_> {
183    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
184        let labels = TextBuf::encode_to_string(|buf| match self.family_labels {
185            Some(l) => LabelList::new("").encode(buf, l),
186            None => Ok(()),
187        })?;
188
189        f.debug_struct("Encoder")
190            .field("name", &self.name)
191            .field("prefix", &self.prefix)
192            .field("unit", &self.unit)
193            .field("metric_type", &self.metric_type.as_str())
194            .field("const_labels", &self.const_labels)
195            .field("labels", &labels.as_str())
196            .finish()
197    }
198}
199
200impl MetricEncoder<'_> {
201    pub fn encode_counter<
202        S: EncodeLabelSet,
203        CounterValue: super::EncodeCounterValue,
204        ExemplarValue: EncodeExemplarValue,
205    >(
206        &mut self,
207        v: &CounterValue,
208        _exemplar: Option<&Exemplar<S, ExemplarValue>>,
209    ) -> Result<(), std::fmt::Error> {
210        self.write_name("")?;
211        self.write_labels::<NoLabelSet>(None)?;
212        v.encode(
213            &mut CounterValueEncoder {
214                writer: self.writer.reborrow(),
215            }
216            .into(),
217        )?;
218        self.writer.write_str("\n")
219    }
220
221    pub fn encode_gauge<GaugeValue: super::EncodeGaugeValue>(
222        &mut self,
223        v: &GaugeValue,
224    ) -> Result<(), std::fmt::Error> {
225        self.write_name("")?;
226        self.write_labels::<NoLabelSet>(None)?;
227        v.encode(
228            &mut GaugeValueEncoder {
229                writer: self.writer.reborrow(),
230            }
231            .into(),
232        )?;
233        self.writer.write_str("\n")
234    }
235
236    pub fn encode_info<S: EncodeLabelSet>(&mut self, label_set: &S) -> Result<(), std::fmt::Error> {
237        self.write_name("")?;
238        self.write_labels(Some(label_set))?;
239        self.writer.write_str(" 1\n")
240    }
241
242    pub fn encode_family<'s, S: EncodeLabelSet>(
243        &'s mut self,
244        label_set: &'s S,
245    ) -> Result<MetricEncoder<'s>, std::fmt::Error> {
246        debug_assert!(self.family_labels.is_none());
247
248        Ok(MetricEncoder {
249            writer: self.writer.reborrow(),
250            prefix: self.prefix,
251            name: self.name,
252            unit: self.unit,
253            metric_type: self.metric_type,
254            const_labels: self.const_labels,
255            family_labels: Some(label_set),
256        })
257    }
258
259    pub fn encode_histogram<S: EncodeLabelSet>(
260        &mut self,
261        sum: f64,
262        count: u64,
263        buckets: &[(f64, u64)],
264        _exemplars: Option<&HashMap<usize, Exemplar<S, f64>>>,
265    ) -> Result<(), std::fmt::Error> {
266        let mut cumulative = 0;
267        let mut inf_seen = false;
268        for (upper_bound, count) in buckets {
269            cumulative += count;
270            self.write_name("_bucket")?;
271            inf_seen |= *upper_bound == f64::INFINITY;
272            self.write_labels(Some(&[("le", GoFloat(*upper_bound))]))?;
273            self.write_u64(cumulative)?;
274        }
275
276        if !inf_seen {
277            self.write_name("_bucket")?;
278            self.write_labels(Some(&[("le", "+Inf")]))?;
279            self.write_u64(count)?;
280        }
281
282        self.write_name("_sum")?;
283        self.write_labels::<NoLabelSet>(None)?;
284        self.writer.write_str(" ")?;
285        self.writer
286            .write_str(format_float(&mut dtoa::Buffer::new(), sum))?;
287        self.writer.write_str("\n")?;
288
289        self.write_name("_count")?;
290        self.write_labels::<NoLabelSet>(None)?;
291        self.write_u64(count)
292    }
293
294    pub fn encode_histogram_with_native<S: EncodeLabelSet>(
295        &mut self,
296        sum: f64,
297        count: u64,
298        buckets: &[(f64, u64)],
299        exemplars: Option<&HashMap<usize, Exemplar<S, f64>>>,
300        _native: NativeHistogram<'_>,
301    ) -> Result<(), std::fmt::Error> {
302        self.encode_histogram(sum, count, buckets, exemplars)
303    }
304
305    fn write_name(&mut self, suffix: &str) -> Result<(), std::fmt::Error> {
306        if let Some(prefix) = self.prefix {
307            self.writer.write_str(prefix.as_str())?;
308            self.writer.write_str("_")?;
309        }
310        self.writer.write_str(self.name)?;
311        if let Some(unit) = self.unit {
312            self.writer.write_str("_")?;
313            self.writer.write_str(unit.as_str())?;
314        }
315        match self.metric_type {
316            MetricType::Counter => self.writer.write_str("_total")?,
317            MetricType::Info => self.writer.write_str("_info")?,
318            MetricType::Gauge | MetricType::Histogram | MetricType::Unknown => {}
319        }
320        self.writer.write_str(suffix)
321    }
322
323    fn write_labels<S: EncodeLabelSet>(
324        &mut self,
325        additional_labels: Option<&S>,
326    ) -> Result<(), std::fmt::Error> {
327        let mut list = LabelList::new("{");
328        list.encode(self.writer.reborrow(), &self.const_labels)?;
329        if let Some(labels) = self.family_labels {
330            list.encode(self.writer.reborrow(), labels)?;
331        }
332        if let Some(labels) = additional_labels {
333            list.encode(self.writer.reborrow(), labels)?;
334        }
335        list.finish(self.writer.reborrow(), "}")
336    }
337
338    fn write_u64(&mut self, v: u64) -> Result<(), std::fmt::Error> {
339        self.writer.write_str(" ")?;
340        self.writer.write_str(itoa::Buffer::new().format(v))?;
341        self.writer.write_str("\n")
342    }
343}
344
345pub(crate) struct CounterValueEncoder<'a> {
346    writer: TextBuf<'a>,
347}
348
349impl std::fmt::Debug for CounterValueEncoder<'_> {
350    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
351        f.debug_struct("CounterValueEncoder").finish()
352    }
353}
354
355impl CounterValueEncoder<'_> {
356    pub fn encode_f64(&mut self, v: f64) -> Result<(), std::fmt::Error> {
357        self.writer.write_str(" ")?;
358        self.writer
359            .write_str(format_float(&mut dtoa::Buffer::new(), v))
360    }
361
362    pub fn encode_u64(&mut self, v: u64) -> Result<(), std::fmt::Error> {
363        self.writer.write_str(" ")?;
364        self.writer.write_str(itoa::Buffer::new().format(v))
365    }
366}
367
368pub(crate) struct GaugeValueEncoder<'a> {
369    writer: TextBuf<'a>,
370}
371
372impl std::fmt::Debug for GaugeValueEncoder<'_> {
373    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
374        f.debug_struct("GaugeValueEncoder").finish()
375    }
376}
377
378impl GaugeValueEncoder<'_> {
379    pub fn encode_u32(&mut self, v: u32) -> Result<(), std::fmt::Error> {
380        self.writer.write_str(" ")?;
381        self.writer.write_str(itoa::Buffer::new().format(v))
382    }
383
384    pub fn encode_u64(&mut self, v: u64) -> Result<(), std::fmt::Error> {
385        self.writer.write_str(" ")?;
386        self.writer.write_str(itoa::Buffer::new().format(v))
387    }
388
389    pub fn encode_i64(&mut self, v: i64) -> Result<(), std::fmt::Error> {
390        self.writer.write_str(" ")?;
391        self.writer.write_str(itoa::Buffer::new().format(v))
392    }
393
394    pub fn encode_f64(&mut self, v: f64) -> Result<(), std::fmt::Error> {
395        self.writer.write_str(" ")?;
396        self.writer
397            .write_str(format_float(&mut dtoa::Buffer::new(), v))
398    }
399}
400
401fn format_float(buf: &mut dtoa::Buffer, value: f64) -> &str {
402    if value.is_finite() {
403        buf.format_finite(value)
404    } else {
405        format_nonfinite(value)
406    }
407}
408
409/// Formats an `f64` the way client_golang's `expfmt` writes histogram `le`
410/// labels, i.e. Go's `strconv.FormatFloat(v, 'g', -1, 64)` with `0`, `+Inf`,
411/// `-Inf` and `NaN` special cased. This keeps series identical to those
412/// exposed by Go clients.
413///
414/// Note: Rust and Go break ties between equally short digit strings
415/// differently, so in rare cases the last digit can differ from Go
416/// (e.g. `562949953421312.25`). Typical bucket bounds are unaffected.
417///
418/// Formatting happens entirely on the stack.
419#[repr(transparent)]
420struct GoFloat(f64);
421
422impl std::fmt::Display for GoFloat {
423    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
424        let v = self.0;
425        // Fast path: Go prints whole numbers below 1e6 as plain integers.
426        if v.fract() == 0.0 && v.abs() < 1e6 {
427            return f.write_str(itoa::Buffer::new().format(v as i64));
428        }
429        // Go's shortest `%g` uses exponent notation iff the decimal exponent is
430        // `< -4` or `>= 6`, i.e. iff `|v|` is outside `[1e-4, 1e6)`. Inside that
431        // range Rust's `Display` prints the same digits. Outside of it, Rust's
432        // `{:e}` only differs in the exponent (`1e6` vs. `1e+06`).
433        if (1e-4..1e6).contains(&v.abs()) {
434            return write!(f, "{v}");
435        }
436        if !v.is_finite() {
437            return f.write_str(format_nonfinite(v));
438        }
439
440        let mut sci = SciBuffer::default();
441        write!(sci, "{v:e}")?;
442        let s = sci.as_str()?;
443        let e = s.find('e').ok_or(std::fmt::Error)?;
444        let (mantissa_e, exponent) = s.split_at(e + 1);
445        let exponent: i32 = exponent.parse().map_err(|_| std::fmt::Error)?;
446        f.write_str(mantissa_e)?;
447        write!(f, "{exponent:+03}")
448    }
449}
450
451impl EncodeLabelValue for GoFloat {
452    fn encode(&self, encoder: &mut LabelValueEncoder) -> Result<(), std::fmt::Error> {
453        write!(encoder, "{self}")
454    }
455}
456
457/// Fixed capacity stack buffer for the `{:e}` representation of an `f64`.
458#[derive(Default)]
459struct SciBuffer {
460    bytes: [u8; 32],
461    len: usize,
462}
463
464impl SciBuffer {
465    fn as_str(&self) -> Result<&str, std::fmt::Error> {
466        std::str::from_utf8(&self.bytes[..self.len]).map_err(|_| std::fmt::Error)
467    }
468}
469
470impl Write for SciBuffer {
471    fn write_str(&mut self, s: &str) -> std::fmt::Result {
472        let dst = self
473            .bytes
474            .get_mut(self.len..self.len + s.len())
475            .ok_or(std::fmt::Error)?;
476        dst.copy_from_slice(s.as_bytes());
477        self.len += s.len();
478        Ok(())
479    }
480}
481
482#[cold]
483fn format_nonfinite(value: f64) -> &'static str {
484    if value.is_nan() {
485        "NaN"
486    } else if value.is_sign_positive() {
487        "+Inf"
488    } else {
489        "-Inf"
490    }
491}
492
493#[cfg(test)]
494mod tests {
495    use super::*;
496    use crate::collector::Collector;
497    use crate::encoding::text::FLUSH_THRESHOLD;
498    use crate::encoding::{DescriptorEncoder as GenericDescriptorEncoder, EncodeMetric};
499    use crate::metrics::counter::{ConstCounter, Counter};
500    use crate::metrics::exemplar::{CounterWithExemplar, HistogramWithExemplars};
501    use crate::metrics::family::Family;
502    use crate::metrics::gauge::Gauge;
503    use crate::metrics::histogram::{Histogram, NativeHistogramConfig};
504    use crate::metrics::info::Info;
505    use pyo3::{prelude::*, types::PyModule};
506    use std::sync::atomic::{AtomicI64, AtomicU32, AtomicU64};
507
508    fn encode_to_string(registry: &Registry) -> String {
509        let mut encoded = String::new();
510        encode(&mut encoded, registry).unwrap();
511        encoded
512    }
513
514    #[test]
515    fn encode_counter() {
516        let mut registry = Registry::default();
517        let counter: Counter = Counter::default();
518        registry.register("my_counter", "My counter", counter.clone());
519        counter.inc_by(1_000_000);
520
521        let float_counter: Counter<f64> = Counter::default();
522        registry.register(
523            "my_float_counter",
524            "My float counter",
525            float_counter.clone(),
526        );
527        float_counter.inc_by(1.5);
528
529        let expected = "# HELP my_counter_total My counter.\n".to_owned()
530            + "# TYPE my_counter_total counter\n"
531            + "my_counter_total 1000000\n"
532            + "# HELP my_float_counter_total My float counter.\n"
533            + "# TYPE my_float_counter_total counter\n"
534            + "my_float_counter_total 1.5\n";
535        let encoded = encode_to_string(&registry);
536        assert_eq!(expected, encoded);
537        parse_with_python_client(encoded);
538    }
539
540    #[test]
541    fn encode_counter_with_unit_and_exemplar() {
542        let mut registry = Registry::default();
543        let counter: CounterWithExemplar<Vec<(String, u64)>> = CounterWithExemplar::default();
544        registry.register_with_unit(
545            "my_counter",
546            "My counter",
547            crate::registry::Unit::Seconds,
548            counter.clone(),
549        );
550        counter.inc_by(1, Some(vec![("user_id".to_string(), 42)]), None);
551
552        let expected = "# HELP my_counter_seconds_total My counter.\n".to_owned()
553            + "# TYPE my_counter_seconds_total counter\n"
554            + "my_counter_seconds_total 1\n";
555        let encoded = encode_to_string(&registry);
556        assert_eq!(expected, encoded);
557        parse_with_python_client(encoded);
558    }
559
560    #[test]
561    fn encode_gauges() {
562        let mut registry = Registry::default();
563        let gauge: Gauge = Gauge::default();
564        registry.register("my_gauge", "My gauge", gauge.clone());
565        gauge.set(-3);
566
567        let float_gauge = Gauge::<f64, std::sync::atomic::AtomicU64>::default();
568        registry.register("my_float_gauge", "My float gauge", float_gauge.clone());
569        float_gauge.set(0.25);
570
571        let u32_gauge = Gauge::<u32, AtomicU32>::default();
572        registry.register("my_u32_gauge", "My u32 gauge", u32_gauge.clone());
573        u32_gauge.set(7);
574
575        let u64_gauge = Gauge::<u64, AtomicU64>::default();
576        registry.register("my_u64_gauge", "My u64 gauge", u64_gauge.clone());
577        u64_gauge.set(0);
578
579        let i64_gauge = Gauge::<i64, AtomicI64>::default();
580        registry.register("my_i64_gauge", "My i64 gauge", i64_gauge.clone());
581        i64_gauge.set(-1);
582
583        let expected = "# HELP my_gauge My gauge.\n".to_owned()
584            + "# TYPE my_gauge gauge\n"
585            + "my_gauge -3\n"
586            + "# HELP my_float_gauge My float gauge.\n"
587            + "# TYPE my_float_gauge gauge\n"
588            + "my_float_gauge 0.25\n"
589            + "# HELP my_u32_gauge My u32 gauge.\n"
590            + "# TYPE my_u32_gauge gauge\n"
591            + "my_u32_gauge 7\n"
592            + "# HELP my_u64_gauge My u64 gauge.\n"
593            + "# TYPE my_u64_gauge gauge\n"
594            + "my_u64_gauge 0\n"
595            + "# HELP my_i64_gauge My i64 gauge.\n"
596            + "# TYPE my_i64_gauge gauge\n"
597            + "my_i64_gauge -1\n";
598        let encoded = encode_to_string(&registry);
599        assert_eq!(expected, encoded);
600        parse_with_python_client(encoded);
601    }
602
603    #[test]
604    fn encode_info() {
605        let mut registry =
606            Registry::with_labels(vec![(Cow::Borrowed("env"), Cow::Borrowed("prod"))].into_iter());
607        let info = Info::new(vec![("os".to_string(), "GNU/linux".to_string())]);
608        registry.register("my_info_metric", "My info metric", info);
609
610        let expected = "# HELP my_info_metric_info My info metric.\n".to_owned()
611            + "# TYPE my_info_metric_info gauge\n"
612            + "my_info_metric_info{env=\"prod\",os=\"GNU/linux\"} 1\n";
613        let encoded = encode_to_string(&registry);
614        assert_eq!(expected, encoded);
615        parse_with_python_client(encoded);
616    }
617
618    #[test]
619    fn encode_info_with_const_labels_and_empty_label_set() {
620        let mut registry =
621            Registry::with_labels(vec![(Cow::Borrowed("env"), Cow::Borrowed("prod"))].into_iter());
622        let info = Info::new(Vec::<(String, String)>::new());
623        registry.register("my_info_metric", "My info metric", info);
624
625        let expected = "# HELP my_info_metric_info My info metric.\n".to_owned()
626            + "# TYPE my_info_metric_info gauge\n"
627            + "my_info_metric_info{env=\"prod\"} 1\n";
628        let encoded = encode_to_string(&registry);
629        assert_eq!(expected, encoded);
630        parse_with_python_client(encoded);
631    }
632
633    #[test]
634    fn encode_unknown_collector() {
635        #[derive(Debug)]
636        struct MyCollector;
637
638        impl Collector for MyCollector {
639            fn encode(&self, mut encoder: GenericDescriptorEncoder) -> Result<(), std::fmt::Error> {
640                let counter = ConstCounter::new(42u64);
641                let metric_encoder = encoder.encode_descriptor(
642                    "my_const_counter",
643                    "some help",
644                    None,
645                    counter.metric_type(),
646                )?;
647                counter.encode(metric_encoder)?;
648
649                let metric_encoder = encoder.encode_descriptor(
650                    "my_untyped",
651                    "untyped help",
652                    None,
653                    MetricType::Unknown,
654                )?;
655                ConstCounter::new(3u64).encode(metric_encoder)?;
656                Ok(())
657            }
658        }
659
660        let mut registry = Registry::default();
661        registry.register_collector(Box::new(MyCollector));
662
663        let expected = "# HELP my_const_counter_total some help\n".to_owned()
664            + "# TYPE my_const_counter_total counter\n"
665            + "my_const_counter_total 42\n"
666            + "# HELP my_untyped untyped help\n"
667            + "# TYPE my_untyped untyped\n"
668            + "my_untyped 3\n";
669        let encoded = encode_to_string(&registry);
670        assert_eq!(expected, encoded);
671        parse_with_python_client(encoded);
672    }
673
674    #[test]
675    fn encode_special_values() {
676        let mut registry = Registry::default();
677        let pos_inf = Gauge::<f64, AtomicU64>::default();
678        registry.register("pos_inf", "Pos inf", pos_inf.clone());
679        pos_inf.set(f64::INFINITY);
680
681        let neg_inf = Gauge::<f64, AtomicU64>::default();
682        registry.register("neg_inf", "Neg inf", neg_inf.clone());
683        neg_inf.set(f64::NEG_INFINITY);
684
685        let nan = Gauge::<f64, AtomicU64>::default();
686        registry.register("nan", "NaN", nan.clone());
687        nan.set(f64::NAN);
688
689        let float_counter: Counter<f64> = Counter::default();
690        registry.register("inf_counter", "Inf counter", float_counter.clone());
691        float_counter.inc_by(f64::INFINITY);
692
693        let big: Counter = Counter::default();
694        registry.register("big", "Big", big.clone());
695        big.inc_by(9007199254740993);
696
697        let expected = "# HELP pos_inf Pos inf.\n".to_owned()
698            + "# TYPE pos_inf gauge\n"
699            + "pos_inf +Inf\n"
700            + "# HELP neg_inf Neg inf.\n"
701            + "# TYPE neg_inf gauge\n"
702            + "neg_inf -Inf\n"
703            + "# HELP nan NaN.\n"
704            + "# TYPE nan gauge\n"
705            + "nan NaN\n"
706            + "# HELP inf_counter_total Inf counter.\n"
707            + "# TYPE inf_counter_total counter\n"
708            + "inf_counter_total +Inf\n"
709            + "# HELP big_total Big.\n"
710            + "# TYPE big_total counter\n"
711            + "big_total 9007199254740993\n";
712        let encoded = encode_to_string(&registry);
713        assert_eq!(expected, encoded);
714        parse_with_python_client(encoded);
715    }
716
717    #[test]
718    fn encode_histogram() {
719        let mut registry = Registry::default();
720        let histogram = Histogram::new([1.0, 2.5, 1e6]);
721        registry.register("my_histogram", "My histogram", histogram.clone());
722        histogram.observe(1.0);
723        histogram.observe(2_000_000.0);
724
725        let expected = "# HELP my_histogram My histogram.\n".to_owned()
726            + "# TYPE my_histogram histogram\n"
727            + "my_histogram_bucket{le=\"1\"} 1\n"
728            + "my_histogram_bucket{le=\"2.5\"} 1\n"
729            + "my_histogram_bucket{le=\"1e+06\"} 1\n"
730            + "my_histogram_bucket{le=\"+Inf\"} 2\n"
731            + "my_histogram_sum 2000001.0\n"
732            + "my_histogram_count 2\n";
733        let encoded = encode_to_string(&registry);
734        assert_eq!(expected, encoded);
735        parse_with_python_client(encoded);
736    }
737
738    type HistogramFamily =
739        Family<Vec<(String, String)>, HistogramWithExemplars<Vec<(String, u64)>>>;
740
741    fn register_histogram_family(registry: &mut Registry) -> HistogramFamily {
742        let family = HistogramFamily::new_with_constructor(|| {
743            HistogramWithExemplars::new([0.5].into_iter())
744        });
745        registry.register("my_histogram_family", "My histogram family", family.clone());
746        family
747    }
748
749    fn get_label_set() -> Vec<(String, String)> {
750        vec![("method".to_string(), "GET".to_string())]
751    }
752
753    fn post_500_label_set() -> Vec<(String, String)> {
754        vec![
755            ("method".to_string(), "POST".to_string()),
756            ("status".to_string(), "500".to_string()),
757        ]
758    }
759
760    /// Asserts `encoded == prefix + <blocks in some order>`. Needed because
761    /// `Family` iterates a `HashMap`, so the order of label sets is unspecified.
762    fn assert_encoded_with_blocks_in_any_order(encoded: &str, prefix: &str, blocks: &[&str]) {
763        let mut rest = encoded
764            .strip_prefix(prefix)
765            .unwrap_or_else(|| panic!("expected prefix:\n{prefix}\ngot:\n{encoded}"))
766            .to_owned();
767        for block in blocks {
768            assert!(
769                rest.contains(block),
770                "missing block:\n{block}\nin:\n{encoded}"
771            );
772            rest = rest.replacen(block, "", 1);
773        }
774        assert!(rest.is_empty(), "unexpected trailing output:\n{rest}");
775    }
776
777    #[test]
778    fn encode_histogram_without_observations() {
779        let mut registry = Registry::default();
780        let histogram = HistogramWithExemplars::<Vec<(String, u64)>>::new([0.5].into_iter());
781        registry.register("my_histogram", "My histogram", histogram.clone());
782
783        let family = register_histogram_family(&mut registry);
784        drop(family.get_or_create(&get_label_set()));
785        drop(family.get_or_create(&post_500_label_set()));
786
787        let prefix = "# HELP my_histogram My histogram.\n".to_owned()
788            + "# TYPE my_histogram histogram\n"
789            + "my_histogram_bucket{le=\"0.5\"} 0\n"
790            + "my_histogram_bucket{le=\"+Inf\"} 0\n"
791            + "my_histogram_sum 0.0\n"
792            + "my_histogram_count 0\n"
793            + "# HELP my_histogram_family My histogram family.\n"
794            + "# TYPE my_histogram_family histogram\n";
795        let get_block = "my_histogram_family_bucket{method=\"GET\",le=\"0.5\"} 0\n".to_owned()
796            + "my_histogram_family_bucket{method=\"GET\",le=\"+Inf\"} 0\n"
797            + "my_histogram_family_sum{method=\"GET\"} 0.0\n"
798            + "my_histogram_family_count{method=\"GET\"} 0\n";
799        let post_block = "my_histogram_family_bucket{method=\"POST\",status=\"500\",le=\"0.5\"} 0\n"
800            .to_owned()
801            + "my_histogram_family_bucket{method=\"POST\",status=\"500\",le=\"+Inf\"} 0\n"
802            + "my_histogram_family_sum{method=\"POST\",status=\"500\"} 0.0\n"
803            + "my_histogram_family_count{method=\"POST\",status=\"500\"} 0\n";
804
805        let encoded = encode_to_string(&registry);
806        assert_encoded_with_blocks_in_any_order(&encoded, &prefix, &[&get_block, &post_block]);
807        parse_with_python_client(encoded);
808    }
809
810    #[test]
811    fn encode_histogram_drops_exemplars() {
812        let mut registry = Registry::default();
813        let histogram = HistogramWithExemplars::new([0.5].into_iter());
814        registry.register("my_histogram", "My histogram", histogram.clone());
815        histogram.observe(0.25, Some(vec![("user_id".to_string(), 42u64)]), None);
816
817        let family = register_histogram_family(&mut registry);
818        family.get_or_create(&get_label_set()).observe(
819            0.25,
820            Some(vec![("user_id".to_string(), 42)]),
821            None,
822        );
823        family.get_or_create(&post_500_label_set()).observe(
824            0.75,
825            Some(vec![("user_id".to_string(), 7)]),
826            None,
827        );
828
829        let prefix = "# HELP my_histogram My histogram.\n".to_owned()
830            + "# TYPE my_histogram histogram\n"
831            + "my_histogram_bucket{le=\"0.5\"} 1\n"
832            + "my_histogram_bucket{le=\"+Inf\"} 1\n"
833            + "my_histogram_sum 0.25\n"
834            + "my_histogram_count 1\n"
835            + "# HELP my_histogram_family My histogram family.\n"
836            + "# TYPE my_histogram_family histogram\n";
837        let get_block = "my_histogram_family_bucket{method=\"GET\",le=\"0.5\"} 1\n".to_owned()
838            + "my_histogram_family_bucket{method=\"GET\",le=\"+Inf\"} 1\n"
839            + "my_histogram_family_sum{method=\"GET\"} 0.25\n"
840            + "my_histogram_family_count{method=\"GET\"} 1\n";
841        let post_block = "my_histogram_family_bucket{method=\"POST\",status=\"500\",le=\"0.5\"} 0\n"
842            .to_owned()
843            + "my_histogram_family_bucket{method=\"POST\",status=\"500\",le=\"+Inf\"} 1\n"
844            + "my_histogram_family_sum{method=\"POST\",status=\"500\"} 0.75\n"
845            + "my_histogram_family_count{method=\"POST\",status=\"500\"} 1\n";
846
847        let encoded = encode_to_string(&registry);
848        assert_encoded_with_blocks_in_any_order(&encoded, &prefix, &[&get_block, &post_block]);
849        parse_with_python_client(encoded);
850    }
851
852    #[test]
853    fn encode_native_histograms() {
854        let mut registry = Registry::default();
855        let native_only = Histogram::new_native(NativeHistogramConfig::default());
856        registry.register("native_only", "Native only", native_only.clone());
857        native_only.observe(3.0);
858
859        let native_and_classic =
860            Histogram::new_classic_and_native([1.0], NativeHistogramConfig::default());
861        registry.register(
862            "native_and_classic",
863            "Native and classic",
864            native_and_classic.clone(),
865        );
866        native_and_classic.observe(0.5);
867
868        let expected = "# HELP native_only Native only.\n".to_owned()
869            + "# TYPE native_only histogram\n"
870            + "native_only_bucket{le=\"+Inf\"} 1\n"
871            + "native_only_sum 3.0\n"
872            + "native_only_count 1\n"
873            + "# HELP native_and_classic Native and classic.\n"
874            + "# TYPE native_and_classic histogram\n"
875            + "native_and_classic_bucket{le=\"1\"} 1\n"
876            + "native_and_classic_bucket{le=\"+Inf\"} 1\n"
877            + "native_and_classic_sum 0.5\n"
878            + "native_and_classic_count 1\n";
879        let encoded = encode_to_string(&registry);
880        assert_eq!(expected, encoded);
881        parse_with_python_client(encoded);
882    }
883
884    #[test]
885    fn encode_family_with_const_labels_and_prefix() {
886        let mut registry = Registry::default();
887        let sub_registry = registry
888            .sub_registry_with_prefix("my_prefix")
889            .sub_registry_with_label((Cow::Borrowed("region"), Cow::Borrowed("eu")));
890
891        let counters = Family::<Vec<(String, String)>, Counter>::default();
892        sub_registry.register("my_counter_family", "My counter family", counters.clone());
893        counters
894            .get_or_create(&vec![
895                ("method".to_string(), "GET".to_string()),
896                ("status".to_string(), "200".to_string()),
897            ])
898            .inc();
899
900        let histograms = Family::<Vec<(String, String)>, Histogram>::new_with_constructor(|| {
901            Histogram::new([1.0])
902        });
903        sub_registry.register(
904            "my_histogram_family",
905            "My histogram family",
906            histograms.clone(),
907        );
908        histograms
909            .get_or_create(&vec![("method".to_string(), "GET".to_string())])
910            .observe(0.5);
911
912        let expected = "# HELP my_prefix_my_counter_family_total My counter family.\n".to_owned()
913            + "# TYPE my_prefix_my_counter_family_total counter\n"
914            + "my_prefix_my_counter_family_total{region=\"eu\",method=\"GET\",status=\"200\"} 1\n"
915            + "# HELP my_prefix_my_histogram_family My histogram family.\n"
916            + "# TYPE my_prefix_my_histogram_family histogram\n"
917            + "my_prefix_my_histogram_family_bucket{region=\"eu\",method=\"GET\",le=\"1\"} 1\n"
918            + "my_prefix_my_histogram_family_bucket{region=\"eu\",method=\"GET\",le=\"+Inf\"} 1\n"
919            + "my_prefix_my_histogram_family_sum{region=\"eu\",method=\"GET\"} 0.5\n"
920            + "my_prefix_my_histogram_family_count{region=\"eu\",method=\"GET\"} 1\n";
921        let encoded = encode_to_string(&registry);
922        assert_eq!(expected, encoded);
923        parse_with_python_client(encoded);
924    }
925
926    #[test]
927    fn encode_family_with_empty_label_set() {
928        let mut registry = Registry::default();
929        let family = Family::<Vec<(String, String)>, Counter>::default();
930        registry.register("my_counter", "My counter", family.clone());
931        family.get_or_create(&vec![]).inc();
932
933        let expected = "# HELP my_counter_total My counter.\n".to_owned()
934            + "# TYPE my_counter_total counter\n"
935            + "my_counter_total 1\n";
936        let encoded = encode_to_string(&registry);
937        assert_eq!(expected, encoded);
938        parse_with_python_client(encoded);
939    }
940
941    #[test]
942    fn encode_omits_empty_family() {
943        let mut registry = Registry::default();
944        let family = Family::<Vec<(String, String)>, Counter>::default();
945        registry.register("my_counter", "My counter", family);
946
947        assert_eq!("", encode_to_string(&registry));
948    }
949
950    #[test]
951    fn encode_flushes_large_output_in_chunks() {
952        /// Writer recording each `write_str` call separately.
953        #[derive(Default)]
954        struct ChunkRecorder(Vec<String>);
955
956        impl Write for ChunkRecorder {
957            fn write_str(&mut self, s: &str) -> std::fmt::Result {
958                self.0.push(s.to_owned());
959                Ok(())
960            }
961        }
962
963        let mut registry = Registry::default();
964        for i in 0..200 {
965            let family = Family::<Vec<(String, String)>, Counter>::default();
966            registry.register(format!("my_counter_{i}"), "My counter", family.clone());
967            for j in 0..10 {
968                family
969                    .get_or_create(&vec![("label".to_string(), j.to_string())])
970                    .inc();
971            }
972        }
973
974        let expected = encode_to_string(&registry);
975        assert!(expected.len() > 2 * FLUSH_THRESHOLD);
976
977        let mut recorder = ChunkRecorder::default();
978        encode(&mut recorder, &registry).unwrap();
979
980        // The output is flushed in multiple chunks of at least
981        // `FLUSH_THRESHOLD` bytes (except for the trailing remainder), and the
982        // concatenation matches.
983        let (tail, chunks) = recorder.0.split_last().unwrap();
984        assert!(chunks.len() > 1);
985        assert!(chunks.iter().all(|chunk| chunk.len() >= FLUSH_THRESHOLD));
986        assert!(tail.len() < FLUSH_THRESHOLD);
987        assert_eq!(recorder.0.concat(), expected);
988
989        parse_with_python_client(expected);
990    }
991
992    #[test]
993    fn encode_escapes_help_and_label_values() {
994        let mut registry = Registry::default();
995        let family = Family::<Vec<(String, String)>, Gauge>::default();
996        registry.register(
997            "my_gauge",
998            "Help with \\ backslash, \"quotes\" and\nnewline",
999            family.clone(),
1000        );
1001        family
1002            .get_or_create(&vec![(
1003                "path".to_string(),
1004                "C:\\dir \"quoted\"\nnext".to_string(),
1005            )])
1006            .set(2);
1007
1008        let expected = "# HELP my_gauge Help with \\\\ backslash, \"quotes\" and\\nnewline.\n"
1009            .to_owned()
1010            + "# TYPE my_gauge gauge\n"
1011            + "my_gauge{path=\"C:\\\\dir \\\"quoted\\\"\\nnext\"} 2\n";
1012        let encoded = encode_to_string(&registry);
1013        assert_eq!(expected, encoded);
1014        parse_with_python_client(encoded);
1015    }
1016
1017    #[test]
1018    fn go_float_matches_go() {
1019        // Expected values generated with Go 1.26 via
1020        // `strconv.FormatFloat(v, 'g', -1, 64)`, except for `-0.0`, which
1021        // client_golang's expfmt writes as `0`.
1022        let cases: &[(f64, &str)] = &[
1023            (0.0, "0"),
1024            (-0.0, "0"),
1025            (1.0, "1"),
1026            (-1.0, "-1"),
1027            (2.5, "2.5"),
1028            (0.1, "0.1"),
1029            (0.25, "0.25"),
1030            (0.0001, "0.0001"),
1031            (0.0003, "0.0003"),
1032            (0.00001, "1e-05"),
1033            (1e-7, "1e-07"),
1034            (1.5e-7, "1.5e-07"),
1035            (99999.0, "99999"),
1036            (100000.0, "100000"),
1037            (999999.0, "999999"),
1038            (1e6, "1e+06"),
1039            (-1e6, "-1e+06"),
1040            (1234567.0, "1.234567e+06"),
1041            (123456789.0, "1.23456789e+08"),
1042            (-123.456, "-123.456"),
1043            (1.0 / 3.0, "0.3333333333333333"),
1044            (0.1 + 0.2, "0.30000000000000004"),
1045            (1e15, "1e+15"),
1046            (1e21, "1e+21"),
1047            (1e22, "1e+22"),
1048            (1e300, "1e+300"),
1049            (9007199254740992.0, "9.007199254740992e+15"),
1050            (f64::MAX, "1.7976931348623157e+308"),
1051            (f64::MIN_POSITIVE, "2.2250738585072014e-308"),
1052            (5e-324, "5e-324"),
1053            (f64::INFINITY, "+Inf"),
1054            (f64::NEG_INFINITY, "-Inf"),
1055            (f64::NAN, "NaN"),
1056            // Neighbors of the plain/exponent notation boundaries.
1057            (
1058                f64::from_bits(1e-4f64.to_bits() - 1),
1059                "9.999999999999999e-05",
1060            ),
1061            (999999.9999999999, "999999.9999999999"),
1062        ];
1063        for (v, expected) in cases {
1064            assert_eq!(*expected, GoFloat(*v).to_string(), "for {v:?}");
1065        }
1066    }
1067
1068    #[test]
1069    fn go_float_matches_go_exponential_buckets() {
1070        // `exponential_buckets(1.0, 2.0, 25)`
1071        let exponential = [
1072            "1",
1073            "2",
1074            "4",
1075            "8",
1076            "16",
1077            "32",
1078            "64",
1079            "128",
1080            "256",
1081            "512",
1082            "1024",
1083            "2048",
1084            "4096",
1085            "8192",
1086            "16384",
1087            "32768",
1088            "65536",
1089            "131072",
1090            "262144",
1091            "524288",
1092            "1.048576e+06",
1093            "2.097152e+06",
1094            "4.194304e+06",
1095            "8.388608e+06",
1096            "1.6777216e+07",
1097        ];
1098        for (v, expected) in
1099            crate::metrics::histogram::exponential_buckets(1.0, 2.0, 25).zip(exponential)
1100        {
1101            assert_eq!(expected, GoFloat(v).to_string(), "for {v:?}");
1102        }
1103    }
1104
1105    #[test]
1106    fn go_float_matches_go_linear_buckets() {
1107        // `linear_buckets(0.005, 0.005, 10)`, accumulated rounding error must be
1108        // preserved exactly as Go would print it.
1109        let linear = [
1110            "0.005",
1111            "0.01",
1112            "0.015",
1113            "0.02",
1114            "0.025",
1115            "0.030000000000000002",
1116            "0.034999999999999996",
1117            "0.04",
1118            "0.045",
1119            "0.049999999999999996",
1120        ];
1121        for (v, expected) in crate::metrics::histogram::linear_buckets(0.005, 0.005, 10).zip(linear)
1122        {
1123            assert_eq!(expected, GoFloat(v).to_string(), "for {v:?}");
1124        }
1125    }
1126
1127    fn parse_with_python_client(input: String) {
1128        pyo3::Python::initialize();
1129
1130        println!("{input:?}");
1131        Python::attach(|py| {
1132            let parser = PyModule::from_code(
1133                py,
1134                c"
1135from prometheus_client.parser import text_string_to_metric_families
1136
1137def parse(input):
1138    families = text_string_to_metric_families(input)
1139    list(families)
1140",
1141                c"parser.py",
1142                c"parser",
1143            )
1144            .map_err(|e| e.to_string())
1145            .unwrap();
1146
1147            parser
1148                .getattr("parse")
1149                .expect("`parse` to exist.")
1150                .call1((input.clone(),))
1151                .map_err(|e| e.to_string())
1152                .unwrap();
1153        })
1154    }
1155}