fastmetrics 0.7.1

OpenMetrics / Prometheus client library in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
//! A metric family is a collection of metrics with the same name but different label values.
//!
//! Each metric within a family has the same metadata, but has a unique set of label values.
//!
//! See [`Family`] for more details.

use std::{
    collections::{HashMap, hash_map::Entry},
    fmt::{self, Debug},
    hash::{BuildHasher, Hash},
    sync::Arc,
};

use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard};

use crate::{
    encoder::{EncodeLabelSet, EncodeMetric, MetricEncoder},
    error::Result,
    raw::{LabelSetSchema, MetricLabelSet, MetricType, TypedMetric},
};

type MetricFactory<LS, M> = dyn Fn(&LS) -> M + Send + Sync + 'static;

cfg_if::cfg_if! {
    if #[cfg(feature = "foldhash")] {
        type RandomState = foldhash::fast::RandomState;
    } else {
        type RandomState = std::hash::RandomState;
    }
}

/// A collection of metrics that share the same name but have different label values.
///
/// The type parameters are:
/// - `LS`: The label set type that uniquely identifies a metric within the family
/// - `M`: The specific metric type (e.g., Counter, Gauge) stored in this family
/// - `S`: The hash algorithm of internal HashMap type.
///
/// A metric family maintains a map of label sets to metric instances. Each combination
/// of label values maps to a unique metric instance. This allows tracking metrics
/// across different dimensions (e.g., request counts by method and status code).
///
/// # Example
///
/// A counter metric family named "http_requests_total" might contain multiple individual counters
/// for different HTTP methods (GET, POST) and status codes (200, 404, etc.).
///
/// ```rust
/// # use fastmetrics::{
/// #     encoder::{EncodeLabelSet, LabelSetEncoder},
/// #     error::Result,
/// #     metrics::{counter::Counter, family::Family},
/// #     raw::LabelSetSchema,
/// #     registry::Registry,
/// # };
/// #
/// # fn main() -> Result<()> {
/// let mut registry = Registry::default();
///
/// #[derive(Clone, Eq, PartialEq, Hash)]
/// struct HttpLabels {
///     method: &'static str,
///     status: &'static str,
/// }
///
/// impl LabelSetSchema for HttpLabels {
///     fn names() -> Option<&'static [&'static str]> {
///         Some(&["method", "status"])
///     }
/// }
///
/// impl EncodeLabelSet for HttpLabels {
///     fn encode(&self, encoder: &mut dyn LabelSetEncoder) -> Result<()> {
///         encoder.encode(&("method", self.method))?;
///         encoder.encode(&("status", self.status))?;
///         Ok(())
///     }
/// }
///
/// let http_requests = Family::<HttpLabels, Counter>::default();
///
/// registry.register("http_requests", "Total HTTP requests", http_requests.clone())?;
///
/// // Create metrics with different labels
/// let labels = HttpLabels { method: "GET", status: "200" };
/// http_requests.with_or_new(&labels, |metric| metric.inc());
///
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct Family<LS, M, S = RandomState> {
    // label set => metric points
    metrics: Arc<RwLock<HashMap<LS, M, S>>>,
    metric_factory: Arc<MetricFactory<LS, M>>,
}

impl<LS, M, S> Debug for Family<LS, M, S>
where
    LS: Debug,
    M: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MetricFamily").field("metrics", &self.metrics).finish()
    }
}

impl<LS, M, S> Default for Family<LS, M, S>
where
    M: Default + 'static,
    S: Default,
{
    fn default() -> Self {
        Self::new(M::default)
    }
}

impl<LS, M, S> Family<LS, M, S> {
    pub(crate) fn read(&self) -> RwLockReadGuard<'_, HashMap<LS, M, S>> {
        self.metrics.read()
    }

    pub(crate) fn write(&self) -> RwLockWriteGuard<'_, HashMap<LS, M, S>> {
        self.metrics.write()
    }
}

