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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
use std::{borrow::Cow, sync::OnceLock};

use parking_lot::RwLock;

use crate::{
    error::{Error, Result},
    registry::{Metric, Registry, Unit},
};

struct GlobalRegistry {
    registry: OnceLock<RwLock<Registry>>,
}

impl GlobalRegistry {
    const fn new() -> Self {
        Self { registry: OnceLock::new() }
    }
}

trait RegistryProvider: Send + Sync {
    fn set(&self, registry: Registry) -> Result<()>;

    fn get(&self) -> &RwLock<Registry>;
}

impl RegistryProvider for GlobalRegistry {
    fn set(&self, registry: Registry) -> Result<()> {
        self.registry
            .set(RwLock::new(registry))
            .map_err(|_| Error::duplicated("Global registry has already been initialized"))
    }

    fn get(&self) -> &RwLock<Registry> {
        self.registry.get_or_init(|| RwLock::new(Registry::default()))
    }
}

static GLOBAL_REGISTRY: GlobalRegistry = GlobalRegistry::new();

#[cfg(test)]
thread_local! {
    static TEST_REGISTRY: std::cell::RefCell<Option<&'static dyn RegistryProvider>> = std::cell::RefCell::new(None);
}

fn registry_provider() -> &'static dyn RegistryProvider {
    #[cfg(not(test))]
    {
        &GLOBAL_REGISTRY
    }

    #[cfg(test)]
    {
        TEST_REGISTRY.with(|reg| reg.borrow().unwrap_or(&GLOBAL_REGISTRY))
    }
}

/// Sets the global registry to the provided registry instance.
///
/// This function allows you to replace the default global registry with a custom one.
/// It can only be called once - subsequent calls will return an [`Error`].
///
/// # Thread Safety
///
/// This function is thread-safe and can be called from multiple threads simultaneously.
/// However, only the first successful call will set the registry.
///
/// # Example
///
/// ```rust
/// # use fastmetrics::{
/// #    error::{ErrorKind, Result},
/// #    registry::{Registry, set_global_registry}
/// # };
/// #
/// # fn main() -> Result<()> {
/// let custom_registry = Registry::builder()
///     .with_namespace("myapp")
///     .with_const_labels([("env", "prod")])
///     .build()?;
///
/// // This will succeed
/// assert!(set_global_registry(custom_registry).is_ok());
/// // metric operations
/// // ...
///
/// // This will fail
/// let another_registry = Registry::builder()
///     .with_namespace("other")
///     .build()?;
/// let res = set_global_registry(another_registry);
/// assert!(res.is_err());
/// if let Err(err) = res {
///     assert_eq!(err.kind(), ErrorKind::Duplicated);
/// }
/// # Ok(())
/// # }
/// ```
pub fn set_global_registry(registry: Registry) -> Result<()> {
    let provider = registry_provider();
    provider.set(registry)
}

/// Executes a function with read-only access to the global registry.
///
/// This function provides safe, read-only access to the global registry without
/// exposing the underlying synchronization primitives. The global registry will
/// be initialized with default settings if it hasn't been set previously.
///
/// # Arguments
///
/// * `f` - A closure that takes a reference to the [`Registry`] and returns a value of type `R`
///
/// # Returns
///
/// Returns the result of calling the provided closure with the global registry.
///
/// # Example
///
/// ```rust
/// # use fastmetrics::registry::with_global_registry;
/// #
/// let namespace = with_global_registry(|registry| {
///     registry.namespace().map(|s| s.to_owned())
/// });
/// ```
pub fn with_global_registry<F, R>(f: F) -> R
where
    F: FnOnce(&Registry) -> R,
{
    let provider = registry_provider();
    let registry = provider.get().read();
    f(&registry)
}

