capy-framework 0.10.0

An opinionated full-stack Rust web framework with strong conventions and sensible defaults.
Documentation
use crate::Context;
use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
};
use std::{future::Future, time::Duration};

/// JSON wire data for a bounded database readiness probe.
#[derive(Debug, serde::Serialize, capy_http::ApiSchema)]
#[schemars(crate = "capy_http::schema")]
pub struct ReadinessResponse {
    /// `ready` (HTTP 200) or `not_ready` (HTTP 503).
    pub status: &'static str,
}

/// Readiness for standard DB-backed applications, with an independent probe deadline.
/// Mount beside `health`, conventionally at `/api/ready`. Driver details never
/// enter the response. Liveness remains independent of the database.
pub async fn ready(Context(context): Context) -> Response {
    probe(
        context.db.ping(),
        Duration::from_secs(context.config.http.readiness_timeout_seconds),
    )
    .await
}

async fn probe(
    future: impl Future<Output = Result<(), sea_orm::DbErr>>,
    timeout: Duration,
) -> Response {
    let ready = matches!(tokio::time::timeout(timeout, future).await, Ok(Ok(())));
    let status = if ready {
        StatusCode::OK
    } else {
        StatusCode::SERVICE_UNAVAILABLE
    };
    (
        status,
        axum::Json(ReadinessResponse {
            status: if ready { "ready" } else { "not_ready" },
        }),
    )
        .into_response()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn stalled_database_probe_is_independently_bounded() {
        let response = tokio::time::timeout(
            Duration::from_secs(1),
            probe(std::future::pending(), Duration::from_millis(10)),
        )
        .await
        .unwrap();
        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
        let body = axum::body::to_bytes(response.into_body(), 1024)
            .await
            .unwrap();
        assert_eq!(&body[..], br#"{"status":"not_ready"}"#);
    }
}