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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
//! Basic usage example for rat_congestion library
//!
//! This example demonstrates how to use the congestion control library
//! with mock network data to showcase the algorithms in action.

use rat_congestion::{
    CongestionController, ControllerConfig, NetworkMetrics, MetricsWindow,
    CongestionEvent, PLATFORM
};
use std::time::{Duration, Instant};
use std::collections::VecDeque;

/// Mock implementation of NetworkMetrics for demonstration
#[derive(Debug)]
struct MockNetworkMetrics {
    packets_sent: u64,
    packets_acked: u64,
    packets_lost: u64,
    bytes_sent: u64,
    bytes_acked: u64,
    bytes_lost: u64,
    current_rtt: Duration,
    min_rtt: Duration,
    bandwidth_estimate: u64,
    loss_rate: f64,
    bw_ratio: f64,
    rtt_cv: f64,
    last_update: Instant,
}

impl MockNetworkMetrics {
    fn new() -> Self {
        let now = Instant::now();
        Self {
            packets_sent: 0,
            packets_acked: 0,
            packets_lost: 0,
            bytes_sent: 0,
            bytes_acked: 0,
            bytes_lost: 0,
            current_rtt: Duration::from_millis(50),
            min_rtt: Duration::from_millis(50),
            bandwidth_estimate: 1_000_000, // 1 Mbps initial estimate
            loss_rate: 0.0,
            bw_ratio: 1.0,
            rtt_cv: 0.1,
            last_update: now,
        }
    }

    fn print_stats(&self) {
        println!("📊 Network Metrics:");
        println!("   Packets: sent={}, acked={}, lost={}", 
                 self.packets_sent, self.packets_acked, self.packets_lost);
        println!("   Bytes: sent={}, acked={}, lost={}", 
                 self.bytes_sent, self.bytes_acked, self.bytes_lost);
        println!("   RTT: current={:?}, min={:?}", self.current_rtt, self.min_rtt);
        println!("   Bandwidth: {} bps ({:.2} Mbps)", 
                 self.bandwidth_estimate, self.bandwidth_estimate as f64 / 1_000_000.0);
        println!("   Loss rate: {:.4}%", self.loss_rate * 100.0);
        println!("   BW ratio: {:.2}, RTT CV: {:.3}", self.bw_ratio, self.rtt_cv);
    }
}

impl NetworkMetrics for MockNetworkMetrics {
    fn on_packet_sent(&mut self, bytes: u32) {
        self.packets_sent += 1;
        self.bytes_sent += bytes as u64;
    }

    fn on_packet_acked(&mut self, bytes: u32, rtt: Duration) {
        self.packets_acked += 1;
        self.bytes_acked += bytes as u64;
        
        // Update RTT with simple exponential weighted moving average
        let alpha = 0.125; // Standard TCP alpha
        let rtt_ms = rtt.as_millis() as f64;
        let current_ms = self.current_rtt.as_millis() as f64;
        let new_rtt_ms = (1.0 - alpha) * current_ms + alpha * rtt_ms;
        self.current_rtt = Duration::from_millis(new_rtt_ms as u64);
        
        // Update min RTT
        if rtt < self.min_rtt {
            self.min_rtt = rtt;
        }
        
        // Update bandwidth estimate (simple calculation)
        let elapsed = self.last_update.elapsed();
        if elapsed > Duration::from_millis(100) {
            let throughput = (bytes as u64 * 8 * 1000) / elapsed.as_millis() as u64;
            self.bandwidth_estimate = (self.bandwidth_estimate * 7 + throughput) / 8;
            self.last_update = Instant::now();
        }
    }

    fn on_packet_lost(&mut self, bytes: u32) {
        self.packets_lost += 1;
        self.bytes_lost += bytes as u64;
        
        // Update loss rate
        let total_packets = self.packets_sent;
        if total_packets > 0 {
            self.loss_rate = self.packets_lost as f64 / total_packets as f64;
        }
    }

    fn rtt(&self) -> Duration { self.current_rtt }
    fn min_rtt(&self) -> Duration { self.min_rtt }
    fn bandwidth(&self) -> u64 { self.bandwidth_estimate }
    fn loss_rate(&self) -> f64 { self.loss_rate }
    fn bw_ratio(&self) -> f64 { self.bw_ratio }
    fn set_bw_ratio(&mut self, ratio: f64) { self.bw_ratio = ratio; }
    fn rtt_cv(&self) -> f64 { self.rtt_cv }
    fn set_rtt_cv(&mut self, cv: f64) { self.rtt_cv = cv; }
    
