schedr_model/
metric_doc.rs1use std::fmt;
6
7#[cfg(test)]
8mod tests;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum MetricKind {
13 Counter,
15 Gauge,
17 Histogram,
19 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub struct MetricDoc {
37 pub name: &'static str,
39 pub kind: MetricKind,
41 pub labels: &'static [&'static str],
43 pub help: &'static str,
45}
46
47impl MetricDoc {
48 #[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#[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
103fn 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}