rat_congestion 0.1.0

High-performance congestion control algorithms for network protocols
Documentation
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Congestion control manager with intelligent algorithm switching.
//!
//! This module provides the `CongestionManager` which orchestrates different
//! congestion control algorithms and provides intelligent switching based on
//! network conditions.

use crate::algorithms::{CongestionControlAlgorithm, Bbr, Cubic};
use crate::constants::*;
use crate::events::CongestionEvent;
// Metrics will be provided by external crates
use std::time::{Duration, Instant};

/// Trait for network metrics collection
pub trait NetworkMetrics {
    /// Record a packet sent
    fn on_packet_sent(&mut self, bytes: u32);
    /// Record a packet acknowledged
    fn on_packet_acked(&mut self, bytes: u32, rtt: Duration);
    /// Record a packet lost
    fn on_packet_lost(&mut self, bytes: u32);
    /// Get current RTT estimate
    fn rtt(&self) -> Duration;
    /// Get minimum RTT observed
    fn min_rtt(&self) -> Duration;
    /// Get current bandwidth estimate
    fn bandwidth(&self) -> u64;
    /// Get packet loss rate
    fn loss_rate(&self) -> f64;
    /// Get bandwidth ratio
    fn bw_ratio(&self) -> f64;
    /// Set bandwidth ratio
    fn set_bw_ratio(&mut self, ratio: f64);
    /// Get RTT coefficient of variation
    fn rtt_cv(&self) -> f64;
    /// Set RTT coefficient of variation
    fn set_rtt_cv(&mut self, cv: f64);
    /// Check if RTT is variable
    fn has_variable_rtt(&self) -> bool;
    /// Check if bandwidth utilization is low
    fn has_low_bandwidth_utilization(&self) -> bool;
    /// Check if loss rate is high
    fn has_high_loss(&self) -> bool;
    /// Update metrics with new values
    fn update(&mut self, rtt_us: Duration, loss_rate: f64, throughput: u64, cwnd: u32);
    /// Reset metrics
    fn reset(&mut self);
}

/// Trait for metrics window (rolling statistics)
pub trait MetricsWindow {
    /// Add a new sample
    fn add_sample(&mut self, rtt: Duration, loss_rate: f64, bandwidth: u64);
    /// Get average RTT over the window
    fn avg_rtt(&self) -> Duration;
    /// Get average bandwidth over the window
    fn avg_bandwidth(&self) -> u64;
    /// Get average loss rate over the window
    fn avg_loss_rate(&self) -> f64;
    /// Get RTT coefficient of variation
    fn rtt_coefficient_of_variation(&self) -> Option<f64>;
    /// Check if network conditions are stable
    fn is_stable(&self) -> bool;
    /// Clear the window
    fn clear(&mut self);
}

/// Configuration for the congestion manager.
#[derive(Debug, Clone)]
pub struct CongestionConfig {
    /// Enable automatic algorithm switching
    pub auto_switch: bool,
    /// Cooldown period between algorithm switches
    pub switch_cooldown: Duration,
    /// Window size for metrics collection
    pub metrics_window_size: usize,
    /// Enable platform-specific optimizations
    pub platform_optimized: bool,
}

impl Default for CongestionConfig {
    fn default() -> Self {
        Self {
            auto_switch: true,
            switch_cooldown: perf::SWITCH_COOLDOWN,
            metrics_window_size: 32,
            platform_optimized: true,
        }
    }
}

/// Algorithm selection strategy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AlgorithmType {
    /// Use BBR algorithm
    Bbr,
    /// Use CUBIC algorithm
    Cubic,
    /// Automatically select based on network conditions
    Auto,
}

/// High-performance congestion control manager.
///
/// The manager coordinates between different congestion control algorithms
/// and provides intelligent switching based on real-time network conditions.
pub struct CongestionManager<M: NetworkMetrics, W: MetricsWindow> {
    /// Current active algorithm
    current_algorithm: Box<dyn CongestionControlAlgorithm>,
    /// Configuration settings
    config: CongestionConfig,
    /// Network metrics tracking
    metrics: M,
    /// Rolling window of metrics for analysis
    metrics_window: W,
    /// Timestamp of last algorithm switch
    last_switch: Instant,
    /// Packet loss tracking
    packets_sent: u64,
    packets_lost: u64,
    /// Throughput tracking
    bytes_sent: u64,
    throughput_start: Instant,
}

impl<M: NetworkMetrics, W: MetricsWindow> CongestionManager<M, W> {
    /// Creates a new congestion manager with the specified initial algorithm and metrics.
    pub fn new(
        initial_algorithm: Box<dyn CongestionControlAlgorithm>,
        metrics: M,
        metrics_window: W,
    ) -> Self {
        Self::with_config(initial_algorithm, CongestionConfig::default(), metrics, metrics_window)
    }
    