    fn has_variable_rtt(&self) -> bool { self.rtt_cv > 0.2 }
    fn has_low_bandwidth_utilization(&self) -> bool { self.bw_ratio < 0.8 }
    fn has_high_loss(&self) -> bool { self.loss_rate > 0.01 }
    
    fn update(&mut self, rtt: Duration, loss_rate: f64, throughput: u64, _cwnd: u32) {
        self.current_rtt = rtt;
        self.loss_rate = loss_rate;
        self.bandwidth_estimate = throughput;
    }
    
    fn reset(&mut self) {
        *self = Self::new();
    }
}

/// Mock implementation of MetricsWindow for demonstration
#[derive(Debug)]
struct MockMetricsWindow {
    samples: VecDeque<(Duration, f64, u64)>, // (rtt, loss_rate, bandwidth)
    max_size: usize,
}

impl MockMetricsWindow {
    fn new(max_size: usize) -> Self {
        Self {
            samples: VecDeque::with_capacity(max_size),
            max_size,
        }
    }

    fn print_stats(&self) {
        println!("📈 Metrics Window ({} samples):", self.samples.len());
        if !self.samples.is_empty() {
            println!("   Avg RTT: {:?}", self.avg_rtt());
            println!("   Avg Bandwidth: {} bps ({:.2} Mbps)", 
                     self.avg_bandwidth(), self.avg_bandwidth() as f64 / 1_000_000.0);
            println!("   Avg Loss Rate: {:.4}%", self.avg_loss_rate() * 100.0);
            if let Some(cv) = self.rtt_coefficient_of_variation() {
                println!("   RTT CV: {:.3}", cv);
            }
            println!("   Network Stable: {}", self.is_stable());
        }
    }
}

impl MetricsWindow for MockMetricsWindow {
    fn add_sample(&mut self, rtt: Duration, loss_rate: f64, bandwidth: u64) {
        if self.samples.len() >= self.max_size {
            self.samples.pop_front();
        }
        self.samples.push_back((rtt, loss_rate, bandwidth));
    }

    fn avg_rtt(&self) -> Duration {
        if self.samples.is_empty() {
            return Duration::from_millis(50);
        }
        let sum: u128 = self.samples.iter().map(|(rtt, _, _)| rtt.as_millis()).sum();
        Duration::from_millis((sum / self.samples.len() as u128) as u64)
    }

    fn avg_bandwidth(&self) -> u64 {
        if self.samples.is_empty() {
            return 1_000_000;
        }
        self.samples.iter().map(|(_, _, bw)| *bw).sum::<u64>() / self.samples.len() as u64
    }

    fn avg_loss_rate(&self) -> f64 {
        if self.samples.is_empty() {
            return 0.0;
        }
        self.samples.iter().map(|(_, loss, _)| *loss).sum::<f64>() / self.samples.len() as f64
    }

    fn rtt_coefficient_of_variation(&self) -> Option<f64> {
        if self.samples.len() < 2 {
            return None;
        }
        
        let rtts: Vec<f64> = self.samples.iter()
            .map(|(rtt, _, _)| rtt.as_millis() as f64)
            .collect();
        
        let mean = rtts.iter().sum::<f64>() / rtts.len() as f64;
        let variance = rtts.iter()
            .map(|x| (x - mean).powi(2))
            .sum::<f64>() / rtts.len() as f64;
        
        let std_dev = variance.sqrt();
        Some(std_dev / mean)
    }

    fn is_stable(&self) -> bool {
        if let Some(cv) = self.rtt_coefficient_of_variation() {
            cv < 0.2 && self.avg_loss_rate() < 0.005
        } else {
            true
        }
    }

    fn clear(&mut self) {
        self.samples.clear();
    }
}

/// Generate mock network events to simulate real network conditions
struct NetworkSimulator {
    base_rtt: Duration,
    base_bandwidth: u64,
    packet_size: u32,
    time: Instant,
}

impl NetworkSimulator {
    fn new() -> Self {
        Self {
            base_rtt: Duration::from_millis(50),
            base_bandwidth: 10_000_000, // 10 Mbps
            packet_size: 1460, // Standard MTU
            time: Instant::now(),
        }
    }

