//! HTTP server wiring — composes the static bundle, the HTTP proxy, and the //! WS proxy into a single axum router. use axum::extract::{Request, State, WebSocketUpgrade}; use axum::response::{IntoResponse, Response}; use axum::routing::{any, get}; use axum::Router; use maestro_protocol::routes::{self, UrlError}; use crate::config::WebConfig; use crate::proxy::{pump_ws, upstream_ws_url, ProxyState, UpstreamConfig}; use crate::static_bundle; /// Build the public router. The returned router is ready to hand to /// `axum::serve`. pub fn router(config: &WebConfig) -> Result { let upstream = UpstreamConfig::from_daemon_url(&config.daemon_url)?; let proxy_state = ProxyState::new(upstream); // Mount each route at its real path (not under `nest`, which would strip // the `/api` prefix before the proxy could forward it). WS routes go // first so the HTTP fallback doesn't shadow them. Ok(Router::new() .route(routes::patterns::ATTACH, any(ws_proxy)) .route(routes::EVENTS, any(ws_proxy)) .route("/", get(serve_index)) .fallback(catch_all) .with_state(proxy_state)) } /// Default handler: `/api/*` goes to the daemon, anything else falls through /// to the embedded SPA bundle (with SPA-style fallback to `index.html`). async fn catch_all(State(state): State, req: Request) -> Response { if is_api_path(req.uri().path()) { return crate::proxy::proxy_http(State(state), req).await; } static_bundle::serve_path(req.uri().path()) } /// Split point between the proxied daemon surface and the SPA bundle. A daemon /// route added outside [`routes::API_PREFIX`] would silently be answered with /// `index.html` instead of being forwarded. fn is_api_path(path: &str) -> bool { path.starts_with(&format!("{}/", routes::API_PREFIX)) } async fn ws_proxy(State(state): State, ws: WebSocketUpgrade, req: Request) -> Response { let upstream_url = upstream_ws_url(&state, req.uri()); ws.on_upgrade(move |socket| async move { pump_ws(socket, upstream_url).await; }) } async fn serve_index() -> Response { static_bundle::serve_index().into_response() }