impl<LS, M, S> Family<LS, M, S> {
    /// Creates a new metric family with a custom metric factory.
    ///
    /// The factory is used to create new metric instances when they are needed.
    ///
    /// # Parameters
    ///
    /// - `factory`: A factory function or closure that creates new metric instances
    ///
    /// # Returns
    ///
    /// A new `Family` instance that uses the provided factory to create metrics.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use fastmetrics::{
    /// #     encoder::{EncodeLabelSet, LabelSetEncoder},
    /// #     error::Result,
    /// #     metrics::{
    /// #         gauge::Gauge,
    /// #         family::Family,
    /// #         histogram::{Histogram, exponential_buckets},
    /// #     },
    /// #     raw::LabelSetSchema,
    /// # };
    /// #
    /// // Create a family with a custom factory function
    /// #[derive(Clone, Eq, PartialEq, Hash)]
    /// struct Labels {
    ///     region: &'static str,
    ///     status: &'static str,
    /// }
    ///
    /// impl LabelSetSchema for Labels {
    ///     fn names() -> Option<&'static [&'static str]> {
    ///         Some(&["region", "status"])
    ///     }
    /// }
    ///
    /// impl EncodeLabelSet for Labels {
    ///     fn encode(&self, encoder: &mut dyn LabelSetEncoder) -> Result<()> {
    ///         encoder.encode(&("region", self.region))?;
    ///         encoder.encode(&("status", self.status))?;
    ///         Ok(())
    ///     }
    /// }
    ///
    /// let gauge_family: Family<Labels, Gauge> = Family::new(|| Gauge::new(100));
    /// let histogram_family: Family<Labels, Histogram> = Family::new(|| {
    ///     Histogram::new(exponential_buckets(1.0, 2.0, 10))
    /// });
    /// ```
    pub fn new(metric_factory: impl Fn() -> M + Send + Sync + 'static) -> Self
    where
        S: Default,
    {
        Self::new_with_labels(move |_| metric_factory())
    }

    /// Creates a new metric family with a label-aware factory.
    ///
    /// This is useful for metric types whose constructor needs label values.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use fastmetrics::{
    /// #     encoder::{EncodeLabelSet, LabelSetEncoder},
    /// #     error::Result,
    /// #     metrics::{counter::LazyCounter, family::Family},
    /// #     raw::LabelSetSchema,
    /// # };
    /// #
    /// #[derive(Clone, Eq, PartialEq, Hash)]
    /// struct Labels {
    ///     method: &'static str,
    /// }
    ///
    /// impl LabelSetSchema for Labels {
    ///     fn names() -> Option<&'static [&'static str]> {
    ///         Some(&["method"])
    ///     }
    /// }
    ///
    /// impl EncodeLabelSet for Labels {
    ///     fn encode(&self, encoder: &mut dyn LabelSetEncoder) -> Result<()> {
    ///         encoder.encode(&("method", self.method))?;
    ///         Ok(())
    ///     }
    /// }
    ///
    /// # fn main() -> Result<()> {
    /// let family = Family::<Labels, LazyCounter<u64>>::new_with_labels(|labels| {
    ///     let method = labels.method;
    ///     LazyCounter::new(move || if method == "GET" { 1u64 } else { 2u64 })
    /// });
    ///
    /// let labels = Labels { method: "GET" };
    /// let value = family.with_or_new(&labels, |counter| counter.fetch());
    /// assert_eq!(value, 1);
    /// # Ok(())
    /// # }
    /// ```
    pub fn new_with_labels(metric_factory: impl Fn(&LS) -> M + Send + Sync + 'static) -> Self
    where
        S: Default,
    {
        Self {
            metrics: Arc::new(RwLock::new(HashMap::default())),
            metric_factory: Arc::new(metric_factory),
        }
    }

    /// Gets a reference to the metric with the specified labels and applies a function to it.
    ///
    /// # Parameters
    ///
    /// - `labels`: The labels to identify the metric
    /// - `func`: Function to apply to the metric if it exists
    ///
    /// # Returns
    ///
    /// Returns `Some(R)` where R is the return value of `func` if the metric exists, or `None`
    /// if no metric exists for the given label set.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use fastmetrics::{
    /// #     encoder::{EncodeLabelSet, LabelSetEncoder},
    /// #     error::Result,
    /// #     raw::LabelSetSchema,
    /// #     metrics::{counter::Counter, family::Family},
    /// #     registry::Registry,
    /// # };
    /// #
    /// # fn main() -> Result<()> {
    /// let mut registry = Registry::default();
    ///
    /// #[derive(Clone, Eq, PartialEq, Hash)]
    /// struct Labels {
    ///     method: &'static str,
    ///     status: &'static str,
    /// }
    ///
    /// impl LabelSetSchema for Labels {
    ///     fn names() -> Option<&'static [&'static str]> {
    ///         Some(&["method", "status"])
    ///     }
    /// }
    ///
    /// impl EncodeLabelSet for Labels {
    ///     fn encode(&self, encoder: &mut dyn LabelSetEncoder) -> Result<()> {
    ///         encoder.encode(&("method", self.method))?;
    ///         encoder.encode(&("status", self.status))?;
    ///         Ok(())
    ///     }
    /// }
    ///
    /// let http_requests = Family::<Labels, Counter>::default();
    ///
    /// registry.register("http_requests", "Total HTTP requests", http_requests.clone())?;
    ///
    /// let labels = Labels { method: "GET", status: "200" };
    /// assert_eq!(http_requests.with(&labels, |req| req.total()), None);
    ///
    /// http_requests.with_or_new(&labels, |req| req.inc());
    /// assert_eq!(http_requests.with(&labels, |req| req.total()), Some(1));
    ///
    /// http_requests.with(&labels, |req| req.inc());
    /// assert_eq!(http_requests.with(&labels, |req| req.total()), Some(2));
    /// # Ok(())
    /// # }
    /// ```
    pub fn with<R, F>(&self, labels: &LS, func: F) -> Option<R>
    where
        LS: Eq + Hash,
        F: FnOnce(&M) -> R,
        S: BuildHasher,
    {
        let guard = self.read();
        guard.get(labels).map(func)
    }

    /// Gets a reference to an existing metric or creates a new one using this family's metric
    /// factory if it doesn't exist, then applies a function to it.
    ///
    /// This method will:
    /// 1. Check if a metric exists for the given labels
    /// 2. If it exists, apply the function to it
    /// 3. If it doesn't exist, create a metric using this family's metric factory
    ///    and then apply the function
    ///
    /// # Parameters
    ///
    /// - `labels`: The labels to identify the metric
    /// - `func`: Function to apply to the metric
    ///
    /// # Returns
    ///
    /// Returns `Some(R)` where R is the return value of `func` after applying it to
    /// either the existing or newly created metric.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use fastmetrics::{
    /// #     encoder::{EncodeLabelSet, LabelSetEncoder},
    /// #     error::Result,
    /// #     raw::LabelSetSchema,
    /// #     metrics::{counter::Counter, family::Family},
    /// #     registry::Registry,
    /// # };
    /// #
    /// # fn main() -> Result<()> {
    /// let mut registry = Registry::default();
    ///
    /// #[derive(Clone, Eq, PartialEq, Hash)]
    /// struct Labels {
    ///     method: &'static str,
    ///     status: &'static str,
    /// }
    ///
    /// impl LabelSetSchema for Labels {
    ///     fn names() -> Option<&'static [&'static str]> {
    ///         Some(&["method", "status"])
    ///     }
    /// }
    ///
    /// impl EncodeLabelSet for Labels {
    ///     fn encode(&self, encoder: &mut dyn LabelSetEncoder) -> Result<()> {
    ///         encoder.encode(&("method", self.method))?;
    ///         encoder.encode(&("status", self.status))?;
    ///         Ok(())
    ///     }
    /// }
    ///
    /// let http_requests = Family::<Labels, Counter>::default();
    ///
    /// registry.register("http_requests", "Total HTTP requests", http_requests.clone())?;
    ///
    /// let labels = Labels { method: "GET", status: "200" };
    /// http_requests.with_or_new(&labels, |req| req.inc());
    /// assert_eq!(http_requests.with(&labels, |req| req.total()), Some(1));
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_or_new<R, F>(&self, labels: &LS, func: F) -> R
    where
        LS: Clone + Eq + Hash,
        F: FnOnce(&M) -> R,
        S: BuildHasher,
    {
        let read_guard = self.read();
        if let Some(metric) = read_guard.get(labels) {
            return func(metric);
        }
        drop(read_guard);

        // Previously we constructed new metrics while holding the write lock, e.g.:
        // let mut write_guard = self.write();
        // let metric =
        // write_guard.entry(labels.clone()).or_insert((self.metric_factory)(labels));
        // func(metric)

        // That approach kept potentially expensive constructors inside the critical section,
        // blocking readers and other writers. We now stage the value in `new_metric` so heavy
        // work happens outside the lock and we can reuse the constructed metric if another
        // thread races to insert the same labels.
        let mut new_metric = None;
        loop {
            // Acquire the write lock only for entry inspection/insertion; construction happens
            // after dropping it.
            let mut write_guard = self.write();
            match write_guard.entry(labels.clone()) {
                Entry::Occupied(entry) => return func(entry.get()),
                Entry::Vacant(entry) => {
                    if let Some(metric) = new_metric.take() {
                        return func(entry.insert(metric));
                    } else {
                        drop(write_guard);
                        // Construct the metric outside the lock so expensive constructors cannot
                        // stall other threads.
                        new_metric = Some((self.metric_factory)(labels));
                    }
                },
            }
        }
    }
}

impl<LS, M: TypedMetric, S> TypedMetric for Family<LS, M, S> {
    const TYPE: MetricType = <M as TypedMetric>::TYPE;
}

impl<LS: LabelSetSchema, M, S> MetricLabelSet for Family<LS, M, S> {
    type LabelSet = LS;
}

impl<LS, M, S> EncodeMetric for Family<LS, M, S>
where
    LS: EncodeLabelSet + Send + Sync,
    M: EncodeMetric,
    S: Send + Sync,
{
    fn encode(&self, encoder: &mut dyn MetricEncoder) -> Result<()> {
        let guard = self.read();
        for (labels, metric) in guard.iter() {
            encoder.encode(labels, metric)?;
        }
        Ok(())
    }

    fn is_empty(&self) -> bool {
        self.read().is_empty()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        encoder::{EncodeLabelSet, EncodeLabelValue, LabelEncoder, LabelSetEncoder},
        metrics::{
            check_text_encoding,
            counter::{Counter, LazyCounter},
            histogram::{Histogram, exponential_buckets},
        },
    };

    #[derive(Clone, PartialEq, Eq, Hash)]
    struct Labels {
        method: Method,
        status: u16,
        error: Option<bool>,
    }

    #[derive(Clone, PartialEq, Eq, Hash)]
    enum Method {
        Get,
        Put,
    }

    impl LabelSetSchema for Labels {
        fn names() -> Option<&'static [&'static str]> {
            Some(&["method", "status", "error"])
        }
    }

    impl EncodeLabelSet for Labels {
        fn encode(&self, encoder: &mut dyn LabelSetEncoder) -> Result<()> {
            encoder.encode(&("method", &self.method))?;
            encoder.encode(&("status", self.status))?;
            encoder.encode(&("error", self.error))?;
            Ok(())
        }
    }

    impl EncodeLabelValue for Method {
        fn encode(&self, encoder: &mut dyn LabelEncoder) -> Result<()> {
            match self {
                Self::Get => encoder.encode_str_value("GET"),
                Self::Put => encoder.encode_str_value("PUT"),
            }
        }
    }

    #[test]
    fn test_metric_family() {
        check_text_encoding(
            |registry| {
                let http_requests = Family::<Labels, Counter>::default();
                registry
                    .register("http_requests", "Total HTTP requests", http_requests.clone())
                    .unwrap();

                // Create metrics with different labels
                let labels = Labels { method: Method::Get, status: 200, error: None };
                http_requests.with_or_new(&labels, |metric| metric.inc());
                let labels = Labels { method: Method::Get, status: 404, error: Some(true) };
                http_requests.with_or_new(&labels, |metric| metric.inc());
                let labels = Labels { method: Method::Put, status: 200, error: None };
                http_requests.with_or_new(&labels, |metric| metric.inc());
            },
            |output| {
                // println!("{}", output);
                assert!(output.contains(r#"http_requests_total{method="GET",status="200"} 1"#));
                assert!(
                    output.contains(
                        r#"http_requests_total{method="GET",status="404",error="true"} 1"#
                    )
                );
                assert!(output.contains(r#"http_requests_total{method="PUT",status="200"} 1"#));
            },
        );

        check_text_encoding(
            |registry| {
                let http_requests_duration_seconds = Family::<Labels, Histogram>::new(|| {
                    Histogram::new(exponential_buckets(0.005, 2.0, 10))
                });

                registry
                    .register(
                        "http_requests_duration_seconds",
                        "Duration of HTTP requests",
                        http_requests_duration_seconds.clone(),
                    )
                    .unwrap();

                // Create metrics with different labels
                let labels = Labels { method: Method::Get, status: 200, error: None };
                http_requests_duration_seconds.with_or_new(&labels, |hist| hist.observe(0.1));
                let labels = Labels { method: Method::Get, status: 404, error: Some(true) };
                http_requests_duration_seconds.with_or_new(&labels, |hist| hist.observe(0.1));
                let labels = Labels { method: Method::Put, status: 200, error: None };
                http_requests_duration_seconds.with_or_new(&labels, |hist| hist.observe(2.0));
            },
            |output| {
                // println!("{}", output);
                assert!(output.contains(
                    r#"http_requests_duration_seconds_count{method="GET",status="200"} 1"#
                ));
                assert!(output.contains(
                    r#"http_requests_duration_seconds_sum{method="GET",status="200"} 0.1"#
                ));
                assert!(output.contains(
                    r#"http_requests_duration_seconds_count{method="GET",status="404",error="true"} 1"#
                ));
                assert!(output.contains(
                    r#"http_requests_duration_seconds_sum{method="GET",status="404",error="true"} 0.1"#
                ));
                assert!(output.contains(
                    r#"http_requests_duration_seconds_count{method="PUT",status="200"} 1"#
                ));
                assert!(output.contains(
                    r#"http_requests_duration_seconds_sum{method="PUT",status="200"} 2.0"#
                ));
            },
        );
    }

    #[test]
    fn test_empty_metric_family() {
        check_text_encoding(
            |registry| {
                let http_requests = Family::<Labels, Counter>::default();
                registry
                    .register("http_requests", "Total HTTP requests", http_requests)
                    .unwrap();
            },
            |output| {
                assert_eq!(output, "# EOF\n");
            },
        );

        check_text_encoding(
            |registry| {
                let http_requests = Family::<Labels, Counter>::default();
                registry
                    .register("http_requests", "Total HTTP requests", http_requests.clone())
                    .unwrap();

                let labels = Labels { method: Method::Get, status: 200, error: None };
                http_requests.with_or_new(&labels, |_| {});
            },
            |output| {
                assert!(output.contains("# TYPE http_requests counter"));
                assert!(output.contains("# HELP http_requests Total HTTP requests"));
                assert!(output.contains(r#"http_requests_total{method="GET",status="200"} 0"#));
            },
        );
    }

    #[test]
    fn test_new_uses_label_aware_factory() {
        let family = Family::<Labels, LazyCounter<u64>>::new_with_labels(|labels| {
            let method = labels.method.clone();
            let status = u64::from(labels.status);
            let error = labels.error.unwrap_or(false);
            LazyCounter::new(move || {
                let method_value = match method {
                    Method::Get => 1_000_u64,
                    Method::Put => 2_000_u64,
                };
                let error_value = if error { 10_000_u64 } else { 0_u64 };
                method_value + error_value + status
            })
        });

        let labels_get = Labels { method: Method::Get, status: 200, error: None };
        let labels_put = Labels { method: Method::Put, status: 404, error: Some(true) };

        let get_total = family.with_or_new(&labels_get, |counter| counter.fetch());
        assert_eq!(get_total, 1_200_u64);

        let get_total_reused = family.with_or_new(&labels_get, |counter| counter.fetch());
        assert_eq!(get_total_reused, 1_200_u64);

        let put_total = family.with_or_new(&labels_put, |counter| counter.fetch());
        assert_eq!(put_total, 12_404_u64);

        assert_eq!(family.with(&labels_get, |counter| counter.fetch()), Some(1_200_u64));
    }
}