Skip to main content

base/interface/
health.rs

1//! `HealthCheck` — whether the engine, and what a host wired into it, is
2//! working.
3//!
4//! Something with state, asked "are you all right", answering with a verdict
5//! and enough detail to act on. `daemon`'s `doctor` is one such answer; this
6//! is the shape as a contract, so an embedder linking the engine directly can
7//! read the engine's answers and add its own checks beside them.
8//!
9//! # A check answers from what it already knows
10//!
11//! [`HealthCheck::check`] is synchronous and is expected to return promptly. A
12//! probe that blocks on the subsystem it is probing turns "is the database
13//! reachable" into a request that hangs exactly when the answer matters most,
14//! and a health endpoint that hangs during an outage is worse than no health
15//! endpoint. Both implementations the engine ships answer from state they
16//! already hold — a fault counter, a file that is either there or not. A host
17//! whose check needs to go over a network keeps a cached verdict, updated out
18//! of band, and reports that.
19//!
20//! # A check reports, it does not repair
21//!
22//! Nothing here can change what the engine does. A check returns a verdict and
23//! detail; there is no expression that reopens a circuit breaker, reloads
24//! configuration or restarts anything. Diagnosis and action are different
25//! decisions with different consequences, and a diagnostic that silently
26//! repaired things would make every report a description of what it just did
27//! rather than of what it found.
28//!
29//! # There is no `Err`
30//!
31//! A check that cannot determine the answer has determined something: it says
32//! [`HealthStatus::Degraded`] and puts the reason in its summary. Returning a
33//! `Result` would leave every caller deciding whether a failed check means
34//! unhealthy or means nothing, and they would not all decide the same way.
35
36use std::sync::Arc;
37
38/// How well one thing is.
39///
40/// Ordered worst-last, so aggregating a report is a maximum.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
42#[non_exhaustive]
43pub enum HealthStatus {
44    /// Working.
45    Ok,
46    /// Working, but something is wrong that someone should know about — a
47    /// misconfigured tier, a plugin set aside, a fallback in use.
48    Degraded,
49    /// Not working. Whatever this check covers cannot be relied on.
50    Failing,
51}
52
53impl HealthStatus {
54    pub fn label(self) -> &'static str {
55        match self {
56            Self::Ok => "ok",
57            Self::Degraded => "degraded",
58            Self::Failing => "failing",
59        }
60    }
61}
62
63/// One check's answer.
64#[derive(Debug, Clone)]
65pub struct CheckResult {
66    pub status: HealthStatus,
67    /// One line, for a person reading a status page.
68    pub summary: String,
69    /// Whatever a caller needs to act on it. `Null` when the summary is the
70    /// whole story.
71    pub details: serde_json::Value,
72}
73
74impl CheckResult {
75    pub fn ok(summary: impl Into<String>) -> Self {
76        Self::new(HealthStatus::Ok, summary)
77    }
78
79    pub fn degraded(summary: impl Into<String>) -> Self {
80        Self::new(HealthStatus::Degraded, summary)
81    }
82
83    pub fn failing(summary: impl Into<String>) -> Self {
84        Self::new(HealthStatus::Failing, summary)
85    }
86
87    pub fn new(status: HealthStatus, summary: impl Into<String>) -> Self {
88        Self {
89            status,
90            summary: summary.into(),
91            details: serde_json::Value::Null,
92        }
93    }
94
95    pub fn with_details(mut self, details: serde_json::Value) -> Self {
96        self.details = details;
97        self
98    }
99}
100
101/// Something that can say whether it is working.
102pub trait HealthCheck: Send + Sync {
103    /// Stable, dotted, and unique among the checks registered beside it —
104    /// this is what a status page keys on and what an alert names.
105    fn name(&self) -> &str;
106
107    fn check(&self) -> CheckResult;
108}
109
110/// One entry in a report.
111#[derive(Debug, Clone)]
112pub struct NamedResult {
113    pub name: String,
114    pub result: CheckResult,
115}
116
117/// What every registered check answered, and the worst of it.
118#[derive(Debug, Clone)]
119pub struct HealthReport {
120    pub status: HealthStatus,
121    pub checks: Vec<NamedResult>,
122}
123
124impl HealthReport {
125    pub fn is_ok(&self) -> bool {
126        self.status == HealthStatus::Ok
127    }
128
129    /// What one named check answered.
130    pub fn find(&self, name: &str) -> Option<&NamedResult> {
131        self.checks.iter().find(|c| c.name == name)
132    }
133
134    /// The report as JSON, for a status endpoint or an RPC result.
135    pub fn to_json(&self) -> serde_json::Value {
136        serde_json::json!({
137            "status": self.status.label(),
138            "checks": self
139                .checks
140                .iter()
141                .map(|c| serde_json::json!({
142                    "name": c.name,
143                    "status": c.result.status.label(),
144                    "summary": c.result.summary,
145                    "details": c.result.details,
146                }))
147                .collect::<Vec<_>>(),
148        })
149    }
150}
151
152/// The checks in force at one scope, and the report they produce together.
153///
154/// One of these per scope rather than one per process: a session's health and
155/// the whole daemon's are different questions with different lifetimes, and a
156/// single shared registry would either grow a check per session forever or
157/// answer the wrong one of the two.
158#[derive(Default)]
159pub struct HealthChecks(Vec<Arc<dyn HealthCheck>>);
160
161impl HealthChecks {
162    pub fn new() -> Self {
163        Self(Vec::new())
164    }
165
166    pub fn with(mut self, check: Arc<dyn HealthCheck>) -> Self {
167        self.0.push(check);
168        self
169    }
170
171    pub fn from_vec(checks: Vec<Arc<dyn HealthCheck>>) -> Self {
172        Self(checks)
173    }
174
175    pub fn is_empty(&self) -> bool {
176        self.0.is_empty()
177    }
178
179    pub fn checks(&self) -> &[Arc<dyn HealthCheck>] {
180        &self.0
181    }
182
183    /// Run every check. An empty set is [`HealthStatus::Ok`] — nothing has
184    /// said otherwise, which is all any report ever claims.
185    pub fn report(&self) -> HealthReport {
186        let checks: Vec<NamedResult> = self
187            .0
188            .iter()
189            .map(|c| NamedResult {
190                name: c.name().to_string(),
191                result: c.check(),
192            })
193            .collect();
194        let status = checks
195            .iter()
196            .map(|c| c.result.status)
197            .max()
198            .unwrap_or(HealthStatus::Ok);
199        HealthReport { status, checks }
200    }
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206
207    struct Fixed(&'static str, HealthStatus);
208
209    impl HealthCheck for Fixed {
210        fn name(&self) -> &str {
211            self.0
212        }
213        fn check(&self) -> CheckResult {
214            CheckResult::new(self.1, "fixed")
215        }
216    }
217
218    #[test]
219    fn an_empty_set_is_healthy() {
220        let report = HealthChecks::new().report();
221        assert!(report.is_ok());
222        assert!(report.checks.is_empty());
223    }
224
225    #[test]
226    fn the_worst_check_decides_the_report() {
227        let report = HealthChecks::new()
228            .with(Arc::new(Fixed("a", HealthStatus::Ok)))
229            .with(Arc::new(Fixed("b", HealthStatus::Degraded)))
230            .with(Arc::new(Fixed("c", HealthStatus::Ok)))
231            .report();
232        assert_eq!(report.status, HealthStatus::Degraded);
233
234        let worse = HealthChecks::new()
235            .with(Arc::new(Fixed("b", HealthStatus::Degraded)))
236            .with(Arc::new(Fixed("d", HealthStatus::Failing)))
237            .report();
238        assert_eq!(worse.status, HealthStatus::Failing);
239    }
240
241    #[test]
242    fn every_check_is_in_the_report_in_the_order_it_was_registered() {
243        let report = HealthChecks::new()
244            .with(Arc::new(Fixed("a", HealthStatus::Ok)))
245            .with(Arc::new(Fixed("b", HealthStatus::Failing)))
246            .report();
247        let names: Vec<_> = report.checks.iter().map(|c| c.name.as_str()).collect();
248        assert_eq!(names, vec!["a", "b"]);
249        assert_eq!(report.to_json()["checks"][1]["status"], "failing");
250    }
251}