#![allow(clippy::unwrap_used, clippy::expect_used)]
use std::sync::{Arc, Mutex, PoisonError};
use crate::listener::SnapshotSource;
use crate::probes::router;
use crate::snapshot::{ModuleSnapshot, Snapshot};
use axum::Router;
use axum::body::Body;
use axum::http::{Method, Request, StatusCode};
use redup_abstractions::Phase;
use tower::ServiceExt;
const READY_PATHS: [&str; 3] = ["/readyz", "/health", "/healthz"];
const CONTENT_TYPE: &str = "text/plain; charset=utf-8";
#[derive(Clone)]
struct Cell(Arc<Mutex<Snapshot>>);
impl Cell {
fn of(view: Snapshot) -> Self {
Self(Arc::new(Mutex::new(view)))
}
fn set(&self, view: Snapshot) {
*self.0.lock().unwrap_or_else(PoisonError::into_inner) = view;
}
fn source(&self) -> SnapshotSource {
let cell = Arc::clone(&self.0);
Arc::new(move || cell.lock().unwrap_or_else(PoisonError::into_inner).clone())
}
fn router(&self) -> Router {
router().with_state(self.source())
}
}
fn snapshot(readiness: Phase, liveness: Phase) -> Cell {
Cell::of(Snapshot::new(
readiness,
liveness,
vec![ModuleSnapshot::new("worker", Phase::Serving)],
))
}
async fn probe(router: &Router, method: Method, uri: &str) -> (StatusCode, String, String) {
let request = Request::builder()
.method(method)
.uri(uri)
.body(Body::empty())
.expect("static probe request is always valid");
let response = router
.clone()
.oneshot(request)
.await
.unwrap_or_else(|never| match never {});
let status = response.status();
let content_type = response
.headers()
.get("content-type")
.map(|value| value.to_str().unwrap().to_owned())
.unwrap_or_default();
let bytes = http_body_util::BodyExt::collect(response.into_body())
.await
.expect("probe body is a static string")
.to_bytes();
let body = String::from_utf8(bytes.to_vec()).expect("probe body is utf-8");
(status, content_type, body)
}
async fn get(router: &Router, uri: &str) -> (StatusCode, String, String) {
probe(router, Method::GET, uri).await
}
#[tokio::test]
async fn readiness_serving_is_success_on_all_paths() {
let snapshot = snapshot(Phase::Serving, Phase::Serving);
for uri in READY_PATHS {
let (status, content_type, body) = get(&snapshot.router(), uri).await;
assert_eq!(status, StatusCode::OK, "uri: {uri}");
assert_eq!(content_type, CONTENT_TYPE, "uri: {uri}");
assert_eq!(body, "Success", "uri: {uri}");
}
}
#[tokio::test]
async fn readiness_non_serving_phase_is_failed_on_all_paths() {
for phase in [
Phase::Unknown,
Phase::Starting,
Phase::NotServing,
Phase::Failed,
] {
let snapshot = snapshot(phase, Phase::Serving);
for uri in READY_PATHS {
let (status, content_type, body) = get(&snapshot.router(), uri).await;
assert_eq!(
status,
StatusCode::SERVICE_UNAVAILABLE,
"phase: {phase:?}, uri: {uri}"
);
assert_eq!(content_type, CONTENT_TYPE, "phase: {phase:?}, uri: {uri}");
assert_eq!(body, "Failed", "phase: {phase:?}, uri: {uri}");
}
}
}
#[tokio::test]
async fn readiness_module_phase_gates_answer() {
for (phase, expected) in [
(Phase::Serving, (StatusCode::OK, "Success")),
(Phase::Unknown, (StatusCode::SERVICE_UNAVAILABLE, "Failed")),
(Phase::Starting, (StatusCode::SERVICE_UNAVAILABLE, "Failed")),
(
Phase::NotServing,
(StatusCode::SERVICE_UNAVAILABLE, "Failed"),
),
(Phase::Failed, (StatusCode::SERVICE_UNAVAILABLE, "Failed")),
] {
let snapshot = Cell::of(Snapshot::new(
Phase::Serving,
Phase::Serving,
vec![ModuleSnapshot::new("worker", phase)],
));
let (status, content_type, body) = get(&snapshot.router(), "/readyz/worker").await;
assert_eq!(status, expected.0, "phase: {phase:?}");
assert_eq!(content_type, CONTENT_TYPE, "phase: {phase:?}");
assert_eq!(body, expected.1, "phase: {phase:?}");
}
}
#[tokio::test]
async fn readiness_unknown_module_is_not_found() {
let snapshot = snapshot(Phase::Serving, Phase::Serving);
let (status, content_type, body) = get(&snapshot.router(), "/readyz/absent").await;
assert_eq!(status, StatusCode::NOT_FOUND);
assert_eq!(content_type, CONTENT_TYPE);
assert_eq!(body, "Not found");
}
#[tokio::test]
async fn liveness_without_name_serves_everything_but_failed() {
for phase in [
Phase::Unknown,
Phase::Serving,
Phase::Starting,
Phase::NotServing,
] {
let snapshot = snapshot(Phase::Serving, phase);
let (status, content_type, body) = get(&snapshot.router(), "/livez").await;
assert_eq!(status, StatusCode::OK, "phase: {phase:?}");
assert_eq!(content_type, CONTENT_TYPE, "phase: {phase:?}");
assert_eq!(body, "Success", "phase: {phase:?}");
}
let snapshot = snapshot(Phase::Serving, Phase::Failed);
let (status, content_type, body) = get(&snapshot.router(), "/livez").await;
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(content_type, CONTENT_TYPE);
assert_eq!(body, "Failed");
}
#[tokio::test]
async fn liveness_with_name_serves_everything_but_failed() {
for phase in [
Phase::Unknown,
Phase::Serving,
Phase::Starting,
Phase::NotServing,
] {
let snapshot = Cell::of(Snapshot::new(
Phase::Serving,
Phase::Serving,
vec![ModuleSnapshot::new("worker", phase)],
));
let (status, content_type, body) = get(&snapshot.router(), "/livez/worker").await;
assert_eq!(status, StatusCode::OK, "phase: {phase:?}");
assert_eq!(content_type, CONTENT_TYPE, "phase: {phase:?}");
assert_eq!(body, "Success", "phase: {phase:?}");
}
let snapshot = Cell::of(Snapshot::new(
Phase::Serving,
Phase::Serving,
vec![ModuleSnapshot::new("worker", Phase::Failed)],
));
let (status, content_type, body) = get(&snapshot.router(), "/livez/worker").await;
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(content_type, CONTENT_TYPE);
assert_eq!(body, "Failed");
}
#[tokio::test]
async fn liveness_unknown_module_is_not_found() {
let snapshot = snapshot(Phase::Serving, Phase::Serving);
let (status, content_type, body) = get(&snapshot.router(), "/livez/absent").await;
assert_eq!(status, StatusCode::NOT_FOUND);
assert_eq!(content_type, CONTENT_TYPE);
assert_eq!(body, "Not found");
}
#[tokio::test]
async fn head_is_served_like_get() {
let snapshot = snapshot(Phase::Serving, Phase::Serving);
for uri in ["/readyz", "/livez", "/readyz/worker", "/livez/worker"] {
let (status, content_type, body) = probe(&snapshot.router(), Method::HEAD, uri).await;
assert_eq!(status, StatusCode::OK, "uri: {uri}");
assert_eq!(content_type, CONTENT_TYPE, "uri: {uri}");
assert_eq!(body, "", "uri: {uri}");
}
}
#[tokio::test]
async fn post_is_method_not_allowed() {
let snapshot = snapshot(Phase::Serving, Phase::Serving);
for uri in [
"/readyz",
"/health",
"/healthz",
"/livez",
"/readyz/worker",
"/livez/worker",
] {
let (status, _content_type, _body) = probe(&snapshot.router(), Method::POST, uri).await;
assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED, "uri: {uri}");
}
}
#[tokio::test]
async fn unknown_path_is_not_found() {
let snapshot = snapshot(Phase::Serving, Phase::Serving);
for uri in ["/nope", "/readyz/worker/extra"] {
let (status, _content_type, _body) = get(&snapshot.router(), uri).await;
assert_eq!(status, StatusCode::NOT_FOUND, "uri: {uri}");
}
}
#[tokio::test]
async fn empty_module_name_does_not_match() {
let snapshot = snapshot(Phase::Serving, Phase::Serving);
for uri in ["/readyz/", "/livez/"] {
let (status, _content_type, _body) = get(&snapshot.router(), uri).await;
assert_eq!(status, StatusCode::NOT_FOUND, "uri: {uri}");
}
}
#[tokio::test]
async fn source_is_read_on_every_request() {
let holder = Cell::of(Snapshot::new(
Phase::Serving,
Phase::Serving,
vec![ModuleSnapshot::new("worker", Phase::Serving)],
));
let router = holder.router();
let (status, _content_type, body) = get(&router, "/readyz").await;
assert_eq!((status, body.as_str()), (StatusCode::OK, "Success"));
holder.set(Snapshot::new(
Phase::NotServing,
Phase::Failed,
vec![ModuleSnapshot::new("worker", Phase::Failed)],
));
let (status, _content_type, body) = get(&router, "/readyz").await;
assert_eq!(
(status, body.as_str()),
(StatusCode::SERVICE_UNAVAILABLE, "Failed")
);
let (status, _content_type, body) = get(&router, "/livez").await;
assert_eq!(
(status, body.as_str()),
(StatusCode::SERVICE_UNAVAILABLE, "Failed")
);
let (status, _content_type, body) = get(&router, "/livez/worker").await;
assert_eq!(
(status, body.as_str()),
(StatusCode::SERVICE_UNAVAILABLE, "Failed")
);
}