Skip to main content

bamboo_server/server/
web_service.rs

1use std::path::PathBuf;
2
3use actix_files as fs;
4use actix_web::{web, App, HttpServer};
5use tokio::sync::oneshot;
6use tracing::{error, info};
7
8use super::listeners::DEFAULT_WORKER_COUNT;
9use super::tls::build_rustls_config;
10use crate::app_state::AppState;
11use crate::config::{build_cors, build_rate_limiter, build_security_headers};
12use crate::routes::{configure_routes, configure_routes_with_rate_limiting};
13use actix_governor::Governor;
14use bamboo_config::TlsConfig;
15
16/// Manageable web service with start/stop lifecycle
17///
18/// Use this when you need to programmatically control the server lifecycle,
19/// such as in tests or embedded scenarios.
20pub struct WebService {
21    shutdown_tx: Option<oneshot::Sender<()>>,
22    server_handle: Option<tokio::task::JoinHandle<()>>,
23    /// Handle to the running server's [`AppState`], retained so [`WebService::stop`]
24    /// /[`Drop`] can gracefully stop AppState-owned background tasks (the #47
25    /// MCP-proxy reconnect supervisor) instead of leaking them until process exit.
26    /// #119.
27    app_state: Option<web::Data<AppState>>,
28    /// Bamboo home directory containing all application data (config, sessions, skills, etc.)
29    bamboo_home_dir: PathBuf,
30    port: u16,
31}
32
33impl WebService {
34    /// Create a new WebService instance
35    ///
36    /// # Arguments
37    /// * `bamboo_home_dir` - Bamboo home directory (e.g., `${HOME}/.bamboo` or custom path)
38    pub fn new(bamboo_home_dir: PathBuf) -> Self {
39        Self {
40            shutdown_tx: None,
41            server_handle: None,
42            app_state: None,
43            bamboo_home_dir,
44            port: 3456, // Default port
45        }
46    }
47
48    /// Start the web service on the specified port using the default localhost bind.
49    pub async fn start(&mut self, port: u16) -> Result<(), String> {
50        self.start_with_bind(port, "127.0.0.1").await
51    }
52
53    /// Start the web service on the specified port and bind address.
54    pub async fn start_with_bind(&mut self, port: u16, bind: &str) -> Result<(), String> {
55        self.start_with_bind_tls(port, bind, None).await
56    }
57
58    /// Start the web service, terminating TLS itself when `tls` is `Some` (#181).
59    ///
60    /// `None` keeps the plaintext `.bind()` path unchanged (desktop loopback).
61    pub async fn start_with_bind_tls(
62        &mut self,
63        port: u16,
64        bind: &str,
65        tls: Option<&TlsConfig>,
66    ) -> Result<(), String> {
67        info!("Starting web service...");
68        if self.server_handle.is_some() {
69            return Err("Web service is already running".to_string());
70        }
71
72        let (shutdown_tx, mut shutdown_rx) = oneshot::channel::<()>();
73        self.port = port;
74
75        let app_state = web::Data::new(
76            AppState::new(self.bamboo_home_dir.clone())
77                .await
78                .map_err(|e| format!("Failed to initialize app state: {e}"))?,
79        );
80        // Retain a handle so stop()/Drop can stop AppState-owned background tasks. #119
81        self.app_state = Some(app_state.clone());
82        let bind_addr = bind.to_string();
83        let listen_addr = format!("{bind}:{port}");
84        let bind_for_log = bind_addr.clone();
85
86        let server = HttpServer::new(move || {
87            App::new()
88                .app_data(app_state.clone())
89                .wrap(build_cors(&bind_addr, port))
90                .configure(configure_routes) // No rate limiting for WebService
91        })
92        .workers(DEFAULT_WORKER_COUNT);
93
94        // Fail-fast: build the rustls config before binding; `None` → unchanged
95        // plaintext `.bind()` path. #181.
96        let server = match tls {
97            Some(tls) => server
98                .bind_rustls_0_23(&listen_addr, build_rustls_config(tls)?)
99                .map_err(|e| format!("Failed to bind TLS server: {e}"))?,
100            None => server
101                .bind(&listen_addr)
102                .map_err(|e| format!("Failed to bind server: {e}"))?,
103        }
104        .run();
105
106        let server_handle = tokio::spawn(async move {
107            tokio::select! {
108                result = server => {
109                    if let Err(e) = result {
110                        error!("Server error: {}", e);
111                    }
112                }
113                _ = &mut shutdown_rx => {
114                    info!("Web service shutdown signal received");
115                }
116            }
117        });
118
119        self.shutdown_tx = Some(shutdown_tx);
120        self.server_handle = Some(server_handle);
121
122        let scheme = if tls.is_some() { "https" } else { "http" };
123        info!(
124            "Web service started successfully on {scheme}://{}:{}",
125            bind_for_log, port
126        );
127        Ok(())
128    }
129
130    /// Start the web service on the specified port and bind address, serving static files
131    /// alongside the API routes.
132    pub async fn start_with_bind_and_static(
133        &mut self,
134        port: u16,
135        bind: &str,
136        static_dir: PathBuf,
137    ) -> Result<(), String> {
138        self.start_with_bind_and_static_tls(port, bind, static_dir, None)
139            .await
140    }
141
142    /// Like [`WebService::start_with_bind_and_static`], terminating TLS itself
143    /// when `tls` is `Some` (#181). `None` keeps the plaintext path unchanged.
144    pub async fn start_with_bind_and_static_tls(
145        &mut self,
146        port: u16,
147        bind: &str,
148        static_dir: PathBuf,
149        tls: Option<&TlsConfig>,
150    ) -> Result<(), String> {
151        info!("Starting web service with static frontend...");
152        if self.server_handle.is_some() {
153            return Err("Web service is already running".to_string());
154        }
155
156        let (shutdown_tx, mut shutdown_rx) = oneshot::channel::<()>();
157        self.port = port;
158
159        let static_dir = static_dir
160            .canonicalize()
161            .map_err(|e| format!("Static directory not found: {:?}: {}", static_dir, e))?;
162        if !static_dir.is_dir() {
163            return Err(format!(
164                "Static path is not a directory: {}",
165                static_dir.display()
166            ));
167        }
168
169        let app_state = web::Data::new(
170            AppState::new(self.bamboo_home_dir.clone())
171                .await
172                .map_err(|e| format!("Failed to initialize app state: {e}"))?,
173        );
174        // Retain a handle so stop()/Drop can stop AppState-owned background tasks. #119
175        self.app_state = Some(app_state.clone());
176        // Per-IP rate limiter for this network-exposed production server. #13
177        let rate_limiter = build_rate_limiter();
178        let bind_addr = bind.to_string();
179        let listen_addr = format!("{bind}:{port}");
180        let bind_for_log = bind_addr.clone();
181
182        let server = HttpServer::new(move || {
183            App::new()
184                .app_data(web::JsonConfig::default().limit(25 * 1024 * 1024))
185                .app_data(web::PayloadConfig::new(30 * 1024 * 1024))
186                .app_data(app_state.clone())
187                .wrap(Governor::new(&rate_limiter))
188                .wrap(build_cors(&bind_addr, port))
189                .wrap(build_security_headers())
190                // Immutable long-cache for hashed `/assets/*` so a proxy/CDN
191                // (e.g. Cloudflare tunnel) caches chunks at the edge instead of
192                // round-tripping each one to origin (#preload-error fix).
193                .wrap(actix_web::middleware::from_fn(
194                    crate::config::add_asset_cache_headers,
195                ))
196                .configure(configure_routes_with_rate_limiting)
197                .service(
198                    fs::Files::new("/", static_dir.clone())
199                        .index_file("index.html")
200                        .prefer_utf8(true)
201                        .disable_content_disposition()
202                        .disable_content_disposition(),
203                )
204        })
205        .workers(DEFAULT_WORKER_COUNT);
206
207        // Fail-fast: build the rustls config before binding; `None` → unchanged
208        // plaintext `.bind()` path. #181.
209        let server = match tls {
210            Some(tls) => server
211                .bind_rustls_0_23(&listen_addr, build_rustls_config(tls)?)
212                .map_err(|e| format!("Failed to bind TLS server: {e}"))?,
213            None => server
214                .bind(&listen_addr)
215                .map_err(|e| format!("Failed to bind server: {e}"))?,
216        }
217        .run();
218
219        let server_handle = tokio::spawn(async move {
220            tokio::select! {
221                result = server => {
222                    if let Err(e) = result {
223                        error!("Server error: {}", e);
224                    }
225                }
226                _ = &mut shutdown_rx => {
227                    info!("Web service shutdown signal received");
228                }
229            }
230        });
231
232        self.shutdown_tx = Some(shutdown_tx);
233        self.server_handle = Some(server_handle);
234
235        let scheme = if tls.is_some() { "https" } else { "http" };
236        info!(
237            "Web service with static frontend started successfully on {scheme}://{}:{}",
238            bind_for_log, port
239        );
240        Ok(())
241    }
242
243    /// Stop the web service
244    pub async fn stop(&mut self) -> Result<(), String> {
245        if let Some(shutdown_tx) = self.shutdown_tx.take() {
246            if shutdown_tx.send(()).is_err() {
247                error!("Failed to send shutdown signal");
248                return Err("Error sending shutdown signal".to_string());
249            }
250
251            if let Some(handle) = self.server_handle.take() {
252                if let Err(e) = handle.await {
253                    error!("Error waiting for server shutdown: {}", e);
254                    return Err(format!("Error waiting for server shutdown: {}", e));
255                }
256            }
257
258            // Gracefully stop AppState-owned background tasks — the #47 MCP-proxy
259            // reconnect supervisor (via its cancellation token) and the MCP servers.
260            // Without this the token was wired but never cancelled, so the
261            // supervisor only died at process exit. #119.
262            if let Some(state) = self.app_state.take() {
263                state.shutdown().await;
264            }
265
266            info!("Web service stopped successfully");
267        }
268
269        Ok(())
270    }
271
272    /// Check if the web service is currently running
273    pub fn is_running(&self) -> bool {
274        self.server_handle.is_some()
275    }
276
277    /// Get the port the web service is running on
278    pub fn port(&self) -> u16 {
279        self.port
280    }
281}
282
283impl Drop for WebService {
284    fn drop(&mut self) {
285        if let Some(shutdown_tx) = self.shutdown_tx.take() {
286            let _ = shutdown_tx.send(());
287        }
288        // Drop can't run the async shutdown(), but cancelling the MCP-proxy
289        // supervisor's token is synchronous — so a WebService dropped without an
290        // explicit stop() still tears down the reconnect loop. (The async MCP
291        // server cleanup is left to process exit on this fallback path.) #119.
292        if let Some(state) = self.app_state.take() {
293            state.mcp_proxy_shutdown.cancel();
294        }
295    }
296}
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301
302    /// #119 e2e: WebService::stop() must cancel the AppState-owned MCP-proxy
303    /// reconnect supervisor's token, so it terminates on server stop rather than
304    /// leaking until process exit.
305    #[tokio::test]
306    async fn stop_cancels_mcp_proxy_supervisor_token() {
307        let home = tempfile::TempDir::new().expect("tempdir");
308        let mut service = WebService::new(home.path().to_path_buf());
309        // Port 0 -> OS-assigned ephemeral port (no conflict).
310        service
311            .start_with_bind(0, "127.0.0.1")
312            .await
313            .expect("web service starts");
314
315        // Capture the supervisor's cancellation token while the service runs.
316        let token = service
317            .app_state
318            .as_ref()
319            .expect("app_state retained after start")
320            .mcp_proxy_shutdown
321            .clone();
322        assert!(
323            !token.is_cancelled(),
324            "supervisor token is live while the service runs"
325        );
326
327        service.stop().await.expect("web service stops");
328
329        assert!(
330            token.is_cancelled(),
331            "stop() must cancel the MCP-proxy supervisor token so it terminates"
332        );
333    }
334}