Skip to main content

redup_bootstrap/telemetry/metrics/
meter.rs

1//! Счётчик метрик для модулей.
2
3use 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
14/// Суффиксы имён, зарезервированные для любого инструмента, с объяснением, за кем закреплены.
15const 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
38/// Суффиксы, зарезервированные под ряды гистограммы.
39const 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
51/// Счётчик метрик для модулей: добавляет префикс службы и суффикс единицы, проверяет правила имён.
52///
53/// Автор модуля пишет имя без префикса службы и без суффикса единицы — их добавляет счётчик:
54/// имя метрики выходит `{префикс}_{имя}{суффикс единицы}`.
55pub struct Meter {
56    /// Реестр инстанса.
57    registry: Arc<Registry>,
58    /// Префикс службы.
59    prefix: String,
60    /// Настройка корзин гистограмм.
61    histogram: HistogramConfig,
62}
63
64impl Meter {
65    /// Счётчик метрик службы с префиксом `prefix` и настройкой корзин `histogram`.
66    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    /// Счётчик событий. Имя — без префикса службы и без суффикса единицы.
79    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    /// Наблюдаемая величина.
86    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    /// Гистограмма распределения. Корзины берутся из настройки по имени с префиксом и единице.
93    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    /// Имя с префиксом службы, без суффикса единицы: под ним настройка ищет свою сетку корзин.
101    fn prefixed(&self, name: &str) -> String {
102        format!("{}_{}", self.prefix, name)
103    }
104}
105
106/// Полное имя метрики: `{префикс}_{имя}{суффикс единицы}`.
107fn full_name(prefix: &str, name: &str, unit: Unit) -> String {
108    format!("{}_{}{}", prefix, name, unit.suffix())
109}
110
111/// Проверяет имя модуля по правилам счётчика метрик: правило имён, зарезервированные суффиксы, у
112/// гистограммы — ещё и суффиксы её рядов.
113fn 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}