use axum::{
Json,
http::StatusCode,
response::{IntoResponse, Response},
};
use crate::observability::{HealthReport, HealthState};
#[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 {
(
Self::status_code_for_state(self.report.state()),
Json(self.report),
)
.into_response()
}
}
#[cfg(test)]
mod tests {
use axum::{body::to_bytes, http::StatusCode, response::IntoResponse};
use crate::observability::{HealthCheck, HealthReport};
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);
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
assert!(String::from_utf8_lossy(&body).contains("unavailable"));
}
}