use std::sync::Arc;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum HealthStatus {
Ok,
Degraded,
Failing,
}
impl HealthStatus {
pub fn label(self) -> &'static str {
match self {
Self::Ok => "ok",
Self::Degraded => "degraded",
Self::Failing => "failing",
}
}
}
#[derive(Debug, Clone)]
pub struct CheckResult {
pub status: HealthStatus,
pub summary: String,
pub details: serde_json::Value,
}
impl CheckResult {
pub fn ok(summary: impl Into<String>) -> Self {
Self::new(HealthStatus::Ok, summary)
}
pub fn degraded(summary: impl Into<String>) -> Self {
Self::new(HealthStatus::Degraded, summary)
}
pub fn failing(summary: impl Into<String>) -> Self {
Self::new(HealthStatus::Failing, summary)
}
pub fn new(status: HealthStatus, summary: impl Into<String>) -> Self {
Self {
status,
summary: summary.into(),
details: serde_json::Value::Null,
}
}
pub fn with_details(mut self, details: serde_json::Value) -> Self {
self.details = details;
self
}
}
pub trait HealthCheck: Send + Sync {
fn name(&self) -> &str;
fn check(&self) -> CheckResult;
}
#[derive(Debug, Clone)]
pub struct NamedResult {
pub name: String,
pub result: CheckResult,
}
#[derive(Debug, Clone)]
pub struct HealthReport {
pub status: HealthStatus,
pub checks: Vec<NamedResult>,
}
impl HealthReport {
pub fn is_ok(&self) -> bool {
self.status == HealthStatus::Ok
}
pub fn find(&self, name: &str) -> Option<&NamedResult> {
self.checks.iter().find(|c| c.name == name)
}
pub fn to_json(&self) -> serde_json::Value {
serde_json::json!({
"status": self.status.label(),
"checks": self
.checks
.iter()
.map(|c| serde_json::json!({
"name": c.name,
"status": c.result.status.label(),
"summary": c.result.summary,
"details": c.result.details,
}))
.collect::<Vec<_>>(),
})
}
}
#[derive(Default)]
pub struct HealthChecks(Vec<Arc<dyn HealthCheck>>);
impl HealthChecks {
pub fn new() -> Self {
Self(Vec::new())
}
pub fn with(mut self, check: Arc<dyn HealthCheck>) -> Self {
self.0.push(check);
self
}
pub fn from_vec(checks: Vec<Arc<dyn HealthCheck>>) -> Self {
Self(checks)
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn checks(&self) -> &[Arc<dyn HealthCheck>] {
&self.0
}
pub fn report(&self) -> HealthReport {
let checks: Vec<NamedResult> = self
.0
.iter()
.map(|c| NamedResult {
name: c.name().to_string(),
result: c.check(),
})
.collect();
let status = checks
.iter()
.map(|c| c.result.status)
.max()
.unwrap_or(HealthStatus::Ok);
HealthReport { status, checks }
}
}
#[cfg(test)]
mod tests {
use super::*;
struct Fixed(&'static str, HealthStatus);
impl HealthCheck for Fixed {
fn name(&self) -> &str {
self.0
}
fn check(&self) -> CheckResult {
CheckResult::new(self.1, "fixed")
}
}
#[test]
fn an_empty_set_is_healthy() {
let report = HealthChecks::new().report();
assert!(report.is_ok());
assert!(report.checks.is_empty());
}
#[test]
fn the_worst_check_decides_the_report() {
let report = HealthChecks::new()
.with(Arc::new(Fixed("a", HealthStatus::Ok)))
.with(Arc::new(Fixed("b", HealthStatus::Degraded)))
.with(Arc::new(Fixed("c", HealthStatus::Ok)))
.report();
assert_eq!(report.status, HealthStatus::Degraded);
let worse = HealthChecks::new()
.with(Arc::new(Fixed("b", HealthStatus::Degraded)))
.with(Arc::new(Fixed("d", HealthStatus::Failing)))
.report();
assert_eq!(worse.status, HealthStatus::Failing);
}
#[test]
fn every_check_is_in_the_report_in_the_order_it_was_registered() {
let report = HealthChecks::new()
.with(Arc::new(Fixed("a", HealthStatus::Ok)))
.with(Arc::new(Fixed("b", HealthStatus::Failing)))
.report();
let names: Vec<_> = report.checks.iter().map(|c| c.name.as_str()).collect();
assert_eq!(names, vec!["a", "b"]);
assert_eq!(report.to_json()["checks"][1]["status"], "failing");
}
}