/// Executes a function with mutable access to the global registry.
///
/// This function provides safe, mutable access to the global registry without
/// exposing the underlying synchronization primitives. The global registry will
/// be initialized with default settings if it hasn't been set previously.
///
/// # Arguments
///
/// * `f` - A closure that takes a mutable reference to the [`Registry`] and returns a value of type
///   `R`
///
/// # Returns
///
/// Returns the result of calling the provided closure with the global registry.
///
/// # Example
///
/// ```rust
/// # use fastmetrics::{
/// #     registry::with_global_registry_mut,
/// #     metrics::counter::Counter
/// # };
/// #
/// let res = with_global_registry_mut(|registry| {
///     // Perform mutable operations on the registry
///     registry.register("my_counter", "my_counter help", <Counter>::default()).map(|_| ())
/// });
/// ```
pub fn with_global_registry_mut<F, R>(f: F) -> R
where
    F: FnOnce(&mut Registry) -> R,
{
    let provider = registry_provider();
    let mut registry = provider.get().write();
    f(&mut registry)
}

/// Registers a metric to the global [`Registry`] and returns the metric instance.
///
/// This function provides a convenient way to register metrics with the global registry
/// while retaining ownership of the metric for updates. It's particularly useful with
/// `LazyLock` for creating static global metrics.
///
/// # Arguments
///
/// * `name` - The name of the metric (it must satisfy the OpenMetrics metric name rules)
/// * `help` - A description of what the metric measures
/// * `metric` - The metric instance to register (must implement [`Clone`])
///
/// # Returns
///
/// Returns `Ok(metric)` if registration succeeds, or [`Error`] if:
/// - A same metric already exists
/// - The metric name violates the OpenMetrics metric name rules
/// - The help text violates the OpenMetrics escaped-string rules
///
/// # Examples
///
/// ## Basic usage
///
/// ```rust
/// # use fastmetrics::{
/// #     error::Result,
/// #     metrics::counter::Counter,
/// #     registry::register,
/// # };
/// #
/// # fn main() -> Result<()> {
/// let counter = register("http_requests_total", "Total HTTP requests", <Counter>::default())?;
///
/// // Use the returned counter
/// counter.inc();
/// assert_eq!(counter.total(), 1);
/// # Ok(())
/// # }
/// ```
///
/// ## With LazyLock for static metrics
///
/// ```rust
/// # use std::sync::LazyLock;
/// #
/// # use fastmetrics::{
/// #     metrics::counter::Counter,
/// #     registry::register,
/// # };
/// #
/// static REQUEST_COUNTER: LazyLock<Counter> = LazyLock::new(|| {
///     register("requests_total", "Total requests processed", <Counter>::default())
///         .expect("Failed to register counter")
/// });
///
/// fn handle_request() {
///     REQUEST_COUNTER.inc();
/// }
/// ```
///
/// ## Error handling
///
/// ```rust
/// # use fastmetrics::{
/// #     error::{ErrorKind, Result},
/// #     metrics::counter::Counter,
/// #     registry::register,
/// # };
/// #
/// # fn main() -> Result<()> {
/// // Register first counter
/// let counter1 = register("my_counter", "A counter", <Counter>::default())?;
///
/// // Try to register another counter with the same name - this will fail
/// let result = register("my_counter", "Another counter", <Counter>::default());
/// assert!(result.is_err());
/// if let Err(err) = result {
///     assert_eq!(err.kind(), ErrorKind::Duplicated);
///     assert_eq!(err.message(), "metric already exists");
/// }
/// # Ok(())
/// # }
/// ```
pub fn register<M>(
    name: impl Into<Cow<'static, str>>,
    help: impl Into<Cow<'static, str>>,
    metric: M,
) -> Result<M>
where
    M: Metric + Clone + 'static,
{
    register_metric(name, help, None::<Unit>, metric)
}