    /// Simulate network conditions changing over time
    fn simulate_network_event(&mut self, step: usize) -> (Duration, bool) {
        // Simulate different network conditions
        let (rtt_variation, loss_probability) = match step {
            0..=50 => {
                // Good network conditions
                (0.1, 0.001)
            },
            51..=100 => {
                // Network congestion starts
                (0.3, 0.01)
            },
            101..=150 => {
                // High congestion
                (0.5, 0.03)
            },
            151..=200 => {
                // Recovery phase
                (0.2, 0.005)
            },
            _ => {
                // Stable again
                (0.1, 0.001)
            }
        };

        // Add random variation to RTT
        let rtt_factor = 1.0 + (fastrand::f64() - 0.5) * rtt_variation;
        let current_rtt = Duration::from_millis(
            (self.base_rtt.as_millis() as f64 * rtt_factor) as u64
        );

        // Determine if packet is lost
        let is_lost = fastrand::f64() < loss_probability;

        (current_rtt, is_lost)
    }
}

fn main() {
    println!("🚀 RAT Congestion Control Library Demo");
    println!("=====================================\n");
    
    // Display platform information
    println!("🖥️  Platform: {}", PLATFORM);
    println!();

    // Create mock metrics and window
    let metrics = MockNetworkMetrics::new();
    let metrics_window = MockMetricsWindow::new(32);
    
    // Create different controller configurations for comparison
    println!("🔧 Creating Controllers...");
    
    // BBR Controller
    let bbr_config = ControllerConfig::builder()
        .initial_algorithm("bbr")
        .auto_switching(false)
        .build();
    let mut bbr_controller = CongestionController::with_config(
        bbr_config, 
        MockNetworkMetrics::new(), 
        MockMetricsWindow::new(32)
    );
    
    // CUBIC Controller
    let cubic_config = ControllerConfig::builder()
        .initial_algorithm("cubic")
        .auto_switching(false)
        .build();
    let mut cubic_controller = CongestionController::with_config(
        cubic_config,
        MockNetworkMetrics::new(),
        MockMetricsWindow::new(32)
    );
    
    // Adaptive Controller
    let mut adaptive_controller = CongestionController::adaptive(
        MockNetworkMetrics::new(),
        MockMetricsWindow::new(32)
    );
    
    println!("✅ Controllers created:");
    println!("   - BBR Controller (algorithm: {})", bbr_controller.current_algorithm());
    println!("   - CUBIC Controller (algorithm: {})", cubic_controller.current_algorithm());
    println!("   - Adaptive Controller (algorithm: {})", adaptive_controller.current_algorithm());
    println!();
    
    // Network simulator
    let mut simulator = NetworkSimulator::new();
    
    println!("🌐 Starting Network Simulation...");
    println!("==================================\n");
    
    // Simulate network traffic
    for step in 0..250 {
        let (rtt, is_lost) = simulator.simulate_network_event(step);
        let packet_size = simulator.packet_size;
        
        // Process the same event for all controllers
        if is_lost {
            bbr_controller.on_packet_lost(packet_size as u64);
            cubic_controller.on_packet_lost(packet_size as u64);
            adaptive_controller.on_packet_lost(packet_size as u64);
        } else {
            bbr_controller.on_packet_acked(packet_size as u64, rtt);
            cubic_controller.on_packet_acked(packet_size as u64, rtt);
            adaptive_controller.on_packet_acked(packet_size as u64, rtt);
        }
        
        // Print detailed status every 50 steps
        if step % 50 == 0 {
            println!("📊 Step {}: Network Conditions", step);
            println!("   RTT: {:?}, Packet Lost: {}", rtt, is_lost);
            println!();
            
            // BBR Status
            println!("🔵 BBR Controller Status:");
            println!("   Algorithm: {}", bbr_controller.current_algorithm());
            println!("   Window Size: {} bytes ({:.1} KB)", 
                     bbr_controller.window_size(), 
                     bbr_controller.window_size() as f64 / 1024.0);
            println!("   Pacing Rate: {} bps ({:.2} Mbps)", 
                     bbr_controller.pacing_rate(),
                     bbr_controller.pacing_rate() as f64 / 1_000_000.0);
            println!("   SSThresh: {}", bbr_controller.slow_start_threshold());
            println!("   Can Send 10KB: {}", bbr_controller.can_send(10240));
            println!();
            
            // CUBIC Status
            println!("🟠 CUBIC Controller Status:");
            println!("   Algorithm: {}", cubic_controller.current_algorithm());
            println!("   Window Size: {} bytes ({:.1} KB)", 
                     cubic_controller.window_size(),
                     cubic_controller.window_size() as f64 / 1024.0);
            println!("   Pacing Rate: {} bps ({:.2} Mbps)", 
                     cubic_controller.pacing_rate(),
                     cubic_controller.pacing_rate() as f64 / 1_000_000.0);
            println!("   SSThresh: {}", cubic_controller.slow_start_threshold());
            println!("   Can Send 10KB: {}", cubic_controller.can_send(10240));
            println!();
            
            // Adaptive Status
            println!("🟢 Adaptive Controller Status:");
            println!("   Algorithm: {}", adaptive_controller.current_algorithm());
            println!("   Window Size: {} bytes ({:.1} KB)", 
                     adaptive_controller.window_size(),
                     adaptive_controller.window_size() as f64 / 1024.0);
            println!("   Pacing Rate: {} bps ({:.2} Mbps)", 
                     adaptive_controller.pacing_rate(),
                     adaptive_controller.pacing_rate() as f64 / 1_000_000.0);
            println!("   SSThresh: {}", adaptive_controller.slow_start_threshold());
            println!("   Can Send 10KB: {}", adaptive_controller.can_send(10240));
            println!();
            
            println!("{}", "=".repeat(60));
            println!();
        }
        
        // Brief status every 10 steps
        if step % 10 == 0 && step % 50 != 0 {
            println!("Step {}: BBR={:.1}KB, CUBIC={:.1}KB, Adaptive={:.1}KB ({})", 
                     step,
                     bbr_controller.window_size() as f64 / 1024.0,
                     cubic_controller.window_size() as f64 / 1024.0,
                     adaptive_controller.window_size() as f64 / 1024.0,
                     adaptive_controller.current_algorithm());
        }
    }
    
    println!();
    println!("🏁 Simulation Complete!");
    println!("======================\n");
    
    // Final comparison
    println!("📈 Final Performance Comparison:");
    println!("BBR Controller:");
    println!("   Final Window: {:.1} KB", bbr_controller.window_size() as f64 / 1024.0);
    println!("   Final Pacing Rate: {:.2} Mbps", bbr_controller.pacing_rate() as f64 / 1_000_000.0);
    println!();
    
    println!("CUBIC Controller:");
    println!("   Final Window: {:.1} KB", cubic_controller.window_size() as f64 / 1024.0);
    println!("   Final Pacing Rate: {:.2} Mbps", cubic_controller.pacing_rate() as f64 / 1_000_000.0);
    println!();
    
    println!("Adaptive Controller:");
    println!("   Final Algorithm: {}", adaptive_controller.current_algorithm());
    println!("   Final Window: {:.1} KB", adaptive_controller.window_size() as f64 / 1024.0);
    println!("   Final Pacing Rate: {:.2} Mbps", adaptive_controller.pacing_rate() as f64 / 1_000_000.0);
    println!();
    
    // Demonstrate batch processing
    println!("🔄 Demonstrating Batch Processing:");
    let ack_batch = vec![
        (1460, Duration::from_millis(45)),
        (1460, Duration::from_millis(47)),
        (1460, Duration::from_millis(52)),
        (1460, Duration::from_millis(49)),
        (1460, Duration::from_millis(51)),
    ];
    
    println!("Processing batch of {} ACKs...", ack_batch.len());
    adaptive_controller.process_ack_batch(&ack_batch);
    println!("✅ Batch processed. New window size: {:.1} KB", 
             adaptive_controller.window_size() as f64 / 1024.0);
    println!();
    
    // Demonstrate algorithm switching
    println!("🔀 Demonstrating Manual Algorithm Switching:");
    let current = adaptive_controller.current_algorithm();
    let target = if current == "BBR" { "cubic" } else { "bbr" };
    println!("Switching from {} to {}...", current, target);
    adaptive_controller.switch_algorithm(target);
    println!("✅ Switched to: {}", adaptive_controller.current_algorithm());
    println!();
    
    // Platform information
    println!("🖥️  Platform Information:");
    println!("Platform: {}", adaptive_controller.platform());
    println!();
    
    println!("🎉 Demo completed successfully!");
    println!("This example showed:");
    println!("  ✓ Different controller configurations");
    println!("  ✓ Network simulation with varying conditions");
    println!("  ✓ Real-time performance monitoring");
    println!("  ✓ Algorithm comparison");
    println!("  ✓ Batch processing capabilities");
    println!("  ✓ Dynamic algorithm switching");
}