Skip to main content

yaiko_core/
health.rs

1//! Health check utilities for Yaiko applications
2//!
3//! Provides a standard health check endpoint.
4
5use crate::{Handler, Request, Response};
6use async_trait::async_trait;
7
8/// Health check handler returning {"status": "ok"}
9pub struct HealthCheck;
10
11impl HealthCheck {
12    pub fn new() -> Self {
13        Self
14    }
15}
16
17impl Default for HealthCheck {
18    fn default() -> Self {
19        Self::new()
20    }
21}
22
23#[async_trait]
24impl Handler for HealthCheck {
25    async fn handle(
26        &self,
27        _req: Request,
28    ) -> Result<Response, Box<dyn std::error::Error + Send + Sync>> {
29        Ok(Response::new()
30            .status(hyper::StatusCode::OK)
31            .header("Content-Type", "application/json")
32            .header("Cache-Control", "no-cache, no-store, must-revalidate")
33            .text(r#"{"status":"ok"}"#))
34    }
35}
36
37/// Detailed health check with custom checks
38pub struct DetailedHealthCheck {
39    #[allow(clippy::type_complexity)]
40    checks: Vec<(&'static str, Box<dyn Fn() -> bool + Send + Sync>)>,
41}
42
43impl DetailedHealthCheck {
44    pub fn new() -> Self {
45        Self { checks: Vec::new() }
46    }
47
48    /// Return whether every registered dependency check currently passes.
49    pub fn is_ready(&self) -> bool {
50        self.checks.iter().all(|(_, check)| check())
51    }
52
53    /// Add a health check
54    pub fn add_check<F>(mut self, name: &'static str, check: F) -> Self
55    where
56        F: Fn() -> bool + Send + Sync + 'static,
57    {
58        self.checks.push((name, Box::new(check)));
59        self
60    }
61}
62
63impl Default for DetailedHealthCheck {
64    fn default() -> Self {
65        Self::new()
66    }
67}
68
69#[async_trait]
70impl Handler for DetailedHealthCheck {
71    async fn handle(
72        &self,
73        _req: Request,
74    ) -> Result<Response, Box<dyn std::error::Error + Send + Sync>> {
75        let mut all_ok = true;
76        let mut results = Vec::new();
77
78        for (name, check) in &self.checks {
79            let ok = check();
80            if !ok {
81                all_ok = false;
82            }
83            results.push(format!(
84                r#""{}":{}"#,
85                name,
86                if ok { "true" } else { "false" }
87            ));
88        }
89
90        let status = if all_ok { "ok" } else { "degraded" };
91        let body = format!(
92            r#"{{"status":"{}","checks":{{{}}}}}"#,
93            status,
94            results.join(",")
95        );
96
97        let http_status = if all_ok {
98            hyper::StatusCode::OK
99        } else {
100            hyper::StatusCode::SERVICE_UNAVAILABLE
101        };
102
103        Ok(Response::new()
104            .status(http_status)
105            .header("Content-Type", "application/json")
106            .header("Cache-Control", "no-cache, no-store, must-revalidate")
107            .text(&body))
108    }
109}
110
111/// Liveness is a process-level check with no dependency probes.
112pub type LivenessCheck = HealthCheck;
113
114/// Readiness is a dependency-aware detailed health check.
115pub type ReadinessCheck = DetailedHealthCheck;