use std::sync::{Arc, Mutex, OnceLock};
use std::time::Instant;
use axum::Json;
use axum::Router;
use axum::extract::{Request, State};
use axum::http::{Method, StatusCode, header};
use axum::response::{IntoResponse, Response};
use chrono::{DateTime, Utc};
use serde_json::json;
use tokio::net::TcpListener;
use tower::ServiceExt;
pub const RETRY_AFTER_SECS: u64 = 5;
pub struct Startup {
since: DateTime<Utc>,
phase: Mutex<Phase>,
app: OnceLock<Router>,
}
struct Phase {
what: String,
began: Instant,
}
impl Startup {
pub fn new() -> Arc<Self> {
Arc::new(Startup {
since: Utc::now(),
phase: Mutex::new(Phase {
what: "starting up".to_string(),
began: Instant::now(),
}),
app: OnceLock::new(),
})
}
pub fn phase(&self, what: impl Into<String>) {
let what = what.into();
tracing::info!("startup: {what}");
*self.phase.lock().unwrap_or_else(|e| e.into_inner()) = Phase {
what,
began: Instant::now(),
};
}
pub fn reason(&self) -> Option<String> {
self.current().err()
}
pub fn ready(&self, app: Router) {
if self.app.set(app).is_err() {
tracing::warn!("startup handed over the app twice; keeping the first");
}
}
pub async fn serve(self: Arc<Self>, listener: TcpListener) -> std::io::Result<()> {
axum::serve(listener, self.router()).await
}
pub fn router(self: Arc<Self>) -> Router {
Router::new().fallback(gate).with_state(self)
}
fn current(&self) -> Result<Router, String> {
if let Some(app) = self.app.get() {
return Ok(app.clone());
}
let phase = self.phase.lock().unwrap_or_else(|e| e.into_inner());
Err(format!(
"{}, {}s so far",
phase.what,
phase.began.elapsed().as_secs()
))
}
}
async fn gate(State(startup): State<Arc<Startup>>, request: Request) -> Response {
let reason = match startup.current() {
Ok(app) => {
return match app.oneshot(request).await {
Ok(response) => response,
Err(never) => match never {},
};
}
Err(reason) => reason,
};
let health = request.uri().path() == "/health"
&& matches!(*request.method(), Method::GET | Method::HEAD);
if health {
return Json(json!({
"status": "starting",
"version": env!("CARGO_PKG_VERSION"),
"state": "starting",
"reason": reason,
"since": startup.since.to_rfc3339(),
"serving": {"state": "starting", "reason": reason},
}))
.into_response();
}
(
StatusCode::SERVICE_UNAVAILABLE,
[(header::RETRY_AFTER, RETRY_AFTER_SECS.to_string())],
Json(json!({"error": format!("the daemon is starting: {reason}")})),
)
.into_response()
}