Skip to main content

diode_http/
health_check.rs

1use async_trait::async_trait;
2use axum::{Router, routing};
3use diode::{
4    AddServiceExt as _, App, AppBuilder, AppContext, Dependencies, Plugin, Service,
5    ServiceDependencyExt as _, StdError,
6};
7use serde::{Deserialize, Serialize};
8use std::{
9    marker::PhantomData,
10    sync::Arc,
11    time::{Duration, Instant},
12};
13
14use crate::{ControlServerPlugin, RouterBuilder};
15
16#[derive(Default)]
17pub(crate) struct HealthCheckRegistry {
18    health_checks: Vec<Arc<dyn DynHealthCheck>>,
19}
20
21impl HealthCheckRegistry {
22    pub fn add_health_check<T>(&mut self, health_check: Arc<T>)
23    where
24        T: HealthCheck + 'static,
25    {
26        self.health_checks.push(health_check);
27    }
28
29    pub fn build_health_checks(&self) -> Arc<[Arc<dyn DynHealthCheck>]> {
30        self.health_checks.clone().into()
31    }
32}
33
34pub trait HealthCheck: Send + Sync {
35    fn name(&self) -> &str;
36
37    fn health_check(&self) -> impl Future<Output = Result<(), StdError>> + Send;
38}
39
40#[async_trait]
41pub(crate) trait DynHealthCheck: Send + Sync {
42    fn name(&self) -> &str;
43
44    async fn health_check(&self) -> Result<(), StdError>;
45}
46
47#[async_trait]
48impl<T> DynHealthCheck for T
49where
50    T: HealthCheck + 'static,
51{
52    fn name(&self) -> &str {
53        self.name()
54    }
55
56    async fn health_check(&self) -> Result<(), StdError> {
57        self.health_check().await
58    }
59}
60
61struct HealthCheckServiceProvider<T>(PhantomData<T>);
62
63impl<T> Plugin for HealthCheckServiceProvider<T>
64where
65    T: Service<Handle = Arc<T>> + HealthCheck + 'static,
66{
67    async fn build(&self, ctx: &AppContext) -> Result<(), StdError> {
68        let component = ctx.get_component::<T::Handle>().unwrap();
69        ctx.get_component_mut::<HealthCheckRegistry>()
70            .unwrap()
71            .add_health_check(component);
72        Ok(())
73    }
74
75    fn dependencies(&self) -> Dependencies {
76        T::dependencies()
77            .service::<T>()
78            .plugin::<ControlServerPlugin>()
79    }
80}
81
82pub trait AddHealthCheckExt {
83    fn add_health_check<T>(&mut self, health_check: impl Into<Arc<T>>) -> &mut Self
84    where
85        T: HealthCheck + 'static;
86}
87
88impl AddHealthCheckExt for AppBuilder {
89    fn add_health_check<T>(&mut self, health_check: impl Into<Arc<T>>) -> &mut Self
90    where
91        T: HealthCheck + 'static,
92    {
93        if !self.has_component::<HealthCheckRegistry>() {
94            self.add_component(HealthCheckRegistry::default());
95        }
96        self.get_component_mut::<HealthCheckRegistry>()
97            .unwrap()
98            .add_health_check(health_check.into());
99        self
100    }
101}
102
103pub trait AddHealthCheckServiceExt {
104    fn add_health_check_service<T>(&mut self) -> &mut Self
105    where
106        T: Service<Handle = Arc<T>> + HealthCheck + 'static;
107
108    fn has_health_check_service<T>(&self) -> bool
109    where
110        T: Service<Handle = Arc<T>> + HealthCheck + 'static;
111}
112
113impl AddHealthCheckServiceExt for AppBuilder {
114    fn add_health_check_service<T>(&mut self) -> &mut Self
115    where
116        T: Service<Handle = Arc<T>> + HealthCheck + 'static,
117    {
118        if !self.has_service::<T>() {
119            self.add_service::<T>();
120        }
121        self.add_plugin(HealthCheckServiceProvider::<T>(PhantomData));
122        self
123    }
124
125    fn has_health_check_service<T>(&self) -> bool
126    where
127        T: Service<Handle = Arc<T>> + HealthCheck + 'static,
128    {
129        self.has_plugin::<HealthCheckServiceProvider<T>>()
130    }
131}
132
133#[derive(Clone)]
134pub struct HealthClient {
135    client: reqwest::Client,
136    endpoint: String,
137}
138
139impl HealthClient {
140    pub fn new(endpoint: String) -> Self {
141        Self {
142            client: reqwest::Client::new(),
143            endpoint,
144        }
145    }
146
147    pub async fn health_check(&self) -> Result<(), HealthCheckError> {
148        let response = self
149            .client
150            .get(&self.endpoint)
151            .send()
152            .await
153            .map_err(|err| HealthCheckError {
154                name: "health_client".into(),
155                message: format!("Health check failed: {err}"),
156            })?;
157        let status = response.status();
158        if status.is_success() {
159            Ok(())
160        } else {
161            Err(response.json().await.map_err(|_| HealthCheckError {
162                name: "health_client".into(),
163                message: format!("Health check failed with status: {status}"),
164            })?)
165        }
166    }
167
168    pub async fn wait_for_ready(&self, timeout: Duration) -> Result<(), HealthCheckError> {
169        let start = Instant::now();
170        loop {
171            match self.health_check().await {
172                Ok(_) => return Ok(()),
173                Err(err) => {
174                    if start.elapsed() >= timeout {
175                        return Err(err);
176                    }
177                    tokio::time::sleep(Duration::from_millis(100)).await;
178                }
179            }
180        }
181    }
182}
183
184#[derive(Service)]
185pub struct HealthRouter;
186
187impl RouterBuilder for HealthRouter {
188    fn build_router(self: Arc<Self>, app: &App) -> Router {
189        let health_checks = app
190            .get_component_ref::<HealthCheckRegistry>()
191            .unwrap()
192            .build_health_checks();
193        Router::new().route(
194            "/health",
195            routing::get(|| async move { self.health(health_checks.as_ref()).await }),
196        )
197    }
198}
199
200const HEALTHY: &str = "healthy";
201
202impl HealthRouter {
203    async fn health(
204        &self,
205        health_checks: &[Arc<dyn DynHealthCheck>],
206    ) -> Result<&'static str, HealthCheckError> {
207        for health_check in health_checks {
208            let name = health_check.name().to_string();
209            if let Err(err) = health_check.health_check().await {
210                return Err(HealthCheckError {
211                    name,
212                    message: err.to_string(),
213                });
214            }
215        }
216        Ok(HEALTHY)
217    }
218}
219
220#[derive(Clone, Debug, Serialize, Deserialize)]
221pub struct HealthCheckError {
222    name: String,
223    message: String,
224}
225
226impl axum::response::IntoResponse for HealthCheckError {
227    fn into_response(self) -> axum::response::Response {
228        (
229            axum::http::StatusCode::INTERNAL_SERVER_ERROR,
230            axum::response::Json(self),
231        )
232            .into_response()
233    }
234}
235
236#[derive(Service)]
237pub struct PingHandler;
238
239impl PingHandler {
240    async fn ping() -> &'static str {
241        "pong"
242    }
243}
244
245impl RouterBuilder for PingHandler {
246    fn build_router(self: Arc<Self>, _app: &App) -> Router {
247        Router::new().route("/ping", routing::get(|| async move { Self::ping().await }))
248    }
249}