Skip to main content

mira/
alert.rs

1//! Static-rule alerting: a KYAML document in, webhooks out.
2//!
3//! # A rule is a query, not a new language
4//!
5//! Every alerting system this replaces ships a second language — PromQL, a
6//! DSL, a builder UI — and that language is the reason "why did this page?" is
7//! hard to answer: the thing that fired is not the thing you can look at. Here
8//! a rule *embeds a `/api/v1/query` document*, verbatim. The operator builds
9//! the query in the UI, presses nothing, pastes it into the rules file, and the
10//! link in the resulting page opens the same query in the same UI. There is one
11//! filter grammar in this product and this is not a second one.
12//!
13//! # Two metrics, and why that is enough
14//!
15//! `count` is how many records matched. `ratio` is that over a second query's
16//! count. Between them they express both of the rules everyone actually writes:
17//!
18//! * *error rate above 5% over a minute* — numerator `status_code = 2`,
19//!   denominator the same filter without it, `ratio > 5%`.
20//! * *p95 latency above 500 ms* — numerator adds `duration_nano > 500000000`,
21//!   same denominator, `ratio > 5%`.
22//!
23//! The second one is not an approximation of a quantile, it *is* the quantile:
24//! `p95(d) > T` and `|{d > T}| / |d| > 0.05` are the same statement. That
25//! identity is why there is no digest in this file and no `p95(...)` in the
26//! grammar — a percentile threshold was always a counting question wearing a
27//! statistics hat, and Mira can already count exactly.
28//!
29//! # Counting is free
30//!
31//! [`query::search_open`] with `limit: 0` returns no rows and an exact
32//! `rows_matched`: the early exit needs a held hit to fire and there are none,
33//! so every matching block is scanned, and the per-wave trim throws the hits
34//! away before they accumulate. So an evaluation costs one scan and allocates
35//! nothing per match — the same code path, the same zone maps and the same
36//! bloom filters the UI's query uses, which is also why a rule cannot drift
37//! from what the operator sees.
38//!
39//! # One replica evaluates
40//!
41//! Principle 4 is no coordination state, and N replicas reading the same block
42//! directory would each fire the same rule N times. There is no lease and no
43//! leader here: alerting is off unless `alerts.rules` names a file, so the
44//! deployment enables it on one replica and that is the whole mechanism. State
45//! — which rules are firing, and since when — is in memory, so a restart
46//! re-evaluates from scratch and re-pages anything still breaching.
47//!
48//! ponytail: dedup is the operator pointing one replica at the rules file. A
49//! lease file in the block directory is the upgrade path if that stops being
50//! enough, and it stays inside "the block directory is the manifest".
51//!
52//! # Why HTTPS is a Cargo feature
53//!
54//! Slack, Discord and PagerDuty are all HTTPS, and in-process TLS costs eleven
55//! crates against a tree of 148 — `ring` among them, which would be the second
56//! C dependency in a binary whose README states it has one. Both of those are
57//! published product properties (section 11), so the default build posts over HTTP and
58//! refuses an `https://` target at load time, naming the feature. Build with
59//! `--features webhook-tls` and it dials TLS directly.
60
61use 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
74/// What the whole rules file parsed to.
75pub struct Rules {
76    /// How often every rule is evaluated.
77    pub every: Duration,
78    /// Prefix for the links in a notification, e.g. `https://mira.example.com`.
79    /// Empty means the payloads carry no link — an alert with a link to
80    /// `http://0.0.0.0:4318` is worse than one with none.
81    pub link_base: String,
82    pub rules: Vec<Rule>,
83    pub targets: Vec<Target_>,
84}
85
86pub struct Rule {
87    pub name: String,
88    /// The numerator. Window and `limit` are set per evaluation.
89    query: Search,
90    /// The denominator, for `ratio`. Absent for `count`.
91    of: Option<Search>,
92    over: Duration,
93    metric: Metric,
94    cmp: Cmp,
95    threshold: f64,
96    /// How long the comparison must hold before the rule fires. Zero fires on
97    /// the first breach.
98    hold: Duration,
99    severity: String,
100    /// Indices into [`Rules::targets`], resolved at load so a typo in a rule's
101    /// `notify` is a startup error rather than a page that never arrives.
102    notify: Vec<usize>,
103}
104
105/// A webhook endpoint.
106///
107/// Deliberately not `Debug`, and neither is anything holding one: a Slack
108/// webhook URL *is* the credential and so is PagerDuty's routing key, so the
109/// derive that makes them one careless `{:?}` away from a log line is the one
110/// thing this type must not have.
111pub struct Target_ {
112    pub name: String,
113    url: String,
114    format: Format,
115    /// PagerDuty's Events v2 routing key. Ignored by the other formats.
116    key: String,
117}
118
119#[derive(Clone, Copy, PartialEq, Eq)]
120enum Format {
121    Slack,
122    Discord,
123    Pagerduty,
124    /// Mira's own alert object, for anything else.
125    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    /// Whether a reading breaches, which is not the same as whether the
153    /// comparison holds.
154    ///
155    /// An empty ratio window reports 0.0 — see `count_pair` for why 0.0 rather
156    /// than NaN — and 0.0 is below every threshold a `<` rule could name. So a
157    /// rule written `ratio < 99%`, which is how anyone writes a success-rate
158    /// SLO, fires the moment traffic stops and stays firing: the same false
159    /// positive the `>` direction was already spared, in the direction nobody
160    /// checked. `count` is the rule for alerting on the absence of traffic.
161    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/// What one rule is currently doing. Reported verbatim by `/api/v1/alerts`.
176#[derive(Default, Clone)]
177pub struct State {
178    /// When the comparison first held, in wall nanoseconds. Cleared the moment
179    /// it stops holding, which is what makes `hold` a *sustained* breach rather
180    /// than a count of breaching evaluations.
181    since: Option<i64>,
182    firing: Option<i64>,
183    value: f64,
184    matched: usize,
185    total: Option<usize>,
186    /// The last evaluation's failure, if it failed. A rule whose query is
187    /// unanswerable is not a quiet rule.
188    error: Option<String>,
189    at: i64,
190}
191
192impl State {
193    /// Advance the state machine one evaluation, and say whether that is a
194    /// notification: `Some(true)` fired, `Some(false)` resolved, `None` nothing
195    /// changed.
196    ///
197    /// A method rather than a `match` inside [`Engine::tick`] because the only
198    /// interesting thing in this file has a clock in it, and a test that drives
199    /// the clock has to drive *this* — a test carrying its own copy of these
200    /// arms would pass while the engine did something else, which is how the
201    /// last round of bugs in this repository survived its unit tests.
202    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                // A rule with no `for` fires on the evaluation that first
215                // breached, not on the next one.
216                (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
238// ---------------------------------------------------------------- parsing
239
240impl Rules {
241    /// No `alerts.rules` in the config. Still an [`Engine`], so the endpoint,
242    /// the TUI pane and the MCP tool all answer "no rules" rather than 404.
243    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        // A name is the dedup key in every payload format below and the handle
285        // an operator silences by, so two rules sharing one is not a cosmetic
286        // problem — it is two alerts that cancel each other's PagerDuty
287        // incident.
288        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        // Refused here rather than at the first page, because the first page is
325        // exactly when nobody is reading logs.
326        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        // A rule that names no target still evaluates and still shows up in
378        // `/api/v1/alerts` and the TUI. That is the useful default for writing
379        // a rule you do not yet trust enough to page on.
380        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
409/// A rule's embedded query document, with the four keys the engine owns
410/// refused rather than ignored.
411///
412/// `over` is the window and `limit` is always zero, so a `from` in the document
413/// would be silently overwritten every tick — the exact class of mistake
414/// `known` exists to catch one level up.
415fn 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
432/// `count > 100`, `ratio >= 5%`, `count < 1`.
433///
434/// Split on the operator rather than on whitespace: `ratio>0.05` is what
435/// someone types and refusing it teaches nothing.
436fn 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    // Longest first, so `>=` is not read as `>` followed by junk.
444    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    // `5%` is how a human writes an error-rate threshold and `0.05` is what it
460    // compares against. Accepting only one of them is a footgun either way.
461    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
469// ------------------------------------------------------------- evaluation
470
471pub 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    /// Evaluate every rule once and dispatch whatever changed.
489    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            // Lock, decide, unlock. The dispatch below awaits, and a `MutexGuard`
505            // held across an await is both a deadlock waiting for a second
506            // evaluator and a `!Send` future.
507            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    /// Every rule's current state, as `/api/v1/alerts` returns it.
537    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                        // The predicate, not just a link to it: a reader with no
588                        // browser — the TUI, an agent — needs the terms.
589                        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
608/// Run a rule's queries and reduce them to one number.
609///
610/// Two scans for a ratio, not one over a superset filtered twice: the terms are
611/// AND-ed and the denominator is a different conjunction, so there is no single
612/// scan that answers both, and two exact counts beat one estimate.
613async 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        // Zero traffic is not a 100% error rate, and paging as though it were
627        // is how an alert wakes someone up for a deployment that is simply
628        // idle. A `count` rule is the way to alert on the absence of traffic.
629        (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    // Same reason every handler in `api.rs` does this: an mmap page fault
641    // stalls the OS thread it lands on, and the evaluator shares a runtime with
642    // the ingest listeners.
643    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
650// ----------------------------------------------------------------- links
651
652/// The UI URL that shows the rows this rule counted.
653///
654/// The UI keeps all of its view state in the location hash (`route.svelte.js`),
655/// which is what makes this possible at all: there is no saved view to create
656/// and no id to store, so a link is a pure function of the rule. The `q`
657/// grammar is the UI's, so the terms are re-spelled here — twenty lines against
658/// a page that lands the on-call on the exact rows, rather than on a home
659/// screen and a re-derivation of what fired at 3am.
660fn 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
679/// The rule's `where` terms, spelled in the filter-bar grammar both UIs read.
680///
681/// Split out of [`link`] because it is the half that is useful without a
682/// `link_base`: the TUI has no URL to open, and an agent asked "why did this
683/// fire" wants the predicate rather than a link it cannot click. Both surfaces
684/// paste this straight into a filter box, so the alert and the query it came
685/// from cannot drift into two different spellings.
686pub(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            // A non-string scalar is its own text; only a string can carry the
695            // space that the UI's tokeniser would split on.
696            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
725/// Percent-encode everything outside the unreserved set.
726///
727/// Not a general URL encoder and not trying to be: this escapes a query-string
728/// *value*, so the conservative set is correct and the aggressive one is safe.
729fn 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
742// -------------------------------------------------------------- dispatch
743
744/// One line of prose per alert, shared by every format that takes prose.
745fn 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            // Slack's mrkdwn link form. Plain text with a bare URL renders too,
793            // so a target misconfigured as slack is ugly rather than broken.
794            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            // The rule name, so the resolve closes the incident the trigger
812            // opened. This is the reason two rules may not share a name.
813            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                // Events v2 takes exactly these four. Anything else is a 400,
821                // so an unrecognised severity degrades to `warning` rather than
822                // losing the page.
823                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
879/// POST a JSON body, with a deadline.
880///
881/// No retry. A webhook that is down stays down for longer than the evaluation
882/// period, so a retry loop turns one missed page into a queue of stale ones —
883/// and the state machine already re-pages on the next transition. The failure
884/// is logged, and `/api/v1/alerts` carries it.
885async 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    // Drained rather than dropped: an undrained body leaves the connection
899    // unusable, so the pool opens a new one for every alert.
900    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
917/// One pooled client for the process. Alerts are rare and bursty, and a fresh
918/// TCP (and TLS) handshake per page is the whole latency of a page.
919fn 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
946/// Every rule this node evaluates and what it is currently doing.
947///
948/// An empty list means this node has no rules file — alerting is off here, not
949/// all clear. `link` on a firing rule opens the records behind it.
950async 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
959/// Start the evaluator, if this deployment has rules.
960pub 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        // A slow scan must not queue up ticks and then run them back to back:
974        // that turns a struggling evaluator into a busy loop over the same
975        // blocks.
976        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    /// The file `make demo` loads and `docs/config.md` points at.
1006    ///
1007    /// A documented example that does not parse is worse than no example, and
1008    /// this one is also the only place the schema is written out in full — so
1009    /// it is checked at compile time, against the parser, rather than by
1010    /// whoever next runs the demo.
1011    #[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        // No targets: the demo has nothing to POST to, and a rule with no
1017        // target must still evaluate rather than be quietly dropped.
1018        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        // The percentile example has to be a ratio rule with both counts, or
1030        // the comment above it in the file is a lie.
1031        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        // The spellings both UIs paste into a filter box. Pinned here because
1037        // they are the contract with a parser in another language: the browser's
1038        // `parseFilter` has a test over these same four strings, so a change to
1039        // `filter_of` that the JS tokeniser cannot read fails on this side first.
1040        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        // The trailing slash is stripped, or every link would have two.
1057        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        // `limit: 0` is what makes an evaluation a count rather than a read.
1065        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        // The module doc's claim, as an executable statement: p95 > 500ms is
1072        // "more than 5% of spans took longer than 500ms", and the rule that
1073        // says so is an ordinary ratio rule with a range term.
1074        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    /// Every operator and every scalar the query grammar has, spelled back out.
1088    ///
1089    /// `filter_of` is the one place a rule's predicate is turned into text, and
1090    /// both UIs paste that text into a filter box and re-parse it. An operator
1091    /// this function has no symbol for, or a value it quotes wrongly, is a
1092    /// link that opens rows the rule did not count.
1093    #[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        // `unwrap_err` would need `Rules: Debug`, and `Rules` holds webhook
1119        // credentials — see [`Target_`].
1120        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        // The window is the engine's, and a `from` that looked accepted and was
1141        // overwritten every tick is the silent failure this refuses.
1142        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        // A bare name where a list belongs. YAML would happily read it, and
1159        // reading it as "no targets" is a rule that evaluates and never pages.
1160        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        // The shapes of the document itself, not of a rule inside it. Each one
1184        // is a plausible typo whose silent reading would be "alerting is off".
1185        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    /// A rules file is read from disk, and both ways that fails say which file.
1206    ///
1207    /// The path matters more than it looks: a node refuses to start on a bad
1208    /// rules file, so this message is the entire diagnosis someone gets from a
1209    /// container that exited.
1210    #[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    /// The other direction: a threshold that fires when a number gets too low.
1230    ///
1231    /// `<` and `<=` exist because the alert nobody writes until the outage is
1232    /// "traffic stopped" — a rule whose breach is an absence, where every
1233    /// greater-than rule in the file goes quiet at exactly the wrong moment.
1234    #[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        // And the prose an operator is paged with reads the right way round.
1258        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    /// The state machine, driven by hand. `for` is the only part of it with a
1282    /// clock, and the bug it exists to prevent — a rule that fires because it
1283    /// breached twice with a recovery in between — is invisible without one.
1284    #[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        // Three minutes later, but it recovered in between, so the clock restarts.
1296        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        // Already firing: no second page.
1301        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        // The UI's own `q` grammar (`api.js`), percent-encoded: an operator
1311        // clicking this gets the query in the search box, not a home page.
1312        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        // No base configured means no link, rather than one pointing at 0.0.0.0.
1316        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        // Same dedup key both ways, or the resolve opens a second incident.
1353        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        // A `count` rule has no denominator at all, and the raw format says so
1372        // with `null`. A zero there is a ratio of nothing over nothing to
1373        // whatever is reading this, which is the one thing it is not.
1374        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        // Discord has no link markup, so the URL goes on its own line. It is
1379        // still the same one Slack wraps — a reader comparing two channels must
1380        // not land on two different sets of rows.
1381        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        // No `link_base` configured: every format still pages, and none of them
1392        // emits a dangling separator where the URL would have been.
1393        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        // 0/0. The arithmetic answer is NaN and the operational answer is "no
1416        // traffic, no alert"; paging on a deployment that is merely quiet is
1417        // the classic false positive this avoids.
1418        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        // And not a zero percent success rate either. `ratio < 99%` is how a
1423        // success-rate SLO is written, and 0.0 is below every threshold such a
1424        // rule could name — so the guard the `>` direction got for free has to
1425        // be explicit, or an idle deployment pages permanently.
1426        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        // A window with traffic in it still decides normally, in both
1432        // directions: the guard is about the empty window, not about zero.
1433        assert!(slo.cmp.breaches(0.0, slo.threshold, Some(200)));
1434        assert!(!slo.cmp.breaches(1.0, slo.threshold, Some(200)));
1435        // And a `count` rule, which has no denominator, is untouched — it is
1436        // the documented way to alert on the absence of traffic.
1437        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    /// A webhook that answers is not a webhook that accepted.
1450    ///
1451    /// Slack retires an incoming-webhook URL with a 403 and PagerDuty rejects a
1452    /// stale routing key with a 400: in both cases the POST succeeds at every
1453    /// layer this process controls, and the page is not delivered. Treating a
1454    /// non-2xx as success is silent — nothing is retried, by design — so the
1455    /// status is the only evidence, and it has to reach the log line and
1456    /// `/api/v1/alerts` with the number in it.
1457    ///
1458    /// The 204 afterwards is served on the *same* socket, and the server here
1459    /// accepts exactly one: that is what makes draining the failed response
1460    /// body a correctness property rather than tidiness. An undrained body is
1461    /// never returned to the pool, so dropping the `collect` moves the second
1462    /// page onto a second connection and this test sees it.
1463    #[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            // So a client that opens a *second* connection fails this test in
1471            // ten seconds rather than hanging it forever on a read nobody will
1472            // answer — or on a write nobody is draining.
1473            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                // A body on the refusal, because that is what a real endpoint
1498                // sends — an error page, not a word. Big enough that it cannot
1499                // have arrived alongside the header: a five-byte body is
1500                // already in the client's read buffer by the time the status
1501                // is, and a connection like that is reusable whether anyone
1502                // drained it or not, so a small one would prove nothing.
1503                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        // 204 is a success and plenty of receivers answer with it, so "2xx"
1526        // rather than "200" is the contract.
1527        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        // And a URL no request can be built from fails before the socket: the
1540        // text is the builder's, so neither a connector error nor the ten-second
1541        // timeout can satisfy this.
1542        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        // 64-bit values are strings on the wire (section 7.6) and the two clients read
1556        // them with a coercion that expects that.
1557        assert!(j.contains(r#""over_nano":"60000000000""#), "{j}");
1558        assert!(j.contains(r#""error":null"#), "{j}");
1559    }
1560}