prometheus_client/metrics/
family.rs

1//! Module implementing an Open Metrics metric family.
2//!
3//! See [`Family`] for details.
4
5use crate::encoding::{EncodeLabelSet, EncodeMetric, MetricEncoder};
6
7use super::{MetricType, TypedMetric};
8use parking_lot::{MappedRwLockReadGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};
9use std::collections::HashMap;
10use std::sync::Arc;
11
12/// Representation of the OpenMetrics *MetricFamily* data type.
13///
14/// A [`Family`] is a set of metrics with the same name, help text and
15/// type, differentiated by their label values thus spanning a multidimensional
16/// space.
17///
18/// # Generic over the label set
19///
20/// A [`Family`] is generic over the label type. For convenience one might
21/// choose a `Vec<(String, String)>`, for performance and/or type safety one might
22/// define a custom type.
23///
24/// ## Examples
25///
26/// ### [`Family`] with `Vec<(String, String)>` for convenience
27///
28/// ```
29/// # use prometheus_client::encoding::text::encode;
30/// # use prometheus_client::metrics::counter::{Atomic, Counter};
31/// # use prometheus_client::metrics::family::Family;
32/// # use prometheus_client::registry::Registry;
33/// #
34/// # let mut registry = Registry::default();
35/// let family = Family::<Vec<(String, String)>, Counter>::default();
36/// # registry.register(
37/// #   "my_counter",
38/// #   "This is my counter",
39/// #   family.clone(),
40/// # );
41///
42/// // Record a single HTTP GET request.
43/// family.get_or_create(&vec![("method".to_owned(), "GET".to_owned())]).inc();
44///
45/// # // Encode all metrics in the registry in the text format.
46/// # let mut buffer = String::new();
47/// # encode(&mut buffer, &registry).unwrap();
48/// #
49/// # let expected = "# HELP my_counter This is my counter.\n".to_owned() +
50/// #                "# TYPE my_counter counter\n" +
51/// #                "my_counter_total{method=\"GET\"} 1\n" +
52/// #                "# EOF\n";
53/// # assert_eq!(expected, buffer);
54/// ```
55///
56/// ### [`Family`] with custom type for performance and/or type safety
57///
58/// Using `EncodeLabelSet` and `EncodeLabelValue` derive macro to generate
59/// [`EncodeLabelSet`] for `struct`s and
60/// [`EncodeLabelValue`](crate::encoding::EncodeLabelValue) for `enum`s.
61///
62/// ```
63/// # use prometheus_client::encoding::{EncodeLabelSet, EncodeLabelValue};
64/// # use prometheus_client::encoding::text::encode;
65/// # use prometheus_client::metrics::counter::{Atomic, Counter};
66/// # use prometheus_client::metrics::family::Family;
67/// # use prometheus_client::registry::Registry;
68/// # use std::io::Write;
69/// #
70/// # let mut registry = Registry::default();
71/// #[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
72/// struct Labels {
73///   method: Method,
74/// };
75///
76/// #[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelValue)]
77/// enum Method {
78///   GET,
79///   PUT,
80/// };
81///
82/// let family = Family::<Labels, Counter>::default();
83/// # registry.register(
84/// #   "my_counter",
85/// #   "This is my counter",
86/// #   family.clone(),
87/// # );
88///
89/// // Record a single HTTP GET request.
90/// family.get_or_create(&Labels { method: Method::GET }).inc();
91/// #
92/// # // Encode all metrics in the registry in the text format.
93/// # let mut buffer = String::new();
94/// # encode(&mut buffer, &registry).unwrap();
95/// #
96/// # let expected = "# HELP my_counter This is my counter.\n".to_owned() +
97/// #                "# TYPE my_counter counter\n" +
98/// #                "my_counter_total{method=\"GET\"} 1\n" +
99/// #                "# EOF\n";
100/// # assert_eq!(expected, buffer);
101/// ```
102// TODO: Consider exposing hash algorithm.
103pub struct Family<S, M, C = fn() -> M> {
104    metrics: Arc<RwLock<HashMap<S, M>>>,
105    /// Function that when called constructs a new metric.
106    ///
107    /// For most metric types this would simply be its [`Default`]
108    /// implementation set through [`Family::default`]. For metric types that
109    /// need custom construction logic like
110    /// [`Histogram`](crate::metrics::histogram::Histogram) in order to set
111    /// specific buckets, a custom constructor is set via
112    /// [`Family::new_with_constructor`].
113    constructor: C,
114}
115
116impl<S: std::fmt::Debug, M: std::fmt::Debug, C> std::fmt::Debug for Family<S, M, C> {
117    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118        f.debug_struct("Family")
119            .field("metrics", &self.metrics)
120            .finish()
121    }
122}
123
124/// A constructor for creating new metrics in a [`Family`] when calling
125/// [`Family::get_or_create`]. Such constructor is provided via
126/// [`Family::new_with_constructor`].
127///
128/// This is mostly used when creating histograms using constructors that need to
129/// capture variables.
130///
131/// ```
132/// # use prometheus_client::metrics::family::{Family, MetricConstructor};
133/// # use prometheus_client::metrics::histogram::Histogram;
134/// struct CustomBuilder {
135///     buckets: Vec<f64>,
136/// }
137///
138/// impl MetricConstructor<Histogram> for CustomBuilder {
139///     fn new_metric(&self) -> Histogram {
140///         // When a new histogram is created, this function will be called.
141///         Histogram::new(self.buckets.iter().cloned())
142///     }
143/// }
144///
145/// let custom_builder = CustomBuilder { buckets: vec![0.0, 10.0, 100.0] };
146/// let metric = Family::<(), Histogram, CustomBuilder>::new_with_constructor(custom_builder);
147/// ```
148pub trait MetricConstructor<M> {
149    /// Create a new instance of the metric type.
150    fn new_metric(&self) -> M;
151}
152
153/// In cases in which the explicit type of the metric is not required, it is
154/// posible to directly provide a closure even if it captures variables.
155///
156/// ```
157/// # use prometheus_client::metrics::family::{Family};
158/// # use prometheus_client::metrics::histogram::Histogram;
159/// let custom_buckets = [0.0, 10.0, 100.0];
160/// let metric = Family::<(), Histogram, _>::new_with_constructor(|| {
161///     Histogram::new(custom_buckets.into_iter())
162/// });
163/// # metric.get_or_create(&());
164/// ```
165impl<M, F: Fn() -> M> MetricConstructor<M> for F {
166    fn new_metric(&self) -> M {
167        self()
168    }
169}
170
171impl<S: Clone + std::hash::Hash + Eq, M: Default> Default for Family<S, M> {
172    fn default() -> Self {
173        Self {
174            metrics: Arc::new(RwLock::new(Default::default())),
175            constructor: M::default,
176        }
177    }
178}
179
180impl<S: Clone + std::hash::Hash + Eq, M, C> Family<S, M, C> {
181    /// Create a metric family using a custom constructor to construct new
182    /// metrics.
183    ///
184    /// When calling [`Family::get_or_create`] a [`Family`] needs to be able to
185    /// construct a new metric in case none exists for the given label set. In
186    /// most cases, e.g. for [`Counter`](crate::metrics::counter::Counter)
187    /// [`Family`] can just use the [`Default::default`] implementation for the
188    /// metric type. For metric types such as
189    /// [`Histogram`](crate::metrics::histogram::Histogram) one might want
190    /// [`Family`] to construct a
191    /// [`Histogram`](crate::metrics::histogram::Histogram) with custom buckets
192    /// (see example below). For such case one can use this method. For more
193    /// involved constructors see [`MetricConstructor`].
194    ///
195    /// ```
196    /// # use prometheus_client::metrics::family::Family;
197    /// # use prometheus_client::metrics::histogram::{exponential_buckets, Histogram};
198    /// Family::<Vec<(String, String)>, Histogram>::new_with_constructor(|| {
199    ///     Histogram::new(exponential_buckets(1.0, 2.0, 10))
200    /// });
201    /// ```
202    pub fn new_with_constructor(constructor: C) -> Self {
203        Self {
204            metrics: Arc::new(RwLock::new(Default::default())),
205            constructor,
206        }
207    }
208}
209
210impl<S: Clone + std::hash::Hash + Eq, M, C: MetricConstructor<M>> Family<S, M, C> {
211    /// Access a metric with the given label set, creating it if one does not
212    /// yet exist.
213    ///
214    /// ```
215    /// # use prometheus_client::metrics::counter::{Atomic, Counter};
216    /// # use prometheus_client::metrics::family::Family;
217    /// #
218    /// let family = Family::<Vec<(String, String)>, Counter>::default();
219    ///
220    /// // Will create the metric with label `method="GET"` on first call and
221    /// // return a reference.
222    /// family.get_or_create(&vec![("method".to_owned(), "GET".to_owned())]).inc();
223    ///
224    /// // Will return a reference to the existing metric on all subsequent
225    /// // calls.
226    /// family.get_or_create(&vec![("method".to_owned(), "GET".to_owned())]).inc();
227    /// ```
228    pub fn get_or_create(&self, label_set: &S) -> MappedRwLockReadGuard<M> {
229        if let Some(metric) = self.get(label_set) {
230            return metric;
231        }
232
233        let mut write_guard = self.metrics.write();
234
235        write_guard
236            .entry(label_set.clone())
237            .or_insert_with(|| self.constructor.new_metric());
238
239        let read_guard = RwLockWriteGuard::downgrade(write_guard);
240
241        RwLockReadGuard::map(read_guard, |metrics| {
242            metrics
243                .get(label_set)
244                .expect("Metric to exist after creating it.")
245        })
246    }
247
248    /// Access a metric with the given label set, returning None if one
249    /// does not yet exist.
250    ///
251    /// ```
252    /// # use prometheus_client::metrics::counter::{Atomic, Counter};
253    /// # use prometheus_client::metrics::family::Family;
254    /// #
255    /// let family = Family::<Vec<(String, String)>, Counter>::default();
256    ///
257    /// if let Some(metric) = family.get(&vec![("method".to_owned(), "GET".to_owned())]) {
258    ///     metric.inc();
259    /// };
260    /// ```
261    pub fn get(&self, label_set: &S) -> Option<MappedRwLockReadGuard<M>> {
262        RwLockReadGuard::try_map(self.metrics.read(), |metrics| metrics.get(label_set)).ok()
263    }
264
265    /// Remove a label set from the metric family.
266    ///
267    /// Returns a bool indicating if a label set was removed or not.
268    ///
269    /// ```
270    /// # use prometheus_client::metrics::counter::{Atomic, Counter};
271    /// # use prometheus_client::metrics::family::Family;
272    /// #
273    /// let family = Family::<Vec<(String, String)>, Counter>::default();
274    ///
275    /// // Will create the metric with label `method="GET"` on first call and
276    /// // return a reference.
277    /// family.get_or_create(&vec![("method".to_owned(), "GET".to_owned())]).inc();
278    ///
279    /// // Will return `true`, indicating that the `method="GET"` label set was
280    /// // removed.
281    /// assert!(family.remove(&vec![("method".to_owned(), "GET".to_owned())]));
282    /// ```
283    pub fn remove(&self, label_set: &S) -> bool {
284        self.metrics.write().remove(label_set).is_some()
285    }
286
287    /// Clear all label sets from the metric family.
288    ///
289    /// ```
290    /// # use prometheus_client::metrics::counter::{Atomic, Counter};
291    /// # use prometheus_client::metrics::family::Family;
292    /// #
293    /// let family = Family::<Vec<(String, String)>, Counter>::default();
294    ///
295    /// // Will create the metric with label `method="GET"` on first call and
296    /// // return a reference.
297    /// family.get_or_create(&vec![("method".to_owned(), "GET".to_owned())]).inc();
298    ///
299    /// // Clear the family of all label sets.
300    /// family.clear();
301    /// ```
302    pub fn clear(&self) {
303        self.metrics.write().clear()
304    }
305
306    pub(crate) fn read(&self) -> RwLockReadGuard<HashMap<S, M>> {
307        self.metrics.read()
308    }
309}
310
311impl<S, M, C: Clone> Clone for Family<S, M, C> {
312    fn clone(&self) -> Self {
313        Family {
314            metrics: self.metrics.clone(),
315            constructor: self.constructor.clone(),
316        }
317    }
318}
319
320impl<S, M: TypedMetric, C> TypedMetric for Family<S, M, C> {
321    const TYPE: MetricType = <M as TypedMetric>::TYPE;
322}
323
324impl<S, M, C> EncodeMetric for Family<S, M, C>
325where
326    S: Clone + std::hash::Hash + Eq + EncodeLabelSet,
327    M: EncodeMetric + TypedMetric,
328    C: MetricConstructor<M>,
329{
330    fn encode(&self, mut encoder: MetricEncoder) -> Result<(), std::fmt::Error> {
331        let guard = self.read();
332        for (label_set, m) in guard.iter() {
333            let encoder = encoder.encode_family(label_set)?;
334            m.encode(encoder)?;
335        }
336        Ok(())
337    }
338
339    fn metric_type(&self) -> MetricType {
340        M::TYPE
341    }
342}
343
344#[cfg(test)]
345mod tests {
346    use super::*;
347    use crate::metrics::counter::Counter;
348    use crate::metrics::histogram::{exponential_buckets, Histogram};
349
350    #[test]
351    fn counter_family() {
352        let family = Family::<Vec<(String, String)>, Counter>::default();
353
354        family
355            .get_or_create(&vec![("method".to_string(), "GET".to_string())])
356            .inc();
357
358        assert_eq!(
359            1,
360            family
361                .get_or_create(&vec![("method".to_string(), "GET".to_string())])
362                .get()
363        );
364    }
365
366    #[test]
367    fn histogram_family() {
368        Family::<(), Histogram>::new_with_constructor(|| {
369            Histogram::new(exponential_buckets(1.0, 2.0, 10))
370        });
371    }
372
373    #[test]
374    fn histogram_family_with_struct_constructor() {
375        struct CustomBuilder {
376            custom_start: f64,
377        }
378        impl MetricConstructor<Histogram> for CustomBuilder {
379            fn new_metric(&self) -> Histogram {
380                Histogram::new(exponential_buckets(self.custom_start, 2.0, 10))
381            }
382        }
383
384        let custom_builder = CustomBuilder { custom_start: 1.0 };
385        Family::<(), Histogram, CustomBuilder>::new_with_constructor(custom_builder);
386    }
387
388    #[test]
389    fn counter_family_remove() {
390        let family = Family::<Vec<(String, String)>, Counter>::default();
391
392        family
393            .get_or_create(&vec![("method".to_string(), "GET".to_string())])
394            .inc();
395
396        assert_eq!(
397            1,
398            family
399                .get_or_create(&vec![("method".to_string(), "GET".to_string())])
400                .get()
401        );
402
403        family
404            .get_or_create(&vec![("method".to_string(), "POST".to_string())])
405            .inc_by(2);
406
407        assert_eq!(
408            2,
409            family
410                .get_or_create(&vec![("method".to_string(), "POST".to_string())])
411                .get()
412        );
413
414        // Attempt to remove it twice, showing it really was removed on the
415        // first attempt.
416        assert!(family.remove(&vec![("method".to_string(), "POST".to_string())]));
417        assert!(!family.remove(&vec![("method".to_string(), "POST".to_string())]));
418
419        // This should make a new POST label.
420        family
421            .get_or_create(&vec![("method".to_string(), "POST".to_string())])
422            .inc();
423
424        assert_eq!(
425            1,
426            family
427                .get_or_create(&vec![("method".to_string(), "POST".to_string())])
428                .get()
429        );
430
431        // GET label should have be untouched.
432        assert_eq!(
433            1,
434            family
435                .get_or_create(&vec![("method".to_string(), "GET".to_string())])
436                .get()
437        );
438    }
439
440    #[test]
441    fn counter_family_clear() {
442        let family = Family::<Vec<(String, String)>, Counter>::default();
443
444        // Create a label and check it.
445        family
446            .get_or_create(&vec![("method".to_string(), "GET".to_string())])
447            .inc();
448
449        assert_eq!(
450            1,
451            family
452                .get_or_create(&vec![("method".to_string(), "GET".to_string())])
453                .get()
454        );
455
456        // Clear it, then try recreating and checking it again.
457        family.clear();
458
459        family
460            .get_or_create(&vec![("method".to_string(), "GET".to_string())])
461            .inc();
462
463        assert_eq!(
464            1,
465            family
466                .get_or_create(&vec![("method".to_string(), "GET".to_string())])
467                .get()
468        );
469    }
470
471    #[test]
472    fn test_get() {
473        let family = Family::<Vec<(String, String)>, Counter>::default();
474
475        // Test getting a non-existent metric.
476        let non_existent = family.get(&vec![("method".to_string(), "GET".to_string())]);
477        assert!(non_existent.is_none());
478
479        // Create a metric.
480        family
481            .get_or_create(&vec![("method".to_string(), "GET".to_string())])
482            .inc();
483
484        // Test getting an existing metric.
485        let existing = family.get(&vec![("method".to_string(), "GET".to_string())]);
486        assert!(existing.is_some());
487        assert_eq!(existing.unwrap().get(), 1);
488
489        // Test getting a different non-existent metric.
490        let another_non_existent = family.get(&vec![("method".to_string(), "POST".to_string())]);
491        assert!(another_non_existent.is_none());
492
493        // Test modifying the metric through the returned reference.
494        if let Some(metric) = family.get(&vec![("method".to_string(), "GET".to_string())]) {
495            metric.inc();
496        }
497
498        // Verify the modification.
499        let modified = family.get(&vec![("method".to_string(), "GET".to_string())]);
500        assert_eq!(modified.unwrap().get(), 2);
501
502        // Test with a different label set type.
503        let string_family = Family::<String, Counter>::default();
504        string_family.get_or_create(&"test".to_string()).inc();
505
506        let string_metric = string_family.get(&"test".to_string());
507        assert!(string_metric.is_some());
508        assert_eq!(string_metric.unwrap().get(), 1);
509
510        let non_existent_string = string_family.get(&"non_existent".to_string());
511        assert!(non_existent_string.is_none());
512    }
513}