use std::sync::OnceLock;
use std::time::Duration;
use serde_json::{Map, Value, json};
use super::{Answer, Clock, ClockReason, Level, Listing, Presence, Read};
use crate::collection::{self, Confirmation, Page};
use crate::contract::Contract;
use crate::heartbeat;
use crate::packed::{self, Layout, ReadRefusal, Record, WriteRefusal};
use crate::wire::{Envelope, Run, Seq, Stamp, Tag};
use crate::words::{self, Index};
pub const PROFILE: &str = "health.v2";
pub const IFACE: &str = "health.v2";
pub const FINGERPRINT: &str = "b447f613bea7bdc24703500280a20bf0cf20fb27cbb38ecd25f5164b0ae005b1";
pub const SCHEMA_STEM: &str = "health.v2";
pub const PUBLISHED: &[&str] =
&["sha256:d270e1487bb6b2688aa34e5cb55804a14edc61a64e5fdd88d167b21ca4eaa983"];
#[must_use]
pub fn is_published(id: &str) -> bool {
PUBLISHED.contains(&id)
}
pub const VOCABULARY: &[&str] = &["reasons", "details", "codes"];
pub const CHECKS_COLL: u32 = 0;
pub const STATUS_COLL: u32 = 1;
pub const STATUS_CLASS: heartbeat::Class = heartbeat::Class::Host;
#[must_use]
pub fn uses_v2(c: &Contract) -> bool {
words::uses(c, PROFILE)
}
pub const REASONS: &[&str] = &[
"starting",
"serving",
"stopping",
"check",
"upstream_lost",
"fallback",
"backlog",
"misconfigured",
];
pub const DETAILS: &[&str] = &["ok", "unreachable", "timeout", "refused", "cannot_run"];
pub const CODES: &[&str] = &[super::CLOCK_AHEAD];
pub const STARTING: &str = "starting";
pub const CHECK: &str = "check";
pub const CANNOT_RUN: &str = "cannot_run";
pub const OWN_FIRST: u8 = 32;
pub const OWN_MAX: usize = 31;
const PROFILE_FIRST: u8 = 1;
const HALF_MAX: u8 = 30;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Word(u8);
impl Word {
pub const NONE: Word = Word(0);
pub const OUT_OF_RANGE: Word = Word(63);
pub const OUT_OF_RANGE_NAME: &'static str = words::OUT_OF_RANGE;
pub const MAX: u8 = 62;
#[must_use]
pub const fn new(n: u8) -> Option<Word> {
if n <= Word::MAX { Some(Word(n)) } else { None }
}
#[must_use]
pub const fn code(self) -> u8 {
self.0
}
#[must_use]
pub const fn is_none(self) -> bool {
self.0 == 0
}
#[must_use]
pub const fn is_out_of_range(self) -> bool {
self.0 == Word::OUT_OF_RANGE.0
}
#[must_use]
pub fn to_json(self) -> Value {
if self.is_out_of_range() {
json!(Word::OUT_OF_RANGE_NAME)
} else {
json!(self.0)
}
}
#[must_use]
pub fn of_json(v: &Value) -> Option<Word> {
match v {
Value::String(s) if s == Word::OUT_OF_RANGE_NAME => Some(Word::OUT_OF_RANGE),
v => Word::new(u8::try_from(v.as_u64()?).ok()?),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Kind {
Reason,
Detail,
Code,
}
impl Kind {
pub const ALL: [Kind; 3] = [Kind::Reason, Kind::Detail, Kind::Code];
#[must_use]
pub const fn key(self) -> &'static str {
match self {
Kind::Reason => "health.reasons",
Kind::Detail => "health.details",
Kind::Code => "health.codes",
}
}
#[must_use]
pub const fn table(self) -> &'static str {
match self {
Kind::Reason => "reasons",
Kind::Detail => "details",
Kind::Code => "codes",
}
}
#[must_use]
pub const fn profile(self) -> &'static [&'static str] {
match self {
Kind::Reason => REASONS,
Kind::Detail => DETAILS,
Kind::Code => CODES,
}
}
}
#[must_use]
pub fn is_name(s: &str) -> bool {
super::is_code_form(s)
}
#[must_use]
pub fn names(v: &Value) -> Option<Vec<String>> {
words::list(v, OWN_MAX, is_name, true)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Invalid {
NotUsed,
Value,
Disagrees,
}
impl Invalid {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::NotUsed => "not_used",
Self::Value => "value",
Self::Disagrees => "disagrees",
}
}
#[must_use]
pub fn says(self) -> &'static str {
match self {
Self::NotUsed => "the contract's `uses` does not list health.v2",
Self::Value => {
"its value is not a list of at most 31 names, each [a-z][a-z0-9_]*, none twice"
}
Self::Disagrees => {
"two resources carry two different lists: write the key once, on [defaults]"
}
}
}
}
impl std::fmt::Display for Invalid {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Declared {
None,
Table(Vec<String>),
Invalid(Invalid),
}
impl Declared {
#[must_use]
pub fn table(&self) -> Option<&[String]> {
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 names(v) {
Some(list) => lists.push(list),
None => return (Declared::Invalid(Invalid::Value), 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, kind: Kind) -> Declared {
declaration(
uses_v2(c),
c.resources
.iter()
.filter_map(|r| r.annotations.get(kind.key())),
)
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Tables {
pub reasons: Option<Vec<String>>,
pub details: Option<Vec<String>>,
pub codes: Option<Vec<String>>,
}
impl Tables {
#[must_use]
pub fn get(&self, kind: Kind) -> Option<&[String]> {
match kind {
Kind::Reason => self.reasons.as_deref(),
Kind::Detail => self.details.as_deref(),
Kind::Code => self.codes.as_deref(),
}
}
fn slot(&mut self, kind: Kind) -> &mut Option<Vec<String>> {
match kind {
Kind::Reason => &mut self.reasons,
Kind::Detail => &mut self.details,
Kind::Code => &mut self.codes,
}
}
#[must_use]
pub fn of(c: &Contract) -> Tables {
let mut t = Tables::default();
for kind in Kind::ALL {
*t.slot(kind) = declaration_of(c, kind).table().map(<[String]>::to_vec);
}
t
}
#[must_use]
pub fn of_instance<'a>(named: impl IntoIterator<Item = &'a Tables>) -> InstanceTables {
let named: Vec<&Tables> = named.into_iter().collect();
let of = |kind| instance_table(named.iter().map(|t| t.get(kind)));
InstanceTables {
reasons: of(Kind::Reason),
details: of(Kind::Detail),
codes: of(Kind::Code),
}
}
}
pub type Instance = words::Instance<String>;
#[must_use]
pub fn instance_table<'a>(named: impl IntoIterator<Item = Option<&'a [String]>>) -> Instance {
words::instance_table(named)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstanceTables {
pub reasons: Instance,
pub details: Instance,
pub codes: Instance,
}
impl Default for InstanceTables {
fn default() -> Self {
InstanceTables {
reasons: Instance::None,
details: Instance::None,
codes: Instance::None,
}
}
}
impl InstanceTables {
#[must_use]
pub fn get(&self, kind: Kind) -> &Instance {
match kind {
Kind::Reason => &self.reasons,
Kind::Detail => &self.details,
Kind::Code => &self.codes,
}
}
#[must_use]
pub fn own(&self, kind: Kind) -> Option<&[String]> {
self.get(kind).table()
}
}
#[must_use]
pub fn write_word(kind: Kind, word: Option<&str>, own: Option<&[String]>) -> Word {
let Some(word) = word else {
return Word::NONE;
};
let place = |index: Index, first: u8| match index {
Index::At(i) => Word(first + i),
Index::OutOfRange => Word::OUT_OF_RANGE,
};
if kind.profile().contains(&word) {
return place(words::write(kind.profile(), word, HALF_MAX), PROFILE_FIRST);
}
place(
own.map_or(Index::OutOfRange, |t| words::write(t, word, HALF_MAX)),
OWN_FIRST,
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Named<'a> {
None,
Profile(&'static str),
Service(&'a str),
Number(u8),
OutOfRange,
}
#[must_use]
pub fn read_word(kind: Kind, word: Word, own: Option<&[String]>) -> Named<'_> {
let n = word.code();
if word.is_none() {
Named::None
} else if word.is_out_of_range() {
Named::OutOfRange
} else if n < OWN_FIRST {
match words::read(Some(kind.profile()), Index::At(n - PROFILE_FIRST)) {
words::Word::Entry(name) => Named::Profile(name),
_ => Named::Number(n),
}
} else {
match words::read(own, Index::At(n - OWN_FIRST)) {
words::Word::Entry(name) => Named::Service(name),
_ => Named::Number(n),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Growth {
Same,
Appended,
Moved,
}
impl Growth {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Same => "same",
Self::Appended => "appended",
Self::Moved => "moved",
}
}
}
#[must_use]
pub fn growth(old: &[String], new: &[String]) -> Growth {
if old == new {
Growth::Same
} else if new.starts_with(old) {
Growth::Appended
} 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 mut out = Vec::new();
for kind in Kind::ALL {
let carrying: Vec<_> = c
.resources
.iter()
.filter(|r| r.annotations.contains_key(kind.key()))
.collect();
let values = carrying.iter().map(|r| &r.annotations[kind.key()]);
if let (Declared::Invalid(reason), Some(i)) = declared(true, values) {
out.push(Lint {
profile: PROFILE,
at: Lint::place(carrying[i]),
key: Some(kind.key()),
token: reason.as_str(),
says: reason.says(),
});
}
}
out
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RecordType {
Status,
Check,
Fault,
}
impl RecordType {
pub const ALL: [RecordType; 3] = [RecordType::Status, RecordType::Check, RecordType::Fault];
#[must_use]
pub const fn name(self) -> &'static str {
match self {
RecordType::Status => "Status",
RecordType::Check => "Check",
RecordType::Fault => "Fault",
}
}
#[must_use]
pub const fn tag(self) -> u8 {
match self {
RecordType::Status | RecordType::Check => 3,
RecordType::Fault => 11,
}
}
#[must_use]
pub fn layout(self) -> &'static Layout {
static LAYOUTS: OnceLock<[Layout; 3]> = OnceLock::new();
let all = LAYOUTS.get_or_init(|| {
let doc = schema();
RecordType::ALL.map(|t| {
packed::layout_in(&doc, t.name()).expect("the standard schema's declaration reads")
})
});
&all[self as usize]
}
}
fn schema() -> Value {
let level = json!({"name": "level", "type": "enum",
"values": ["unknown", "ok", "degraded", "failed"]});
let word = |name: &str| {
json!({"name": name, "type": "int", "minimum": 0, "maximum": Word::MAX,
"reserved": [Word::OUT_OF_RANGE_NAME]})
};
let time = |name: &str| json!({"name": name, "type": "time", "optional": true});
json!({"types": {
"Status": {"fields": [level, word("reason"), time("since"), packed::MARKER]},
"Check": {"fields": [level, word("detail"), time("at"), packed::MARKER]},
"Fault": {"fields": [
word("code"),
level,
{"name": "argument", "type": "int", "minimum": 0, "maximum": Argument::MAX,
"reserved": [Argument::NOT_AVAILABLE_NAME]},
time("at"),
packed::MARKER,
]},
}})
}
pub const UNKNOWN: &str = "unknown";
fn level_json(l: Option<Level>) -> Value {
json!(l.map_or(UNKNOWN, Level::as_str))
}
fn level_of_json(v: &Value) -> Option<Option<Level>> {
Some(match v.as_str()? {
UNKNOWN => None,
"ok" => Some(Level::Ok),
"degraded" => Some(Level::Degraded),
"failed" => Some(Level::Failed),
_ => return None,
})
}
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()
}
#[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()
}
#[must_use]
pub fn level_read(record: Result<Option<Level>, ReadRefusal>) -> Read {
match record {
Ok(Some(l)) => Read::Level(l),
Ok(None) => Read::Unspecified,
Err(_) => Read::Undecodable,
}
}
pub trait Packed: Sized {
const TYPE: RecordType;
fn to_json(&self) -> Value;
fn of_json(v: &Value) -> Option<Self>;
#[must_use]
fn tag() -> u8 {
Self::TYPE.tag()
}
fn write(&self, epoch: i64) -> Result<Record, WriteRefusal> {
Self::TYPE.layout().write(&self.to_json(), Some(epoch))
}
fn put(&self, stamp: Stamp, epoch: i64) -> Result<Vec<u8>, WriteRefusal> {
let record = self.write(epoch)?;
let tag = Tag::new(Self::tag()).expect("a tag of four bits");
Ok(Envelope::mutation(tag, stamp, &record.bytes).write())
}
fn read(tag: u8, bytes: &[u8], epoch: i64) -> Result<Self, ReadRefusal> {
let value = Self::TYPE.layout().read(tag, bytes, Some(epoch))?;
Self::of_json(&value).ok_or(ReadRefusal::Code)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Status {
pub level: Option<Level>,
pub reason: Word,
pub since: Option<i64>,
}
impl Status {
#[must_use]
pub fn starting(since: Option<i64>) -> Status {
Status {
level: None,
reason: write_word(Kind::Reason, Some(STARTING), None),
since,
}
}
}
impl Packed for Status {
const TYPE: RecordType = RecordType::Status;
fn to_json(&self) -> Value {
let mut m = Map::new();
m.insert("level".into(), level_json(self.level));
m.insert("reason".into(), self.reason.to_json());
if let Some(t) = self.since {
m.insert("since".into(), time_json(t));
}
Value::Object(m)
}
fn of_json(v: &Value) -> Option<Self> {
Some(Status {
level: level_of_json(v.get("level")?)?,
reason: Word::of_json(v.get("reason")?)?,
since: match v.get("since") {
None => None,
Some(t) => Some(time_of_json(t)?),
},
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Check {
pub level: Option<Level>,
pub detail: Word,
pub at: Option<i64>,
}
impl Packed for Check {
const TYPE: RecordType = RecordType::Check;
fn to_json(&self) -> Value {
let mut m = Map::new();
m.insert("level".into(), level_json(self.level));
m.insert("detail".into(), self.detail.to_json());
if let Some(t) = self.at {
m.insert("at".into(), time_json(t));
}
Value::Object(m)
}
fn of_json(v: &Value) -> Option<Self> {
Some(Check {
level: level_of_json(v.get("level")?)?,
detail: Word::of_json(v.get("detail")?)?,
at: match v.get("at") {
None => None,
Some(t) => Some(time_of_json(t)?),
},
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Argument {
Number(u16),
NotAvailable,
}
impl Argument {
pub const MAX: u16 = 65_534;
pub const NOT_AVAILABLE_NAME: &'static str = "not_available";
#[must_use]
pub const fn new(n: u16) -> Option<Argument> {
if n <= Argument::MAX {
Some(Argument::Number(n))
} else {
None
}
}
#[must_use]
pub fn clock_ahead(offset: Option<Duration>) -> Argument {
let Some(offset) = offset else {
return Argument::NotAvailable;
};
let up = offset
.as_secs()
.saturating_add(u64::from(offset.subsec_nanos() > 0));
Argument::Number(u16::try_from(up).map_or(Argument::MAX, |s| s.min(Argument::MAX)))
}
#[must_use]
pub fn to_json(self) -> Value {
match self {
Argument::Number(n) => json!(n),
Argument::NotAvailable => json!(Argument::NOT_AVAILABLE_NAME),
}
}
#[must_use]
pub fn of_json(v: &Value) -> Option<Argument> {
match v {
Value::String(s) if s == Argument::NOT_AVAILABLE_NAME => Some(Argument::NotAvailable),
v => Argument::new(u16::try_from(v.as_u64()?).ok()?),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Fault {
pub code: Word,
pub level: Option<Level>,
pub argument: Argument,
pub at: Option<i64>,
}
impl Fault {
#[must_use]
pub fn clock_ahead(offset: Option<Duration>, at: Option<i64>) -> Fault {
Fault {
code: write_word(Kind::Code, Some(super::CLOCK_AHEAD), None),
level: Some(Level::Failed),
argument: Argument::clock_ahead(offset),
at,
}
}
#[must_use]
pub fn is_clock_ahead(&self) -> bool {
read_word(Kind::Code, self.code, None) == Named::Profile(super::CLOCK_AHEAD)
}
}
impl Packed for Fault {
const TYPE: RecordType = RecordType::Fault;
fn to_json(&self) -> Value {
let mut m = Map::new();
m.insert("code".into(), self.code.to_json());
m.insert("level".into(), level_json(self.level));
m.insert("argument".into(), self.argument.to_json());
if let Some(t) = self.at {
m.insert("at".into(), time_json(t));
}
Value::Object(m)
}
fn of_json(v: &Value) -> Option<Self> {
Some(Fault {
code: Word::of_json(v.get("code")?)?,
level: level_of_json(v.get("level")?)?,
argument: Argument::of_json(v.get("argument")?)?,
at: match v.get("at") {
None => None,
Some(t) => Some(time_of_json(t)?),
},
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Collection {
Status,
Checks,
}
impl Collection {
#[must_use]
pub const fn coll(self) -> u32 {
match self {
Collection::Status => STATUS_COLL,
Collection::Checks => CHECKS_COLL,
}
}
#[must_use]
pub const fn suffix(self) -> &'static str {
match self {
Collection::Status => "health.v2/state/status",
Collection::Checks => "health.v2/state/checks",
}
}
#[must_use]
pub fn of(key: &str, coll: u32) -> Option<Collection> {
[Collection::Status, Collection::Checks]
.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 stamp: Stamp,
pub confirmation: Confirmation,
pub confirmed_at: Option<collection::Time>,
pub record: Result<R, ReadRefusal>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StatusEntry {
None,
Tombstone(Stamp),
Live(Entry<Status>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StatusSnapshot {
pub heard: Heard,
pub entry: StatusEntry,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChecksSnapshot {
pub heard: Heard,
pub live: Vec<Entry<Check>>,
pub retired: Vec<(String, Stamp)>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Reading {
pub status: Option<StatusSnapshot>,
pub checks: Option<ChecksSnapshot>,
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 entry_of<R: Packed>(e: &collection::Entry, page: &Page, epoch: i64) -> Entry<R> {
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(),
stamp: stamp_of(e.run, e.seq, page.run),
confirmation: e.confirmation,
confirmed_at,
record: R::read(page.tag.get(), &e.record, epoch),
}
}
impl Reading {
#[must_use]
pub fn of<'a>(replies: impl IntoIterator<Item = (&'a str, &'a [u8])>, epoch: i64) -> Reading {
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 header = |p: &Pages| Heard {
complete: p.heard.complete(),
tag: p.heard.tag,
run: p.heard.run,
asof: p.heard.asof,
time: p.heard.time,
};
let [status, checks] = held;
let status = status.map(|p| {
let live = p.pages.iter().find_map(|page| {
page.live
.iter()
.find(|e| e.id.is_empty())
.map(|e| (e, page))
});
let tomb = p
.pages
.iter()
.find_map(|page| page.tombs.iter().find(|t| t.id.is_empty()));
let entry = match (live, tomb) {
(Some((e, page)), _) => StatusEntry::Live(entry_of(e, page, epoch)),
(None, Some(t)) => StatusEntry::Tombstone(stamp_of(t.run, t.seq, p.heard.run)),
(None, None) => StatusEntry::None,
};
StatusSnapshot {
heard: header(&p),
entry,
}
});
let checks = checks.map(|p| ChecksSnapshot {
heard: header(&p),
live: p
.pages
.iter()
.flat_map(|page| page.live.iter().map(move |e| entry_of(e, page, epoch)))
.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(),
});
Reading {
status,
checks,
mixed,
}
}
#[must_use]
pub fn is_one_instant(&self) -> bool {
let (Some(s), Some(c)) = (&self.status, &self.checks) else {
return false;
};
if self.mixed
|| !s.heard.complete
|| !c.heard.complete
|| (s.heard.run, s.heard.asof) != (c.heard.run, c.heard.asof)
{
return false;
}
let (run, asof) = (s.heard.run, s.heard.asof);
let within = |stamp: &Stamp| stamp.run != run || stamp.seq.get() <= asof.get();
let status = match &s.entry {
StatusEntry::None => true,
StatusEntry::Tombstone(stamp) => within(stamp),
StatusEntry::Live(e) => within(&e.stamp),
};
status
&& c.live.iter().all(|e| within(&e.stamp))
&& c.retired.iter().all(|(_, stamp)| within(stamp))
}
#[must_use]
pub fn status_level(&self) -> Option<Read> {
match &self.status.as_ref()?.entry {
StatusEntry::Live(e) => Some(level_read(e.record.map(|s| s.level))),
StatusEntry::None | StatusEntry::Tombstone(_) => None,
}
}
#[must_use]
pub fn check_levels(&self) -> Option<Vec<Read>> {
let c = self.checks.as_ref().filter(|c| c.heard.complete)?;
Some(
c.live
.iter()
.map(|e| level_read(e.record.map(|k| k.level)))
.collect(),
)
}
#[must_use]
pub fn status_better_than_a_check(&self) -> Option<bool> {
if !self.is_one_instant() {
return None;
}
let status = self.status_level()?.level()?;
Some(!super::consistent(status, &self.check_levels()?))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ClockHeard {
Heartbeat(heartbeat::Time),
HeartbeatUnread,
StatusPut,
StatusDeleted,
ClockAhead,
Fault,
}
#[must_use]
pub fn clock_of(presence: Presence, last_read: Option<heartbeat::Time>) -> Clock {
let c = |answer, reason| Clock { answer, reason };
match presence {
Presence::Absent => return c(Answer::NotAsked, ClockReason::Absent),
Presence::Present(Listing::NotListed) => {
return c(Answer::NotAsked, ClockReason::NotListed);
}
_ => {}
}
match last_read {
Some(heartbeat::Time::Ahead) => c(Answer::Yes, ClockReason::Ahead),
Some(heartbeat::Time::At { .. }) => c(Answer::No, ClockReason::Confirmed),
Some(heartbeat::Time::Unknown) => c(Answer::Unobservable, ClockReason::TimeUnknown),
None => c(Answer::Unobservable, ClockReason::NothingHeard),
}
}
#[must_use]
pub fn clock_ahead(presence: Presence, heard: &[ClockHeard]) -> Clock {
let last = heard.iter().rev().find_map(|h| match h {
ClockHeard::Heartbeat(t) => Some(*t),
_ => None,
});
clock_of(presence, last)
}
#[cfg(test)]
mod tests {
use super::*;
fn table(names: &[&str]) -> Vec<String> {
names.iter().map(|n| (*n).to_owned()).collect()
}
#[test]
fn the_schemas_layouts_are_six_six_and_eight_bytes() {
for (t, tag, min, max) in [
(RecordType::Status, 3, 10, 42),
(RecordType::Check, 3, 10, 42),
(RecordType::Fault, 11, 26, 58),
] {
let l = t.layout();
assert_eq!(
(l.tag(), l.min_bits(), l.max_bits()),
(tag, min, max),
"{t:?}"
);
assert_eq!(t.tag(), tag);
}
assert_eq!(
RecordType::Status.layout().form(),
RecordType::Check.layout().form(),
"one layout, so one tag: the key says which"
);
}
#[test]
fn a_status_writes_reads_and_puts_as_the_text_says() {
let epoch = 1_767_225_600;
let s = Status {
level: Some(Level::Ok),
reason: write_word(Kind::Reason, Some("serving"), None),
since: Some(1_794_062_759),
};
let r = s.write(epoch).unwrap();
assert_eq!(r.bytes, [0x42, 0x80, 0xcc, 0xc0, 0x53, 0x80]);
assert_eq!(Status::read(3, &r.bytes, epoch), Ok(s));
let stamp = Stamp {
run: Run::U16(3),
seq: Seq::new(5).unwrap(),
};
let put = s.put(stamp, epoch).unwrap();
assert_eq!(put[0], 0x03, "form 0, a 16-bit run, tag 3");
assert_eq!(put.len(), 12);
let start = Status::starting(time_at(0, epoch));
assert_eq!(start.since, None);
assert_eq!(start.write(epoch).unwrap().bytes, [0x01, 0x00]);
let before = Status {
since: Some(epoch - 1),
..s
};
assert_eq!(before.write(epoch).unwrap_err(), WriteRefusal::Range);
assert_eq!(time_at(1_794_062_759_123, epoch), Some(1_794_062_759));
assert_eq!(time_at(i128::from(epoch) * 1000 - 1, epoch), None);
}
#[test]
fn a_refused_record_and_unknown_are_never_ok() {
let epoch = 0;
let ok = [0x42, 0x80, 0xcc, 0xc0, 0x53, 0x80];
let level =
|tag, bytes: &[u8]| level_read(Status::read(tag, bytes, epoch).map(|s| s.level));
assert_eq!(level(3, &ok), Read::Level(Level::Ok));
let mut pad = ok;
pad[5] |= 1;
assert_eq!(Status::read(3, &pad, epoch), Err(ReadRefusal::Pad));
assert_eq!(
level(3, &pad),
Read::Undecodable,
"never the ok its bits read"
);
assert_eq!(level(11, &ok), Read::Undecodable, "a fault's tag");
assert_eq!(level(3, &ok[..5]), Read::Undecodable);
assert_eq!(level(3, &[0x01, 0x00]), Read::Unspecified, "unknown");
assert_eq!(Read::Unspecified.level(), None);
}
#[test]
fn a_clock_ahead_fault_carries_its_offset_rounded_up_and_capped() {
let a = |ms| Argument::clock_ahead(Some(Duration::from_millis(ms)));
assert_eq!(a(2000), Argument::Number(2));
assert_eq!(a(2001), Argument::Number(3));
assert_eq!(a(1), Argument::Number(1));
assert_eq!(a(65_534_001), Argument::Number(65_534));
assert_eq!(Argument::clock_ahead(None), Argument::NotAvailable);
assert_eq!(Argument::new(65_535), None);
let f = Fault::clock_ahead(Some(Duration::from_secs(2)), Some(1_794_062_759));
assert!(f.is_clock_ahead());
assert_eq!(
f.write(1_767_225_600).unwrap().bytes,
[0x07, 0x00, 0x02, 0x80, 0xcc, 0xc0, 0x53, 0x80]
);
assert_eq!(Fault::tag(), 11);
}
#[test]
fn a_word_is_the_profiles_number_then_the_instances_own_then_out_of_range() {
let own = table(&["starting", "tc_netns_gone"]);
let w = |word| write_word(Kind::Reason, word, Some(&own));
assert_eq!(w(None), Word::NONE);
assert_eq!(w(Some("starting")).code(), 1, "the profile's number");
assert_eq!(w(Some("tc_netns_gone")).code(), 33);
assert_eq!(w(Some("timeout")), Word::OUT_OF_RANGE, "a detail's name");
assert_eq!(
write_word(Kind::Reason, Some("tc_netns_gone"), None),
Word::OUT_OF_RANGE
);
let r = |n| read_word(Kind::Reason, Word::new(n).unwrap(), Some(&own));
assert_eq!(r(0), Named::None);
assert_eq!(r(8), Named::Profile("misconfigured"));
assert_eq!(r(9), Named::Number(9), "a later text's");
assert_eq!(r(33), Named::Service("tc_netns_gone"));
assert_eq!(r(34), Named::Number(34), "a later revision's");
assert_eq!(
read_word(Kind::Reason, Word::OUT_OF_RANGE, Some(&own)),
Named::OutOfRange
);
assert_eq!(Word::new(63), None);
for kind in Kind::ALL {
assert!(kind.profile().len() <= 31, "{kind:?}");
for (i, name) in kind.profile().iter().enumerate() {
assert!(is_name(name));
assert_eq!(
usize::from(write_word(kind, Some(name), None).code()),
i + 1
);
}
}
}
#[test]
fn an_instance_has_the_one_table_its_named_revisions_hold() {
let a = table(&["tc_a", "tc_b"]);
let b = table(&["tc_a"]);
assert_eq!(instance_table([None, None]), Instance::None);
assert_eq!(
instance_table([None, Some(&a[..]), Some(&a[..])]),
Instance::Table(a.clone())
);
assert_eq!(
instance_table([Some(&a[..]), Some(&b[..])]),
Instance::Differ
);
assert_eq!(Instance::Differ.table(), None, "no word from 32 to 62");
assert_eq!(growth(&b, &a), Growth::Appended);
assert_eq!(growth(&a, &b), Growth::Moved);
}
#[test]
fn the_last_read_heartbeat_answers_the_clock_question_and_no_fault_does() {
use heartbeat::Time;
let p = Presence::Present(Listing::Listed { token: true });
let at = Time::At { secs: 1, ms: 0 };
let a = |heard: &[ClockHeard]| {
let c = clock_ahead(p, heard);
(c.answer, c.reason)
};
assert_eq!(
a(&[ClockHeard::Heartbeat(Time::Ahead)]),
(Answer::Yes, ClockReason::Ahead)
);
assert_eq!(
a(&[ClockHeard::ClockAhead]),
(Answer::Unobservable, ClockReason::NothingHeard),
"a fault is an occurrence, and answers nothing"
);
assert_eq!(
a(&[ClockHeard::Heartbeat(at), ClockHeard::ClockAhead]),
(Answer::No, ClockReason::Confirmed)
);
assert_eq!(
a(&[
ClockHeard::Heartbeat(Time::Ahead),
ClockHeard::Heartbeat(Time::Unknown)
]),
(Answer::Unobservable, ClockReason::TimeUnknown)
);
assert_eq!(
a(&[
ClockHeard::Heartbeat(Time::Ahead),
ClockHeard::HeartbeatUnread,
ClockHeard::StatusPut
]),
(Answer::Yes, ClockReason::Ahead)
);
assert_eq!(
clock_of(Presence::Absent, Some(Time::Ahead)).answer,
Answer::NotAsked
);
assert_eq!(
clock_of(Presence::Incomplete, Some(Time::Ahead)).answer,
Answer::Yes,
"a heartbeat read on its key is its owner's word"
);
}
}