allsource_core/infrastructure/web/
boot_gate.rs1use axum::{
6 Json, Router,
7 extract::Request,
8 http::{StatusCode, header},
9 response::{IntoResponse, Response},
10};
11use std::sync::{Arc, OnceLock};
12use tower::Service;
13
14#[derive(Default)]
15pub struct BootGate {
16 app: OnceLock<Router>,
17}
18
19impl BootGate {
20 pub fn new() -> Arc<Self> {
21 Arc::new(Self::default())
22 }
23
24 pub fn open(&self, app: Router) {
26 if self.app.set(app).is_err() {
27 tracing::warn!("boot gate opened twice; keeping the first router");
28 }
29 }
30
31 pub fn is_open(&self) -> bool {
32 self.app.get().is_some()
33 }
34
35 pub fn router(self: &Arc<Self>) -> Router {
37 let gate = Arc::clone(self);
38 Router::new().fallback(move |request: Request| {
39 let gate = Arc::clone(&gate);
40 async move {
41 let Some(app) = gate.app.get() else {
42 return not_ready();
43 };
44 match app.clone().call(request).await {
45 Ok(response) => response,
46 Err(never) => match never {},
47 }
48 }
49 })
50 }
51}
52
53pub fn not_ready() -> Response {
54 (
55 StatusCode::SERVICE_UNAVAILABLE,
56 [(header::RETRY_AFTER, "1")],
57 Json(serde_json::json!({
58 "error": "not_ready",
59 "message": "Core is starting; retry shortly.",
60 })),
61 )
62 .into_response()
63}