capy_framework/
readiness.rs1use crate::Context;
2use axum::{
3 http::StatusCode,
4 response::{IntoResponse, Response},
5};
6use std::{future::Future, time::Duration};
7
8#[derive(Debug, serde::Serialize, capy_http::ApiSchema)]
10#[schemars(crate = "capy_http::schema")]
11pub struct ReadinessResponse {
12 pub status: &'static str,
14}
15
16pub async fn ready(Context(context): Context) -> Response {
20 probe(
21 context.db.ping(),
22 Duration::from_secs(context.config.http.readiness_timeout_seconds),
23 )
24 .await
25}
26
27async fn probe(
28 future: impl Future<Output = Result<(), sea_orm::DbErr>>,
29 timeout: Duration,
30) -> Response {
31 let ready = matches!(tokio::time::timeout(timeout, future).await, Ok(Ok(())));
32 let status = if ready {
33 StatusCode::OK
34 } else {
35 StatusCode::SERVICE_UNAVAILABLE
36 };
37 (
38 status,
39 axum::Json(ReadinessResponse {
40 status: if ready { "ready" } else { "not_ready" },
41 }),
42 )
43 .into_response()
44}
45
46#[cfg(test)]
47mod tests {
48 use super::*;
49
50 #[tokio::test]
51 async fn stalled_database_probe_is_independently_bounded() {
52 let response = tokio::time::timeout(
53 Duration::from_secs(1),
54 probe(std::future::pending(), Duration::from_millis(10)),
55 )
56 .await
57 .unwrap();
58 assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
59 let body = axum::body::to_bytes(response.into_body(), 1024)
60 .await
61 .unwrap();
62 assert_eq!(&body[..], br#"{"status":"not_ready"}"#);
63 }
64}