use std::{future::Future, pin::Pin, sync::Arc};
use poem::{Route, get, handler, http::StatusCode};
pub type ReadinessProbe = Arc<dyn Fn() -> Pin<Box<dyn Future<Output = bool> + Send>> + Send + Sync>;
pub fn probe<F, Fut>(check: F) -> ReadinessProbe
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = bool> + Send + 'static,
{
Arc::new(move || Box::pin(check()))
}
pub fn always_ready() -> ReadinessProbe {
probe(|| async { true })
}
pub fn mount(route: Route, ready: ReadinessProbe) -> Route {
route.at("/health", get(liveness)).at(
"/health/ready",
get(poem::endpoint::make(move |_| {
let ready = Arc::clone(&ready);
async move { readiness(ready().await) }
})),
)
}
#[handler]
fn liveness() -> &'static str {
"ok"
}
fn readiness(ready: bool) -> (StatusCode, &'static str) {
if ready {
(StatusCode::OK, "ready")
} else {
(StatusCode::SERVICE_UNAVAILABLE, "not ready")
}
}
#[cfg(test)]
mod tests {
use poem::test::TestClient;
use super::*;
#[tokio::test]
async fn should_answer_200_on_liveness_when_a_dependency_is_down() {
let client = TestClient::new(mount(Route::new(), probe(|| async { false })));
let response = client.get("/health").send().await;
response.assert_status_is_ok();
response.assert_text("ok").await;
}
#[tokio::test]
async fn should_answer_200_on_readiness_when_dependencies_are_ready() {
let client = TestClient::new(mount(Route::new(), always_ready()));
let response = client.get("/health/ready").send().await;
response.assert_status_is_ok();
response.assert_text("ready").await;
}
#[tokio::test]
async fn should_answer_503_on_readiness_when_a_dependency_is_down() {
let client = TestClient::new(mount(Route::new(), probe(|| async { false })));
let response = client.get("/health/ready").send().await;
response.assert_status(StatusCode::SERVICE_UNAVAILABLE);
response.assert_text("not ready").await;
}
#[tokio::test]
async fn should_ask_the_dependencies_on_every_readiness_request() {
let up = Arc::new(std::sync::atomic::AtomicBool::new(true));
let flag = Arc::clone(&up);
let client = TestClient::new(mount(
Route::new(),
probe(move || {
let flag = Arc::clone(&flag);
async move { flag.load(std::sync::atomic::Ordering::SeqCst) }
}),
));
client
.get("/health/ready")
.send()
.await
.assert_status_is_ok();
up.store(false, std::sync::atomic::Ordering::SeqCst);
let response = client.get("/health/ready").send().await;
response.assert_status(StatusCode::SERVICE_UNAVAILABLE);
}
}