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    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
47/// A named check reporting whether a part of the application is healthy.
48///
49/// Implementors are aggregated by the control server's [`HealthRouter`]: a
50/// `GET /health` runs every registered check in registration order and fails on
51/// the first error, reporting that check's [`name`](HealthCheck::name).
52///
53/// Register a check with [`AddHealthCheckExt::add_health_check`] (a concrete
54/// instance) or [`AddHealthCheckServiceExt::add_health_check_service`] (resolved
55/// from a [`Service`]).
56pub trait HealthCheck: Send + Sync {
57    /// Name reported when this check fails.
58    fn name(&self) -> &str;
59
60    /// Performs the check, returning `Err` if the dependency is unhealthy.
61    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
106/// Registers concrete [`HealthCheck`] instances on the control server.
107///
108/// Lives on [`AppContext`], so checks can be registered while configuring the
109/// [`AppBuilder`] or from within a plugin's `build`. A check is identified by its
110/// type and is only ever run if [`ControlServerPlugin`] is added (it provides the
111/// registry and the [`HealthRouter`] that drives the checks).
112pub trait AddHealthCheckExt {
113    /// Registers `health_check` on the control server.
114    ///
115    /// # Panics
116    ///
117    /// Panics if a health check of type `T` is already registered. Guard with
118    /// [`has_health_check`](AddHealthCheckExt::has_health_check) when the same
119    /// type may be registered more than once; to run several checks of the same
120    /// kind, make the type itself aggregate them.
121    fn add_health_check<T>(&self, health_check: impl Into<Arc<T>>)
122    where
123        T: HealthCheck + 'static;
124
125    /// Returns whether a health check of type `T` is registered.
126    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
153/// Registers health checks resolved from the dependency-injection container.
154///
155/// The check type `T` is a [`Service`], built by the container and registered as
156/// a [`HealthCheck`]. The service is added automatically if not already present.
157pub trait AddHealthCheckServiceExt {
158    /// Registers the [`Service`] `T` as a health check on the control server.
159    ///
160    /// # Panics
161    ///
162    /// Panics if `T` is already registered as a health-check service. Building
163    /// the [`App`] additionally panics if `T` is registered both as a service
164    /// and as an instance via [`AddHealthCheckExt::add_health_check`].
165    fn add_health_check_service<T>(&mut self) -> &mut Self
166    where
167        T: Service<Handle = Arc<T>> + HealthCheck + 'static;
168
169    /// Returns whether `T` is registered as a health-check service.
170    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/// Client for probing a service's `/health` endpoint over HTTP.
196///
197/// The [`ControlServerPlugin`] registers a `HealthClient` component pointed at
198/// its own health endpoint; it can also be built directly with
199/// [`new`](HealthClient::new) to probe a remote service (for example to wait for
200/// a dependency to become ready).
201#[derive(Clone)]
202pub struct HealthClient {
203    client: reqwest::Client,
204    endpoint: String,
205}
206
207impl HealthClient {
208    /// Creates a client that probes `endpoint`.
209    ///
210    /// `endpoint` must be the full health URL, for example
211    /// `http://127.0.0.1:8080/health`.
212    pub fn new(endpoint: String) -> Self {
213        Self {
214            client: reqwest::Client::new(),
215            endpoint,
216        }
217    }
218
219    /// Performs a single health probe.
220    ///
221    /// # Errors
222    ///
223    /// Returns a [`HealthCheckError`] if the request cannot be sent or the
224    /// endpoint responds with a non-success status.
225    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    /// Polls the endpoint until it reports healthy or `timeout` elapses,
247    /// retrying every 100 ms.
248    ///
249    /// # Errors
250    ///
251    /// Returns the last [`HealthCheckError`] if the endpoint is still not healthy
252    /// when `timeout` elapses.
253    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/// Router exposing `GET /health` on the control server.
270///
271/// Aggregates every registered [`HealthCheck`]: the endpoint returns `200` with
272/// body `healthy` when all checks pass, or `500` with a JSON [`HealthCheckError`]
273/// naming the first check that failed. Register it with
274/// [`add_control_router_service`](crate::AddControlRouterServiceExt::add_control_router_service);
275/// it relies on [`ControlServerPlugin`] for the health-check registry.
276#[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/// Error reported by a failed health check: the failing check's name and a
313/// message.
314///
315/// Serializes to JSON and renders as an HTTP `500` response.
316#[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/// Router exposing `GET /ping`, which always returns `pong`.
333///
334/// A trivial liveness endpoint; register it as a router on either server.
335#[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}