1use std::collections::BTreeMap;
33use std::sync::OnceLock;
34
35use serde_json::{Map, Value, json};
36
37use super::{
38 Answer, Asked, Judged, Presence, PutFacts, Reason, SetJudged, SetVerdict, Severity, State,
39 Step5, Transition,
40};
41use crate::collection::{self, Confirmation, Page};
42use crate::contract::Contract;
43use crate::freshness;
44use crate::grammar::{self, Addr, IfaceId, Key, KeyError, KindToken, ZkKey};
45use crate::heartbeat;
46use crate::packed::{self, Decimal, Fixed, Layout, ReadRefusal, WriteRefusal};
47use crate::template::Template;
48use crate::wire::{Envelope, Run, Seq, Stamp, Tag};
49use crate::words;
50
51pub const PROFILE: &str = "alarms.v2";
53
54pub const IFACE: &str = "alarms.v2";
56
57pub const FINGERPRINT: &str = "2292477cadf555dd09b07499ca048add4e48c63d60a209c13eaf543988c32cb7";
61
62pub const SCHEMA_STEM: &str = "alarms.v2";
65
66pub const PUBLISHED: &[&str] = &[
69 "sha256:fe59e748fc957322428ac633a0908d09aa8b6c66952f7a9cdd8608db715a2b2a",
70 "sha256:a3515ad47772ac778ccfbad3850a086ac18c28a9975eb7c8288c3437db9b99de",
71];
72
73#[must_use]
75pub fn is_published(id: &str) -> bool {
76 PUBLISHED.contains(&id)
77}
78
79pub const VOCABULARY: &[&str] = &["rules"];
82
83pub const RULES: &str = "alarms.rules";
85
86pub const ALARMS: &str = "alarms/{slot}";
88
89pub const WORDS: &str = "words/{slot}";
91
92const ALARMS_CHUNK: &str = "alarms";
93const WORDS_CHUNK: &str = "words";
94
95pub const ALARMS_COLL: u32 = 0;
98
99pub const WORDS_COLL: u32 = 1;
101
102pub const TAG: u8 = 11;
105
106pub const MAX_SLOTS: u16 = 256;
109
110pub const MAX_RULES: usize = 255;
113
114const MAX_INDEX: u8 = 254;
116
117pub const LABELS_BITS: u32 = 24;
119
120pub const CLASS: heartbeat::Class = heartbeat::Class::Host;
124
125#[must_use]
128pub fn uses_v2(c: &Contract) -> bool {
129 words::uses(c, PROFILE)
130}
131
132fn iface() -> IfaceId {
133 IfaceId::new(super::NAME, 2).expect("alarms.v2 is an interface id")
134}
135
136#[must_use]
142pub fn parse_slot(chunk: &str) -> Option<u8> {
143 let digits = !chunk.is_empty() && chunk.bytes().all(|b| b.is_ascii_digit());
144 if !digits || (chunk.len() > 1 && chunk.starts_with('0')) {
145 return None;
146 }
147 chunk.parse().ok()
148}
149
150#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
152pub struct SlotKey {
153 pub system: String,
154 pub service: String,
155 pub slot: u8,
156}
157
158fn slot_under(key: &str, chunk: &str) -> Option<SlotKey> {
159 let ZkKey::Data {
160 addr,
161 iface,
162 kind: KindToken::State,
163 resource,
164 } = grammar::parse(key).ok()?
165 else {
166 return None;
167 };
168 if iface.to_string() != IFACE {
169 return None;
170 }
171 let [lit, slot] = resource.as_slice() else {
172 return None;
173 };
174 if lit != chunk {
175 return None;
176 }
177 Some(SlotKey {
178 system: addr.system.as_str().to_owned(),
179 service: addr.service.as_str().to_owned(),
180 slot: parse_slot(slot)?,
181 })
182}
183
184#[must_use]
188pub fn slot_of(key: &str) -> Option<SlotKey> {
189 slot_under(key, ALARMS_CHUNK)
190}
191
192#[must_use]
194pub fn words_slot_of(key: &str) -> Option<SlotKey> {
195 slot_under(key, WORDS_CHUNK)
196}
197
198fn key_under(system: &str, service: &str, chunk: &str, slot: u8) -> Result<Key, KeyError> {
199 let addr = Addr::new(system, service)?;
200 grammar::data_key(
201 &addr,
202 &iface(),
203 KindToken::State,
204 &[chunk, &slot.to_string()],
205 )
206}
207
208pub fn alarm_key(system: &str, service: &str, slot: u8) -> Result<Key, KeyError> {
214 key_under(system, service, ALARMS_CHUNK, slot)
215}
216
217pub fn words_key(system: &str, service: &str, slot: u8) -> Result<Key, KeyError> {
223 key_under(system, service, WORDS_CHUNK, slot)
224}
225
226#[derive(Debug, Clone, PartialEq, Eq)]
231pub struct CollectionRead {
232 pub selector: String,
233 pub snapshot_key: String,
234}
235
236pub fn collection_read(system: &str, service: &str) -> Result<CollectionRead, KeyError> {
241 let addr = Addr::new(system, service)?;
242 let template = Template::parse(ALARMS).expect("the standard template parses");
243 let members = grammar::template_selector(&addr, &iface(), KindToken::State, &template);
244 let selector = collection::collection_read(&members, &template)
245 .expect("a template whose first chunk is a literal has a snapshot key");
246 let snapshot_key =
247 grammar::data_key(&addr, &iface(), KindToken::State, &[ALARMS_CHUNK])?.to_string();
248 Ok(CollectionRead {
249 selector,
250 snapshot_key,
251 })
252}
253
254pub const NOT_AVAILABLE: &str = "not_available";
259
260#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
263pub enum RuleIndex {
264 Table(u8),
266 NotAvailable,
269}
270
271impl RuleIndex {
272 #[must_use]
275 pub const fn new(i: u8) -> Option<RuleIndex> {
276 if i <= MAX_INDEX {
277 Some(RuleIndex::Table(i))
278 } else {
279 None
280 }
281 }
282
283 #[must_use]
286 pub const fn of(index: words::Index) -> RuleIndex {
287 match index {
288 words::Index::At(i) => RuleIndex::Table(i),
289 words::Index::OutOfRange => RuleIndex::NotAvailable,
290 }
291 }
292
293 #[must_use]
295 pub fn to_json(self) -> Value {
296 match self {
297 RuleIndex::Table(i) => json!(i),
298 RuleIndex::NotAvailable => json!(NOT_AVAILABLE),
299 }
300 }
301
302 #[must_use]
304 pub fn of_json(v: &Value) -> Option<RuleIndex> {
305 match v {
306 Value::String(s) if s == NOT_AVAILABLE => Some(RuleIndex::NotAvailable),
307 v => RuleIndex::new(u8::try_from(v.as_u64()?).ok()?),
308 }
309 }
310}
311
312#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
315pub enum Argument {
316 Code(u32),
318 NotAvailable,
320}
321
322impl Argument {
323 pub const MAX: u32 = 1_048_574;
325
326 #[must_use]
328 pub const fn new(n: u32) -> Option<Argument> {
329 if n <= Argument::MAX {
330 Some(Argument::Code(n))
331 } else {
332 None
333 }
334 }
335
336 #[must_use]
338 pub fn to_json(self) -> Value {
339 match self {
340 Argument::Code(n) => json!(n),
341 Argument::NotAvailable => json!(NOT_AVAILABLE),
342 }
343 }
344
345 #[must_use]
347 pub fn of_json(v: &Value) -> Option<Argument> {
348 match v {
349 Value::String(s) if s == NOT_AVAILABLE => Some(Argument::NotAvailable),
350 v => Argument::new(u32::try_from(v.as_u64()?).ok()?),
351 }
352 }
353}
354
355fn schema() -> Value {
359 json!({"types": {"Alarm": {"fields": [
360 {"name": "state", "type": "enum", "values": ["firing", "resolved"]},
361 {"name": "severity", "type": "enum", "values": ["info", "warning", "critical"],
362 "escape": true},
363 {"name": "rule", "type": "int", "minimum": 0, "maximum": MAX_INDEX,
364 "reserved": [NOT_AVAILABLE]},
365 {"name": "at", "type": "time", "optional": true},
366 {"name": "labels", "type": "int", "minimum": 0, "maximum": (1u32 << LABELS_BITS) - 1,
367 "optional": true},
368 {"name": "argument", "type": "int", "minimum": 0, "maximum": Argument::MAX,
369 "reserved": [NOT_AVAILABLE]},
370 {"name": "key", "type": "counter", "width": 64, "optional": true},
371 packed::MARKER,
372 ]}}})
373}
374
375pub const TYPE: &str = "Alarm";
377
378#[must_use]
381pub fn layout() -> &'static Layout {
382 static LAYOUT: OnceLock<Layout> = OnceLock::new();
383 LAYOUT.get_or_init(|| {
384 packed::layout_in(&schema(), TYPE).expect("the standard schema's declaration reads")
385 })
386}
387
388#[must_use]
395pub fn time_at(unix_ms: i128, epoch: i64) -> Option<i64> {
396 packed::time_code(unix_ms, Some(epoch), false).ok()?;
397 i64::try_from(unix_ms.div_euclid(1000)).ok()
398}
399
400#[derive(Debug, Clone, Copy, PartialEq, Eq)]
403pub enum Refused {
404 Core(WriteRefusal),
406 KeyWithRule,
408 KeyMissing,
410 ByWordsFields,
413}
414
415impl Refused {
416 #[must_use]
418 pub fn token(self) -> &'static str {
419 match self {
420 Self::Core(r) => r.token(),
421 Self::KeyWithRule => "key_with_rule",
422 Self::KeyMissing => "key_missing",
423 Self::ByWordsFields => "by_words_fields",
424 }
425 }
426}
427
428impl std::fmt::Display for Refused {
429 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
430 match self {
431 Self::Core(r) => r.fmt(f),
432 Self::KeyWithRule => f.write_str("key_with_rule: `key` beside a table's rule"),
433 Self::KeyMissing => f.write_str("key_missing: no `key` under a rule not_available"),
434 Self::ByWordsFields => {
435 f.write_str("by_words_fields: `labels` or an `argument` under a rule not_available")
436 }
437 }
438 }
439}
440
441impl std::error::Error for Refused {}
442
443impl From<WriteRefusal> for Refused {
444 fn from(r: WriteRefusal) -> Self {
445 Refused::Core(r)
446 }
447}
448
449#[derive(Debug, Clone, Copy, PartialEq, Eq)]
452pub enum Undecodable {
453 Core(ReadRefusal),
457 KeyWithRule,
459 KeyMissing,
461}
462
463impl Undecodable {
464 #[must_use]
466 pub fn token(self) -> &'static str {
467 match self {
468 Self::Core(r) => r.token(),
469 Self::KeyWithRule => "key_with_rule",
470 Self::KeyMissing => "key_missing",
471 }
472 }
473}
474
475impl std::fmt::Display for Undecodable {
476 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
477 match self {
478 Self::Core(r) => r.fmt(f),
479 Self::KeyWithRule => f.write_str("key_with_rule: `key` beside a table's rule"),
480 Self::KeyMissing => f.write_str("key_missing: no `key` under a rule not_available"),
481 }
482 }
483}
484
485impl std::error::Error for Undecodable {}
486
487impl From<ReadRefusal> for Undecodable {
488 fn from(r: ReadRefusal) -> Self {
489 Undecodable::Core(r)
490 }
491}
492
493#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
496pub struct Record {
497 pub state: State,
498 pub severity: Option<Severity>,
501 pub rule: RuleIndex,
502 pub at: Option<i64>,
507 pub labels: Option<u32>,
510 pub argument: Argument,
511 pub key: Option<u64>,
513}
514
515fn time_json(seconds: i64) -> Value {
518 json!(i128::from(seconds) * 1000)
519}
520
521fn time_of_json(v: &Value) -> Option<i64> {
522 let ms = match v {
523 Value::Number(n) => n
524 .as_i64()
525 .map(i128::from)
526 .or_else(|| n.as_u64().map(i128::from))?,
527 _ => return None,
528 };
529 i64::try_from(ms.div_euclid(1000)).ok()
530}
531
532impl Record {
533 #[must_use]
537 pub fn new(state: State, severity: Severity, fields: Fields, at: Option<i64>) -> Record {
538 Record {
539 state,
540 severity: Some(severity),
541 rule: fields.rule,
542 at,
543 labels: fields.labels,
544 argument: fields.argument,
545 key: fields.key,
546 }
547 }
548
549 #[must_use]
552 pub const fn is_by_words(&self) -> bool {
553 matches!(self.rule, RuleIndex::NotAvailable)
554 }
555
556 #[must_use]
561 pub fn to_json(&self) -> Value {
562 let mut m = Map::new();
563 m.insert("state".into(), json!(self.state.as_str()));
564 m.insert(
565 "severity".into(),
566 self.severity.map_or(Value::Null, |s| json!(s.as_str())),
567 );
568 m.insert("rule".into(), self.rule.to_json());
569 if let Some(t) = self.at {
570 m.insert("at".into(), time_json(t));
571 }
572 if let Some(l) = self.labels {
573 m.insert("labels".into(), json!(l));
574 }
575 m.insert("argument".into(), self.argument.to_json());
576 if let Some(k) = self.key {
577 m.insert("key".into(), json!(k));
578 }
579 Value::Object(m)
580 }
581
582 #[must_use]
584 pub fn of_json(v: &Value) -> Option<Record> {
585 let state = match v.get("state")?.as_str()? {
586 "firing" => State::Firing,
587 "resolved" => State::Resolved,
588 _ => return None,
589 };
590 let severity = match v.get("severity")? {
591 Value::Null => None,
592 s => Some(Severity::parse(s.as_str()?)?),
593 };
594 let optional = |name: &str| v.get(name);
595 Some(Record {
596 state,
597 severity,
598 rule: RuleIndex::of_json(v.get("rule")?)?,
599 at: match optional("at") {
600 None => None,
601 Some(t) => Some(time_of_json(t)?),
602 },
603 labels: match optional("labels") {
604 None => None,
605 Some(l) => Some(u32::try_from(l.as_u64()?).ok()?),
606 },
607 argument: Argument::of_json(v.get("argument")?)?,
608 key: match optional("key") {
609 None => None,
610 Some(k) => Some(k.as_u64()?),
611 },
612 })
613 }
614
615 pub fn check(&self) -> Result<(), Undecodable> {
621 match (self.rule, self.key) {
622 (RuleIndex::Table(_), Some(_)) => Err(Undecodable::KeyWithRule),
623 (RuleIndex::NotAvailable, None) => Err(Undecodable::KeyMissing),
624 _ => Ok(()),
625 }
626 }
627
628 pub fn write(&self, epoch: i64) -> Result<packed::Record, Refused> {
637 write_value(&self.to_json(), epoch)
638 }
639
640 pub fn put(&self, stamp: Stamp, epoch: i64) -> Result<Vec<u8>, Refused> {
646 let record = self.write(epoch)?;
647 let tag = Tag::new(TAG).expect("a tag of four bits");
648 Ok(Envelope::mutation(tag, stamp, &record.bytes).write())
649 }
650
651 pub fn read(tag: u8, bytes: &[u8], epoch: i64) -> Result<Record, Undecodable> {
660 let value = layout().read(tag, bytes, Some(epoch))?;
661 let record = Record::of_json(&value).ok_or(ReadRefusal::Code)?;
663 record.check()?;
664 Ok(record)
665 }
666}
667
668pub fn write_value(value: &Value, epoch: i64) -> Result<packed::Record, Refused> {
675 let record = layout().write(value, Some(epoch))?;
676 let r = Record::of_json(value).ok_or(WriteRefusal::Value)?;
678 match r.check() {
679 Err(Undecodable::KeyWithRule) => return Err(Refused::KeyWithRule),
680 Err(_) => return Err(Refused::KeyMissing),
681 Ok(()) => {}
682 }
683 if r.is_by_words() && (r.labels.is_some() || r.argument != Argument::NotAvailable) {
684 return Err(Refused::ByWordsFields);
685 }
686 Ok(record)
687}
688
689#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
693pub enum Act {
694 Raise,
695 Escalate,
696 Refresh,
697 Resolve,
698}
699
700impl Act {
701 #[must_use]
705 pub const fn is_transition(self) -> bool {
706 !matches!(self, Act::Refresh)
707 }
708}
709
710#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
714pub struct Dating {
715 greatest: Option<i64>,
716}
717
718impl Dating {
719 #[must_use]
722 pub const fn known(at: Option<i64>) -> Dating {
723 Dating { greatest: at }
724 }
725
726 #[must_use]
729 pub const fn greatest(&self) -> Option<i64> {
730 self.greatest
731 }
732
733 pub fn transition(&mut self, clock_ms: i128, epoch: i64) -> Option<i64> {
741 let clock = time_at(clock_ms, epoch)?;
742 let new = match self.greatest {
743 Some(g) if clock <= g => g.checked_add(1)?,
744 _ => clock,
745 };
746 time_at(i128::from(new) * 1000, epoch)?;
747 self.greatest = Some(new);
748 Some(new)
749 }
750
751 pub fn at(&mut self, act: Act, held: Option<i64>, clock_ms: i128, epoch: i64) -> Option<i64> {
755 if act.is_transition() {
756 self.transition(clock_ms, epoch)
757 } else {
758 held
759 }
760 }
761}
762
763#[must_use]
770pub fn acknowledged(acked_at_ms: Option<i128>, at: Option<i64>) -> bool {
771 match (acked_at_ms, at) {
772 (Some(acked), Some(at)) => i128::from(at) * 1000 <= acked,
773 _ => false,
774 }
775}
776
777#[must_use]
781pub fn adopted_at(timestamp_ms: u64, epoch: i64) -> Option<i64> {
782 time_at(i128::from(timestamp_ms), epoch)
783}
784
785#[derive(Debug, Clone, PartialEq, Eq, Hash)]
790pub struct ArgumentDecl {
791 minimum: String,
792 resolution: String,
793}
794
795impl ArgumentDecl {
796 #[must_use]
799 pub fn new(minimum: &str, resolution: &str) -> Option<ArgumentDecl> {
800 Decimal::parse(minimum)?;
801 if Decimal::parse(resolution)? <= Decimal::from(0) {
802 return None;
803 }
804 Some(ArgumentDecl {
805 minimum: minimum.to_owned(),
806 resolution: resolution.to_owned(),
807 })
808 }
809
810 #[must_use]
812 pub fn minimum(&self) -> &str {
813 &self.minimum
814 }
815
816 #[must_use]
818 pub fn resolution(&self) -> &str {
819 &self.resolution
820 }
821
822 fn fixed(&self) -> Fixed {
823 Fixed::new(
824 &self.minimum,
825 &self.resolution,
826 u128::from(Argument::MAX) + 1,
827 )
828 }
829
830 fn of_json(v: &Value) -> Option<ArgumentDecl> {
831 let o = v.as_object()?;
832 if o.len() != 2 {
833 return None;
834 }
835 ArgumentDecl::new(o.get("minimum")?.as_str()?, o.get("resolution")?.as_str()?)
836 }
837}
838
839#[derive(Debug, Clone, PartialEq, Eq, Hash)]
841pub enum LabelValues {
842 List(Vec<String>),
844 Range { minimum: i128, maximum: i128 },
847}
848
849#[derive(Debug, Clone, PartialEq, Eq, Hash)]
851pub struct Label {
852 pub name: String,
853 pub values: LabelValues,
854}
855
856impl Label {
857 #[must_use]
859 pub fn count(&self) -> u128 {
860 match &self.values {
861 LabelValues::List(l) => l.len() as u128,
862 LabelValues::Range { minimum, maximum } => {
863 u128::try_from(maximum - minimum).map_or(0, |d| d + 1)
864 }
865 }
866 }
867
868 #[must_use]
871 pub fn width(&self) -> u32 {
872 match self.count() {
873 0 | 1 => 0,
874 n => u128::BITS - (n - 1).leading_zeros(),
875 }
876 }
877
878 #[must_use]
883 pub fn code(&self, text: &str) -> Option<u64> {
884 match &self.values {
885 LabelValues::List(l) => l.iter().position(|v| v == text).map(|i| i as u64),
886 LabelValues::Range { minimum, maximum } => {
887 let n: i128 = text.parse().ok()?;
888 if n.to_string() != text || n < *minimum || n > *maximum {
889 return None;
890 }
891 u64::try_from(n - minimum).ok()
892 }
893 }
894 }
895
896 #[must_use]
899 pub fn text(&self, code: u64) -> Option<String> {
900 if u128::from(code) >= self.count() {
901 return None;
902 }
903 match &self.values {
904 LabelValues::List(l) => l.get(usize::try_from(code).ok()?).cloned(),
905 LabelValues::Range { minimum, .. } => Some((minimum + i128::from(code)).to_string()),
906 }
907 }
908
909 fn of_json(v: &Value) -> Option<Label> {
910 let o = v.as_object()?;
911 let name = o.get("name")?.as_str()?.to_owned();
912 let values = match (o.get("values"), o.get("minimum"), o.get("maximum")) {
913 (Some(list), None, None) if o.len() == 2 => {
914 let list = words::list(list, usize::MAX, |_| true, false)?;
915 if list.is_empty() {
916 return None;
917 }
918 LabelValues::List(list)
919 }
920 (None, Some(minimum), Some(maximum)) if o.len() == 3 => {
921 let minimum = packed::json_integer(minimum).ok()?;
922 let maximum = packed::json_integer(maximum).ok()?;
923 if minimum > maximum {
924 return None;
925 }
926 LabelValues::Range { minimum, maximum }
927 }
928 _ => return None,
929 };
930 Some(Label { name, values })
931 }
932
933 fn to_json(&self) -> Value {
934 match &self.values {
935 LabelValues::List(l) => json!({"name": self.name, "values": l}),
936 LabelValues::Range { minimum, maximum } => {
937 let n = |x: i128| {
939 i64::try_from(x)
940 .map(Value::from)
941 .or_else(|_| u64::try_from(x).map(Value::from))
942 .unwrap_or(Value::Null)
943 };
944 json!({"name": self.name, "minimum": n(*minimum), "maximum": n(*maximum)})
945 }
946 }
947 }
948}
949
950#[derive(Debug, Clone, PartialEq, Eq, Hash)]
953pub struct Rule {
954 pub name: String,
956 pub summary: String,
958 pub category: Option<String>,
960 pub argument: Option<ArgumentDecl>,
961 pub labels: Vec<Label>,
964}
965
966impl AsRef<str> for Rule {
967 fn as_ref(&self) -> &str {
969 &self.name
970 }
971}
972
973enum Piece<'a> {
975 Text(&'a str),
976 Placeholder(&'a str),
978 Stray,
980}
981
982fn pieces(summary: &str) -> Vec<Piece<'_>> {
985 let mut out = Vec::new();
986 let mut rest = summary;
987 while !rest.is_empty() {
988 match rest.find(['{', '}']) {
989 None => {
990 out.push(Piece::Text(rest));
991 break;
992 }
993 Some(i) => {
994 if i > 0 {
995 out.push(Piece::Text(&rest[..i]));
996 }
997 if rest[i..].starts_with('}') {
998 out.push(Piece::Stray);
999 rest = &rest[i + 1..];
1000 } else if let Some(end) = rest[i + 1..].find('}') {
1001 out.push(Piece::Placeholder(&rest[i + 1..i + 1 + end]));
1002 rest = &rest[i + end + 2..];
1003 } else {
1004 out.push(Piece::Stray);
1005 break;
1006 }
1007 }
1008 }
1009 }
1010 out
1011}
1012
1013impl Rule {
1014 #[must_use]
1016 pub fn labels_width(&self) -> u32 {
1017 self.labels.iter().map(Label::width).sum()
1018 }
1019
1020 #[must_use]
1027 pub fn encode<'a>(
1028 &self,
1029 labels: impl IntoIterator<Item = (&'a str, &'a str)>,
1030 ) -> Option<Option<u32>> {
1031 let given: Vec<(&str, &str)> = labels
1032 .into_iter()
1033 .filter(|(n, _)| !super::is_host_scoped(n))
1034 .collect();
1035 if given.len() != self.labels.len() || self.labels_width() > LABELS_BITS {
1036 return None;
1037 }
1038 let mut codes: u64 = 0;
1039 for label in &self.labels {
1040 let mut of_name = given.iter().filter(|(n, _)| *n == label.name);
1041 let (_, text) = of_name.next()?;
1042 if of_name.next().is_some() {
1043 return None;
1044 }
1045 codes = (codes << label.width()) | label.code(text)?;
1046 }
1047 if self.labels.is_empty() {
1048 return Some(None);
1049 }
1050 Some(Some(u32::try_from(codes).ok()?))
1051 }
1052
1053 #[must_use]
1059 pub fn decode(&self, labels: Option<u32>) -> Option<Vec<(String, String)>> {
1060 let Some(codes) = labels else {
1061 return self.labels.is_empty().then(Vec::new);
1062 };
1063 let width = self.labels_width();
1064 if self.labels.is_empty() || width > LABELS_BITS || u64::from(codes) >> width != 0 {
1065 return None;
1066 }
1067 let mut left = width;
1068 let mut out = Vec::with_capacity(self.labels.len());
1069 for label in &self.labels {
1070 let w = label.width();
1071 left -= w;
1072 let code = (u64::from(codes) >> left) & ((1u64 << w) - 1);
1073 out.push((label.name.clone(), label.text(code)?));
1074 }
1075 Some(out)
1076 }
1077
1078 #[must_use]
1084 pub fn argument(&self, reading: Option<&Decimal>) -> Argument {
1085 let (Some(decl), Some(reading)) = (&self.argument, reading) else {
1086 return Argument::NotAvailable;
1087 };
1088 decl.fixed()
1089 .code(reading)
1090 .ok()
1091 .and_then(|c| Argument::new(u32::try_from(c).ok()?))
1092 .unwrap_or(Argument::NotAvailable)
1093 }
1094
1095 #[must_use]
1100 pub fn reading(&self, argument: Argument) -> Option<Decimal> {
1101 let (Some(decl), Argument::Code(code)) = (&self.argument, argument) else {
1102 return None;
1103 };
1104 decl.fixed().value(u64::from(code)).ok()
1105 }
1106
1107 #[must_use]
1111 pub fn summary(&self, labels: &[(String, String)], argument: Argument) -> String {
1112 let mut out = String::new();
1113 for piece in pieces(&self.summary) {
1114 match piece {
1115 Piece::Text(t) => out.push_str(t),
1116 Piece::Stray => {}
1117 Piece::Placeholder("argument") if self.argument.is_some() => {
1118 match self.reading(argument) {
1119 Some(r) => out.push_str(&r.to_string()),
1120 None => out.push('?'),
1121 }
1122 }
1123 Piece::Placeholder(name) => {
1124 if let Some((_, text)) = labels.iter().find(|(n, _)| n == name) {
1125 out.push_str(text);
1126 }
1127 }
1128 }
1129 }
1130 out
1131 }
1132
1133 fn of_json(v: &Value) -> Option<Rule> {
1134 const MEMBERS: [&str; 5] = ["name", "summary", "category", "argument", "labels"];
1135 let o = v.as_object()?;
1136 if o.keys().any(|k| !MEMBERS.contains(&k.as_str())) {
1137 return None;
1138 }
1139 Some(Rule {
1140 name: o.get("name")?.as_str()?.to_owned(),
1141 summary: o.get("summary")?.as_str()?.to_owned(),
1142 category: match o.get("category") {
1143 None => None,
1144 Some(c) => Some(c.as_str()?.to_owned()),
1145 },
1146 argument: match o.get("argument") {
1147 None => None,
1148 Some(a) => Some(ArgumentDecl::of_json(a)?),
1149 },
1150 labels: match o.get("labels") {
1151 None => Vec::new(),
1152 Some(l) => {
1153 let l = l.as_array().filter(|l| !l.is_empty())?;
1154 l.iter().map(Label::of_json).collect::<Option<_>>()?
1155 }
1156 },
1157 })
1158 }
1159
1160 #[must_use]
1162 pub fn to_json(&self) -> Value {
1163 let mut m = Map::new();
1164 m.insert("name".into(), json!(self.name));
1165 m.insert("summary".into(), json!(self.summary));
1166 if let Some(c) = &self.category {
1167 m.insert("category".into(), json!(c));
1168 }
1169 if let Some(a) = &self.argument {
1170 m.insert(
1171 "argument".into(),
1172 json!({"minimum": a.minimum, "resolution": a.resolution}),
1173 );
1174 }
1175 if !self.labels.is_empty() {
1176 m.insert(
1177 "labels".into(),
1178 Value::Array(self.labels.iter().map(Label::to_json).collect()),
1179 );
1180 }
1181 Value::Object(m)
1182 }
1183}
1184
1185#[must_use]
1187pub fn table_json(table: &[Rule]) -> Value {
1188 Value::Array(table.iter().map(Rule::to_json).collect())
1189}
1190
1191#[must_use]
1195pub fn rules(v: &Value) -> Option<Vec<Rule>> {
1196 let list = v.as_array()?;
1197 if list.len() > MAX_RULES {
1198 return None;
1199 }
1200 list.iter().map(Rule::of_json).collect()
1201}
1202
1203#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1206pub enum Invalid {
1207 NotUsed,
1210 Value,
1213 RuleName,
1215 Label,
1219 LabelsWidth,
1221 HostLabel,
1223 Placeholder,
1227 Disagrees,
1229}
1230
1231impl Invalid {
1232 #[must_use]
1234 pub fn as_str(self) -> &'static str {
1235 match self {
1236 Self::NotUsed => "not_used",
1237 Self::Value => "value",
1238 Self::RuleName => "rule_name",
1239 Self::Label => "label",
1240 Self::LabelsWidth => "labels_width",
1241 Self::HostLabel => "host_label",
1242 Self::Placeholder => "placeholder",
1243 Self::Disagrees => "disagrees",
1244 }
1245 }
1246
1247 #[must_use]
1249 pub fn says(self) -> &'static str {
1250 match self {
1251 Self::NotUsed => "the contract's `uses` does not list alarms.v2",
1252 Self::Value => {
1253 "its value is not a list of at most 255 rules: name, summary, and optionally \
1254 category, argument { minimum, resolution } and labels"
1255 }
1256 Self::RuleName => "a rule's name is empty, holds a newline, or is another rule's",
1257 Self::Label => {
1258 "a label's name is empty, `argument`, holds a newline, `=`, `{` or `}`, or comes \
1259 twice in its rule; or a value holds a newline or comes twice"
1260 }
1261 Self::LabelsWidth => "a rule's labels take more than 24 bits",
1262 Self::HostLabel => "a label's name is host-scoped: the key's system names the host",
1263 Self::Placeholder => {
1264 "a summary holds an unclosed `{`, a stray `}`, or a placeholder that is neither \
1265 a label of its rule nor its `argument`"
1266 }
1267 Self::Disagrees => {
1268 "two resources carry two different lists: write the key once, on [defaults]"
1269 }
1270 }
1271 }
1272
1273 fn found_in(self, table: &[Rule]) -> bool {
1276 let labels = || table.iter().flat_map(|r| r.labels.iter());
1277 match self {
1278 Self::NotUsed | Self::Value | Self::Disagrees => false,
1279 Self::RuleName => table.iter().enumerate().any(|(i, r)| {
1280 r.name.is_empty()
1281 || r.name.contains('\n')
1282 || table[..i].iter().any(|before| before.name == r.name)
1283 }),
1284 Self::Label => table.iter().any(|r| {
1285 r.labels.iter().enumerate().any(|(i, l)| {
1286 l.name.is_empty()
1287 || l.name == "argument"
1288 || l.name.contains(['\n', '=', '{', '}'])
1289 || r.labels[..i].iter().any(|before| before.name == l.name)
1290 || match &l.values {
1291 LabelValues::List(values) => values
1292 .iter()
1293 .enumerate()
1294 .any(|(j, v)| v.contains('\n') || values[..j].contains(v)),
1295 LabelValues::Range { .. } => false,
1296 }
1297 })
1298 }),
1299 Self::LabelsWidth => table.iter().any(|r| r.labels_width() > LABELS_BITS),
1300 Self::HostLabel => labels().any(|l| super::is_host_scoped(&l.name)),
1301 Self::Placeholder => table.iter().any(|r| {
1302 pieces(&r.summary).iter().any(|p| match p {
1303 Piece::Text(_) => false,
1304 Piece::Stray => true,
1305 Piece::Placeholder(name) => {
1306 !(r.labels.iter().any(|l| l.name == *name)
1307 || (*name == "argument" && r.argument.is_some()))
1308 }
1309 })
1310 }),
1311 }
1312 }
1313}
1314
1315impl std::fmt::Display for Invalid {
1316 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1317 f.write_str(self.as_str())
1318 }
1319}
1320
1321const OF_A_LIST: [Invalid; 5] = [
1323 Invalid::RuleName,
1324 Invalid::Label,
1325 Invalid::LabelsWidth,
1326 Invalid::HostLabel,
1327 Invalid::Placeholder,
1328];
1329
1330#[derive(Debug, Clone, PartialEq, Eq)]
1332pub enum Declared {
1333 None,
1335 Table(Vec<Rule>),
1337 Invalid(Invalid),
1339}
1340
1341impl Declared {
1342 #[must_use]
1345 pub fn table(&self) -> Option<&[Rule]> {
1346 match self {
1347 Declared::Table(t) => Some(t),
1348 Declared::None | Declared::Invalid(_) => None,
1349 }
1350 }
1351}
1352
1353fn declared<'v>(
1357 uses_v2: bool,
1358 carried: impl IntoIterator<Item = &'v Value>,
1359) -> (Declared, Option<usize>) {
1360 let carried: Vec<&Value> = carried.into_iter().collect();
1361 if carried.is_empty() {
1362 return (Declared::None, None);
1363 }
1364 if !uses_v2 {
1365 return (Declared::Invalid(Invalid::NotUsed), Some(0));
1366 }
1367 let mut lists = Vec::with_capacity(carried.len());
1368 for (i, v) in carried.iter().enumerate() {
1369 match rules(v) {
1370 Some(list) => lists.push(list),
1371 None => return (Declared::Invalid(Invalid::Value), Some(i)),
1372 }
1373 }
1374 for finding in OF_A_LIST {
1375 if let Some(i) = lists.iter().position(|l| finding.found_in(l)) {
1376 return (Declared::Invalid(finding), Some(i));
1377 }
1378 }
1379 if let Some(i) = lists.iter().position(|l| *l != lists[0]) {
1380 return (Declared::Invalid(Invalid::Disagrees), Some(i));
1381 }
1382 (Declared::Table(lists.swap_remove(0)), None)
1383}
1384
1385#[must_use]
1389pub fn declaration<'v>(uses_v2: bool, carried: impl IntoIterator<Item = &'v Value>) -> Declared {
1390 declared(uses_v2, carried).0
1391}
1392
1393#[must_use]
1396pub fn declaration_of(c: &Contract) -> Declared {
1397 declaration(
1398 uses_v2(c),
1399 c.resources.iter().filter_map(|r| r.annotations.get(RULES)),
1400 )
1401}
1402
1403#[must_use]
1405pub fn table_of(c: &Contract) -> Option<Vec<Rule>> {
1406 declaration_of(c).table().map(<[Rule]>::to_vec)
1407}
1408
1409pub type Instance = words::Instance<Rule>;
1413
1414#[must_use]
1420pub fn instance_table<'a>(named: impl IntoIterator<Item = Option<&'a [Rule]>>) -> Instance {
1421 words::instance_table(named)
1422}
1423
1424#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1427pub enum Growth {
1428 Same,
1430 Kept,
1435 Moved,
1437}
1438
1439impl Growth {
1440 #[must_use]
1442 pub fn as_str(self) -> &'static str {
1443 match self {
1444 Self::Same => "same",
1445 Self::Kept => "kept",
1446 Self::Moved => "moved",
1447 }
1448 }
1449}
1450
1451#[must_use]
1453pub fn growth(old: &[Rule], new: &[Rule]) -> Growth {
1454 if old == new {
1455 Growth::Same
1456 } else if old.len() <= new.len()
1457 && old
1458 .iter()
1459 .zip(new)
1460 .all(|(o, n)| o.name == n.name && o.labels == n.labels)
1461 {
1462 Growth::Kept
1463 } else {
1464 Growth::Moved
1465 }
1466}
1467
1468pub use crate::words::Lint;
1471
1472#[must_use]
1478pub fn lint_contract(c: &Contract) -> Vec<Lint> {
1479 if !uses_v2(c) {
1480 return Vec::new();
1481 }
1482 let carrying: Vec<_> = c
1483 .resources
1484 .iter()
1485 .filter(|r| r.annotations.contains_key(RULES))
1486 .collect();
1487 let values = carrying.iter().map(|r| &r.annotations[RULES]);
1488 match declared(true, values) {
1489 (Declared::Invalid(reason), Some(i)) => vec![Lint {
1490 profile: PROFILE,
1491 at: Lint::place(carrying[i]),
1492 key: Some(RULES),
1493 token: reason.as_str(),
1494 says: reason.says(),
1495 }],
1496 _ => Vec::new(),
1497 }
1498}
1499
1500#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1504pub struct Fields {
1505 pub rule: RuleIndex,
1506 pub labels: Option<u32>,
1507 pub argument: Argument,
1508 pub key: Option<u64>,
1509}
1510
1511impl Fields {
1512 #[must_use]
1515 pub fn to_json(&self) -> Value {
1516 let mut m = Map::new();
1517 m.insert("rule".into(), self.rule.to_json());
1518 if let Some(l) = self.labels {
1519 m.insert("labels".into(), json!(l));
1520 }
1521 m.insert("argument".into(), self.argument.to_json());
1522 if let Some(k) = self.key {
1523 m.insert("key".into(), json!(k));
1524 }
1525 Value::Object(m)
1526 }
1527}
1528
1529#[must_use]
1541pub fn write_alarm<'a>(
1542 table: Option<&[Rule]>,
1543 rule: &str,
1544 labels: impl IntoIterator<Item = (&'a str, &'a str)>,
1545 reading: Option<&Decimal>,
1546) -> Fields {
1547 let labels: Vec<(&str, &str)> = labels.into_iter().collect();
1548 let by_table = table.and_then(|t| {
1549 let RuleIndex::Table(i) = RuleIndex::of(words::write(t, rule, MAX_INDEX)) else {
1550 return None;
1551 };
1552 let r = &t[usize::from(i)];
1553 Some(Fields {
1554 rule: RuleIndex::Table(i),
1555 labels: r.encode(labels.iter().copied())?,
1556 argument: r.argument(reading),
1557 key: None,
1558 })
1559 });
1560 by_table.unwrap_or_else(|| Fields {
1561 rule: RuleIndex::NotAvailable,
1562 labels: None,
1563 argument: Argument::NotAvailable,
1564 key: Some(super::derive(rule, labels).integer()),
1565 })
1566}
1567
1568#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1573pub enum Unnamed {
1574 NoTable,
1576 Rule,
1578 Labels,
1581}
1582
1583impl Unnamed {
1584 #[must_use]
1586 pub fn as_str(self) -> &'static str {
1587 match self {
1588 Self::NoTable => "no_table",
1589 Self::Rule => "rule",
1590 Self::Labels => "labels",
1591 }
1592 }
1593}
1594
1595#[derive(Debug, Clone, PartialEq, Eq)]
1597pub struct Named<'t> {
1598 pub index: u8,
1600 pub rule: &'t Rule,
1601 pub labels: Vec<(String, String)>,
1603 pub alert_key: u64,
1606 pub summary: String,
1608 pub argument: Option<Decimal>,
1611}
1612
1613#[derive(Debug, Clone, PartialEq, Eq)]
1616pub enum Naming<'t> {
1617 Named(Named<'t>),
1619 Unnamed(Unnamed),
1621 ByWords { alert_key: u64 },
1624}
1625
1626impl Naming<'_> {
1627 #[must_use]
1630 pub fn alert_key(&self) -> Option<u64> {
1631 match self {
1632 Naming::Named(n) => Some(n.alert_key),
1633 Naming::ByWords { alert_key } => Some(*alert_key),
1634 Naming::Unnamed(_) => None,
1635 }
1636 }
1637}
1638
1639impl Record {
1640 #[must_use]
1648 pub fn name<'t>(&self, table: Option<&'t [Rule]>) -> Naming<'t> {
1649 let index = match (self.rule, self.key) {
1650 (RuleIndex::NotAvailable, Some(alert_key)) => return Naming::ByWords { alert_key },
1651 (RuleIndex::NotAvailable, None) => return Naming::Unnamed(Unnamed::Rule),
1653 (RuleIndex::Table(i), _) => i,
1654 };
1655 let Some(table) = table else {
1656 return Naming::Unnamed(Unnamed::NoTable);
1657 };
1658 let Some(rule) = table.get(usize::from(index)) else {
1659 return Naming::Unnamed(Unnamed::Rule);
1660 };
1661 let Some(labels) = rule.decode(self.labels) else {
1662 return Naming::Unnamed(Unnamed::Labels);
1663 };
1664 let alert_key = super::derive(
1665 &rule.name,
1666 labels.iter().map(|(n, v)| (n.as_str(), v.as_str())),
1667 )
1668 .integer();
1669 Naming::Named(Named {
1670 index,
1671 rule,
1672 summary: rule.summary(&labels, self.argument),
1673 argument: rule.reading(self.argument),
1674 labels,
1675 alert_key,
1676 })
1677 }
1678}
1679
1680#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1684pub enum Raise {
1685 Put(u8),
1689 Firing,
1691 Refused,
1694}
1695
1696#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1698pub enum Resolve {
1699 Put(u8),
1701 NotFiring,
1703}
1704
1705#[derive(Debug, Clone, PartialEq, Eq)]
1708pub struct Left<I> {
1709 pub id: I,
1710 pub state: State,
1711 pub reads: bool,
1713 pub derives: bool,
1715 pub evaluated: bool,
1717}
1718
1719#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1721pub enum Adoption {
1722 Left,
1724 Free,
1727 Resolved,
1730 Adopted,
1733}
1734
1735impl Adoption {
1736 #[must_use]
1738 pub fn as_str(self) -> &'static str {
1739 match self {
1740 Self::Left => "left",
1741 Self::Free => "free",
1742 Self::Resolved => "resolved",
1743 Self::Adopted => "adopted",
1744 }
1745 }
1746}
1747
1748#[derive(Debug, Clone, PartialEq, Eq)]
1752pub struct Slots<I> {
1753 bound: u16,
1754 held: BTreeMap<u8, (I, State)>,
1755}
1756
1757impl<I: Clone + Eq> Slots<I> {
1758 #[must_use]
1761 pub fn new(bound: u16) -> Self {
1762 Slots {
1763 bound: bound.min(MAX_SLOTS),
1764 held: BTreeMap::new(),
1765 }
1766 }
1767
1768 #[must_use]
1770 pub fn bound(&self) -> u16 {
1771 self.bound
1772 }
1773
1774 pub fn held(&self) -> impl Iterator<Item = (u8, &I, State)> {
1776 self.held
1777 .iter()
1778 .map(|(slot, (id, state))| (*slot, id, *state))
1779 }
1780
1781 #[must_use]
1784 pub fn slot_of(&self, id: &I) -> Option<(u8, State)> {
1785 self.held
1786 .iter()
1787 .find(|(_, (held, _))| held == id)
1788 .map(|(slot, (_, state))| (*slot, *state))
1789 }
1790
1791 fn lowest_free(&self) -> Option<u8> {
1795 (0..self.bound)
1796 .filter_map(|s| u8::try_from(s).ok())
1797 .find(|s| !matches!(self.held.get(s), Some((_, State::Firing))))
1798 }
1799
1800 pub fn raise(&mut self, id: &I) -> Raise {
1803 let slot = match self.slot_of(id) {
1804 Some((_, State::Firing)) => return Raise::Firing,
1805 Some((slot, State::Resolved)) => slot,
1806 None => match self.lowest_free() {
1807 Some(slot) => slot,
1808 None => return Raise::Refused,
1809 },
1810 };
1811 self.held.insert(slot, (id.clone(), State::Firing));
1812 Raise::Put(slot)
1813 }
1814
1815 pub fn resolve(&mut self, id: &I) -> Resolve {
1818 match self.slot_of(id) {
1819 Some((slot, State::Firing)) => {
1820 self.held.insert(slot, (id.clone(), State::Resolved));
1821 Resolve::Put(slot)
1822 }
1823 _ => Resolve::NotFiring,
1824 }
1825 }
1826
1827 pub fn forget(&mut self, slot: u8) {
1831 self.held.remove(&slot);
1832 }
1833
1834 #[must_use]
1842 pub fn restart(
1843 left: impl IntoIterator<Item = (u8, Left<I>)>,
1844 bound: u16,
1845 ) -> (Self, BTreeMap<u8, Adoption>) {
1846 let mut slots = Slots::new(bound);
1847 let left: BTreeMap<u8, Left<I>> = left.into_iter().collect();
1848 let mut did = BTreeMap::new();
1849 for (slot, entry) in left {
1850 let adoption = if u16::from(slot) >= slots.bound {
1851 Adoption::Left
1852 } else if entry.state == State::Resolved
1853 || !entry.reads
1854 || !entry.derives
1855 || slots.slot_of(&entry.id).is_some()
1857 {
1858 Adoption::Free
1859 } else if !entry.evaluated {
1860 slots.held.insert(slot, (entry.id, State::Resolved));
1861 Adoption::Resolved
1862 } else {
1863 slots.held.insert(slot, (entry.id, State::Firing));
1864 Adoption::Adopted
1865 };
1866 did.insert(slot, adoption);
1867 }
1868 (slots, did)
1869 }
1870}
1871
1872#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1876pub struct Seen {
1877 pub slot: u8,
1878 pub stamp: Stamp,
1879 pub alert_key: Option<u64>,
1880}
1881
1882#[derive(Debug, Clone, Default, PartialEq, Eq)]
1885pub struct Taken {
1886 pub takes: BTreeMap<u64, Option<u8>>,
1891 pub double: Vec<u64>,
1894}
1895
1896#[must_use]
1902pub fn taken(seen: &[Seen], present: Option<Run>) -> Taken {
1903 let mut out = Taken::default();
1904 let mut best: BTreeMap<u64, Seq> = BTreeMap::new();
1905 for s in seen {
1906 let Some(key) = s.alert_key else { continue };
1907 let take = out.takes.entry(key).or_insert(None);
1908 if Some(s.stamp.run) != present {
1909 continue;
1910 }
1911 match best.get(&key) {
1912 Some(seq) => {
1913 if !out.double.contains(&key) {
1914 out.double.push(key);
1915 }
1916 if s.stamp.seq.get() > seq.get() {
1917 best.insert(key, s.stamp.seq);
1918 *take = Some(s.slot);
1919 }
1920 }
1921 None => {
1922 best.insert(key, s.stamp.seq);
1923 *take = Some(s.slot);
1924 }
1925 }
1926 }
1927 out.double.sort_unstable();
1928 out
1929}
1930
1931#[must_use]
1936pub fn one_slot_each(set: SetVerdict, taken: &Taken) -> Answer {
1937 match set {
1938 SetVerdict::Established if taken.double.is_empty() => Answer::Yes,
1939 SetVerdict::Established => Answer::No,
1940 SetVerdict::Unobservable | SetVerdict::NotAsked => Answer::Unobservable,
1941 }
1942}
1943
1944#[derive(Debug, Clone, PartialEq, Eq)]
1951pub struct Words {
1952 pub rule: String,
1953 pub labels: BTreeMap<String, String>,
1955 pub summary: String,
1956 pub category: Option<String>,
1957}
1958
1959#[derive(Debug, Clone, PartialEq, Eq)]
1961pub enum WordsInvalid {
1962 Json(String),
1964 Schema(String),
1966}
1967
1968impl std::fmt::Display for WordsInvalid {
1969 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1970 match self {
1971 Self::Json(why) => write!(f, "not strict JSON: {why}"),
1972 Self::Schema(why) => write!(f, "outside alarms.v2.Words: {why}"),
1973 }
1974 }
1975}
1976
1977impl Words {
1978 pub fn from_json(v: &Value) -> Result<Words, WordsInvalid> {
1983 let schema = |why: String| WordsInvalid::Schema(why);
1984 let Value::Object(o) = v else {
1985 return Err(schema("not an object".into()));
1986 };
1987 let string = |m: &str, required: bool| -> Result<Option<String>, WordsInvalid> {
1988 match o.get(m) {
1989 None if required => Err(WordsInvalid::Schema(format!("/{m}: missing"))),
1990 None => Ok(None),
1991 Some(Value::String(s)) => Ok(Some(s.clone())),
1992 Some(_) => Err(WordsInvalid::Schema(format!("/{m}: not a string"))),
1993 }
1994 };
1995 let rule = string("rule", true)?.unwrap_or_default();
1996 let summary = string("summary", true)?.unwrap_or_default();
1997 let category = string("category", false)?;
1998 let mut labels = BTreeMap::new();
1999 match o.get("labels") {
2000 None => {}
2001 Some(Value::Object(l)) => {
2002 for (n, v) in l {
2003 let Value::String(v) = v else {
2004 return Err(schema(format!("/labels/{n}: not a string")));
2005 };
2006 labels.insert(n.clone(), v.clone());
2007 }
2008 }
2009 Some(_) => return Err(schema("/labels: not an object".into())),
2010 }
2011 Ok(Words {
2012 rule,
2013 labels,
2014 summary,
2015 category,
2016 })
2017 }
2018
2019 pub fn decode(bytes: &[u8]) -> Result<Words, WordsInvalid> {
2025 let text = std::str::from_utf8(bytes)
2026 .map_err(|e| WordsInvalid::Json(format!("not UTF-8: {e}")))?;
2027 let v = crate::strict::parse_json(text).map_err(|e| WordsInvalid::Json(e.to_string()))?;
2028 Words::from_json(&v)
2029 }
2030
2031 #[must_use]
2033 pub fn to_json(&self) -> Value {
2034 let mut m = Map::new();
2035 m.insert("rule".into(), json!(self.rule));
2036 if !self.labels.is_empty() {
2037 m.insert("labels".into(), json!(self.labels));
2038 }
2039 m.insert("summary".into(), json!(self.summary));
2040 if let Some(c) = &self.category {
2041 m.insert("category".into(), json!(c));
2042 }
2043 Value::Object(m)
2044 }
2045
2046 #[must_use]
2050 pub fn derive(&self) -> super::Derived {
2051 super::derive(
2052 &self.rule,
2053 self.labels.iter().map(|(n, v)| (n.as_str(), v.as_str())),
2054 )
2055 }
2056}
2057
2058#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2060pub enum How {
2061 Strict,
2063 Sanitized,
2065}
2066
2067impl How {
2068 #[must_use]
2070 pub fn as_str(self) -> &'static str {
2071 match self {
2072 Self::Strict => "strict",
2073 Self::Sanitized => "sanitized",
2074 }
2075 }
2076}
2077
2078#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2081pub enum NotTaken {
2082 NoRecord,
2084 Undecodable,
2086 Table,
2089 NoWords,
2091 Unreadable,
2093 Mismatch,
2096}
2097
2098impl NotTaken {
2099 #[must_use]
2101 pub fn as_str(self) -> &'static str {
2102 self.reason().as_str()
2103 }
2104
2105 #[must_use]
2107 pub fn reason(self) -> Reason {
2108 match self {
2109 Self::NoRecord => Reason::NoRecord,
2110 Self::Undecodable => Reason::Undecodable,
2111 Self::Table => Reason::Table,
2112 Self::NoWords => Reason::NoWords,
2113 Self::Unreadable => Reason::Unreadable,
2114 Self::Mismatch => Reason::Mismatch,
2115 }
2116 }
2117}
2118
2119pub fn words_taken<E, F>(
2129 record: Option<&Result<Record, E>>,
2130 words: Option<&Result<Words, F>>,
2131) -> Result<How, NotTaken> {
2132 let record = match record {
2133 None => return Err(NotTaken::NoRecord),
2134 Some(Err(_)) => return Err(NotTaken::Undecodable),
2135 Some(Ok(r)) => r,
2136 };
2137 let key = match (record.rule, record.key) {
2138 (RuleIndex::NotAvailable, Some(key)) => key,
2139 (RuleIndex::NotAvailable, None) => return Err(NotTaken::Undecodable),
2140 (RuleIndex::Table(_), _) => return Err(NotTaken::Table),
2141 };
2142 let words = match words {
2143 None => return Err(NotTaken::NoWords),
2144 Some(Err(_)) => return Err(NotTaken::Unreadable),
2145 Some(Ok(w)) => w,
2146 };
2147 let derived = words.derive();
2148 if derived.integer() != key {
2149 Err(NotTaken::Mismatch)
2150 } else if derived.framed {
2151 Ok(How::Strict)
2152 } else {
2153 Ok(How::Sanitized)
2154 }
2155}
2156
2157#[must_use]
2163pub fn words_derive(taken: Result<How, NotTaken>) -> Judged {
2164 match taken {
2165 Ok(How::Strict) => Judged::new(Answer::Yes, Reason::Strict),
2166 Ok(How::Sanitized) => Judged::new(Answer::Yes, Reason::Sanitized),
2167 Err(why) => Judged::new(
2168 match why {
2169 NotTaken::Mismatch => Answer::No,
2170 NotTaken::Table | NotTaken::NoWords | NotTaken::NoRecord => Answer::NotAsked,
2171 NotTaken::Unreadable | NotTaken::Undecodable => Answer::Unobservable,
2172 },
2173 why.reason(),
2174 ),
2175 }
2176}
2177
2178#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2185pub struct Held {
2186 pub record: Record,
2187 pub run: Run,
2188 pub alert_key: Option<u64>,
2189}
2190
2191impl Held {
2192 #[must_use]
2197 pub fn same_identity(&self, other: &Held) -> bool {
2198 match (self.alert_key, other.alert_key) {
2199 (Some(a), Some(b)) => a == b,
2200 _ => self.record.rule == other.record.rule && self.record.labels == other.record.labels,
2201 }
2202 }
2203
2204 fn facts(&self) -> PutFacts<Option<Severity>, Option<i64>> {
2205 PutFacts {
2206 state: self.record.state,
2207 severity: self.record.severity,
2208 at: self.record.at,
2209 }
2210 }
2211}
2212
2213#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2215pub enum Sample {
2216 Put(Held),
2218 Unreadable,
2220 Delete,
2222}
2223
2224#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2227pub enum Displaced {
2228 Rebound,
2232 Replaced,
2234 Dropped,
2237}
2238
2239impl Displaced {
2240 #[must_use]
2242 pub fn as_str(self) -> &'static str {
2243 match self {
2244 Self::Rebound => "rebound",
2245 Self::Replaced => "replaced",
2246 Self::Dropped => "dropped",
2247 }
2248 }
2249}
2250
2251#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2255pub enum Change {
2256 Firing,
2258 Resolved,
2260}
2261
2262impl Change {
2263 #[must_use]
2265 pub fn as_str(self) -> &'static str {
2266 match self {
2267 Self::Firing => "firing",
2268 Self::Resolved => "resolved",
2269 }
2270 }
2271}
2272
2273#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2277pub struct Report {
2278 pub change: Change,
2279 pub alert_key: Option<u64>,
2280}
2281
2282#[derive(Debug, Clone, PartialEq, Eq)]
2284pub struct Applied {
2285 pub displaced: Option<(Displaced, Held)>,
2288 pub reads: Transition,
2290 pub reports: Vec<Report>,
2295}
2296
2297#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2300pub struct Track {
2301 pub held: Option<Held>,
2304}
2305
2306impl Track {
2307 pub fn apply(&mut self, sample: Sample) -> Applied {
2310 let held = self.held.take();
2311 let was_firing = |h: &Held| h.record.state == State::Firing;
2312 let mut reports = Vec::new();
2313 let new = match sample {
2314 Sample::Unreadable => {
2315 return Applied {
2316 displaced: None,
2317 reads: Transition::Unreadable,
2318 reports,
2319 };
2320 }
2321 Sample::Delete => {
2322 let reads = super::delete_reads(held.map(|h| h.record.state));
2323 if let Some(h) = held.filter(was_firing) {
2324 reports.push(Report {
2325 change: Change::Resolved,
2326 alert_key: h.alert_key,
2327 });
2328 }
2329 return Applied {
2330 displaced: None,
2331 reads,
2332 reports,
2333 };
2334 }
2335 Sample::Put(new) => new,
2336 };
2337 self.held = Some(new);
2338 let (same, displaced) = match held {
2339 Some(h) if h.same_identity(&new) => (Some(h), None),
2340 Some(h) => {
2341 let what = if h.run != new.run {
2342 Displaced::Dropped
2343 } else if was_firing(&h) {
2344 Displaced::Rebound
2345 } else {
2346 Displaced::Replaced
2347 };
2348 (None, Some((what, h)))
2349 }
2350 None => (None, None),
2351 };
2352 if let Some((Displaced::Rebound, h)) = displaced {
2353 reports.push(Report {
2354 change: Change::Resolved,
2355 alert_key: h.alert_key,
2356 });
2357 }
2358 let reads = super::put_reads(
2359 same.as_ref().map(Held::facts),
2360 new.facts(),
2361 same.is_some_and(|h| h.record == new.record),
2362 );
2363 let fired = same.as_ref().is_some_and(was_firing);
2364 let change = match reads {
2365 Transition::Raised if !fired => Some(Change::Firing),
2368 Transition::Escalated => Some(Change::Firing),
2369 Transition::Resolved if fired => Some(Change::Resolved),
2370 _ => None,
2371 };
2372 reports.extend(change.map(|change| Report {
2373 change,
2374 alert_key: new.alert_key,
2375 }));
2376 Applied {
2377 displaced,
2378 reads,
2379 reports,
2380 }
2381 }
2382}
2383
2384#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2389pub enum Collection {
2390 Alarms,
2393 Words,
2396}
2397
2398impl Collection {
2399 #[must_use]
2402 pub const fn coll(self) -> u32 {
2403 match self {
2404 Collection::Alarms => ALARMS_COLL,
2405 Collection::Words => WORDS_COLL,
2406 }
2407 }
2408
2409 #[must_use]
2412 pub const fn suffix(self) -> &'static str {
2413 match self {
2414 Collection::Alarms => "alarms.v2/state/alarms",
2415 Collection::Words => "alarms.v2/state/words",
2416 }
2417 }
2418
2419 #[must_use]
2423 pub fn of(key: &str, coll: u32) -> Option<Collection> {
2424 [Collection::Alarms, Collection::Words]
2425 .into_iter()
2426 .find(|c| {
2427 key.strip_suffix(c.suffix())
2428 .is_some_and(|rest| rest.is_empty() || rest.ends_with('/'))
2429 && c.coll() == coll
2430 })
2431 }
2432}
2433
2434#[derive(Debug, Clone, PartialEq, Eq)]
2437pub struct Heard {
2438 pub complete: bool,
2440 pub tag: Tag,
2442 pub run: Run,
2443 pub asof: Seq,
2444 pub time: collection::Time,
2446}
2447
2448#[derive(Debug, Clone, PartialEq, Eq)]
2450pub struct Entry<R> {
2451 pub id: String,
2454 pub slot: Option<u8>,
2455 pub stamp: Stamp,
2458 pub confirmation: Confirmation,
2459 pub confirmed_at: Option<collection::Time>,
2464 pub record: R,
2467}
2468
2469#[derive(Debug, Clone, PartialEq, Eq)]
2472pub struct Snapshot<R> {
2473 pub heard: Heard,
2474 pub live: Vec<Entry<R>>,
2475 pub retired: Vec<(String, Stamp)>,
2477}
2478
2479#[derive(Debug, Clone, Default, PartialEq, Eq)]
2483pub struct Seed {
2484 pub alarms: Option<Snapshot<Result<Record, Undecodable>>>,
2485 pub words: Option<Snapshot<Result<Words, WordsInvalid>>>,
2486 pub mixed: bool,
2490}
2491
2492struct Pages {
2495 heard: collection::Heard,
2496 pages: Vec<Page>,
2497}
2498
2499fn stamp_of(run: Option<Run>, seq: Seq, header: Run) -> Stamp {
2500 Stamp {
2501 run: run.unwrap_or(header),
2502 seq,
2503 }
2504}
2505
2506fn snapshot_of<R>(p: &Pages, read: impl Fn(&Page, &[u8]) -> R) -> Snapshot<R> {
2507 let entry = |e: &collection::Entry, page: &Page| {
2508 let confirmed_at = match e.confirmation {
2509 Confirmation::None => None,
2510 Confirmation::AtTime => Some(page.time),
2511 Confirmation::At(t) => Some(t),
2512 }
2513 .filter(|t| *t != collection::Time::Unknown);
2514 Entry {
2515 id: e.id.clone(),
2516 slot: parse_slot(&e.id),
2517 stamp: stamp_of(e.run, e.seq, page.run),
2518 confirmation: e.confirmation,
2519 confirmed_at,
2520 record: read(page, &e.record),
2521 }
2522 };
2523 Snapshot {
2524 heard: Heard {
2525 complete: p.heard.complete(),
2526 tag: p.heard.tag,
2527 run: p.heard.run,
2528 asof: p.heard.asof,
2529 time: p.heard.time,
2530 },
2531 live: p
2532 .pages
2533 .iter()
2534 .flat_map(|page| page.live.iter().map(move |e| (e, page)))
2535 .map(|(e, page)| entry(e, page))
2536 .collect(),
2537 retired: p
2538 .pages
2539 .iter()
2540 .flat_map(|page| {
2541 page.tombs
2542 .iter()
2543 .map(|t| (t.id.clone(), stamp_of(t.run, t.seq, page.run)))
2544 })
2545 .collect(),
2546 }
2547}
2548
2549impl Seed {
2550 #[must_use]
2556 pub fn of<'a>(replies: impl IntoIterator<Item = (&'a str, &'a [u8])>, epoch: i64) -> Seed {
2557 let mut held: [Option<Pages>; 2] = [None, None];
2558 let mut mixed = false;
2559 for (key, payload) in replies {
2560 let Ok(page) = Page::parse(payload) else {
2561 continue;
2562 };
2563 let Some(c) = Collection::of(key, page.coll) else {
2564 continue;
2565 };
2566 let slot = &mut held[c as usize];
2567 match slot {
2568 Some(p) if p.heard.holds(key, &page) => {
2569 if p.heard.add(&page) {
2570 p.pages.push(page);
2571 }
2572 }
2573 Some(_) => mixed = true,
2574 None => {
2575 let mut heard = collection::Heard::of(key, &page);
2576 heard.add(&page);
2577 *slot = Some(Pages {
2578 heard,
2579 pages: vec![page],
2580 });
2581 }
2582 }
2583 }
2584 let [alarms, words] = held;
2585 Seed {
2586 alarms: alarms
2587 .map(|p| snapshot_of(&p, |page, bytes| Record::read(page.tag.get(), bytes, epoch))),
2588 words: words.map(|p| snapshot_of(&p, |_, bytes| Words::decode(bytes))),
2589 mixed,
2590 }
2591 }
2592
2593 #[must_use]
2600 pub fn snapshot(&self, stated: &[Run]) -> Option<SnapshotRead> {
2601 let alarms = self.alarms.as_ref()?;
2602 Some(SnapshotRead {
2603 complete: alarms.heard.complete && !self.mixed,
2604 run: SnapshotRun::of(alarms.heard.run, stated),
2605 })
2606 }
2607}
2608
2609#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2615pub enum Latest {
2616 Firing,
2618 Resolved,
2620 Rebound,
2623 Deleted,
2625 Undecodable,
2627}
2628
2629impl Latest {
2630 #[must_use]
2632 pub fn of<E>(record: &Result<Record, E>) -> Latest {
2633 match record {
2634 Ok(r) if r.state == State::Firing => Latest::Firing,
2635 Ok(_) => Latest::Resolved,
2636 Err(_) => Latest::Undecodable,
2637 }
2638 }
2639}
2640
2641#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2645pub struct Reading {
2646 pub presence: Presence,
2651 pub freshness: Option<freshness::Judged>,
2656 pub latest: Option<Latest>,
2659 pub lost: bool,
2662 pub previous_instance: bool,
2665 pub held_whole: bool,
2667 pub left_out: bool,
2672}
2673
2674impl Reading {
2675 fn asked(&self) -> Asked {
2676 Asked {
2677 presence: self.presence,
2678 freshness: self
2679 .freshness
2680 .unwrap_or_else(|| freshness::judge_all(&super::horizon(), &[])),
2681 lost: self.lost,
2682 latest: self.latest.map(|l| match l {
2683 Latest::Firing => Step5::Firing,
2684 Latest::Undecodable => Step5::Undecodable,
2685 Latest::Resolved => Step5::Not(Reason::Resolved),
2686 Latest::Rebound => Step5::Not(Reason::Rebound),
2687 Latest::Deleted => Step5::Not(Reason::Deleted),
2688 }),
2689 previous_instance: self.previous_instance,
2690 held_whole: self.held_whole,
2691 left_out: self.left_out,
2692 }
2693 }
2694}
2695
2696#[must_use]
2702pub fn firing(r: &Reading) -> Judged {
2703 super::firing_asked(&r.asked())
2704}
2705
2706#[must_use]
2710pub fn stale_firing(r: &Reading) -> Judged {
2711 super::stale_firing_asked(&r.asked())
2712}
2713
2714#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2717pub enum SnapshotRun {
2718 Stated,
2720 Other,
2723 Unstated,
2726}
2727
2728impl SnapshotRun {
2729 #[must_use]
2731 pub fn of(run: Run, stated: &[Run]) -> SnapshotRun {
2732 if stated.is_empty() {
2733 SnapshotRun::Unstated
2734 } else if stated.contains(&run) {
2735 SnapshotRun::Stated
2736 } else {
2737 SnapshotRun::Other
2738 }
2739 }
2740}
2741
2742#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2744pub struct SnapshotRead {
2745 pub complete: bool,
2748 pub run: SnapshotRun,
2749}
2750
2751#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2754pub enum Read {
2755 Complete(Option<SnapshotRead>),
2759 Incomplete,
2761}
2762
2763#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2765pub struct Since {
2766 pub lossless: bool,
2768 pub present_throughout: bool,
2772}
2773
2774#[must_use]
2787pub fn owner_set(presence: Presence, read: Option<Read>, since: Option<Since>) -> SetJudged {
2788 let j = |verdict, reason| SetJudged { verdict, reason };
2789 use SetVerdict::{Established, NotAsked, Unobservable};
2790 if let Some(p) = super::premises(presence) {
2791 return j(
2792 match p.answer {
2793 Answer::NotAsked => NotAsked,
2794 _ => Unobservable,
2795 },
2796 p.reason,
2797 );
2798 }
2799 let snapshot = match read {
2800 None => return j(Unobservable, Reason::NoSeed),
2801 Some(Read::Incomplete) => return j(Unobservable, Reason::SeedIncomplete),
2802 Some(Read::Complete(snapshot)) => snapshot,
2803 };
2804 let across = matches!(presence, Presence::AcrossFace { .. });
2805 if let Some(s) = since {
2806 if !s.lossless {
2807 return j(Unobservable, Reason::WindowLost);
2808 }
2809 if !s.present_throughout && !across {
2810 return j(Unobservable, Reason::OwnerGap);
2811 }
2812 }
2813 match snapshot {
2814 None
2815 | Some(SnapshotRead {
2816 complete: false, ..
2817 }) => j(Unobservable, Reason::SnapshotIncomplete),
2818 Some(SnapshotRead {
2819 run: SnapshotRun::Other,
2820 ..
2821 }) if !across => j(Unobservable, Reason::SnapshotRun),
2822 Some(_) => j(Established, Reason::Snapshot),
2823 }
2824}
2825
2826#[cfg(test)]
2827mod tests {
2828 use super::*;
2829
2830 fn table() -> Vec<Rule> {
2831 rules(&json!([
2832 {"name": "hot", "category": "sensor_health", "summary": "Temperature {argument} C",
2833 "argument": {"minimum": "-40", "resolution": "0.1"}},
2834 {"name": "link_down", "summary": "Link to {peer} on {port} is down",
2835 "labels": [{"name": "peer", "values": ["r1", "r2", "r3"]},
2836 {"name": "port", "values": ["eth0", "eth1"]}]},
2837 {"name": "sensor_lost", "summary": "Sensor {sensor} lost",
2838 "labels": [{"name": "sensor", "minimum": 0, "maximum": 63}]},
2839 ]))
2840 .expect("the text's table")
2841 }
2842
2843 fn stamp(run: u16, seq: u32) -> Stamp {
2844 Stamp {
2845 run: Run::U16(run),
2846 seq: Seq::new(seq).unwrap(),
2847 }
2848 }
2849
2850 #[test]
2851 fn the_layout_is_nine_bytes_for_the_usual_record_and_its_tag_is_eleven() {
2852 let l = layout();
2853 assert_eq!((l.tag(), l.min_bits(), l.max_bits()), (TAG, 35, 155));
2854 let epoch = 1_767_225_600;
2855 let r = Record {
2856 state: State::Firing,
2857 severity: Some(Severity::Critical),
2858 rule: RuleIndex::Table(3),
2859 at: Some(1_794_062_759),
2860 labels: None,
2861 argument: Argument::NotAvailable,
2862 key: None,
2863 };
2864 let written = r.write(epoch).unwrap();
2865 assert_eq!(
2866 written.bytes,
2867 [0x40, 0x70, 0x19, 0x98, 0x0a, 0x77, 0xff, 0xff, 0x80]
2868 );
2869 assert_eq!(Record::read(TAG, &written.bytes, epoch), Ok(r));
2870 let put = r.put(stamp(3, 5), epoch).unwrap();
2871 assert_eq!(put[0], 0x0b, "form 0, a 16-bit run, tag 11");
2872 assert_eq!(put.len(), 15);
2873 assert_eq!(
2875 Record::read(0, &written.bytes, epoch),
2876 Err(Undecodable::Core(ReadRefusal::Tag))
2877 );
2878 let bare = Record { at: None, ..r };
2880 assert_eq!(bare.write(epoch).unwrap().bytes.len(), 5);
2881 }
2882
2883 #[test]
2884 fn a_key_goes_with_not_available_and_with_nothing_else() {
2885 let epoch = 0;
2886 let by_words = Record {
2887 state: State::Firing,
2888 severity: Some(Severity::Warning),
2889 rule: RuleIndex::NotAvailable,
2890 at: None,
2891 labels: None,
2892 argument: Argument::NotAvailable,
2893 key: Some(0xa659_f813_308a_d1da),
2894 };
2895 assert_eq!(by_words.write(epoch).unwrap().bytes.len(), 13);
2896 let no_key = Record {
2897 key: None,
2898 ..by_words
2899 };
2900 assert_eq!(no_key.write(epoch), Err(Refused::KeyMissing));
2901 let both = Record {
2902 rule: RuleIndex::Table(1),
2903 ..by_words
2904 };
2905 assert_eq!(both.write(epoch), Err(Refused::KeyWithRule));
2906 let labelled = Record {
2907 labels: Some(2),
2908 ..by_words
2909 };
2910 assert_eq!(labelled.write(epoch), Err(Refused::ByWordsFields));
2911 assert_eq!(RuleIndex::new(255), None);
2912 assert_eq!(Argument::new(1_048_575), None);
2913 }
2914
2915 #[test]
2916 fn an_alarm_is_written_by_its_table_or_by_words_and_read_back() {
2917 let t = table();
2918 let f = write_alarm(
2919 Some(&t),
2920 "link_down",
2921 [("port", "eth0"), ("peer", "r2"), ("host", "h-3fa9c2d41b7e")],
2922 None,
2923 );
2924 assert_eq!(
2925 (f.rule, f.labels, f.key),
2926 (RuleIndex::Table(1), Some(2), None)
2927 );
2928 let record = Record::new(State::Firing, Severity::Warning, f, None);
2929 let Naming::Named(n) = record.name(Some(&t)) else {
2930 panic!("named")
2931 };
2932 assert_eq!(super::super::key_hex(n.alert_key), "a659f813308ad1da");
2933 assert_eq!(n.summary, "Link to r2 on eth0 is down");
2934 let w = write_alarm(
2936 Some(&t),
2937 "link_down",
2938 [("peer", "r4"), ("port", "eth0")],
2939 None,
2940 );
2941 assert_eq!(w.rule, RuleIndex::NotAvailable);
2942 assert!(w.key.is_some() && w.labels.is_none());
2943 assert_eq!(record.name(None), Naming::Unnamed(Unnamed::NoTable));
2945 let hot = &t[0];
2947 let reading = |s: &str| hot.argument(Decimal::parse_input(s).as_ref());
2948 assert_eq!(reading("21.55"), Argument::Code(616));
2949 assert_eq!(reading("-40.2"), Argument::NotAvailable);
2950 assert_eq!(hot.summary(&[], Argument::Code(615)), "Temperature 21.5 C");
2951 assert_eq!(hot.summary(&[], Argument::NotAvailable), "Temperature ? C");
2952 }
2953
2954 #[test]
2955 fn a_tables_findings_come_in_the_texts_order() {
2956 let t = table_json(&table());
2957 assert_eq!(declaration(true, [&t]), Declared::Table(table()));
2958 assert_eq!(
2959 declaration(false, [&t]),
2960 Declared::Invalid(Invalid::NotUsed)
2961 );
2962 let twice = json!([{"name": "a", "summary": "{x}"}, {"name": "a", "summary": "s"}]);
2963 assert_eq!(
2964 declaration(true, [&twice]),
2965 Declared::Invalid(Invalid::RuleName),
2966 "before the placeholder"
2967 );
2968 let other = json!([{"name": "a", "summary": "s"}]);
2969 assert_eq!(
2970 declaration(true, [&t, &other]),
2971 Declared::Invalid(Invalid::Disagrees)
2972 );
2973 assert_eq!(
2974 declaration(true, [&t, &twice]),
2975 Declared::Invalid(Invalid::RuleName),
2976 "a finding of any list stands before `disagrees`"
2977 );
2978 assert_eq!(growth(&table()[..2], &table()), Growth::Kept);
2979 assert_eq!(growth(&table(), &table()[..2]), Growth::Moved);
2980 }
2981
2982 #[test]
2983 fn an_identity_takes_its_own_slot_else_the_lowest_that_does_not_fire() {
2984 let mut s: Slots<&str> = Slots::new(2);
2985 assert_eq!(s.raise(&"a"), Raise::Put(0));
2986 assert_eq!(s.raise(&"a"), Raise::Firing);
2987 assert_eq!(s.raise(&"b"), Raise::Put(1));
2988 assert_eq!(s.raise(&"c"), Raise::Refused, "never over a firing record");
2989 assert_eq!(s.resolve(&"a"), Resolve::Put(0));
2990 assert_eq!(s.resolve(&"a"), Resolve::NotFiring);
2991 assert_eq!(s.raise(&"a"), Raise::Put(0), "a re-raise keeps its slot");
2992 assert_eq!(s.resolve(&"b"), Resolve::Put(1));
2993 assert_eq!(s.raise(&"c"), Raise::Put(1), "a resolved slot retaken");
2994 assert_eq!(s.slot_of(&"b"), None);
2995 }
2996
2997 #[test]
2998 fn at_moves_a_second_at_a_time_and_an_acknowledgement_follows_it() {
2999 let epoch = 1_767_225_600;
3000 let mut d = Dating::default();
3001 assert_eq!(d.transition(1_794_062_759_100, epoch), Some(1_794_062_759));
3002 assert_eq!(d.transition(1_794_062_759_200, epoch), Some(1_794_062_760));
3003 assert_eq!(d.transition(5000, epoch), None, "1970 has no code");
3004 assert_eq!(d.at(Act::Refresh, None, 1_794_062_800_000, epoch), None);
3005 assert_eq!(d.transition(1_794_062_759_300, epoch), Some(1_794_062_761));
3006 assert!(acknowledged(Some(1_794_062_759_123), Some(1_794_062_759)));
3007 assert!(!acknowledged(Some(1_794_062_759_000), Some(1_794_062_760)));
3008 assert!(!acknowledged(Some(1_794_062_759_000), None));
3009 assert!(!acknowledged(None, None));
3010 }
3011
3012 #[test]
3013 fn another_identity_on_a_firing_slot_is_a_resolve_the_reader_lost() {
3014 let record = |rule, state| Record {
3015 state,
3016 severity: Some(Severity::Warning),
3017 rule: RuleIndex::Table(rule),
3018 at: Some(1),
3019 labels: None,
3020 argument: Argument::NotAvailable,
3021 key: None,
3022 };
3023 let held = |rule, state, run, key| Held {
3024 record: record(rule, state),
3025 run: Run::U16(run),
3026 alert_key: Some(key),
3027 };
3028 let mut t = Track::default();
3029 assert_eq!(
3030 t.apply(Sample::Put(held(1, State::Firing, 3, 10))).reads,
3031 Transition::Raised
3032 );
3033 let a = t.apply(Sample::Put(held(2, State::Firing, 3, 20)));
3034 assert_eq!(a.displaced.map(|d| d.0), Some(Displaced::Rebound));
3035 assert_eq!(
3036 a.reports.iter().map(|r| r.change).collect::<Vec<_>>(),
3037 [Change::Resolved, Change::Firing]
3038 );
3039 let b = t.apply(Sample::Put(held(1, State::Firing, 4, 10)));
3040 assert_eq!(b.displaced.map(|d| d.0), Some(Displaced::Dropped));
3041 assert_eq!(
3042 b.reports.len(),
3043 1,
3044 "an earlier run's last word resolves nothing"
3045 );
3046 assert_eq!(t.apply(Sample::Delete).reads, Transition::Resolved);
3047 assert_eq!(t.held, None);
3048 }
3049
3050 #[test]
3051 fn one_complete_snapshot_establishes_an_owners_alarms_with_no_entry() {
3052 let listed = Presence::Present(super::super::Listing::Listed { token: false });
3053 let whole = Read::Complete(Some(SnapshotRead {
3054 complete: true,
3055 run: SnapshotRun::Stated,
3056 }));
3057 let set = owner_set(listed, Some(whole), None);
3058 assert_eq!(
3059 (set.verdict, set.reason),
3060 (SetVerdict::Established, Reason::Snapshot)
3061 );
3062 assert_eq!(
3063 owner_set(listed, Some(Read::Complete(None)), None).reason,
3064 Reason::SnapshotIncomplete,
3065 "no page is silence"
3066 );
3067 let r = Reading {
3068 presence: listed,
3069 freshness: None,
3070 latest: Some(Latest::Rebound),
3071 lost: false,
3072 previous_instance: false,
3073 held_whole: true,
3074 left_out: false,
3075 };
3076 assert_eq!(firing(&r), Judged::new(Answer::No, Reason::Rebound));
3077 assert_eq!(
3078 stale_firing(&r),
3079 Judged::new(Answer::NotAsked, Reason::NotFiring)
3080 );
3081 }
3082}