Skip to main content

prometheus_client/encoding/
text.rs

1//! Open Metrics text format implementation.
2//!
3//! ```
4//! # use prometheus_client::encoding::text::{encode, encode_registry, encode_eof};
5//! # use prometheus_client::metrics::counter::Counter;
6//! # use prometheus_client::registry::Registry;
7//! #
8//! # // Create registry and counter and register the latter with the former.
9//! # let mut registry = Registry::default();
10//! # let counter: Counter = Counter::default();
11//! # registry.register(
12//! #   "my_counter",
13//! #   "This is my counter",
14//! #   counter.clone(),
15//! # );
16//! # counter.inc();
17//! let mut buffer = String::new();
18//!
19//! // Encode the complete OpenMetrics exposition into the message buffer
20//! encode(&mut buffer, &registry).unwrap();
21//! let expected_msg = "# HELP my_counter This is my counter.\n".to_owned() +
22//!                    "# TYPE my_counter counter\n" +
23//!                    "my_counter_total 1\n" +
24//!                    "# EOF\n";
25//! assert_eq!(expected_msg, buffer);
26//! buffer.clear();
27//!
28//! // Encode just the registry into the message buffer
29//! encode_registry(&mut buffer, &registry).unwrap();
30//! let expected_reg = "# HELP my_counter This is my counter.\n".to_owned() +
31//!                    "# TYPE my_counter counter\n" +
32//!                    "my_counter_total 1\n";
33//! assert_eq!(expected_reg, buffer);
34//!
35//! // Encode EOF marker into message buffer to complete the OpenMetrics exposition
36//! encode_eof(&mut buffer).unwrap();
37//! assert_eq!(expected_msg, buffer);
38//! ```
39
40use crate::encoding::{
41    EncodeExemplarTime, EncodeExemplarValue, EncodeLabelSet, NativeHistogram, NoLabelSet,
42};
43use crate::metrics::exemplar::Exemplar;
44use crate::metrics::MetricType;
45use crate::registry::{Prefix, Registry, Unit};
46
47use std::borrow::Cow;
48use std::collections::HashMap;
49use std::fmt::Write;
50
51/// Encode both the metrics registered with the provided [`Registry`] and the
52/// EOF marker into the provided [`Write`]r using the OpenMetrics text format.
53///
54/// Note: This function encodes the **complete** OpenMetrics exposition.
55///
56/// Use [`encode_registry`] or [`encode_eof`] if partial encoding is needed.
57///
58/// See [OpenMetrics exposition format](https://github.com/prometheus/OpenMetrics/blob/v1.0.0/specification/OpenMetrics.md#text-format)
59/// for additional details.
60///
61/// # Examples
62///
63/// ```no_run
64/// # use prometheus_client::encoding::text::encode;
65/// # use prometheus_client::metrics::counter::Counter;
66/// # use prometheus_client::metrics::gauge::Gauge;
67/// # use prometheus_client::registry::Registry;
68/// #
69/// // Initialize registry with metric families
70/// let mut registry = Registry::default();
71/// let counter: Counter = Counter::default();
72/// registry.register(
73///     "my_counter",
74///     "This is my counter",
75///     counter.clone(),
76/// );
77/// let gauge: Gauge = Gauge::default();
78/// registry.register(
79///     "my_gauge",
80///     "This is my gauge",
81///     gauge.clone(),
82/// );
83///
84/// // Encode the complete OpenMetrics exposition into the buffer
85/// let mut buffer = String::new();
86/// encode(&mut buffer, &registry)?;
87/// # Ok::<(), std::fmt::Error>(())
88/// ```
89pub fn encode<W>(writer: &mut W, registry: &Registry) -> Result<(), std::fmt::Error>
90where
91    W: Write,
92{
93    encode_registry(writer, registry)?;
94    encode_eof(writer)
95}
96
97/// Encode the metrics registered with the provided [`Registry`] into the
98/// provided [`Write`]r using the OpenMetrics text format.
99///
100/// Note: The OpenMetrics exposition requires that a complete message must end
101/// with an EOF marker.
102///
103/// This function may be called repeatedly for the HTTP scrape response until
104/// [`encode_eof`] signals the end of the response.
105///
106/// This may also be used to compose a partial message with metrics assembled
107/// from multiple registries.
108///
109/// # Examples
110///
111/// ```no_run
112/// # use prometheus_client::encoding::text::encode_registry;
113/// # use prometheus_client::metrics::counter::Counter;
114/// # use prometheus_client::metrics::gauge::Gauge;
115/// # use prometheus_client::registry::Registry;
116/// #
117/// // Initialize registry with a counter
118/// let mut reg_counter = Registry::default();
119/// let counter: Counter = Counter::default();
120/// reg_counter.register(
121///     "my_counter",
122///     "This is my counter",
123///     counter.clone(),
124/// );
125///
126/// // Encode the counter registry into the buffer
127/// let mut buffer = String::new();
128/// encode_registry(&mut buffer, &reg_counter)?;
129///
130/// // Initialize another registry but with a gauge
131/// let mut reg_gauge = Registry::default();
132/// let gauge: Gauge = Gauge::default();
133/// reg_gauge.register(
134///   "my_gauge",
135///   "This is my gauge",
136///   gauge.clone(),
137/// );
138///
139/// // Encode the gauge registry into the buffer
140/// encode_registry(&mut buffer, &reg_gauge)?;
141/// # Ok::<(), std::fmt::Error>(())
142/// ```
143pub fn encode_registry<W>(writer: &mut W, registry: &Registry) -> Result<(), std::fmt::Error>
144where
145    W: Write,
146{
147    let mut buffer = TextBuf::new_buffer();
148    registry.encode(&mut DescriptorEncoder::new(TextBuf::new(&mut buffer, writer)).into())?;
149    writer.write_str(&buffer)
150}
151
152/// Size (in bytes) at which [`TextBuf`] flushes its buffer to the sink.
153///
154/// Flushed chunks are at least this large, except for the final remainder and
155/// for a flush that precedes a write larger than this threshold (such writes
156/// bypass the buffer, see [`TextBuf::write_large`]).
157pub(crate) const FLUSH_THRESHOLD: usize = 4 * 1024;
158
159/// Largest size the buffer can reach: it holds at most `FLUSH_THRESHOLD - 1`
160/// bytes before a write, and a single buffered write is at most
161/// `FLUSH_THRESHOLD` bytes. Reserving this up front keeps
162/// [`TextBuf::write_str`] allocation free.
163const BUFFER_CAPACITY: usize = FLUSH_THRESHOLD * 2 - 1;
164
165/// Buffered writer used by all text encoders.
166pub(crate) struct TextBuf<'a> {
167    buf: &'a mut String,
168    sink: &'a mut dyn Write,
169}
170
171impl<'a> TextBuf<'a> {
172    pub(crate) fn new(buf: &'a mut String, sink: &'a mut dyn Write) -> Self {
173        Self { buf, sink }
174    }
175
176    /// Reborrow with a shorter lifetime, e.g. to hand to a child encoder.
177    #[inline]
178    pub(crate) fn reborrow(&mut self) -> TextBuf<'_> {
179        TextBuf {
180            buf: self.buf,
181            sink: self.sink,
182        }
183    }
184
185    /// Allocate a buffer large enough that [`TextBuf::write_str`] never has to
186    /// grow it.
187    pub(crate) fn new_buffer() -> String {
188        String::with_capacity(BUFFER_CAPACITY)
189    }
190
191    #[cold]
192    #[inline(never)]
193    fn flush(&mut self) -> std::fmt::Result {
194        self.sink.write_str(self.buf)?;
195        self.buf.clear();
196        Ok(())
197    }
198
199    /// Flush pending output, then hand `s` to the sink directly instead of
200    /// copying it through (and growing) the buffer.
201    #[cold]
202    #[inline(never)]
203    fn write_large(&mut self, s: &str) -> std::fmt::Result {
204        if !self.buf.is_empty() {
205            self.flush()?;
206        }
207        self.sink.write_str(s)
208    }
209}
210
211impl Write for TextBuf<'_> {
212    #[inline]
213    fn write_str(&mut self, s: &str) -> std::fmt::Result {
214        if s.len() > FLUSH_THRESHOLD {
215            return self.write_large(s);
216        }
217        self.buf.push_str(s);
218        if self.buf.len() >= FLUSH_THRESHOLD {
219            self.flush()?;
220        }
221        Ok(())
222    }
223}
224
225impl TextBuf<'_> {
226    /// Run `f` with a [`TextBuf`] and collect everything it writes into a
227    /// `String`.
228    pub(crate) fn encode_to_string(
229        f: impl FnOnce(TextBuf<'_>) -> std::fmt::Result,
230    ) -> Result<String, std::fmt::Error> {
231        let mut out = String::new();
232        let mut buf = String::new();
233        f(TextBuf::new(&mut buf, &mut out))?;
234        out.push_str(&buf);
235        Ok(out)
236    }
237}
238
239/// Encode the EOF marker into the provided [`Write`]r using the OpenMetrics
240/// text format.
241///
242/// Note: This function is used to mark/signal the end of the exposition.
243///
244/// # Examples
245///
246/// ```no_run
247/// # use prometheus_client::encoding::text::{encode_registry, encode_eof};
248/// # use prometheus_client::metrics::counter::Counter;
249/// # use prometheus_client::metrics::gauge::Gauge;
250/// # use prometheus_client::registry::Registry;
251/// #
252/// // Initialize registry with a counter
253/// let mut registry = Registry::default();
254/// let counter: Counter = Counter::default();
255/// registry.register(
256///     "my_counter",
257///     "This is my counter",
258///     counter.clone(),
259/// );
260///
261/// // Encode registry into the buffer
262/// let mut buffer = String::new();
263/// encode_registry(&mut buffer, &registry)?;
264///
265/// // Encode EOF marker to complete the message
266/// encode_eof(&mut buffer)?;
267/// # Ok::<(), std::fmt::Error>(())
268/// ```
269pub fn encode_eof<W>(writer: &mut W) -> Result<(), std::fmt::Error>
270where
271    W: Write,
272{
273    writer.write_str("# EOF\n")
274}
275
276pub(crate) struct DescriptorEncoder<'a> {
277    writer: TextBuf<'a>,
278    prefix: Option<&'a Prefix>,
279    labels: &'a [(Cow<'static, str>, Cow<'static, str>)],
280}
281
282impl std::fmt::Debug for DescriptorEncoder<'_> {
283    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284        f.debug_struct("DescriptorEncoder").finish()
285    }
286}
287
288impl<'a> DescriptorEncoder<'a> {
289    pub(crate) fn new(writer: TextBuf<'a>) -> DescriptorEncoder<'a> {
290        DescriptorEncoder {
291            writer,
292            prefix: Default::default(),
293            labels: Default::default(),
294        }
295    }
296
297    pub(crate) fn with_prefix_and_labels<'s>(
298        &'s mut self,
299        prefix: Option<&'s Prefix>,
300        labels: &'s [(Cow<'static, str>, Cow<'static, str>)],
301    ) -> DescriptorEncoder<'s> {
302        DescriptorEncoder {
303            prefix,
304            labels,
305            writer: self.writer.reborrow(),
306        }
307    }
308
309    pub fn encode_descriptor<'s>(
310        &'s mut self,
311        name: &'s str,
312        help: &str,
313        unit: Option<&'s Unit>,
314        metric_type: MetricType,
315    ) -> Result<MetricEncoder<'s>, std::fmt::Error> {
316        self.writer.write_str("# HELP ")?;
317        if let Some(prefix) = self.prefix {
318            self.writer.write_str(prefix.as_str())?;
319            self.writer.write_str("_")?;
320        }
321        self.writer.write_str(name)?;
322        if let Some(unit) = unit {
323            self.writer.write_str("_")?;
324            self.writer.write_str(unit.as_str())?;
325        }
326        self.writer.write_str(" ")?;
327        self.writer.write_str(help)?;
328        self.writer.write_str("\n")?;
329
330        self.writer.write_str("# TYPE ")?;
331        if let Some(prefix) = self.prefix {
332            self.writer.write_str(prefix.as_str())?;
333            self.writer.write_str("_")?;
334        }
335        self.writer.write_str(name)?;
336        if let Some(unit) = unit {
337            self.writer.write_str("_")?;
338            self.writer.write_str(unit.as_str())?;
339        }
340        self.writer.write_str(" ")?;
341        self.writer.write_str(metric_type.as_str())?;
342        self.writer.write_str("\n")?;
343
344        if let Some(unit) = unit {
345            self.writer.write_str("# UNIT ")?;
346            if let Some(prefix) = self.prefix {
347                self.writer.write_str(prefix.as_str())?;
348                self.writer.write_str("_")?;
349            }
350            self.writer.write_str(name)?;
351            self.writer.write_str("_")?;
352            self.writer.write_str(unit.as_str())?;
353            self.writer.write_str(" ")?;
354            self.writer.write_str(unit.as_str())?;
355            self.writer.write_str("\n")?;
356        }
357
358        Ok(MetricEncoder {
359            writer: self.writer.reborrow(),
360            prefix: self.prefix,
361            name,
362            unit,
363            const_labels: self.labels,
364            family_labels: None,
365        })
366    }
367}
368
369/// Helper type for [`EncodeMetric`](super::EncodeMetric), see
370/// [`EncodeMetric::encode`](super::EncodeMetric::encode).
371///
372// `MetricEncoder` does not take a trait parameter for `writer` and `labels`
373// because `EncodeMetric` which uses `MetricEncoder` needs to be usable as a
374// trait object in order to be able to register different metric types with a
375// `Registry`. Trait objects can not use type parameters.
376//
377// TODO: Alternative solutions to the above are very much appreciated.
378pub(crate) struct MetricEncoder<'a> {
379    writer: TextBuf<'a>,
380    prefix: Option<&'a Prefix>,
381    name: &'a str,
382    unit: Option<&'a Unit>,
383    const_labels: &'a [(Cow<'static, str>, Cow<'static, str>)],
384    family_labels: Option<&'a dyn super::EncodeLabelSet>,
385}
386
387impl std::fmt::Debug for MetricEncoder<'_> {
388    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
389        let labels = TextBuf::encode_to_string(|buf| match self.family_labels {
390            Some(l) => LabelList::new("").encode(buf, l),
391            None => Ok(()),
392        })?;
393
394        f.debug_struct("Encoder")
395            .field("name", &self.name)
396            .field("prefix", &self.prefix)
397            .field("unit", &self.unit)
398            .field("const_labels", &self.const_labels)
399            .field("labels", &labels.as_str())
400            .finish()
401    }
402}
403
404impl MetricEncoder<'_> {
405    pub fn encode_counter<
406        S: EncodeLabelSet,
407        CounterValue: super::EncodeCounterValue,
408        ExemplarValue: EncodeExemplarValue,
409    >(
410        &mut self,
411        v: &CounterValue,
412        exemplar: Option<&Exemplar<S, ExemplarValue>>,
413    ) -> Result<(), std::fmt::Error> {
414        self.write_prefix_name_unit()?;
415
416        self.write_suffix("total")?;
417
418        self.encode_labels::<NoLabelSet>(None)?;
419
420        v.encode(
421            &mut CounterValueEncoder {
422                writer: self.writer.reborrow(),
423            }
424            .into(),
425        )?;
426
427        if let Some(exemplar) = exemplar {
428            self.encode_exemplar(exemplar)?;
429        }
430
431        self.newline()?;
432
433        Ok(())
434    }
435
436    pub fn encode_gauge<GaugeValue: super::EncodeGaugeValue>(
437        &mut self,
438        v: &GaugeValue,
439    ) -> Result<(), std::fmt::Error> {
440        self.write_prefix_name_unit()?;
441
442        self.encode_labels::<NoLabelSet>(None)?;
443
444        v.encode(
445            &mut GaugeValueEncoder {
446                writer: self.writer.reborrow(),
447            }
448            .into(),
449        )?;
450
451        self.newline()?;
452
453        Ok(())
454    }
455
456    pub fn encode_info<S: EncodeLabelSet>(&mut self, label_set: &S) -> Result<(), std::fmt::Error> {
457        self.write_prefix_name_unit()?;
458
459        self.write_suffix("info")?;
460
461        self.encode_labels(Some(label_set))?;
462
463        self.writer.write_str(" ")?;
464        self.writer.write_str(itoa::Buffer::new().format(1))?;
465
466        self.newline()?;
467
468        Ok(())
469    }
470
471    /// Encode a set of labels. Used by wrapper metric types like
472    /// [`Family`](crate::metrics::family::Family).
473    pub fn encode_family<'s, S: EncodeLabelSet>(
474        &'s mut self,
475        label_set: &'s S,
476    ) -> Result<MetricEncoder<'s>, std::fmt::Error> {
477        debug_assert!(self.family_labels.is_none());
478
479        Ok(MetricEncoder {
480            writer: self.writer.reborrow(),
481            prefix: self.prefix,
482            name: self.name,
483            unit: self.unit,
484            const_labels: self.const_labels,
485            family_labels: Some(label_set),
486        })
487    }
488
489    pub fn encode_histogram<S: EncodeLabelSet>(
490        &mut self,
491        sum: f64,
492        count: u64,
493        buckets: &[(f64, u64)],
494        exemplars: Option<&HashMap<usize, Exemplar<S, f64>>>,
495    ) -> Result<(), std::fmt::Error> {
496        self.write_prefix_name_unit()?;
497        self.write_suffix("sum")?;
498        self.encode_labels::<NoLabelSet>(None)?;
499        self.writer.write_str(" ")?;
500        self.writer.write_str(dtoa::Buffer::new().format(sum))?;
501        self.newline()?;
502
503        self.write_prefix_name_unit()?;
504        self.write_suffix("count")?;
505        self.encode_labels::<NoLabelSet>(None)?;
506        self.writer.write_str(" ")?;
507        self.writer.write_str(itoa::Buffer::new().format(count))?;
508        self.newline()?;
509
510        let mut cummulative = 0;
511        for (i, (upper_bound, count)) in buckets.iter().enumerate() {
512            cummulative += count;
513
514            self.write_prefix_name_unit()?;
515            self.write_suffix("bucket")?;
516
517            if *upper_bound == f64::INFINITY {
518                self.encode_labels(Some(&[("le", "+Inf")]))?;
519            } else {
520                self.encode_labels(Some(&[("le", *upper_bound)]))?;
521            }
522
523            self.writer.write_str(" ")?;
524            self.writer
525                .write_str(itoa::Buffer::new().format(cummulative))?;
526
527            if let Some(exemplar) = exemplars.and_then(|e| e.get(&i)) {
528                self.encode_exemplar(exemplar)?
529            }
530
531            self.newline()?;
532        }
533
534        Ok(())
535    }
536
537    pub fn encode_histogram_with_native<S: EncodeLabelSet>(
538        &mut self,
539        sum: f64,
540        count: u64,
541        buckets: &[(f64, u64)],
542        exemplars: Option<&HashMap<usize, Exemplar<S, f64>>>,
543        _native: NativeHistogram<'_>,
544    ) -> Result<(), std::fmt::Error> {
545        if buckets.is_empty() {
546            return Err(std::fmt::Error);
547        }
548
549        self.encode_histogram(sum, count, buckets, exemplars)
550    }
551
552    /// Encode an exemplar for the given metric.
553    fn encode_exemplar<S: EncodeLabelSet, V: EncodeExemplarValue>(
554        &mut self,
555        exemplar: &Exemplar<S, V>,
556    ) -> Result<(), std::fmt::Error> {
557        self.writer.write_str(" # {")?;
558        LabelList::new("").encode(self.writer.reborrow(), &exemplar.label_set)?;
559        self.writer.write_str("} ")?;
560        exemplar.value.encode(
561            ExemplarValueEncoder {
562                writer: self.writer.reborrow(),
563            }
564            .into(),
565        )?;
566        if let Some(timestamp) = exemplar.timestamp {
567            self.writer.write_char(' ')?;
568            timestamp.encode(
569                ExemplarValueEncoder {
570                    writer: self.writer.reborrow(),
571                }
572                .into(),
573            )?;
574        }
575        Ok(())
576    }
577
578    fn newline(&mut self) -> Result<(), std::fmt::Error> {
579        self.writer.write_str("\n")
580    }
581    fn write_prefix_name_unit(&mut self) -> Result<(), std::fmt::Error> {
582        if let Some(prefix) = self.prefix {
583            self.writer.write_str(prefix.as_str())?;
584            self.writer.write_str("_")?;
585        }
586        self.writer.write_str(self.name)?;
587        if let Some(unit) = self.unit {
588            self.writer.write_str("_")?;
589            self.writer.write_str(unit.as_str())?;
590        }
591
592        Ok(())
593    }
594
595    fn write_suffix(&mut self, suffix: &'static str) -> Result<(), std::fmt::Error> {
596        self.writer.write_str("_")?;
597        self.writer.write_str(suffix)?;
598
599        Ok(())
600    }
601
602    // TODO: Consider caching the encoded labels for Histograms as they stay the
603    // same but are currently encoded multiple times.
604    fn encode_labels<S: EncodeLabelSet>(
605        &mut self,
606        additional_labels: Option<&S>,
607    ) -> Result<(), std::fmt::Error> {
608        let mut list = LabelList::new("{");
609        list.encode(self.writer.reborrow(), &self.const_labels)?;
610        if let Some(labels) = additional_labels {
611            list.encode(self.writer.reborrow(), labels)?;
612        }
613        if let Some(labels) = self.family_labels {
614            list.encode(self.writer.reborrow(), labels)?;
615        }
616        list.finish(self.writer.reborrow(), "}")
617    }
618}
619
620pub(crate) struct CounterValueEncoder<'a> {
621    writer: TextBuf<'a>,
622}
623
624impl std::fmt::Debug for CounterValueEncoder<'_> {
625    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
626        f.debug_struct("CounterValueEncoder").finish()
627    }
628}
629
630impl CounterValueEncoder<'_> {
631    pub fn encode_f64(&mut self, v: f64) -> Result<(), std::fmt::Error> {
632        self.writer.write_str(" ")?;
633        self.writer.write_str(dtoa::Buffer::new().format(v))?;
634        Ok(())
635    }
636
637    pub fn encode_u64(&mut self, v: u64) -> Result<(), std::fmt::Error> {
638        self.writer.write_str(" ")?;
639        self.writer.write_str(itoa::Buffer::new().format(v))?;
640        Ok(())
641    }
642}
643
644pub(crate) struct GaugeValueEncoder<'a> {
645    writer: TextBuf<'a>,
646}
647
648impl std::fmt::Debug for GaugeValueEncoder<'_> {
649    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
650        f.debug_struct("GaugeValueEncoder").finish()
651    }
652}
653
654impl GaugeValueEncoder<'_> {
655    pub fn encode_u32(&mut self, v: u32) -> Result<(), std::fmt::Error> {
656        self.writer.write_str(" ")?;
657        self.writer.write_str(itoa::Buffer::new().format(v))?;
658        Ok(())
659    }
660
661    pub fn encode_u64(&mut self, v: u64) -> Result<(), std::fmt::Error> {
662        self.writer.write_str(" ")?;
663        self.writer.write_str(itoa::Buffer::new().format(v))?;
664        Ok(())
665    }
666
667    pub fn encode_i64(&mut self, v: i64) -> Result<(), std::fmt::Error> {
668        self.writer.write_str(" ")?;
669        self.writer.write_str(itoa::Buffer::new().format(v))?;
670        Ok(())
671    }
672
673    pub fn encode_f64(&mut self, v: f64) -> Result<(), std::fmt::Error> {
674        self.writer.write_str(" ")?;
675        self.writer.write_str(dtoa::Buffer::new().format(v))?;
676        Ok(())
677    }
678}
679
680pub(crate) struct ExemplarValueEncoder<'a> {
681    writer: TextBuf<'a>,
682}
683
684impl std::fmt::Debug for ExemplarValueEncoder<'_> {
685    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
686        f.debug_struct("ExemplarValueEncoder").finish()
687    }
688}
689
690impl ExemplarValueEncoder<'_> {
691    pub fn encode(&mut self, v: f64) -> Result<(), std::fmt::Error> {
692        self.writer.write_str(dtoa::Buffer::new().format(v))
693    }
694}
695
696/// Joins one or more label sets into a single comma-separated list.
697///
698/// `open` is written lazily before the first label key, so label sets which
699/// turn out to be empty, as well as labels which never encode a key, produce
700/// no output (in particular, no stray `,` or `{}`).
701#[derive(Debug)]
702pub(crate) struct LabelList {
703    open: &'static str,
704    written: bool,
705}
706
707impl LabelList {
708    pub(crate) fn new(open: &'static str) -> Self {
709        Self {
710            open,
711            written: false,
712        }
713    }
714
715    /// Append all labels of `labels` to the list.
716    pub(crate) fn encode<S: EncodeLabelSet + ?Sized>(
717        &mut self,
718        mut writer: TextBuf<'_>,
719        labels: &S,
720    ) -> Result<(), std::fmt::Error> {
721        labels.encode(&mut LabelSetEncoder::new(writer.reborrow(), self).into())
722    }
723
724    /// Write `close` if at least one label has been written.
725    pub(crate) fn finish(
726        self,
727        mut writer: TextBuf<'_>,
728        close: &str,
729    ) -> Result<(), std::fmt::Error> {
730        if self.written {
731            writer.write_str(close)?;
732        }
733        Ok(())
734    }
735}
736
737pub(crate) struct LabelSetEncoder<'a> {
738    writer: TextBuf<'a>,
739    list: &'a mut LabelList,
740}
741
742impl std::fmt::Debug for LabelSetEncoder<'_> {
743    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
744        f.debug_struct("LabelSetEncoder")
745            .field("list", &self.list)
746            .finish()
747    }
748}
749
750impl<'a> LabelSetEncoder<'a> {
751    pub(crate) fn new(writer: TextBuf<'a>, list: &'a mut LabelList) -> Self {
752        Self { writer, list }
753    }
754
755    pub fn encode_label(&mut self) -> LabelEncoder<'_> {
756        LabelEncoder {
757            writer: self.writer.reborrow(),
758            list: &mut *self.list,
759        }
760    }
761}
762
763pub(crate) struct LabelEncoder<'a> {
764    writer: TextBuf<'a>,
765    list: &'a mut LabelList,
766}
767
768impl std::fmt::Debug for LabelEncoder<'_> {
769    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
770        f.debug_struct("LabelEncoder")
771            .field("list", &self.list)
772            .finish()
773    }
774}
775
776impl LabelEncoder<'_> {
777    pub fn encode_label_key(&mut self) -> Result<LabelKeyEncoder<'_>, std::fmt::Error> {
778        // Only mark the list as written once a key is actually encoded, so a
779        // label which never writes a key leaves no stray separator behind.
780        let separator = if self.list.written {
781            ","
782        } else {
783            self.list.open
784        };
785        self.list.written = true;
786        if !separator.is_empty() {
787            self.writer.write_str(separator)?;
788        }
789        Ok(LabelKeyEncoder {
790            writer: self.writer.reborrow(),
791        })
792    }
793}
794
795pub(crate) struct LabelKeyEncoder<'a> {
796    writer: TextBuf<'a>,
797}
798
799impl std::fmt::Debug for LabelKeyEncoder<'_> {
800    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
801        f.debug_struct("LabelKeyEncoder").finish()
802    }
803}
804
805impl<'a> LabelKeyEncoder<'a> {
806    pub fn encode_label_value(mut self) -> Result<LabelValueEncoder<'a>, std::fmt::Error> {
807        self.writer.write_str("=\"")?;
808        Ok(LabelValueEncoder {
809            writer: self.writer,
810        })
811    }
812}
813
814impl std::fmt::Write for LabelKeyEncoder<'_> {
815    fn write_str(&mut self, s: &str) -> std::fmt::Result {
816        self.writer.write_str(s)
817    }
818}
819
820pub(crate) struct LabelValueEncoder<'a> {
821    writer: TextBuf<'a>,
822}
823
824impl std::fmt::Debug for LabelValueEncoder<'_> {
825    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
826        f.debug_struct("LabelValueEncoder").finish()
827    }
828}
829
830impl LabelValueEncoder<'_> {
831    pub fn finish(mut self) -> Result<(), std::fmt::Error> {
832        self.writer.write_str("\"")
833    }
834
835    pub(crate) fn write_str_unescaped(&mut self, s: &str) -> Result<(), std::fmt::Error> {
836        self.writer.write_str(s)
837    }
838
839    #[cold]
840    fn write_str_escaped(&mut self, s: &str) -> Result<(), std::fmt::Error> {
841        let mut last = 0;
842        for (index, byte) in s.bytes().enumerate() {
843            let escaped = match byte {
844                b'\\' => "\\\\",
845                b'"' => "\\\"",
846                b'\n' => "\\n",
847                _ => continue,
848            };
849            self.writer.write_str(&s[last..index])?;
850            self.writer.write_str(escaped)?;
851            last = index + 1;
852        }
853        self.writer.write_str(&s[last..])
854    }
855}
856
857impl std::fmt::Write for LabelValueEncoder<'_> {
858    fn write_str(&mut self, s: &str) -> std::fmt::Result {
859        let needs_escaping = s.bytes().fold(false, |found, byte| {
860            found | matches!(byte, b'\\' | b'"' | b'\n')
861        });
862        if needs_escaping {
863            self.write_str_escaped(s)
864        } else {
865            self.write_str_unescaped(s)
866        }
867    }
868}
869
870#[cfg(test)]
871mod tests {
872    use super::*;
873    use crate::metrics::exemplar::HistogramWithExemplars;
874    use crate::metrics::family::Family;
875    use crate::metrics::gauge::Gauge;
876    use crate::metrics::histogram::{exponential_buckets, Histogram, NativeHistogramConfig};
877    use crate::metrics::info::Info;
878    use crate::metrics::{counter::Counter, exemplar::CounterWithExemplar};
879    use pyo3::{prelude::*, types::PyModule};
880    use quickcheck::QuickCheck;
881    use std::borrow::Cow;
882    use std::fmt::Error;
883    use std::sync::atomic::{AtomicI32, AtomicU32};
884    use std::time::{SystemTime, UNIX_EPOCH};
885
886    #[test]
887    fn text_buf_never_reallocates() {
888        let mut buf = TextBuf::new_buffer();
889        let capacity = buf.capacity();
890        let mut sink = String::new();
891
892        let writes = [
893            "a".repeat(FLUSH_THRESHOLD - 1),
894            // Worst case: `FLUSH_THRESHOLD - 1` bytes pending, then a write of
895            // exactly `FLUSH_THRESHOLD` bytes stays on the buffered path.
896            "b".repeat(FLUSH_THRESHOLD),
897            "c".to_owned(),
898            "d".repeat(FLUSH_THRESHOLD - 1),
899            // Oversized writes bypass the buffer.
900            "e".repeat(3 * FLUSH_THRESHOLD),
901            "f".repeat(FLUSH_THRESHOLD - 1),
902            "g".repeat(FLUSH_THRESHOLD),
903        ];
904
905        let mut text_buf = TextBuf::new(&mut buf, &mut sink);
906        for write in &writes {
907            text_buf.write_str(write).unwrap();
908            assert_eq!(capacity, text_buf.buf.capacity());
909        }
910
911        sink.push_str(&buf);
912        assert_eq!(writes.concat(), sink);
913    }
914
915    #[test]
916    fn label_values_escape_special_characters() {
917        let encoded = TextBuf::encode_to_string(|mut buf| {
918            let mut list = LabelList::new("");
919            let mut label_set_encoder = LabelSetEncoder::new(buf.reborrow(), &mut list);
920            let mut label_encoder = label_set_encoder.encode_label();
921            let mut key_encoder = label_encoder.encode_label_key()?;
922            key_encoder.write_str("label")?;
923            let mut value_encoder = key_encoder.encode_label_value()?;
924            value_encoder.write_str("plain \\ quoted \" line\ncarriage\r unicode λ")?;
925            value_encoder.finish()
926        })
927        .unwrap();
928
929        assert_eq!(
930            concat!(
931                r#"label="plain \\ quoted \" line\ncarriage"#,
932                "\r",
933                r#" unicode λ""#
934            ),
935            encoded
936        );
937    }
938
939    #[test]
940    fn label_value_escaping_matches_reference() {
941        fn reference(s: &str) -> String {
942            let mut escaped = String::new();
943            for character in s.chars() {
944                match character {
945                    '\\' => escaped.push_str("\\\\"),
946                    '"' => escaped.push_str("\\\""),
947                    '\n' => escaped.push_str("\\n"),
948                    _ => escaped.push(character),
949                }
950            }
951            escaped
952        }
953
954        fn encode(value: &str) -> String {
955            TextBuf::encode_to_string(|writer| LabelValueEncoder { writer }.write_str(value))
956                .unwrap()
957        }
958
959        fn prop(value: String) -> bool {
960            if encode(&value) != reference(&value) {
961                return false;
962            }
963
964            // Guarantee that QuickCheck exercises a newline without another special
965            // byte that could independently select the escaping path.
966            let newline_only = format!("{}\n", value.replace(['\\', '"', '\n'], ""));
967            encode(&newline_only) == reference(&newline_only)
968        }
969
970        QuickCheck::new()
971            .tests(1_000)
972            .quickcheck(prop as fn(String) -> bool);
973    }
974
975    #[test]
976    fn oversized_label_value_is_encoded() {
977        let value = "v".repeat(3 * FLUSH_THRESHOLD);
978
979        let mut registry = Registry::default();
980        let family = Family::<Vec<(String, String)>, Counter>::default();
981        registry.register("requests", "Requests", family.clone());
982        family
983            .get_or_create(&vec![("label".to_string(), value.clone())])
984            .inc();
985
986        let mut encoded = String::new();
987        encode(&mut encoded, &registry).unwrap();
988
989        let expected = "# HELP requests Requests.\n".to_owned()
990            + "# TYPE requests counter\n"
991            + "requests_total{label=\""
992            + &value
993            + "\"} 1\n"
994            + "# EOF\n";
995        assert_eq!(expected, encoded);
996        parse_with_python_client(encoded);
997    }
998
999    #[test]
1000    fn escaped_label_values_produce_parseable_exposition() {
1001        let mut registry = Registry::default();
1002        let family = Family::<Vec<(String, String)>, Counter>::default();
1003        registry.register("requests", "Requests", family.clone());
1004        family
1005            .get_or_create(&vec![(
1006                "client_version".to_string(),
1007                "a\"} evil{x=\"1\\line\nnext".to_string(),
1008            )])
1009            .inc();
1010
1011        let mut encoded = String::new();
1012        encode(&mut encoded, &registry).unwrap();
1013
1014        assert_eq!(
1015            concat!(
1016                "# HELP requests Requests.\n",
1017                "# TYPE requests counter\n",
1018                r#"requests_total{client_version="a\"} evil{x=\"1\\line\nnext"} 1"#,
1019                "\n# EOF\n"
1020            ),
1021            encoded
1022        );
1023        parse_with_python_client(encoded);
1024    }
1025
1026    #[test]
1027    fn encode_counter() {
1028        let counter: Counter = Counter::default();
1029        let mut registry = Registry::default();
1030        registry.register("my_counter", "My counter", counter);
1031
1032        let counter_f32 = Counter::<f32, AtomicU32>::default();
1033        registry.register("f32_counter", "Counter::<f32, AtomicU32>", counter_f32);
1034        let counter_u32 = Counter::<u32, AtomicU32>::default();
1035        registry.register("u32_counter", "Counter::<u32, AtomicU32>", counter_u32);
1036        let mut encoded = String::new();
1037
1038        encode(&mut encoded, &registry).unwrap();
1039
1040        parse_with_python_client(encoded);
1041    }
1042
1043    #[test]
1044    fn encode_counter_with_unit() {
1045        let mut registry = Registry::default();
1046        let counter: Counter = Counter::default();
1047        registry.register_with_unit("my_counter", "My counter", Unit::Seconds, counter);
1048
1049        let mut encoded = String::new();
1050        encode(&mut encoded, &registry).unwrap();
1051
1052        let expected = "# HELP my_counter_seconds My counter.\n".to_owned()
1053            + "# TYPE my_counter_seconds counter\n"
1054            + "# UNIT my_counter_seconds seconds\n"
1055            + "my_counter_seconds_total 0\n"
1056            + "# EOF\n";
1057        assert_eq!(expected, encoded);
1058
1059        parse_with_python_client(encoded);
1060    }
1061
1062    #[test]
1063    fn encode_counter_with_exemplar() {
1064        let now = SystemTime::now();
1065
1066        let mut registry = Registry::default();
1067
1068        let counter_with_exemplar: CounterWithExemplar<Vec<(String, u64)>> =
1069            CounterWithExemplar::default();
1070        registry.register_with_unit(
1071            "my_counter_with_exemplar",
1072            "My counter with exemplar",
1073            Unit::Seconds,
1074            counter_with_exemplar.clone(),
1075        );
1076
1077        counter_with_exemplar.inc_by(1, Some(vec![("user_id".to_string(), 42)]), None);
1078
1079        let mut encoded = String::new();
1080        encode(&mut encoded, &registry).unwrap();
1081
1082        let expected = "# HELP my_counter_with_exemplar_seconds My counter with exemplar.\n"
1083            .to_owned()
1084            + "# TYPE my_counter_with_exemplar_seconds counter\n"
1085            + "# UNIT my_counter_with_exemplar_seconds seconds\n"
1086            + "my_counter_with_exemplar_seconds_total 1 # {user_id=\"42\"} 1.0\n"
1087            + "# EOF\n";
1088        assert_eq!(expected, encoded);
1089
1090        parse_with_python_client(encoded);
1091
1092        counter_with_exemplar.inc_by(1, Some(vec![("user_id".to_string(), 99)]), Some(now));
1093
1094        let mut encoded = String::new();
1095        encode(&mut encoded, &registry).unwrap();
1096
1097        let expected = "# HELP my_counter_with_exemplar_seconds My counter with exemplar.\n"
1098            .to_owned()
1099            + "# TYPE my_counter_with_exemplar_seconds counter\n"
1100            + "# UNIT my_counter_with_exemplar_seconds seconds\n"
1101            + "my_counter_with_exemplar_seconds_total 2 # {user_id=\"99\"} 1.0 "
1102            + dtoa::Buffer::new().format(now.duration_since(UNIX_EPOCH).unwrap().as_secs_f64())
1103            + "\n"
1104            + "# EOF\n";
1105        assert_eq!(expected, encoded);
1106
1107        parse_with_python_client(encoded);
1108    }
1109
1110    #[test]
1111    fn encode_gauge() {
1112        let mut registry = Registry::default();
1113        let gauge: Gauge = Gauge::default();
1114        registry.register("my_gauge", "My gauge", gauge);
1115        let gauge = Gauge::<u32, AtomicU32>::default();
1116        registry.register("u32_gauge", "Gauge::<u32, AtomicU32>", gauge);
1117
1118        let gauge_f32 = Gauge::<f32, AtomicU32>::default();
1119        registry.register("f32_gauge", "Gauge::<f32, AtomicU32>", gauge_f32);
1120
1121        let gauge_i32 = Gauge::<i32, AtomicI32>::default();
1122        registry.register("i32_gauge", "Gauge::<i32, AtomicU32>", gauge_i32);
1123
1124        let mut encoded = String::new();
1125
1126        encode(&mut encoded, &registry).unwrap();
1127
1128        parse_with_python_client(encoded);
1129    }
1130
1131    #[test]
1132    fn encode_counter_family() {
1133        let mut registry = Registry::default();
1134        let family = Family::<Vec<(String, String)>, Counter>::default();
1135        registry.register("my_counter_family", "My counter family", family.clone());
1136
1137        family
1138            .get_or_create(&vec![
1139                ("method".to_string(), "GET".to_string()),
1140                ("status".to_string(), "200".to_string()),
1141            ])
1142            .inc();
1143
1144        let mut encoded = String::new();
1145
1146        encode(&mut encoded, &registry).unwrap();
1147
1148        parse_with_python_client(encoded);
1149    }
1150
1151    #[test]
1152    fn encode_counter_family_with_prefix_with_label() {
1153        let mut registry = Registry::default();
1154        let sub_registry = registry.sub_registry_with_prefix("my_prefix");
1155        let sub_sub_registry = sub_registry
1156            .sub_registry_with_label((Cow::Borrowed("my_key"), Cow::Borrowed("my_value")));
1157        let family = Family::<Vec<(String, String)>, Counter>::default();
1158        sub_sub_registry.register("my_counter_family", "My counter family", family.clone());
1159
1160        family
1161            .get_or_create(&vec![
1162                ("method".to_string(), "GET".to_string()),
1163                ("status".to_string(), "200".to_string()),
1164            ])
1165            .inc();
1166
1167        let mut encoded = String::new();
1168
1169        encode(&mut encoded, &registry).unwrap();
1170
1171        let expected = "# HELP my_prefix_my_counter_family My counter family.\n"
1172            .to_owned()
1173            + "# TYPE my_prefix_my_counter_family counter\n"
1174            + "my_prefix_my_counter_family_total{my_key=\"my_value\",method=\"GET\",status=\"200\"} 1\n"
1175            + "# EOF\n";
1176        assert_eq!(expected, encoded);
1177
1178        parse_with_python_client(encoded);
1179    }
1180
1181    #[test]
1182    fn encode_info() {
1183        let mut registry = Registry::default();
1184        let info = Info::new(vec![("os".to_string(), "GNU/linux".to_string())]);
1185        registry.register("my_info_metric", "My info metric", info);
1186
1187        let mut encoded = String::new();
1188        encode(&mut encoded, &registry).unwrap();
1189
1190        let expected = "# HELP my_info_metric My info metric.\n".to_owned()
1191            + "# TYPE my_info_metric info\n"
1192            + "my_info_metric_info{os=\"GNU/linux\"} 1\n"
1193            + "# EOF\n";
1194        assert_eq!(expected, encoded);
1195
1196        parse_with_python_client(encoded);
1197    }
1198
1199    #[test]
1200    fn encode_info_with_const_labels_and_empty_label_set() {
1201        let mut registry =
1202            Registry::with_labels(vec![(Cow::Borrowed("env"), Cow::Borrowed("prod"))].into_iter());
1203        let info = Info::new(Vec::<(String, String)>::new());
1204        registry.register("my_info_metric", "My info metric", info);
1205
1206        let mut encoded = String::new();
1207        encode(&mut encoded, &registry).unwrap();
1208
1209        let expected = "# HELP my_info_metric My info metric.\n".to_owned()
1210            + "# TYPE my_info_metric info\n"
1211            + "my_info_metric_info{env=\"prod\"} 1\n"
1212            + "# EOF\n";
1213        assert_eq!(expected, encoded);
1214
1215        parse_with_python_client(encoded);
1216    }
1217
1218    #[test]
1219    fn encode_labels_skipping_label_key() {
1220        /// Label which only encodes a key when present.
1221        #[derive(Clone, Debug, Hash, PartialEq, Eq)]
1222        struct OptionalLabel(Option<(&'static str, &'static str)>);
1223
1224        impl crate::encoding::EncodeLabel for OptionalLabel {
1225            fn encode(&self, encoder: crate::encoding::LabelEncoder) -> Result<(), Error> {
1226                match self.0 {
1227                    Some(label) => label.encode(encoder),
1228                    None => Ok(()),
1229                }
1230            }
1231        }
1232
1233        fn encode_info(
1234            const_labels: Vec<(Cow<'static, str>, Cow<'static, str>)>,
1235            labels: Vec<OptionalLabel>,
1236        ) -> String {
1237            let mut registry = Registry::with_labels(const_labels.into_iter());
1238            registry.register("my_info_metric", "My info metric", Info::new(labels));
1239            let mut encoded = String::new();
1240            encode(&mut encoded, &registry).unwrap();
1241            encoded
1242        }
1243
1244        fn expected(series: &str) -> String {
1245            "# HELP my_info_metric My info metric.\n".to_owned()
1246                + "# TYPE my_info_metric info\n"
1247                + series
1248                + "\n# EOF\n"
1249        }
1250
1251        let cases = [
1252            (vec![], vec![OptionalLabel(None)], "my_info_metric_info 1"),
1253            (
1254                vec![],
1255                vec![
1256                    OptionalLabel(None),
1257                    OptionalLabel(Some(("a", "1"))),
1258                    OptionalLabel(None),
1259                    OptionalLabel(Some(("b", "2"))),
1260                ],
1261                "my_info_metric_info{a=\"1\",b=\"2\"} 1",
1262            ),
1263            (
1264                vec![(Cow::Borrowed("env"), Cow::Borrowed("prod"))],
1265                vec![OptionalLabel(None)],
1266                "my_info_metric_info{env=\"prod\"} 1",
1267            ),
1268        ];
1269
1270        for (const_labels, labels, series) in cases {
1271            let encoded = encode_info(const_labels, labels);
1272            assert_eq!(expected(series), encoded);
1273            parse_with_python_client(encoded);
1274        }
1275    }
1276
1277    #[test]
1278    fn encode_histogram() {
1279        let mut registry = Registry::default();
1280        let histogram = Histogram::new(exponential_buckets(1.0, 2.0, 10));
1281        registry.register("my_histogram", "My histogram", histogram.clone());
1282        histogram.observe(1.0);
1283
1284        let mut encoded = String::new();
1285
1286        encode(&mut encoded, &registry).unwrap();
1287
1288        parse_with_python_client(encoded);
1289    }
1290
1291    #[test]
1292    fn encode_classic_and_native_histogram_as_classic_text() {
1293        let mut registry = Registry::default();
1294        let histogram = Histogram::new_classic_and_native(
1295            [1.0, 2.0],
1296            NativeHistogramConfig::with_bucket_factor(1.1),
1297        );
1298        registry.register("my_histogram", "My histogram", histogram.clone());
1299        histogram.observe(1.0);
1300
1301        let mut encoded = String::new();
1302        encode(&mut encoded, &registry).unwrap();
1303
1304        let expected = "# HELP my_histogram My histogram.\n".to_owned()
1305            + "# TYPE my_histogram histogram\n"
1306            + "my_histogram_sum 1.0\n"
1307            + "my_histogram_count 1\n"
1308            + "my_histogram_bucket{le=\"1.0\"} 1\n"
1309            + "my_histogram_bucket{le=\"2.0\"} 1\n"
1310            + "my_histogram_bucket{le=\"+Inf\"} 1\n"
1311            + "# EOF\n";
1312        assert_eq!(expected, encoded);
1313    }
1314
1315    #[test]
1316    fn encode_native_only_histogram_errors() {
1317        let mut registry = Registry::default();
1318        let histogram = Histogram::new_native(NativeHistogramConfig::with_schema(0));
1319        registry.register("my_histogram", "My histogram", histogram.clone());
1320        histogram.observe(1.0);
1321
1322        let mut encoded = String::new();
1323        assert!(encode(&mut encoded, &registry).is_err());
1324    }
1325
1326    #[test]
1327    fn encode_histogram_family() {
1328        let mut registry = Registry::default();
1329        let family =
1330            Family::new_with_constructor(|| Histogram::new(exponential_buckets(1.0, 2.0, 10)));
1331        registry.register("my_histogram", "My histogram", family.clone());
1332        family
1333            .get_or_create(&vec![
1334                ("method".to_string(), "GET".to_string()),
1335                ("status".to_string(), "200".to_string()),
1336            ])
1337            .observe(1.0);
1338
1339        let mut encoded = String::new();
1340
1341        encode(&mut encoded, &registry).unwrap();
1342
1343        parse_with_python_client(encoded);
1344    }
1345
1346    #[test]
1347    fn encode_histogram_family_with_empty_struct_family_labels() {
1348        let mut registry = Registry::default();
1349        let family =
1350            Family::new_with_constructor(|| Histogram::new(exponential_buckets(1.0, 2.0, 10)));
1351        registry.register("my_histogram", "My histogram", family.clone());
1352
1353        #[derive(Eq, PartialEq, Hash, Debug, Clone)]
1354        struct EmptyLabels {}
1355
1356        impl EncodeLabelSet for EmptyLabels {
1357            fn encode(&self, _encoder: &mut crate::encoding::LabelSetEncoder) -> Result<(), Error> {
1358                Ok(())
1359            }
1360        }
1361
1362        family.get_or_create(&EmptyLabels {}).observe(1.0);
1363
1364        let mut encoded = String::new();
1365
1366        encode(&mut encoded, &registry).unwrap();
1367
1368        parse_with_python_client(encoded);
1369    }
1370
1371    #[test]
1372    fn encode_histogram_with_exemplars() {
1373        let now = SystemTime::now();
1374
1375        let mut registry = Registry::default();
1376        let histogram = HistogramWithExemplars::new(exponential_buckets(1.0, 2.0, 10));
1377        registry.register("my_histogram", "My histogram", histogram.clone());
1378
1379        histogram.observe(1.0, Some([("user_id".to_string(), 42u64)]), Some(now));
1380        histogram.observe(2.0, Some([("user_id".to_string(), 99u64)]), None);
1381
1382        let mut encoded = String::new();
1383        encode(&mut encoded, &registry).unwrap();
1384
1385        let expected = "# HELP my_histogram My histogram.\n".to_owned()
1386            + "# TYPE my_histogram histogram\n"
1387            + "my_histogram_sum 3.0\n"
1388            + "my_histogram_count 2\n"
1389            + "my_histogram_bucket{le=\"1.0\"} 1 # {user_id=\"42\"} 1.0 "
1390            + dtoa::Buffer::new().format(now.duration_since(UNIX_EPOCH).unwrap().as_secs_f64())
1391            + "\n"
1392            + "my_histogram_bucket{le=\"2.0\"} 2 # {user_id=\"99\"} 2.0\n"
1393            + "my_histogram_bucket{le=\"4.0\"} 2\n"
1394            + "my_histogram_bucket{le=\"8.0\"} 2\n"
1395            + "my_histogram_bucket{le=\"16.0\"} 2\n"
1396            + "my_histogram_bucket{le=\"32.0\"} 2\n"
1397            + "my_histogram_bucket{le=\"64.0\"} 2\n"
1398            + "my_histogram_bucket{le=\"128.0\"} 2\n"
1399            + "my_histogram_bucket{le=\"256.0\"} 2\n"
1400            + "my_histogram_bucket{le=\"512.0\"} 2\n"
1401            + "my_histogram_bucket{le=\"+Inf\"} 2\n"
1402            + "# EOF\n";
1403        assert_eq!(expected, encoded);
1404
1405        parse_with_python_client(encoded);
1406    }
1407
1408    #[test]
1409    fn sub_registry_with_prefix_and_label() {
1410        let top_level_metric_name = "my_top_level_metric";
1411        let mut registry = Registry::default();
1412        let counter: Counter = Counter::default();
1413        registry.register(top_level_metric_name, "some help", counter.clone());
1414
1415        let prefix_1 = "prefix_1";
1416        let prefix_1_metric_name = "my_prefix_1_metric";
1417        let sub_registry = registry.sub_registry_with_prefix(prefix_1);
1418        sub_registry.register(prefix_1_metric_name, "some help", counter.clone());
1419
1420        let prefix_1_1 = "prefix_1_1";
1421        let prefix_1_1_metric_name = "my_prefix_1_1_metric";
1422        let sub_sub_registry = sub_registry.sub_registry_with_prefix(prefix_1_1);
1423        sub_sub_registry.register(prefix_1_1_metric_name, "some help", counter.clone());
1424
1425        let label_1_2 = (Cow::Borrowed("registry"), Cow::Borrowed("1_2"));
1426        let prefix_1_2_metric_name = "my_prefix_1_2_metric";
1427        let sub_sub_registry = sub_registry.sub_registry_with_label(label_1_2.clone());
1428        sub_sub_registry.register(prefix_1_2_metric_name, "some help", counter.clone());
1429
1430        let labels_1_3 = vec![
1431            (Cow::Borrowed("label_1_3_1"), Cow::Borrowed("value_1_3_1")),
1432            (Cow::Borrowed("label_1_3_2"), Cow::Borrowed("value_1_3_2")),
1433        ];
1434        let prefix_1_3_metric_name = "my_prefix_1_3_metric";
1435        let sub_sub_registry =
1436            sub_registry.sub_registry_with_labels(labels_1_3.clone().into_iter());
1437        sub_sub_registry.register(prefix_1_3_metric_name, "some help", counter.clone());
1438
1439        let prefix_1_3_1 = "prefix_1_3_1";
1440        let prefix_1_3_1_metric_name = "my_prefix_1_3_1_metric";
1441        let sub_sub_sub_registry = sub_sub_registry.sub_registry_with_prefix(prefix_1_3_1);
1442        sub_sub_sub_registry.register(prefix_1_3_1_metric_name, "some help", counter.clone());
1443
1444        let prefix_2 = "prefix_2";
1445        let _ = registry.sub_registry_with_prefix(prefix_2);
1446
1447        let prefix_3 = "prefix_3";
1448        let prefix_3_metric_name = "my_prefix_3_metric";
1449        let sub_registry = registry.sub_registry_with_prefix(prefix_3);
1450        sub_registry.register(prefix_3_metric_name, "some help", counter);
1451
1452        let mut encoded = String::new();
1453        encode(&mut encoded, &registry).unwrap();
1454
1455        let expected = "# HELP my_top_level_metric some help.\n".to_owned()
1456            + "# TYPE my_top_level_metric counter\n"
1457            + "my_top_level_metric_total 0\n"
1458            + "# HELP prefix_1_my_prefix_1_metric some help.\n"
1459            + "# TYPE prefix_1_my_prefix_1_metric counter\n"
1460            + "prefix_1_my_prefix_1_metric_total 0\n"
1461            + "# HELP prefix_1_prefix_1_1_my_prefix_1_1_metric some help.\n"
1462            + "# TYPE prefix_1_prefix_1_1_my_prefix_1_1_metric counter\n"
1463            + "prefix_1_prefix_1_1_my_prefix_1_1_metric_total 0\n"
1464            + "# HELP prefix_1_my_prefix_1_2_metric some help.\n"
1465            + "# TYPE prefix_1_my_prefix_1_2_metric counter\n"
1466            + "prefix_1_my_prefix_1_2_metric_total{registry=\"1_2\"} 0\n"
1467            + "# HELP prefix_1_my_prefix_1_3_metric some help.\n"
1468            + "# TYPE prefix_1_my_prefix_1_3_metric counter\n"
1469            + "prefix_1_my_prefix_1_3_metric_total{label_1_3_1=\"value_1_3_1\",label_1_3_2=\"value_1_3_2\"} 0\n"
1470            + "# HELP prefix_1_prefix_1_3_1_my_prefix_1_3_1_metric some help.\n"
1471            + "# TYPE prefix_1_prefix_1_3_1_my_prefix_1_3_1_metric counter\n"
1472            + "prefix_1_prefix_1_3_1_my_prefix_1_3_1_metric_total{label_1_3_1=\"value_1_3_1\",label_1_3_2=\"value_1_3_2\"} 0\n"
1473            + "# HELP prefix_3_my_prefix_3_metric some help.\n"
1474            + "# TYPE prefix_3_my_prefix_3_metric counter\n"
1475            + "prefix_3_my_prefix_3_metric_total 0\n"
1476            + "# EOF\n";
1477        assert_eq!(expected, encoded);
1478
1479        parse_with_python_client(encoded);
1480    }
1481
1482    #[test]
1483    fn sub_registry_collector() {
1484        use crate::encoding::EncodeMetric;
1485
1486        #[derive(Debug)]
1487        struct Collector {
1488            name: String,
1489        }
1490
1491        impl Collector {
1492            fn new(name: impl Into<String>) -> Self {
1493                Self { name: name.into() }
1494            }
1495        }
1496
1497        impl crate::collector::Collector for Collector {
1498            fn encode(
1499                &self,
1500                mut encoder: crate::encoding::DescriptorEncoder,
1501            ) -> Result<(), std::fmt::Error> {
1502                let counter = crate::metrics::counter::ConstCounter::new(42u64);
1503                let metric_encoder = encoder.encode_descriptor(
1504                    &self.name,
1505                    "some help",
1506                    None,
1507                    counter.metric_type(),
1508                )?;
1509                counter.encode(metric_encoder)?;
1510                Ok(())
1511            }
1512        }
1513
1514        let mut registry = Registry::default();
1515        registry.register_collector(Box::new(Collector::new("top_level")));
1516
1517        let sub_registry = registry.sub_registry_with_prefix("prefix_1");
1518        sub_registry.register_collector(Box::new(Collector::new("sub_level")));
1519
1520        let sub_sub_registry = sub_registry.sub_registry_with_prefix("prefix_1_2");
1521        sub_sub_registry.register_collector(Box::new(Collector::new("sub_sub_level")));
1522
1523        let mut encoded = String::new();
1524        encode(&mut encoded, &registry).unwrap();
1525
1526        let expected = "# HELP top_level some help\n".to_owned()
1527            + "# TYPE top_level counter\n"
1528            + "top_level_total 42\n"
1529            + "# HELP prefix_1_sub_level some help\n"
1530            + "# TYPE prefix_1_sub_level counter\n"
1531            + "prefix_1_sub_level_total 42\n"
1532            + "# HELP prefix_1_prefix_1_2_sub_sub_level some help\n"
1533            + "# TYPE prefix_1_prefix_1_2_sub_sub_level counter\n"
1534            + "prefix_1_prefix_1_2_sub_sub_level_total 42\n"
1535            + "# EOF\n";
1536        assert_eq!(expected, encoded);
1537
1538        parse_with_python_client(encoded);
1539    }
1540
1541    #[test]
1542    fn label_sets_can_be_composed() {
1543        #[derive(Clone, Debug, Eq, Hash, PartialEq)]
1544        struct Color(&'static str);
1545        impl EncodeLabelSet for Color {
1546            fn encode(
1547                &self,
1548                encoder: &mut crate::encoding::LabelSetEncoder,
1549            ) -> Result<(), std::fmt::Error> {
1550                use crate::encoding::EncodeLabel;
1551                let Self(color) = *self;
1552                let labels = ("color", color);
1553                let encoder = encoder.encode_label();
1554                labels.encode(encoder)
1555            }
1556        }
1557
1558        #[derive(Clone, Debug, Eq, Hash, PartialEq)]
1559        struct Size(&'static str);
1560        impl EncodeLabelSet for Size {
1561            fn encode(
1562                &self,
1563                encoder: &mut crate::encoding::LabelSetEncoder,
1564            ) -> Result<(), std::fmt::Error> {
1565                use crate::encoding::EncodeLabel;
1566                let Self(size) = *self;
1567                let labels = ("size", size);
1568                let encoder = encoder.encode_label();
1569                labels.encode(encoder)
1570            }
1571        }
1572
1573        type Labels = (Color, Size);
1574
1575        let mut registry = Registry::default();
1576        let family = Family::<Labels, Counter>::default();
1577        registry.register("items", "Example metric", family.clone());
1578
1579        let labels = (Color("red"), Size("large"));
1580        let counter = family.get_or_create(&labels);
1581        counter.inc();
1582
1583        let mut encoded = String::new();
1584        encode(&mut encoded, &registry).unwrap();
1585
1586        let expected = "# HELP items Example metric.\n\
1587                        # TYPE items counter\n\
1588                        items_total{color=\"red\",size=\"large\"} 1\n\
1589                        # EOF\n";
1590        assert_eq!(expected, encoded);
1591
1592        parse_with_python_client(encoded);
1593    }
1594
1595    #[test]
1596    fn encode_registry_eof() {
1597        let mut orders_registry = Registry::default();
1598
1599        let total_orders: Counter<u64> = Default::default();
1600        orders_registry.register("orders", "Total orders received", total_orders.clone());
1601        total_orders.inc();
1602
1603        let processing_times = Histogram::new(exponential_buckets(1.0, 2.0, 10));
1604        orders_registry.register_with_unit(
1605            "processing_times",
1606            "Order times",
1607            Unit::Seconds,
1608            processing_times.clone(),
1609        );
1610        processing_times.observe(2.4);
1611
1612        let mut user_auth_registry = Registry::default();
1613
1614        let successful_logins: Counter<u64> = Default::default();
1615        user_auth_registry.register(
1616            "successful_logins",
1617            "Total successful logins",
1618            successful_logins.clone(),
1619        );
1620        successful_logins.inc();
1621
1622        let failed_logins: Counter<u64> = Default::default();
1623        user_auth_registry.register(
1624            "failed_logins",
1625            "Total failed logins",
1626            failed_logins.clone(),
1627        );
1628
1629        let mut response = String::new();
1630
1631        encode_registry(&mut response, &orders_registry).unwrap();
1632        assert_eq!(&response[response.len() - 20..], "bucket{le=\"+Inf\"} 1\n");
1633
1634        encode_registry(&mut response, &user_auth_registry).unwrap();
1635        assert_eq!(&response[response.len() - 20..], "iled_logins_total 0\n");
1636
1637        encode_eof(&mut response).unwrap();
1638        assert_eq!(&response[response.len() - 20..], "ogins_total 0\n# EOF\n");
1639    }
1640
1641    fn parse_with_python_client(input: String) {
1642        pyo3::Python::initialize();
1643
1644        println!("{input:?}");
1645        Python::attach(|py| {
1646            let parser = PyModule::from_code(
1647                py,
1648                c"
1649from prometheus_client.openmetrics.parser import text_string_to_metric_families
1650
1651def parse(input):
1652    families = text_string_to_metric_families(input)
1653    list(families)
1654",
1655                c"parser.py",
1656                c"parser",
1657            )
1658            .map_err(|e| e.to_string())
1659            .unwrap();
1660
1661            parser
1662                .getattr("parse")
1663                .expect("`parse` to exist.")
1664                .call1((input.clone(),))
1665                .map_err(|e| e.to_string())
1666                .unwrap();
1667        })
1668    }
1669
1670    #[test]
1671    fn encode_flushes_large_output_in_chunks() {
1672        /// Writer recording each `write_str` call separately.
1673        #[derive(Default)]
1674        struct ChunkRecorder(Vec<String>);
1675
1676        impl Write for ChunkRecorder {
1677            fn write_str(&mut self, s: &str) -> std::fmt::Result {
1678                self.0.push(s.to_owned());
1679                Ok(())
1680            }
1681        }
1682
1683        let mut registry = Registry::default();
1684        for i in 0..200 {
1685            let family = Family::<Vec<(String, String)>, Counter>::default();
1686            registry.register(format!("my_counter_{i}"), "My counter", family.clone());
1687            for j in 0..10 {
1688                family
1689                    .get_or_create(&vec![("label".to_string(), j.to_string())])
1690                    .inc();
1691            }
1692        }
1693
1694        let mut expected = String::new();
1695        encode(&mut expected, &registry).unwrap();
1696        assert!(expected.len() > 2 * FLUSH_THRESHOLD);
1697
1698        let mut recorder = ChunkRecorder::default();
1699        encode(&mut recorder, &registry).unwrap();
1700
1701        // The output is flushed in multiple chunks of at least
1702        // `FLUSH_THRESHOLD` bytes (except for the trailing remainder and the
1703        // EOF marker), and the concatenation matches.
1704        let (chunks, tail) = recorder.0.split_at(recorder.0.len() - 2);
1705        assert!(chunks.len() > 1);
1706        assert!(chunks.iter().all(|chunk| chunk.len() >= FLUSH_THRESHOLD));
1707        assert!(tail[0].len() < FLUSH_THRESHOLD);
1708        assert_eq!(tail[1], "# EOF\n");
1709        assert_eq!(recorder.0.concat(), expected);
1710
1711        parse_with_python_client(expected);
1712    }
1713
1714    #[test]
1715    fn encode_omit_empty() {
1716        let mut registry = Registry::default();
1717        let counter1: Family<Vec<(&'static str, &'static str)>, Counter> = Default::default();
1718        let counter2: Family<Vec<(&'static str, &'static str)>, Counter> = Default::default();
1719        let counter3: Family<Vec<(&'static str, &'static str)>, Counter> = Default::default();
1720
1721        registry.register("counter1", "First counter", counter1.clone());
1722        registry.register("counter2", "Second counter", counter2.clone());
1723        registry.register("counter3", "Third counter", counter3.clone());
1724
1725        counter1.get_or_create(&vec![("label", "value")]).inc();
1726
1727        let mut encoded = String::new();
1728        encode(&mut encoded, &registry).unwrap();
1729
1730        let expected = "# HELP counter1 First counter.\n".to_owned()
1731            + "# TYPE counter1 counter\n"
1732            + "counter1_total{label=\"value\"} 1\n"
1733            + "# EOF\n";
1734        assert_eq!(expected, encoded);
1735
1736        counter2.get_or_create(&vec![("label", "value")]).inc();
1737
1738        let mut encoded = String::new();
1739        encode(&mut encoded, &registry).unwrap();
1740
1741        let expected = "# HELP counter1 First counter.\n".to_owned()
1742            + "# TYPE counter1 counter\n"
1743            + "counter1_total{label=\"value\"} 1\n"
1744            + "# HELP counter2 Second counter.\n"
1745            + "# TYPE counter2 counter\n"
1746            + "counter2_total{label=\"value\"} 1\n"
1747            + "# EOF\n";
1748        assert_eq!(expected, encoded);
1749    }
1750}