/// Registers a metric with a unit to the global [`Registry`] and returns the metric instance.
///
/// This function is similar to [`register`] but allows specifying a unit for the metric,
/// which is important for proper metric interpretation and display in monitoring systems.
///
/// # Arguments
///
/// * `name` - The name of the metric (it must satisfy the OpenMetrics metric name rules)
/// * `help` - A description of what the metric measures
/// * `unit` - The unit of measurement (e.g., [`Unit::Seconds`], [`Unit::Bytes`])
/// * `metric` - The metric instance to register (must implement [`Clone`])
///
/// # Returns
///
/// Returns `Ok(metric)` if registration succeeds, or [`Error`] if:
/// - A same metric already exists
/// - The metric name violates the OpenMetrics metric name rules
/// - The help text violates the OpenMetrics escaped-string rules
/// - The unit format is invalid (custom units must use characters allowed by the metric name ABNF)
/// - The metric type doesn't support units (StateSet, Info, Unknown types must have empty units)
///
/// # Examples
///
/// ## With predefined units
///
/// ```rust
/// # use fastmetrics::{
/// #     error::Result,
/// #     metrics::histogram::Histogram,
/// #     registry::{register_with_unit, Unit},
/// # };
/// #
/// # fn main() -> Result<()> {
/// let duration_histogram = register_with_unit(
///     "request_duration",
///     "HTTP request duration",
///     Unit::Seconds,
///     Histogram::default(),
/// )?;
///
/// duration_histogram.observe(0.1); // 100ms
/// # Ok(())
/// # }
/// ```
///
/// ## With custom units
///
/// ```rust
/// # use fastmetrics::{
/// #     error::Result,
/// #     metrics::gauge::Gauge,
/// #     registry::register_with_unit,
/// # };
/// #
/// # fn main() -> Result<()> {
/// let temperature = register_with_unit(
///     "cpu_temperature",
///     "CPU temperature",
///     "celsius",
///     <Gauge>::default(),
/// )?;
///
/// temperature.set(65);
/// # Ok(())
/// # }
/// ```
///
/// ## With LazyLock for static metrics
///
/// ```rust
/// # use std::sync::LazyLock;
/// #
/// # use fastmetrics::{
/// #     metrics::gauge::Gauge,
/// #     registry::{register_with_unit, Unit},
/// # };
/// #
/// static MEMORY_USAGE: LazyLock<Gauge> = LazyLock::new(|| {
///     register_with_unit(
///         "memory_usage",
///         "Current memory usage",
///         Unit::Bytes,
///         <Gauge>::default(),
///     )
///     .expect("Failed to register memory_usage gauge")
/// });
///
/// fn update_memory_stats() {
///     MEMORY_USAGE.set(1024 * 1024 * 512); // 512MB
/// }
/// ```
///
/// ## Error cases
///
/// ```rust
/// # use fastmetrics::{
/// #     error::{ErrorKind, Result},
/// #     metrics::gauge::Gauge,
/// #     registry::register_with_unit,
/// # };
/// #
/// # fn main() -> Result<()> {
/// // Invalid unit format (contains characters disallowed by OpenMetrics)
/// let result = register_with_unit(
///     "invalid_metric",
///     "Invalid metric",
///     "invalid-unit",
///     <Gauge>::default(),
/// );
/// assert!(result.is_err());
/// if let Err(err) = result {
///     assert_eq!(err.kind(), ErrorKind::Invalid);
/// }
/// # Ok(())
/// # }
/// ```
pub fn register_with_unit<M>(
    name: impl Into<Cow<'static, str>>,
    help: impl Into<Cow<'static, str>>,
    unit: impl Into<Unit>,
    metric: M,
) -> Result<M>
where
    M: Metric + Clone + 'static,
{
    register_metric(name, help, Some(unit), metric)
}

