1use nmbrs_workload::model::{StopConditionSpec, WorkloadPhase};
37
38const ACTIVITY_FAMILIES: [&str; 18] = [
43 "cycles_servicetime",
44 "cycles_waittime",
45 "cycles_responsetime",
46 "result_success",
47 "result_failure",
48 "result_total",
49 "cycles_total",
50 "skips_total",
51 "errors_total",
52 "attempt_total",
53 "attempt_success",
54 "attempt_failure",
55 "stanzas_total",
56 "daemon_cancelled_total",
57 "daemon_errors_total",
58 "result_elements",
59 "result_bytes",
60 "tries",
61];
62
63pub fn lint_workload<'a>(
67 workload_stop_when: &[StopConditionSpec],
68 phases: impl Iterator<Item = (&'a str, &'a WorkloadPhase)> + Clone,
69) -> Result<Vec<String>, String> {
70 let mut warnings = Vec::new();
71
72 let mut known: Vec<String> = ACTIVITY_FAMILIES.iter().map(|s| s.to_string()).collect();
76 for (_, phase) in phases.clone() {
77 known.extend(phase.metrics.keys().cloned());
78 }
79
80 for sc in workload_stop_when {
81 lint_metric_families(&sc.when, &known, "workload `stop_when`", &mut warnings);
82 }
83
84 for (name, phase) in phases {
85 let ctx = format!("phase '{name}'");
86 if let Some(spec) = phase.errors.as_deref() {
87 lint_error_router(spec, &ctx, &mut warnings)?;
88 }
89 for op in &phase.ops {
90 if let Some(serde_json::Value::String(spec)) = op.params.get("errors") {
91 lint_error_router(spec, &format!("{ctx} op '{}'", op.name), &mut warnings)?;
92 }
93 }
94 for sc in &phase.stop_when {
95 lint_metric_families(
96 &sc.when,
97 &known,
98 &format!("{ctx} `stop_when`"),
99 &mut warnings,
100 );
101 }
102 if let Some(gate) = &phase.continue_if {
103 lint_metric_families(
104 &gate.when,
105 &known,
106 &format!("{ctx} `continue_if`"),
107 &mut warnings,
108 );
109 }
110 if let Some(poll) = &phase.poll {
111 lint_metric_families(
112 &poll.until,
113 &known,
114 &format!("{ctx} `poll.until`"),
115 &mut warnings,
116 );
117 }
118 }
119
120 Ok(warnings)
121}
122
123fn lint_error_router(spec: &str, ctx: &str, warnings: &mut Vec<String>) -> Result<(), String> {
127 if spec.contains('{') {
128 return Ok(()); }
130 let router = nmbrs_errorhandler::ErrorRouter::parse(spec)
131 .map_err(|e| format!("{ctx}: invalid `errors:` spec '{spec}': {e}"))?;
132 if !router.has_catch_all() {
133 warnings.push(format!(
134 "{ctx}: `errors: \"{spec}\"` has no catch-all rule — an error \
135 class matching no pattern falls through to `stop`; end the \
136 spec with `.*:<verbs>` to make the default explicit"
137 ));
138 }
139 Ok(())
140}
141
142fn lint_metric_families(src: &str, known: &[String], ctx: &str, warnings: &mut Vec<String>) {
146 for family in metric_families(src) {
147 if family.contains('{') {
148 continue; }
150 if !known.iter().any(|k| k == &family) && !crate::adapter::adapter_publishes_family(&family)
151 {
152 warnings.push(format!(
153 "{ctx}: `metric()` selector names family '{family}', which is \
154 not a built-in instrument family, a declared phase metric, or a \
155 family an adapter publishes — \
156 an unregistered family reads 0.0 silently; check the spelling \
157 (predicate: {src})"
158 ));
159 }
160 }
161}
162
163fn metric_families(src: &str) -> Vec<String> {
168 let bytes = src.as_bytes();
169 let mut out = Vec::new();
170 let mut i = 0;
171 while let Some(rel) = src[i..].find("metric") {
172 let start = i + rel;
173 i = start + "metric".len();
174 if start > 0 {
176 let prev = bytes[start - 1] as char;
177 if prev.is_alphanumeric() || prev == '_' {
178 continue;
179 }
180 }
181 let mut j = i;
183 if src[j..].starts_with("_window") {
184 j += "_window".len();
185 }
186 let rest = src[j..].trim_start();
187 let Some(after_paren) = rest.strip_prefix('(') else {
188 continue;
189 };
190 let sel = after_paren.trim_start();
191 let Some(quote) = sel.chars().next().filter(|c| *c == '\'' || *c == '"') else {
192 continue; };
194 let body = &sel[1..];
195 let Some(end) = body.find(quote) else {
196 continue;
197 };
198 let selector = &body[..end];
199 let family = selector.split(',').next().unwrap_or("").trim().to_string();
200 if !family.is_empty() {
201 out.push(family);
202 }
203 }
204 out
205}
206
207#[cfg(test)]
208mod tests {
209 use super::*;
210
211 #[test]
212 fn extracts_families_from_both_call_forms() {
213 let src = "metric('cycles_total, phase=ingest', 'count') >= 5 \
214 && metric_window(\"result_failure\", 'rate') < 0.1";
215 assert_eq!(
216 metric_families(src),
217 vec!["cycles_total".to_string(), "result_failure".to_string()]
218 );
219 }
220
221 #[test]
222 fn ignores_non_literal_selectors_and_other_identifiers() {
223 assert!(metric_families("my_metric('x','count') + metric(fam, 'count')").is_empty());
224 }
225
226 #[test]
227 fn unknown_family_warns_known_family_does_not() {
228 let known: Vec<String> = ACTIVITY_FAMILIES.iter().map(|s| s.to_string()).collect();
229 let mut w = Vec::new();
230 lint_metric_families(
231 "metric('cycles_totl, phase=x', 'count') > 0",
232 &known,
233 "t",
234 &mut w,
235 );
236 assert_eq!(w.len(), 1, "typo'd family must warn: {w:?}");
237 w.clear();
238 lint_metric_families(
239 "metric('cycles_total, phase=x', 'count') > 0",
240 &known,
241 "t",
242 &mut w,
243 );
244 assert!(w.is_empty(), "known family must not warn: {w:?}");
245 }
246
247 #[test]
248 fn router_without_catch_all_warns_with_catch_all_does_not() {
249 let mut w = Vec::new();
250 lint_error_router("TimeoutError:retry,warn", "t", &mut w).unwrap();
251 assert_eq!(w.len(), 1, "no catch-all must warn: {w:?}");
252 w.clear();
253 lint_error_router("TimeoutError:retry,warn;.*:counter", "t", &mut w).unwrap();
254 assert!(w.is_empty(), "catch-all present must not warn: {w:?}");
255 }
256
257 #[test]
258 fn bad_router_spec_is_a_load_error_interpolated_is_deferred() {
259 let mut w = Vec::new();
260 let err = lint_error_router(".*:sotp", "phase 'p'", &mut w).unwrap_err();
261 assert!(err.contains("unknown error handler"), "got: {err}");
262 lint_error_router("{overload_policy}", "t", &mut w)
263 .expect("interpolated spec must be deferred, not parsed");
264 }
265}