redup-bootstrap 0.3.1

Ядро платформы: инстанс службы, модули, жизненный цикл, здоровье и телеметрия.
Documentation
//! Счётчик метрик для модулей.

use std::sync::Arc;

use crate::telemetry::histogram_config::HistogramConfig;
use crate::telemetry::metrics::counter::Counter;
use crate::telemetry::metrics::error::MetricError;
use crate::telemetry::metrics::histogram::Histogram;
use crate::telemetry::metrics::names::{check_metric_name, check_reserved_suffix};
use crate::telemetry::metrics::read::Read;
use crate::telemetry::metrics::registry::Registry;
use crate::telemetry::metrics::unit::Unit;

/// Суффиксы имён, зарезервированные для любого инструмента, с объяснением, за кем закреплены.
const RESERVED_SUFFIXES: [(&str, &str); 5] = [
    (
        "_seconds",
        "the unit suffix is added by the meter based on Unit",
    ),
    (
        "_bytes",
        "the unit suffix is added by the meter based on Unit",
    ),
    (
        "_ratio",
        "the unit suffix is added by the meter based on Unit",
    ),
    (
        "_total",
        "the suffix is added by the Prometheus exposition for counters",
    ),
    (
        "_ms",
        "milliseconds are not allowed, seconds are the unit of time",
    ),
];

/// Суффиксы, зарезервированные под ряды гистограммы.
const HISTOGRAM_SUFFIXES: [(&str, &str); 3] = [
    (
        "_bucket",
        "the suffix is reserved for histogram bucket series",
    ),
    ("_sum", "the suffix is reserved for histogram sum series"),
    (
        "_count",
        "the suffix is reserved for histogram count series",
    ),
];

/// Счётчик метрик для модулей: добавляет префикс службы и суффикс единицы, проверяет правила имён.
///
/// Автор модуля пишет имя без префикса службы и без суффикса единицы — их добавляет счётчик:
/// имя метрики выходит `{префикс}_{имя}{суффикс единицы}`.
pub struct Meter {
    /// Реестр инстанса.
    registry: Arc<Registry>,
    /// Префикс службы.
    prefix: String,
    /// Настройка корзин гистограмм.
    histogram: HistogramConfig,
}

impl Meter {
    /// Счётчик метрик службы с префиксом `prefix` и настройкой корзин `histogram`.
    pub(crate) fn new(
        registry: Arc<Registry>,
        prefix: impl Into<String>,
        histogram: HistogramConfig,
    ) -> Self {
        Self {
            registry,
            prefix: prefix.into(),
            histogram,
        }
    }

    /// Счётчик событий. Имя — без префикса службы и без суффикса единицы.
    pub fn counter(&self, name: &str, unit: Unit, help: &str) -> Result<Counter, MetricError> {
        check_module_name(name, false)?;
        let metric = full_name(&self.prefix, name, unit);
        self.registry.counter(&metric, help)
    }

    /// Наблюдаемая величина.
    pub fn gauge(&self, name: &str, unit: Unit, help: &str, read: Read) -> Result<(), MetricError> {
        check_module_name(name, false)?;
        let metric = full_name(&self.prefix, name, unit);
        self.registry.observable(&metric, help, read)
    }

    /// Гистограмма распределения. Корзины берутся из настройки по имени с префиксом и единице.
    pub fn histogram(&self, name: &str, unit: Unit, help: &str) -> Result<Histogram, MetricError> {
        check_module_name(name, true)?;
        let metric = full_name(&self.prefix, name, unit);
        let buckets = self.histogram.buckets_for(&self.prefixed(name), unit);
        self.registry.histogram(&metric, help, Some(buckets))
    }

    /// Имя с префиксом службы, без суффикса единицы: под ним настройка ищет свою сетку корзин.
    fn prefixed(&self, name: &str) -> String {
        format!("{}_{}", self.prefix, name)
    }
}

/// Полное имя метрики: `{префикс}_{имя}{суффикс единицы}`.
fn full_name(prefix: &str, name: &str, unit: Unit) -> String {
    format!("{}_{}{}", prefix, name, unit.suffix())
}

/// Проверяет имя модуля по правилам счётчика метрик: правило имён, зарезервированные суффиксы, у
/// гистограммы — ещё и суффиксы её рядов.
fn check_module_name(name: &str, histogram: bool) -> Result<(), MetricError> {
    check_metric_name(name)?;
    let suffixes = RESERVED_SUFFIXES
        .iter()
        .chain(HISTOGRAM_SUFFIXES.iter().filter(|_| histogram));
    for (suffix, reason) in suffixes {
        check_reserved_suffix(name, suffix, reason)?;
    }
    Ok(())
}