Skip to main content

memtui/app/
connections.rs

1use crate::backend::Backend;
2use crate::types::ConnectionConfig;
3use std::collections::HashMap;
4use std::sync::Arc;
5use tokio::sync::RwLock;
6
7/// Connection status for a backend
8#[derive(Debug, Clone, PartialEq)]
9pub enum ConnectionStatus {
10    Disconnected,
11    Connecting,
12    Connected,
13    Error(String),
14}
15
16/// Manages multiple backend connections
17pub struct ConnectionManager {
18    connections: HashMap<String, Arc<RwLock<Box<dyn Backend>>>>,
19    configs: HashMap<String, ConnectionConfig>,
20    statuses: HashMap<String, ConnectionStatus>,
21    active_id: Option<String>,
22}
23
24impl ConnectionManager {
25    pub fn new() -> Self {
26        Self {
27            connections: HashMap::new(),
28            configs: HashMap::new(),
29            statuses: HashMap::new(),
30            active_id: None,
31        }
32    }
33
34    /// Add a new connection configuration
35    pub fn add_connection(&mut self, config: ConnectionConfig) {
36        let id = config.id.clone();
37        self.statuses
38            .insert(id.clone(), ConnectionStatus::Disconnected);
39        self.configs.insert(id, config);
40    }
41
42    /// Get all connection configs sorted by name for stable UI ordering
43    pub fn get_configs(&self) -> Vec<&ConnectionConfig> {
44        let mut configs: Vec<_> = self.configs.values().collect();
45        configs.sort_by(|a, b| a.name.cmp(&b.name));
46        configs
47    }
48
49    /// Get all connection configs as a Vec (for saving)
50    pub fn get_all_configs(&self) -> Vec<ConnectionConfig> {
51        let mut configs: Vec<_> = self.configs.values().cloned().collect();
52        configs.sort_by(|a, b| a.name.cmp(&b.name));
53        configs
54    }
55
56    /// Load connections from a list
57    pub fn load_configs(&mut self, configs: Vec<ConnectionConfig>) {
58        self.configs.clear();
59        self.statuses.clear();
60        for config in configs {
61            let id = config.id.clone();
62            self.statuses
63                .insert(id.clone(), ConnectionStatus::Disconnected);
64            self.configs.insert(id, config);
65        }
66    }
67
68    /// Get a connection config by ID
69    pub fn get_config(&self, id: &str) -> Option<&ConnectionConfig> {
70        self.configs.get(id)
71    }
72
73    /// Set status for a connection
74    pub fn set_status(&mut self, id: &str, status: ConnectionStatus) {
75        self.statuses.insert(id.to_string(), status);
76    }
77
78    /// Register an active, connected backend
79    pub fn register_connection(&mut self, id: &str, backend: Arc<RwLock<Box<dyn Backend>>>) {
80        self.connections.insert(id.to_string(), backend);
81        self.active_id = Some(id.to_string());
82        self.statuses
83            .insert(id.to_string(), ConnectionStatus::Connected);
84    }
85
86    /// Disconnect from a backend
87    pub async fn disconnect(&mut self, id: &str) -> Result<(), Box<dyn std::error::Error>> {
88        if let Some(backend_arc) = self.connections.remove(id) {
89            // We need to acquire write lock to disconnect
90            let mut backend = backend_arc.write().await;
91            backend.disconnect().await?;
92        }
93
94        self.statuses
95            .insert(id.to_string(), ConnectionStatus::Disconnected);
96
97        Ok(())
98    }
99
100    /// Get a handle to the active backend (thread-safe)
101    pub fn get_active_backend_handle(&self) -> Option<Arc<RwLock<Box<dyn Backend>>>> {
102        self.active_id
103            .as_ref()
104            .and_then(|id| self.connections.get(id))
105            .cloned()
106    }
107
108    /// Get the active connection ID
109    pub fn get_active_id(&self) -> Option<&str> {
110        self.active_id.as_deref()
111    }
112
113    /// Set the active connection
114    pub fn set_active(&mut self, id: &str) -> bool {
115        if self.configs.contains_key(id) {
116            self.active_id = Some(id.to_string());
117            true
118        } else {
119            false
120        }
121    }
122
123    /// Check if a connection is active (connected)
124    pub fn is_connected(&self, id: &str) -> bool {
125        self.connections.contains_key(id)
126    }
127
128    /// Remove a connection configuration
129    pub fn remove_config(&mut self, id: &str) {
130        self.configs.remove(id);
131        self.connections.remove(id);
132        self.statuses.remove(id);
133        if self.active_id.as_deref() == Some(id) {
134            self.active_id = None;
135        }
136    }
137
138    /// Get connection status
139    pub fn get_status(&self, id: &str) -> ConnectionStatus {
140        self.statuses
141            .get(id)
142            .cloned()
143            .unwrap_or(ConnectionStatus::Disconnected)
144    }
145
146    /// Get all statuses
147    pub fn get_statuses(&self) -> &HashMap<String, ConnectionStatus> {
148        &self.statuses
149    }
150
151    /// Get the status of the active connection
152    pub fn get_active_status(&self) -> Option<ConnectionStatus> {
153        self.active_id.as_ref().map(|id| self.get_status(id))
154    }
155}
156
157impl Default for ConnectionManager {
158    fn default() -> Self {
159        Self::new()
160    }
161}