redup_bootstrap/telemetry/metrics/
meter.rs1use std::sync::Arc;
4
5use crate::telemetry::histogram_config::HistogramConfig;
6use crate::telemetry::metrics::counter::Counter;
7use crate::telemetry::metrics::error::MetricError;
8use crate::telemetry::metrics::histogram::Histogram;
9use crate::telemetry::metrics::names::{check_metric_name, check_reserved_suffix};
10use crate::telemetry::metrics::read::Read;
11use crate::telemetry::metrics::registry::Registry;
12use crate::telemetry::metrics::unit::Unit;
13
14const RESERVED_SUFFIXES: [(&str, &str); 5] = [
16 (
17 "_seconds",
18 "the unit suffix is added by the meter based on Unit",
19 ),
20 (
21 "_bytes",
22 "the unit suffix is added by the meter based on Unit",
23 ),
24 (
25 "_ratio",
26 "the unit suffix is added by the meter based on Unit",
27 ),
28 (
29 "_total",
30 "the suffix is added by the Prometheus exposition for counters",
31 ),
32 (
33 "_ms",
34 "milliseconds are not allowed, seconds are the unit of time",
35 ),
36];
37
38const HISTOGRAM_SUFFIXES: [(&str, &str); 3] = [
40 (
41 "_bucket",
42 "the suffix is reserved for histogram bucket series",
43 ),
44 ("_sum", "the suffix is reserved for histogram sum series"),
45 (
46 "_count",
47 "the suffix is reserved for histogram count series",
48 ),
49];
50
51pub struct Meter {
56 registry: Arc<Registry>,
58 prefix: String,
60 histogram: HistogramConfig,
62}
63
64impl Meter {
65 pub(crate) fn new(
67 registry: Arc<Registry>,
68 prefix: impl Into<String>,
69 histogram: HistogramConfig,
70 ) -> Self {
71 Self {
72 registry,
73 prefix: prefix.into(),
74 histogram,
75 }
76 }
77
78 pub fn counter(&self, name: &str, unit: Unit, help: &str) -> Result<Counter, MetricError> {
80 check_module_name(name, false)?;
81 let metric = full_name(&self.prefix, name, unit);
82 self.registry.counter(&metric, help)
83 }
84
85 pub fn gauge(&self, name: &str, unit: Unit, help: &str, read: Read) -> Result<(), MetricError> {
87 check_module_name(name, false)?;
88 let metric = full_name(&self.prefix, name, unit);
89 self.registry.observable(&metric, help, read)
90 }
91
92 pub fn histogram(&self, name: &str, unit: Unit, help: &str) -> Result<Histogram, MetricError> {
94 check_module_name(name, true)?;
95 let metric = full_name(&self.prefix, name, unit);
96 let buckets = self.histogram.buckets_for(&self.prefixed(name), unit);
97 self.registry.histogram(&metric, help, Some(buckets))
98 }
99
100 fn prefixed(&self, name: &str) -> String {
102 format!("{}_{}", self.prefix, name)
103 }
104}
105
106fn full_name(prefix: &str, name: &str, unit: Unit) -> String {
108 format!("{}_{}{}", prefix, name, unit.suffix())
109}
110
111fn check_module_name(name: &str, histogram: bool) -> Result<(), MetricError> {
114 check_metric_name(name)?;
115 let suffixes = RESERVED_SUFFIXES
116 .iter()
117 .chain(HISTOGRAM_SUFFIXES.iter().filter(|_| histogram));
118 for (suffix, reason) in suffixes {
119 check_reserved_suffix(name, suffix, reason)?;
120 }
121 Ok(())
122}