1pub 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
62pub const PROFILE: &str = "alarms.v1";
64
65pub const IFACE: &str = "alarms.v1";
67
68pub const NAME: &str = "alarms";
70
71pub const VOCABULARY: &[&str] = &[];
74
75pub const ALARMS: &str = "alarms/{alert_key}";
77
78const ALARMS_CHUNK: &str = "alarms";
80
81pub const TTL: Duration = Duration::from_secs(900);
83
84pub const REFRESH: Duration = Duration::from_secs(450);
87
88pub const MAX_ALARMS: u64 = 256;
90
91pub const HOST: &str = "host";
93
94pub const HOST_SCOPED_PREFIX: &str = "host.";
96
97pub const UNNAMED: &str = "unnamed";
99
100pub const MAX_TIME_MS: u64 = (1 << 53) - 1;
102
103#[must_use]
105pub fn horizon() -> Horizon {
106 Horizon::Within(TTL)
107}
108
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
113pub enum Major {
114 V1,
116 V2,
118}
119
120impl Major {
121 #[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 #[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 #[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#[must_use]
164pub fn is_host_scoped(name: &str) -> bool {
165 name == HOST || name.starts_with(HOST_SCOPED_PREFIX)
166}
167
168#[derive(Debug, Clone, PartialEq, Eq)]
172pub enum Unframed {
173 Rule,
175 LabelName(String),
177 LabelValue { name: String },
179}
180
181impl Unframed {
182 #[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
203fn 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
214fn 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#[must_use]
235pub fn key_hex(key: u64) -> String {
236 format!("{key:016x}")
237}
238
239#[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
248pub 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#[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#[derive(Debug, Clone, PartialEq, Eq)]
318pub struct Derived {
319 pub key: String,
321 pub input: String,
324 pub framed: bool,
327}
328
329impl Derived {
330 #[must_use]
332 pub fn integer(&self) -> u64 {
333 fnv1a_64(self.input.as_bytes())
334 }
335}
336
337#[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#[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 #[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 #[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#[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 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
419pub struct Alarm {
420 pub timestamp: u64,
423 #[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#[derive(Debug, Clone, PartialEq, Eq)]
438pub enum Invalid {
439 Json(String),
443 Schema(String),
445 TimeRange(&'static str),
447}
448
449impl Invalid {
450 #[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
471fn 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 #[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 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 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 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 #[must_use]
581 pub fn derive(&self) -> Derived {
582 derive(&self.rule, self.label_pairs())
583 }
584
585 #[must_use]
587 pub fn alert_key(&self) -> String {
588 self.derive().key
589 }
590
591 #[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
616pub 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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
645pub enum Gravity {
646 Error,
647 Warning,
648}
649
650#[derive(Debug, Clone, PartialEq, Eq)]
652pub enum Problem {
653 ObservedBeforeTimestamp,
655 ObservedOnResolved,
657 Unframed(Unframed),
660 LabelName(String),
662}
663
664impl Problem {
665 #[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 #[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#[derive(Debug, Clone, Copy)]
703pub enum Sample<'a> {
704 Put(&'a Alarm),
706 Unreadable,
708 Delete,
710}
711
712#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
715pub enum Transition {
716 Raised,
719 Escalated,
721 Refreshed,
724 Confirmed,
726 Resolved,
728 Retired,
730 Unreadable,
732}
733
734impl Transition {
735 #[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#[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
766pub(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
794pub(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#[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#[derive(Debug, Clone, Default, PartialEq, Eq)]
821pub struct Track {
822 pub held: Option<Alarm>,
825}
826
827impl Track {
828 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#[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 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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
902pub enum Listing {
903 Listed { token: bool },
906 NotListed,
908 Unread,
910}
911
912#[derive(Debug, Clone, Copy, PartialEq, Eq)]
914pub enum Presence {
915 Present(Listing),
917 Absent,
919 Incomplete,
921 AcrossFace { reachable: bool },
925}
926
927#[derive(Debug, Clone, Copy, PartialEq, Eq)]
930pub enum Latest {
931 Firing,
933 Resolved,
935 Deleted,
937 Undecodable,
939}
940
941#[derive(Debug, Clone, Copy)]
943pub struct Reading<'a> {
944 pub presence: Presence,
945 pub observations: &'a [Observation],
953 pub latest: Option<Latest>,
955 pub previous_instance: bool,
963 pub held_whole: bool,
966 pub left_out: bool,
983}
984
985#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
988pub enum Answer {
989 Yes,
990 No,
991 Unobservable,
993 NotAsked,
995}
996
997impl Answer {
998 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1019pub enum Reason {
1020 Firing,
1022 Resolved,
1024 Deleted,
1026 Stale,
1029 Fresh,
1031 NotFiring,
1033 Absent,
1035 NotListed,
1037 PresenceIncomplete,
1039 NoDescriptor,
1041 FaceClosed,
1044 NothingCrossed,
1046 AcrossFace,
1048 LastKnown,
1050 PreviousInstance,
1053 Incomplete,
1056 NotRead,
1058 NotHeld,
1060 Undecodable,
1062 Answered,
1064 Window,
1067 NoSeed,
1069 SeedIncomplete,
1072 NoMember,
1074 WindowLost,
1076 WindowShort,
1079 OwnerGap,
1082 WindowUnconfirmed,
1086 AnyFiring,
1088 NoneFiring,
1090 OwnerUnobservable,
1092 ScopeIncomplete,
1096 AlarmUnobservable,
1099 NoOwner,
1102 Strict,
1104 Sanitized,
1106 Mismatch,
1108 NoDocument,
1110 Rebound,
1114 Snapshot,
1117 SnapshotIncomplete,
1120 SnapshotRun,
1123 Table,
1126 NoWords,
1128 NoRecord,
1130 Unreadable,
1132 Freshness(freshness::Reason),
1134}
1135
1136impl Reason {
1137 #[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 #[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#[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
1284fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1305pub(crate) enum Step5 {
1306 Firing,
1308 Undecodable,
1310 Not(Reason),
1313}
1314
1315#[derive(Debug, Clone, Copy)]
1318pub(crate) struct Asked {
1319 pub presence: Presence,
1320 pub freshness: freshness::Judged,
1322 pub lost: bool,
1325 pub latest: Option<Step5>,
1326 pub previous_instance: bool,
1328 pub held_whole: bool,
1330 pub left_out: bool,
1332}
1333
1334impl Asked {
1335 fn left_out(&self) -> bool {
1338 self.held_whole && self.left_out
1339 }
1340
1341 fn of(r: &Reading<'_>) -> Asked {
1343 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
1375enum Read {
1378 Done(Judged),
1379 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 if r.lost && !r.left_out() {
1396 return Read::Done(Judged::new(Unobservable, Reason::Incomplete));
1397 }
1398 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
1422pub(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 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
1451pub(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#[must_use]
1481pub fn firing(r: &Reading<'_>) -> Judged {
1482 firing_asked(&Asked::of(r))
1483}
1484
1485#[must_use]
1489pub fn stale_firing(r: &Reading<'_>) -> Judged {
1490 stale_firing_asked(&Asked::of(r))
1491}
1492
1493#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1495pub enum Seed {
1496 Complete { members: usize },
1499 Incomplete,
1501}
1502
1503#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1509pub struct Window {
1510 pub listened: Duration,
1514 pub lossless: bool,
1517 pub present_throughout: bool,
1521 pub in_step: Option<bool>,
1527}
1528
1529#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1531pub enum SetVerdict {
1532 Established,
1533 Unobservable,
1534 NotAsked,
1535}
1536
1537impl SetVerdict {
1538 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1551pub struct SetJudged {
1552 pub verdict: SetVerdict,
1553 pub reason: Reason,
1554}
1555
1556#[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 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#[derive(Debug, Clone, Copy)]
1606pub struct OwnerAlarms<'a> {
1607 pub set: SetJudged,
1609 pub alarms: &'a [(Judged, Option<Severity>)],
1612}
1613
1614#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1616pub struct AnyFiring {
1617 pub answer: Answer,
1618 pub reason: Reason,
1619 pub firing: usize,
1621 pub established: usize,
1623 pub unobservable: usize,
1624 pub not_asked: usize,
1625}
1626
1627#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1630pub enum ScopeRead {
1631 Whole,
1636 NotWhole,
1639}
1640
1641#[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#[derive(Debug, Clone, Copy)]
1695pub enum Payload<'a> {
1696 Alarm(&'a Alarm),
1698 Unreadable,
1700 Deleted,
1702}
1703
1704#[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 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 let mut v = firing_doc();
1803 v["timestamp"] = json!(1000.0);
1804 assert_eq!(doc(v).timestamp, 1000);
1805 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 assert_eq!(serde_json::to_value(&a).unwrap(), firing_doc());
1829 }
1830
1831 #[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 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 #[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(¬_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}