footing 0.1.18

Feature-gated foundations for Rust backend services
Documentation
use axum::{
    Json,
    http::StatusCode,
    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)]
/// A response containing health.
pub struct HealthResponse {
    report: HealthReport,
}

impl HealthResponse {
    #[must_use]
    /// Creates a new instance.
    pub fn new(report: HealthReport) -> Self {
        Self { report }
    }

    #[must_use]
    /// Returns the report.
    pub fn report(&self) -> &HealthReport {
        &self.report
    }

    #[must_use]
    /// Creates status code for state.
    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, Json(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();
        let body = String::from_utf8_lossy(&body);
        assert!(body.contains("unavailable"));
        assert!(body.contains("database"));
        assert!(!body.contains("down"));
        assert!(!body.contains("message"));
    }
}