use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use axum::extract::State;
use axum::http::StatusCode;
use axum::routing::get;
use axum::{Json, Router};
use serde::Serialize;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HealthState {
Starting,
Ready,
Draining,
}
impl HealthState {
pub fn as_str(self) -> &'static str {
match self {
HealthState::Starting => "starting",
HealthState::Ready => "ready",
HealthState::Draining => "draining",
}
}
fn from_u8(value: u8) -> Self {
match value {
1 => HealthState::Ready,
2 => HealthState::Draining,
_ => HealthState::Starting,
}
}
fn as_u8(self) -> u8 {
match self {
HealthState::Starting => 0,
HealthState::Ready => 1,
HealthState::Draining => 2,
}
}
}
#[derive(Debug, Clone)]
pub struct Health {
state: Arc<AtomicU8>,
}
impl Health {
pub fn starting() -> Self {
Self {
state: Arc::new(AtomicU8::new(HealthState::Starting.as_u8())),
}
}
pub fn state(&self) -> HealthState {
HealthState::from_u8(self.state.load(Ordering::SeqCst))
}
pub fn set(&self, state: HealthState) {
self.state.store(state.as_u8(), Ordering::SeqCst);
}
pub fn set_ready(&self) {
self.set(HealthState::Ready);
}
pub fn set_draining(&self) {
self.set(HealthState::Draining);
}
pub fn is_ready(&self) -> bool {
self.state() == HealthState::Ready
}
}
impl Default for Health {
fn default() -> Self {
Self::starting()
}
}
pub type ReadinessCheck = Arc<dyn Fn() -> Pin<Box<dyn Future<Output = bool> + Send>> + Send + Sync>;
#[derive(Clone)]
struct ReadinessDep {
check: ReadinessCheck,
ttl: Duration,
cache: Arc<Mutex<Option<(Instant, bool)>>>,
}
impl ReadinessDep {
async fn healthy(&self) -> bool {
if let Some((at, ok)) = *self.cache.lock().unwrap_or_else(|e| e.into_inner()) {
if at.elapsed() < self.ttl {
return ok;
}
}
let ok = (self.check)().await;
*self.cache.lock().unwrap_or_else(|e| e.into_inner()) = Some((Instant::now(), ok));
ok
}
}
#[derive(Clone)]
struct ReadyState {
health: Health,
dep: Option<ReadinessDep>,
}
#[derive(Debug, Serialize)]
struct HealthBody {
status: &'static str,
state: &'static str,
}
async fn live(State(health): State<Health>) -> (StatusCode, Json<HealthBody>) {
(
StatusCode::OK,
Json(HealthBody {
status: "live",
state: health.state().as_str(),
}),
)
}
async fn ready(State(state): State<ReadyState>) -> (StatusCode, Json<HealthBody>) {
let lifecycle = state.health.state();
if lifecycle != HealthState::Ready {
return unready(lifecycle);
}
match &state.dep {
Some(dep) if !dep.healthy().await => (
StatusCode::SERVICE_UNAVAILABLE,
Json(HealthBody {
status: "unready",
state: "dependency-unready",
}),
),
_ => (
StatusCode::OK,
Json(HealthBody {
status: "ready",
state: lifecycle.as_str(),
}),
),
}
}
fn unready(state: HealthState) -> (StatusCode, Json<HealthBody>) {
(
StatusCode::SERVICE_UNAVAILABLE,
Json(HealthBody {
status: "unready",
state: state.as_str(),
}),
)
}
pub fn health_router(health: Health) -> Router {
build_router(health, None)
}
pub fn health_router_with_dependency(
health: Health,
check: ReadinessCheck,
ttl: Duration,
) -> Router {
build_router(
health,
Some(ReadinessDep {
check,
ttl,
cache: Arc::new(Mutex::new(None)),
}),
)
}
fn build_router(health: Health, dep: Option<ReadinessDep>) -> Router {
let live_route = Router::new()
.route("/health/live", get(live))
.with_state(health.clone());
let ready_route = Router::new()
.route("/health/ready", get(ready))
.with_state(ReadyState { health, dep });
live_route.merge(ready_route)
}
#[cfg(test)]
mod tests {
use super::*;
use axum::body::Body;
use axum::http::Request;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use tower::ServiceExt;
async fn status(router: &Router, path: &str) -> StatusCode {
router
.clone()
.oneshot(Request::builder().uri(path).body(Body::empty()).unwrap())
.await
.unwrap()
.status()
}
#[tokio::test]
async fn readiness_reflects_the_dependency_but_liveness_ignores_it() {
let health = Health::starting();
health.set_ready();
let healthy = Arc::new(AtomicBool::new(true));
let flag = healthy.clone();
let check: ReadinessCheck = Arc::new(move || {
let flag = flag.clone();
Box::pin(async move { flag.load(Ordering::SeqCst) })
});
let app = health_router_with_dependency(health, check, Duration::ZERO);
assert_eq!(status(&app, "/health/ready").await, StatusCode::OK);
healthy.store(false, Ordering::SeqCst);
assert_eq!(
status(&app, "/health/ready").await,
StatusCode::SERVICE_UNAVAILABLE
);
assert_eq!(status(&app, "/health/live").await, StatusCode::OK);
healthy.store(true, Ordering::SeqCst);
assert_eq!(status(&app, "/health/ready").await, StatusCode::OK);
}
#[tokio::test]
async fn the_dependency_check_is_cached_within_its_ttl() {
let health = Health::starting();
health.set_ready();
let calls = Arc::new(AtomicUsize::new(0));
let counter = calls.clone();
let check: ReadinessCheck = Arc::new(move || {
counter.fetch_add(1, Ordering::SeqCst);
Box::pin(async { true })
});
let app = health_router_with_dependency(health, check, Duration::from_secs(300));
for _ in 0..5 {
assert_eq!(status(&app, "/health/ready").await, StatusCode::OK);
}
assert_eq!(
calls.load(Ordering::SeqCst),
1,
"the dependency is probed once within the TTL, not per request"
);
}
#[tokio::test]
async fn readiness_without_a_dependency_tracks_only_the_lifecycle() {
let health = Health::starting();
let app = health_router(health.clone());
assert_eq!(
status(&app, "/health/ready").await,
StatusCode::SERVICE_UNAVAILABLE
);
health.set_ready();
assert_eq!(status(&app, "/health/ready").await, StatusCode::OK);
health.set_draining();
assert_eq!(
status(&app, "/health/ready").await,
StatusCode::SERVICE_UNAVAILABLE
);
assert_eq!(status(&app, "/health/live").await, StatusCode::OK);
}
}