use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::Arc;
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()
}
}
#[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(health): State<Health>) -> (StatusCode, Json<HealthBody>) {
let state = health.state();
let status = if state == HealthState::Ready {
StatusCode::OK
} else {
StatusCode::SERVICE_UNAVAILABLE
};
(
status,
Json(HealthBody {
status: if state == HealthState::Ready {
"ready"
} else {
"unready"
},
state: state.as_str(),
}),
)
}
pub fn health_router(health: Health) -> Router {
Router::new()
.route("/health/live", get(live))
.route("/health/ready", get(ready))
.with_state(health)
}