    /// Creates a new congestion manager with custom configuration.
    pub fn with_config(
        initial_algorithm: Box<dyn CongestionControlAlgorithm>,
        config: CongestionConfig,
        metrics: M,
        metrics_window: W,
    ) -> Self {
        let now = Instant::now();
        Self {
            current_algorithm: initial_algorithm,
            config,
            metrics,
            metrics_window,
            last_switch: now,
            packets_sent: 0,
            packets_lost: 0,
            bytes_sent: 0,
            throughput_start: now,
        }
    }
    
    /// Creates a manager with BBR algorithm.
    pub fn with_bbr(metrics: M, metrics_window: W) -> Self {
        Self::new(Box::new(Bbr::new()), metrics, metrics_window)
    }
    
    /// Creates a manager with CUBIC algorithm.
    pub fn with_cubic(metrics: M, metrics_window: W) -> Self {
        Self::new(Box::new(Cubic::new()), metrics, metrics_window)
    }
    
    /// Creates a manager with automatic algorithm selection.
    pub fn with_auto(metrics: M, metrics_window: W) -> Self {
        // Start with BBR for better initial performance
        let mut manager = Self::new(Box::new(Bbr::new()), metrics, metrics_window);
        manager.config.auto_switch = true;
        manager
    }
    
    /// Manually switch to a different algorithm.
    pub fn switch_algorithm(&mut self, new_algorithm: Box<dyn CongestionControlAlgorithm>) {
        self.current_algorithm = new_algorithm;
        self.last_switch = Instant::now();
    }
    
    /// Switch to a specific algorithm type.
    pub fn switch_to(&mut self, algorithm_type: AlgorithmType) {
        let new_algorithm: Box<dyn CongestionControlAlgorithm> = match algorithm_type {
            AlgorithmType::Bbr => Box::new(Bbr::new()),
            AlgorithmType::Cubic => Box::new(Cubic::new()),
            AlgorithmType::Auto => {
                // For auto, decide based on current conditions
                if self.should_use_bbr() {
                    Box::new(Bbr::new())
                } else {
                    Box::new(Cubic::new())
                }
            }
        };
        
        self.switch_algorithm(new_algorithm);
    }
    
    /// Intelligent algorithm switching decision based on network conditions.
    ///
    /// This implements the dynamic decision algorithm from the BBR_CUBIC documentation:
    /// - Use BBR when: high loss rate OR (high RTT variation AND low bandwidth utilization)
    /// - Use CUBIC otherwise
    pub fn smart_switch_decision(&mut self) {
        if !self.config.auto_switch {
            return;
        }
        
        // Respect cooldown period
        if Instant::now() - self.last_switch < self.config.switch_cooldown {
            return;
        }
        
        let should_use_bbr = self.should_use_bbr();
        let current_is_bbr = self.current_algorithm.algorithm_name() == "BBR";
        
        if should_use_bbr && !current_is_bbr {
            self.switch_algorithm(Box::new(Bbr::new()));
        } else if !should_use_bbr && current_is_bbr {
            self.switch_algorithm(Box::new(Cubic::new()));
        }
    }
    
    /// Determine if BBR should be used based on current network conditions.
    fn should_use_bbr(&self) -> bool {
        // High loss rate favors BBR
        if self.metrics.has_high_loss() {
            return true;
        }
        
        // High RTT variation AND low bandwidth utilization favors BBR
        if self.metrics.has_variable_rtt() && self.metrics.has_low_bandwidth_utilization() {
            return true;
        }
        
        false
    }
    
    /// Process a congestion control event and update metrics.
    #[inline(always)]
    pub fn on_congestion_event(&mut self, event: CongestionEvent) {
        // Update internal statistics
        match &event {
            CongestionEvent::PacketAcked { bytes, rtt, .. } => {
                self.packets_sent += 1;
                self.bytes_sent += bytes;
                
                // Update metrics with new RTT measurement
                self.update_metrics_with_rtt(*rtt);
            },
            CongestionEvent::PacketLost { bytes, .. } => {
                self.packets_lost += 1;
                self.bytes_sent += bytes; // Still counts as sent
                
                // Update loss rate
                self.update_loss_rate();
            },
            CongestionEvent::ExplicitCongestionNotification => {
                // ECN doesn't affect our basic statistics
            }
        }
        
        // Forward event to current algorithm
        self.current_algorithm.on_congestion_event(event);
        
        // Update metrics window
        self.update_metrics_window();
        
        // Consider algorithm switching
        self.smart_switch_decision();
    }
    
