use std::fmt;
use std::time::Duration;
use crate::freshness::{self, Horizon, Observation};
pub const PROFILE: &str = "health.v1";
pub const IFACE: &str = "health.v1";
pub const STATUS: &str = "status";
pub const CHECKS: &str = "checks/{check}";
pub const FAULTS: &str = "faults";
pub const STATUS_TTL: Duration = Duration::from_secs(60);
pub const STATUS_REFRESH: Duration = Duration::from_secs(30);
pub const MAX_CHECKS: u64 = 64;
pub const CLOCK_AHEAD: &str = "clock_ahead";
pub const CODES: &[&str] = &[CLOCK_AHEAD];
#[must_use]
pub fn status_horizon() -> Horizon {
Horizon::Within(STATUS_TTL)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Level {
Ok,
Degraded,
Failed,
}
impl Level {
#[must_use]
pub fn wire(self) -> i32 {
match self {
Self::Ok => 1,
Self::Degraded => 2,
Self::Failed => 3,
}
}
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Ok => "ok",
Self::Degraded => "degraded",
Self::Failed => "failed",
}
}
}
impl fmt::Display for Level {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Ok => "OK",
Self::Degraded => "DEGRADED",
Self::Failed => "FAILED",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Read {
Level(Level),
Unspecified,
Unlisted(i32),
Undecodable,
}
impl Read {
#[must_use]
pub fn from_wire(n: i32) -> Self {
match n {
0 => Self::Unspecified,
1 => Self::Level(Level::Ok),
2 => Self::Level(Level::Degraded),
3 => Self::Level(Level::Failed),
n => Self::Unlisted(n),
}
}
#[must_use]
pub fn level(self) -> Option<Level> {
match self {
Self::Level(l) => Some(l),
_ => None,
}
}
}
#[must_use]
pub fn worst_check(checks: &[Read]) -> Option<(usize, Level)> {
checks
.iter()
.enumerate()
.filter_map(|(i, r)| r.level().map(|l| (i, l)))
.fold(None, |best, (i, l)| match best {
Some((_, b)) if b >= l => best,
_ => Some((i, l)),
})
}
#[must_use]
pub fn consistent(status: Level, checks: &[Read]) -> bool {
worst_check(checks).is_none_or(|(_, w)| w <= status)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Listing {
Listed { token: bool },
NotListed,
Unread,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Presence {
Present(Listing),
Absent,
Incomplete,
AcrossFace { status_crosses: bool },
}
#[derive(Debug, Clone, Copy)]
pub struct Reading<'a> {
pub presence: Presence,
pub status: &'a [Observation],
pub level: Option<Read>,
pub checks: Option<&'a [Read]>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Verdict {
Healthy,
Unhealthy,
Stale,
Unobservable,
NotAsked,
}
impl Verdict {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Healthy => "healthy",
Self::Unhealthy => "unhealthy",
Self::Stale => "stale",
Self::Unobservable => "unobservable",
Self::NotAsked => "not_asked",
}
}
#[must_use]
pub fn is_finding(self) -> bool {
matches!(self, Self::Unhealthy | Self::Stale)
}
}
impl fmt::Display for Verdict {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Reason {
Ok,
Degraded,
Failed,
Inconsistent,
Check,
UnknownLevel,
Undecodable,
Deleted,
PresenceIncomplete,
NoDescriptor,
FaceClosed,
NothingCrossed,
Absent,
NotListed,
LastKnown,
ChecksUnread,
Freshness(freshness::Reason),
}
impl Reason {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Ok => "ok",
Self::Degraded => "degraded",
Self::Failed => "failed",
Self::Inconsistent => "inconsistent",
Self::Check => "check",
Self::UnknownLevel => "unknown_level",
Self::Undecodable => "undecodable",
Self::Deleted => "deleted",
Self::PresenceIncomplete => "presence_incomplete",
Self::NoDescriptor => "no_descriptor",
Self::FaceClosed => "face_closed",
Self::NothingCrossed => "nothing_crossed",
Self::Absent => "absent",
Self::NotListed => "not_listed",
Self::LastKnown => "last_known",
Self::ChecksUnread => "checks_unread",
Self::Freshness(r) => r.as_str(),
}
}
#[must_use]
pub fn says(self) -> &'static str {
match self {
Self::Ok => "its status is OK and confirmed, and no check is worse",
Self::Degraded => "its status is DEGRADED",
Self::Failed => "its status is FAILED",
Self::Inconsistent => "a check is worse than its status, which health.v1 §2.2 forbids",
Self::Check => "its status's level is unknown, and a check is DEGRADED or FAILED",
Self::UnknownLevel => "its status's level is unknown",
Self::Undecodable => "its status does not decode",
Self::Deleted => "its owner deleted its status",
Self::PresenceIncomplete => {
"its token was not seen, and the presence read may be incomplete or refused"
}
Self::NoDescriptor => "its descriptor could not be read",
Self::FaceClosed => "the constrained face does not let its status cross",
Self::NothingCrossed => {
"nothing of its status has crossed the constrained face, so none is known to exist"
}
Self::Absent => "it is absent: presence's word, not a level",
Self::NotListed => "its descriptor does not list health.v1",
Self::LastKnown => "only an archive's last-known status was read, never current",
Self::ChecksUnread => "its checks were not read",
Self::Freshness(r) => r.says(),
}
}
}
impl fmt::Display for Reason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Judged {
pub verdict: Verdict,
pub reason: Reason,
pub level: Option<Level>,
}
impl Judged {
const fn new(verdict: Verdict, reason: Reason, level: Option<Level>) -> Self {
Self {
verdict,
reason,
level,
}
}
const fn unobservable(reason: Reason) -> Self {
Self::new(Verdict::Unobservable, reason, None)
}
const fn not_asked(reason: Reason) -> Self {
Self::new(Verdict::NotAsked, reason, None)
}
const fn unhealthy(reason: Reason, level: Level) -> Self {
Self::new(Verdict::Unhealthy, reason, Some(level))
}
}
#[must_use]
pub fn judge(r: &Reading<'_>) -> Judged {
use Reason as R;
match r.presence {
Presence::Absent => return Judged::not_asked(R::Absent),
Presence::Incomplete => return Judged::unobservable(R::PresenceIncomplete),
Presence::AcrossFace {
status_crosses: false,
} => return Judged::unobservable(R::FaceClosed),
Presence::Present(Listing::NotListed) => return Judged::not_asked(R::NotListed),
Presence::Present(Listing::Unread) => return Judged::unobservable(R::NoDescriptor),
Presence::AcrossFace {
status_crosses: true,
}
| Presence::Present(Listing::Listed { .. }) => {}
}
let f = freshness::judge_all(&status_horizon(), r.status);
match f.verdict {
freshness::Verdict::Fresh => {}
freshness::Verdict::Stale
if f.reason == freshness::Reason::NoDelivery
&& matches!(r.presence, Presence::AcrossFace { .. }) =>
{
return Judged::unobservable(R::NothingCrossed);
}
freshness::Verdict::Stale => {
return Judged::new(Verdict::Stale, R::Freshness(f.reason), None);
}
freshness::Verdict::Unobservable => return Judged::unobservable(R::Freshness(f.reason)),
freshness::Verdict::NotAsked => {
return match f.reason {
freshness::Reason::Deleted => Judged::unobservable(R::Deleted),
freshness::Reason::LastKnown => Judged::not_asked(R::LastKnown),
other => Judged::not_asked(R::Freshness(other)),
};
}
}
let worst = worst_check(r.checks.unwrap_or(&[])).map(|(_, l)| l);
match r.level.and_then(Read::level) {
Some(status) => match worst {
Some(w) if w > status => Judged::unhealthy(R::Inconsistent, w),
_ => match status {
Level::Ok => Judged::new(Verdict::Healthy, R::Ok, Some(Level::Ok)),
Level::Degraded => Judged::unhealthy(R::Degraded, Level::Degraded),
Level::Failed => Judged::unhealthy(R::Failed, Level::Failed),
},
},
None => match worst {
Some(w) if w > Level::Ok => Judged::unhealthy(R::Check, w),
_ => Judged::unobservable(match r.level {
Some(Read::Unspecified | Read::Unlisted(_)) => R::UnknownLevel,
_ => R::Undecodable,
}),
},
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Rollup {
pub worst: Option<Level>,
pub healthy: usize,
pub unhealthy: usize,
pub stale: usize,
pub unobservable: usize,
pub not_asked: usize,
}
#[must_use]
pub fn rollup(judged: impl IntoIterator<Item = Judged>) -> Rollup {
let mut r = Rollup::default();
for j in judged {
match j.verdict {
Verdict::Healthy => r.healthy += 1,
Verdict::Unhealthy => r.unhealthy += 1,
Verdict::Stale => r.stale += 1,
Verdict::Unobservable => r.unobservable += 1,
Verdict::NotAsked => r.not_asked += 1,
}
if matches!(j.verdict, Verdict::Healthy | Verdict::Unhealthy) {
r.worst = r.worst.max(j.level);
}
}
r
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Answer {
Yes,
No,
Unobservable,
NotAsked,
}
impl Answer {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Yes => "yes",
Self::No => "no",
Self::Unobservable => "unobservable",
Self::NotAsked => "not_asked",
}
}
}
impl fmt::Display for Answer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Agreement {
pub answer: Answer,
pub reason: Reason,
}
#[must_use]
pub fn agrees(judged: Judged, checks_read: bool) -> Agreement {
let a = |answer, reason| Agreement { answer, reason };
match (judged.verdict, judged.reason) {
(Verdict::NotAsked, r) => a(Answer::NotAsked, r),
(_, Reason::Inconsistent) => a(Answer::No, Reason::Inconsistent),
(
Verdict::Healthy | Verdict::Unhealthy,
r @ (Reason::Ok | Reason::Degraded | Reason::Failed),
) => {
if checks_read {
a(Answer::Yes, r)
} else {
a(Answer::Unobservable, Reason::ChecksUnread)
}
}
(Verdict::Unhealthy, Reason::Check) => a(Answer::Unobservable, Reason::UnknownLevel),
(_, r) => a(Answer::Unobservable, r),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Heard {
Heartbeat,
HeartbeatHeld,
StatusPut,
StatusDeleted,
ClockAhead,
Fault,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ClockReason {
ClockAhead,
Confirmed,
TimeUnknown,
NothingHeard,
Absent,
NotListed,
}
impl ClockReason {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::ClockAhead => "clock_ahead",
Self::Confirmed => "confirmed",
Self::TimeUnknown => "time_unknown",
Self::NothingHeard => "nothing_heard",
Self::Absent => "absent",
Self::NotListed => "not_listed",
}
}
#[must_use]
pub fn says(self) -> &'static str {
match self {
Self::ClockAhead => {
"a clock_ahead fault was heard, and no heartbeat with its time known since"
}
Self::Confirmed => {
"its last heartbeat had its time known, after its last clock_ahead fault or with \
none heard"
}
Self::TimeUnknown => {
"its last heartbeat's time was unknown, and no clock_ahead fault was heard since \
one with its time known"
}
Self::NothingHeard => "no clock_ahead fault and no heartbeat was heard in the window",
Self::Absent => "it is absent: presence's word",
Self::NotListed => "its descriptor does not list health.v1",
}
}
}
impl fmt::Display for ClockReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Clock {
pub answer: Answer,
pub reason: ClockReason,
}
#[must_use]
pub fn clock_ahead(presence: Presence, heard: &[Heard]) -> 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);
}
_ => {}
}
let last = |h: Heard| heard.iter().rposition(|x| *x == h);
let fault = last(Heard::ClockAhead);
let known = last(Heard::Heartbeat);
let unknown = last(Heard::HeartbeatHeld);
match (fault, known, unknown) {
(Some(f), k, _) if k.is_none_or(|k| k < f) => c(Answer::Yes, ClockReason::ClockAhead),
(_, Some(k), u) if u.is_none_or(|u| u < k) => c(Answer::No, ClockReason::Confirmed),
(_, _, Some(_)) => c(Answer::Unobservable, ClockReason::TimeUnknown),
_ => c(Answer::Unobservable, ClockReason::NothingHeard),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Code<'a> {
Profile(&'static str),
Application(&'a str),
Malformed(&'a str),
}
impl Code<'_> {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::Profile(_) => "profile",
Self::Application(_) => "application",
Self::Malformed(_) => "malformed",
}
}
}
#[must_use]
pub fn code(s: &str) -> Code<'_> {
let mut bytes = s.bytes();
let well_formed = bytes.next().is_some_and(|b| b.is_ascii_lowercase())
&& bytes.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_');
if !well_formed {
return Code::Malformed(s);
}
match CODES.iter().find(|c| **c == s) {
Some(c) => Code::Profile(c),
None => Code::Application(s),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::freshness::Last;
fn fresh() -> [Observation; 1] {
[Observation::Subscribed {
last: Some(Last::Put(Duration::from_secs(10))),
listened: Duration::from_secs(120),
complete: true,
}]
}
fn present() -> Presence {
Presence::Present(Listing::Listed { token: false })
}
#[test]
fn the_levels_are_ordered_and_unspecified_is_none_of_them() {
assert!(Level::Ok < Level::Degraded && Level::Degraded < Level::Failed);
for l in [Level::Ok, Level::Degraded, Level::Failed] {
assert_eq!(Read::from_wire(l.wire()), Read::Level(l));
}
assert_eq!(Read::from_wire(0), Read::Unspecified);
assert_eq!(Read::from_wire(4), Read::Unlisted(4));
assert_eq!(Read::Unspecified.level(), None);
}
#[test]
fn the_worst_check_is_the_first_at_the_worst_known_level() {
let checks = [
Read::Level(Level::Degraded),
Read::Unlisted(9),
Read::Level(Level::Failed),
Read::Level(Level::Failed),
];
assert_eq!(worst_check(&checks), Some((2, Level::Failed)));
assert_eq!(worst_check(&[Read::Unspecified]), None);
assert!(consistent(Level::Failed, &checks));
assert!(!consistent(Level::Degraded, &checks));
assert!(consistent(Level::Ok, &[]));
}
#[test]
fn a_fresh_status_vouches_for_its_checks_and_a_stale_one_does_not() {
let o = fresh();
let checks = [Read::Level(Level::Failed)];
let mut r = Reading {
presence: present(),
status: &o,
level: Some(Read::Level(Level::Ok)),
checks: Some(&checks),
};
assert_eq!(
judge(&r),
Judged::unhealthy(Reason::Inconsistent, Level::Failed)
);
let stale = [Observation::Subscribed {
last: Some(Last::Put(Duration::from_secs(61))),
listened: Duration::from_secs(120),
complete: true,
}];
r.status = &stale;
assert_eq!(judge(&r).verdict, Verdict::Stale);
}
#[test]
fn a_rollup_never_folds_stale_into_a_level() {
let stale = Judged::new(
Verdict::Stale,
Reason::Freshness(freshness::Reason::BeyondHorizon),
None,
);
let r = rollup([
stale,
Judged::new(Verdict::Healthy, Reason::Ok, Some(Level::Ok)),
]);
assert_eq!(r.worst, Some(Level::Ok));
assert_eq!((r.healthy, r.stale), (1, 1));
assert_eq!(rollup([stale]).worst, None);
}
#[test]
fn the_status_agrees_with_its_checks_only_when_fresh_at_a_level_and_read() {
let j = |verdict, reason, level| Judged::new(verdict, reason, level);
let ok = j(Verdict::Healthy, Reason::Ok, Some(Level::Ok));
assert_eq!(agrees(ok, true).answer, Answer::Yes);
assert_eq!(
agrees(ok, false),
Agreement {
answer: Answer::Unobservable,
reason: Reason::ChecksUnread
}
);
let liar = Judged::unhealthy(Reason::Inconsistent, Level::Failed);
assert_eq!(agrees(liar, true).answer, Answer::No);
let frank = Judged::unhealthy(Reason::Failed, Level::Failed);
assert_eq!(agrees(frank, true).answer, Answer::Yes, "worse is allowed");
let unknown = Judged::unhealthy(Reason::Check, Level::Failed);
assert_eq!(agrees(unknown, true).reason, Reason::UnknownLevel);
let stale = j(
Verdict::Stale,
Reason::Freshness(freshness::Reason::BeyondHorizon),
None,
);
assert_eq!(agrees(stale, true).answer, Answer::Unobservable);
let absent = Judged::not_asked(Reason::Absent);
assert_eq!(agrees(absent, true).answer, Answer::NotAsked);
}
#[test]
fn the_clock_is_ahead_on_a_fault_no_heartbeat_with_its_time_followed() {
use Heard::{ClockAhead, Fault, Heartbeat, HeartbeatHeld, StatusDeleted, StatusPut};
let p = present();
let a = |heard: &[Heard]| clock_ahead(p, heard).answer;
assert_eq!(a(&[ClockAhead]), Answer::Yes);
assert_eq!(a(&[Heartbeat, ClockAhead]), Answer::Yes);
assert_eq!(a(&[ClockAhead, Heartbeat]), Answer::No);
assert_eq!(a(&[ClockAhead, StatusDeleted]), Answer::Yes);
assert_eq!(
a(&[ClockAhead, StatusPut]),
Answer::Yes,
"the guard holds no put"
);
assert_eq!(a(&[ClockAhead, HeartbeatHeld]), Answer::Yes);
assert_eq!(a(&[Heartbeat]), Answer::No);
assert_eq!(a(&[StatusPut]), Answer::Unobservable);
assert_eq!(
clock_ahead(p, &[Heartbeat, HeartbeatHeld]).reason,
ClockReason::TimeUnknown,
"a time unknown since: no longer no, and no fault to say yes"
);
assert_eq!(a(&[ClockAhead, HeartbeatHeld, Heartbeat]), Answer::No);
assert_eq!(a(&[Fault]), Answer::Unobservable, "never from silence");
assert_eq!(a(&[]), Answer::Unobservable);
assert_eq!(
clock_ahead(Presence::Absent, &[ClockAhead]).answer,
Answer::NotAsked
);
}
#[test]
fn codes_are_lowercase_ascii_and_the_table_is_the_profiles() {
assert_eq!(code("clock_ahead"), Code::Profile(CLOCK_AHEAD));
assert_eq!(code("tc_netns_gone"), Code::Application("tc_netns_gone"));
assert_eq!(code(""), Code::Malformed(""));
assert_eq!(code("_x"), Code::Malformed("_x"));
assert_eq!(code("Clock_ahead").as_str(), "malformed");
}
}