use axum::{
Json,
http::{StatusCode, header::CACHE_CONTROL},
response::{IntoResponse, Response},
};
use serde::Serialize;
use crate::observability::{HealthCheck, HealthReport, HealthState};
#[derive(Serialize)]
struct PublicHealthReport<'a> {
service: &'a str,
state: HealthState,
checks: Vec<PublicHealthCheck<'a>>,
}
impl<'a> From<&'a HealthReport> for PublicHealthReport<'a> {
fn from(report: &'a HealthReport) -> Self {
Self {
service: report.service(),
state: report.state(),
checks: report
.checks()
.iter()
.map(PublicHealthCheck::from)
.collect(),
}
}
}
#[derive(Serialize)]
struct PublicHealthCheck<'a> {
name: &'a str,
state: HealthState,
}
impl<'a> From<&'a HealthCheck> for PublicHealthCheck<'a> {
fn from(check: &'a HealthCheck) -> Self {
Self {
name: check.name(),
state: check.state(),
}
}
}
#[derive(Debug, Clone)]
pub struct HealthResponse {
report: HealthReport,
}
impl HealthResponse {
#[must_use]
pub fn new(report: HealthReport) -> Self {
Self { report }
}
#[must_use]
pub fn report(&self) -> &HealthReport {
&self.report
}
#[must_use]
pub const fn status_code_for_state(state: HealthState) -> StatusCode {
match state {
HealthState::Serving | HealthState::Degraded => StatusCode::OK,
HealthState::Unavailable => StatusCode::SERVICE_UNAVAILABLE,
}
}
}
impl IntoResponse for HealthResponse {
fn into_response(self) -> Response {
let status = Self::status_code_for_state(self.report.state());
let report = PublicHealthReport::from(&self.report);
(status, [(CACHE_CONTROL, "no-store")], Json(report)).into_response()
}
}
#[cfg(test)]
mod tests {
use axum::{
Router,
body::{Body, to_bytes},
http::{Method, Request, StatusCode, header::CACHE_CONTROL},
response::IntoResponse,
routing::get,
};
use tower::ServiceExt;
use crate::observability::{HealthCheck, HealthReport, HealthState};
use super::HealthResponse;
#[tokio::test]
async fn health_response_maps_unavailable_to_503() {
let report = HealthReport::new(
"example_service",
vec![
HealthCheck::unavailable("database", "down").expect("static health check is valid"),
],
)
.expect("static health report is valid");
let response = HealthResponse::new(report).into_response();
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(response.headers()[CACHE_CONTROL], "no-store");
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
let body = String::from_utf8_lossy(&body);
assert!(body.contains("unavailable"));
assert!(body.contains("database"));
assert!(!body.contains("down"));
assert!(!body.contains("message"));
}
#[tokio::test]
async fn all_health_states_disable_caching_for_get_and_head() {
for (state, status) in [
(HealthState::Serving, StatusCode::OK),
(HealthState::Degraded, StatusCode::OK),
(HealthState::Unavailable, StatusCode::SERVICE_UNAVAILABLE),
] {
let app = Router::new().route(
"/health",
get(move || async move {
HealthResponse::new(
HealthReport::new(
"example_service",
vec![HealthCheck::new("database", state).unwrap()],
)
.unwrap(),
)
}),
);
for method in [Method::GET, Method::HEAD] {
let response = app
.clone()
.oneshot(
Request::builder()
.method(method.clone())
.uri("/health")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), status);
assert_eq!(response.headers()[CACHE_CONTROL], "no-store");
let body = to_bytes(response.into_body(), 1024).await.unwrap();
assert_eq!(body.is_empty(), method == Method::HEAD);
}
}
}
}