use axum::{Json, Router, extract::State, http::StatusCode, response::IntoResponse, routing::get};
use serde_json::json;
use std::{future::Future, pin::Pin, sync::Arc};
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
pub type Check = Arc<dyn Fn() -> BoxFuture<'static, Result<(), String>> + Send + Sync>;
pub(crate) fn router(checks: Vec<(String, Check)>) -> Router {
Router::new()
.route("/healthz", get(|| async { "ok" }))
.route("/readyz", get(ready))
.with_state(Arc::new(checks))
}
async fn ready(State(checks): State<Arc<Vec<(String, Check)>>>) -> impl IntoResponse {
let mut failed = vec![];
for (name, check) in checks.iter() {
if let Err(e) = check().await {
tracing::warn!(check = %name, "readiness check failed: {e}");
failed.push(name.as_str());
}
}
if failed.is_empty() {
(StatusCode::OK, Json(json!({"status": "ok"})))
} else {
(
StatusCode::SERVICE_UNAVAILABLE,
Json(json!({"status": "unavailable", "failed": failed})),
)
}
}