Skip to main content

yaiko_core/
health_registry.rs

1//! Async dependency health registry for readiness and operational diagnostics.
2
3use crate::{Handler, Request, Response};
4use async_trait::async_trait;
5use serde::Serialize;
6use std::future::Future;
7use std::pin::Pin;
8use std::sync::Arc;
9use std::time::Duration;
10
11pub type ProbeFuture = Pin<Box<dyn Future<Output = Result<(), String>> + Send>>;
12pub type ProbeFn = Box<dyn Fn() -> ProbeFuture + Send + Sync>;
13
14#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
15pub struct ProbeResult {
16    pub name: String,
17    pub status: String,
18    pub detail: Option<String>,
19}
20
21#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
22pub struct HealthReport {
23    pub status: String,
24    pub ready: bool,
25    pub checks: Vec<ProbeResult>,
26}
27
28impl HealthReport {
29    pub fn is_ready(&self) -> bool {
30        self.ready
31    }
32}
33
34struct Probe {
35    name: String,
36    check: ProbeFn,
37}
38
39pub struct DependencyHealthRegistry {
40    probes: Vec<Probe>,
41    timeout: Duration,
42}
43
44impl DependencyHealthRegistry {
45    pub fn new() -> Self {
46        Self {
47            probes: Vec::new(),
48            timeout: Duration::from_secs(2),
49        }
50    }
51
52    pub fn timeout(mut self, timeout: Duration) -> Self {
53        self.timeout = timeout;
54        self
55    }
56
57    pub fn add_probe<F, Fut>(mut self, name: impl Into<String>, check: F) -> Self
58    where
59        F: Fn() -> Fut + Send + Sync + 'static,
60        Fut: Future<Output = Result<(), String>> + Send + 'static,
61    {
62        self.probes.push(Probe {
63            name: name.into(),
64            check: Box::new(move || Box::pin(check())),
65        });
66        self
67    }
68
69    pub async fn check(&self) -> HealthReport {
70        let mut checks = Vec::with_capacity(self.probes.len());
71        let mut ready = true;
72        for probe in &self.probes {
73            let result = tokio::time::timeout(self.timeout, (probe.check)()).await;
74            let probe_result = match result {
75                Ok(Ok(())) => ProbeResult {
76                    name: probe.name.clone(),
77                    status: "ok".to_string(),
78                    detail: None,
79                },
80                Ok(Err(error)) => {
81                    ready = false;
82                    ProbeResult {
83                        name: probe.name.clone(),
84                        status: "failed".to_string(),
85                        detail: Some(error),
86                    }
87                }
88                Err(_) => {
89                    ready = false;
90                    ProbeResult {
91                        name: probe.name.clone(),
92                        status: "timeout".to_string(),
93                        detail: Some(format!("timed out after {}ms", self.timeout.as_millis())),
94                    }
95                }
96            };
97            checks.push(probe_result);
98        }
99        HealthReport {
100            status: if ready { "ok" } else { "degraded" }.to_string(),
101            ready,
102            checks,
103        }
104    }
105
106    pub fn handler(self: Arc<Self>) -> DependencyHealthHandler {
107        DependencyHealthHandler { registry: self }
108    }
109}
110
111impl Default for DependencyHealthRegistry {
112    fn default() -> Self {
113        Self::new()
114    }
115}
116
117pub struct DependencyHealthHandler {
118    registry: Arc<DependencyHealthRegistry>,
119}
120
121#[async_trait]
122impl Handler for DependencyHealthHandler {
123    async fn handle(
124        &self,
125        _request: Request,
126    ) -> Result<Response, Box<dyn std::error::Error + Send + Sync>> {
127        let report = self.registry.check().await;
128        let status = if report.ready {
129            hyper::StatusCode::OK
130        } else {
131            hyper::StatusCode::SERVICE_UNAVAILABLE
132        };
133        Ok(Response::new()
134            .status(status)
135            .header("Cache-Control", "no-cache, no-store, must-revalidate")
136            .json(&report)?)
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143    use std::time::Duration;
144
145    #[tokio::test]
146    async fn aggregates_success_and_failure_probes() {
147        let registry = DependencyHealthRegistry::new()
148            .add_probe("database", || async { Ok(()) })
149            .add_probe("cache", || async { Err("offline".to_string()) });
150        let report = registry.check().await;
151        assert!(!report.is_ready());
152        assert_eq!(report.status, "degraded");
153        assert_eq!(report.checks[0].status, "ok");
154        assert_eq!(report.checks[1].detail.as_deref(), Some("offline"));
155    }
156
157    #[tokio::test]
158    async fn reports_timed_out_dependencies_as_unready() {
159        let registry = DependencyHealthRegistry::new()
160            .timeout(Duration::from_millis(5))
161            .add_probe("slow", || async {
162                tokio::time::sleep(Duration::from_millis(30)).await;
163                Ok(())
164            });
165        let report = registry.check().await;
166        assert!(!report.ready);
167        assert_eq!(report.checks[0].status, "timeout");
168    }
169
170    #[tokio::test]
171    async fn empty_registry_is_ready() {
172        let report = DependencyHealthRegistry::new().check().await;
173        assert!(report.ready);
174        assert_eq!(report.status, "ok");
175        assert!(report.checks.is_empty());
176    }
177}