1use std::sync::Arc;
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
42#[non_exhaustive]
43pub enum HealthStatus {
44 Ok,
46 Degraded,
49 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#[derive(Debug, Clone)]
65pub struct CheckResult {
66 pub status: HealthStatus,
67 pub summary: String,
69 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
101pub trait HealthCheck: Send + Sync {
103 fn name(&self) -> &str;
106
107 fn check(&self) -> CheckResult;
108}
109
110#[derive(Debug, Clone)]
112pub struct NamedResult {
113 pub name: String,
114 pub result: CheckResult,
115}
116
117#[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 pub fn find(&self, name: &str) -> Option<&NamedResult> {
131 self.checks.iter().find(|c| c.name == name)
132 }
133
134 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#[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 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}