use axum::Router;
use axum::extract::{FromRef, Path, State};
use axum::http::header;
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use redup_abstractions::Phase;
use crate::listener::SnapshotSource;
use crate::probes::probe_outcome::ProbeOutcome;
use crate::snapshot::Snapshot;
mod probe_outcome;
#[cfg(test)]
mod tests;
const CONTENT_TYPE: &str = "text/plain; charset=utf-8";
pub(crate) fn router<S>() -> Router<S>
where
S: Clone + Send + Sync + 'static,
SnapshotSource: FromRef<S>,
{
Router::new()
.route("/readyz", get(readiness))
.route("/health", get(readiness))
.route("/healthz", get(readiness))
.route("/readyz/{name}", get(readiness_module))
.route("/livez", get(liveness))
.route("/livez/{name}", get(liveness_module))
}
async fn readiness(State(source): State<SnapshotSource>) -> Response {
let view = source();
reply(ProbeOutcome::for_readiness(view.readiness()))
}
async fn readiness_module(
State(source): State<SnapshotSource>,
Path(name): Path<String>,
) -> Response {
let view = source();
reply(module_outcome(&view, &name, ProbeOutcome::for_readiness))
}
async fn liveness(State(source): State<SnapshotSource>) -> Response {
let view = source();
reply(ProbeOutcome::for_liveness(view.liveness()))
}
async fn liveness_module(
State(source): State<SnapshotSource>,
Path(name): Path<String>,
) -> Response {
let view = source();
reply(module_outcome(&view, &name, ProbeOutcome::for_liveness))
}
fn module_outcome(view: &Snapshot, name: &str, gate: fn(Phase) -> ProbeOutcome) -> ProbeOutcome {
match view.modules().iter().find(|module| module.name() == name) {
Some(module) => gate(module.phase()),
None => ProbeOutcome::not_found(),
}
}
fn reply(outcome: ProbeOutcome) -> Response {
(
outcome.status(),
[(header::CONTENT_TYPE, CONTENT_TYPE)],
outcome.body(),
)
.into_response()
}