diode_http/
health_check.rs1use 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 any::{TypeId, type_name},
10 collections::HashSet,
11 marker::PhantomData,
12 sync::Arc,
13 time::{Duration, Instant},
14};
15
16use crate::{ControlServerPlugin, RouterBuilder};
17
18#[derive(Default)]
19pub(crate) struct HealthCheckRegistry {
20 health_checks: Vec<Arc<dyn DynHealthCheck>>,
21 types: HashSet<TypeId>,
22}
23
24impl HealthCheckRegistry {
25 pub fn add_health_check<T>(&mut self, health_check: Arc<T>)
26 where
27 T: HealthCheck + 'static,
28 {
29 if !self.types.insert(TypeId::of::<T>()) {
30 panic!("Health check {} already added", type_name::<T>());
31 }
32 self.health_checks.push(health_check);
33 }
34
35 pub fn has_health_check<T>(&self) -> bool
36 where
37 T: HealthCheck + 'static,
38 {
39 self.types.contains(&TypeId::of::<T>())
40 }
41
42 pub fn build_health_checks(&self) -> Arc<[Arc<dyn DynHealthCheck>]> {
43 self.health_checks.clone().into()
44 }
45}
46
47pub trait HealthCheck: Send + Sync {
57 fn name(&self) -> &str;
59
60 fn health_check(&self) -> impl Future<Output = Result<(), StdError>> + Send;
62}
63
64#[async_trait]
65pub(crate) trait DynHealthCheck: Send + Sync {
66 fn name(&self) -> &str;
67
68 async fn health_check(&self) -> Result<(), StdError>;
69}
70
71#[async_trait]
72impl<T> DynHealthCheck for T
73where
74 T: HealthCheck + 'static,
75{
76 fn name(&self) -> &str {
77 self.name()
78 }
79
80 async fn health_check(&self) -> Result<(), StdError> {
81 self.health_check().await
82 }
83}
84
85struct HealthCheckServiceProvider<T>(PhantomData<T>);
86
87impl<T> Plugin for HealthCheckServiceProvider<T>
88where
89 T: Service<Handle = Arc<T>> + HealthCheck + 'static,
90{
91 async fn build(&self, ctx: &AppContext) -> Result<(), StdError> {
92 let component = ctx.get_component::<T::Handle>().unwrap();
93 ctx.get_component_mut::<HealthCheckRegistry>()
94 .unwrap()
95 .add_health_check(component);
96 Ok(())
97 }
98
99 fn dependencies(&self) -> Dependencies {
100 T::dependencies()
101 .service::<T>()
102 .plugin::<ControlServerPlugin>()
103 }
104}
105
106pub trait AddHealthCheckExt {
113 fn add_health_check<T>(&self, health_check: impl Into<Arc<T>>)
122 where
123 T: HealthCheck + 'static;
124
125 fn has_health_check<T>(&self) -> bool
127 where
128 T: HealthCheck + 'static;
129}
130
131impl AddHealthCheckExt for AppContext {
132 fn add_health_check<T>(&self, health_check: impl Into<Arc<T>>)
133 where
134 T: HealthCheck + 'static,
135 {
136 if !self.has_component::<HealthCheckRegistry>() {
137 self.add_component(HealthCheckRegistry::default());
138 }
139 self.get_component_mut::<HealthCheckRegistry>()
140 .unwrap()
141 .add_health_check(health_check.into());
142 }
143
144 fn has_health_check<T>(&self) -> bool
145 where
146 T: HealthCheck + 'static,
147 {
148 self.get_component_ref::<HealthCheckRegistry>()
149 .is_some_and(|registry| registry.has_health_check::<T>())
150 }
151}
152
153pub trait AddHealthCheckServiceExt {
158 fn add_health_check_service<T>(&mut self) -> &mut Self
166 where
167 T: Service<Handle = Arc<T>> + HealthCheck + 'static;
168
169 fn has_health_check_service<T>(&self) -> bool
171 where
172 T: Service<Handle = Arc<T>> + HealthCheck + 'static;
173}
174
175impl AddHealthCheckServiceExt for AppBuilder {
176 fn add_health_check_service<T>(&mut self) -> &mut Self
177 where
178 T: Service<Handle = Arc<T>> + HealthCheck + 'static,
179 {
180 if !self.has_service::<T>() {
181 self.add_service::<T>();
182 }
183 self.add_plugin(HealthCheckServiceProvider::<T>(PhantomData));
184 self
185 }
186
187 fn has_health_check_service<T>(&self) -> bool
188 where
189 T: Service<Handle = Arc<T>> + HealthCheck + 'static,
190 {
191 self.has_plugin::<HealthCheckServiceProvider<T>>()
192 }
193}
194
195#[derive(Clone)]
202pub struct HealthClient {
203 client: reqwest::Client,
204 endpoint: String,
205}
206
207impl HealthClient {
208 pub fn new(endpoint: String) -> Self {
213 Self {
214 client: reqwest::Client::new(),
215 endpoint,
216 }
217 }
218
219 pub async fn health_check(&self) -> Result<(), HealthCheckError> {
226 let response = self
227 .client
228 .get(&self.endpoint)
229 .send()
230 .await
231 .map_err(|err| HealthCheckError {
232 name: "health_client".into(),
233 message: format!("Health check failed: {err}"),
234 })?;
235 let status = response.status();
236 if status.is_success() {
237 Ok(())
238 } else {
239 Err(response.json().await.map_err(|_| HealthCheckError {
240 name: "health_client".into(),
241 message: format!("Health check failed with status: {status}"),
242 })?)
243 }
244 }
245
246 pub async fn wait_for_ready(&self, timeout: Duration) -> Result<(), HealthCheckError> {
254 let start = Instant::now();
255 loop {
256 match self.health_check().await {
257 Ok(_) => return Ok(()),
258 Err(err) => {
259 if start.elapsed() >= timeout {
260 return Err(err);
261 }
262 tokio::time::sleep(Duration::from_millis(100)).await;
263 }
264 }
265 }
266 }
267}
268
269#[derive(Service)]
277pub struct HealthRouter;
278
279impl RouterBuilder for HealthRouter {
280 fn build_router(self: Arc<Self>, app: &App) -> Router {
281 let health_checks = app
282 .get_component_ref::<HealthCheckRegistry>()
283 .unwrap()
284 .build_health_checks();
285 Router::new().route(
286 "/health",
287 routing::get(|| async move { self.health(health_checks.as_ref()).await }),
288 )
289 }
290}
291
292const HEALTHY: &str = "healthy";
293
294impl HealthRouter {
295 async fn health(
296 &self,
297 health_checks: &[Arc<dyn DynHealthCheck>],
298 ) -> Result<&'static str, HealthCheckError> {
299 for health_check in health_checks {
300 let name = health_check.name().to_string();
301 if let Err(err) = health_check.health_check().await {
302 return Err(HealthCheckError {
303 name,
304 message: err.to_string(),
305 });
306 }
307 }
308 Ok(HEALTHY)
309 }
310}
311
312#[derive(Clone, Debug, Serialize, Deserialize)]
317pub struct HealthCheckError {
318 name: String,
319 message: String,
320}
321
322impl axum::response::IntoResponse for HealthCheckError {
323 fn into_response(self) -> axum::response::Response {
324 (
325 axum::http::StatusCode::INTERNAL_SERVER_ERROR,
326 axum::response::Json(self),
327 )
328 .into_response()
329 }
330}
331
332#[derive(Service)]
336pub struct PingHandler;
337
338impl PingHandler {
339 async fn ping() -> &'static str {
340 "pong"
341 }
342}
343
344impl RouterBuilder for PingHandler {
345 fn build_router(self: Arc<Self>, _app: &App) -> Router {
346 Router::new().route("/ping", routing::get(|| async move { Self::ping().await }))
347 }
348}