1use std::path::Path;
62use std::sync::{Arc, Mutex};
63use std::time::Duration;
64
65use bytes::Bytes;
66use http_body_util::{BodyExt, Full};
67use mira_core::json::Json;
68use mira_core::query::{self, Op, Search, Signal, Target, Term, Value};
69use yaml_rust2::Yaml;
70
71use crate::api::{self, Api};
72use crate::config;
73
74pub struct Rules {
76 pub every: Duration,
78 pub link_base: String,
82 pub rules: Vec<Rule>,
83 pub targets: Vec<Target_>,
84}
85
86pub struct Rule {
87 pub name: String,
88 query: Search,
90 of: Option<Search>,
92 over: Duration,
93 metric: Metric,
94 cmp: Cmp,
95 threshold: f64,
96 hold: Duration,
99 severity: String,
100 notify: Vec<usize>,
103}
104
105pub struct Target_ {
112 pub name: String,
113 url: String,
114 format: Format,
115 key: String,
117}
118
119#[derive(Clone, Copy, PartialEq, Eq)]
120enum Format {
121 Slack,
122 Discord,
123 Pagerduty,
124 Json,
126}
127
128#[derive(Clone, Copy, PartialEq, Eq)]
129enum Metric {
130 Count,
131 Ratio,
132}
133
134#[derive(Clone, Copy)]
135enum Cmp {
136 Gt,
137 Gte,
138 Lt,
139 Lte,
140}
141
142impl Cmp {
143 fn holds(self, v: f64, t: f64) -> bool {
144 match self {
145 Cmp::Gt => v > t,
146 Cmp::Gte => v >= t,
147 Cmp::Lt => v < t,
148 Cmp::Lte => v <= t,
149 }
150 }
151
152 fn breaches(self, v: f64, t: f64, total: Option<usize>) -> bool {
162 total != Some(0) && self.holds(v, t)
163 }
164
165 fn as_str(self) -> &'static str {
166 match self {
167 Cmp::Gt => ">",
168 Cmp::Gte => ">=",
169 Cmp::Lt => "<",
170 Cmp::Lte => "<=",
171 }
172 }
173}
174
175#[derive(Default, Clone)]
177pub struct State {
178 since: Option<i64>,
182 firing: Option<i64>,
183 value: f64,
184 matched: usize,
185 total: Option<usize>,
186 error: Option<String>,
189 at: i64,
190}
191
192impl State {
193 fn advance(&mut self, breaching: bool, now: i64, hold: i64) -> Option<bool> {
203 match (breaching, self.since, self.firing) {
204 (false, _, Some(_)) => {
205 (self.since, self.firing) = (None, None);
206 Some(false)
207 }
208 (false, _, None) => {
209 self.since = None;
210 None
211 }
212 (true, None, _) => {
213 self.since = Some(now);
214 (hold == 0).then(|| {
217 self.firing = Some(now);
218 true
219 })
220 }
221 (true, Some(began), None) if now - began >= hold => {
222 self.firing = Some(now);
223 Some(true)
224 }
225 (true, Some(_), _) => None,
226 }
227 }
228
229 fn phase(&self) -> &'static str {
230 match (self.firing.is_some(), self.since.is_some()) {
231 (true, _) => "firing",
232 (_, true) => "pending",
233 _ => "ok",
234 }
235 }
236}
237
238impl Rules {
241 pub fn off() -> Rules {
244 Rules {
245 every: Duration::from_secs(15),
246 link_base: String::new(),
247 rules: Vec::new(),
248 targets: Vec::new(),
249 }
250 }
251
252 pub fn load(path: &Path) -> Result<Rules, String> {
253 let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
254 Rules::parse(&text).map_err(|e| format!("{}: {e}", path.display()))
255 }
256
257 pub fn parse(text: &str) -> Result<Rules, String> {
258 let doc = api::parse(text)?;
259 api::known(&doc, &["every", "link_base", "notify", "rules"])?;
260 let every = match doc["every"].as_str() {
261 Some(s) => config::duration(s).map_err(|e| format!("every: {e}"))?,
262 None => Duration::from_secs(15),
263 };
264 let link_base = match &doc["link_base"] {
265 Yaml::BadValue | Yaml::Null => String::new(),
266 y => y
267 .as_str()
268 .ok_or("link_base must be a quoted string")?
269 .trim_end_matches('/')
270 .to_owned(),
271 };
272 let targets = match &doc["notify"] {
273 Yaml::BadValue | Yaml::Null => Vec::new(),
274 Yaml::Array(a) => a.iter().map(target).collect::<Result<Vec<_>, _>>()?,
275 _ => return Err("`notify` must be a list of webhook targets".into()),
276 };
277 let rules = match &doc["rules"] {
278 Yaml::Array(a) => a
279 .iter()
280 .map(|y| rule(y, &targets))
281 .collect::<Result<Vec<_>, _>>()?,
282 _ => return Err("`rules` must be a list of rules".into()),
283 };
284 for (i, r) in rules.iter().enumerate() {
289 if rules[..i].iter().any(|o| o.name == r.name) {
290 return Err(format!("two rules named {:?}", r.name));
291 }
292 }
293 Ok(Rules {
294 every,
295 link_base,
296 rules,
297 targets,
298 })
299 }
300}
301
302fn target(y: &Yaml) -> Result<Target_, String> {
303 api::known(y, &["name", "url", "format", "key"])?;
304 let name = y["name"]
305 .as_str()
306 .ok_or("a notify target needs a quoted `name`")?
307 .to_owned();
308 let url = y["url"]
309 .as_str()
310 .ok_or_else(|| format!("notify {name:?}: needs a quoted `url`"))?
311 .to_owned();
312 let format = match y["format"].as_str().unwrap_or("json") {
313 "slack" => Format::Slack,
314 "discord" => Format::Discord,
315 "pagerduty" => Format::Pagerduty,
316 "json" => Format::Json,
317 other => {
318 return Err(format!(
319 "notify {name:?}: unknown format {other:?}; expected slack discord pagerduty json"
320 ));
321 }
322 };
323 if url.starts_with("https://") && !cfg!(feature = "webhook-tls") {
324 return Err(format!(
327 "notify {name:?}: this build posts over HTTP only. Rebuild with \
328 `--features webhook-tls` for a direct https:// target, or point it \
329 at a local egress proxy."
330 ));
331 }
332 if !url.starts_with("http://") && !url.starts_with("https://") {
333 return Err(format!("notify {name:?}: url must be http:// or https://"));
334 }
335 if format == Format::Pagerduty && y["key"].as_str().unwrap_or_default().is_empty() {
336 return Err(format!(
337 "notify {name:?}: pagerduty needs `key`, the Events v2 routing key"
338 ));
339 }
340 Ok(Target_ {
341 name,
342 url,
343 format,
344 key: y["key"].as_str().unwrap_or_default().to_owned(),
345 })
346}
347
348pub(crate) fn rule(y: &Yaml, targets: &[Target_]) -> Result<Rule, String> {
349 api::known(
350 y,
351 &[
352 "name", "query", "of", "over", "when", "for", "severity", "notify",
353 ],
354 )?;
355 let name = y["name"]
356 .as_str()
357 .ok_or("a rule needs a quoted `name`")?
358 .to_owned();
359 let at = |e: String| format!("rule {name:?}: {e}");
360 let query = windowless(&y["query"], "query").map_err(at)?;
361 let of = match &y["of"] {
362 Yaml::BadValue | Yaml::Null => None,
363 d => Some(windowless(d, "of").map_err(at)?),
364 };
365 let over = config::duration(y["over"].as_str().unwrap_or("1m")).map_err(&at)?;
366 let hold = config::duration(y["for"].as_str().unwrap_or("0s")).map_err(&at)?;
367 let (metric, cmp, threshold) = when(y["when"].as_str().unwrap_or_default()).map_err(at)?;
368 if metric == Metric::Ratio && of.is_none() {
369 return Err(at("`ratio` needs `of`, the denominator query".into()));
370 }
371 if metric == Metric::Count && of.is_some() {
372 return Err(at(
373 "`of` is the denominator of a `ratio`; `count` has none".into()
374 ));
375 }
376 let notify = match &y["notify"] {
377 Yaml::BadValue | Yaml::Null => Vec::new(),
381 Yaml::Array(a) => a
382 .iter()
383 .map(|n| {
384 let n = n
385 .as_str()
386 .ok_or_else(|| at("notify names are strings".into()))?;
387 targets
388 .iter()
389 .position(|t| t.name == n)
390 .ok_or_else(|| at(format!("notify {n:?} is not a target in `notify`")))
391 })
392 .collect::<Result<Vec<_>, _>>()?,
393 _ => return Err(at("`notify` must be a list of target names".into())),
394 };
395 Ok(Rule {
396 name,
397 query,
398 of,
399 over,
400 metric,
401 cmp,
402 threshold,
403 hold,
404 severity: y["severity"].as_str().unwrap_or("warning").to_owned(),
405 notify,
406 })
407}
408
409fn windowless(doc: &Yaml, field: &str) -> Result<Search, String> {
416 if doc.is_badvalue() || doc.is_null() {
417 return Err(format!("`{field}` is required and is a query document"));
418 }
419 for k in ["from", "to", "limit", "after"] {
420 if !doc[k].is_badvalue() {
421 return Err(format!(
422 "{field}: `{k}` is the engine's; the window is `over` and the \
423 limit is always zero because this counts rather than reads"
424 ));
425 }
426 }
427 let mut s = api::search_doc(doc, 0)?;
428 s.limit = 0;
429 Ok(s)
430}
431
432fn when(s: &str) -> Result<(Metric, Cmp, f64), String> {
437 let bad = || {
438 format!(
439 "when: expected `count <op> <number>` or `ratio <op> <number>`, \
440 op one of > >= < <=, got {s:?}"
441 )
442 };
443 let (cmp, at) = [
445 (Cmp::Gte, ">="),
446 (Cmp::Lte, "<="),
447 (Cmp::Gt, ">"),
448 (Cmp::Lt, "<"),
449 ]
450 .into_iter()
451 .find_map(|(c, sym)| s.find(sym).map(|i| (c, (i, sym.len()))))
452 .ok_or_else(bad)?;
453 let metric = match s[..at.0].trim() {
454 "count" => Metric::Count,
455 "ratio" => Metric::Ratio,
456 _ => return Err(bad()),
457 };
458 let rhs = s[at.0 + at.1..].trim();
459 let (num, scale) = match rhs.strip_suffix('%') {
462 Some(n) => (n.trim(), 0.01),
463 None => (rhs, 1.0),
464 };
465 let v: f64 = num.parse().map_err(|_| bad())?;
466 Ok((metric, cmp, v * scale))
467}
468
469pub struct Engine {
472 pub rules: Rules,
473 state: Mutex<Vec<State>>,
474}
475
476impl Default for Engine {
477 fn default() -> Engine {
478 Engine::new(Rules::off())
479 }
480}
481
482impl Engine {
483 pub fn new(rules: Rules) -> Engine {
484 let state = Mutex::new(vec![State::default(); rules.rules.len()]);
485 Engine { rules, state }
486 }
487
488 pub async fn tick(&self, api: &Api) {
490 let now = api::now_nanos();
491 for (i, r) in self.rules.rules.iter().enumerate() {
492 let (value, matched, total, error) = match count_pair(api, r, now).await {
493 Ok(v) => v,
494 Err(e) => {
495 let mut st = self.state.lock().expect("alert state");
496 st[i].error = Some(e.clone());
497 st[i].at = now;
498 tracing::warn!(rule = %r.name, error = %e, "alert rule failed");
499 continue;
500 }
501 };
502 let breaching = r.cmp.breaches(value, r.threshold, total);
503
504 let event = {
508 let mut st = self.state.lock().expect("alert state");
509 let s = &mut st[i];
510 (s.value, s.matched, s.total, s.error, s.at) = (value, matched, total, error, now);
511 s.advance(breaching, now, r.hold.as_nanos() as i64)
512 .map(|firing| (firing, s.clone()))
513 };
514 if let Some((firing, snapshot)) = event {
515 self.dispatch(r, &snapshot, firing).await;
516 }
517 }
518 }
519
520 async fn dispatch(&self, r: &Rule, s: &State, firing: bool) {
521 tracing::info!(
522 rule = %r.name, severity = %r.severity, value = s.value,
523 state = if firing { "firing" } else { "resolved" },
524 "alert"
525 );
526 let link = link(&self.rules.link_base, r);
527 for &t in &r.notify {
528 let t = &self.rules.targets[t];
529 let body = payload(t, r, s, firing, &link);
530 if let Err(e) = post(&t.url, body).await {
531 tracing::warn!(rule = %r.name, target = %t.name, error = %e, "webhook failed");
532 }
533 }
534 }
535
536 pub fn json(&self) -> String {
538 let st = self.state.lock().expect("alert state");
539 let mut j = Json::new();
540 j.obj(|j| {
541 j.key("alerts");
542 j.arr(|j| {
543 for (r, s) in self.rules.rules.iter().zip(st.iter()) {
544 j.obj(|j| {
545 j.key("name");
546 j.str(&r.name);
547 j.key("state");
548 j.str(s.phase());
549 j.key("severity");
550 j.str(&r.severity);
551 j.key("metric");
552 j.str(match r.metric {
553 Metric::Count => "count",
554 Metric::Ratio => "ratio",
555 });
556 j.key("op");
557 j.str(r.cmp.as_str());
558 j.key("threshold");
559 j.f64(r.threshold);
560 j.key("value");
561 j.f64(s.value);
562 j.key("matched");
563 j.u64(s.matched as u64);
564 j.key("total");
565 match s.total {
566 Some(t) => j.u64(t as u64),
567 None => j.null(),
568 }
569 j.key("over_nano");
570 j.u64_str(r.over.as_nanos() as u64);
571 j.key("for_nano");
572 j.u64_str(r.hold.as_nanos() as u64);
573 j.key("since");
574 match s.since {
575 Some(t) => j.i64_str(t),
576 None => j.null(),
577 }
578 j.key("firing_since");
579 match s.firing {
580 Some(t) => j.i64_str(t),
581 None => j.null(),
582 }
583 j.key("evaluated_at");
584 j.i64_str(s.at);
585 j.key("signal");
586 j.str(signal_name(r));
587 j.key("filter");
590 j.str(&filter_of(&r.query.terms));
591 j.key("link");
592 j.str(&link(&self.rules.link_base, r));
593 j.key("error");
594 match &s.error {
595 Some(e) => j.str(e),
596 None => j.null(),
597 }
598 });
599 }
600 });
601 j.key("every_nano");
602 j.u64_str(self.rules.every.as_nanos() as u64);
603 });
604 j.into_string()
605 }
606}
607
608async fn count_pair(
614 api: &Api,
615 r: &Rule,
616 now: i64,
617) -> Result<(f64, usize, Option<usize>, Option<String>), String> {
618 let from = now - r.over.as_nanos() as i64;
619 let matched = count(api, &r.query, from, now).await?;
620 let total = match &r.of {
621 Some(q) => Some(count(api, q, from, now).await?),
622 None => None,
623 };
624 let value = match (r.metric, total) {
625 (Metric::Count, _) => matched as f64,
626 (Metric::Ratio, Some(0)) | (Metric::Ratio, None) => 0.0,
630 (Metric::Ratio, Some(t)) => matched as f64 / t as f64,
631 };
632 Ok((value, matched, total, None))
633}
634
635async fn count(api: &Api, q: &Search, from: i64, to: i64) -> Result<usize, String> {
636 let mut q = q.clone();
637 (q.from, q.to, q.limit) = (from, to, 0);
638 let dir = api.data_dir.clone();
639 let open = api.open(q.signal.dir()).await;
640 tokio::task::spawn_blocking(move || query::search_open(&dir, &q, &open))
644 .await
645 .map_err(|e| e.to_string())?
646 .map(|r| r.stats.rows_matched)
647 .map_err(|e| e.to_string())
648}
649
650fn link(base: &str, r: &Rule) -> String {
661 if base.is_empty() {
662 return String::new();
663 }
664 let range = format!("-{}s", r.over.as_secs().max(1));
665 format!(
666 "{base}/#/{}?q={}&range={range}",
667 signal_name(r),
668 urlencode(&filter_of(&r.query.terms))
669 )
670}
671
672fn signal_name(r: &Rule) -> &'static str {
673 match r.query.signal {
674 Signal::Logs => "logs",
675 Signal::Traces => "traces",
676 }
677}
678
679pub(crate) fn filter_of(terms: &[Term]) -> String {
687 let q: Vec<String> = terms
688 .iter()
689 .map(|t| {
690 let (kind, key) = match &t.target {
691 Target::Field(f) => ("field", f.as_str()),
692 Target::Attr(a) => ("attr", a.as_str()),
693 };
694 let v = match &t.value {
697 Value::Str(s) => s.clone(),
698 Value::Int(i) => i.to_string(),
699 Value::Double(d) => d.to_string(),
700 Value::Bool(b) => b.to_string(),
701 };
702 let v = if v.contains(' ') || v.is_empty() {
703 format!("\"{}\"", v.replace('"', ""))
704 } else {
705 v
706 };
707 format!("{kind}:{key}{}{v}", op_symbol(t.op))
708 })
709 .collect();
710 q.join(" ")
711}
712
713fn op_symbol(op: Op) -> &'static str {
714 match op {
715 Op::Eq => "=",
716 Op::Ne => "!=",
717 Op::Lt => "<",
718 Op::Lte => "<=",
719 Op::Gt => ">",
720 Op::Gte => ">=",
721 Op::Contains => "~",
722 }
723}
724
725fn urlencode(s: &str) -> String {
730 let mut out = String::with_capacity(s.len());
731 for b in s.bytes() {
732 match b {
733 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
734 out.push(b as char);
735 }
736 _ => out.push_str(&format!("%{b:02X}")),
737 }
738 }
739 out
740}
741
742fn summary(r: &Rule, s: &State, firing: bool) -> String {
746 let value = match r.metric {
747 Metric::Ratio => format!("{:.2}%", s.value * 100.0),
748 Metric::Count => format!("{:.0}", s.value),
749 };
750 let threshold = match r.metric {
751 Metric::Ratio => format!("{:.2}%", r.threshold * 100.0),
752 Metric::Count => format!("{:.0}", r.threshold),
753 };
754 let head = if firing { "FIRING" } else { "RESOLVED" };
755 let over = human(r.over);
756 match (r.metric, s.total) {
757 (Metric::Ratio, Some(t)) => format!(
758 "[{head}] {} — {} {} {} over {over} ({} of {t} records)",
759 r.name,
760 value,
761 r.cmp.as_str(),
762 threshold,
763 s.matched
764 ),
765 _ => format!(
766 "[{head}] {} — {} records {} {} over {over}",
767 r.name,
768 value,
769 r.cmp.as_str(),
770 threshold
771 ),
772 }
773}
774
775fn human(d: Duration) -> String {
776 let s = d.as_secs();
777 match s {
778 0 => "0s".into(),
779 s if s % 86_400 == 0 => format!("{}d", s / 86_400),
780 s if s % 3_600 == 0 => format!("{}h", s / 3_600),
781 s if s % 60 == 0 => format!("{}m", s / 60),
782 s => format!("{s}s"),
783 }
784}
785
786fn payload(t: &Target_, r: &Rule, s: &State, firing: bool, link: &str) -> String {
787 let text = summary(r, s, firing);
788 let mut j = Json::new();
789 match t.format {
790 Format::Slack => j.obj(|j| {
791 j.key("text");
792 j.str(&match link.is_empty() {
795 true => text.clone(),
796 false => format!("{text}\n<{link}|open in Mira>"),
797 });
798 }),
799 Format::Discord => j.obj(|j| {
800 j.key("content");
801 j.str(&match link.is_empty() {
802 true => text.clone(),
803 false => format!("{text}\n{link}"),
804 });
805 }),
806 Format::Pagerduty => j.obj(|j| {
807 j.key("routing_key");
808 j.str(&t.key);
809 j.key("event_action");
810 j.str(if firing { "trigger" } else { "resolve" });
811 j.key("dedup_key");
814 j.str(&r.name);
815 j.key("payload");
816 j.obj(|j| {
817 j.key("summary");
818 j.str(&text);
819 j.key("severity");
820 j.str(match r.severity.as_str() {
824 s @ ("critical" | "error" | "warning" | "info") => s,
825 _ => "warning",
826 });
827 j.key("source");
828 j.str("mira");
829 });
830 if !link.is_empty() {
831 j.key("links");
832 j.arr(|j| {
833 j.obj(|j| {
834 j.key("href");
835 j.str(link);
836 j.key("text");
837 j.str("open in Mira");
838 });
839 });
840 }
841 }),
842 Format::Json => j.raw(&alert_json(r, s, firing, link)),
843 }
844 j.into_string()
845}
846
847fn alert_json(r: &Rule, s: &State, firing: bool, link: &str) -> String {
848 let mut j = Json::new();
849 j.obj(|j| {
850 j.key("rule");
851 j.str(&r.name);
852 j.key("state");
853 j.str(if firing { "firing" } else { "resolved" });
854 j.key("severity");
855 j.str(&r.severity);
856 j.key("summary");
857 j.str(&summary(r, s, firing));
858 j.key("value");
859 j.f64(s.value);
860 j.key("threshold");
861 j.f64(r.threshold);
862 j.key("matched");
863 j.u64(s.matched as u64);
864 j.key("total");
865 match s.total {
866 Some(t) => j.u64(t as u64),
867 None => j.null(),
868 }
869 j.key("over_nano");
870 j.u64_str(r.over.as_nanos() as u64);
871 j.key("at");
872 j.i64_str(s.at);
873 j.key("link");
874 j.str(link);
875 });
876 j.into_string()
877}
878
879async fn post(url: &str, body: String) -> Result<(), String> {
886 let req = hyper::Request::builder()
887 .method(hyper::Method::POST)
888 .uri(url)
889 .header(hyper::header::CONTENT_TYPE, "application/json")
890 .body(Full::new(Bytes::from(body)))
891 .map_err(|e| e.to_string())?;
892 let fut = client().request(req);
893 let resp = tokio::time::timeout(WEBHOOK_TIMEOUT, fut)
894 .await
895 .map_err(|_| format!("no response in {}", human(WEBHOOK_TIMEOUT)))?
896 .map_err(|e| e.to_string())?;
897 let status = resp.status();
898 let _ = resp.into_body().collect().await;
901 match status.is_success() {
902 true => Ok(()),
903 false => Err(format!("HTTP {}", status.as_u16())),
904 }
905}
906
907const WEBHOOK_TIMEOUT: Duration = Duration::from_secs(10);
908
909type Client = hyper_util::client::legacy::Client<Connector, Full<Bytes>>;
910
911#[cfg(not(feature = "webhook-tls"))]
912type Connector = hyper_util::client::legacy::connect::HttpConnector;
913
914#[cfg(feature = "webhook-tls")]
915type Connector = hyper_rustls::HttpsConnector<hyper_util::client::legacy::connect::HttpConnector>;
916
917fn client() -> &'static Client {
920 static C: std::sync::OnceLock<Client> = std::sync::OnceLock::new();
921 C.get_or_init(|| {
922 let b = hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new());
923 #[cfg(not(feature = "webhook-tls"))]
924 {
925 b.build_http()
926 }
927 #[cfg(feature = "webhook-tls")]
928 {
929 b.build(
930 hyper_rustls::HttpsConnectorBuilder::new()
931 .with_webpki_roots()
932 .https_or_http()
933 .enable_http1()
934 .build(),
935 )
936 }
937 })
938}
939
940pub fn router(api: Api) -> axum::Router {
941 axum::Router::new()
942 .route("/api/v1/alerts", axum::routing::get(handler))
943 .with_state(api)
944}
945
946async fn handler(axum::extract::State(api): axum::extract::State<Api>) -> axum::response::Response {
951 use axum::response::IntoResponse;
952 (
953 [(axum::http::header::CONTENT_TYPE, "application/json")],
954 api.alerts.json(),
955 )
956 .into_response()
957}
958
959pub fn spawn(api: Api) {
961 let engine = Arc::clone(&api.alerts);
962 if engine.rules.rules.is_empty() {
963 return;
964 }
965 tracing::info!(
966 rules = engine.rules.rules.len(),
967 targets = engine.rules.targets.len(),
968 every = %human(engine.rules.every),
969 "alerting"
970 );
971 tokio::spawn(async move {
972 let mut tick = tokio::time::interval(engine.rules.every);
973 tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
977 loop {
978 tick.tick().await;
979 engine.tick(&api).await;
980 }
981 });
982}
983
984#[cfg(test)]
985mod tests {
986 use super::*;
987
988 const DOC: &str = r#"{
989 "every": "5s",
990 "link_base": "https://mira.example.com/",
991 "notify": [ { "name": "oncall", "url": "http://127.0.0.1:9/hook", "format": "slack" } ],
992 "rules": [
993 { "name": "checkout-errors",
994 "over": "1m", "for": "2m", "severity": "critical", "notify": ["oncall"],
995 "query": { "signal": "traces", "where": [
996 { "attr": "service.name", "eq": "checkout" },
997 { "field": "status_code", "eq": 2 } ] },
998 "of": { "signal": "traces", "where": [
999 { "attr": "service.name", "eq": "checkout" } ] },
1000 "when": "ratio > 5%" },
1001 { "name": "any-log", "query": { "signal": "logs" }, "when": "count>=1" }
1002 ]
1003 }"#;
1004
1005 #[test]
1012 fn the_shipped_example_rules_file_parses() {
1013 let r = Rules::parse(include_str!("../../../docs/e2e/alerts.kyaml")).expect("alerts.kyaml");
1014 assert_eq!(r.every, Duration::from_secs(15));
1015 assert_eq!(r.link_base, "http://localhost:4318");
1016 assert!(r.targets.is_empty());
1019 let names: Vec<&str> = r.rules.iter().map(|x| x.name.as_str()).collect();
1020 assert_eq!(
1021 names,
1022 [
1023 "shop-error-rate",
1024 "checkout-p95-latency",
1025 "card-declines",
1026 "inventory-outage"
1027 ]
1028 );
1029 let p95 = &r.rules[1];
1032 assert!(matches!(p95.metric, Metric::Ratio));
1033 assert!(p95.of.is_some());
1034 assert!((p95.threshold - 0.05).abs() < 1e-12);
1035
1036 let filters: Vec<String> = r.rules.iter().map(|r| filter_of(&r.query.terms)).collect();
1041 assert_eq!(
1042 filters,
1043 [
1044 "field:status_code=2",
1045 "attr:service.name=checkout field:duration_nano>250000000",
1046 "attr:exception.type=payments.CardDeclined",
1047 "attr:service.name=inventory field:severity_number>=21",
1048 ]
1049 );
1050 }
1051
1052 #[test]
1053 fn a_rules_file_parses_to_what_it_says() {
1054 let r = Rules::parse(DOC).unwrap();
1055 assert_eq!(r.every, Duration::from_secs(5));
1056 assert_eq!(r.link_base, "https://mira.example.com");
1058 assert_eq!(r.rules.len(), 2);
1059 let a = &r.rules[0];
1060 assert_eq!(a.threshold, 0.05);
1061 assert_eq!(a.hold, Duration::from_secs(120));
1062 assert_eq!(a.notify, vec![0]);
1063 assert!(a.of.is_some());
1064 assert_eq!(a.query.limit, 0);
1066 assert_eq!(r.rules[1].severity, "warning");
1067 }
1068
1069 #[test]
1070 fn a_percentile_threshold_is_a_ratio_threshold() {
1071 let r = Rules::parse(
1075 r#"{ "rules": [ { "name": "p95", "over": "5m", "when": "ratio > 5%",
1076 "query": { "signal": "traces", "where": [
1077 { "field": "duration_nano", "gt": 500000000 } ] },
1078 "of": { "signal": "traces" } } ] }"#,
1079 )
1080 .unwrap();
1081 let rule = &r.rules[0];
1082 assert!(matches!(rule.metric, Metric::Ratio));
1083 assert!(rule.cmp.holds(0.06, rule.threshold));
1084 assert!(!rule.cmp.holds(0.04, rule.threshold));
1085 }
1086
1087 #[test]
1094 fn every_operator_and_scalar_survives_the_trip_through_a_filter_box() {
1095 let r = Rules::parse(
1096 r#"{ "rules": [ { "name": "all-ops", "over": "1m", "when": "count > 0",
1097 "query": { "signal": "logs", "where": [
1098 { "attr": "service.name", "ne": "checkout" },
1099 { "field": "severity_number", "lt": 17 },
1100 { "field": "severity_number", "lte": 16 },
1101 { "attr": "http.route", "contains": "/api" },
1102 { "attr": "sampling.ratio", "eq": 0.25 },
1103 { "attr": "deployment.canary", "eq": true },
1104 { "attr": "http.target", "eq": "GET /a b" },
1105 { "attr": "empty", "eq": "" } ] } } ] }"#,
1106 )
1107 .unwrap();
1108 assert_eq!(
1109 filter_of(&r.rules[0].query.terms),
1110 "attr:service.name!=checkout field:severity_number<17 \
1111 field:severity_number<=16 attr:http.route~/api attr:sampling.ratio=0.25 \
1112 attr:deployment.canary=true attr:http.target=\"GET /a b\" attr:empty=\"\""
1113 );
1114 }
1115
1116 #[test]
1117 fn every_way_to_write_a_rule_wrong_is_refused_by_name() {
1118 let bad = |doc: &str, want: &str| {
1121 let e = Rules::parse(doc).err().expect("should not have parsed");
1122 assert!(e.contains(want), "{e:?} should mention {want:?}");
1123 };
1124 bad(
1125 r#"{ "rules": [ { "name": "a", "query": {}, "when": "count ~ 1" } ] }"#,
1126 "when",
1127 );
1128 bad(
1129 r#"{ "rules": [ { "name": "a", "query": {}, "when": "p95 > 1" } ] }"#,
1130 "when",
1131 );
1132 bad(
1133 r#"{ "rules": [ { "name": "a", "query": {}, "when": "ratio > 1" } ] }"#,
1134 "of",
1135 );
1136 bad(
1137 r#"{ "rules": [ { "name": "a", "query": {}, "of": {}, "when": "count > 1" } ] }"#,
1138 "denominator",
1139 );
1140 bad(
1143 r#"{ "rules": [ { "name": "a", "query": { "from": "-1h" }, "when": "count > 1" } ] }"#,
1144 "over",
1145 );
1146 bad(
1147 r#"{ "rules": [ { "name": "a", "when": "count > 1" } ] }"#,
1148 "required",
1149 );
1150 bad(
1151 r#"{ "rules": [ { "name": "a", "query": {}, "when": "count > 1", "nope": "x" } ] }"#,
1152 "nope",
1153 );
1154 bad(
1155 r#"{ "rules": [ { "name": "a", "query": {}, "when": "count>1", "notify": ["ghost"] } ] }"#,
1156 "ghost",
1157 );
1158 bad(
1161 r#"{ "notify": [ { "name": "n", "url": "http://x/" } ],
1162 "rules": [ { "name": "a", "query": {}, "when": "count>1", "notify": "n" } ] }"#,
1163 "list of target names",
1164 );
1165 bad(
1166 r#"{ "notify": [ { "name": "n", "url": "http://x/" } ],
1167 "rules": [ { "name": "a", "query": {}, "when": "count>1", "notify": [7] } ] }"#,
1168 "notify names are strings",
1169 );
1170 bad(
1171 r#"{ "rules": [ { "name": "a", "query": {}, "when": "count>1" },
1172 { "name": "a", "query": {}, "when": "count>1" } ] }"#,
1173 "two rules named",
1174 );
1175 bad(
1176 r#"{ "notify": [ { "name": "pd", "url": "http://x/", "format": "pagerduty" } ], "rules": [] }"#,
1177 "routing key",
1178 );
1179 bad(
1180 r#"{ "notify": [ { "name": "n", "url": "ftp://x/" } ], "rules": [] }"#,
1181 "http://",
1182 );
1183 bad(r#"{ "every": "soon", "rules": [] }"#, "every");
1186 bad(r#"{ "link_base": 4318, "rules": [] }"#, "link_base");
1187 bad(r#"{ "notify": { "name": "n" }, "rules": [] }"#, "notify");
1188 bad(r#"{ "rules": { "name": "a" } }"#, "rules");
1189 bad(r#"{ "rules": [], "alerts": [] }"#, "alerts");
1190 bad(
1191 r#"{ "notify": [ { "url": "http://x/" } ], "rules": [] }"#,
1192 "name",
1193 );
1194 bad(r#"{ "notify": [ { "name": "n" } ], "rules": [] }"#, "url");
1195 bad(
1196 r#"{ "notify": [ { "name": "n", "url": "http://x/", "format": "email" } ], "rules": [] }"#,
1197 "email",
1198 );
1199 bad(
1200 r#"{ "notify": [ { "name": "n", "url": "http://x/", "to": "me" } ], "rules": [] }"#,
1201 "to",
1202 );
1203 }
1204
1205 #[test]
1211 fn a_rules_file_is_loaded_by_path_and_names_the_path_when_it_cannot_be() {
1212 let dir = std::env::temp_dir().join(format!("mira-rules-{}", std::process::id()));
1213 std::fs::create_dir_all(&dir).expect("mkdir");
1214 let path = dir.join("alerts.kyaml");
1215 std::fs::write(&path, DOC).expect("write");
1216 let r = Rules::load(&path).expect("load");
1217 assert_eq!(r.rules.len(), 2);
1218
1219 std::fs::write(&path, "{ rules: nope }").expect("write");
1220 let e = Rules::load(&path).err().expect("should not have parsed");
1221 assert!(e.contains("alerts.kyaml") && e.contains("rules"), "{e}");
1222
1223 let missing = dir.join("gone.kyaml");
1224 let e = Rules::load(&missing).err().expect("should not have opened");
1225 assert!(e.contains("gone.kyaml"), "{e}");
1226 std::fs::remove_dir_all(&dir).ok();
1227 }
1228
1229 #[test]
1235 fn a_rule_can_fire_on_too_little_rather_than_too_much() {
1236 let r = Rules::parse(
1237 r#"{ "rules": [
1238 { "name": "traffic-gone", "over": "5m", "when": "count < 100",
1239 "query": { "signal": "traces" } },
1240 { "name": "success-rate", "over": "5m", "when": "ratio <= 99%",
1241 "query": { "signal": "traces", "where": [ { "field": "status_code", "eq": 1 } ] },
1242 "of": { "signal": "traces" } } ] }"#,
1243 )
1244 .expect("rules");
1245
1246 let quiet = &r.rules[0];
1247 assert_eq!(quiet.cmp.as_str(), "<");
1248 assert!(quiet.cmp.holds(3.0, 100.0));
1249 assert!(!quiet.cmp.holds(100.0, 100.0));
1250
1251 let rate = &r.rules[1];
1252 assert_eq!(rate.cmp.as_str(), "<=");
1253 assert!((rate.threshold - 0.99).abs() < 1e-12);
1254 assert!(rate.cmp.holds(0.99, 0.99));
1255 assert!(!rate.cmp.holds(0.999, 0.99));
1256
1257 let s = State {
1259 value: 3.0,
1260 matched: 3,
1261 total: None,
1262 at: 0,
1263 ..State::default()
1264 };
1265 assert_eq!(
1266 summary(quiet, &s, true),
1267 "[FIRING] traffic-gone — 3 records < 100 over 5m"
1268 );
1269 }
1270
1271 #[cfg(not(feature = "webhook-tls"))]
1272 #[test]
1273 fn an_https_target_is_refused_at_load_by_a_build_that_cannot_dial_it() {
1274 let e =
1275 Rules::parse(r#"{ "notify": [ { "name": "s", "url": "https://x/" } ], "rules": [] }"#)
1276 .err()
1277 .expect("an https target should not load in this build");
1278 assert!(e.contains("webhook-tls"), "{e:?}");
1279 }
1280
1281 #[test]
1285 fn for_needs_a_sustained_breach_not_a_repeated_one() {
1286 let e = Engine::new(Rules::parse(DOC).unwrap());
1287 let hold = e.rules.rules[0].hold.as_nanos() as i64;
1288 let step = |breaching: bool, now: i64| -> (Option<bool>, &'static str) {
1289 let mut st = e.state.lock().unwrap();
1290 let s = &mut st[0];
1291 (s.advance(breaching, now, hold), s.phase())
1292 };
1293 const MIN: i64 = 60_000_000_000;
1294 assert_eq!(step(true, 0), (None, "pending"));
1295 assert_eq!(step(false, MIN), (None, "ok"));
1297 assert_eq!(step(true, 2 * MIN), (None, "pending"));
1298 assert_eq!(step(true, 3 * MIN), (None, "pending"));
1299 assert_eq!(step(true, 4 * MIN), (Some(true), "firing"));
1300 assert_eq!(step(true, 5 * MIN), (None, "firing"));
1302 assert_eq!(step(false, 6 * MIN), (Some(false), "ok"));
1303 }
1304
1305 #[test]
1306 fn a_link_lands_on_the_rows_that_fired() {
1307 let r = Rules::parse(DOC).unwrap();
1308 let l = link(&r.link_base, &r.rules[0]);
1309 assert!(l.starts_with("https://mira.example.com/#/traces?q="), "{l}");
1310 assert!(l.contains("attr%3Aservice.name%3Dcheckout"), "{l}");
1313 assert!(l.contains("field%3Astatus_code%3D2"), "{l}");
1314 assert!(l.ends_with("&range=-60s"), "{l}");
1315 assert_eq!(link("", &r.rules[0]), "");
1317 }
1318
1319 #[test]
1320 fn each_format_says_the_same_thing_in_its_own_words() {
1321 let r = Rules::parse(DOC).unwrap();
1322 let rule = &r.rules[0];
1323 let s = State {
1324 value: 0.12,
1325 matched: 24,
1326 total: Some(200),
1327 ..State::default()
1328 };
1329 let link = link(&r.link_base, rule);
1330 let text = summary(rule, &s, true);
1331 assert!(text.contains("FIRING"), "{text}");
1332 assert!(text.contains("12.00%"), "{text}");
1333 assert!(text.contains("24 of 200"), "{text}");
1334 assert!(text.contains("over 1m"), "{text}");
1335
1336 let slack = payload(&r.targets[0], rule, &s, true, &link);
1337 assert!(slack.starts_with(r#"{"text":"[FIRING]"#), "{slack}");
1338 assert!(slack.contains("|open in Mira>"), "{slack}");
1339
1340 let pd = Target_ {
1341 name: "pd".into(),
1342 url: "http://x/".into(),
1343 format: Format::Pagerduty,
1344 key: "rk".into(),
1345 };
1346 let fire = payload(&pd, rule, &s, true, &link);
1347 assert!(fire.contains(r#""event_action":"trigger""#), "{fire}");
1348 assert!(fire.contains(r#""dedup_key":"checkout-errors""#), "{fire}");
1349 assert!(fire.contains(r#""severity":"critical""#), "{fire}");
1350 let clear = payload(&pd, rule, &s, false, &link);
1351 assert!(clear.contains(r#""event_action":"resolve""#), "{clear}");
1352 assert!(
1354 clear.contains(r#""dedup_key":"checkout-errors""#),
1355 "{clear}"
1356 );
1357
1358 let raw = Target_ {
1359 format: Format::Json,
1360 ..Target_ {
1361 name: "j".into(),
1362 url: "http://x/".into(),
1363 format: Format::Json,
1364 key: String::new(),
1365 }
1366 };
1367 let j = payload(&raw, rule, &s, true, &link);
1368 assert!(j.contains(r#""rule":"checkout-errors""#), "{j}");
1369 assert!(j.contains(r#""state":"firing""#), "{j}");
1370 assert!(j.contains(r#""total":200"#), "{j}");
1371 let counted = payload(&raw, &r.rules[1], &State::default(), true, "");
1375 assert!(counted.contains(r#""total":null"#), "{counted}");
1376 assert!(counted.contains(r#""matched":0"#), "{counted}");
1377
1378 let dis = Target_ {
1382 name: "d".into(),
1383 url: "http://x/".into(),
1384 format: Format::Discord,
1385 key: String::new(),
1386 };
1387 let d = payload(&dis, rule, &s, true, &link);
1388 assert!(d.starts_with(r#"{"content":"[FIRING]"#), "{d}");
1389 assert!(d.contains(&link), "{d}");
1390
1391 for t in [&r.targets[0], &dis] {
1394 let p = payload(t, rule, &s, true, "");
1395 assert!(p.ends_with(r#"over 1m (24 of 200 records)"}"#), "{p}");
1396 }
1397 }
1398
1399 #[test]
1400 fn a_severity_pagerduty_does_not_know_degrades_rather_than_400s() {
1401 let mut r = Rules::parse(DOC).unwrap();
1402 r.rules[0].severity = "sev1".into();
1403 let pd = Target_ {
1404 name: "pd".into(),
1405 url: "http://x/".into(),
1406 format: Format::Pagerduty,
1407 key: "rk".into(),
1408 };
1409 let out = payload(&pd, &r.rules[0], &State::default(), true, "");
1410 assert!(out.contains(r#""severity":"warning""#), "{out}");
1411 }
1412
1413 #[test]
1414 fn an_idle_service_is_not_a_hundred_percent_error_rate() {
1415 let r = Rules::parse(DOC).unwrap();
1419 let rule = &r.rules[0];
1420 assert!(!rule.cmp.breaches(0.0, rule.threshold, Some(0)));
1421
1422 let slo =
1427 Rules::parse(&DOC.replace(r#""when": "ratio > 5%""#, r#""when": "ratio < 99%""#))
1428 .unwrap();
1429 let slo = &slo.rules[0];
1430 assert!(!slo.cmp.breaches(0.0, slo.threshold, Some(0)));
1431 assert!(slo.cmp.breaches(0.0, slo.threshold, Some(200)));
1434 assert!(!slo.cmp.breaches(1.0, slo.threshold, Some(200)));
1435 assert!(r.rules[1].cmp.breaches(1.0, r.rules[1].threshold, None));
1438 }
1439
1440 #[test]
1441 fn durations_round_trip_the_way_they_were_written() {
1442 assert_eq!(human(Duration::from_secs(60)), "1m");
1443 assert_eq!(human(Duration::from_secs(90)), "90s");
1444 assert_eq!(human(Duration::from_secs(7200)), "2h");
1445 assert_eq!(human(Duration::from_secs(86_400)), "1d");
1446 assert_eq!(human(Duration::ZERO), "0s");
1447 }
1448
1449 #[tokio::test]
1464 async fn a_webhook_that_refuses_the_page_is_a_failure_that_names_the_status() {
1465 use std::io::{Read, Write};
1466 let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
1467 let url = format!("http://{}/hook", listener.local_addr().expect("addr"));
1468 let seen = std::thread::spawn(move || {
1469 let (mut sock, _) = listener.accept().expect("accept");
1470 sock.set_read_timeout(Some(Duration::from_secs(10)))
1474 .expect("timeout");
1475 sock.set_write_timeout(Some(Duration::from_secs(10)))
1476 .expect("timeout");
1477 let mut bodies = Vec::new();
1478 for i in 0..2 {
1479 let mut head = Vec::new();
1480 let mut byte = [0u8; 1];
1481 while !head.ends_with(b"\r\n\r\n") && sock.read(&mut byte).unwrap_or(0) == 1 {
1482 head.push(byte[0]);
1483 }
1484 let text = String::from_utf8_lossy(&head).to_lowercase();
1485 let len: usize = text
1486 .split("content-length:")
1487 .nth(1)
1488 .and_then(|t| t.split("\r\n").next())
1489 .and_then(|t| t.trim().parse().ok())
1490 .unwrap_or(0);
1491 let mut body = vec![0u8; len];
1492 let read = sock.read_exact(&mut body).is_ok();
1493 bodies.push(match read {
1494 true => String::from_utf8_lossy(&body).into_owned(),
1495 false => "<nothing arrived on this connection>".into(),
1496 });
1497 const PAGE: usize = 1 << 20;
1504 let reply: Vec<u8> = match i {
1505 0 => {
1506 let mut r = format!(
1507 "HTTP/1.1 500 Internal Server Error\r\ncontent-length: {PAGE}\r\n\r\n"
1508 )
1509 .into_bytes();
1510 r.extend(std::iter::repeat_n(b'x', PAGE));
1511 r
1512 }
1513 _ => b"HTTP/1.1 204 No Content\r\ncontent-length: 0\r\n\r\n".to_vec(),
1514 };
1515 let _ = sock.write_all(&reply);
1516 }
1517 listener.set_nonblocking(true).expect("nonblocking");
1518 (bodies, listener.accept().is_ok())
1519 });
1520
1521 assert_eq!(
1522 post(&url, r#"{"text":"first"}"#.into()).await,
1523 Err("HTTP 500".to_owned())
1524 );
1525 assert_eq!(post(&url, r#"{"text":"second"}"#.into()).await, Ok(()));
1528 let (bodies, reconnected) = seen.join().expect("receiver");
1529 assert_eq!(
1530 bodies,
1531 [r#"{"text":"first"}"#, r#"{"text":"second"}"#],
1532 "both bodies arrived intact, down one socket"
1533 );
1534 assert!(
1535 !reconnected,
1536 "the refusal's body was drained, so the pooled connection survived it"
1537 );
1538
1539 assert_eq!(
1543 post("http://[bad", "{}".into()).await,
1544 Err("invalid authority".to_owned())
1545 );
1546 }
1547
1548 #[test]
1549 fn the_alerts_document_reports_every_rule_including_the_quiet_ones() {
1550 let e = Engine::new(Rules::parse(DOC).unwrap());
1551 let j = e.json();
1552 assert!(j.contains(r#""name":"checkout-errors""#), "{j}");
1553 assert!(j.contains(r#""state":"ok""#), "{j}");
1554 assert!(j.contains(r#""name":"any-log""#), "{j}");
1555 assert!(j.contains(r#""over_nano":"60000000000""#), "{j}");
1558 assert!(j.contains(r#""error":null"#), "{j}");
1559 }
1560}