use crate::Context;
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
use std::{future::Future, time::Duration};
#[derive(Debug, serde::Serialize, capy_http::ApiSchema)]
#[schemars(crate = "capy_http::schema")]
pub struct ReadinessResponse {
pub status: &'static str,
}
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"}"#);
}
}