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