Skip to main content

zenkey_model/
health.rs

1//! `health.v1`: how well a service serves
2//! (`spec/profiles/health/v1.md`, #721).
3//!
4//! The profile's session-free half: the levels and their order (§2.1,
5//! §2.6), the fault codes (§2.10), and the pure judgement of one reading of
6//! one service (§2.11), built on [`freshness::judge_all`] for the status,
7//! with a tool's roll-up of many (§2.2) and §5's other two questions.
8//!
9//! ```text
10//! Read::from_wire(n)  ─▶ Level(OK < DEGRADED < FAILED) │ Unspecified │ Unlisted(n) │ Undecodable
11//! judge(reading)      ─▶ healthy │ unhealthy │ stale │ unobservable │ not_asked, + reason, + level
12//! rollup(judged…)     ─▶ the worst established level, every verdict counted
13//! agrees(judged, read)─▶ §5 "does its status agree with its checks?": yes │ no │ unestablished
14//! clock_ahead(p, heard)─▶ §5 "is its clock ahead?": yes │ no │ unestablished
15//! code(s)             ─▶ profile │ application │ malformed
16//! ```
17//!
18//! There is no I/O and no clock here. A reader observes presence, the
19//! descriptor, the status (as [`freshness::Observation`]s, plus the level
20//! of the latest value) and the checks, and hands them over as values. The
21//! owner's puts, its heartbeats and its `clock_ahead` fault are the
22//! runtime's.
23//!
24//! **Two majors** (#986's Q1). [`v2`] is `health.v2`'s
25//! (`spec/profiles/health/v2.md`): packed records, words by table, and a
26//! clock question a heartbeat answers alone. It restates this text by
27//! reference, so what a reader concludes is one set for both:
28//!
29//! ```text
30//! Major::of(interfaces)  ─▶ the major a descriptor's reading is judged under: v2 where it lists both
31//! judge_status(…)        ─▶ §2.11's five steps from the status's freshness as judged, either major's
32//! rollup · agrees        ─▶ over verdicts and levels of either major
33//! ```
34//!
35//! A `health.v2` record's `unknown` is [`Read::Unspecified`], and one a
36//! reader refuses [`Read::Undecodable`] ([`v2::level_read`]): unknown is
37//! never `OK` under either. The clock question is each major's own
38//! ([`clock_ahead`], [`v2::clock_ahead`]).
39
40pub mod v2;
41
42use std::fmt;
43use std::time::Duration;
44
45use crate::freshness::{self, Horizon, Observation};
46
47/// The profile's name, as an annotation key's prefix carries it. Only
48/// `health.v2` publishes a vocabulary ([`v2::VOCABULARY`]).
49pub const NAME: &str = "health";
50
51/// The profile's id, which is also its standard contract's interface id.
52pub const PROFILE: &str = "health.v1";
53
54/// The standard contract's interface id (§3).
55pub const IFACE: &str = "health.v1";
56
57/// The status's template (§3): `state/status`.
58pub const STATUS: &str = "status";
59
60/// The checks' template (§3): `state/checks/{check}`.
61pub const CHECKS: &str = "checks/{check}";
62
63/// The faults' template (§3): `stream/faults`.
64pub const FAULTS: &str = "faults";
65
66/// The status's horizon, the contract's `freshness.ttl_s` (§2.4).
67pub const STATUS_TTL: Duration = Duration::from_secs(60);
68
69/// The owner's bound between two confirmations of its status, ttl/2
70/// (`freshness.v1` §2.4).
71pub const STATUS_REFRESH: Duration = Duration::from_secs(30);
72
73/// The contract's bound on an owner's checks (§2.3).
74pub const MAX_CHECKS: u64 = 64;
75
76/// The profile's code for a clock running ahead (§2.5, §2.10).
77pub const CLOCK_AHEAD: &str = "clock_ahead";
78
79/// The profile's table of fault codes (§2.10).
80pub const CODES: &[&str] = &[CLOCK_AHEAD];
81
82/// The status's horizon, as `freshness.v1` reads it.
83#[must_use]
84pub fn status_horizon() -> Horizon {
85    Horizon::Within(STATUS_TTL)
86}
87
88/// Which major of the profile a service's health is read under
89/// (`health.v2` §2.11's step 2, §2.12). The two are two interfaces: an
90/// instance implements one, and a reader reads either.
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
92pub enum Major {
93    /// `health.v1`: protobuf records with free text.
94    V1,
95    /// `health.v2`: packed records, their words numbers ([`v2`]).
96    V2,
97}
98
99impl Major {
100    /// The major's interface id, which is its standard contract's.
101    #[must_use]
102    pub const fn iface(self) -> &'static str {
103        match self {
104            Major::V1 => IFACE,
105            Major::V2 => v2::IFACE,
106        }
107    }
108
109    /// The major an interface id names: the deployment's word across a
110    /// constrained face, where no descriptor crosses (§2.8). `None` for
111    /// any other interface.
112    #[must_use]
113    pub fn named(iface: &str) -> Option<Major> {
114        [Major::V2, Major::V1]
115            .into_iter()
116            .find(|m| m.iface() == iface)
117    }
118
119    /// The major a descriptor is read by, from the interface ids its
120    /// `interfaces` holds: `health.v2` where it lists it, `health.v1`
121    /// where it lists that and not `health.v2`, and `None` where it lists
122    /// neither, which is not asked (`not_listed`). One that lists both
123    /// breaks `health.v2` §2.3, and is read as `health.v2`.
124    #[must_use]
125    pub fn of<'a>(interfaces: impl IntoIterator<Item = &'a str>) -> Option<Major> {
126        let mut found = None;
127        for iface in interfaces {
128            match Major::named(iface) {
129                Some(Major::V2) => return Some(Major::V2),
130                Some(Major::V1) => found = Some(Major::V1),
131                None => {}
132            }
133        }
134        found
135    }
136}
137
138/// A level (§2.1). The order is the declaration's: `Ok` < `Degraded` <
139/// `Failed`, a later level being worse. `UNSPECIFIED` is not one (§2.6).
140#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
141pub enum Level {
142    Ok,
143    Degraded,
144    Failed,
145}
146
147impl Level {
148    /// The enum's number on the wire (`health.v1.Level`).
149    #[must_use]
150    pub fn wire(self) -> i32 {
151        match self {
152            Self::Ok => 1,
153            Self::Degraded => 2,
154            Self::Failed => 3,
155        }
156    }
157
158    /// The fixture's token.
159    #[must_use]
160    pub fn as_str(self) -> &'static str {
161        match self {
162            Self::Ok => "ok",
163            Self::Degraded => "degraded",
164            Self::Failed => "failed",
165        }
166    }
167}
168
169impl fmt::Display for Level {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        f.write_str(match self {
172            Self::Ok => "OK",
173            Self::Degraded => "DEGRADED",
174            Self::Failed => "FAILED",
175        })
176    }
177}
178
179/// A level as a reader read it from a payload: a level, or unknown (§2.6).
180#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
181pub enum Read {
182    /// `OK`, `DEGRADED` or `FAILED`.
183    Level(Level),
184    /// `LEVEL_UNSPECIFIED`, 0: unknown, never `OK`. A `health.v2` record's
185    /// `unknown` is this (`health.v2` §0, §2.6).
186    Unspecified,
187    /// A number the enum does not list, which proto3 keeps (its enums are
188    /// open): unknown, never `OK`.
189    Unlisted(i32),
190    /// A payload that does not decode as the message: unknown. So is a
191    /// `health.v2` record its reader refuses (`health.v2` §2.6).
192    Undecodable,
193}
194
195impl Read {
196    /// The enum's number as decoded.
197    #[must_use]
198    pub fn from_wire(n: i32) -> Self {
199        match n {
200            0 => Self::Unspecified,
201            1 => Self::Level(Level::Ok),
202            2 => Self::Level(Level::Degraded),
203            3 => Self::Level(Level::Failed),
204            n => Self::Unlisted(n),
205        }
206    }
207
208    /// The level, when it is one.
209    #[must_use]
210    pub fn level(self) -> Option<Level> {
211        match self {
212            Self::Level(l) => Some(l),
213            _ => None,
214        }
215    }
216}
217
218/// The worst of the levels among `checks`, with the index of the first
219/// check at it; a check at an unknown level bounds nothing (§2.2).
220#[must_use]
221pub fn worst_check(checks: &[Read]) -> Option<(usize, Level)> {
222    checks
223        .iter()
224        .enumerate()
225        .filter_map(|(i, r)| r.level().map(|l| (i, l)))
226        .fold(None, |best, (i, l)| match best {
227            Some((_, b)) if b >= l => best,
228            _ => Some((i, l)),
229        })
230}
231
232/// §2.2: whether a status at `status` is no better than its worst current
233/// check. A status may be worse.
234#[must_use]
235pub fn consistent(status: Level, checks: &[Read]) -> bool {
236    worst_check(checks).is_none_or(|(_, w)| w <= status)
237}
238
239/// What the descriptor of a present service says (§2.7).
240#[derive(Debug, Clone, Copy, PartialEq, Eq)]
241pub enum Listing {
242    /// Its `interfaces` list `health.v1`, with its `"token"`: `false` for an
243    /// interface in the tokenless set. The token plays no part in a verdict.
244    Listed { token: bool },
245    /// Its `interfaces` do not list `health.v1`.
246    NotListed,
247    /// The descriptor could not be read.
248    Unread,
249}
250
251/// A service's presence, as the reader saw it (core §8.1, §8.5).
252#[derive(Debug, Clone, Copy, PartialEq, Eq)]
253pub enum Presence {
254    /// Its instance token was seen, with what its descriptor says.
255    Present(Listing),
256    /// A complete read held no instance token of it.
257    Absent,
258    /// Its token was not seen, in a read possibly incomplete or refused.
259    Incomplete,
260    /// Across a constrained face, where tokens and descriptors do not
261    /// cross, and the deployment's word says the service implements
262    /// `health.v1` (core R7): whether the face lets `state/status` cross.
263    AcrossFace { status_crosses: bool },
264}
265
266/// One reading of one service (§0, §2.11).
267#[derive(Debug, Clone, Copy)]
268pub struct Reading<'a> {
269    pub presence: Presence,
270    /// The observations of `state/status`, judged as `freshness.v1` judges
271    /// them, at [`STATUS_TTL`].
272    pub status: &'a [Observation],
273    /// The level of the latest status value read, or `None` when no value
274    /// was read.
275    pub level: Option<Read>,
276    /// The levels of the checks the owner answered, or `None` when the
277    /// checks were not read.
278    pub checks: Option<&'a [Read]>,
279}
280
281/// The answer to "is this service healthy?" (§5). Unhealthy and stale are
282/// findings.
283#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
284pub enum Verdict {
285    Healthy,
286    Unhealthy,
287    /// The status was not confirmed within its horizon: a finding of its
288    /// own, never a level (§2.4).
289    Stale,
290    /// The question was put, and the reading could not answer it.
291    Unobservable,
292    /// Nobody put the question, or its premise does not hold (the reason
293    /// says which).
294    NotAsked,
295}
296
297impl Verdict {
298    /// The fixture's token.
299    #[must_use]
300    pub fn as_str(self) -> &'static str {
301        match self {
302            Self::Healthy => "healthy",
303            Self::Unhealthy => "unhealthy",
304            Self::Stale => "stale",
305            Self::Unobservable => "unobservable",
306            Self::NotAsked => "not_asked",
307        }
308    }
309
310    /// Whether the verdict is a finding (§5's polarity).
311    #[must_use]
312    pub fn is_finding(self) -> bool {
313        matches!(self, Self::Unhealthy | Self::Stale)
314    }
315}
316
317impl fmt::Display for Verdict {
318    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
319        f.write_str(self.as_str())
320    }
321}
322
323/// Why a verdict is what it is: the fixture's reason class (§2.11).
324#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
325pub enum Reason {
326    /// Healthy: a fresh status at `OK`, no current check worse.
327    Ok,
328    /// Unhealthy: a fresh status at `DEGRADED`.
329    Degraded,
330    /// Unhealthy: a fresh status at `FAILED`.
331    Failed,
332    /// Unhealthy: a current check worse than the status, which breaks §2.2;
333    /// read at the check's level.
334    Inconsistent,
335    /// Unhealthy: the status's level unknown, and a current check
336    /// `DEGRADED` or `FAILED`.
337    Check,
338    /// Unobservable: the status's level is unknown (§2.6).
339    UnknownLevel,
340    /// Unobservable: the status's payload did not decode (§2.6).
341    Undecodable,
342    /// Unobservable: the owner deleted its status, which §2.3 forbids.
343    Deleted,
344    /// Unobservable: its token not seen, in a read possibly incomplete.
345    PresenceIncomplete,
346    /// Unobservable: the descriptor could not be read (§2.7).
347    NoDescriptor,
348    /// Unobservable: across a face that does not let the status cross
349    /// (§2.8).
350    FaceClosed,
351    /// Unobservable: across a face that lets the status cross, nothing of
352    /// it arrived, so no status is known to exist (§2.8, `freshness.v1`
353    /// §2.5).
354    NothingCrossed,
355    /// Not asked: absent, presence's word (§2.1).
356    Absent,
357    /// Not asked: the descriptor does not list `health.v1` (§2.7).
358    NotListed,
359    /// Not asked: only an archive's status was read, last-known (core S6).
360    LastKnown,
361    /// Unobservable, for §5's second question only ([`agrees`]): the checks
362    /// were not read, so whether one is worse than the status is not known.
363    ChecksUnread,
364    /// Stale or unobservable: the status's freshness, `freshness.v1`'s
365    /// reason.
366    Freshness(freshness::Reason),
367}
368
369impl Reason {
370    /// The fixture's token.
371    #[must_use]
372    pub fn as_str(self) -> &'static str {
373        match self {
374            Self::Ok => "ok",
375            Self::Degraded => "degraded",
376            Self::Failed => "failed",
377            Self::Inconsistent => "inconsistent",
378            Self::Check => "check",
379            Self::UnknownLevel => "unknown_level",
380            Self::Undecodable => "undecodable",
381            Self::Deleted => "deleted",
382            Self::PresenceIncomplete => "presence_incomplete",
383            Self::NoDescriptor => "no_descriptor",
384            Self::FaceClosed => "face_closed",
385            Self::NothingCrossed => "nothing_crossed",
386            Self::Absent => "absent",
387            Self::NotListed => "not_listed",
388            Self::LastKnown => "last_known",
389            Self::ChecksUnread => "checks_unread",
390            Self::Freshness(r) => r.as_str(),
391        }
392    }
393
394    /// The reason in words, for a tool's message.
395    #[must_use]
396    pub fn says(self) -> &'static str {
397        match self {
398            Self::Ok => "its status is OK and confirmed, and no check is worse",
399            Self::Degraded => "its status is DEGRADED",
400            Self::Failed => "its status is FAILED",
401            Self::Inconsistent => "a check is worse than its status, which health.v1 §2.2 forbids",
402            Self::Check => "its status's level is unknown, and a check is DEGRADED or FAILED",
403            Self::UnknownLevel => "its status's level is unknown",
404            Self::Undecodable => "its status does not decode",
405            Self::Deleted => "its owner deleted its status",
406            Self::PresenceIncomplete => {
407                "its token was not seen, and the presence read may be incomplete or refused"
408            }
409            Self::NoDescriptor => "its descriptor could not be read",
410            Self::FaceClosed => "the constrained face does not let its status cross",
411            Self::NothingCrossed => {
412                "nothing of its status has crossed the constrained face, so none is known to exist"
413            }
414            Self::Absent => "it is absent: presence's word, not a level",
415            Self::NotListed => "its descriptor does not list health.v1",
416            Self::LastKnown => "only an archive's last-known status was read, never current",
417            Self::ChecksUnread => "its checks were not read",
418            Self::Freshness(r) => r.says(),
419        }
420    }
421}
422
423impl fmt::Display for Reason {
424    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
425        f.write_str(self.as_str())
426    }
427}
428
429/// A verdict, its reason, and for healthy and unhealthy the level it rests
430/// on.
431#[derive(Debug, Clone, Copy, PartialEq, Eq)]
432pub struct Judged {
433    pub verdict: Verdict,
434    pub reason: Reason,
435    pub level: Option<Level>,
436}
437
438impl Judged {
439    const fn new(verdict: Verdict, reason: Reason, level: Option<Level>) -> Self {
440        Self {
441            verdict,
442            reason,
443            level,
444        }
445    }
446
447    const fn unobservable(reason: Reason) -> Self {
448        Self::new(Verdict::Unobservable, reason, None)
449    }
450
451    const fn not_asked(reason: Reason) -> Self {
452        Self::new(Verdict::NotAsked, reason, None)
453    }
454
455    const fn unhealthy(reason: Reason, level: Level) -> Self {
456        Self::new(Verdict::Unhealthy, reason, Some(level))
457    }
458}
459
460/// Judges one reading by §2.11's order: presence, the descriptor, the
461/// status's freshness ([`freshness::judge_all`] at [`STATUS_TTL`]), its
462/// level, then the checks it vouches for.
463#[must_use]
464pub fn judge(r: &Reading<'_>) -> Judged {
465    let status = freshness::judge_all(&status_horizon(), r.status);
466    judge_status(r.presence, status, r.level, r.checks)
467}
468
469/// §2.11's five steps from the status's freshness as judged, for a reader
470/// that holds `freshness.v2`'s verdict over its observations of
471/// `state/status` at the standard contract's horizon rather than the
472/// observations: presence, the descriptor, that verdict, the level of the
473/// latest status read (`None` where no value was read), then the checks
474/// the owner answered (`None` where they were not read).
475///
476/// Either major's reading is judged so (`health.v2` §2.11): the steps,
477/// the verdicts and the reasons are one set. For `health.v2` the
478/// presence's [`Listing`] says whether the descriptor lists a major
479/// ([`Major::of`]), and a level is read from a record
480/// ([`v2::level_read`]).
481#[must_use]
482pub fn judge_status(
483    presence: Presence,
484    status: freshness::Judged,
485    level: Option<Read>,
486    checks: Option<&[Read]>,
487) -> Judged {
488    use Reason as R;
489    // 1. Presence; 2. the descriptor.
490    match presence {
491        Presence::Absent => return Judged::not_asked(R::Absent),
492        Presence::Incomplete => return Judged::unobservable(R::PresenceIncomplete),
493        Presence::AcrossFace {
494            status_crosses: false,
495        } => return Judged::unobservable(R::FaceClosed),
496        Presence::Present(Listing::NotListed) => return Judged::not_asked(R::NotListed),
497        Presence::Present(Listing::Unread) => return Judged::unobservable(R::NoDescriptor),
498        Presence::AcrossFace {
499            status_crosses: true,
500        }
501        | Presence::Present(Listing::Listed { .. }) => {}
502    }
503    // 3. The status's freshness.
504    let f = status;
505    match f.verdict {
506        freshness::Verdict::Fresh => {}
507        // A present, listed owner holds a status (§2.3), so silence ages
508        // it. Across a face nothing says one exists until something
509        // crosses (`freshness.v1` §2.5, "a member it knows").
510        freshness::Verdict::Stale
511            if f.reason == freshness::Reason::NoDelivery
512                && matches!(presence, Presence::AcrossFace { .. }) =>
513        {
514            return Judged::unobservable(R::NothingCrossed);
515        }
516        freshness::Verdict::Stale => {
517            return Judged::new(Verdict::Stale, R::Freshness(f.reason), None);
518        }
519        freshness::Verdict::Unobservable => return Judged::unobservable(R::Freshness(f.reason)),
520        freshness::Verdict::NotAsked => {
521            return match f.reason {
522                freshness::Reason::Deleted => Judged::unobservable(R::Deleted),
523                freshness::Reason::LastKnown => Judged::not_asked(R::LastKnown),
524                // No horizon, or a kind without one: not at the status's
525                // fixed horizon, but kept apart rather than guessed.
526                other => Judged::not_asked(R::Freshness(other)),
527            };
528        }
529    }
530    // 4. The status's level; 5. the checks, current with a fresh status.
531    let worst = worst_check(checks.unwrap_or(&[])).map(|(_, l)| l);
532    match level.and_then(Read::level) {
533        Some(status) => match worst {
534            Some(w) if w > status => Judged::unhealthy(R::Inconsistent, w),
535            _ => match status {
536                Level::Ok => Judged::new(Verdict::Healthy, R::Ok, Some(Level::Ok)),
537                Level::Degraded => Judged::unhealthy(R::Degraded, Level::Degraded),
538                Level::Failed => Judged::unhealthy(R::Failed, Level::Failed),
539            },
540        },
541        None => match worst {
542            Some(w) if w > Level::Ok => Judged::unhealthy(R::Check, w),
543            _ => Judged::unobservable(match level {
544                Some(Read::Unspecified | Read::Unlisted(_)) => R::UnknownLevel,
545                // A fresh status always carries a value; a level not read
546                // from it is a payload not read.
547                _ => R::Undecodable,
548            }),
549        },
550    }
551}
552
553/// A tool's roll-up of many services (§2.2, §5).
554#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
555pub struct Rollup {
556    /// The worst level among the established verdicts, healthy and
557    /// unhealthy; `None` when none is established.
558    pub worst: Option<Level>,
559    pub healthy: usize,
560    pub unhealthy: usize,
561    pub stale: usize,
562    pub unobservable: usize,
563    pub not_asked: usize,
564}
565
566/// Rolls up judged readings: the worst established level, with every
567/// verdict counted, and stale, unobservable and not asked never folded into
568/// a level (§2.2).
569#[must_use]
570pub fn rollup(judged: impl IntoIterator<Item = Judged>) -> Rollup {
571    let mut r = Rollup::default();
572    for j in judged {
573        match j.verdict {
574            Verdict::Healthy => r.healthy += 1,
575            Verdict::Unhealthy => r.unhealthy += 1,
576            Verdict::Stale => r.stale += 1,
577            Verdict::Unobservable => r.unobservable += 1,
578            Verdict::NotAsked => r.not_asked += 1,
579        }
580        if matches!(j.verdict, Verdict::Healthy | Verdict::Unhealthy) {
581            r.worst = r.worst.max(j.level);
582        }
583    }
584    r
585}
586
587/// A yes-or-no question of §5, answered in the three states: a pole of each
588/// Established kind, and the two Unestablished kinds apart (core O5).
589#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
590pub enum Answer {
591    Yes,
592    No,
593    /// The question was put, and the reading could not answer it.
594    Unobservable,
595    /// Nobody put the question, or its premise does not hold.
596    NotAsked,
597}
598
599impl Answer {
600    /// The fixture's token.
601    #[must_use]
602    pub fn as_str(self) -> &'static str {
603        match self {
604            Self::Yes => "yes",
605            Self::No => "no",
606            Self::Unobservable => "unobservable",
607            Self::NotAsked => "not_asked",
608        }
609    }
610}
611
612impl fmt::Display for Answer {
613    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
614        f.write_str(self.as_str())
615    }
616}
617
618/// §5's second question, "does its status agree with its checks?" (§2.2),
619/// for one reading, and its reason in [`Reason`]'s vocabulary.
620#[derive(Debug, Clone, Copy, PartialEq, Eq)]
621pub struct Agreement {
622    pub answer: Answer,
623    pub reason: Reason,
624}
625
626/// §5's second question over one reading, from what [`judge`] concluded of
627/// it and whether its checks were read: *yes* for a fresh status at a level
628/// with no current check worse; *no* for a current check worse than that
629/// status ([`Reason::Inconsistent`], the finding about the owner, which a
630/// tool reports only from two readings a grace apart, §2.2); not asked as
631/// the first question's not asked; unobservable when the status is not
632/// fresh, its level is unknown, or the checks were not read.
633#[must_use]
634pub fn agrees(judged: Judged, checks_read: bool) -> Agreement {
635    let a = |answer, reason| Agreement { answer, reason };
636    match (judged.verdict, judged.reason) {
637        (Verdict::NotAsked, r) => a(Answer::NotAsked, r),
638        (_, Reason::Inconsistent) => a(Answer::No, Reason::Inconsistent),
639        (
640            Verdict::Healthy | Verdict::Unhealthy,
641            r @ (Reason::Ok | Reason::Degraded | Reason::Failed),
642        ) => {
643            if checks_read {
644                a(Answer::Yes, r)
645            } else {
646                a(Answer::Unobservable, Reason::ChecksUnread)
647            }
648        }
649        // A status at an unknown level bounds nothing (§2.6), so whether a
650        // check is worse than it has no answer.
651        (Verdict::Unhealthy, Reason::Check) => a(Answer::Unobservable, Reason::UnknownLevel),
652        (_, r) => a(Answer::Unobservable, r),
653    }
654}
655
656/// One delivery a subscriber heard of one service during its reading, as
657/// §5's last question reads it.
658///
659/// Since text 0.9 (#978's F6) the clock guard holds no write of the
660/// status, which carries no Zenoh timestamp, and the heartbeat goes on
661/// vouching while it holds. So the evidence that the guard does not hold is
662/// a heartbeat's time, known, never a confirmation of the status.
663#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
664pub enum Heard {
665    /// A heartbeat covering `health.v1`, its status's section read in step
666    /// with the reader's view (`freshness.v2` §2.5, `confirmed`, its bit
667    /// set or clear), whose time is known: the guard did not hold when the
668    /// owner wrote it (`freshness.v2` §2.10).
669    Heartbeat,
670    /// The same, whose time is no instant: the ahead time, as while the
671    /// guard holds (core §7.5, `freshness.v2` §2.10), or the unknown time,
672    /// all ones. Under this major neither answers alone: the fault does
673    /// (text 0.11; `health.v2` §2.5 reads the ahead time as a yes).
674    HeartbeatHeld,
675    /// A put of `state/status`: the guard does not hold it, so it says
676    /// nothing of the clock.
677    StatusPut,
678    /// A delete of `state/status`, which §2.3 forbids: nothing of the
679    /// clock.
680    StatusDeleted,
681    /// A `faults` sample whose code is `clock_ahead` (§2.5, §2.10).
682    ClockAhead,
683    /// A `faults` sample with any other code, which says nothing of the
684    /// clock.
685    Fault,
686}
687
688impl Heard {
689    /// A heartbeat read in step, by the time it carries (core §7.5):
690    /// [`Heard::Heartbeat`] for an instant, [`Heard::HeartbeatHeld`] for
691    /// the ahead time and for the unknown time. Under this major the ahead
692    /// time is read exactly as the unknown time it replaced was, so core
693    /// 0.113 moved no answer of [`clock_ahead`] (text 0.11).
694    #[must_use]
695    pub fn heartbeat(time: crate::heartbeat::Time) -> Heard {
696        if time.is_instant() {
697            Heard::Heartbeat
698        } else {
699            Heard::HeartbeatHeld
700        }
701    }
702}
703
704/// Why §5's last question has its answer.
705#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
706pub enum ClockReason {
707    /// Yes, under `health.v2` alone ([`v2::clock_of`]): the last heartbeat
708    /// read carries the ahead time, so its owner's guard held when it
709    /// wrote it (`health.v2` §2.5).
710    Ahead,
711    /// Yes: a `clock_ahead` fault, and no heartbeat whose time is known
712    /// heard since.
713    ClockAhead,
714    /// No: the last heartbeat heard has its time known, and came after the
715    /// last `clock_ahead` fault, or with none heard. Its guard did not hold
716    /// when the owner wrote it.
717    Confirmed,
718    /// Unobservable: no `clock_ahead` fault heard since the last heartbeat
719    /// whose time is known, and the last heartbeat's time no instant,
720    /// ahead or unknown.
721    TimeUnknown,
722    /// Unobservable: no `clock_ahead` fault and no heartbeat heard within
723    /// the reader's window. Never "no" from the faults' silence.
724    NothingHeard,
725    /// Not asked: absent, presence's word (§2.1).
726    Absent,
727    /// Not asked: the descriptor does not list `health.v1` (§2.7).
728    NotListed,
729}
730
731impl ClockReason {
732    /// The fixture's token.
733    #[must_use]
734    pub fn as_str(self) -> &'static str {
735        match self {
736            Self::Ahead => "ahead",
737            Self::ClockAhead => "clock_ahead",
738            Self::Confirmed => "confirmed",
739            Self::TimeUnknown => "time_unknown",
740            Self::NothingHeard => "nothing_heard",
741            Self::Absent => "absent",
742            Self::NotListed => "not_listed",
743        }
744    }
745
746    /// The reason in words, for a tool's message.
747    #[must_use]
748    pub fn says(self) -> &'static str {
749        match self {
750            Self::Ahead => "its last heartbeat's time was ahead: its clock guard held",
751            Self::ClockAhead => {
752                "a clock_ahead fault was heard, and no heartbeat with its time known since"
753            }
754            Self::Confirmed => {
755                "its last heartbeat had its time known, after its last clock_ahead fault or with \
756                 none heard"
757            }
758            Self::TimeUnknown => {
759                "its last heartbeat's time was no instant, ahead or unknown, and no clock_ahead \
760                 fault was heard since one with its time known"
761            }
762            Self::NothingHeard => "no clock_ahead fault and no heartbeat was heard in the window",
763            Self::Absent => "it is absent: presence's word",
764            Self::NotListed => "its descriptor does not list health.v1",
765        }
766    }
767}
768
769impl fmt::Display for ClockReason {
770    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
771        f.write_str(self.as_str())
772    }
773}
774
775/// §5's last question, "is this service's clock ahead?" (§2.5), and why.
776/// Yes is the finding.
777#[derive(Debug, Clone, Copy, PartialEq, Eq)]
778pub struct Clock {
779    pub answer: Answer,
780    pub reason: ClockReason,
781}
782
783/// §5's last question from what one subscriber heard of one service in its
784/// window, in arrival order: *yes* on a `clock_ahead` fault with no
785/// heartbeat whose time is known heard since; *no* when the last heartbeat
786/// heard has its time known and came after the last fault, or with none
787/// heard; unobservable otherwise, since the faults' silence is their
788/// normal state (core O5) and a time that is no instant, ahead or unknown,
789/// answers nothing alone under this major. A put
790/// or a delete of the status says nothing of the clock: the guard holds
791/// neither (§2.5). Not asked as the first question's: absent, or not
792/// listing `health.v1`. Whatever else presence says, a fault heard is the
793/// service's own word, and answers. Nothing rests on a fault's stamp, nor
794/// its level (§2.5).
795#[must_use]
796pub fn clock_ahead(presence: Presence, heard: &[Heard]) -> Clock {
797    let c = |answer, reason| Clock { answer, reason };
798    match presence {
799        Presence::Absent => return c(Answer::NotAsked, ClockReason::Absent),
800        Presence::Present(Listing::NotListed) => {
801            return c(Answer::NotAsked, ClockReason::NotListed);
802        }
803        _ => {}
804    }
805    let last = |h: Heard| heard.iter().rposition(|x| *x == h);
806    let fault = last(Heard::ClockAhead);
807    let known = last(Heard::Heartbeat);
808    let unknown = last(Heard::HeartbeatHeld);
809    match (fault, known, unknown) {
810        (Some(f), k, _) if k.is_none_or(|k| k < f) => c(Answer::Yes, ClockReason::ClockAhead),
811        (_, Some(k), u) if u.is_none_or(|u| u < k) => c(Answer::No, ClockReason::Confirmed),
812        (_, _, Some(_)) => c(Answer::Unobservable, ClockReason::TimeUnknown),
813        _ => c(Answer::Unobservable, ClockReason::NothingHeard),
814    }
815}
816
817/// A fault's code, read by §2.10.
818#[derive(Debug, Clone, Copy, PartialEq, Eq)]
819pub enum Code<'a> {
820    /// A code of the profile's table ([`CODES`]).
821    Profile(&'static str),
822    /// Any other code of the form `[a-z][a-z0-9_]*`: an application's.
823    Application(&'a str),
824    /// Not of that form: still an occurrence, shown verbatim.
825    Malformed(&'a str),
826}
827
828impl Code<'_> {
829    /// The fixture's token.
830    #[must_use]
831    pub fn as_str(&self) -> &'static str {
832        match self {
833            Self::Profile(_) => "profile",
834            Self::Application(_) => "application",
835            Self::Malformed(_) => "malformed",
836        }
837    }
838}
839
840/// Whether `s` has a code's form (§2.10): `[a-z][a-z0-9_]*`, the whole
841/// of it. `health.v2`'s names have it too ([`v2::is_name`]).
842#[must_use]
843pub fn is_code_form(s: &str) -> bool {
844    let mut bytes = s.bytes();
845    bytes.next().is_some_and(|b| b.is_ascii_lowercase())
846        && bytes.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
847}
848
849/// Reads a fault's code (§2.10), exactly: no trimming, no case folding.
850#[must_use]
851pub fn code(s: &str) -> Code<'_> {
852    if !is_code_form(s) {
853        return Code::Malformed(s);
854    }
855    match CODES.iter().find(|c| **c == s) {
856        Some(c) => Code::Profile(c),
857        None => Code::Application(s),
858    }
859}
860
861#[cfg(test)]
862mod tests {
863    use super::*;
864    use crate::freshness::Last;
865
866    fn fresh() -> [Observation; 1] {
867        [Observation::Subscribed {
868            last: Some(Last::Put(Duration::from_secs(10))),
869            listened: Duration::from_secs(120),
870            complete: true,
871        }]
872    }
873
874    fn present() -> Presence {
875        Presence::Present(Listing::Listed { token: false })
876    }
877
878    #[test]
879    fn the_levels_are_ordered_and_unspecified_is_none_of_them() {
880        assert!(Level::Ok < Level::Degraded && Level::Degraded < Level::Failed);
881        for l in [Level::Ok, Level::Degraded, Level::Failed] {
882            assert_eq!(Read::from_wire(l.wire()), Read::Level(l));
883        }
884        assert_eq!(Read::from_wire(0), Read::Unspecified);
885        assert_eq!(Read::from_wire(4), Read::Unlisted(4));
886        assert_eq!(Read::Unspecified.level(), None);
887    }
888
889    #[test]
890    fn the_worst_check_is_the_first_at_the_worst_known_level() {
891        let checks = [
892            Read::Level(Level::Degraded),
893            Read::Unlisted(9),
894            Read::Level(Level::Failed),
895            Read::Level(Level::Failed),
896        ];
897        assert_eq!(worst_check(&checks), Some((2, Level::Failed)));
898        assert_eq!(worst_check(&[Read::Unspecified]), None);
899        assert!(consistent(Level::Failed, &checks));
900        assert!(!consistent(Level::Degraded, &checks));
901        assert!(consistent(Level::Ok, &[]));
902    }
903
904    #[test]
905    fn a_fresh_status_vouches_for_its_checks_and_a_stale_one_does_not() {
906        let o = fresh();
907        let checks = [Read::Level(Level::Failed)];
908        let mut r = Reading {
909            presence: present(),
910            status: &o,
911            level: Some(Read::Level(Level::Ok)),
912            checks: Some(&checks),
913        };
914        assert_eq!(
915            judge(&r),
916            Judged::unhealthy(Reason::Inconsistent, Level::Failed)
917        );
918        let stale = [Observation::Subscribed {
919            last: Some(Last::Put(Duration::from_secs(61))),
920            listened: Duration::from_secs(120),
921            complete: true,
922        }];
923        r.status = &stale;
924        assert_eq!(judge(&r).verdict, Verdict::Stale);
925    }
926
927    #[test]
928    fn a_rollup_never_folds_stale_into_a_level() {
929        let stale = Judged::new(
930            Verdict::Stale,
931            Reason::Freshness(freshness::Reason::BeyondHorizon),
932            None,
933        );
934        let r = rollup([
935            stale,
936            Judged::new(Verdict::Healthy, Reason::Ok, Some(Level::Ok)),
937        ]);
938        assert_eq!(r.worst, Some(Level::Ok));
939        assert_eq!((r.healthy, r.stale), (1, 1));
940        assert_eq!(rollup([stale]).worst, None);
941    }
942
943    #[test]
944    fn the_status_agrees_with_its_checks_only_when_fresh_at_a_level_and_read() {
945        let j = |verdict, reason, level| Judged::new(verdict, reason, level);
946        let ok = j(Verdict::Healthy, Reason::Ok, Some(Level::Ok));
947        assert_eq!(agrees(ok, true).answer, Answer::Yes);
948        assert_eq!(
949            agrees(ok, false),
950            Agreement {
951                answer: Answer::Unobservable,
952                reason: Reason::ChecksUnread
953            }
954        );
955        let liar = Judged::unhealthy(Reason::Inconsistent, Level::Failed);
956        assert_eq!(agrees(liar, true).answer, Answer::No);
957        let frank = Judged::unhealthy(Reason::Failed, Level::Failed);
958        assert_eq!(agrees(frank, true).answer, Answer::Yes, "worse is allowed");
959        let unknown = Judged::unhealthy(Reason::Check, Level::Failed);
960        assert_eq!(agrees(unknown, true).reason, Reason::UnknownLevel);
961        let stale = j(
962            Verdict::Stale,
963            Reason::Freshness(freshness::Reason::BeyondHorizon),
964            None,
965        );
966        assert_eq!(agrees(stale, true).answer, Answer::Unobservable);
967        let absent = Judged::not_asked(Reason::Absent);
968        assert_eq!(agrees(absent, true).answer, Answer::NotAsked);
969    }
970
971    #[test]
972    fn the_clock_is_ahead_on_a_fault_no_heartbeat_with_its_time_followed() {
973        use Heard::{ClockAhead, Fault, Heartbeat, HeartbeatHeld, StatusDeleted, StatusPut};
974        let p = present();
975        let a = |heard: &[Heard]| clock_ahead(p, heard).answer;
976        assert_eq!(a(&[ClockAhead]), Answer::Yes);
977        assert_eq!(a(&[Heartbeat, ClockAhead]), Answer::Yes);
978        assert_eq!(a(&[ClockAhead, Heartbeat]), Answer::No);
979        assert_eq!(a(&[ClockAhead, StatusDeleted]), Answer::Yes);
980        assert_eq!(
981            a(&[ClockAhead, StatusPut]),
982            Answer::Yes,
983            "the guard holds no put"
984        );
985        assert_eq!(a(&[ClockAhead, HeartbeatHeld]), Answer::Yes);
986        assert_eq!(a(&[Heartbeat]), Answer::No);
987        assert_eq!(a(&[StatusPut]), Answer::Unobservable);
988        assert_eq!(
989            clock_ahead(p, &[Heartbeat, HeartbeatHeld]).reason,
990            ClockReason::TimeUnknown,
991            "a time unknown since: no longer no, and no fault to say yes"
992        );
993        assert_eq!(a(&[ClockAhead, HeartbeatHeld, Heartbeat]), Answer::No);
994        // Core 0.113's ahead time reads as the unknown time did (text
995        // 0.11): no instant, so no evidence either way under this major.
996        use crate::heartbeat::Time;
997        assert_eq!(Heard::heartbeat(Time::Ahead), HeartbeatHeld);
998        assert_eq!(Heard::heartbeat(Time::Unknown), HeartbeatHeld);
999        assert_eq!(Heard::heartbeat(Time::At { secs: 7, ms: 0 }), Heartbeat);
1000        assert_eq!(
1001            clock_ahead(p, &[Heartbeat, Heard::heartbeat(Time::Ahead)]).reason,
1002            ClockReason::TimeUnknown,
1003            "the ahead time alone answers nothing under health.v1"
1004        );
1005        assert_eq!(a(&[Fault]), Answer::Unobservable, "never from silence");
1006        assert_eq!(a(&[]), Answer::Unobservable);
1007        assert_eq!(
1008            clock_ahead(Presence::Absent, &[ClockAhead]).answer,
1009            Answer::NotAsked
1010        );
1011    }
1012
1013    /// `health.v2` §2.11's step 2 and §2.12: a reader reads a service by
1014    /// the major its descriptor lists, `health.v2` where it lists both.
1015    #[test]
1016    fn a_descriptor_is_read_by_the_major_it_lists_and_v2_where_it_lists_both() {
1017        assert_eq!(Major::of(["freshness.v2", "health.v1"]), Some(Major::V1));
1018        assert_eq!(Major::of(["health.v2", "freshness.v2"]), Some(Major::V2));
1019        assert_eq!(Major::of(["health.v1", "health.v2"]), Some(Major::V2));
1020        assert_eq!(Major::of(["health.v2", "health.v1"]), Some(Major::V2));
1021        assert_eq!(Major::of(["tc.v1"]), None, "not listed: not asked");
1022        assert_eq!(Major::of([]), None);
1023        assert_eq!(Major::named("health.v2"), Some(Major::V2));
1024        assert_eq!(Major::named("health.v3"), None);
1025        assert_eq!((Major::V1.iface(), Major::V2.iface()), (IFACE, v2::IFACE));
1026    }
1027
1028    /// A status's freshness as judged gives what its observations give:
1029    /// [`judge`] is [`judge_status`] over `freshness.v2`'s verdict.
1030    #[test]
1031    fn a_reading_is_judged_alike_from_its_observations_and_from_their_verdict() {
1032        let o = fresh();
1033        let status = freshness::judge_all(&status_horizon(), &o);
1034        assert_eq!(status.verdict, freshness::Verdict::Fresh);
1035        let checks = [Read::Level(Level::Degraded)];
1036        for level in [
1037            Some(Read::Level(Level::Ok)),
1038            Some(Read::Unspecified),
1039            Some(Read::Undecodable),
1040            None,
1041        ] {
1042            let r = Reading {
1043                presence: present(),
1044                status: &o,
1045                level,
1046                checks: Some(&checks),
1047            };
1048            assert_eq!(
1049                judge(&r),
1050                judge_status(present(), status, level, Some(&checks))
1051            );
1052        }
1053        // A `health.v2` record at `unknown`, and one refused: never ok.
1054        let unknown = judge_status(present(), status, Some(Read::Unspecified), None);
1055        assert_eq!(
1056            (unknown.verdict, unknown.reason),
1057            (Verdict::Unobservable, Reason::UnknownLevel)
1058        );
1059        let refused = judge_status(present(), status, Some(Read::Undecodable), None);
1060        assert_eq!(
1061            (refused.verdict, refused.reason),
1062            (Verdict::Unobservable, Reason::Undecodable)
1063        );
1064    }
1065
1066    #[test]
1067    fn codes_are_lowercase_ascii_and_the_table_is_the_profiles() {
1068        assert_eq!(code("clock_ahead"), Code::Profile(CLOCK_AHEAD));
1069        assert_eq!(code("tc_netns_gone"), Code::Application("tc_netns_gone"));
1070        assert_eq!(code(""), Code::Malformed(""));
1071        assert_eq!(code("_x"), Code::Malformed("_x"));
1072        assert_eq!(code("Clock_ahead").as_str(), "malformed");
1073    }
1074}