redup-bootstrap 0.1.1

Ядро платформы: инстанс службы, модули, жизненный цикл, здоровье и телеметрия.
Documentation
//! Общие помощники тестов метрик.
// Помощники вызываются из функций `#[test]` и не во всех наборах тестов сразу.
#![allow(clippy::expect_used, dead_code)]

use prometheus_parse::{Sample, Scrape, Value};

use crate::telemetry::HistogramConfig;

/// Разбирает текст выгрузки независимым разборщиком Prometheus.
pub(crate) fn scrape(text: &str) -> Scrape {
    Scrape::parse(
        text.lines()
            .map(|line| Ok::<String, std::io::Error>(line.to_owned())),
    )
    .expect("the exposition text is parsed by prometheus-parse")
}

/// Ряды выгрузки с именем `metric`.
pub(crate) fn samples<'a>(scrape: &'a Scrape, metric: &str) -> Vec<&'a Sample> {
    scrape
        .samples
        .iter()
        .filter(|sample| sample.metric == metric)
        .collect()
}

/// Числовое значение ряда.
pub(crate) fn value(sample: &Sample) -> Option<f64> {
    match sample.value {
        Value::Counter(value) | Value::Gauge(value) | Value::Untyped(value) => Some(value),
        Value::Histogram(_) | Value::Summary(_) => None,
    }
}

/// Значение первого числового ряда с именем `metric`.
pub(crate) fn scalar(scrape: &Scrape, metric: &str) -> Option<f64> {
    samples(scrape, metric).into_iter().find_map(value)
}

/// Ряды гистограммы с именем `metric`: пары «граница — накопленное число наблюдений».
pub(crate) fn histogram_buckets(scrape: &Scrape, metric: &str) -> Vec<(f64, f64)> {
    samples(scrape, metric)
        .into_iter()
        .find_map(|sample| match &sample.value {
            Value::Histogram(buckets) => Some(
                buckets
                    .iter()
                    .map(|bucket| (bucket.less_than, bucket.count))
                    .collect(),
            ),
            _ => None,
        })
        .unwrap_or_default()
}

/// Загружает настройку корзин из текста YAML.
pub(crate) fn histogram_config(tag: &str, yaml: &str) -> HistogramConfig {
    let directory =
        std::env::temp_dir().join(format!("metricsplay-tests-{}-{tag}", std::process::id()));
    std::fs::create_dir_all(&directory).expect("the temporary directory");
    std::fs::write(directory.join("config.yaml"), yaml).expect("the configuration file");
    let loaded =
        redup_config::load::<HistogramConfig>(&redup_config::Source::directory(&directory))
            .expect("the configuration is accepted");
    std::fs::remove_dir_all(&directory).ok();
    loaded.value
}