use std::{fmt::Display, future::Future, sync::Arc, time::Duration};
use axum::{
http::{
header::{CACHE_CONTROL, CONTENT_TYPE},
HeaderValue, StatusCode,
},
response::{IntoResponse, Response},
routing::{get, MethodRouter},
Router,
};
pub const DEFAULT_READINESS_TIMEOUT: Duration = Duration::from_secs(2);
const READY_BODY: &str = "ready\n";
const NOT_READY_BODY: &str = "not ready\n";
const NO_STORE: HeaderValue = HeaderValue::from_static("no-store");
const TEXT_PLAIN_UTF_8: HeaderValue = HeaderValue::from_static("text/plain; charset=utf-8");
pub struct Readiness<P> {
name: &'static str,
probe: P,
timeout: Duration,
}
impl<P> Readiness<P> {
pub const fn new(name: &'static str, probe: P) -> Self {
Self {
name,
probe,
timeout: DEFAULT_READINESS_TIMEOUT,
}
}
pub const fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
pub fn into_route<Fut, E>(self) -> MethodRouter
where
P: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), E>> + Send + 'static,
E: Display + Send + 'static,
{
let Self {
name,
probe,
timeout,
} = self;
let probe = Arc::new(probe);
get(move || {
let probe = Arc::clone(&probe);
async move { run_probe(name, timeout, probe).await }
})
}
pub fn into_router<Fut, E>(self) -> Router
where
P: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), E>> + Send + 'static,
E: Display + Send + 'static,
{
Router::new().route("/readyz", self.into_route())
}
}
async fn run_probe<P, Fut, E>(name: &'static str, timeout: Duration, probe: Arc<P>) -> Response
where
P: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), E>> + Send + 'static,
E: Display + Send + 'static,
{
match tokio::time::timeout(timeout, (probe.as_ref())()).await {
Ok(Ok(())) => readiness_response(StatusCode::OK, READY_BODY),
Ok(Err(error)) => {
tracing::warn!(
probe = name,
error = %error,
"readiness dependency probe failed"
);
readiness_response(StatusCode::SERVICE_UNAVAILABLE, NOT_READY_BODY)
}
Err(_) => {
tracing::warn!(
probe = name,
timeout_ms = timeout.as_millis(),
"readiness dependency probe timed out"
);
readiness_response(StatusCode::SERVICE_UNAVAILABLE, NOT_READY_BODY)
}
}
}
fn readiness_response(status: StatusCode, body: &'static str) -> Response {
(
status,
[(CACHE_CONTROL, NO_STORE), (CONTENT_TYPE, TEXT_PLAIN_UTF_8)],
body,
)
.into_response()
}