summaryrefslogtreecommitdiff
path: root/src/router/manager.rs
blob: 9b23434dd67111eec35b6effa8a19ebb8b464052 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

// Simple RouterManager that just tracks status without complex state management
pub struct RouterManager {
    is_running: Arc<AtomicBool>,
}

impl RouterManager {
    pub async fn new(
        config: &crate::cfg::config::Config,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        if !config.router.integrated_router {
            return Ok(Self {
                is_running: Arc::new(AtomicBool::new(false)),
            });
        }

        // Initialize router synchronously to avoid Send issues
        Self::init_router(config).await?;

        let manager = Self {
            is_running: Arc::new(AtomicBool::new(true)),
        };

        // Give the router some time to initialize
        tokio::time::sleep(std::time::Duration::from_secs(2)).await;

        Ok(manager)
    }

    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),
        });

        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(())
    }

    /// 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) {
            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 {
        self.is_running.load(Ordering::SeqCst)
    }
}

/*
impl Drop for RouterManager {
    fn drop(&mut self) {
        //todooo
    }
}
*/