Skip to main content

redup_bootstrap/telemetry/metrics/
counter.rs

1//! Счётчик: только растёт.
2
3use std::sync::Arc;
4
5use prometheus_client::metrics::counter::Counter as ClientCounter;
6use prometheus_client::metrics::family::Family;
7
8use crate::telemetry::metrics::error::MetricError;
9use crate::telemetry::metrics::instrument::InstrumentState;
10use crate::telemetry::metrics::labels::Labels;
11
12/// Счётчик: только растёт.
13///
14/// Клон — тот же инструмент; `with` даёт привязку к набору меток того же семейства. Привязанный
15/// инструмент стоит кэшировать и писать без выделения памяти.
16#[derive(Debug, Clone)]
17pub struct Counter {
18    /// Состояние семейства, общее всем привязкам.
19    state: Arc<InstrumentState<Family<Labels, ClientCounter>>>,
20    /// Набор меток этой привязки.
21    labels: Labels,
22}
23
24impl Counter {
25    /// Прибавить `value`.
26    pub fn increment(&self, value: u64) {
27        self.state.family.get_or_create(&self.labels).inc_by(value);
28    }
29
30    /// Тот же счётчик с метками.
31    pub fn with(&self, labels: Labels) -> Result<Self, MetricError> {
32        self.state.bind(&labels)?;
33        Ok(Self {
34            state: self.state.clone(),
35            labels,
36        })
37    }
38
39    /// Счётчик поверх семейства `family` с именем `name`.
40    pub(crate) fn new(name: &str, family: Family<Labels, ClientCounter>) -> Self {
41        Self {
42            state: Arc::new(InstrumentState::new(name.to_owned(), family)),
43            labels: Labels::new(),
44        }
45    }
46}