Skip to main content

schedr_model/
metric_doc.rs

1//! What each metric is, for the code that registers it and for the metrics reference in the
2//! documentation (see archive/PROJECT.md, Observability): one list per role, so the name and help
3//! text are written once, and a test per role checks the type and labels against a scrape.
4
5use std::fmt;
6
7#[cfg(test)]
8mod tests;
9
10/// A metric's type, as a scrape shows it.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum MetricKind {
13    /// Only goes up; shown with `_total`.
14    Counter,
15    /// Goes up and down.
16    Gauge,
17    /// Counts observations into buckets; shown with `_bucket`, `_sum` and `_count`.
18    Histogram,
19    /// A constant labelled 1; shown with `_info`.
20    Info,
21}
22
23impl fmt::Display for MetricKind {
24    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25        f.write_str(match self {
26            Self::Counter => "counter",
27            Self::Gauge => "gauge",
28            Self::Histogram => "histogram",
29            Self::Info => "info",
30        })
31    }
32}
33
34/// One metric: the name it is registered under, its type, labels and help text.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub struct MetricDoc {
37    /// The name as registered (without the registry's prefix or the type's suffix).
38    pub name: &'static str,
39    /// Its type.
40    pub kind: MetricKind,
41    /// Its label names.
42    pub labels: &'static [&'static str],
43    /// What it measures.
44    pub help: &'static str,
45}
46
47impl MetricDoc {
48    /// The name in a scrape's samples under `prefix` (e.g. `schedr`): with `_total` for a
49    /// counter and `_info` for an info metric.
50    #[must_use]
51    pub fn exposed(&self, prefix: Option<&str>) -> String {
52        let suffix = match self.kind {
53            MetricKind::Counter => "_total",
54            MetricKind::Info => "_info",
55            MetricKind::Gauge | MetricKind::Histogram => "",
56        };
57        match prefix {
58            Some(prefix) => format!("{prefix}_{}{suffix}", self.name),
59            None => format!("{}{suffix}", self.name),
60        }
61    }
62}
63
64/// What doesn't match between `docs` and a `scrape` (the text format) of a registry under
65/// `prefix` that holds them, every label family having a member: a metric missing from the
66/// scrape or with another type, help text or label names, and a metric the scrape has but
67/// `docs` doesn't. Empty when they match.
68#[must_use]
69pub fn scrape_mismatches(scrape: &str, prefix: Option<&str>, docs: &[MetricDoc]) -> Vec<String> {
70    let base = |doc: &MetricDoc| match prefix {
71        Some(prefix) => format!("{prefix}_{}", doc.name),
72        None => doc.name.to_owned(),
73    };
74    let mut wrong = Vec::new();
75    let typed: Vec<(&str, &str)> = scrape
76        .lines()
77        .filter_map(|line| line.strip_prefix("# TYPE ")?.split_once(' '))
78        .collect();
79    for (name, _) in &typed {
80        if !docs.iter().any(|doc| base(doc) == *name) {
81            wrong.push(format!("`{name}` is not documented"));
82        }
83    }
84    for doc in docs {
85        let name = base(doc);
86        let kind = doc.kind.to_string();
87        if !typed.contains(&(name.as_str(), kind.as_str())) {
88            wrong.push(format!("`{name}` isn't in the scrape as a {kind}"));
89            continue;
90        }
91        if !scrape.contains(&format!("# HELP {name} {}.\n", doc.help)) {
92            wrong.push(format!("`{name}` has other help text"));
93        }
94        for labels in samples(scrape, &name) {
95            if labels != doc.labels {
96                wrong.push(format!("`{name}` has the labels {labels:?}"));
97            }
98        }
99    }
100    wrong
101}
102
103/// The label names of each sample of the metric `name` (`le` left out).
104fn samples<'a>(scrape: &'a str, name: &str) -> Vec<Vec<&'a str>> {
105    let suffixes = ["", "_total", "_info", "_bucket", "_sum", "_count"];
106    scrape
107        .lines()
108        .filter(|line| !line.starts_with('#'))
109        .filter(|line| {
110            let sample = line.split(['{', ' ']).next().unwrap_or_default();
111            suffixes.iter().any(|s| sample == format!("{name}{s}"))
112        })
113        .map(|line| {
114            let Some((_, rest)) = line.split_once('{') else {
115                return Vec::new();
116            };
117            rest.split("\",")
118                .filter_map(|pair| pair.split_once('=').map(|(key, _)| key))
119                .filter(|key| *key != "le")
120                .collect()
121        })
122        .collect()
123}