nmbrs-workload 0.7.3

Uniform workload specification parsing and processing for nmbrs
Documentation
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! What a key-metric designation holds between its parentheses
//! (SRD-113; SRD-118 ยง10.1): the family, the matchers that select
//! among its series, and for a family of the session sampler the mode
//! its samples are counted by.

use crate::model::KeyMetric;

impl KeyMetric {
    /// The sample modes, in the order they are listed to a user. They
    /// are the values of the `phase_samples` matcher
    /// (`nmbrs_metrics::queryapi::phase_samples`).
    pub const SAMPLE_MODES: &'static [&'static str] =
        &["within", "overlapping", "nearest", "closing"];

    /// The mode a designation of a sampler family has when it names
    /// none.
    pub const DEFAULT_SAMPLES: &'static str = "overlapping";

    /// True when `family` is the session sampler's: recorded by the
    /// session, with no `phase` label, and read over a phase by its
    /// samples' times.
    pub fn is_session_family(family: &str) -> bool {
        family.starts_with("sysmon_")
    }

    /// The mode this designation's samples are counted by, when its
    /// family is the session sampler's.
    pub fn sample_mode(&self) -> Option<&str> {
        Self::is_session_family(&self.family)
            .then(|| self.samples.as_deref().unwrap_or(Self::DEFAULT_SAMPLES))
    }

    /// Read what a designation holds between its parentheses:
    /// `family`, `family{matchers}`, `family, mode` or
    /// `family{matchers}, mode`. Returns the family, the matchers
    /// without their braces, and the mode.
    pub fn parse_measure(inner: &str) -> Result<(String, String, Option<String>), String> {
        let inner = inner.trim();
        let (family, matchers, rest) = match inner.split_once('{') {
            None => match inner.split_once(',') {
                Some((family, mode)) => (family, "", format!(",{mode}")),
                None => (inner, "", String::new()),
            },
            Some((family, after)) => {
                let (matchers, rest) = after.rsplit_once('}').ok_or_else(|| {
                    format!("'{inner}' opens matchers with `{{` and does not close them")
                })?;
                (family, matchers, rest.to_string())
            }
        };
        let rest = rest.trim();
        let samples = match rest.strip_prefix(',') {
            None if rest.is_empty() => None,
            None => {
                return Err(format!(
                    "'{rest}' follows the measure; only `, <sample mode>` may"
                ));
            }
            Some(mode) => {
                let mode = mode.trim();
                if !Self::SAMPLE_MODES.contains(&mode) {
                    return Err(format!(
                        "'{mode}' is not a sample mode; the modes are {}",
                        Self::SAMPLE_MODES.join(", ")
                    ));
                }
                Some(mode.to_string())
            }
        };
        let matchers = matchers.trim();
        for item in split_matchers(matchers) {
            let label = item
                .split(['=', '!', '~'])
                .next()
                .unwrap_or_default()
                .trim();
            let quoted = item.trim_end().ends_with('"') && item.matches('"').count() >= 2;
            if label.is_empty() || label.len() == item.trim().len() || !quoted {
                return Err(format!(
                    "'{}' is not a matcher; a matcher is label=\"value\"",
                    item.trim()
                ));
            }
            if label == "phase" || label == "phase_samples" {
                return Err(format!(
                    "a designation's matchers may not name `{label}`: the designation \
                     is of the phase it is written on"
                ));
            }
        }
        Ok((family.trim().to_string(), matchers.to_string(), samples))
    }
}

/// The matchers of a selector's braces, split at the commas that are
/// not inside a quoted value.
fn split_matchers(text: &str) -> Vec<&str> {
    let mut items = Vec::new();
    let (mut start, mut quoted, mut escaped) = (0, false, false);
    for (at, c) in text.char_indices() {
        match c {
            _ if escaped => escaped = false,
            '\\' if quoted => escaped = true,
            '"' => quoted = !quoted,
            ',' if !quoted => {
                items.push(&text[start..at]);
                start = at + 1;
            }
            _ => {}
        }
    }
    items.push(&text[start..]);
    items.into_iter().filter(|i| !i.trim().is_empty()).collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn read(inner: &str) -> (String, String, Option<String>) {
        KeyMetric::parse_measure(inner).unwrap()
    }

    #[test]
    fn a_measure_is_a_family_with_optional_matchers_and_mode() {
        assert_eq!(
            read("result_success"),
            ("result_success".into(), String::new(), None)
        );
        assert_eq!(
            read(" sysmon_cpu_util , within "),
            (
                "sysmon_cpu_util".into(),
                String::new(),
                Some("within".into())
            )
        );
        assert_eq!(
            read(r#"sysmon_cgroup_io_write_bytes_per_s{cgroup="node", device=~"md.*"}"#),
            (
                "sysmon_cgroup_io_write_bytes_per_s".into(),
                r#"cgroup="node", device=~"md.*""#.into(),
                None
            )
        );
        assert_eq!(
            read(r#"sysmon_proc_rss_bytes{proc="a,b"}, closing"#),
            (
                "sysmon_proc_rss_bytes".into(),
                r#"proc="a,b""#.into(),
                Some("closing".into())
            )
        );
        // `span()` holds nothing.
        assert_eq!(read(""), (String::new(), String::new(), None));
    }

    #[test]
    fn what_is_wrong_with_a_measure_is_said() {
        for (inner, says) in [
            ("sysmon_cpu_util, inside", "'inside' is not a sample mode"),
            ("f{a=\"b\"", "does not close them"),
            ("f{a=\"b\"} within", "only `, <sample mode>` may"),
            ("f{a}", "'a' is not a matcher"),
            ("f{a=b}", "'a=b' is not a matcher"),
            ("f{phase=\"x\"}", "may not name `phase`"),
            (
                "f{phase_samples=\"within\"}",
                "may not name `phase_samples`",
            ),
        ] {
            let err = KeyMetric::parse_measure(inner).unwrap_err();
            assert!(err.contains(says), "{inner}: {err}");
        }
    }

    #[test]
    fn a_sampler_family_has_a_mode_and_another_has_none() {
        let metric = |family: &str, samples: Option<&str>| KeyMetric {
            column: "c".into(),
            agg: crate::model::KeyAgg::Avg,
            family: family.into(),
            matchers: String::new(),
            samples: samples.map(String::from),
        };
        assert_eq!(
            metric("sysmon_cpu_util", None).sample_mode(),
            Some("overlapping")
        );
        assert_eq!(
            metric("sysmon_cpu_util", Some("closing")).sample_mode(),
            Some("closing")
        );
        assert_eq!(metric("result_success", None).sample_mode(), None);
    }
}