second_brain_api/
startup.rs1use std::sync::{Arc, Mutex, OnceLock};
5use std::time::Instant;
6
7use axum::Json;
8use axum::Router;
9use axum::extract::{Request, State};
10use axum::http::{Method, StatusCode, header};
11use axum::response::{IntoResponse, Response};
12use chrono::{DateTime, Utc};
13use serde_json::json;
14use tokio::net::TcpListener;
15use tower::ServiceExt;
16
17pub const RETRY_AFTER_SECS: u64 = 5;
18
19pub struct Startup {
20 since: DateTime<Utc>,
21 phase: Mutex<Phase>,
22 app: OnceLock<Router>,
23}
24
25struct Phase {
26 what: String,
27 began: Instant,
28}
29
30impl Startup {
31 pub fn new() -> Arc<Self> {
32 Arc::new(Startup {
33 since: Utc::now(),
34 phase: Mutex::new(Phase {
35 what: "starting up".to_string(),
36 began: Instant::now(),
37 }),
38 app: OnceLock::new(),
39 })
40 }
41
42 pub fn phase(&self, what: impl Into<String>) {
43 let what = what.into();
44 tracing::info!("startup: {what}");
45 *self.phase.lock().unwrap_or_else(|e| e.into_inner()) = Phase {
46 what,
47 began: Instant::now(),
48 };
49 }
50
51 pub fn reason(&self) -> Option<String> {
53 self.current().err()
54 }
55
56 pub fn ready(&self, app: Router) {
58 if self.app.set(app).is_err() {
59 tracing::warn!("startup handed over the app twice; keeping the first");
60 }
61 }
62
63 pub async fn serve(self: Arc<Self>, listener: TcpListener) -> std::io::Result<()> {
64 axum::serve(listener, self.router()).await
65 }
66
67 pub fn router(self: Arc<Self>) -> Router {
68 Router::new().fallback(gate).with_state(self)
69 }
70
71 fn current(&self) -> Result<Router, String> {
72 if let Some(app) = self.app.get() {
73 return Ok(app.clone());
74 }
75 let phase = self.phase.lock().unwrap_or_else(|e| e.into_inner());
76 Err(format!(
77 "{}, {}s so far",
78 phase.what,
79 phase.began.elapsed().as_secs()
80 ))
81 }
82}
83
84async fn gate(State(startup): State<Arc<Startup>>, request: Request) -> Response {
85 let reason = match startup.current() {
86 Ok(app) => {
87 return match app.oneshot(request).await {
88 Ok(response) => response,
89 Err(never) => match never {},
90 };
91 }
92 Err(reason) => reason,
93 };
94 let health = request.uri().path() == "/health"
95 && matches!(*request.method(), Method::GET | Method::HEAD);
96 if health {
97 return Json(json!({
98 "status": "starting",
99 "version": env!("CARGO_PKG_VERSION"),
100 "state": "starting",
101 "reason": reason,
102 "since": startup.since.to_rfc3339(),
103 "serving": {"state": "starting", "reason": reason},
104 }))
105 .into_response();
106 }
107 (
108 StatusCode::SERVICE_UNAVAILABLE,
109 [(header::RETRY_AFTER, RETRY_AFTER_SECS.to_string())],
110 Json(json!({"error": format!("the daemon is starting: {reason}")})),
111 )
112 .into_response()
113}