Skip to main content

nmbrs_workload/
key_metric.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! What a key-metric designation holds between its parentheses
5//! (SRD-113; SRD-118 §10.1): the family, the matchers that select
6//! among its series, and for a family of the session sampler the mode
7//! its samples are counted by.
8
9use crate::model::KeyMetric;
10
11impl KeyMetric {
12    /// The sample modes, in the order they are listed to a user. They
13    /// are the values of the `phase_samples` matcher
14    /// (`nmbrs_metrics::queryapi::phase_samples`).
15    pub const SAMPLE_MODES: &'static [&'static str] =
16        &["within", "overlapping", "nearest", "closing"];
17
18    /// The mode a designation of a sampler family has when it names
19    /// none.
20    pub const DEFAULT_SAMPLES: &'static str = "overlapping";
21
22    /// True when `family` is the session sampler's: recorded by the
23    /// session, with no `phase` label, and read over a phase by its
24    /// samples' times.
25    pub fn is_session_family(family: &str) -> bool {
26        family.starts_with("sysmon_")
27    }
28
29    /// True when `family` is a phase's own record of a sampler family
30    /// (`sysmon_phases=on`, SRD-118 §11): a series of the phase, which
31    /// carries the same window statistics the sampler's does.
32    pub fn is_phase_host_family(family: &str) -> bool {
33        family.starts_with("phase_sysmon_")
34    }
35
36    /// True when `family` is a host measure, the session's or a
37    /// phase's own.
38    pub fn is_host_family(family: &str) -> bool {
39        Self::is_session_family(family) || Self::is_phase_host_family(family)
40    }
41
42    /// The mode this designation's samples are counted by, when its
43    /// family is the session sampler's.
44    pub fn sample_mode(&self) -> Option<&str> {
45        Self::is_session_family(&self.family)
46            .then(|| self.samples.as_deref().unwrap_or(Self::DEFAULT_SAMPLES))
47    }
48
49    /// Read what a designation holds between its parentheses:
50    /// `family`, `family{matchers}`, `family, mode` or
51    /// `family{matchers}, mode`. Returns the family, the matchers
52    /// without their braces, and the mode.
53    pub fn parse_measure(inner: &str) -> Result<(String, String, Option<String>), String> {
54        let inner = inner.trim();
55        let (family, matchers, rest) = match inner.split_once('{') {
56            None => match inner.split_once(',') {
57                Some((family, mode)) => (family, "", format!(",{mode}")),
58                None => (inner, "", String::new()),
59            },
60            Some((family, after)) => {
61                let (matchers, rest) = after.rsplit_once('}').ok_or_else(|| {
62                    format!("'{inner}' opens matchers with `{{` and does not close them")
63                })?;
64                (family, matchers, rest.to_string())
65            }
66        };
67        let rest = rest.trim();
68        let samples = match rest.strip_prefix(',') {
69            None if rest.is_empty() => None,
70            None => {
71                return Err(format!(
72                    "'{rest}' follows the measure; only `, <sample mode>` may"
73                ));
74            }
75            Some(mode) => {
76                let mode = mode.trim();
77                if !Self::SAMPLE_MODES.contains(&mode) {
78                    return Err(format!(
79                        "'{mode}' is not a sample mode; the modes are {}",
80                        Self::SAMPLE_MODES.join(", ")
81                    ));
82                }
83                Some(mode.to_string())
84            }
85        };
86        let matchers = matchers.trim();
87        for item in split_matchers(matchers) {
88            let label = item
89                .split(['=', '!', '~'])
90                .next()
91                .unwrap_or_default()
92                .trim();
93            let quoted = item.trim_end().ends_with('"') && item.matches('"').count() >= 2;
94            if label.is_empty() || label.len() == item.trim().len() || !quoted {
95                return Err(format!(
96                    "'{}' is not a matcher; a matcher is label=\"value\"",
97                    item.trim()
98                ));
99            }
100            if label == "phase" || label == "phase_samples" {
101                return Err(format!(
102                    "a designation's matchers may not name `{label}`: the designation \
103                     is of the phase it is written on"
104                ));
105            }
106        }
107        Ok((family.trim().to_string(), matchers.to_string(), samples))
108    }
109}
110
111/// The matchers of a selector's braces, split at the commas that are
112/// not inside a quoted value.
113fn split_matchers(text: &str) -> Vec<&str> {
114    let mut items = Vec::new();
115    let (mut start, mut quoted, mut escaped) = (0, false, false);
116    for (at, c) in text.char_indices() {
117        match c {
118            _ if escaped => escaped = false,
119            '\\' if quoted => escaped = true,
120            '"' => quoted = !quoted,
121            ',' if !quoted => {
122                items.push(&text[start..at]);
123                start = at + 1;
124            }
125            _ => {}
126        }
127    }
128    items.push(&text[start..]);
129    items.into_iter().filter(|i| !i.trim().is_empty()).collect()
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135
136    fn read(inner: &str) -> (String, String, Option<String>) {
137        KeyMetric::parse_measure(inner).unwrap()
138    }
139
140    #[test]
141    fn a_measure_is_a_family_with_optional_matchers_and_mode() {
142        assert_eq!(
143            read("result_success"),
144            ("result_success".into(), String::new(), None)
145        );
146        assert_eq!(
147            read(" sysmon_cpu_util , within "),
148            (
149                "sysmon_cpu_util".into(),
150                String::new(),
151                Some("within".into())
152            )
153        );
154        assert_eq!(
155            read(r#"sysmon_cgroup_io_write_bytes_per_s{cgroup="node", device=~"md.*"}"#),
156            (
157                "sysmon_cgroup_io_write_bytes_per_s".into(),
158                r#"cgroup="node", device=~"md.*""#.into(),
159                None
160            )
161        );
162        assert_eq!(
163            read(r#"sysmon_proc_rss_bytes{proc="a,b"}, closing"#),
164            (
165                "sysmon_proc_rss_bytes".into(),
166                r#"proc="a,b""#.into(),
167                Some("closing".into())
168            )
169        );
170        // `span()` holds nothing.
171        assert_eq!(read(""), (String::new(), String::new(), None));
172    }
173
174    #[test]
175    fn what_is_wrong_with_a_measure_is_said() {
176        for (inner, says) in [
177            ("sysmon_cpu_util, inside", "'inside' is not a sample mode"),
178            ("f{a=\"b\"", "does not close them"),
179            ("f{a=\"b\"} within", "only `, <sample mode>` may"),
180            ("f{a}", "'a' is not a matcher"),
181            ("f{a=b}", "'a=b' is not a matcher"),
182            ("f{phase=\"x\"}", "may not name `phase`"),
183            (
184                "f{phase_samples=\"within\"}",
185                "may not name `phase_samples`",
186            ),
187        ] {
188            let err = KeyMetric::parse_measure(inner).unwrap_err();
189            assert!(err.contains(says), "{inner}: {err}");
190        }
191    }
192
193    #[test]
194    fn a_sampler_family_has_a_mode_and_another_has_none() {
195        let metric = |family: &str, samples: Option<&str>| KeyMetric {
196            column: "c".into(),
197            agg: crate::model::KeyAgg::Avg,
198            family: family.into(),
199            matchers: String::new(),
200            samples: samples.map(String::from),
201        };
202        assert_eq!(
203            metric("sysmon_cpu_util", None).sample_mode(),
204            Some("overlapping")
205        );
206        assert_eq!(
207            metric("sysmon_cpu_util", Some("closing")).sample_mode(),
208            Some("closing")
209        );
210        assert_eq!(metric("result_success", None).sample_mode(), None);
211    }
212}