Skip to main content

zenkey_model/
alarms.rs

1//! `alarms.v1`: the active alarms of one service
2//! (`spec/profiles/alarms/v1.md`, #800).
3//!
4//! The profile's session-free half: the key recipe, byte for byte
5//! ZenSight's (§2.2), with its framing and the sanitizing step a reader
6//! re-derives through (§2.3); the document and its checks (§2.4); the
7//! reading of one key's samples into transitions (§2.6); a reference to an
8//! alarm from another interface (§2.12); and §5's four questions as pure
9//! judgements in three states (§2.14, §2.15), built on
10//! [`freshness::judge_all`] at the contract's 900 s.
11//!
12//! ```text
13//! alert_key(rule, labels)   ─▶ the key │ Unframed: the strict recipe, framed input only      §2.2
14//! sanitize(rule, labels)    ─▶ the discriminating input, with §2.3's substitutions         §2.3
15//! derive(rule, labels)      ─▶ Derived{key, input, framed}: the reader's, never refusing   §2.3
16//! decode(bytes)             ─▶ strict JSON first (0.2), then Alarm::from_json              §2.4
17//! Alarm::from_json(v)       ─▶ Alarm │ Invalid{json, schema, time_range}; check(a) ─▶ problems  §2.4
18//! Track::apply(sample)      ─▶ raised │ escalated │ refreshed │ confirmed │ resolved │ retired │ unreadable  §2.6
19//! AlarmRef::key / from_key  ─▶ zk2/<system>/<service>/alarms.v1/state/alarms/<alert_key>  §2.12
20//! firing(reading)           ─▶ §5 "is this alarm firing?": yes │ no │ unobservable │ not_asked, + reason
21//! owner_set(p, seed, win)   ─▶ established │ unobservable │ not_asked: an owner's alarms known whole  §2.15
22//! any_firing(s, owners, sc) ─▶ §5 "is anything firing at or above s?", the scope's reads whole or not
23//! rederives(key, payload)   ─▶ §5 "does this key re-derive from its document?"
24//! stale_firing(reading)     ─▶ §5 "is a firing alarm past its horizon, its owner present?"
25//! ```
26//!
27//! There is no I/O and no clock here. A reader merges what it heard of a
28//! key by the owner's stamp (core §4.2), measures what its observations
29//! hold, and hands them over as values. The owner's puts, its confirmations
30//! and its adoption at a restart (§2.5, §2.7, §2.9) are the runtime's.
31//!
32//! **Two majors** (#984's S1). [`v2`] is `alarms.v2`'s
33//! (`spec/profiles/alarms/v2.md`): an alarm in a slot, a transition in one
34//! packed record, its words by a table. It restates this text by reference,
35//! so the identity and what a reader concludes are one set for both:
36//!
37//! ```text
38//! Major::of(interfaces)   ─▶ the major a descriptor's alarms are read by: v2 where it lists both
39//! derive · alert_key      ─▶ the alert key, the identity under either major
40//! transition (§2.6)       ─▶ one table of puts against the record held, either major's
41//! any_firing              ─▶ over owners and alarms of either major
42//! ```
43//!
44//! [`firing`], [`stale_firing`] and [`owner_set`] are this major's, and
45//! [`v2::firing`], [`v2::stale_firing`] and [`v2::owner_set`] that one's:
46//! the steps before the latest sample and after it are shared, and the
47//! answers, the reasons and the counts are one set ([`Reason`]).
48
49pub mod v2;
50
51use std::collections::BTreeMap;
52use std::fmt;
53use std::time::Duration;
54
55use serde::{Deserialize, Serialize};
56use serde_json::Value;
57
58use crate::freshness::{self, Horizon, Observation};
59use crate::grammar::{self, Addr, IfaceId, Key, KeyError, KindToken, ZkKey};
60use crate::slug::{chunk_slug, chunk_unslug};
61
62/// The profile's id, which is also its standard contract's interface id.
63pub const PROFILE: &str = "alarms.v1";
64
65/// The standard contract's interface id (§3).
66pub const IFACE: &str = "alarms.v1";
67
68/// The profile's name, as an annotation key's prefix would carry it.
69pub const NAME: &str = "alarms";
70
71/// The published vocabulary (§4): empty. Core 0.34 replaces the interim
72/// `severity_default` with it, so W105 warns of every `alarms.<key>`.
73pub const VOCABULARY: &[&str] = &[];
74
75/// The one template (§3): `state/alarms/{alert_key}`.
76pub const ALARMS: &str = "alarms/{alert_key}";
77
78/// The template's literal chunk.
79const ALARMS_CHUNK: &str = "alarms";
80
81/// The contract's horizon, `freshness.ttl_s = 900` (§2.7).
82pub const TTL: Duration = Duration::from_secs(900);
83
84/// The owner's bound between two confirmations of a firing alarm, ttl/2
85/// (`freshness.v1` §2.4).
86pub const REFRESH: Duration = Duration::from_secs(450);
87
88/// The contract's bound on one service's alarms (§2.8).
89pub const MAX_ALARMS: u64 = 256;
90
91/// The host-scoped label named for the host itself (§2.2).
92pub const HOST: &str = "host";
93
94/// The prefix of every other host-scoped label name (§2.2).
95pub const HOST_SCOPED_PREFIX: &str = "host.";
96
97/// The rule an empty one is sanitized to (§2.3).
98pub const UNNAMED: &str = "unnamed";
99
100/// The largest time a document carries, 2^53−1 ms (§2.4).
101pub const MAX_TIME_MS: u64 = (1 << 53) - 1;
102
103/// The horizon, as `freshness.v1` reads it.
104#[must_use]
105pub fn horizon() -> Horizon {
106    Horizon::Within(TTL)
107}
108
109/// Which major of the profile a service's alarms are read by (`alarms.v2`
110/// §2.1, §2.14's step 2, §2.17). The two are two interfaces: an instance
111/// implements one, and a reader reads either.
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
113pub enum Major {
114    /// `alarms.v1`: a JSON document on the alert key.
115    V1,
116    /// `alarms.v2`: a packed record on a slot ([`v2`]).
117    V2,
118}
119
120impl Major {
121    /// The major's interface id, which is its standard contract's.
122    #[must_use]
123    pub const fn iface(self) -> &'static str {
124        match self {
125            Major::V1 => IFACE,
126            Major::V2 => v2::IFACE,
127        }
128    }
129
130    /// The major an interface id names: the deployment's word across a
131    /// constrained face, where no descriptor crosses (`alarms.v2` §2.11).
132    /// `None` for any other interface, a later major among them.
133    #[must_use]
134    pub fn named(iface: &str) -> Option<Major> {
135        [Major::V2, Major::V1]
136            .into_iter()
137            .find(|m| m.iface() == iface)
138    }
139
140    /// The major a descriptor is read by, from the interface ids its
141    /// `interfaces` holds: `alarms.v2` where it lists it, `alarms.v1`
142    /// where it lists that and not `alarms.v2`, and `None` where it lists
143    /// neither, which is not asked (`not_listed`). One that lists both
144    /// breaks `alarms.v2` §2.1, and is read as `alarms.v2`.
145    #[must_use]
146    pub fn of<'a>(interfaces: impl IntoIterator<Item = &'a str>) -> Option<Major> {
147        let mut found = None;
148        for iface in interfaces {
149            match Major::named(iface) {
150                Some(Major::V2) => return Some(Major::V2),
151                Some(Major::V1) => found = Some(Major::V1),
152                None => {}
153            }
154        }
155        found
156    }
157}
158
159// --- §2.2, §2.3: the key ---------------------------------------------------------
160
161/// Whether a label is host-scoped (§2.2): `host`, or a name starting with
162/// `host.`. The comparison is exact: no trimming, no case folding.
163#[must_use]
164pub fn is_host_scoped(name: &str) -> bool {
165    name == HOST || name.starts_with(HOST_SCOPED_PREFIX)
166}
167
168/// Why the strict recipe refuses its input (§2.3): the framing would stop
169/// being injective. Host-scoped labels are removed first, so none of them
170/// is ever the cause.
171#[derive(Debug, Clone, PartialEq, Eq)]
172pub enum Unframed {
173    /// The rule is empty, or holds a newline.
174    Rule,
175    /// A discriminating label's name is empty, or holds a newline or `=`.
176    LabelName(String),
177    /// A discriminating label's value holds a newline.
178    LabelValue { name: String },
179}
180
181impl Unframed {
182    /// The fixture's token.
183    #[must_use]
184    pub fn as_str(&self) -> &'static str {
185        match self {
186            Self::Rule => "rule",
187            Self::LabelName(_) => "label_name",
188            Self::LabelValue { .. } => "label_value",
189        }
190    }
191}
192
193impl fmt::Display for Unframed {
194    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195        match self {
196            Self::Rule => f.write_str("the rule is empty or holds a newline"),
197            Self::LabelName(n) => write!(f, "label name {n:?} is empty or holds a newline or '='"),
198            Self::LabelValue { name } => write!(f, "label {name:?}'s value holds a newline"),
199        }
200    }
201}
202
203/// FNV-1a, 64 bits: offset basis `0xcbf29ce484222325`, prime
204/// `0x100000001b3` (§2.2).
205fn fnv1a_64(bytes: &[u8]) -> u64 {
206    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
207    for &b in bytes {
208        h ^= u64::from(b);
209        h = h.wrapping_mul(0x0100_0000_01b3);
210    }
211    h
212}
213
214/// The input: the rule, then `\n<name>=<value>` per label, sorted by name,
215/// then by value, in byte order (§2.2). `str`'s order is byte order.
216fn frame(rule: &str, labels: &mut [(&str, &str)]) -> String {
217    labels.sort_unstable();
218    let mut input = String::from(rule);
219    for (name, value) in labels.iter() {
220        input.push('\n');
221        input.push_str(name);
222        input.push('=');
223        input.push_str(value);
224    }
225    input
226}
227
228fn render(input: &str) -> String {
229    key_hex(fnv1a_64(input.as_bytes()))
230}
231
232/// An alert key's 64 bits as its 16 lowercase hexadecimal digits (§2.2):
233/// how `alarms.v2` shows the integer a record by words carries.
234#[must_use]
235pub fn key_hex(key: u64) -> String {
236    format!("{key:016x}")
237}
238
239/// An alert key's 16 lowercase hexadecimal digits as its 64 bits, `None`
240/// for any other text: the integer an `alarms.v2` record carries in `key`.
241#[must_use]
242pub fn key_integer(key: &str) -> Option<u64> {
243    crate::chunk::is_lower_hex(key, 16)
244        .then(|| u64::from_str_radix(key, 16).ok())
245        .flatten()
246}
247
248/// The strict recipe (§2.2): host-scoped labels removed, then the input
249/// framed and hashed, or refused when the rule or a discriminating label
250/// breaks the framing (§2.3). `labels` are every label of the document.
251///
252/// ```
253/// use zenkey_model::alarms::alert_key;
254/// let key = alert_key("link_down", [("port", "eth0"), ("host", "h-3fa9c2d41b7e"), ("peer", "r2")]);
255/// assert_eq!(key.as_deref(), Ok("a659f813308ad1da"));
256/// ```
257///
258/// # Errors
259///
260/// [`Unframed`], for the first part that breaks the framing: the rule,
261/// then the labels in the order given.
262pub fn alert_key<'a>(
263    rule: &str,
264    labels: impl IntoIterator<Item = (&'a str, &'a str)>,
265) -> Result<String, Unframed> {
266    if rule.is_empty() || rule.contains('\n') {
267        return Err(Unframed::Rule);
268    }
269    let mut kept = Vec::new();
270    for (name, value) in labels {
271        if is_host_scoped(name) {
272            continue;
273        }
274        if name.is_empty() || name.contains(['\n', '=']) {
275            return Err(Unframed::LabelName(name.to_owned()));
276        }
277        if value.contains('\n') {
278            return Err(Unframed::LabelValue {
279                name: name.to_owned(),
280            });
281        }
282        kept.push((name, value));
283    }
284    Ok(render(&frame(rule, &mut kept)))
285}
286
287/// The sanitizing step (§2.3): host-scoped labels removed, then a newline
288/// becomes `_` in the rule and in each value, a newline or `=` becomes `_`
289/// in each name, an empty rule becomes `unnamed` and an empty name `_`. It
290/// changes nothing in framed input, so a reader can always apply it.
291#[must_use]
292pub fn sanitize<'a>(
293    rule: &str,
294    labels: impl IntoIterator<Item = (&'a str, &'a str)>,
295) -> (String, Vec<(String, String)>) {
296    let rule = rule.replace('\n', "_");
297    let rule = if rule.is_empty() {
298        UNNAMED.to_owned()
299    } else {
300        rule
301    };
302    let labels = labels
303        .into_iter()
304        .filter(|(n, _)| !is_host_scoped(n))
305        .map(|(n, v)| {
306            let n = n.replace(['\n', '='], "_");
307            (
308                if n.is_empty() { "_".to_owned() } else { n },
309                v.replace('\n', "_"),
310            )
311        })
312        .collect();
313    (rule, labels)
314}
315
316/// What a reader derives from a document (§2.3).
317#[derive(Debug, Clone, PartialEq, Eq)]
318pub struct Derived {
319    /// The alert key: 16 lowercase hex digits.
320    pub key: String,
321    /// The input hashed: the framed, sanitized rule and discriminating
322    /// labels.
323    pub input: String,
324    /// Whether the strict recipe accepts the document as it is: `false`
325    /// when the key went through the sanitizing step.
326    pub framed: bool,
327}
328
329impl Derived {
330    /// The alert key as its 64 bits ([`key_integer`]).
331    #[must_use]
332    pub fn integer(&self) -> u64 {
333        fnv1a_64(self.input.as_bytes())
334    }
335}
336
337/// The reader's recipe (§2.3): [`sanitize`], then frame and hash. It never
338/// refuses, and on framed input it is [`alert_key`].
339#[must_use]
340pub fn derive<'a>(rule: &str, labels: impl IntoIterator<Item = (&'a str, &'a str)>) -> Derived {
341    let labels: Vec<(&str, &str)> = labels.into_iter().collect();
342    let framed = alert_key(rule, labels.iter().copied()).is_ok();
343    let (rule, sanitized) = sanitize(rule, labels);
344    let mut pairs: Vec<(&str, &str)> = sanitized
345        .iter()
346        .map(|(n, v)| (n.as_str(), v.as_str()))
347        .collect();
348    let input = frame(&rule, &mut pairs);
349    Derived {
350        key: render(&input),
351        input,
352        framed,
353    }
354}
355
356// --- §2.4: the document ----------------------------------------------------------
357
358/// A severity (§2.4), ordered: `Info` < `Warning` < `Critical`.
359#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
360#[serde(rename_all = "lowercase")]
361pub enum Severity {
362    Info,
363    Warning,
364    Critical,
365}
366
367impl Severity {
368    /// The wire token.
369    #[must_use]
370    pub fn as_str(self) -> &'static str {
371        match self {
372            Self::Info => "info",
373            Self::Warning => "warning",
374            Self::Critical => "critical",
375        }
376    }
377
378    /// The severity a wire token names, or `None`.
379    #[must_use]
380    pub fn parse(s: &str) -> Option<Self> {
381        match s {
382            "info" => Some(Self::Info),
383            "warning" => Some(Self::Warning),
384            "critical" => Some(Self::Critical),
385            _ => None,
386        }
387    }
388}
389
390impl fmt::Display for Severity {
391    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
392        f.write_str(self.as_str())
393    }
394}
395
396/// An alarm's state, in its document (§2.4, §2.6).
397#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
398#[serde(rename_all = "lowercase")]
399pub enum State {
400    Firing,
401    Resolved,
402}
403
404impl State {
405    /// The wire token.
406    #[must_use]
407    pub fn as_str(self) -> &'static str {
408        match self {
409            Self::Firing => "firing",
410            Self::Resolved => "resolved",
411        }
412    }
413}
414
415/// One alarm's document, `alarms.v1.Alarm` (§2.4, §3). Members the 1.0
416/// schema does not name are ignored when read, as a later minor may add
417/// some.
418#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
419pub struct Alarm {
420    /// Milliseconds since the Unix epoch, on the owner's clock, of the
421    /// latest transition (§2.5).
422    pub timestamp: u64,
423    /// The instant of the latest refresh, on a refresh only (§2.5).
424    #[serde(default, skip_serializing_if = "Option::is_none")]
425    pub observed_at_ms: Option<u64>,
426    pub rule: String,
427    pub severity: Severity,
428    pub state: State,
429    pub summary: String,
430    #[serde(default, skip_serializing_if = "Option::is_none")]
431    pub category: Option<String>,
432    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
433    pub labels: BTreeMap<String, String>,
434}
435
436/// Why a payload is no document a reader can read (§2.4).
437#[derive(Debug, Clone, PartialEq, Eq)]
438pub enum Invalid {
439    /// Not strict JSON (text 0.2, F-126): not UTF-8, not JSON, a duplicate
440    /// member, a number that is not finite, or a string with no UTF-8 form
441    /// (a lone surrogate escape), with why. Only [`decode`] reports it.
442    Json(String),
443    /// Outside the 1.0 schema, with where and why.
444    Schema(String),
445    /// A time outside 0 to 2^53−1 ms, naming the member.
446    TimeRange(&'static str),
447}
448
449impl Invalid {
450    /// The fixture's token.
451    #[must_use]
452    pub fn as_str(&self) -> &'static str {
453        match self {
454            Self::Json(_) => "json",
455            Self::Schema(_) => "schema",
456            Self::TimeRange(_) => "time_range",
457        }
458    }
459}
460
461impl fmt::Display for Invalid {
462    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
463        match self {
464            Self::Json(why) => write!(f, "not strict JSON: {why}"),
465            Self::Schema(why) => write!(f, "outside alarms.v1.Alarm: {why}"),
466            Self::TimeRange(m) => write!(f, "{m} is outside 0 to 2^53-1 ms"),
467        }
468    }
469}
470
471/// An integral number as the 1.0 schema reads one (`1.0` included, JSON
472/// Schema 2020-12): `Ok(Some(n))` within 0 to 2^53−1, `Ok(None)` for an
473/// integer outside it, `Err` for a value that is no integer.
474fn time(v: &Value) -> Result<Option<u64>, ()> {
475    let Value::Number(n) = v else { return Err(()) };
476    if let Some(u) = n.as_u64() {
477        return Ok((u <= MAX_TIME_MS).then_some(u));
478    }
479    if n.is_i64() {
480        return Ok(None);
481    }
482    let f = n.as_f64().ok_or(())?;
483    if !f.is_finite() || f.fract() != 0.0 {
484        return Err(());
485    }
486    // `-0.0 >= 0.0` holds, and is the integer 0.
487    #[allow(
488        clippy::cast_precision_loss,
489        clippy::cast_possible_truncation,
490        clippy::cast_sign_loss
491    )]
492    Ok((f >= 0.0 && f <= MAX_TIME_MS as f64).then_some(f as u64))
493}
494
495impl Alarm {
496    /// Reads a decoded payload (§2.4): the 1.0 schema's members, types and
497    /// enums, then the times' range.
498    ///
499    /// # Errors
500    ///
501    /// [`Invalid`]: the schema's first refusal, then a time out of range.
502    pub fn from_json(v: &Value) -> Result<Self, Invalid> {
503        let schema = |why: String| Invalid::Schema(why);
504        let Value::Object(o) = v else {
505            return Err(schema("not an object".into()));
506        };
507        for m in ["timestamp", "rule", "severity", "state", "summary"] {
508            if !o.contains_key(m) {
509                return Err(schema(format!("/{m}: missing")));
510            }
511        }
512        let string = |m: &str| -> Result<Option<String>, Invalid> {
513            match o.get(m) {
514                None => Ok(None),
515                Some(Value::String(s)) => Ok(Some(s.clone())),
516                Some(_) => Err(Invalid::Schema(format!("/{m}: not a string"))),
517            }
518        };
519        let integer = |m: &'static str| -> Result<Option<Option<u64>>, Invalid> {
520            match o.get(m) {
521                None => Ok(None),
522                Some(t) => time(t)
523                    .map(Some)
524                    .map_err(|()| Invalid::Schema(format!("/{m}: not an integer"))),
525            }
526        };
527        // Present by the loop above; refused, never a panic, if it is not.
528        let missing = |m: &str| Invalid::Schema(format!("/{m}: missing"));
529        let timestamp = integer("timestamp")?.ok_or_else(|| missing("timestamp"))?;
530        let observed_at_ms = integer("observed_at_ms")?;
531        let rule = string("rule")?.ok_or_else(|| missing("rule"))?;
532        let summary = string("summary")?.ok_or_else(|| missing("summary"))?;
533        let category = string("category")?;
534        let severity = match o.get("severity") {
535            Some(Value::String(s)) => Severity::parse(s),
536            _ => None,
537        }
538        .ok_or_else(|| schema("/severity: not info, warning or critical".into()))?;
539        let state = match o.get("state").and_then(Value::as_str) {
540            Some("firing") => State::Firing,
541            Some("resolved") => State::Resolved,
542            _ => return Err(schema("/state: not firing or resolved".into())),
543        };
544        let mut labels = BTreeMap::new();
545        match o.get("labels") {
546            None => {}
547            Some(Value::Object(l)) => {
548                for (n, v) in l {
549                    let Value::String(v) = v else {
550                        return Err(schema(format!("/labels/{n}: not a string")));
551                    };
552                    labels.insert(n.clone(), v.clone());
553                }
554            }
555            Some(_) => return Err(schema("/labels: not an object".into())),
556        }
557        let timestamp = timestamp.ok_or(Invalid::TimeRange("timestamp"))?;
558        let observed_at_ms = match observed_at_ms {
559            None => None,
560            Some(t) => Some(t.ok_or(Invalid::TimeRange("observed_at_ms"))?),
561        };
562        Ok(Self {
563            timestamp,
564            observed_at_ms,
565            rule,
566            severity,
567            state,
568            summary,
569            category,
570            labels,
571        })
572    }
573
574    /// The labels, as the recipe takes them.
575    pub fn label_pairs(&self) -> impl Iterator<Item = (&str, &str)> {
576        self.labels.iter().map(|(n, v)| (n.as_str(), v.as_str()))
577    }
578
579    /// What a reader derives from this document (§2.3).
580    #[must_use]
581    pub fn derive(&self) -> Derived {
582        derive(&self.rule, self.label_pairs())
583    }
584
585    /// The alert key of this document (§2.2, §2.3).
586    #[must_use]
587    pub fn alert_key(&self) -> String {
588        self.derive().key
589    }
590
591    /// The document's problems (§2.4), in this order: the errors, then the
592    /// warnings.
593    #[must_use]
594    pub fn check(&self) -> Vec<Problem> {
595        let mut out = Vec::new();
596        if let Some(o) = self.observed_at_ms {
597            if o < self.timestamp {
598                out.push(Problem::ObservedBeforeTimestamp);
599            }
600            if self.state == State::Resolved {
601                out.push(Problem::ObservedOnResolved);
602            }
603        }
604        if let Err(u) = alert_key(&self.rule, self.label_pairs()) {
605            out.push(Problem::Unframed(u));
606        }
607        for n in self.labels.keys() {
608            if !is_label_name(n) {
609                out.push(Problem::LabelName(n.clone()));
610            }
611        }
612        out
613    }
614}
615
616/// Reads a payload's bytes as a document (§2.4, text 0.2): strict JSON
617/// first, as core §3.3's D000 reads a descriptor (UTF-8, RFC 8259, no
618/// duplicate member at any depth, every number finite, every string with a
619/// UTF-8 form), then [`Alarm::from_json`]. So two readers never read two
620/// severities, or derive two keys, from one put (F-126).
621///
622/// # Errors
623///
624/// [`Invalid::Json`] for bytes that are not strict JSON, else
625/// [`Alarm::from_json`]'s.
626pub fn decode(bytes: &[u8]) -> Result<Alarm, Invalid> {
627    let text = std::str::from_utf8(bytes).map_err(|e| Invalid::Json(format!("not UTF-8: {e}")))?;
628    let v = crate::strict::parse_json(text).map_err(|e| Invalid::Json(e.to_string()))?;
629    Alarm::from_json(&v)
630}
631
632/// The recommended form of a label name (§2.4): one or more
633/// `[a-z][a-z0-9_]*` segments joined by `.`.
634#[must_use]
635pub fn is_label_name(name: &str) -> bool {
636    name.split('.').all(|seg| {
637        let mut cs = seg.bytes();
638        cs.next().is_some_and(|c| c.is_ascii_lowercase())
639            && cs.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_')
640    })
641}
642
643/// Whether a problem breaks a MUST (an error) or a SHOULD (a warning).
644#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
645pub enum Gravity {
646    Error,
647    Warning,
648}
649
650/// A problem of a readable document (§2.4).
651#[derive(Debug, Clone, PartialEq, Eq)]
652pub enum Problem {
653    /// `observed_at_ms` earlier than `timestamp`: an error.
654    ObservedBeforeTimestamp,
655    /// `observed_at_ms` on a resolved document: an error.
656    ObservedOnResolved,
657    /// The rule or a discriminating label breaks the framing, so the key
658    /// is derived through the sanitizing step (§2.3): a warning.
659    Unframed(Unframed),
660    /// A label name outside the recommended form: a warning.
661    LabelName(String),
662}
663
664impl Problem {
665    /// The fixture's token.
666    #[must_use]
667    pub fn as_str(&self) -> &'static str {
668        match self {
669            Self::ObservedBeforeTimestamp => "observed_before_timestamp",
670            Self::ObservedOnResolved => "observed_on_resolved",
671            Self::Unframed(_) => "unframed",
672            Self::LabelName(_) => "label_name_form",
673        }
674    }
675
676    /// An error or a warning.
677    #[must_use]
678    pub fn gravity(&self) -> Gravity {
679        match self {
680            Self::ObservedBeforeTimestamp | Self::ObservedOnResolved => Gravity::Error,
681            Self::Unframed(_) | Self::LabelName(_) => Gravity::Warning,
682        }
683    }
684}
685
686impl fmt::Display for Problem {
687    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
688        match self {
689            Self::ObservedBeforeTimestamp => f.write_str("observed_at_ms is before timestamp"),
690            Self::ObservedOnResolved => f.write_str("a resolved document carries observed_at_ms"),
691            Self::Unframed(u) => {
692                write!(f, "{u}, so the key is derived through the sanitizing step")
693            }
694            Self::LabelName(n) => write!(f, "label name {n:?} is not lowercase dotted snake_case"),
695        }
696    }
697}
698
699// --- §2.6: transitions ----------------------------------------------------------
700
701/// One sample of one alarm key, in the owner's stamp order (core §4.2).
702#[derive(Debug, Clone, Copy)]
703pub enum Sample<'a> {
704    /// A put whose payload reads as a document.
705    Put(&'a Alarm),
706    /// A put whose payload does not (§2.4).
707    Unreadable,
708    /// A delete, or a `reply_del`.
709    Delete,
710}
711
712/// What one sample means for the alarm (§2.6), read from the document's
713/// `state`, never from the sample's kind.
714#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
715pub enum Transition {
716    /// Firing, from nothing held, from resolved, or with a new timestamp at
717    /// the same severity.
718    Raised,
719    /// Firing at another severity than the firing one held, either way.
720    Escalated,
721    /// The same transition, its content changed (a summary, a host-scoped
722    /// label, `observed_at_ms`).
723    Refreshed,
724    /// The document held, put again unchanged (`freshness.v1` §2.4).
725    Confirmed,
726    /// Resolved: a resolved document, or a delete of a firing one.
727    Resolved,
728    /// A delete of a key whose alarm was resolved, or not known.
729    Retired,
730    /// A put that does not read: the alarm's state is not known.
731    Unreadable,
732}
733
734impl Transition {
735    /// The fixture's token.
736    #[must_use]
737    pub fn as_str(self) -> &'static str {
738        match self {
739            Self::Raised => "raised",
740            Self::Escalated => "escalated",
741            Self::Refreshed => "refreshed",
742            Self::Confirmed => "confirmed",
743            Self::Resolved => "resolved",
744            Self::Retired => "retired",
745            Self::Unreadable => "unreadable",
746        }
747    }
748}
749
750impl fmt::Display for Transition {
751    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
752        f.write_str(self.as_str())
753    }
754}
755
756/// What §2.6's table reads of one put, under either major: its state, its
757/// severity and the instant of its latest transition (`timestamp`, or
758/// `alarms.v2`'s `at`).
759#[derive(Debug, Clone, Copy, PartialEq, Eq)]
760pub(crate) struct PutFacts<S, T> {
761    pub state: State,
762    pub severity: S,
763    pub at: T,
764}
765
766/// §2.6's table for a put against the same alarm held (`None`: nothing
767/// held), `equal` saying whether the two are equal in every member:
768/// escalated on another severity, raised or resolved again on another
769/// instant, else confirmed or refreshed. One table for both majors
770/// (`alarms.v2` §2.6).
771pub(crate) fn put_reads<S: PartialEq, T: PartialEq>(
772    held: Option<PutFacts<S, T>>,
773    put: PutFacts<S, T>,
774    equal: bool,
775) -> Transition {
776    use Transition as T;
777    let Some(h) = held else {
778        return match put.state {
779            State::Firing => T::Raised,
780            State::Resolved => T::Resolved,
781        };
782    };
783    match (h.state, put.state) {
784        (State::Firing, State::Firing) if put.severity != h.severity => T::Escalated,
785        (State::Resolved, State::Firing) => T::Raised,
786        (State::Firing, State::Resolved) => T::Resolved,
787        (State::Firing, State::Firing) if put.at != h.at => T::Raised,
788        (State::Resolved, State::Resolved) if put.at != h.at => T::Resolved,
789        _ if equal => T::Confirmed,
790        _ => T::Refreshed,
791    }
792}
793
794/// §2.6's column for a delete, or a tombstone, over the state held:
795/// resolved over a firing alarm, retired over a resolved one or nothing.
796pub(crate) fn delete_reads(held: Option<State>) -> Transition {
797    match held {
798        Some(State::Firing) => Transition::Resolved,
799        Some(State::Resolved) | None => Transition::Retired,
800    }
801}
802
803/// The transition `sample` makes from the document `held` (§2.6).
804#[must_use]
805pub fn transition(held: Option<&Alarm>, sample: Sample<'_>) -> Transition {
806    let facts = |a: &Alarm| PutFacts {
807        state: a.state,
808        severity: a.severity,
809        at: a.timestamp,
810    };
811    match sample {
812        Sample::Unreadable => Transition::Unreadable,
813        Sample::Delete => delete_reads(held.map(|h| h.state)),
814        Sample::Put(n) => put_reads(held.map(facts), facts(n), held == Some(n)),
815    }
816}
817
818/// One key's document as a reader follows it (§2.6): what it holds, and
819/// the transition each sample makes.
820#[derive(Debug, Clone, Default, PartialEq, Eq)]
821pub struct Track {
822    /// The document held: `None` before any, after a delete, and after a
823    /// put that did not read.
824    pub held: Option<Alarm>,
825}
826
827impl Track {
828    /// Reads one sample, the next in the owner's stamp order.
829    pub fn apply(&mut self, sample: Sample<'_>) -> Transition {
830        let t = transition(self.held.as_ref(), sample);
831        self.held = match sample {
832            Sample::Put(a) => Some(a.clone()),
833            Sample::Unreadable | Sample::Delete => None,
834        };
835        t
836    }
837}
838
839// --- §2.12: references ----------------------------------------------------------
840
841/// One alarm, named from another interface (§2.12): its owner's system and
842/// service, and its alert key, never packed into one string.
843#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
844pub struct AlarmRef {
845    pub system: String,
846    pub service: String,
847    pub alert_key: String,
848}
849
850impl AlarmRef {
851    /// The alarm's key: `zk2/<system>/<service>/alarms.v1/state/alarms/<alert_key>`,
852    /// the alert key slugged as any parameter value is (core §1.4).
853    ///
854    /// # Errors
855    ///
856    /// [`KeyError`] when the system or the service is not a name (core §1.2).
857    pub fn key(&self) -> Result<Key, KeyError> {
858        let addr = Addr::new(&self.system, &self.service)?;
859        let iface = IfaceId::new(NAME, 1)?;
860        grammar::data_key(
861            &addr,
862            &iface,
863            KindToken::State,
864            &[ALARMS_CHUNK, &chunk_slug(&self.alert_key)],
865        )
866    }
867
868    /// The alarm a key names, or `None` for a key that is not one of this
869    /// major's alarms.
870    #[must_use]
871    pub fn from_key(key: &str) -> Option<Self> {
872        let ZkKey::Data {
873            addr,
874            iface,
875            kind: KindToken::State,
876            resource,
877        } = grammar::parse(key).ok()?
878        else {
879            return None;
880        };
881        if iface.to_string() != IFACE {
882            return None;
883        }
884        let [lit, chunk] = resource.as_slice() else {
885            return None;
886        };
887        if lit != ALARMS_CHUNK {
888            return None;
889        }
890        Some(Self {
891            system: addr.system.as_str().to_owned(),
892            service: addr.service.as_str().to_owned(),
893            alert_key: chunk_unslug(chunk)?,
894        })
895    }
896}
897
898// --- §5: what a tool may conclude -----------------------------------------------
899
900/// What the descriptor of a present owner says (§2.13).
901#[derive(Debug, Clone, Copy, PartialEq, Eq)]
902pub enum Listing {
903    /// Its `interfaces` list `alarms.v1`, with its `"token"`, which plays
904    /// no part in a verdict.
905    Listed { token: bool },
906    /// Its `interfaces` do not list `alarms.v1`.
907    NotListed,
908    /// The descriptor could not be read.
909    Unread,
910}
911
912/// An owner's presence, as the reader saw it (core §8.1, §8.5).
913#[derive(Debug, Clone, Copy, PartialEq, Eq)]
914pub enum Presence {
915    /// Its instance token was seen, with what its descriptor says.
916    Present(Listing),
917    /// A complete read held no instance token of it.
918    Absent,
919    /// Its token was not seen, in a read possibly incomplete or refused.
920    Incomplete,
921    /// Across a constrained face, where presence does not cross, and the
922    /// deployment's word says the owner implements `alarms.v1` (§2.11):
923    /// whether the face lets the reader reach its alarms.
924    AcrossFace { reachable: bool },
925}
926
927/// The latest sample a reader holds of one key, by the owner's stamp
928/// (core §4.2).
929#[derive(Debug, Clone, Copy, PartialEq, Eq)]
930pub enum Latest {
931    /// A put of a firing document.
932    Firing,
933    /// A put of a resolved document.
934    Resolved,
935    /// A delete, or a `reply_del`.
936    Deleted,
937    /// A put that does not read (§2.4).
938    Undecodable,
939}
940
941/// One reading of one alarm key (§2.14).
942#[derive(Debug, Clone, Copy)]
943pub struct Reading<'a> {
944    pub presence: Presence,
945    /// The observations of the key, judged as `freshness.v1` judges them,
946    /// at [`TTL`]. A GET among them is the reader's seed, made after any
947    /// loss its subscription had (core §4.2): one that answered this key,
948    /// with a value or a `reply_del`, heals the loss for it; one that drew
949    /// nothing for it does not (text 0.2, F-128), unless it established the
950    /// owner's alarms and left the key out ([`Reading::left_out`], text
951    /// 0.5).
952    pub observations: &'a [Observation],
953    /// The latest sample read, or `None` when none was.
954    pub latest: Option<Latest>,
955    /// Whether that latest put's stamp's id is not the current
956    /// descriptor's `meta.zid`, compared by value (core §4.3, §3.3): an
957    /// earlier instance stamped it, or another session did, which is also
958    /// core §4.2's foreign-stamp finding. `false` when the descriptor
959    /// carries no `meta.zid`: a stamp is then unattributable, never foreign
960    /// (core §3.3). A re-mint that keeps its session keeps its zid, and is
961    /// not told apart (text 0.2, F-129).
962    pub previous_instance: bool,
963    /// Whether the owner's alarms are established in this reading
964    /// ([`owner_set`], §2.15): a key they do not hold then reads not firing.
965    pub held_whole: bool,
966    /// Whether the reader's latest complete GET of the owner's alarms, its
967    /// seed (§2.15), left this key out: it answered the key with neither a
968    /// value nor a `reply_del`, and nothing of the key arrived after that GET
969    /// was asked. With [`Reading::held_whole`], that GET is the one that
970    /// established the owner's alarms, and two things follow (§2.14):
971    /// - the sample the reader holds is none (step 5, text 0.3): the owner
972    ///   answers every live key (core S2), so the key's delete went past the
973    ///   tombstone window unheard;
974    /// - a loss before that GET is healed for the key (step 4, text 0.5,
975    ///   F-136): an owner's alarms are established only over a window that
976    ///   lost nothing, which after a loss runs from the first complete GET
977    ///   that followed it, so the GET was asked after the loss, and the
978    ///   window has heard everything of the key since.
979    ///
980    /// Without `held_whole` it plays no part: an empty reply set is no
981    /// verdict (core O5).
982    pub left_out: bool,
983}
984
985/// A question of §5, answered in the three states: a pole of each
986/// established kind, and the two unestablished kinds apart (core O5).
987#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
988pub enum Answer {
989    Yes,
990    No,
991    /// The question was put, and the reading could not answer it.
992    Unobservable,
993    /// Nobody put the question, or its premise does not hold.
994    NotAsked,
995}
996
997impl Answer {
998    /// The fixture's token.
999    #[must_use]
1000    pub fn as_str(self) -> &'static str {
1001        match self {
1002            Self::Yes => "yes",
1003            Self::No => "no",
1004            Self::Unobservable => "unobservable",
1005            Self::NotAsked => "not_asked",
1006        }
1007    }
1008}
1009
1010impl fmt::Display for Answer {
1011    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1012        f.write_str(self.as_str())
1013    }
1014}
1015
1016/// Why an answer is what it is: the fixture's reason class (§2.14, §2.15,
1017/// §5).
1018#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1019pub enum Reason {
1020    /// Is it firing, yes: a fresh firing document.
1021    Firing,
1022    /// Is it firing, no: a resolved document.
1023    Resolved,
1024    /// Is it firing, no: a delete or a `reply_del`, read as resolved.
1025    Deleted,
1026    /// Unobservable, or the stale question's yes: not confirmed within
1027    /// 900 s.
1028    Stale,
1029    /// The stale question's no: confirmed within 900 s.
1030    Fresh,
1031    /// The stale question, not asked: the latest is not firing.
1032    NotFiring,
1033    /// Not asked: absent, presence's word.
1034    Absent,
1035    /// Not asked: the descriptor does not list `alarms.v1`.
1036    NotListed,
1037    /// Unobservable: its token not seen, in a read possibly incomplete.
1038    PresenceIncomplete,
1039    /// Unobservable: the descriptor could not be read.
1040    NoDescriptor,
1041    /// Unobservable: across a face that does not let the reader reach the
1042    /// owner's alarms (§2.11).
1043    FaceClosed,
1044    /// Unobservable: across a face, nothing of the key arrived.
1045    NothingCrossed,
1046    /// Unobservable: across a face, where presence does not cross.
1047    AcrossFace,
1048    /// Not asked: only an archive was read, last-known (core S6).
1049    LastKnown,
1050    /// Not asked: the latest put is an earlier instance's last word, which
1051    /// the present instance has neither put nor answered (§2.14).
1052    PreviousInstance,
1053    /// Unobservable: a subscription lost deliveries, and no GET answered
1054    /// since.
1055    Incomplete,
1056    /// Unobservable: nothing of the key was read.
1057    NotRead,
1058    /// Is it firing, no: the owner's alarms, established, do not hold it.
1059    NotHeld,
1060    /// Unobservable: the latest put does not read (§2.4).
1061    Undecodable,
1062    /// An owner's alarms established: a complete GET that it answered.
1063    Answered,
1064    /// An owner's alarms established: a complete, empty GET, and a lossless
1065    /// window longer than the horizon, the owner present throughout.
1066    Window,
1067    /// An owner's alarms unobservable: no GET was made.
1068    NoSeed,
1069    /// An owner's alarms unobservable: the GET ended at its timeout, or
1070    /// with an error reply.
1071    SeedIncomplete,
1072    /// An owner's alarms unobservable: an empty GET and no window (core O5).
1073    NoMember,
1074    /// An owner's alarms unobservable: the window lost a delivery.
1075    WindowLost,
1076    /// An owner's alarms unobservable: the window was no longer than the
1077    /// horizon.
1078    WindowShort,
1079    /// An owner's alarms unobservable: the owner was not present
1080    /// throughout the window.
1081    OwnerGap,
1082    /// An owner's alarms unobservable: its revision uses `freshness.v2`,
1083    /// and the latest heartbeat of its alarms heard in the window was not
1084    /// in step with the reader's view, or none was heard (text 0.11).
1085    WindowUnconfirmed,
1086    /// Anything firing, yes.
1087    AnyFiring,
1088    /// Anything firing, no.
1089    NoneFiring,
1090    /// Anything firing, unobservable: an owner's alarms are.
1091    OwnerUnobservable,
1092    /// Anything firing, unobservable: the reads that found the owners in
1093    /// scope were not whole, so an owner they missed may fire (text 0.5,
1094    /// F-137).
1095    ScopeIncomplete,
1096    /// Anything firing, unobservable: an alarm at or above the severity,
1097    /// or of a severity not known, is.
1098    AlarmUnobservable,
1099    /// Anything firing, not asked: no owner's alarms were established or
1100    /// unobservable.
1101    NoOwner,
1102    /// Re-derives, yes: the strict recipe gives the key.
1103    Strict,
1104    /// Re-derives, yes: the sanitizing step gives the key (§2.3).
1105    Sanitized,
1106    /// Re-derives, no.
1107    Mismatch,
1108    /// Re-derives, not asked: a delete carries no document.
1109    NoDocument,
1110    /// `alarms.v2`. Is it firing, no: another identity's record is on its
1111    /// slot under its run, so it resolved and the reader lost that put
1112    /// (§2.6, §2.14).
1113    Rebound,
1114    /// `alarms.v2`. An owner's alarms established: one complete snapshot,
1115    /// with an entry or with none (§2.15).
1116    Snapshot,
1117    /// `alarms.v2`. An owner's alarms unobservable: no page of the
1118    /// snapshot, or a page missing.
1119    SnapshotIncomplete,
1120    /// `alarms.v2`. An owner's alarms unobservable: the snapshot's run is
1121    /// one no present descriptor states, an earlier instance's.
1122    SnapshotRun,
1123    /// `alarms.v2`. Do the slot's words derive its record's key, not
1124    /// asked: the record names a table's rule (§2.4).
1125    Table,
1126    /// `alarms.v2`. The same, not asked: no words were read.
1127    NoWords,
1128    /// `alarms.v2`. The same, not asked: no record is held on the slot.
1129    NoRecord,
1130    /// `alarms.v2`. The same, unobservable: the words do not read.
1131    Unreadable,
1132    /// Unobservable: the key's freshness, `freshness.v1`'s reason.
1133    Freshness(freshness::Reason),
1134}
1135
1136impl Reason {
1137    /// The fixture's token.
1138    #[must_use]
1139    pub fn as_str(self) -> &'static str {
1140        match self {
1141            Self::Firing => "firing",
1142            Self::Resolved => "resolved",
1143            Self::Deleted => "deleted",
1144            Self::Stale => "stale",
1145            Self::Fresh => "fresh",
1146            Self::NotFiring => "not_firing",
1147            Self::Absent => "absent",
1148            Self::NotListed => "not_listed",
1149            Self::PresenceIncomplete => "presence_incomplete",
1150            Self::NoDescriptor => "no_descriptor",
1151            Self::FaceClosed => "face_closed",
1152            Self::NothingCrossed => "nothing_crossed",
1153            Self::AcrossFace => "across_face",
1154            Self::LastKnown => "last_known",
1155            Self::PreviousInstance => "previous_instance",
1156            Self::Incomplete => "incomplete",
1157            Self::NotRead => "not_read",
1158            Self::NotHeld => "not_held",
1159            Self::Undecodable => "undecodable",
1160            Self::Answered => "answered",
1161            Self::Window => "window",
1162            Self::NoSeed => "no_seed",
1163            Self::SeedIncomplete => "seed_incomplete",
1164            Self::NoMember => "no_member",
1165            Self::WindowLost => "window_lost",
1166            Self::WindowShort => "window_short",
1167            Self::OwnerGap => "owner_gap",
1168            Self::WindowUnconfirmed => "window_unconfirmed",
1169            Self::AnyFiring => "any_firing",
1170            Self::NoneFiring => "none_firing",
1171            Self::OwnerUnobservable => "owner_unobservable",
1172            Self::ScopeIncomplete => "scope_incomplete",
1173            Self::AlarmUnobservable => "alarm_unobservable",
1174            Self::NoOwner => "no_owner",
1175            Self::Strict => "strict",
1176            Self::Sanitized => "sanitized",
1177            Self::Mismatch => "mismatch",
1178            Self::NoDocument => "no_document",
1179            Self::Rebound => "rebound",
1180            Self::Snapshot => "snapshot",
1181            Self::SnapshotIncomplete => "snapshot_incomplete",
1182            Self::SnapshotRun => "snapshot_run",
1183            Self::Table => "table",
1184            Self::NoWords => "no_words",
1185            Self::NoRecord => "no_record",
1186            Self::Unreadable => "unreadable",
1187            Self::Freshness(r) => r.as_str(),
1188        }
1189    }
1190
1191    /// The reason in words, for a tool's message.
1192    #[must_use]
1193    pub fn says(self) -> &'static str {
1194        match self {
1195            Self::Firing => "its owner says it fires, and confirmed it within 900 s",
1196            Self::Resolved => "its owner put it resolved",
1197            Self::Deleted => "its owner deleted it, which reads as resolved",
1198            Self::Stale => "its owner has not confirmed it within 900 s",
1199            Self::Fresh => "its owner confirmed it within 900 s",
1200            Self::NotFiring => "it is not firing",
1201            Self::Absent => "its owner is absent: presence's word, and its alarms are last-known",
1202            Self::NotListed => "its owner's descriptor does not list alarms.v1",
1203            Self::PresenceIncomplete => {
1204                "its owner's token was not seen, and the presence read may be incomplete or refused"
1205            }
1206            Self::NoDescriptor => "its owner's descriptor could not be read",
1207            Self::FaceClosed => "the constrained face does not let this reader reach its alarms",
1208            Self::NothingCrossed => "nothing of it has crossed the constrained face",
1209            Self::AcrossFace => {
1210                "its owner is across a constrained face, where presence does not cross"
1211            }
1212            Self::LastKnown => "only an archive's last-known word was read, never current",
1213            Self::PreviousInstance => {
1214                "the latest put is an earlier instance's, which the present one has not made its own"
1215            }
1216            Self::Incomplete => "deliveries were lost, and no GET answered since",
1217            Self::NotRead => "nothing of it was read",
1218            Self::NotHeld => "its owner's alarms, known whole, do not hold it",
1219            Self::Undecodable => "its latest put does not read as an alarms.v1 document",
1220            Self::Answered => "its owner answered a complete GET",
1221            Self::Window => {
1222                "a complete GET drew nothing, and a lossless window longer than 900 s heard no alarm"
1223            }
1224            Self::NoSeed => "no GET of its alarms was made",
1225            Self::SeedIncomplete => "the GET of its alarms ended at its timeout, or with an error",
1226            Self::NoMember => "the GET drew nothing, which is no verdict (core O5)",
1227            Self::WindowLost => "the window lost a delivery",
1228            Self::WindowShort => "the window was no longer than 900 s",
1229            Self::OwnerGap => "its owner was not present throughout the window",
1230            Self::WindowUnconfirmed => {
1231                "no heartbeat of its owner in the window said the reader holds its alarms"
1232            }
1233            Self::AnyFiring => "an alarm at or above the severity fires",
1234            Self::NoneFiring => "no alarm at or above the severity fires",
1235            Self::OwnerUnobservable => "an owner's alarms are not known whole",
1236            Self::ScopeIncomplete => {
1237                "the reads that found the owners in scope were not whole, so an owner they \
1238                 missed may fire"
1239            }
1240            Self::AlarmUnobservable => {
1241                "an alarm that may be at or above the severity is unobservable"
1242            }
1243            Self::NoOwner => "no owner in scope was asked",
1244            Self::Strict => "the key is the document's, by the strict recipe",
1245            Self::Sanitized => "the key is the document's, through the sanitizing step",
1246            Self::Mismatch => "the key is not the one its document derives",
1247            Self::NoDocument => "a delete carries no document",
1248            Self::Rebound => "another alarm's record is on its slot under its run, so it resolved",
1249            Self::Snapshot => "its owner answered one complete snapshot of its alarms",
1250            Self::SnapshotIncomplete => {
1251                "the read drew no page of its alarms' snapshot, or a page is missing"
1252            }
1253            Self::SnapshotRun => {
1254                "the snapshot's run is one no present descriptor states, an earlier instance's"
1255            }
1256            Self::Table => "the slot's record names a table's rule, which its table names",
1257            Self::NoWords => "no words were read on the slot",
1258            Self::NoRecord => "no record is held on the slot",
1259            Self::Unreadable => "the slot's words do not read as alarms.v2.Words",
1260            Self::Freshness(r) => r.says(),
1261        }
1262    }
1263}
1264
1265impl fmt::Display for Reason {
1266    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1267        f.write_str(self.as_str())
1268    }
1269}
1270
1271/// An answer and its reason.
1272#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1273pub struct Judged {
1274    pub answer: Answer,
1275    pub reason: Reason,
1276}
1277
1278impl Judged {
1279    const fn new(answer: Answer, reason: Reason) -> Self {
1280        Self { answer, reason }
1281    }
1282}
1283
1284/// §2.14's premises: presence, then the descriptor. `None` lets the
1285/// reading go on.
1286fn premises(p: Presence) -> Option<Judged> {
1287    use Answer::{NotAsked, Unobservable};
1288    match p {
1289        Presence::Absent => Some(Judged::new(NotAsked, Reason::Absent)),
1290        Presence::Incomplete => Some(Judged::new(Unobservable, Reason::PresenceIncomplete)),
1291        Presence::AcrossFace { reachable: false } => {
1292            Some(Judged::new(Unobservable, Reason::FaceClosed))
1293        }
1294        Presence::Present(Listing::NotListed) => Some(Judged::new(NotAsked, Reason::NotListed)),
1295        Presence::Present(Listing::Unread) => Some(Judged::new(Unobservable, Reason::NoDescriptor)),
1296        Presence::AcrossFace { reachable: true } | Presence::Present(Listing::Listed { .. }) => {
1297            None
1298        }
1299    }
1300}
1301
1302/// The latest sample of one alarm as §2.14's step 5 reads it, under either
1303/// major.
1304#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1305pub(crate) enum Step5 {
1306    /// A firing document, or a firing record, that reads.
1307    Firing,
1308    /// A put that does not read (§2.4).
1309    Undecodable,
1310    /// Not firing, and why: a resolved put, a delete, or `alarms.v2`'s
1311    /// `rebound`.
1312    Not(Reason),
1313}
1314
1315/// One reading of one alarm with its freshness judged: what §2.14's steps
1316/// take under either major (`alarms.v2` §2.14).
1317#[derive(Debug, Clone, Copy)]
1318pub(crate) struct Asked {
1319    pub presence: Presence,
1320    /// `freshness`'s verdict over the alarm's observations, at [`TTL`].
1321    pub freshness: freshness::Judged,
1322    /// A subscription lost deliveries, and no GET has answered the alarm
1323    /// since.
1324    pub lost: bool,
1325    pub latest: Option<Step5>,
1326    /// [`Reading::previous_instance`].
1327    pub previous_instance: bool,
1328    /// [`Reading::held_whole`].
1329    pub held_whole: bool,
1330    /// [`Reading::left_out`].
1331    pub left_out: bool,
1332}
1333
1334impl Asked {
1335    /// Whether the read that established the owner's alarms left the alarm
1336    /// out ([`Reading::left_out`]): §2.14 steps 4 and 5.
1337    fn left_out(&self) -> bool {
1338        self.held_whole && self.left_out
1339    }
1340
1341    /// One reading of one `alarms.v1` key.
1342    fn of(r: &Reading<'_>) -> Asked {
1343        // A subscription lost deliveries, and since then no GET answered
1344        // the key (§2.14 step 4, text 0.5, F-136).
1345        let lossy = r.observations.iter().any(|o| {
1346            matches!(
1347                o,
1348                Observation::Subscribed {
1349                    complete: false,
1350                    ..
1351                }
1352            )
1353        });
1354        let answered = r
1355            .observations
1356            .iter()
1357            .any(|o| matches!(o, Observation::Got { reply: Some(_), .. }));
1358        Asked {
1359            presence: r.presence,
1360            freshness: freshness::judge_all(&horizon(), r.observations),
1361            lost: lossy && !answered,
1362            latest: r.latest.map(|l| match l {
1363                Latest::Firing => Step5::Firing,
1364                Latest::Undecodable => Step5::Undecodable,
1365                Latest::Resolved => Step5::Not(Reason::Resolved),
1366                Latest::Deleted => Step5::Not(Reason::Deleted),
1367            }),
1368            previous_instance: r.previous_instance,
1369            held_whole: r.held_whole,
1370            left_out: r.left_out,
1371        }
1372    }
1373}
1374
1375/// What the reading of an alarm established before its freshness was asked,
1376/// or its freshness. Shared by [`firing_asked`] and [`stale_firing_asked`].
1377enum Read {
1378    Done(Judged),
1379    /// The latest is a readable firing put, or a put that does not read,
1380    /// with the alarm's freshness.
1381    Judge {
1382        firing: bool,
1383        freshness: freshness::Judged,
1384    },
1385}
1386
1387fn read(r: &Asked, not_firing: impl Fn(Reason) -> Judged) -> Read {
1388    use Answer::{NotAsked, Unobservable};
1389    let f = r.freshness;
1390    if f.verdict == freshness::Verdict::NotAsked && f.reason == freshness::Reason::LastKnown {
1391        return Read::Done(Judged::new(NotAsked, Reason::LastKnown));
1392    }
1393    // A loss, unless the read that established the owner's alarms left the
1394    // alarm out, which heals it (step 4, text 0.5, F-136).
1395    if r.lost && !r.left_out() {
1396        return Read::Done(Judged::new(Unobservable, Reason::Incomplete));
1397    }
1398    // The sample an alarm left out by the establishing read holds is none
1399    // (step 5, text 0.3).
1400    let latest = if r.left_out() { None } else { r.latest };
1401    match latest {
1402        None if r.held_whole => Read::Done(not_firing(Reason::NotHeld)),
1403        None => Read::Done(Judged::new(
1404            Unobservable,
1405            if matches!(r.presence, Presence::AcrossFace { .. }) {
1406                Reason::NothingCrossed
1407            } else {
1408                Reason::NotRead
1409            },
1410        )),
1411        Some(Step5::Not(reason)) => Read::Done(not_firing(reason)),
1412        Some(Step5::Firing | Step5::Undecodable) if r.previous_instance => {
1413            Read::Done(Judged::new(NotAsked, Reason::PreviousInstance))
1414        }
1415        Some(l @ (Step5::Firing | Step5::Undecodable)) => Read::Judge {
1416            firing: l == Step5::Firing,
1417            freshness: f,
1418        },
1419    }
1420}
1421
1422/// §5's first question over a reading as judged, either major's
1423/// ([`firing`], [`v2::firing`]).
1424pub(crate) fn firing_asked(r: &Asked) -> Judged {
1425    use Answer::{No, Unobservable, Yes};
1426    if let Some(j) = premises(r.presence) {
1427        return j;
1428    }
1429    let (firing, f) = match read(r, |reason| Judged::new(No, reason)) {
1430        Read::Done(j) => return j,
1431        Read::Judge { firing, freshness } => (firing, freshness),
1432    };
1433    match f.verdict {
1434        freshness::Verdict::Fresh if firing => Judged::new(Yes, Reason::Firing),
1435        freshness::Verdict::Fresh => Judged::new(Unobservable, Reason::Undecodable),
1436        // Across a face nothing says the key exists until something
1437        // crosses (`freshness.v1` §2.5, "a member it knows").
1438        freshness::Verdict::Stale
1439            if f.reason == freshness::Reason::NoDelivery
1440                && matches!(r.presence, Presence::AcrossFace { .. }) =>
1441        {
1442            Judged::new(Unobservable, Reason::NothingCrossed)
1443        }
1444        freshness::Verdict::Stale => Judged::new(Unobservable, Reason::Stale),
1445        freshness::Verdict::Unobservable | freshness::Verdict::NotAsked => {
1446            Judged::new(Unobservable, Reason::Freshness(f.reason))
1447        }
1448    }
1449}
1450
1451/// §5's last question over a reading as judged, either major's
1452/// ([`stale_firing`], [`v2::stale_firing`]).
1453pub(crate) fn stale_firing_asked(r: &Asked) -> Judged {
1454    use Answer::{No, NotAsked, Unobservable, Yes};
1455    if let Some(j) = premises(r.presence) {
1456        return j;
1457    }
1458    if matches!(r.presence, Presence::AcrossFace { .. }) {
1459        return Judged::new(Unobservable, Reason::AcrossFace);
1460    }
1461    let f = match read(r, |_| Judged::new(NotAsked, Reason::NotFiring)) {
1462        Read::Done(j) => return j,
1463        Read::Judge { firing: false, .. } => {
1464            return Judged::new(Unobservable, Reason::Undecodable);
1465        }
1466        Read::Judge { freshness, .. } => freshness,
1467    };
1468    match f.verdict {
1469        freshness::Verdict::Stale => Judged::new(Yes, Reason::Stale),
1470        freshness::Verdict::Fresh => Judged::new(No, Reason::Fresh),
1471        freshness::Verdict::Unobservable | freshness::Verdict::NotAsked => {
1472            Judged::new(Unobservable, Reason::Freshness(f.reason))
1473        }
1474    }
1475}
1476
1477/// §5's first question, "is this alarm firing?", by §2.14's order:
1478/// presence, the descriptor, an archive alone, a loss, the latest sample,
1479/// then its freshness at 900 s. Yes is the finding.
1480#[must_use]
1481pub fn firing(r: &Reading<'_>) -> Judged {
1482    firing_asked(&Asked::of(r))
1483}
1484
1485/// §5's last question, "is this firing alarm past its horizon while its
1486/// owner is present?", over the reading [`firing`] takes. Yes is the
1487/// finding, about the owner (§2.7).
1488#[must_use]
1489pub fn stale_firing(r: &Reading<'_>) -> Judged {
1490    stale_firing_asked(&Asked::of(r))
1491}
1492
1493/// How a reader's S4 GET of an owner's alarms ended (§2.15, core §2.7).
1494#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1495pub enum Seed {
1496    /// At the routers' final reply, with no error reply, with this many
1497    /// keys answered with a value. A `reply_del` is not one.
1498    Complete { members: usize },
1499    /// At its timeout, or with an error reply.
1500    Incomplete,
1501}
1502
1503/// A reader's subscription window on an owner's alarms, declared before
1504/// its GET (core §4.2), as core §2.7 establishes one. After a loss, the
1505/// window starts again at the first complete GET that followed it, the
1506/// reader's re-seed (text 0.2, F-128): a loss before that GET is healed by
1507/// it, one after it is not.
1508#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1509pub struct Window {
1510    /// How long it has listened, from its declaration plus its reply
1511    /// timeout (core §2.7), or since the re-seed that followed its latest
1512    /// loss.
1513    pub listened: Duration,
1514    /// It lost no delivery over the window, established as core §2.7 says
1515    /// (0.25, 0.27).
1516    pub lossless: bool,
1517    /// The owner held its instance token from the window's start until one
1518    /// lease after its end (core §2.7). Not asked across a face, where
1519    /// presence does not cross.
1520    pub present_throughout: bool,
1521    /// Of an owner whose revision uses `freshness.v2` (§2.15, text 0.11):
1522    /// whether the latest heartbeat covering its alarms heard in the
1523    /// window was in step with the reader's view, its section's digest and
1524    /// live count the view's; `Some(false)` too when none was heard. `None`
1525    /// for an owner that re-puts, under `freshness.v1`.
1526    pub in_step: Option<bool>,
1527}
1528
1529/// Whether an owner's alarms are known whole (§2.15).
1530#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1531pub enum SetVerdict {
1532    Established,
1533    Unobservable,
1534    NotAsked,
1535}
1536
1537impl SetVerdict {
1538    /// The fixture's token.
1539    #[must_use]
1540    pub fn as_str(self) -> &'static str {
1541        match self {
1542            Self::Established => "established",
1543            Self::Unobservable => "unobservable",
1544            Self::NotAsked => "not_asked",
1545        }
1546    }
1547}
1548
1549/// A [`SetVerdict`] and its reason.
1550#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1551pub struct SetJudged {
1552    pub verdict: SetVerdict,
1553    pub reason: Reason,
1554}
1555
1556/// Whether an owner's alarms are known whole, by §2.15's order (text 0.2,
1557/// F-130): §2.14's steps 1 and 2, with their reasons; the seed; a window
1558/// that lost a delivery, then a gap in presence, which is not asked across
1559/// a face; a seed the owner answered; then, for an empty seed, the face and
1560/// the window.
1561#[must_use]
1562pub fn owner_set(presence: Presence, seed: Option<Seed>, window: Option<Window>) -> SetJudged {
1563    let j = |verdict, reason| SetJudged { verdict, reason };
1564    use SetVerdict::{Established, NotAsked, Unobservable};
1565    if let Some(p) = premises(presence) {
1566        return j(
1567            match p.answer {
1568                Answer::NotAsked => NotAsked,
1569                _ => Unobservable,
1570            },
1571            p.reason,
1572        );
1573    }
1574    let members = match seed {
1575        None => return j(Unobservable, Reason::NoSeed),
1576        Some(Seed::Incomplete) => return j(Unobservable, Reason::SeedIncomplete),
1577        Some(Seed::Complete { members }) => members,
1578    };
1579    // Across a face presence does not cross, so whether the owner was
1580    // present throughout is not asked there (text 0.2, F-130).
1581    let across = matches!(presence, Presence::AcrossFace { .. });
1582    if let Some(w) = window {
1583        if !w.lossless {
1584            return j(Unobservable, Reason::WindowLost);
1585        }
1586        if !w.present_throughout && !across {
1587            return j(Unobservable, Reason::OwnerGap);
1588        }
1589    }
1590    if members > 0 {
1591        return j(Established, Reason::Answered);
1592    }
1593    if across {
1594        return j(Unobservable, Reason::AcrossFace);
1595    }
1596    match window {
1597        None => j(Unobservable, Reason::NoMember),
1598        Some(w) if w.listened <= TTL => j(Unobservable, Reason::WindowShort),
1599        Some(w) if w.in_step == Some(false) => j(Unobservable, Reason::WindowUnconfirmed),
1600        Some(_) => j(Established, Reason::Window),
1601    }
1602}
1603
1604/// One owner in a scope, as §5's second question reads it.
1605#[derive(Debug, Clone, Copy)]
1606pub struct OwnerAlarms<'a> {
1607    /// Whether its alarms are known whole ([`owner_set`]).
1608    pub set: SetJudged,
1609    /// Each alarm read of it: [`firing`]'s answer, and the severity of its
1610    /// latest document, `None` when none reads.
1611    pub alarms: &'a [(Judged, Option<Severity>)],
1612}
1613
1614/// §5's second question over a scope.
1615#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1616pub struct AnyFiring {
1617    pub answer: Answer,
1618    pub reason: Reason,
1619    /// The alarms firing at or above the severity.
1620    pub firing: usize,
1621    /// The owners, by their set's verdict.
1622    pub established: usize,
1623    pub unobservable: usize,
1624    pub not_asked: usize,
1625}
1626
1627/// Whether the reads that found a scope's owners were whole (§2.15, text
1628/// 0.5, F-137): what a reader knows of the owners its selector selects.
1629#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1630pub enum ScopeRead {
1631    /// Its latest presence read ran to its final reply, and, when it
1632    /// follows instance tokens since, it lost none of their moves; or,
1633    /// across a constrained face, the deployment's word names the owner
1634    /// (§2.11).
1635    Whole,
1636    /// Its latest presence read possibly incomplete or refused, none made,
1637    /// or a loss since: an owner it missed is counted nowhere, and may fire.
1638    NotWhole,
1639}
1640
1641/// §5's second question, "is anything firing at or above `at_least` under
1642/// this selector?", over the owners in scope (§2.15), by its order: yes on
1643/// any alarm firing at or above it, whatever else is known; then an owner
1644/// unobservable; then the scope's reads not whole (text 0.5, F-137); then
1645/// an established owner's alarm that may be at or above it unobservable;
1646/// then no owner established, not asked; else no. Yes is the finding.
1647#[must_use]
1648pub fn any_firing(at_least: Severity, owners: &[OwnerAlarms<'_>], scope: ScopeRead) -> AnyFiring {
1649    let mut out = AnyFiring {
1650        answer: Answer::No,
1651        reason: Reason::NoneFiring,
1652        firing: 0,
1653        established: 0,
1654        unobservable: 0,
1655        not_asked: 0,
1656    };
1657    let mut alarm_doubt = false;
1658    for o in owners {
1659        match o.set.verdict {
1660            SetVerdict::Established => out.established += 1,
1661            SetVerdict::Unobservable => out.unobservable += 1,
1662            SetVerdict::NotAsked => out.not_asked += 1,
1663        }
1664        for (j, sev) in o.alarms {
1665            let high = sev.is_none_or(|s| s >= at_least);
1666            match j.answer {
1667                Answer::Yes if high && sev.is_some() => out.firing += 1,
1668                Answer::Yes | Answer::Unobservable
1669                    if high && o.set.verdict == SetVerdict::Established =>
1670                {
1671                    alarm_doubt = true;
1672                }
1673                _ => {}
1674            }
1675        }
1676    }
1677    (out.answer, out.reason) = if out.firing > 0 {
1678        (Answer::Yes, Reason::AnyFiring)
1679    } else if out.unobservable > 0 {
1680        (Answer::Unobservable, Reason::OwnerUnobservable)
1681    } else if scope == ScopeRead::NotWhole {
1682        (Answer::Unobservable, Reason::ScopeIncomplete)
1683    } else if alarm_doubt {
1684        (Answer::Unobservable, Reason::AlarmUnobservable)
1685    } else if out.established == 0 {
1686        (Answer::NotAsked, Reason::NoOwner)
1687    } else {
1688        (Answer::No, Reason::NoneFiring)
1689    };
1690    out
1691}
1692
1693/// The payload a key holds, as §5's third question reads it.
1694#[derive(Debug, Clone, Copy)]
1695pub enum Payload<'a> {
1696    /// A document.
1697    Alarm(&'a Alarm),
1698    /// A put that does not read (§2.4).
1699    Unreadable,
1700    /// A delete: no document.
1701    Deleted,
1702}
1703
1704/// §5's third question, "does this key re-derive from its document?"
1705/// (§2.2, §2.3), for the alert key the key carries (the template's value,
1706/// unslugged). No is the finding; a yes through the sanitizing step is the
1707/// owner's break of §2.3's SHOULD, which a tool MAY report.
1708#[must_use]
1709pub fn rederives(alert_key: &str, payload: Payload<'_>) -> Judged {
1710    match payload {
1711        Payload::Deleted => Judged::new(Answer::NotAsked, Reason::NoDocument),
1712        Payload::Unreadable => Judged::new(Answer::Unobservable, Reason::Undecodable),
1713        Payload::Alarm(a) => {
1714            let d = a.derive();
1715            if d.key != alert_key {
1716                Judged::new(Answer::No, Reason::Mismatch)
1717            } else if d.framed {
1718                Judged::new(Answer::Yes, Reason::Strict)
1719            } else {
1720                Judged::new(Answer::Yes, Reason::Sanitized)
1721            }
1722        }
1723    }
1724}
1725
1726#[cfg(test)]
1727mod tests {
1728    use super::*;
1729    use serde_json::json;
1730
1731    #[test]
1732    fn the_test_vector() {
1733        let labels = [("peer", "r2"), ("port", "eth0"), ("host", "h-3fa9c2d41b7e")];
1734        assert_eq!(
1735            alert_key("link_down", labels).as_deref(),
1736            Ok("a659f813308ad1da")
1737        );
1738        let d = derive("link_down", labels);
1739        assert_eq!(d.input, "link_down\npeer=r2\nport=eth0");
1740        assert_eq!(d.input.len(), 27);
1741        assert!(d.framed);
1742        assert_eq!(d.key, "a659f813308ad1da");
1743    }
1744
1745    #[test]
1746    fn host_scoped_labels_drop_out_first() {
1747        assert!(is_host_scoped("host"));
1748        assert!(is_host_scoped("host.id"));
1749        assert!(is_host_scoped("host."));
1750        assert!(!is_host_scoped("hostname"));
1751        assert!(!is_host_scoped("Host"));
1752        let with = alert_key("r", [("port", "1"), ("host.id", "a\nb"), ("host.=", "")]);
1753        assert_eq!(with, alert_key("r", [("port", "1")]));
1754    }
1755
1756    #[test]
1757    fn sanitizing_is_the_identity_on_framed_input() {
1758        let labels = [("b", "2"), ("a", "1"), ("host", "h")];
1759        let (rule, s) = sanitize("r", labels);
1760        assert_eq!(rule, "r");
1761        assert_eq!(s, vec![("b".into(), "2".into()), ("a".into(), "1".into())]);
1762        assert_eq!(
1763            derive("r", labels).key,
1764            alert_key("r", labels).expect("framed")
1765        );
1766    }
1767
1768    #[test]
1769    fn unframed_input_is_sanitized_not_refused() {
1770        assert_eq!(
1771            alert_key("link\ndown", [("port", "22")]),
1772            Err(Unframed::Rule)
1773        );
1774        let d = derive("link\ndown", [("port", "22")]);
1775        assert!(!d.framed);
1776        assert_eq!(Ok(d.key), alert_key("link_down", [("port", "22")]));
1777        assert_eq!(derive("", []).input, "unnamed");
1778        assert_eq!(derive("\n", []).input, "_");
1779        assert_eq!(derive("x", [("", "1")]).input, "x\n_=1");
1780        // Two names that sanitize to one sort by value.
1781        assert_eq!(
1782            derive("x", [("a=b", "2"), ("a_b", "1")]).input,
1783            "x\na_b=1\na_b=2"
1784        );
1785    }
1786
1787    fn doc(v: Value) -> Alarm {
1788        Alarm::from_json(&v).expect("a document")
1789    }
1790
1791    fn firing_doc() -> Value {
1792        json!({"timestamp": 1000, "rule": "link_down", "severity": "warning",
1793               "state": "firing", "summary": "s", "labels": {"peer": "r2"}})
1794    }
1795
1796    #[test]
1797    fn documents_read_as_the_schema_says() {
1798        let a = doc(firing_doc());
1799        assert_eq!(a.severity, Severity::Warning);
1800        assert!(a.check().is_empty());
1801        // An integral float is an integer (JSON Schema 2020-12).
1802        let mut v = firing_doc();
1803        v["timestamp"] = json!(1000.0);
1804        assert_eq!(doc(v).timestamp, 1000);
1805        // Unknown members are ignored.
1806        let mut v = firing_doc();
1807        v["later"] = json!({"x": 1});
1808        assert_eq!(doc(v), a);
1809        for (m, bad) in [
1810            ("severity", json!("major")),
1811            ("state", json!("acked")),
1812            ("timestamp", json!(1.5)),
1813            ("labels", json!({"a": 1})),
1814            ("observed_at_ms", Value::Null),
1815        ] {
1816            let mut v = firing_doc();
1817            v[m] = bad;
1818            assert_eq!(
1819                Alarm::from_json(&v).map_err(|e| e.as_str()),
1820                Err("schema"),
1821                "{m}"
1822            );
1823        }
1824        let mut v = firing_doc();
1825        v["timestamp"] = json!(-1);
1826        assert_eq!(Alarm::from_json(&v), Err(Invalid::TimeRange("timestamp")));
1827        // Serialized back, the document is the schema's.
1828        assert_eq!(serde_json::to_value(&a).unwrap(), firing_doc());
1829    }
1830
1831    /// F-126 (text 0.2): a payload is strict JSON before it is a document.
1832    #[test]
1833    fn a_payload_is_strict_json_first() {
1834        let ok = br#"{"timestamp": 1000, "rule": "r", "severity": "info", "state": "firing", "summary": "s"}"#;
1835        assert_eq!(decode(ok).expect("reads").rule, "r");
1836        for (bad, why) in [
1837            (
1838                &br#"{"timestamp": 1, "rule": "r", "severity": "info", "severity": "critical", "state": "firing", "summary": "s"}"#[..],
1839                "a duplicate member",
1840            ),
1841            (
1842                br#"{"timestamp": 1, "rule": "r", "severity": "info", "state": "firing", "summary": "s", "labels": {"a": "1", "a": "2"}}"#,
1843                "a duplicate label",
1844            ),
1845            (
1846                br#"{"timestamp": NaN, "rule": "r", "severity": "info", "state": "firing", "summary": "s"}"#,
1847                "NaN",
1848            ),
1849            (
1850                br#"{"timestamp": 1, "rule": "\ud800", "severity": "info", "state": "firing", "summary": "s"}"#,
1851                "a lone surrogate",
1852            ),
1853            (b"\xff", "not UTF-8"),
1854            (
1855                br#"{"timestamp": 1, "rule": "r", "severity": "info", "state": "firing", "summary": "s"} x"#,
1856                "trailing text",
1857            ),
1858        ] {
1859            assert_eq!(decode(bad).map_err(|e| e.as_str()), Err("json"), "{why}");
1860        }
1861        let schema = br#"{"timestamp": 1, "rule": "r", "severity": "major", "state": "firing", "summary": "s"}"#;
1862        assert_eq!(decode(schema).map_err(|e| e.as_str()), Err("schema"));
1863    }
1864
1865    #[test]
1866    fn a_documents_problems() {
1867        let mut v = firing_doc();
1868        v["observed_at_ms"] = json!(999);
1869        v["state"] = json!("resolved");
1870        v["labels"] = json!({"Peer": "r2", "a=b": "c"});
1871        let p: Vec<&str> = doc(v).check().iter().map(Problem::as_str).collect();
1872        assert_eq!(
1873            p,
1874            [
1875                "observed_before_timestamp",
1876                "observed_on_resolved",
1877                "unframed",
1878                "label_name_form",
1879                "label_name_form"
1880            ]
1881        );
1882        assert!(is_label_name("host.boot_id"));
1883        assert!(is_label_name("if_index"));
1884        assert!(!is_label_name("host."));
1885        assert!(!is_label_name("_x"));
1886        assert!(!is_label_name(""));
1887    }
1888
1889    #[test]
1890    fn transitions_take_the_state_from_the_document() {
1891        let raise = doc(firing_doc());
1892        let mut escalate = raise.clone();
1893        escalate.severity = Severity::Critical;
1894        escalate.timestamp = 2000;
1895        let mut refresh = escalate.clone();
1896        refresh.summary = "t".into();
1897        refresh.observed_at_ms = Some(3000);
1898        let mut resolve = refresh.clone();
1899        resolve.state = State::Resolved;
1900        resolve.timestamp = 4000;
1901        resolve.observed_at_ms = None;
1902        let mut t = Track::default();
1903        let seen: Vec<Transition> = [
1904            Sample::Put(&raise),
1905            Sample::Put(&escalate),
1906            Sample::Put(&refresh),
1907            Sample::Put(&refresh),
1908            Sample::Put(&resolve),
1909            Sample::Delete,
1910            Sample::Put(&raise),
1911            Sample::Delete,
1912        ]
1913        .into_iter()
1914        .map(|s| t.apply(s))
1915        .collect();
1916        use Transition as T;
1917        assert_eq!(
1918            seen,
1919            [
1920                T::Raised,
1921                T::Escalated,
1922                T::Refreshed,
1923                T::Confirmed,
1924                T::Resolved,
1925                T::Retired,
1926                T::Raised,
1927                T::Resolved
1928            ]
1929        );
1930    }
1931
1932    #[test]
1933    fn a_ref_is_the_alarms_key() {
1934        let r = AlarmRef {
1935            system: "h-3fa9c2d41b7e".into(),
1936            service: "snmp.router01".into(),
1937            alert_key: "a659f813308ad1da".into(),
1938        };
1939        let k = r.key().expect("a key");
1940        assert_eq!(
1941            k.as_str(),
1942            "zk2/h-3fa9c2d41b7e/snmp.router01/alarms.v1/state/alarms/a659f813308ad1da"
1943        );
1944        assert_eq!(AlarmRef::from_key(k.as_str()), Some(r));
1945        assert_eq!(AlarmRef::from_key("zk2/a/b/health.v1/state/status"), None);
1946    }
1947
1948    fn sub(age: u64) -> Observation {
1949        Observation::Subscribed {
1950            last: Some(freshness::Last::Put(Duration::from_secs(age))),
1951            listened: Duration::from_secs(2000),
1952            complete: true,
1953        }
1954    }
1955
1956    #[test]
1957    fn firing_and_stale() {
1958        let present = Presence::Present(Listing::Listed { token: true });
1959        let fresh = [sub(10)];
1960        let stale = [sub(1000)];
1961        let r = |obs, latest| Reading {
1962            presence: present,
1963            observations: obs,
1964            latest: Some(latest),
1965            previous_instance: false,
1966            held_whole: false,
1967            left_out: false,
1968        };
1969        assert_eq!(firing(&r(&fresh, Latest::Firing)).answer, Answer::Yes);
1970        assert_eq!(firing(&r(&stale, Latest::Firing)).reason, Reason::Stale);
1971        assert_eq!(stale_firing(&r(&stale, Latest::Firing)).answer, Answer::Yes);
1972        assert_eq!(firing(&r(&stale, Latest::Resolved)).answer, Answer::No);
1973        assert_eq!(
1974            firing(&Reading {
1975                presence: Presence::Absent,
1976                ..r(&fresh, Latest::Firing)
1977            })
1978            .reason,
1979            Reason::Absent
1980        );
1981    }
1982
1983    #[test]
1984    fn a_scope_answers_no_only_when_known_whole() {
1985        let est = owner_set(
1986            Presence::Present(Listing::Listed { token: false }),
1987            Some(Seed::Complete { members: 0 }),
1988            Some(Window {
1989                listened: Duration::from_secs(901),
1990                lossless: true,
1991                present_throughout: true,
1992                in_step: None,
1993            }),
1994        );
1995        assert_eq!(est.verdict, SetVerdict::Established);
1996        let warn = [(
1997            Judged::new(Answer::Yes, Reason::Firing),
1998            Some(Severity::Warning),
1999        )];
2000        let one = [OwnerAlarms {
2001            set: est,
2002            alarms: &warn,
2003        }];
2004        let a = any_firing(Severity::Critical, &one, ScopeRead::Whole);
2005        assert_eq!((a.answer, a.firing), (Answer::No, 0));
2006        let a = any_firing(Severity::Warning, &one, ScopeRead::Whole);
2007        assert_eq!((a.answer, a.firing), (Answer::Yes, 1));
2008        assert_eq!(
2009            any_firing(Severity::Info, &[], ScopeRead::Whole).answer,
2010            Answer::NotAsked
2011        );
2012        // A scope whose reads were not whole is never no, nor not asked
2013        // (text 0.5, F-137): an owner they missed may fire.
2014        let a = any_firing(Severity::Critical, &one, ScopeRead::NotWhole);
2015        assert_eq!(
2016            (a.answer, a.reason),
2017            (Answer::Unobservable, Reason::ScopeIncomplete)
2018        );
2019        assert_eq!(
2020            any_firing(Severity::Info, &[], ScopeRead::NotWhole).reason,
2021            Reason::ScopeIncomplete
2022        );
2023        assert_eq!(
2024            any_firing(Severity::Warning, &one, ScopeRead::NotWhole).answer,
2025            Answer::Yes,
2026            "a yes whatever else is unknown"
2027        );
2028    }
2029
2030    /// §2.14 steps 4 and 5 (text 0.3, 0.5, F-136): the GET that established
2031    /// the owner's alarms leaves a key out, so the sample held is none, and
2032    /// a loss before it is healed for the key; without the establishing,
2033    /// neither.
2034    #[test]
2035    fn a_key_the_establishing_get_left_out_is_not_held() {
2036        let lossy = [
2037            Observation::Subscribed {
2038                last: Some(freshness::Last::Put(Duration::from_secs(600))),
2039                listened: Duration::from_secs(2000),
2040                complete: false,
2041            },
2042            Observation::Got {
2043                reply: None,
2044                clock: freshness::ClockTrust::Trusted {
2045                    delta: freshness::DEFAULT_DELTA,
2046                },
2047            },
2048        ];
2049        let r = Reading {
2050            presence: Presence::Present(Listing::Listed { token: true }),
2051            observations: &lossy,
2052            latest: Some(Latest::Firing),
2053            previous_instance: false,
2054            held_whole: true,
2055            left_out: true,
2056        };
2057        let pair = |j: Judged| (j.answer, j.reason);
2058        assert_eq!(pair(firing(&r)), (Answer::No, Reason::NotHeld));
2059        assert_eq!(
2060            pair(stale_firing(&r)),
2061            (Answer::NotAsked, Reason::NotFiring)
2062        );
2063        let not_established = Reading {
2064            held_whole: false,
2065            ..r
2066        };
2067        assert_eq!(
2068            pair(firing(&not_established)),
2069            (Answer::Unobservable, Reason::Incomplete)
2070        );
2071        let answered_or_newer = Reading {
2072            left_out: false,
2073            ..r
2074        };
2075        assert_eq!(
2076            pair(firing(&answered_or_newer)),
2077            (Answer::Unobservable, Reason::Incomplete)
2078        );
2079    }
2080}