use crate::operator::Operator;
use axum::Router;
use axum::extract::State;
use axum::http::StatusCode;
use axum::routing::get;
use std::sync::Arc;
use std::time::Duration;
pub const READY_TIMEOUT: Duration = Duration::from_secs(2);
pub fn router(operator: Arc<Operator>) -> Router {
Router::new()
.route("/healthz", get(|| async { "ok" }))
.route("/readyz", get(ready))
.with_state(operator)
}
async fn ready(State(operator): State<Arc<Operator>>) -> (StatusCode, &'static str) {
let ping = tokio::task::spawn_blocking(move || operator.ping());
let why = match tokio::time::timeout(READY_TIMEOUT, ping).await {
Ok(Ok(Ok(()))) => return (StatusCode::OK, "ready"),
Ok(Ok(Err(err))) => format!("{err:#}"),
Ok(Err(err)) => err.to_string(),
Err(_) => format!("no answer within {READY_TIMEOUT:?}"),
};
tracing::warn!(error = %why, "readyz: the database does not answer");
(StatusCode::SERVICE_UNAVAILABLE, "not ready")
}