1use crate::model::KeyMetric;
10
11impl KeyMetric {
12 pub const SAMPLE_MODES: &'static [&'static str] =
16 &["within", "overlapping", "nearest", "closing"];
17
18 pub const DEFAULT_SAMPLES: &'static str = "overlapping";
21
22 pub fn is_session_family(family: &str) -> bool {
26 family.starts_with("sysmon_")
27 }
28
29 pub fn sample_mode(&self) -> Option<&str> {
32 Self::is_session_family(&self.family)
33 .then(|| self.samples.as_deref().unwrap_or(Self::DEFAULT_SAMPLES))
34 }
35
36 pub fn parse_measure(inner: &str) -> Result<(String, String, Option<String>), String> {
41 let inner = inner.trim();
42 let (family, matchers, rest) = match inner.split_once('{') {
43 None => match inner.split_once(',') {
44 Some((family, mode)) => (family, "", format!(",{mode}")),
45 None => (inner, "", String::new()),
46 },
47 Some((family, after)) => {
48 let (matchers, rest) = after.rsplit_once('}').ok_or_else(|| {
49 format!("'{inner}' opens matchers with `{{` and does not close them")
50 })?;
51 (family, matchers, rest.to_string())
52 }
53 };
54 let rest = rest.trim();
55 let samples = match rest.strip_prefix(',') {
56 None if rest.is_empty() => None,
57 None => {
58 return Err(format!(
59 "'{rest}' follows the measure; only `, <sample mode>` may"
60 ));
61 }
62 Some(mode) => {
63 let mode = mode.trim();
64 if !Self::SAMPLE_MODES.contains(&mode) {
65 return Err(format!(
66 "'{mode}' is not a sample mode; the modes are {}",
67 Self::SAMPLE_MODES.join(", ")
68 ));
69 }
70 Some(mode.to_string())
71 }
72 };
73 let matchers = matchers.trim();
74 for item in split_matchers(matchers) {
75 let label = item
76 .split(['=', '!', '~'])
77 .next()
78 .unwrap_or_default()
79 .trim();
80 let quoted = item.trim_end().ends_with('"') && item.matches('"').count() >= 2;
81 if label.is_empty() || label.len() == item.trim().len() || !quoted {
82 return Err(format!(
83 "'{}' is not a matcher; a matcher is label=\"value\"",
84 item.trim()
85 ));
86 }
87 if label == "phase" || label == "phase_samples" {
88 return Err(format!(
89 "a designation's matchers may not name `{label}`: the designation \
90 is of the phase it is written on"
91 ));
92 }
93 }
94 Ok((family.trim().to_string(), matchers.to_string(), samples))
95 }
96}
97
98fn split_matchers(text: &str) -> Vec<&str> {
101 let mut items = Vec::new();
102 let (mut start, mut quoted, mut escaped) = (0, false, false);
103 for (at, c) in text.char_indices() {
104 match c {
105 _ if escaped => escaped = false,
106 '\\' if quoted => escaped = true,
107 '"' => quoted = !quoted,
108 ',' if !quoted => {
109 items.push(&text[start..at]);
110 start = at + 1;
111 }
112 _ => {}
113 }
114 }
115 items.push(&text[start..]);
116 items.into_iter().filter(|i| !i.trim().is_empty()).collect()
117}
118
119#[cfg(test)]
120mod tests {
121 use super::*;
122
123 fn read(inner: &str) -> (String, String, Option<String>) {
124 KeyMetric::parse_measure(inner).unwrap()
125 }
126
127 #[test]
128 fn a_measure_is_a_family_with_optional_matchers_and_mode() {
129 assert_eq!(
130 read("result_success"),
131 ("result_success".into(), String::new(), None)
132 );
133 assert_eq!(
134 read(" sysmon_cpu_util , within "),
135 (
136 "sysmon_cpu_util".into(),
137 String::new(),
138 Some("within".into())
139 )
140 );
141 assert_eq!(
142 read(r#"sysmon_cgroup_io_write_bytes_per_s{cgroup="node", device=~"md.*"}"#),
143 (
144 "sysmon_cgroup_io_write_bytes_per_s".into(),
145 r#"cgroup="node", device=~"md.*""#.into(),
146 None
147 )
148 );
149 assert_eq!(
150 read(r#"sysmon_proc_rss_bytes{proc="a,b"}, closing"#),
151 (
152 "sysmon_proc_rss_bytes".into(),
153 r#"proc="a,b""#.into(),
154 Some("closing".into())
155 )
156 );
157 assert_eq!(read(""), (String::new(), String::new(), None));
159 }
160
161 #[test]
162 fn what_is_wrong_with_a_measure_is_said() {
163 for (inner, says) in [
164 ("sysmon_cpu_util, inside", "'inside' is not a sample mode"),
165 ("f{a=\"b\"", "does not close them"),
166 ("f{a=\"b\"} within", "only `, <sample mode>` may"),
167 ("f{a}", "'a' is not a matcher"),
168 ("f{a=b}", "'a=b' is not a matcher"),
169 ("f{phase=\"x\"}", "may not name `phase`"),
170 (
171 "f{phase_samples=\"within\"}",
172 "may not name `phase_samples`",
173 ),
174 ] {
175 let err = KeyMetric::parse_measure(inner).unwrap_err();
176 assert!(err.contains(says), "{inner}: {err}");
177 }
178 }
179
180 #[test]
181 fn a_sampler_family_has_a_mode_and_another_has_none() {
182 let metric = |family: &str, samples: Option<&str>| KeyMetric {
183 column: "c".into(),
184 agg: crate::model::KeyAgg::Avg,
185 family: family.into(),
186 matchers: String::new(),
187 samples: samples.map(String::from),
188 };
189 assert_eq!(
190 metric("sysmon_cpu_util", None).sample_mode(),
191 Some("overlapping")
192 );
193 assert_eq!(
194 metric("sysmon_cpu_util", Some("closing")).sample_mode(),
195 Some("closing")
196 );
197 assert_eq!(metric("result_success", None).sample_mode(), None);
198 }
199}