From 2523ecb0180af4ed2d2d51a7c90ee77187fc4c5e Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar Date: Wed, 4 Nov 2026 08:17:15 +0000 Subject: [PATCH] fix(health): answer 503 when MongoDB does not answer (#60) (#822) --- compliance-agent/src/api/handlers/health.rs | 56 ++++++++++++++++++++- compliance-agent/src/database.rs | 14 ++++++ 2 files changed, 68 insertions(+), 2 deletions(-) diff --git a/compliance-agent/src/api/handlers/health.rs b/compliance-agent/src/api/handlers/health.rs index 3148ddc..e25c114 100644 --- a/compliance-agent/src/api/handlers/health.rs +++ b/compliance-agent/src/api/handlers/health.rs @@ -13,9 +13,44 @@ pub async fn access() -> Json { Json(serde_json::json!({ "access": true })) } +/// How long the health check waits for MongoDB before it reports it down. +const DB_PING_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2); + +/// `GET /api/v1/health`: 200 `{"status":"ok"}` when MongoDB answers a ping, +/// 503 `{"status":"degraded","mongo":"unreachable"}` when it does not, so a +/// load balancer and the container health check stop sending traffic to an +/// instance that cannot serve it (#60). Public, untraced, no tenant. #[tracing::instrument(skip_all)] -pub async fn health() -> Json { - Json(serde_json::json!({ "status": "ok" })) +pub async fn health( + axum::extract::Extension(agent): AgentExt, +) -> (axum::http::StatusCode, Json) { + let reachable = match tokio::time::timeout(DB_PING_TIMEOUT, agent.db_pool.ping()).await { + Ok(Ok(())) => true, + Ok(Err(e)) => { + tracing::warn!(error = %e, "health: MongoDB ping failed"); + false + } + Err(_) => { + tracing::warn!("health: MongoDB ping timed out"); + false + } + }; + health_answer(reachable) +} + +/// The health answer for whether MongoDB answered. +fn health_answer(mongo_reachable: bool) -> (axum::http::StatusCode, Json) { + if mongo_reachable { + ( + axum::http::StatusCode::OK, + Json(serde_json::json!({ "status": "ok" })), + ) + } else { + ( + axum::http::StatusCode::SERVICE_UNAVAILABLE, + Json(serde_json::json!({ "status": "degraded", "mongo": "unreachable" })), + ) + } } /// Findings that still need someone's attention: not resolved, not a false @@ -128,3 +163,20 @@ pub async fn stats_overview( page: None, })) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_health_answer_follows_the_database() { + let (status, Json(body)) = health_answer(true); + assert_eq!(status, axum::http::StatusCode::OK); + assert_eq!(body, serde_json::json!({ "status": "ok" })); + + let (status, Json(body)) = health_answer(false); + assert_eq!(status, axum::http::StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(body["status"], "degraded"); + assert_eq!(body["mongo"], "unreachable"); + } +} diff --git a/compliance-agent/src/database.rs b/compliance-agent/src/database.rs index 81a4a89..adec508 100644 --- a/compliance-agent/src/database.rs +++ b/compliance-agent/src/database.rs @@ -168,6 +168,20 @@ impl DatabasePool { } } + /// Ask MongoDB whether it answers (`ping` on the `admin` database), for + /// the health check. + /// + /// # Errors + /// + /// The driver's error when the server cannot be reached or refuses. + pub async fn ping(&self) -> Result<(), mongodb::error::Error> { + self.client + .database("admin") + .run_command(doc! { "ping": 1 }) + .await + .map(|_| ()) + } + /// Raw client handle. Reserved for cross-tenant admin flows that /// must opt in explicitly (tenant listing, drop-on-offboard). pub fn client(&self) -> &Client {