    /// Update metrics with new RTT measurement.
    fn update_metrics_with_rtt(&mut self, rtt: Duration) {
        let throughput = self.calculate_throughput();
        
        self.metrics.update(
            rtt,
            self.calculate_loss_rate(),
            throughput,
            self.current_algorithm.congestion_window() as u32,
        );
        
        // Update RTT coefficient of variation from metrics window
        if let Some(cv) = self.metrics_window.rtt_coefficient_of_variation() {
            self.metrics.set_rtt_cv(cv);
        }
        
        // Update bandwidth utilization (simplified)
        let pacing_rate = self.current_algorithm.pacing_rate();
        if pacing_rate > 0 {
            let new_ratio = ((throughput as f64) / (pacing_rate as f64)).min(1.0);
            self.metrics.set_bw_ratio(new_ratio);
        }
    }
    
    /// Update loss rate calculation.
    fn update_loss_rate(&mut self) {
        let total_packets = self.packets_sent + self.packets_lost;
        if total_packets > 0 {
            let loss_rate = self.packets_lost as f64 / total_packets as f64;
            
            self.metrics.update(
                self.metrics.rtt(),
                loss_rate,
                self.calculate_throughput(),
                self.current_algorithm.congestion_window() as u32,
            );
        }
    }
    
    /// Calculate current loss rate.
    fn calculate_loss_rate(&self) -> f64 {
        let total_packets = self.packets_sent + self.packets_lost;
        if total_packets > 0 {
            self.packets_lost as f64 / total_packets as f64
        } else {
            0.0
        }
    }
    
    /// Calculate current throughput in bits per second.
    fn calculate_throughput(&self) -> u64 {
        let elapsed = Instant::now().duration_since(self.throughput_start);
        if elapsed.as_secs_f64() > 0.0 {
            ((self.bytes_sent * 8) as f64 / elapsed.as_secs_f64()) as u64
        } else {
            0
        }
    }
    
    /// Update the metrics window with current measurements.
    fn update_metrics_window(&mut self) {
        self.metrics_window.add_sample(
            self.metrics.rtt(),
            self.metrics.loss_rate(),
            self.metrics.bandwidth(),
        );
    }
    
    /// Get current network metrics.
    pub fn network_metrics(&self) -> &M {
        &self.metrics
    }
    
    /// Get the metrics window for advanced analysis.
    pub fn metrics_window(&self) -> &W {
        &self.metrics_window
    }
    
    /// Reset all statistics and metrics.
    pub fn reset_statistics(&mut self) {
        self.packets_sent = 0;
        self.packets_lost = 0;
        self.bytes_sent = 0;
        self.throughput_start = Instant::now();
        self.metrics.reset();
        self.metrics_window.clear();
    }
    
    /// Get the current configuration.
    pub fn config(&self) -> &CongestionConfig {
        &self.config
    }
    
    /// Update the configuration.
    pub fn set_config(&mut self, config: CongestionConfig) {
        self.config = config;
    }
    
    // Delegate methods to current algorithm
    
    /// Get the current congestion window size.
    #[inline(always)]
    pub fn congestion_window(&self) -> u64 {
        self.current_algorithm.congestion_window()
    }
    
    /// Check if more data can be sent.
    #[inline(always)]
    pub fn can_send(&self, bytes_in_flight: u64) -> bool {
        self.current_algorithm.can_send(bytes_in_flight)
    }
    
    /// Get the current pacing rate.
    #[inline(always)]
    pub fn pacing_rate(&self) -> u64 {
        self.current_algorithm.pacing_rate()
    }
    
    /// Get the name of the current algorithm.
    pub fn algorithm_name(&self) -> &'static str {
        self.current_algorithm.algorithm_name()
    }
    
    /// Get the current slow start threshold.
    pub fn ssthresh(&self) -> u64 {
        self.current_algorithm.ssthresh()
    }
    
    /// Process multiple ACKs in batch for better performance.
    pub fn process_ack_batch(&mut self, acks: &[(u64, u64, Duration)]) {
        // Update statistics for all ACKs
        for &(_, bytes, rtt) in acks {
            self.packets_sent += 1;
            self.bytes_sent += bytes;
        }
        
        // Update metrics with the most recent RTT
        if let Some(&(_, _, rtt)) = acks.last() {
            self.update_metrics_with_rtt(rtt);
        }
        
        // Forward to algorithm
        self.current_algorithm.process_ack_batch(acks);
        
        // Update metrics window
        self.update_metrics_window();
        
        // Consider algorithm switching
        self.smart_switch_decision();
    }
}