/// Registers a metric with an optional unit to the global [`Registry`] and returns the metric
/// instance.
///
/// This is the most flexible registration method that allows specifying an optional unit.
/// It serves as the underlying implementation for both [`register`] and [`register_with_unit`].
/// Use [`register`] for metrics without units or [`register_with_unit`] for metrics with units
/// unless you need the flexibility of optional units.
///
/// # Arguments
///
/// * `name` - The name of the metric (it must satisfy the OpenMetrics metric name rules)
/// * `help` - A description of what the metric measures
/// * `unit` - An optional unit of measurement (e.g., `Some(Unit::Seconds)`, `None::<Unit>`)
/// * `metric` - The metric instance to register (must implement [`Clone`])
///
/// # Returns
///
/// Returns `Ok(metric)` if registration succeeds, or [`Error`] if:
/// - A same metric already exists
/// - The metric name violates the OpenMetrics metric name rules
/// - The help text violates the OpenMetrics escaped-string rules
/// - The unit format is invalid (custom units must use characters allowed by the metric name ABNF)
/// - The metric type doesn't support units (StateSet, Info, Unknown types must have empty units)
///
/// # Examples
///
/// ## Register without the unit
///
/// ```rust
/// # use fastmetrics::{
/// #     error::Result,
/// #     metrics::counter::Counter,
/// #     registry::{register_metric, Unit},
/// # };
/// #
/// # fn main() -> Result<()> {
/// let counter = register_metric(
///     "requests_total",
///     "Total number of requests",
///     None::<Unit>,
///     <Counter>::default(),
/// )?;
///
/// counter.inc();
/// assert_eq!(counter.total(), 1);
/// # Ok(())
/// # }
/// ```
///
/// ## Register with a unit
///
/// ```rust
/// # use fastmetrics::{
/// #     error::Result,
/// #     metrics::histogram::Histogram,
/// #     registry::{register_metric, Unit},
/// # };
/// #
/// # fn main() -> Result<()> {
/// let histogram = register_metric(
///     "http_request_duration",
///     "Duration of HTTP request",
///     Some(Unit::Seconds),
///     Histogram::default(),
/// )?;
///
/// histogram.observe(0.1); // 100ms
/// # Ok(())
/// # }
/// ```
///
/// ## Conditional unit based on configuration
///
/// ```rust
/// # use fastmetrics::{
/// #     error::Result,
/// #     metrics::gauge::Gauge,
/// #     registry::{register_metric, Unit},
/// # };
/// #
/// # fn main() -> Result<()> {
/// let use_metric_units = true; // from config
/// let unit: Option<Unit> = if use_metric_units {
///     Some("celsius".into())
/// } else {
///     None
/// };
///
/// let temperature = register_metric(
///     "cpu_temperature",
///     "CPU temperature",
///     unit,
///     <Gauge>::default(),
/// )?;
///
/// temperature.set(65);
/// # Ok(())
/// # }
/// ```
///
/// ## With LazyLock for static metrics
///
/// ```rust
/// # use std::sync::LazyLock;
/// #
/// # use fastmetrics::{
/// #     metrics::gauge::Gauge,
/// #     registry::{register_metric, Unit},
/// # };
/// #
/// static MEMORY_USAGE: LazyLock<Gauge> = LazyLock::new(|| {
///     register_metric(
///         "memory_usage",
///         "Current memory usage",
///         Some(Unit::Bytes),
///         <Gauge>::default(),
///     )
///     .expect("Failed to register memory_usage gauge")
/// });
///
/// fn update_memory_stats() {
///     MEMORY_USAGE.set(1024 * 1024 * 512); // 512MB
/// }
/// ```
///
/// ## Error cases
///
/// ```rust
/// # use fastmetrics::{
/// #     error::{ErrorKind, Result},
/// #     metrics::{counter::Counter, gauge::Gauge},
/// #     registry::{register_metric, Unit},
/// # };
/// #
/// # fn main() -> Result<()> {
/// // Invalid unit format (contains characters disallowed by OpenMetrics)
/// let result = register_metric(
///     "invalid_metric",
///     "Invalid metric",
///     Some("invalid-unit"),
///     <Gauge>::default(),
/// );
/// assert!(result.is_err());
/// if let Err(err) = result {
///     assert_eq!(err.kind(), ErrorKind::Invalid);
/// }
///
/// // Duplicate registration
/// let counter1 = register_metric("my_counter", "A counter", None::<Unit>, <Counter>::default())?;
/// let result = register_metric("my_counter", "Another counter", None::<Unit>, <Counter>::default());
/// assert!(result.is_err());
/// if let Err(err) = result {
///     assert_eq!(err.kind(), ErrorKind::Duplicated);
/// }
/// # Ok(())
/// # }
/// ```
pub fn register_metric<M>(
    name: impl Into<Cow<'static, str>>,
    help: impl Into<Cow<'static, str>>,
    unit: Option<impl Into<Unit>>,
    metric: M,
) -> Result<M>
where
    M: Metric + Clone + 'static,
{
    with_global_registry_mut(|registry| {
        registry.register_metric(name, help, unit, metric.clone()).map(|_| metric)
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    fn with_test_provider<F, R>(provider: &'static dyn RegistryProvider, f: F) -> R
    where
        F: FnOnce() -> R,
    {
        TEST_REGISTRY.with(|current| {
            let old_provider = current.borrow_mut().replace(provider);
            let result = f();
            *current.borrow_mut() = old_provider;
            result
        })
    }

    #[derive(Default)]
    struct TestRegistry {
        registry: OnceLock<RwLock<Registry>>,
    }

    impl TestRegistry {
        fn new(registry: Registry) -> Self {
            let this = Self { registry: OnceLock::new() };
            let _ = this.registry.set(RwLock::new(registry));
            this
        }
    }

    impl RegistryProvider for TestRegistry {
        fn set(&self, registry: Registry) -> Result<()> {
            self.registry
                .set(RwLock::new(registry))
                .map_err(|_| Error::duplicated("Global registry has already been initialized"))
        }

        fn get(&self) -> &RwLock<Registry> {
            self.registry.get_or_init(|| RwLock::new(Registry::default()))
        }
    }

    fn create_test_provider(registry: Registry) -> &'static TestRegistry {
        Box::leak(Box::new(TestRegistry::new(registry)))
    }

    fn create_default_test_provider() -> &'static TestRegistry {
        Box::leak(Box::new(TestRegistry::default()))
    }

    #[test]
    fn test_global_registry() -> Result<()> {
        let provider = create_default_test_provider();
        with_test_provider(provider, || {
            with_global_registry(|registry| {
                assert_eq!(registry.namespace(), None);
            });
        });

        let registry = Registry::builder().with_namespace("test1").build()?;
        let provider = create_test_provider(registry);
        with_test_provider(provider, || {
            with_global_registry(|registry| {
                assert_eq!(registry.namespace(), Some("test1"));
            });
        });

        let registry = Registry::builder().with_namespace("test2").build()?;
        let provider = create_test_provider(registry);
        with_test_provider(provider, || {
            with_global_registry(|registry| {
                assert_eq!(registry.namespace(), Some("test2"));
            });
        });

        Ok(())
    }

    #[test]
    fn test_concurrent_access() -> Result<()> {
        let registry = Registry::builder().with_namespace("concurrent").build()?;
        let provider = create_test_provider(registry);

        with_test_provider(provider, || {
            with_global_registry(|registry| {
                assert_eq!(registry.namespace(), Some("concurrent"));
            });

            let handles: Vec<_> = (0..4)
                .map(|_| {
                    let test_provider = provider;
                    std::thread::spawn(move || {
                        // use the provider directly instead of thread_local
                        let registry = test_provider.get().read();
                        registry.namespace().map(|s| s.to_owned())
                    })
                })
                .collect();

            for handle in handles {
                let namespace = handle.join().expect("Thread should not panic");
                assert_eq!(namespace, Some("concurrent".to_owned()));
            }
        });

        Ok(())
    }

    #[test]
    fn test_mutable_and_immutable_access() -> Result<()> {
        let registry = Registry::builder().with_namespace("test").build()?;
        let provider = create_test_provider(registry);

        with_test_provider(provider, || {
            // access the mutable registry
            with_global_registry_mut(|registry| {
                assert_eq!(registry.namespace(), Some("test"));
                // do mutable operations, such as registering metrics
            });

            // access the immutable registry
            with_global_registry(|registry| {
                assert_eq!(registry.namespace(), Some("test"));
            });
        });

        Ok(())
    }

    #[test]
    fn duplicated_set_global_registry() -> Result<()> {
        // Create a test provider to isolate this test
        let provider = create_default_test_provider();

        with_test_provider(provider, || {
            // The First call should succeed
            let registry1 = Registry::builder().with_namespace("first").build()?;
            let result1 = set_global_registry(registry1);
            assert!(result1.is_ok(), "First set_global_registry should succeed");

            // Verify the registry was set
            with_global_registry(|registry| {
                assert_eq!(registry.namespace(), Some("first"));
            });

            // The Second call should fail since the global registry is already initialized
            let registry2 = Registry::builder().with_namespace("second").build()?;
            let result2 = set_global_registry(registry2);
            assert!(result2.is_err(), "Second set_global_registry should fail");

            // Verify the original registry is still in place
            with_global_registry(|registry| {
                assert_eq!(registry.namespace(), Some("first"));
            });

            Ok(())
        })
    }
}