Skip to main content

fips_core/transport/ble/
pool.rs

1//! BLE connection pool with priority eviction.
2//!
3//! BLE hardware limits concurrent connections (typically 4-10). The pool
4//! enforces a configurable maximum and prioritizes static (configured)
5//! peers over dynamically discovered ones.
6
7use std::collections::HashMap;
8
9use tokio::task::JoinHandle;
10
11use crate::transport::{TransportAddr, TransportError};
12
13use super::addr::BleAddr;
14
15/// A single BLE connection in the pool.
16pub struct BleConnection<S> {
17    /// The L2CAP stream for this connection.
18    pub stream: S,
19    /// Background receive task handle.
20    pub recv_task: Option<JoinHandle<()>>,
21    /// Negotiated L2CAP send MTU.
22    pub send_mtu: u16,
23    /// Negotiated L2CAP receive MTU.
24    pub recv_mtu: u16,
25    /// When the connection was established.
26    pub established_at: tokio::time::Instant,
27    /// Whether this is a static (configured) peer.
28    pub is_static: bool,
29    /// Parsed remote address.
30    pub addr: BleAddr,
31}
32
33impl<S> BleConnection<S> {
34    /// Effective MTU for this connection: min(send, recv).
35    pub fn effective_mtu(&self) -> u16 {
36        self.send_mtu.min(self.recv_mtu)
37    }
38}
39
40impl<S> Drop for BleConnection<S> {
41    fn drop(&mut self) {
42        if let Some(task) = self.recv_task.take() {
43            task.abort();
44        }
45    }
46}
47
48/// Connection pool managing BLE connections with priority eviction.
49pub struct ConnectionPool<S> {
50    connections: HashMap<TransportAddr, BleConnection<S>>,
51    max_connections: usize,
52}
53
54impl<S> ConnectionPool<S> {
55    /// Create a new pool with the given maximum capacity.
56    pub fn new(max_connections: usize) -> Self {
57        Self {
58            connections: HashMap::new(),
59            max_connections,
60        }
61    }
62
63    /// Get the number of active connections.
64    pub fn len(&self) -> usize {
65        self.connections.len()
66    }
67
68    /// Check if the pool is empty.
69    pub fn is_empty(&self) -> bool {
70        self.connections.is_empty()
71    }
72
73    /// Check if the pool is at capacity.
74    pub fn is_full(&self) -> bool {
75        self.connections.len() >= self.max_connections
76    }
77
78    /// Get the maximum pool capacity.
79    pub fn max_connections(&self) -> usize {
80        self.max_connections
81    }
82
83    /// Look up a connection by transport address.
84    pub fn get(&self, addr: &TransportAddr) -> Option<&BleConnection<S>> {
85        self.connections.get(addr)
86    }
87
88    /// Look up a mutable connection by transport address.
89    pub fn get_mut(&mut self, addr: &TransportAddr) -> Option<&mut BleConnection<S>> {
90        self.connections.get_mut(addr)
91    }
92
93    /// Check if a connection exists for the given address.
94    pub fn contains(&self, addr: &TransportAddr) -> bool {
95        self.connections.contains_key(addr)
96    }
97
98    /// Try to insert a connection, evicting if necessary.
99    ///
100    /// Returns `Ok(evicted_addr)` on success (with optional evicted peer),
101    /// or `Err` if the pool is full and the new connection cannot evict anyone.
102    pub fn insert(
103        &mut self,
104        addr: TransportAddr,
105        conn: BleConnection<S>,
106    ) -> Result<Option<TransportAddr>, TransportError> {
107        use std::collections::hash_map::Entry;
108
109        // Already connected — replace
110        if let Entry::Occupied(mut e) = self.connections.entry(addr.clone()) {
111            e.insert(conn);
112            return Ok(None);
113        }
114
115        // Room available
116        if !self.is_full() {
117            self.connections.insert(addr, conn);
118            return Ok(None);
119        }
120
121        // Pool full — try eviction
122        let evicted = self.find_eviction_candidate(conn.is_static)?;
123        self.connections.remove(&evicted);
124        self.connections.insert(addr, conn);
125        Ok(Some(evicted))
126    }
127
128    /// Remove a connection by address.
129    pub fn remove(&mut self, addr: &TransportAddr) -> Option<BleConnection<S>> {
130        self.connections.remove(addr)
131    }
132
133    /// Get all connection addresses.
134    pub fn addrs(&self) -> Vec<TransportAddr> {
135        self.connections.keys().cloned().collect()
136    }
137
138    /// Find the best eviction candidate.
139    ///
140    /// Static peers requesting a slot can evict the oldest non-static peer.
141    /// Non-static peers cannot evict anyone if all slots are static.
142    fn find_eviction_candidate(
143        &self,
144        new_is_static: bool,
145    ) -> Result<TransportAddr, TransportError> {
146        if new_is_static {
147            // Static peer can evict oldest non-static
148            self.connections
149                .iter()
150                .filter(|(_, c)| !c.is_static)
151                .min_by_key(|(_, c)| c.established_at)
152                .map(|(addr, _)| addr.clone())
153                .ok_or_else(|| {
154                    TransportError::NotSupported("BLE pool full: all connections are static".into())
155                })
156        } else {
157            // Non-static peer evicts oldest non-static
158            self.connections
159                .iter()
160                .filter(|(_, c)| !c.is_static)
161                .min_by_key(|(_, c)| c.established_at)
162                .map(|(addr, _)| addr.clone())
163                .ok_or_else(|| {
164                    TransportError::NotSupported("BLE pool full: all connections are static".into())
165                })
166        }
167    }
168}
169
170// ============================================================================
171// Tests
172// ============================================================================
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177
178    fn test_addr(n: u8) -> TransportAddr {
179        TransportAddr::from_string(&format!("hci0/AA:BB:CC:DD:EE:{n:02X}"))
180    }
181
182    fn test_ble_addr(n: u8) -> BleAddr {
183        BleAddr::from_mac("hci0", [0xAA, 0xBB, 0xCC, 0xDD, 0xEE, n])
184    }
185
186    fn test_conn(n: u8, is_static: bool) -> BleConnection<()> {
187        BleConnection {
188            stream: (),
189            recv_task: None,
190            send_mtu: 2048,
191            recv_mtu: 2048,
192            established_at: tokio::time::Instant::now(),
193            is_static,
194            addr: test_ble_addr(n),
195        }
196    }
197
198    #[test]
199    fn test_pool_basic_insert() {
200        let mut pool: ConnectionPool<()> = ConnectionPool::new(7);
201        assert!(pool.is_empty());
202
203        pool.insert(test_addr(1), test_conn(1, false)).unwrap();
204        assert_eq!(pool.len(), 1);
205        assert!(!pool.is_empty());
206        assert!(pool.contains(&test_addr(1)));
207    }
208
209    #[test]
210    fn test_pool_remove() {
211        let mut pool: ConnectionPool<()> = ConnectionPool::new(7);
212        pool.insert(test_addr(1), test_conn(1, false)).unwrap();
213        assert!(pool.remove(&test_addr(1)).is_some());
214        assert!(pool.is_empty());
215    }
216
217    #[test]
218    fn test_pool_full_eviction() {
219        let mut pool: ConnectionPool<()> = ConnectionPool::new(3);
220        pool.insert(test_addr(1), test_conn(1, false)).unwrap();
221        pool.insert(test_addr(2), test_conn(2, false)).unwrap();
222        pool.insert(test_addr(3), test_conn(3, false)).unwrap();
223        assert!(pool.is_full());
224
225        // Inserting a 4th should evict the oldest non-static
226        let result = pool.insert(test_addr(4), test_conn(4, false));
227        assert!(result.is_ok());
228        assert!(result.unwrap().is_some()); // something was evicted
229        assert_eq!(pool.len(), 3);
230        assert!(pool.contains(&test_addr(4)));
231    }
232
233    #[test]
234    fn test_pool_static_evicts_nonstatic() {
235        let mut pool: ConnectionPool<()> = ConnectionPool::new(2);
236        pool.insert(test_addr(1), test_conn(1, false)).unwrap();
237        pool.insert(test_addr(2), test_conn(2, false)).unwrap();
238
239        // Static peer should evict a non-static
240        let result = pool.insert(test_addr(3), test_conn(3, true));
241        assert!(result.is_ok());
242        assert_eq!(pool.len(), 2);
243        assert!(pool.contains(&test_addr(3)));
244    }
245
246    #[test]
247    fn test_pool_all_static_rejects() {
248        let mut pool: ConnectionPool<()> = ConnectionPool::new(2);
249        pool.insert(test_addr(1), test_conn(1, true)).unwrap();
250        pool.insert(test_addr(2), test_conn(2, true)).unwrap();
251
252        // Non-static peer cannot evict static peers
253        let result = pool.insert(test_addr(3), test_conn(3, false));
254        assert!(result.is_err());
255    }
256
257    #[test]
258    fn test_pool_replace_existing() {
259        let mut pool: ConnectionPool<()> = ConnectionPool::new(2);
260        pool.insert(test_addr(1), test_conn(1, false)).unwrap();
261
262        // Re-inserting same address should replace, not grow
263        let result = pool.insert(test_addr(1), test_conn(1, true));
264        assert!(result.is_ok());
265        assert_eq!(pool.len(), 1);
266        assert!(pool.get(&test_addr(1)).unwrap().is_static);
267    }
268
269    #[test]
270    fn test_pool_effective_mtu() {
271        let mut conn = test_conn(1, false);
272        conn.send_mtu = 1024;
273        conn.recv_mtu = 2048;
274        assert_eq!(conn.effective_mtu(), 1024);
275    }
276
277    #[test]
278    fn test_pool_addrs() {
279        let mut pool: ConnectionPool<()> = ConnectionPool::new(7);
280        pool.insert(test_addr(1), test_conn(1, false)).unwrap();
281        pool.insert(test_addr(2), test_conn(2, false)).unwrap();
282
283        let mut addrs = pool.addrs();
284        addrs.sort_by(|a, b| a.as_str().cmp(&b.as_str()));
285        assert_eq!(addrs.len(), 2);
286    }
287}