diff options
Diffstat (limited to 'src/router/manager.rs')
| -rw-r--r-- | src/router/manager.rs | 200 |
1 files changed, 95 insertions, 105 deletions
diff --git a/src/router/manager.rs b/src/router/manager.rs index 23b7c69..5fb8868 100644 --- a/src/router/manager.rs +++ b/src/router/manager.rs @@ -1,21 +1,8 @@ -use crate::router::router::RouterUtils; -use crate::router::router::{Emissary, EmissaryConfig}; -use log::{debug, error, info}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; -use tokio::sync::mpsc; -use tokio::task::JoinHandle; - -#[derive(Debug)] -pub enum RouterMessage { - Start, - Stop, - Status, -} +// Simple RouterManager that just tracks status without complex state management pub struct RouterManager { - handle: Option<JoinHandle<()>>, - tx: mpsc::Sender<RouterMessage>, is_running: Arc<AtomicBool>, } @@ -25,104 +12,114 @@ impl RouterManager { ) -> Result<Self, Box<dyn std::error::Error>> { if !config.router.integrated_router { return Ok(Self { - handle: None, - tx: { - let (tx, _) = mpsc::channel(1); - tx - }, is_running: Arc::new(AtomicBool::new(false)), }); } - let (tx, mut rx) = mpsc::channel::<RouterMessage>(1); - let is_running = Arc::new(AtomicBool::new(false)); - let is_running_clone = is_running.clone(); + // Initialize router synchronously to avoid Send issues + Self::init_router(config).await?; - let router_config = config.router.clone(); - let handle = tokio::spawn(async move { - info!("Router manager task started"); + let manager = Self { + is_running: Arc::new(AtomicBool::new(true)), + }; - let mut router = Emissary::new(EmissaryConfig { - storage: Some(std::path::PathBuf::from(&router_config.storage_path)), - auto_update: Some(router_config.auto_update), - http_proxy_port: Some(router_config.http_proxy_port), - socks_proxy_port: Some(router_config.socks_proxy_port), - }); + // Give the router some time to initialize + tokio::time::sleep(std::time::Duration::from_secs(2)).await; - if let Err(e) = router.config().await { - error!("Failed to configure router: {}", e); - return; - } - - let storage_path = std::path::Path::new(&router_config.storage_path); - if !storage_path.exists() - || storage_path - .read_dir() - .ok() - .is_none_or(|mut d| d.next().is_none()) - { - info!("Router storage is empty, performing initial reseed..."); - if let Err(e) = router.reseed().await { - error!("Failed to reseed router: {}", e); - return; - } - } - - let router_task = tokio::spawn(async move { - info!("Starting router service..."); - match router.start().await { - Ok(_) => info!("Router service stopped"), - Err(e) => error!("Router service error: {}", e), - } - }); + Ok(manager) + } - is_running_clone.store(true, Ordering::SeqCst); - info!("Router manager is now running"); - - while let Some(msg) = rx.recv().await { - match msg { - RouterMessage::Stop => { - info!("Stopping router..."); - // TODO: Implement proper router shutdown - is_running_clone.store(false, Ordering::SeqCst); - break; - } - RouterMessage::Status => { - debug!( - "Router status: {}", - if is_running_clone.load(Ordering::SeqCst) { - "running" - } else { - "stopped" - } - ); - } - _ => {} - } - } - - if let Err(e) = router_task.await { - error!("Router task panicked: {}", e); - } - - info!("Router manager task finished"); + async fn init_router( + config: &crate::cfg::config::Config, + ) -> Result<(), Box<dyn std::error::Error>> { + use crate::router::router::{Emissary, EmissaryConfig, RouterUtils}; + use std::path::Path; + + let router_config = &config.router; + let mut router = Emissary::new(EmissaryConfig { + storage: Some(std::path::PathBuf::from(&router_config.storage_path)), + auto_update: Some(router_config.auto_update), + http_proxy_port: Some(router_config.http_proxy_port), + socks_proxy_port: Some(router_config.socks_proxy_port), }); - tokio::time::sleep(std::time::Duration::from_secs(1)).await; + router.config().await?; + + let storage_path = Path::new(&router_config.storage_path); + if !storage_path.exists() { + std::fs::create_dir_all(storage_path)?; + } + + // Check if storage directory is empty + let should_reseed = match std::fs::read_dir(storage_path) { + Ok(mut entries) => entries.next().is_none(), + Err(_) => true, // if we can't read, reseed anyway + }; + + if should_reseed { + println!("Router storage is empty, performing initial reseed..."); + router.reseed().await?; + } + + let router_instance = router.start().await?; + + // Store the router instance in the global static variable + *super::router::ROUTER.lock().await = Some(router_instance); + println!("Router service successfully initialized and stored globally"); - Ok(Self { - handle: Some(handle), - tx, - is_running, - }) + Ok(()) } - pub async fn stop(&self) { + /// Starts the integrated router if it is not currently running. + /// Note: The router is typically started automatically when the RouterManager is created, + /// so calling this method usually just prints a message indicating that the router + /// starts automatically. + /// + /// # Returns + /// + /// * `Ok(())` always returns OK as this is a compatibility method + pub async fn start(&self) -> Result<(), Box<dyn std::error::Error>> { + if !self.is_running.load(Ordering::SeqCst) { + println!("Router start functionality not implemented for this mode"); + // We can't really control the router lifecycle since it's managed globally + } + Ok(()) + } + + /// Restarts the integrated router if it is currently running. + /// This stops the current router instance and starts a new one. + /// + /// # Returns + /// + /// * `Ok(())` when the restart is initiated + /// * `Err(Box<dyn std::error::Error>)` if the restart failed + pub async fn restart(&self) -> Result<(), Box<dyn std::error::Error>> { + println!("Restarting router..."); + + // Clear the global router instance + *super::router::ROUTER.lock().await = None; + + // Get config again (this is not ideal but needed for restart) + let config = crate::cfg::config::Config::parse() + .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))?; + + Self::init_router(&config).await?; + + println!("Router restarted successfully"); + Ok(()) + } + + /// Stops the integrated router if it is currently running. + /// This clears the global router instance. + pub async fn stop(&self) -> Result<(), Box<dyn std::error::Error>> { if self.is_running.load(Ordering::SeqCst) { - if let Err(e) = self.tx.send(RouterMessage::Stop).await { - error!("Failed to send stop message to router: {}", e); - } + println!("Stopping router..."); + // Clear the global router instance + *super::router::ROUTER.lock().await = None; + self.is_running.store(false, Ordering::SeqCst); + println!("Router stopped"); } + Ok(()) } pub fn is_running(&self) -> bool { @@ -132,13 +129,6 @@ impl RouterManager { impl Drop for RouterManager { fn drop(&mut self) { - if self.is_running() { - let tx = self.tx.clone(); - tokio::spawn(async move { - if let Err(e) = tx.send(RouterMessage::Stop).await { - error!("Failed to send stop message during drop: {}", e); - } - }); - } + //todooo } } |
