Skip to main content

qualia_core_db/net/acoustic_ble_mesh/
routing.rs

1//! Mesh routing: the inter-network router, routing/forwarding tables, route
2//! discovery and caching, and congestion control (queue management + rate control).
3
4use super::*;
5
6/// Mesh router for inter-network routing
7pub struct MeshRouter {
8    routing_table: RoutingTable,
9    forwarding_table: ForwardingTable,
10    route_discovery: RouteDiscovery,
11    congestion_control: CongestionControl,
12}
13
14/// Routing table
15#[derive(Debug, Clone)]
16pub struct RoutingTable {
17    pub entries: Vec<RouteEntry>,
18}
19
20/// Route entry
21#[derive(Debug, Clone)]
22pub struct RouteEntry {
23    pub destination: u16,
24    pub next_hop: u16,
25    pub metric: u8,
26    pub sequence_number: u16,
27}
28
29/// Forwarding table
30#[derive(Debug, Clone)]
31pub struct ForwardingTable {
32    pub entries: Vec<ForwardingEntry>,
33}
34
35/// Forwarding entry
36#[derive(Debug, Clone)]
37pub struct ForwardingEntry {
38    pub destination: String,
39    pub next_hop: String,
40    pub interface: NetworkInterface,
41    pub metric: u16,
42    pub ttl: u8,
43}
44
45/// Route discovery
46pub struct RouteDiscovery {
47    pub discovery_protocol: DiscoveryProtocol,
48    pub route_cache: RouteCache,
49    pub discovery_timeout: Duration,
50}
51
52/// Discovery protocols
53#[derive(Debug, Clone, PartialEq)]
54pub enum DiscoveryProtocol {
55    Proactive,
56    Reactive,
57    Hybrid,
58}
59
60/// Route cache
61#[derive(Debug, Clone)]
62pub struct RouteCache {
63    pub entries: Vec<CachedRoute>,
64}
65
66/// Cached route
67#[derive(Debug, Clone)]
68pub struct CachedRoute {
69    pub destination: String,
70    pub route: Vec<String>,
71    pub metric: u16,
72    pub timestamp: Instant,
73    pub ttl: Duration,
74}
75
76/// Congestion control
77pub struct CongestionControl {
78    pub algorithm: CongestionAlgorithm,
79    pub queue_management: QueueManagement,
80    pub rate_control: RateControl,
81}
82
83/// Congestion algorithms
84#[derive(Debug, Clone, PartialEq)]
85pub enum CongestionAlgorithm {
86    DropTail,
87    RED,
88    ECN,
89    Custom,
90}
91
92/// Queue management
93#[derive(Debug, Clone)]
94pub struct QueueManagement {
95    pub queue_size: usize,
96    pub drop_policy: DropPolicy,
97}
98
99/// Drop policies
100#[derive(Debug, Clone, PartialEq)]
101pub enum DropPolicy {
102    DropTail,
103    DropHead,
104    Random,
105    Priority,
106}
107
108/// Rate control
109#[derive(Debug, Clone)]
110pub struct RateControl {
111    pub token_bucket: TokenBucket,
112    pub leaky_bucket: LeakyBucket,
113}
114
115/// Token bucket
116#[derive(Debug, Clone)]
117pub struct TokenBucket {
118    pub capacity: u32,
119    pub rate: u32,
120    pub tokens: u32,
121    pub last_update: Instant,
122}
123
124/// Leaky bucket
125#[derive(Debug, Clone)]
126pub struct LeakyBucket {
127    pub capacity: u32,
128    pub rate: u32,
129    pub level: u32,
130    pub last_update: Instant,
131}
132
133impl MeshRouter {
134    /// Creates a router with empty forwarding table, discovery, and congestion-control state.
135    pub fn new() -> Self {
136        Self {
137            routing_table: RoutingTable::new(),
138            forwarding_table: ForwardingTable::new(),
139            route_discovery: RouteDiscovery::new(),
140            congestion_control: CongestionControl::new(),
141        }
142    }
143
144    /// Initializes congestion control; `MeshError` propagates.
145    pub fn initialize(&mut self) -> Result<(), MeshError> {
146        self.congestion_control.initialize()?;
147        Ok(())
148    }
149
150    /// Number of live entries in the forwarding table.
151    pub fn get_route_count(&self) -> u32 {
152        self.routing_table.entries.len() as u32
153    }
154
155    /// Shared access to the forwarding table.
156    pub fn forwarding_table(&self) -> &ForwardingTable {
157        &self.forwarding_table
158    }
159
160    /// Shared access to the route-discovery state.
161    pub fn route_discovery(&self) -> &RouteDiscovery {
162        &self.route_discovery
163    }
164
165    /// Shared access to the congestion-control state.
166    pub fn congestion_control(&self) -> &CongestionControl {
167        &self.congestion_control
168    }
169
170    /// Prunes stale forwarding entries (expired TTL / empty next hop) and decrements TTL on survivors — real maintenance pass.
171    pub fn optimize_routes(&mut self) -> Result<(), MeshError> {
172        // Prune stale forwarding entries (expired TTL or empty next hop).
173        self.forwarding_table
174            .entries
175            .retain(|e| e.ttl > 0 && !e.next_hop.is_empty());
176        // Decrement TTL on remaining entries.
177        for e in &mut self.forwarding_table.entries {
178            e.ttl = e.ttl.saturating_sub(1);
179        }
180        Ok(())
181    }
182}
183
184impl RoutingTable {
185    /// Creates an empty routing table.
186    pub fn new() -> Self {
187        Self {
188            entries: Vec::new(),
189        }
190    }
191}
192
193impl ForwardingTable {
194    /// Creates an empty forwarding table.
195    pub fn new() -> Self {
196        Self {
197            entries: Vec::new(),
198        }
199    }
200}
201
202impl RouteDiscovery {
203    /// Creates an empty route-discovery state.
204    pub fn new() -> Self {
205        Self {
206            discovery_protocol: DiscoveryProtocol::Hybrid,
207            route_cache: RouteCache::new(),
208            discovery_timeout: Duration::from_secs(30),
209        }
210    }
211}
212
213impl RouteCache {
214    /// Creates an empty route cache.
215    pub fn new() -> Self {
216        Self {
217            entries: Vec::new(),
218        }
219    }
220}
221
222impl CongestionControl {
223    /// Creates congestion control with default algorithm/queue/rate state.
224    pub fn new() -> Self {
225        Self {
226            algorithm: CongestionAlgorithm::RED,
227            queue_management: QueueManagement::new(),
228            rate_control: RateControl::new(),
229        }
230    }
231
232    /// No-op returning `Ok(())` — in-memory state needs no setup.
233    pub fn initialize(&mut self) -> Result<(), MeshError> {
234        Ok(())
235    }
236
237    /// The configured congestion algorithm.
238    pub fn algorithm(&self) -> &CongestionAlgorithm {
239        &self.algorithm
240    }
241
242    /// Queue-management configuration.
243    pub fn queue_management(&self) -> &QueueManagement {
244        &self.queue_management
245    }
246
247    /// Rate-control configuration.
248    pub fn rate_control(&self) -> &RateControl {
249        &self.rate_control
250    }
251}
252
253impl QueueManagement {
254    /// Creates default queue-management state.
255    pub fn new() -> Self {
256        Self {
257            queue_size: 1000,
258            drop_policy: DropPolicy::DropTail,
259        }
260    }
261}
262
263impl RateControl {
264    /// Creates default rate-control state.
265    pub fn new() -> Self {
266        Self {
267            token_bucket: TokenBucket::new(),
268            leaky_bucket: LeakyBucket::new(),
269        }
270    }
271}
272
273impl TokenBucket {
274    /// Creates an empty token-bucket rate limiter state.
275    pub fn new() -> Self {
276        Self {
277            capacity: 1000,
278            rate: 100,
279            tokens: 1000,
280            last_update: Instant::now(),
281        }
282    }
283}
284
285impl LeakyBucket {
286    /// Creates an empty leaky-bucket rate limiter state.
287    pub fn new() -> Self {
288        Self {
289            capacity: 1000,
290            rate: 100,
291            level: 0,
292            last_update: Instant::now(),
293        }
294    }
295}