use std::collections::BTreeMap;
use std::sync::OnceLock;
use serde_json::{Map, Value, json};
use super::{
Answer, Asked, Judged, Presence, PutFacts, Reason, SetJudged, SetVerdict, Severity, State,
Step5, Transition,
};
use crate::collection::{self, Confirmation, Page};
use crate::contract::Contract;
use crate::freshness;
use crate::grammar::{self, Addr, IfaceId, Key, KeyError, KindToken, ZkKey};
use crate::heartbeat;
use crate::packed::{self, Decimal, Fixed, Layout, ReadRefusal, WriteRefusal};
use crate::template::Template;
use crate::wire::{Envelope, Run, Seq, Stamp, Tag};
use crate::words;
pub const PROFILE: &str = "alarms.v2";
pub const IFACE: &str = "alarms.v2";
pub const FINGERPRINT: &str = "2292477cadf555dd09b07499ca048add4e48c63d60a209c13eaf543988c32cb7";
pub const SCHEMA_STEM: &str = "alarms.v2";
pub const PUBLISHED: &[&str] = &[
"sha256:fe59e748fc957322428ac633a0908d09aa8b6c66952f7a9cdd8608db715a2b2a",
"sha256:a3515ad47772ac778ccfbad3850a086ac18c28a9975eb7c8288c3437db9b99de",
];
#[must_use]
pub fn is_published(id: &str) -> bool {
PUBLISHED.contains(&id)
}
pub const VOCABULARY: &[&str] = &["rules"];
pub const RULES: &str = "alarms.rules";
pub const ALARMS: &str = "alarms/{slot}";
pub const WORDS: &str = "words/{slot}";
const ALARMS_CHUNK: &str = "alarms";
const WORDS_CHUNK: &str = "words";
pub const ALARMS_COLL: u32 = 0;
pub const WORDS_COLL: u32 = 1;
pub const TAG: u8 = 11;
pub const MAX_SLOTS: u16 = 256;
pub const MAX_RULES: usize = 255;
const MAX_INDEX: u8 = 254;
pub const LABELS_BITS: u32 = 24;
pub const CLASS: heartbeat::Class = heartbeat::Class::Host;
#[must_use]
pub fn uses_v2(c: &Contract) -> bool {
words::uses(c, PROFILE)
}
fn iface() -> IfaceId {
IfaceId::new(super::NAME, 2).expect("alarms.v2 is an interface id")
}
#[must_use]
pub fn parse_slot(chunk: &str) -> Option<u8> {
let digits = !chunk.is_empty() && chunk.bytes().all(|b| b.is_ascii_digit());
if !digits || (chunk.len() > 1 && chunk.starts_with('0')) {
return None;
}
chunk.parse().ok()
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SlotKey {
pub system: String,
pub service: String,
pub slot: u8,
}
fn slot_under(key: &str, chunk: &str) -> Option<SlotKey> {
let ZkKey::Data {
addr,
iface,
kind: KindToken::State,
resource,
} = grammar::parse(key).ok()?
else {
return None;
};
if iface.to_string() != IFACE {
return None;
}
let [lit, slot] = resource.as_slice() else {
return None;
};
if lit != chunk {
return None;
}
Some(SlotKey {
system: addr.system.as_str().to_owned(),
service: addr.service.as_str().to_owned(),
slot: parse_slot(slot)?,
})
}
#[must_use]
pub fn slot_of(key: &str) -> Option<SlotKey> {
slot_under(key, ALARMS_CHUNK)
}
#[must_use]
pub fn words_slot_of(key: &str) -> Option<SlotKey> {
slot_under(key, WORDS_CHUNK)
}
fn key_under(system: &str, service: &str, chunk: &str, slot: u8) -> Result<Key, KeyError> {
let addr = Addr::new(system, service)?;
grammar::data_key(
&addr,
&iface(),
KindToken::State,
&[chunk, &slot.to_string()],
)
}
pub fn alarm_key(system: &str, service: &str, slot: u8) -> Result<Key, KeyError> {
key_under(system, service, ALARMS_CHUNK, slot)
}
pub fn words_key(system: &str, service: &str, slot: u8) -> Result<Key, KeyError> {
key_under(system, service, WORDS_CHUNK, slot)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CollectionRead {
pub selector: String,
pub snapshot_key: String,
}
pub fn collection_read(system: &str, service: &str) -> Result<CollectionRead, KeyError> {
let addr = Addr::new(system, service)?;
let template = Template::parse(ALARMS).expect("the standard template parses");
let members = grammar::template_selector(&addr, &iface(), KindToken::State, &template);
let selector = collection::collection_read(&members, &template)
.expect("a template whose first chunk is a literal has a snapshot key");
let snapshot_key =
grammar::data_key(&addr, &iface(), KindToken::State, &[ALARMS_CHUNK])?.to_string();
Ok(CollectionRead {
selector,
snapshot_key,
})
}
pub const NOT_AVAILABLE: &str = "not_available";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RuleIndex {
Table(u8),
NotAvailable,
}
impl RuleIndex {
#[must_use]
pub const fn new(i: u8) -> Option<RuleIndex> {
if i <= MAX_INDEX {
Some(RuleIndex::Table(i))
} else {
None
}
}
#[must_use]
pub const fn of(index: words::Index) -> RuleIndex {
match index {
words::Index::At(i) => RuleIndex::Table(i),
words::Index::OutOfRange => RuleIndex::NotAvailable,
}
}
#[must_use]
pub fn to_json(self) -> Value {
match self {
RuleIndex::Table(i) => json!(i),
RuleIndex::NotAvailable => json!(NOT_AVAILABLE),
}
}
#[must_use]
pub fn of_json(v: &Value) -> Option<RuleIndex> {
match v {
Value::String(s) if s == NOT_AVAILABLE => Some(RuleIndex::NotAvailable),
v => RuleIndex::new(u8::try_from(v.as_u64()?).ok()?),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Argument {
Code(u32),
NotAvailable,
}
impl Argument {
pub const MAX: u32 = 1_048_574;
#[must_use]
pub const fn new(n: u32) -> Option<Argument> {
if n <= Argument::MAX {
Some(Argument::Code(n))
} else {
None
}
}
#[must_use]
pub fn to_json(self) -> Value {
match self {
Argument::Code(n) => json!(n),
Argument::NotAvailable => json!(NOT_AVAILABLE),
}
}
#[must_use]
pub fn of_json(v: &Value) -> Option<Argument> {
match v {
Value::String(s) if s == NOT_AVAILABLE => Some(Argument::NotAvailable),
v => Argument::new(u32::try_from(v.as_u64()?).ok()?),
}
}
}
fn schema() -> Value {
json!({"types": {"Alarm": {"fields": [
{"name": "state", "type": "enum", "values": ["firing", "resolved"]},
{"name": "severity", "type": "enum", "values": ["info", "warning", "critical"],
"escape": true},
{"name": "rule", "type": "int", "minimum": 0, "maximum": MAX_INDEX,
"reserved": [NOT_AVAILABLE]},
{"name": "at", "type": "time", "optional": true},
{"name": "labels", "type": "int", "minimum": 0, "maximum": (1u32 << LABELS_BITS) - 1,
"optional": true},
{"name": "argument", "type": "int", "minimum": 0, "maximum": Argument::MAX,
"reserved": [NOT_AVAILABLE]},
{"name": "key", "type": "counter", "width": 64, "optional": true},
packed::MARKER,
]}}})
}
pub const TYPE: &str = "Alarm";
#[must_use]
pub fn layout() -> &'static Layout {
static LAYOUT: OnceLock<Layout> = OnceLock::new();
LAYOUT.get_or_init(|| {
packed::layout_in(&schema(), TYPE).expect("the standard schema's declaration reads")
})
}
#[must_use]
pub fn time_at(unix_ms: i128, epoch: i64) -> Option<i64> {
packed::time_code(unix_ms, Some(epoch), false).ok()?;
i64::try_from(unix_ms.div_euclid(1000)).ok()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Refused {
Core(WriteRefusal),
KeyWithRule,
KeyMissing,
ByWordsFields,
}
impl Refused {
#[must_use]
pub fn token(self) -> &'static str {
match self {
Self::Core(r) => r.token(),
Self::KeyWithRule => "key_with_rule",
Self::KeyMissing => "key_missing",
Self::ByWordsFields => "by_words_fields",
}
}
}
impl std::fmt::Display for Refused {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Core(r) => r.fmt(f),
Self::KeyWithRule => f.write_str("key_with_rule: `key` beside a table's rule"),
Self::KeyMissing => f.write_str("key_missing: no `key` under a rule not_available"),
Self::ByWordsFields => {
f.write_str("by_words_fields: `labels` or an `argument` under a rule not_available")
}
}
}
}
impl std::error::Error for Refused {}
impl From<WriteRefusal> for Refused {
fn from(r: WriteRefusal) -> Self {
Refused::Core(r)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Undecodable {
Core(ReadRefusal),
KeyWithRule,
KeyMissing,
}
impl Undecodable {
#[must_use]
pub fn token(self) -> &'static str {
match self {
Self::Core(r) => r.token(),
Self::KeyWithRule => "key_with_rule",
Self::KeyMissing => "key_missing",
}
}
}
impl std::fmt::Display for Undecodable {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Core(r) => r.fmt(f),
Self::KeyWithRule => f.write_str("key_with_rule: `key` beside a table's rule"),
Self::KeyMissing => f.write_str("key_missing: no `key` under a rule not_available"),
}
}
}
impl std::error::Error for Undecodable {}
impl From<ReadRefusal> for Undecodable {
fn from(r: ReadRefusal) -> Self {
Undecodable::Core(r)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Record {
pub state: State,
pub severity: Option<Severity>,
pub rule: RuleIndex,
pub at: Option<i64>,
pub labels: Option<u32>,
pub argument: Argument,
pub key: Option<u64>,
}
fn time_json(seconds: i64) -> Value {
json!(i128::from(seconds) * 1000)
}
fn time_of_json(v: &Value) -> Option<i64> {
let ms = match v {
Value::Number(n) => n
.as_i64()
.map(i128::from)
.or_else(|| n.as_u64().map(i128::from))?,
_ => return None,
};
i64::try_from(ms.div_euclid(1000)).ok()
}
impl Record {
#[must_use]
pub fn new(state: State, severity: Severity, fields: Fields, at: Option<i64>) -> Record {
Record {
state,
severity: Some(severity),
rule: fields.rule,
at,
labels: fields.labels,
argument: fields.argument,
key: fields.key,
}
}
#[must_use]
pub const fn is_by_words(&self) -> bool {
matches!(self.rule, RuleIndex::NotAvailable)
}
#[must_use]
pub fn to_json(&self) -> Value {
let mut m = Map::new();
m.insert("state".into(), json!(self.state.as_str()));
m.insert(
"severity".into(),
self.severity.map_or(Value::Null, |s| json!(s.as_str())),
);
m.insert("rule".into(), self.rule.to_json());
if let Some(t) = self.at {
m.insert("at".into(), time_json(t));
}
if let Some(l) = self.labels {
m.insert("labels".into(), json!(l));
}
m.insert("argument".into(), self.argument.to_json());
if let Some(k) = self.key {
m.insert("key".into(), json!(k));
}
Value::Object(m)
}
#[must_use]
pub fn of_json(v: &Value) -> Option<Record> {
let state = match v.get("state")?.as_str()? {
"firing" => State::Firing,
"resolved" => State::Resolved,
_ => return None,
};
let severity = match v.get("severity")? {
Value::Null => None,
s => Some(Severity::parse(s.as_str()?)?),
};
let optional = |name: &str| v.get(name);
Some(Record {
state,
severity,
rule: RuleIndex::of_json(v.get("rule")?)?,
at: match optional("at") {
None => None,
Some(t) => Some(time_of_json(t)?),
},
labels: match optional("labels") {
None => None,
Some(l) => Some(u32::try_from(l.as_u64()?).ok()?),
},
argument: Argument::of_json(v.get("argument")?)?,
key: match optional("key") {
None => None,
Some(k) => Some(k.as_u64()?),
},
})
}
pub fn check(&self) -> Result<(), Undecodable> {
match (self.rule, self.key) {
(RuleIndex::Table(_), Some(_)) => Err(Undecodable::KeyWithRule),
(RuleIndex::NotAvailable, None) => Err(Undecodable::KeyMissing),
_ => Ok(()),
}
}
pub fn write(&self, epoch: i64) -> Result<packed::Record, Refused> {
write_value(&self.to_json(), epoch)
}
pub fn put(&self, stamp: Stamp, epoch: i64) -> Result<Vec<u8>, Refused> {
let record = self.write(epoch)?;
let tag = Tag::new(TAG).expect("a tag of four bits");
Ok(Envelope::mutation(tag, stamp, &record.bytes).write())
}
pub fn read(tag: u8, bytes: &[u8], epoch: i64) -> Result<Record, Undecodable> {
let value = layout().read(tag, bytes, Some(epoch))?;
let record = Record::of_json(&value).ok_or(ReadRefusal::Code)?;
record.check()?;
Ok(record)
}
}
pub fn write_value(value: &Value, epoch: i64) -> Result<packed::Record, Refused> {
let record = layout().write(value, Some(epoch))?;
let r = Record::of_json(value).ok_or(WriteRefusal::Value)?;
match r.check() {
Err(Undecodable::KeyWithRule) => return Err(Refused::KeyWithRule),
Err(_) => return Err(Refused::KeyMissing),
Ok(()) => {}
}
if r.is_by_words() && (r.labels.is_some() || r.argument != Argument::NotAvailable) {
return Err(Refused::ByWordsFields);
}
Ok(record)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Act {
Raise,
Escalate,
Refresh,
Resolve,
}
impl Act {
#[must_use]
pub const fn is_transition(self) -> bool {
!matches!(self, Act::Refresh)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct Dating {
greatest: Option<i64>,
}
impl Dating {
#[must_use]
pub const fn known(at: Option<i64>) -> Dating {
Dating { greatest: at }
}
#[must_use]
pub const fn greatest(&self) -> Option<i64> {
self.greatest
}
pub fn transition(&mut self, clock_ms: i128, epoch: i64) -> Option<i64> {
let clock = time_at(clock_ms, epoch)?;
let new = match self.greatest {
Some(g) if clock <= g => g.checked_add(1)?,
_ => clock,
};
time_at(i128::from(new) * 1000, epoch)?;
self.greatest = Some(new);
Some(new)
}
pub fn at(&mut self, act: Act, held: Option<i64>, clock_ms: i128, epoch: i64) -> Option<i64> {
if act.is_transition() {
self.transition(clock_ms, epoch)
} else {
held
}
}
}
#[must_use]
pub fn acknowledged(acked_at_ms: Option<i128>, at: Option<i64>) -> bool {
match (acked_at_ms, at) {
(Some(acked), Some(at)) => i128::from(at) * 1000 <= acked,
_ => false,
}
}
#[must_use]
pub fn adopted_at(timestamp_ms: u64, epoch: i64) -> Option<i64> {
time_at(i128::from(timestamp_ms), epoch)
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ArgumentDecl {
minimum: String,
resolution: String,
}
impl ArgumentDecl {
#[must_use]
pub fn new(minimum: &str, resolution: &str) -> Option<ArgumentDecl> {
Decimal::parse(minimum)?;
if Decimal::parse(resolution)? <= Decimal::from(0) {
return None;
}
Some(ArgumentDecl {
minimum: minimum.to_owned(),
resolution: resolution.to_owned(),
})
}
#[must_use]
pub fn minimum(&self) -> &str {
&self.minimum
}
#[must_use]
pub fn resolution(&self) -> &str {
&self.resolution
}
fn fixed(&self) -> Fixed {
Fixed::new(
&self.minimum,
&self.resolution,
u128::from(Argument::MAX) + 1,
)
}
fn of_json(v: &Value) -> Option<ArgumentDecl> {
let o = v.as_object()?;
if o.len() != 2 {
return None;
}
ArgumentDecl::new(o.get("minimum")?.as_str()?, o.get("resolution")?.as_str()?)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum LabelValues {
List(Vec<String>),
Range { minimum: i128, maximum: i128 },
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Label {
pub name: String,
pub values: LabelValues,
}
impl Label {
#[must_use]
pub fn count(&self) -> u128 {
match &self.values {
LabelValues::List(l) => l.len() as u128,
LabelValues::Range { minimum, maximum } => {
u128::try_from(maximum - minimum).map_or(0, |d| d + 1)
}
}
}
#[must_use]
pub fn width(&self) -> u32 {
match self.count() {
0 | 1 => 0,
n => u128::BITS - (n - 1).leading_zeros(),
}
}
#[must_use]
pub fn code(&self, text: &str) -> Option<u64> {
match &self.values {
LabelValues::List(l) => l.iter().position(|v| v == text).map(|i| i as u64),
LabelValues::Range { minimum, maximum } => {
let n: i128 = text.parse().ok()?;
if n.to_string() != text || n < *minimum || n > *maximum {
return None;
}
u64::try_from(n - minimum).ok()
}
}
}
#[must_use]
pub fn text(&self, code: u64) -> Option<String> {
if u128::from(code) >= self.count() {
return None;
}
match &self.values {
LabelValues::List(l) => l.get(usize::try_from(code).ok()?).cloned(),
LabelValues::Range { minimum, .. } => Some((minimum + i128::from(code)).to_string()),
}
}
fn of_json(v: &Value) -> Option<Label> {
let o = v.as_object()?;
let name = o.get("name")?.as_str()?.to_owned();
let values = match (o.get("values"), o.get("minimum"), o.get("maximum")) {
(Some(list), None, None) if o.len() == 2 => {
let list = words::list(list, usize::MAX, |_| true, false)?;
if list.is_empty() {
return None;
}
LabelValues::List(list)
}
(None, Some(minimum), Some(maximum)) if o.len() == 3 => {
let minimum = packed::json_integer(minimum).ok()?;
let maximum = packed::json_integer(maximum).ok()?;
if minimum > maximum {
return None;
}
LabelValues::Range { minimum, maximum }
}
_ => return None,
};
Some(Label { name, values })
}
fn to_json(&self) -> Value {
match &self.values {
LabelValues::List(l) => json!({"name": self.name, "values": l}),
LabelValues::Range { minimum, maximum } => {
let n = |x: i128| {
i64::try_from(x)
.map(Value::from)
.or_else(|_| u64::try_from(x).map(Value::from))
.unwrap_or(Value::Null)
};
json!({"name": self.name, "minimum": n(*minimum), "maximum": n(*maximum)})
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Rule {
pub name: String,
pub summary: String,
pub category: Option<String>,
pub argument: Option<ArgumentDecl>,
pub labels: Vec<Label>,
}
impl AsRef<str> for Rule {
fn as_ref(&self) -> &str {
&self.name
}
}
enum Piece<'a> {
Text(&'a str),
Placeholder(&'a str),
Stray,
}
fn pieces(summary: &str) -> Vec<Piece<'_>> {
let mut out = Vec::new();
let mut rest = summary;
while !rest.is_empty() {
match rest.find(['{', '}']) {
None => {
out.push(Piece::Text(rest));
break;
}
Some(i) => {
if i > 0 {
out.push(Piece::Text(&rest[..i]));
}
if rest[i..].starts_with('}') {
out.push(Piece::Stray);
rest = &rest[i + 1..];
} else if let Some(end) = rest[i + 1..].find('}') {
out.push(Piece::Placeholder(&rest[i + 1..i + 1 + end]));
rest = &rest[i + end + 2..];
} else {
out.push(Piece::Stray);
break;
}
}
}
}
out
}
impl Rule {
#[must_use]
pub fn labels_width(&self) -> u32 {
self.labels.iter().map(Label::width).sum()
}
#[must_use]
pub fn encode<'a>(
&self,
labels: impl IntoIterator<Item = (&'a str, &'a str)>,
) -> Option<Option<u32>> {
let given: Vec<(&str, &str)> = labels
.into_iter()
.filter(|(n, _)| !super::is_host_scoped(n))
.collect();
if given.len() != self.labels.len() || self.labels_width() > LABELS_BITS {
return None;
}
let mut codes: u64 = 0;
for label in &self.labels {
let mut of_name = given.iter().filter(|(n, _)| *n == label.name);
let (_, text) = of_name.next()?;
if of_name.next().is_some() {
return None;
}
codes = (codes << label.width()) | label.code(text)?;
}
if self.labels.is_empty() {
return Some(None);
}
Some(Some(u32::try_from(codes).ok()?))
}
#[must_use]
pub fn decode(&self, labels: Option<u32>) -> Option<Vec<(String, String)>> {
let Some(codes) = labels else {
return self.labels.is_empty().then(Vec::new);
};
let width = self.labels_width();
if self.labels.is_empty() || width > LABELS_BITS || u64::from(codes) >> width != 0 {
return None;
}
let mut left = width;
let mut out = Vec::with_capacity(self.labels.len());
for label in &self.labels {
let w = label.width();
left -= w;
let code = (u64::from(codes) >> left) & ((1u64 << w) - 1);
out.push((label.name.clone(), label.text(code)?));
}
Some(out)
}
#[must_use]
pub fn argument(&self, reading: Option<&Decimal>) -> Argument {
let (Some(decl), Some(reading)) = (&self.argument, reading) else {
return Argument::NotAvailable;
};
decl.fixed()
.code(reading)
.ok()
.and_then(|c| Argument::new(u32::try_from(c).ok()?))
.unwrap_or(Argument::NotAvailable)
}
#[must_use]
pub fn reading(&self, argument: Argument) -> Option<Decimal> {
let (Some(decl), Argument::Code(code)) = (&self.argument, argument) else {
return None;
};
decl.fixed().value(u64::from(code)).ok()
}
#[must_use]
pub fn summary(&self, labels: &[(String, String)], argument: Argument) -> String {
let mut out = String::new();
for piece in pieces(&self.summary) {
match piece {
Piece::Text(t) => out.push_str(t),
Piece::Stray => {}
Piece::Placeholder("argument") if self.argument.is_some() => {
match self.reading(argument) {
Some(r) => out.push_str(&r.to_string()),
None => out.push('?'),
}
}
Piece::Placeholder(name) => {
if let Some((_, text)) = labels.iter().find(|(n, _)| n == name) {
out.push_str(text);
}
}
}
}
out
}
fn of_json(v: &Value) -> Option<Rule> {
const MEMBERS: [&str; 5] = ["name", "summary", "category", "argument", "labels"];
let o = v.as_object()?;
if o.keys().any(|k| !MEMBERS.contains(&k.as_str())) {
return None;
}
Some(Rule {
name: o.get("name")?.as_str()?.to_owned(),
summary: o.get("summary")?.as_str()?.to_owned(),
category: match o.get("category") {
None => None,
Some(c) => Some(c.as_str()?.to_owned()),
},
argument: match o.get("argument") {
None => None,
Some(a) => Some(ArgumentDecl::of_json(a)?),
},
labels: match o.get("labels") {
None => Vec::new(),
Some(l) => {
let l = l.as_array().filter(|l| !l.is_empty())?;
l.iter().map(Label::of_json).collect::<Option<_>>()?
}
},
})
}
#[must_use]
pub fn to_json(&self) -> Value {
let mut m = Map::new();
m.insert("name".into(), json!(self.name));
m.insert("summary".into(), json!(self.summary));
if let Some(c) = &self.category {
m.insert("category".into(), json!(c));
}
if let Some(a) = &self.argument {
m.insert(
"argument".into(),
json!({"minimum": a.minimum, "resolution": a.resolution}),
);
}
if !self.labels.is_empty() {
m.insert(
"labels".into(),
Value::Array(self.labels.iter().map(Label::to_json).collect()),
);
}
Value::Object(m)
}
}
#[must_use]
pub fn table_json(table: &[Rule]) -> Value {
Value::Array(table.iter().map(Rule::to_json).collect())
}
#[must_use]
pub fn rules(v: &Value) -> Option<Vec<Rule>> {
let list = v.as_array()?;
if list.len() > MAX_RULES {
return None;
}
list.iter().map(Rule::of_json).collect()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Invalid {
NotUsed,
Value,
RuleName,
Label,
LabelsWidth,
HostLabel,
Placeholder,
Disagrees,
}
impl Invalid {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::NotUsed => "not_used",
Self::Value => "value",
Self::RuleName => "rule_name",
Self::Label => "label",
Self::LabelsWidth => "labels_width",
Self::HostLabel => "host_label",
Self::Placeholder => "placeholder",
Self::Disagrees => "disagrees",
}
}
#[must_use]
pub fn says(self) -> &'static str {
match self {
Self::NotUsed => "the contract's `uses` does not list alarms.v2",
Self::Value => {
"its value is not a list of at most 255 rules: name, summary, and optionally \
category, argument { minimum, resolution } and labels"
}
Self::RuleName => "a rule's name is empty, holds a newline, or is another rule's",
Self::Label => {
"a label's name is empty, `argument`, holds a newline, `=`, `{` or `}`, or comes \
twice in its rule; or a value holds a newline or comes twice"
}
Self::LabelsWidth => "a rule's labels take more than 24 bits",
Self::HostLabel => "a label's name is host-scoped: the key's system names the host",
Self::Placeholder => {
"a summary holds an unclosed `{`, a stray `}`, or a placeholder that is neither \
a label of its rule nor its `argument`"
}
Self::Disagrees => {
"two resources carry two different lists: write the key once, on [defaults]"
}
}
}
fn found_in(self, table: &[Rule]) -> bool {
let labels = || table.iter().flat_map(|r| r.labels.iter());
match self {
Self::NotUsed | Self::Value | Self::Disagrees => false,
Self::RuleName => table.iter().enumerate().any(|(i, r)| {
r.name.is_empty()
|| r.name.contains('\n')
|| table[..i].iter().any(|before| before.name == r.name)
}),
Self::Label => table.iter().any(|r| {
r.labels.iter().enumerate().any(|(i, l)| {
l.name.is_empty()
|| l.name == "argument"
|| l.name.contains(['\n', '=', '{', '}'])
|| r.labels[..i].iter().any(|before| before.name == l.name)
|| match &l.values {
LabelValues::List(values) => values
.iter()
.enumerate()
.any(|(j, v)| v.contains('\n') || values[..j].contains(v)),
LabelValues::Range { .. } => false,
}
})
}),
Self::LabelsWidth => table.iter().any(|r| r.labels_width() > LABELS_BITS),
Self::HostLabel => labels().any(|l| super::is_host_scoped(&l.name)),
Self::Placeholder => table.iter().any(|r| {
pieces(&r.summary).iter().any(|p| match p {
Piece::Text(_) => false,
Piece::Stray => true,
Piece::Placeholder(name) => {
!(r.labels.iter().any(|l| l.name == *name)
|| (*name == "argument" && r.argument.is_some()))
}
})
}),
}
}
}
impl std::fmt::Display for Invalid {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
const OF_A_LIST: [Invalid; 5] = [
Invalid::RuleName,
Invalid::Label,
Invalid::LabelsWidth,
Invalid::HostLabel,
Invalid::Placeholder,
];
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Declared {
None,
Table(Vec<Rule>),
Invalid(Invalid),
}
impl Declared {
#[must_use]
pub fn table(&self) -> Option<&[Rule]> {
match self {
Declared::Table(t) => Some(t),
Declared::None | Declared::Invalid(_) => None,
}
}
}
fn declared<'v>(
uses_v2: bool,
carried: impl IntoIterator<Item = &'v Value>,
) -> (Declared, Option<usize>) {
let carried: Vec<&Value> = carried.into_iter().collect();
if carried.is_empty() {
return (Declared::None, None);
}
if !uses_v2 {
return (Declared::Invalid(Invalid::NotUsed), Some(0));
}
let mut lists = Vec::with_capacity(carried.len());
for (i, v) in carried.iter().enumerate() {
match rules(v) {
Some(list) => lists.push(list),
None => return (Declared::Invalid(Invalid::Value), Some(i)),
}
}
for finding in OF_A_LIST {
if let Some(i) = lists.iter().position(|l| finding.found_in(l)) {
return (Declared::Invalid(finding), Some(i));
}
}
if let Some(i) = lists.iter().position(|l| *l != lists[0]) {
return (Declared::Invalid(Invalid::Disagrees), Some(i));
}
(Declared::Table(lists.swap_remove(0)), None)
}
#[must_use]
pub fn declaration<'v>(uses_v2: bool, carried: impl IntoIterator<Item = &'v Value>) -> Declared {
declared(uses_v2, carried).0
}
#[must_use]
pub fn declaration_of(c: &Contract) -> Declared {
declaration(
uses_v2(c),
c.resources.iter().filter_map(|r| r.annotations.get(RULES)),
)
}
#[must_use]
pub fn table_of(c: &Contract) -> Option<Vec<Rule>> {
declaration_of(c).table().map(<[Rule]>::to_vec)
}
pub type Instance = words::Instance<Rule>;
#[must_use]
pub fn instance_table<'a>(named: impl IntoIterator<Item = Option<&'a [Rule]>>) -> Instance {
words::instance_table(named)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Growth {
Same,
Kept,
Moved,
}
impl Growth {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Same => "same",
Self::Kept => "kept",
Self::Moved => "moved",
}
}
}
#[must_use]
pub fn growth(old: &[Rule], new: &[Rule]) -> Growth {
if old == new {
Growth::Same
} else if old.len() <= new.len()
&& old
.iter()
.zip(new)
.all(|(o, n)| o.name == n.name && o.labels == n.labels)
{
Growth::Kept
} else {
Growth::Moved
}
}
pub use crate::words::Lint;
#[must_use]
pub fn lint_contract(c: &Contract) -> Vec<Lint> {
if !uses_v2(c) {
return Vec::new();
}
let carrying: Vec<_> = c
.resources
.iter()
.filter(|r| r.annotations.contains_key(RULES))
.collect();
let values = carrying.iter().map(|r| &r.annotations[RULES]);
match declared(true, values) {
(Declared::Invalid(reason), Some(i)) => vec![Lint {
profile: PROFILE,
at: Lint::place(carrying[i]),
key: Some(RULES),
token: reason.as_str(),
says: reason.says(),
}],
_ => Vec::new(),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Fields {
pub rule: RuleIndex,
pub labels: Option<u32>,
pub argument: Argument,
pub key: Option<u64>,
}
impl Fields {
#[must_use]
pub fn to_json(&self) -> Value {
let mut m = Map::new();
m.insert("rule".into(), self.rule.to_json());
if let Some(l) = self.labels {
m.insert("labels".into(), json!(l));
}
m.insert("argument".into(), self.argument.to_json());
if let Some(k) = self.key {
m.insert("key".into(), json!(k));
}
Value::Object(m)
}
}
#[must_use]
pub fn write_alarm<'a>(
table: Option<&[Rule]>,
rule: &str,
labels: impl IntoIterator<Item = (&'a str, &'a str)>,
reading: Option<&Decimal>,
) -> Fields {
let labels: Vec<(&str, &str)> = labels.into_iter().collect();
let by_table = table.and_then(|t| {
let RuleIndex::Table(i) = RuleIndex::of(words::write(t, rule, MAX_INDEX)) else {
return None;
};
let r = &t[usize::from(i)];
Some(Fields {
rule: RuleIndex::Table(i),
labels: r.encode(labels.iter().copied())?,
argument: r.argument(reading),
key: None,
})
});
by_table.unwrap_or_else(|| Fields {
rule: RuleIndex::NotAvailable,
labels: None,
argument: Argument::NotAvailable,
key: Some(super::derive(rule, labels).integer()),
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Unnamed {
NoTable,
Rule,
Labels,
}
impl Unnamed {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::NoTable => "no_table",
Self::Rule => "rule",
Self::Labels => "labels",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Named<'t> {
pub index: u8,
pub rule: &'t Rule,
pub labels: Vec<(String, String)>,
pub alert_key: u64,
pub summary: String,
pub argument: Option<Decimal>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Naming<'t> {
Named(Named<'t>),
Unnamed(Unnamed),
ByWords { alert_key: u64 },
}
impl Naming<'_> {
#[must_use]
pub fn alert_key(&self) -> Option<u64> {
match self {
Naming::Named(n) => Some(n.alert_key),
Naming::ByWords { alert_key } => Some(*alert_key),
Naming::Unnamed(_) => None,
}
}
}
impl Record {
#[must_use]
pub fn name<'t>(&self, table: Option<&'t [Rule]>) -> Naming<'t> {
let index = match (self.rule, self.key) {
(RuleIndex::NotAvailable, Some(alert_key)) => return Naming::ByWords { alert_key },
(RuleIndex::NotAvailable, None) => return Naming::Unnamed(Unnamed::Rule),
(RuleIndex::Table(i), _) => i,
};
let Some(table) = table else {
return Naming::Unnamed(Unnamed::NoTable);
};
let Some(rule) = table.get(usize::from(index)) else {
return Naming::Unnamed(Unnamed::Rule);
};
let Some(labels) = rule.decode(self.labels) else {
return Naming::Unnamed(Unnamed::Labels);
};
let alert_key = super::derive(
&rule.name,
labels.iter().map(|(n, v)| (n.as_str(), v.as_str())),
)
.integer();
Naming::Named(Named {
index,
rule,
summary: rule.summary(&labels, self.argument),
argument: rule.reading(self.argument),
labels,
alert_key,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Raise {
Put(u8),
Firing,
Refused,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Resolve {
Put(u8),
NotFiring,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Left<I> {
pub id: I,
pub state: State,
pub reads: bool,
pub derives: bool,
pub evaluated: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Adoption {
Left,
Free,
Resolved,
Adopted,
}
impl Adoption {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Left => "left",
Self::Free => "free",
Self::Resolved => "resolved",
Self::Adopted => "adopted",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Slots<I> {
bound: u16,
held: BTreeMap<u8, (I, State)>,
}
impl<I: Clone + Eq> Slots<I> {
#[must_use]
pub fn new(bound: u16) -> Self {
Slots {
bound: bound.min(MAX_SLOTS),
held: BTreeMap::new(),
}
}
#[must_use]
pub fn bound(&self) -> u16 {
self.bound
}
pub fn held(&self) -> impl Iterator<Item = (u8, &I, State)> {
self.held
.iter()
.map(|(slot, (id, state))| (*slot, id, *state))
}
#[must_use]
pub fn slot_of(&self, id: &I) -> Option<(u8, State)> {
self.held
.iter()
.find(|(_, (held, _))| held == id)
.map(|(slot, (_, state))| (*slot, *state))
}
fn lowest_free(&self) -> Option<u8> {
(0..self.bound)
.filter_map(|s| u8::try_from(s).ok())
.find(|s| !matches!(self.held.get(s), Some((_, State::Firing))))
}
pub fn raise(&mut self, id: &I) -> Raise {
let slot = match self.slot_of(id) {
Some((_, State::Firing)) => return Raise::Firing,
Some((slot, State::Resolved)) => slot,
None => match self.lowest_free() {
Some(slot) => slot,
None => return Raise::Refused,
},
};
self.held.insert(slot, (id.clone(), State::Firing));
Raise::Put(slot)
}
pub fn resolve(&mut self, id: &I) -> Resolve {
match self.slot_of(id) {
Some((slot, State::Firing)) => {
self.held.insert(slot, (id.clone(), State::Resolved));
Resolve::Put(slot)
}
_ => Resolve::NotFiring,
}
}
pub fn forget(&mut self, slot: u8) {
self.held.remove(&slot);
}
#[must_use]
pub fn restart(
left: impl IntoIterator<Item = (u8, Left<I>)>,
bound: u16,
) -> (Self, BTreeMap<u8, Adoption>) {
let mut slots = Slots::new(bound);
let left: BTreeMap<u8, Left<I>> = left.into_iter().collect();
let mut did = BTreeMap::new();
for (slot, entry) in left {
let adoption = if u16::from(slot) >= slots.bound {
Adoption::Left
} else if entry.state == State::Resolved
|| !entry.reads
|| !entry.derives
|| slots.slot_of(&entry.id).is_some()
{
Adoption::Free
} else if !entry.evaluated {
slots.held.insert(slot, (entry.id, State::Resolved));
Adoption::Resolved
} else {
slots.held.insert(slot, (entry.id, State::Firing));
Adoption::Adopted
};
did.insert(slot, adoption);
}
(slots, did)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Seen {
pub slot: u8,
pub stamp: Stamp,
pub alert_key: Option<u64>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Taken {
pub takes: BTreeMap<u64, Option<u8>>,
pub double: Vec<u64>,
}
#[must_use]
pub fn taken(seen: &[Seen], present: Option<Run>) -> Taken {
let mut out = Taken::default();
let mut best: BTreeMap<u64, Seq> = BTreeMap::new();
for s in seen {
let Some(key) = s.alert_key else { continue };
let take = out.takes.entry(key).or_insert(None);
if Some(s.stamp.run) != present {
continue;
}
match best.get(&key) {
Some(seq) => {
if !out.double.contains(&key) {
out.double.push(key);
}
if s.stamp.seq.get() > seq.get() {
best.insert(key, s.stamp.seq);
*take = Some(s.slot);
}
}
None => {
best.insert(key, s.stamp.seq);
*take = Some(s.slot);
}
}
}
out.double.sort_unstable();
out
}
#[must_use]
pub fn one_slot_each(set: SetVerdict, taken: &Taken) -> Answer {
match set {
SetVerdict::Established if taken.double.is_empty() => Answer::Yes,
SetVerdict::Established => Answer::No,
SetVerdict::Unobservable | SetVerdict::NotAsked => Answer::Unobservable,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Words {
pub rule: String,
pub labels: BTreeMap<String, String>,
pub summary: String,
pub category: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WordsInvalid {
Json(String),
Schema(String),
}
impl std::fmt::Display for WordsInvalid {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Json(why) => write!(f, "not strict JSON: {why}"),
Self::Schema(why) => write!(f, "outside alarms.v2.Words: {why}"),
}
}
}
impl Words {
pub fn from_json(v: &Value) -> Result<Words, WordsInvalid> {
let schema = |why: String| WordsInvalid::Schema(why);
let Value::Object(o) = v else {
return Err(schema("not an object".into()));
};
let string = |m: &str, required: bool| -> Result<Option<String>, WordsInvalid> {
match o.get(m) {
None if required => Err(WordsInvalid::Schema(format!("/{m}: missing"))),
None => Ok(None),
Some(Value::String(s)) => Ok(Some(s.clone())),
Some(_) => Err(WordsInvalid::Schema(format!("/{m}: not a string"))),
}
};
let rule = string("rule", true)?.unwrap_or_default();
let summary = string("summary", true)?.unwrap_or_default();
let category = string("category", false)?;
let mut labels = BTreeMap::new();
match o.get("labels") {
None => {}
Some(Value::Object(l)) => {
for (n, v) in l {
let Value::String(v) = v else {
return Err(schema(format!("/labels/{n}: not a string")));
};
labels.insert(n.clone(), v.clone());
}
}
Some(_) => return Err(schema("/labels: not an object".into())),
}
Ok(Words {
rule,
labels,
summary,
category,
})
}
pub fn decode(bytes: &[u8]) -> Result<Words, WordsInvalid> {
let text = std::str::from_utf8(bytes)
.map_err(|e| WordsInvalid::Json(format!("not UTF-8: {e}")))?;
let v = crate::strict::parse_json(text).map_err(|e| WordsInvalid::Json(e.to_string()))?;
Words::from_json(&v)
}
#[must_use]
pub fn to_json(&self) -> Value {
let mut m = Map::new();
m.insert("rule".into(), json!(self.rule));
if !self.labels.is_empty() {
m.insert("labels".into(), json!(self.labels));
}
m.insert("summary".into(), json!(self.summary));
if let Some(c) = &self.category {
m.insert("category".into(), json!(c));
}
Value::Object(m)
}
#[must_use]
pub fn derive(&self) -> super::Derived {
super::derive(
&self.rule,
self.labels.iter().map(|(n, v)| (n.as_str(), v.as_str())),
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum How {
Strict,
Sanitized,
}
impl How {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Strict => "strict",
Self::Sanitized => "sanitized",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NotTaken {
NoRecord,
Undecodable,
Table,
NoWords,
Unreadable,
Mismatch,
}
impl NotTaken {
#[must_use]
pub fn as_str(self) -> &'static str {
self.reason().as_str()
}
#[must_use]
pub fn reason(self) -> Reason {
match self {
Self::NoRecord => Reason::NoRecord,
Self::Undecodable => Reason::Undecodable,
Self::Table => Reason::Table,
Self::NoWords => Reason::NoWords,
Self::Unreadable => Reason::Unreadable,
Self::Mismatch => Reason::Mismatch,
}
}
}
pub fn words_taken<E, F>(
record: Option<&Result<Record, E>>,
words: Option<&Result<Words, F>>,
) -> Result<How, NotTaken> {
let record = match record {
None => return Err(NotTaken::NoRecord),
Some(Err(_)) => return Err(NotTaken::Undecodable),
Some(Ok(r)) => r,
};
let key = match (record.rule, record.key) {
(RuleIndex::NotAvailable, Some(key)) => key,
(RuleIndex::NotAvailable, None) => return Err(NotTaken::Undecodable),
(RuleIndex::Table(_), _) => return Err(NotTaken::Table),
};
let words = match words {
None => return Err(NotTaken::NoWords),
Some(Err(_)) => return Err(NotTaken::Unreadable),
Some(Ok(w)) => w,
};
let derived = words.derive();
if derived.integer() != key {
Err(NotTaken::Mismatch)
} else if derived.framed {
Ok(How::Strict)
} else {
Ok(How::Sanitized)
}
}
#[must_use]
pub fn words_derive(taken: Result<How, NotTaken>) -> Judged {
match taken {
Ok(How::Strict) => Judged::new(Answer::Yes, Reason::Strict),
Ok(How::Sanitized) => Judged::new(Answer::Yes, Reason::Sanitized),
Err(why) => Judged::new(
match why {
NotTaken::Mismatch => Answer::No,
NotTaken::Table | NotTaken::NoWords | NotTaken::NoRecord => Answer::NotAsked,
NotTaken::Unreadable | NotTaken::Undecodable => Answer::Unobservable,
},
why.reason(),
),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Held {
pub record: Record,
pub run: Run,
pub alert_key: Option<u64>,
}
impl Held {
#[must_use]
pub fn same_identity(&self, other: &Held) -> bool {
match (self.alert_key, other.alert_key) {
(Some(a), Some(b)) => a == b,
_ => self.record.rule == other.record.rule && self.record.labels == other.record.labels,
}
}
fn facts(&self) -> PutFacts<Option<Severity>, Option<i64>> {
PutFacts {
state: self.record.state,
severity: self.record.severity,
at: self.record.at,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Sample {
Put(Held),
Unreadable,
Delete,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Displaced {
Rebound,
Replaced,
Dropped,
}
impl Displaced {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Rebound => "rebound",
Self::Replaced => "replaced",
Self::Dropped => "dropped",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Change {
Firing,
Resolved,
}
impl Change {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Firing => "firing",
Self::Resolved => "resolved",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Report {
pub change: Change,
pub alert_key: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Applied {
pub displaced: Option<(Displaced, Held)>,
pub reads: Transition,
pub reports: Vec<Report>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Track {
pub held: Option<Held>,
}
impl Track {
pub fn apply(&mut self, sample: Sample) -> Applied {
let held = self.held.take();
let was_firing = |h: &Held| h.record.state == State::Firing;
let mut reports = Vec::new();
let new = match sample {
Sample::Unreadable => {
return Applied {
displaced: None,
reads: Transition::Unreadable,
reports,
};
}
Sample::Delete => {
let reads = super::delete_reads(held.map(|h| h.record.state));
if let Some(h) = held.filter(was_firing) {
reports.push(Report {
change: Change::Resolved,
alert_key: h.alert_key,
});
}
return Applied {
displaced: None,
reads,
reports,
};
}
Sample::Put(new) => new,
};
self.held = Some(new);
let (same, displaced) = match held {
Some(h) if h.same_identity(&new) => (Some(h), None),
Some(h) => {
let what = if h.run != new.run {
Displaced::Dropped
} else if was_firing(&h) {
Displaced::Rebound
} else {
Displaced::Replaced
};
(None, Some((what, h)))
}
None => (None, None),
};
if let Some((Displaced::Rebound, h)) = displaced {
reports.push(Report {
change: Change::Resolved,
alert_key: h.alert_key,
});
}
let reads = super::put_reads(
same.as_ref().map(Held::facts),
new.facts(),
same.is_some_and(|h| h.record == new.record),
);
let fired = same.as_ref().is_some_and(was_firing);
let change = match reads {
Transition::Raised if !fired => Some(Change::Firing),
Transition::Escalated => Some(Change::Firing),
Transition::Resolved if fired => Some(Change::Resolved),
_ => None,
};
reports.extend(change.map(|change| Report {
change,
alert_key: new.alert_key,
}));
Applied {
displaced,
reads,
reports,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Collection {
Alarms,
Words,
}
impl Collection {
#[must_use]
pub const fn coll(self) -> u32 {
match self {
Collection::Alarms => ALARMS_COLL,
Collection::Words => WORDS_COLL,
}
}
#[must_use]
pub const fn suffix(self) -> &'static str {
match self {
Collection::Alarms => "alarms.v2/state/alarms",
Collection::Words => "alarms.v2/state/words",
}
}
#[must_use]
pub fn of(key: &str, coll: u32) -> Option<Collection> {
[Collection::Alarms, Collection::Words]
.into_iter()
.find(|c| {
key.strip_suffix(c.suffix())
.is_some_and(|rest| rest.is_empty() || rest.ends_with('/'))
&& c.coll() == coll
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Heard {
pub complete: bool,
pub tag: Tag,
pub run: Run,
pub asof: Seq,
pub time: collection::Time,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry<R> {
pub id: String,
pub slot: Option<u8>,
pub stamp: Stamp,
pub confirmation: Confirmation,
pub confirmed_at: Option<collection::Time>,
pub record: R,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Snapshot<R> {
pub heard: Heard,
pub live: Vec<Entry<R>>,
pub retired: Vec<(String, Stamp)>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Seed {
pub alarms: Option<Snapshot<Result<Record, Undecodable>>>,
pub words: Option<Snapshot<Result<Words, WordsInvalid>>>,
pub mixed: bool,
}
struct Pages {
heard: collection::Heard,
pages: Vec<Page>,
}
fn stamp_of(run: Option<Run>, seq: Seq, header: Run) -> Stamp {
Stamp {
run: run.unwrap_or(header),
seq,
}
}
fn snapshot_of<R>(p: &Pages, read: impl Fn(&Page, &[u8]) -> R) -> Snapshot<R> {
let entry = |e: &collection::Entry, page: &Page| {
let confirmed_at = match e.confirmation {
Confirmation::None => None,
Confirmation::AtTime => Some(page.time),
Confirmation::At(t) => Some(t),
}
.filter(|t| *t != collection::Time::Unknown);
Entry {
id: e.id.clone(),
slot: parse_slot(&e.id),
stamp: stamp_of(e.run, e.seq, page.run),
confirmation: e.confirmation,
confirmed_at,
record: read(page, &e.record),
}
};
Snapshot {
heard: Heard {
complete: p.heard.complete(),
tag: p.heard.tag,
run: p.heard.run,
asof: p.heard.asof,
time: p.heard.time,
},
live: p
.pages
.iter()
.flat_map(|page| page.live.iter().map(move |e| (e, page)))
.map(|(e, page)| entry(e, page))
.collect(),
retired: p
.pages
.iter()
.flat_map(|page| {
page.tombs
.iter()
.map(|t| (t.id.clone(), stamp_of(t.run, t.seq, page.run)))
})
.collect(),
}
}
impl Seed {
#[must_use]
pub fn of<'a>(replies: impl IntoIterator<Item = (&'a str, &'a [u8])>, epoch: i64) -> Seed {
let mut held: [Option<Pages>; 2] = [None, None];
let mut mixed = false;
for (key, payload) in replies {
let Ok(page) = Page::parse(payload) else {
continue;
};
let Some(c) = Collection::of(key, page.coll) else {
continue;
};
let slot = &mut held[c as usize];
match slot {
Some(p) if p.heard.holds(key, &page) => {
if p.heard.add(&page) {
p.pages.push(page);
}
}
Some(_) => mixed = true,
None => {
let mut heard = collection::Heard::of(key, &page);
heard.add(&page);
*slot = Some(Pages {
heard,
pages: vec![page],
});
}
}
}
let [alarms, words] = held;
Seed {
alarms: alarms
.map(|p| snapshot_of(&p, |page, bytes| Record::read(page.tag.get(), bytes, epoch))),
words: words.map(|p| snapshot_of(&p, |_, bytes| Words::decode(bytes))),
mixed,
}
}
#[must_use]
pub fn snapshot(&self, stated: &[Run]) -> Option<SnapshotRead> {
let alarms = self.alarms.as_ref()?;
Some(SnapshotRead {
complete: alarms.heard.complete && !self.mixed,
run: SnapshotRun::of(alarms.heard.run, stated),
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Latest {
Firing,
Resolved,
Rebound,
Deleted,
Undecodable,
}
impl Latest {
#[must_use]
pub fn of<E>(record: &Result<Record, E>) -> Latest {
match record {
Ok(r) if r.state == State::Firing => Latest::Firing,
Ok(_) => Latest::Resolved,
Err(_) => Latest::Undecodable,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Reading {
pub presence: Presence,
pub freshness: Option<freshness::Judged>,
pub latest: Option<Latest>,
pub lost: bool,
pub previous_instance: bool,
pub held_whole: bool,
pub left_out: bool,
}
impl Reading {
fn asked(&self) -> Asked {
Asked {
presence: self.presence,
freshness: self
.freshness
.unwrap_or_else(|| freshness::judge_all(&super::horizon(), &[])),
lost: self.lost,
latest: self.latest.map(|l| match l {
Latest::Firing => Step5::Firing,
Latest::Undecodable => Step5::Undecodable,
Latest::Resolved => Step5::Not(Reason::Resolved),
Latest::Rebound => Step5::Not(Reason::Rebound),
Latest::Deleted => Step5::Not(Reason::Deleted),
}),
previous_instance: self.previous_instance,
held_whole: self.held_whole,
left_out: self.left_out,
}
}
}
#[must_use]
pub fn firing(r: &Reading) -> Judged {
super::firing_asked(&r.asked())
}
#[must_use]
pub fn stale_firing(r: &Reading) -> Judged {
super::stale_firing_asked(&r.asked())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SnapshotRun {
Stated,
Other,
Unstated,
}
impl SnapshotRun {
#[must_use]
pub fn of(run: Run, stated: &[Run]) -> SnapshotRun {
if stated.is_empty() {
SnapshotRun::Unstated
} else if stated.contains(&run) {
SnapshotRun::Stated
} else {
SnapshotRun::Other
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SnapshotRead {
pub complete: bool,
pub run: SnapshotRun,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Read {
Complete(Option<SnapshotRead>),
Incomplete,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Since {
pub lossless: bool,
pub present_throughout: bool,
}
#[must_use]
pub fn owner_set(presence: Presence, read: Option<Read>, since: Option<Since>) -> SetJudged {
let j = |verdict, reason| SetJudged { verdict, reason };
use SetVerdict::{Established, NotAsked, Unobservable};
if let Some(p) = super::premises(presence) {
return j(
match p.answer {
Answer::NotAsked => NotAsked,
_ => Unobservable,
},
p.reason,
);
}
let snapshot = match read {
None => return j(Unobservable, Reason::NoSeed),
Some(Read::Incomplete) => return j(Unobservable, Reason::SeedIncomplete),
Some(Read::Complete(snapshot)) => snapshot,
};
let across = matches!(presence, Presence::AcrossFace { .. });
if let Some(s) = since {
if !s.lossless {
return j(Unobservable, Reason::WindowLost);
}
if !s.present_throughout && !across {
return j(Unobservable, Reason::OwnerGap);
}
}
match snapshot {
None
| Some(SnapshotRead {
complete: false, ..
}) => j(Unobservable, Reason::SnapshotIncomplete),
Some(SnapshotRead {
run: SnapshotRun::Other,
..
}) if !across => j(Unobservable, Reason::SnapshotRun),
Some(_) => j(Established, Reason::Snapshot),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn table() -> Vec<Rule> {
rules(&json!([
{"name": "hot", "category": "sensor_health", "summary": "Temperature {argument} C",
"argument": {"minimum": "-40", "resolution": "0.1"}},
{"name": "link_down", "summary": "Link to {peer} on {port} is down",
"labels": [{"name": "peer", "values": ["r1", "r2", "r3"]},
{"name": "port", "values": ["eth0", "eth1"]}]},
{"name": "sensor_lost", "summary": "Sensor {sensor} lost",
"labels": [{"name": "sensor", "minimum": 0, "maximum": 63}]},
]))
.expect("the text's table")
}
fn stamp(run: u16, seq: u32) -> Stamp {
Stamp {
run: Run::U16(run),
seq: Seq::new(seq).unwrap(),
}
}
#[test]
fn the_layout_is_nine_bytes_for_the_usual_record_and_its_tag_is_eleven() {
let l = layout();
assert_eq!((l.tag(), l.min_bits(), l.max_bits()), (TAG, 35, 155));
let epoch = 1_767_225_600;
let r = Record {
state: State::Firing,
severity: Some(Severity::Critical),
rule: RuleIndex::Table(3),
at: Some(1_794_062_759),
labels: None,
argument: Argument::NotAvailable,
key: None,
};
let written = r.write(epoch).unwrap();
assert_eq!(
written.bytes,
[0x40, 0x70, 0x19, 0x98, 0x0a, 0x77, 0xff, 0xff, 0x80]
);
assert_eq!(Record::read(TAG, &written.bytes, epoch), Ok(r));
let put = r.put(stamp(3, 5), epoch).unwrap();
assert_eq!(put[0], 0x0b, "form 0, a 16-bit run, tag 11");
assert_eq!(put.len(), 15);
assert_eq!(
Record::read(0, &written.bytes, epoch),
Err(Undecodable::Core(ReadRefusal::Tag))
);
let bare = Record { at: None, ..r };
assert_eq!(bare.write(epoch).unwrap().bytes.len(), 5);
}
#[test]
fn a_key_goes_with_not_available_and_with_nothing_else() {
let epoch = 0;
let by_words = Record {
state: State::Firing,
severity: Some(Severity::Warning),
rule: RuleIndex::NotAvailable,
at: None,
labels: None,
argument: Argument::NotAvailable,
key: Some(0xa659_f813_308a_d1da),
};
assert_eq!(by_words.write(epoch).unwrap().bytes.len(), 13);
let no_key = Record {
key: None,
..by_words
};
assert_eq!(no_key.write(epoch), Err(Refused::KeyMissing));
let both = Record {
rule: RuleIndex::Table(1),
..by_words
};
assert_eq!(both.write(epoch), Err(Refused::KeyWithRule));
let labelled = Record {
labels: Some(2),
..by_words
};
assert_eq!(labelled.write(epoch), Err(Refused::ByWordsFields));
assert_eq!(RuleIndex::new(255), None);
assert_eq!(Argument::new(1_048_575), None);
}
#[test]
fn an_alarm_is_written_by_its_table_or_by_words_and_read_back() {
let t = table();
let f = write_alarm(
Some(&t),
"link_down",
[("port", "eth0"), ("peer", "r2"), ("host", "h-3fa9c2d41b7e")],
None,
);
assert_eq!(
(f.rule, f.labels, f.key),
(RuleIndex::Table(1), Some(2), None)
);
let record = Record::new(State::Firing, Severity::Warning, f, None);
let Naming::Named(n) = record.name(Some(&t)) else {
panic!("named")
};
assert_eq!(super::super::key_hex(n.alert_key), "a659f813308ad1da");
assert_eq!(n.summary, "Link to r2 on eth0 is down");
let w = write_alarm(
Some(&t),
"link_down",
[("peer", "r4"), ("port", "eth0")],
None,
);
assert_eq!(w.rule, RuleIndex::NotAvailable);
assert!(w.key.is_some() && w.labels.is_none());
assert_eq!(record.name(None), Naming::Unnamed(Unnamed::NoTable));
let hot = &t[0];
let reading = |s: &str| hot.argument(Decimal::parse_input(s).as_ref());
assert_eq!(reading("21.55"), Argument::Code(616));
assert_eq!(reading("-40.2"), Argument::NotAvailable);
assert_eq!(hot.summary(&[], Argument::Code(615)), "Temperature 21.5 C");
assert_eq!(hot.summary(&[], Argument::NotAvailable), "Temperature ? C");
}
#[test]
fn a_tables_findings_come_in_the_texts_order() {
let t = table_json(&table());
assert_eq!(declaration(true, [&t]), Declared::Table(table()));
assert_eq!(
declaration(false, [&t]),
Declared::Invalid(Invalid::NotUsed)
);
let twice = json!([{"name": "a", "summary": "{x}"}, {"name": "a", "summary": "s"}]);
assert_eq!(
declaration(true, [&twice]),
Declared::Invalid(Invalid::RuleName),
"before the placeholder"
);
let other = json!([{"name": "a", "summary": "s"}]);
assert_eq!(
declaration(true, [&t, &other]),
Declared::Invalid(Invalid::Disagrees)
);
assert_eq!(
declaration(true, [&t, &twice]),
Declared::Invalid(Invalid::RuleName),
"a finding of any list stands before `disagrees`"
);
assert_eq!(growth(&table()[..2], &table()), Growth::Kept);
assert_eq!(growth(&table(), &table()[..2]), Growth::Moved);
}
#[test]
fn an_identity_takes_its_own_slot_else_the_lowest_that_does_not_fire() {
let mut s: Slots<&str> = Slots::new(2);
assert_eq!(s.raise(&"a"), Raise::Put(0));
assert_eq!(s.raise(&"a"), Raise::Firing);
assert_eq!(s.raise(&"b"), Raise::Put(1));
assert_eq!(s.raise(&"c"), Raise::Refused, "never over a firing record");
assert_eq!(s.resolve(&"a"), Resolve::Put(0));
assert_eq!(s.resolve(&"a"), Resolve::NotFiring);
assert_eq!(s.raise(&"a"), Raise::Put(0), "a re-raise keeps its slot");
assert_eq!(s.resolve(&"b"), Resolve::Put(1));
assert_eq!(s.raise(&"c"), Raise::Put(1), "a resolved slot retaken");
assert_eq!(s.slot_of(&"b"), None);
}
#[test]
fn at_moves_a_second_at_a_time_and_an_acknowledgement_follows_it() {
let epoch = 1_767_225_600;
let mut d = Dating::default();
assert_eq!(d.transition(1_794_062_759_100, epoch), Some(1_794_062_759));
assert_eq!(d.transition(1_794_062_759_200, epoch), Some(1_794_062_760));
assert_eq!(d.transition(5000, epoch), None, "1970 has no code");
assert_eq!(d.at(Act::Refresh, None, 1_794_062_800_000, epoch), None);
assert_eq!(d.transition(1_794_062_759_300, epoch), Some(1_794_062_761));
assert!(acknowledged(Some(1_794_062_759_123), Some(1_794_062_759)));
assert!(!acknowledged(Some(1_794_062_759_000), Some(1_794_062_760)));
assert!(!acknowledged(Some(1_794_062_759_000), None));
assert!(!acknowledged(None, None));
}
#[test]
fn another_identity_on_a_firing_slot_is_a_resolve_the_reader_lost() {
let record = |rule, state| Record {
state,
severity: Some(Severity::Warning),
rule: RuleIndex::Table(rule),
at: Some(1),
labels: None,
argument: Argument::NotAvailable,
key: None,
};
let held = |rule, state, run, key| Held {
record: record(rule, state),
run: Run::U16(run),
alert_key: Some(key),
};
let mut t = Track::default();
assert_eq!(
t.apply(Sample::Put(held(1, State::Firing, 3, 10))).reads,
Transition::Raised
);
let a = t.apply(Sample::Put(held(2, State::Firing, 3, 20)));
assert_eq!(a.displaced.map(|d| d.0), Some(Displaced::Rebound));
assert_eq!(
a.reports.iter().map(|r| r.change).collect::<Vec<_>>(),
[Change::Resolved, Change::Firing]
);
let b = t.apply(Sample::Put(held(1, State::Firing, 4, 10)));
assert_eq!(b.displaced.map(|d| d.0), Some(Displaced::Dropped));
assert_eq!(
b.reports.len(),
1,
"an earlier run's last word resolves nothing"
);
assert_eq!(t.apply(Sample::Delete).reads, Transition::Resolved);
assert_eq!(t.held, None);
}
#[test]
fn one_complete_snapshot_establishes_an_owners_alarms_with_no_entry() {
let listed = Presence::Present(super::super::Listing::Listed { token: false });
let whole = Read::Complete(Some(SnapshotRead {
complete: true,
run: SnapshotRun::Stated,
}));
let set = owner_set(listed, Some(whole), None);
assert_eq!(
(set.verdict, set.reason),
(SetVerdict::Established, Reason::Snapshot)
);
assert_eq!(
owner_set(listed, Some(Read::Complete(None)), None).reason,
Reason::SnapshotIncomplete,
"no page is silence"
);
let r = Reading {
presence: listed,
freshness: None,
latest: Some(Latest::Rebound),
lost: false,
previous_instance: false,
held_whole: true,
left_out: false,
};
assert_eq!(firing(&r), Judged::new(Answer::No, Reason::Rebound));
assert_eq!(
stale_firing(&r),
Judged::new(Answer::NotAsked, Reason::NotFiring)
);
}
}