rustrtc 0.3.70

A high-performance real-time communication library — WebRTC, RTP/SRTP, T.38 Fax, and RTP Latching
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
471
472
473
474
475
476
use parking_lot::Mutex;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};

/// Port allocation record with TTL tracking.
#[derive(Debug, Clone)]
struct PortRecord {
    allocated_at: Instant,
    ttl: Duration,
}

impl PortRecord {
    fn is_expired(&self) -> bool {
        self.allocated_at.elapsed() >= self.ttl
    }

    fn remaining(&self) -> Duration {
        self.ttl.saturating_sub(self.allocated_at.elapsed())
    }
}

/// Bitmap for tracking port usage.
struct PortBitmap {
    bits: Vec<u64>,
    start: u16,
    end: u16,
    count: u16,
    used: u16,
}

impl PortBitmap {
    fn new(start: u16, end: u16) -> Self {
        let count = end - start + 1;
        let words = (count as usize + 63) / 64;
        Self {
            bits: vec![0u64; words],
            start,
            end,
            count,
            used: 0,
        }
    }

    #[inline]
    fn bit_index(&self, port: u16) -> (usize, u8) {
        let idx = (port - self.start) as usize;
        (idx / 64, (idx % 64) as u8)
    }

    #[inline]
    fn is_set(&self, port: u16) -> bool {
        let (word, bit) = self.bit_index(port);
        (self.bits[word] >> bit) & 1 == 1
    }

    #[inline]
    fn set(&mut self, port: u16) {
        let (word, bit) = self.bit_index(port);
        self.bits[word] |= 1u64 << bit;
        self.used += 1;
    }

    #[inline]
    fn clear(&mut self, port: u16) {
        let (word, bit) = self.bit_index(port);
        self.bits[word] &= !(1u64 << bit);
        self.used -= 1;
    }

    /// Allocate a free port with random probe.
    fn allocate(&mut self, rng: u64) -> Option<u16> {
        if self.used >= self.count {
            return None;
        }

        let random_offset = (rng % self.count as u64) as u16;
        let probe_port = self.start + random_offset;

        for i in 0..self.count {
            let port = probe_port.wrapping_add(i).wrapping_rem(self.count);
            let port = self.start + port;
            if !self.is_set(port) {
                self.set(port);
                return Some(port);
            }
        }
        None
    }

    /// Allocate a free even port with random probe.
    fn allocate_even(&mut self, rng: u64) -> Option<u16> {
        let even_start = if self.start % 2 == 0 { self.start } else { self.start + 1 };
        let even_end = if self.end % 2 == 0 { self.end } else { self.end - 1 };

        if even_start > even_end {
            return None;
        }

        let even_count = ((even_end - even_start) / 2 + 1) as u64;
        let random_offset = (rng % even_count) as u16;
        let mut port = even_start + random_offset * 2;

        for _ in 0..even_count {
            if !self.is_set(port) {
                self.set(port);
                return Some(port);
            }
            port += 2;
            if port > even_end {
                port = even_start;
            }
        }
        None
    }
}

/// Port allocator with TTL-based recycling.
///
/// # Features
/// - O(1) allocation via bitmap
/// - Automatic TTL-based recycling (ports released after TTL expires)
/// - Manual release support
/// - Periodic cleanup task
///
/// # TTL Strategy
/// - Default TTL: 5 minutes (suitable for RTP sessions)
/// - Ports are marked as "allocated" with timestamp
/// - Background cleanup releases expired ports
/// - Manual release for explicit cleanup (e.g., socket close)
#[derive(Clone)]
pub(crate) struct PortAllocator {
    inner: Arc<Mutex<PortAllocatorInner>>,
    start: u16,
    end: u16,
    default_ttl: Duration,
}

struct PortAllocatorInner {
    bitmap: PortBitmap,
    records: HashMap<u16, PortRecord>,
}

impl std::fmt::Debug for PortAllocator {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let inner = self.inner.lock();
        f.debug_struct("PortAllocator")
            .field("range", &(self.start, self.end))
            .field("allocated", &inner.records.len())
            .field("capacity", &inner.bitmap.count)
            .field("default_ttl", &self.default_ttl)
            .finish()
    }
}

impl PortAllocator {
    /// Create a new port allocator with default TTL (5 minutes).
    pub fn new(start: u16, end: u16) -> Self {
        Self::with_ttl(start, end, Duration::from_secs(300))
    }

    /// Create a new port allocator with custom TTL.
    pub fn with_ttl(start: u16, end: u16, ttl: Duration) -> Self {
        Self {
            inner: Arc::new(Mutex::new(PortAllocatorInner {
                bitmap: PortBitmap::new(start, end),
                records: HashMap::new(),
            })),
            start,
            end,
            default_ttl: ttl,
        }
    }

    /// Allocate a port with default TTL.
    pub fn allocate(&self) -> Option<u16> {
        self.allocate_with_ttl(self.default_ttl)
    }

    /// Allocate a port with custom TTL.
    pub fn allocate_with_ttl(&self, ttl: Duration) -> Option<u16> {
        let rng = crate::transports::ice::stun::random_u64();
        let mut inner = self.inner.lock();
        let port = inner.bitmap.allocate(rng)?;
        inner.records.insert(port, PortRecord {
            allocated_at: Instant::now(),
            ttl,
        });
        Some(port)
    }

    /// Allocate an even port with default TTL.
    pub fn allocate_even(&self) -> Option<u16> {
        self.allocate_even_with_ttl(self.default_ttl)
    }

    /// Allocate an even port with custom TTL.
    pub fn allocate_even_with_ttl(&self, ttl: Duration) -> Option<u16> {
        let rng = crate::transports::ice::stun::random_u64();
        let mut inner = self.inner.lock();
        let port = inner.bitmap.allocate_even(rng)?;
        inner.records.insert(port, PortRecord {
            allocated_at: Instant::now(),
            ttl,
        });
        Some(port)
    }

    /// Release a port immediately.
    pub fn release(&self, port: u16) {
        let mut inner = self.inner.lock();
        if inner.bitmap.is_set(port) {
            inner.bitmap.clear(port);
            inner.records.remove(&port);
        }
    }

    /// Renew a port's TTL (extend its lifetime).
    pub fn renew(&self, port: u16) {
        self.renew_with_ttl(port, self.default_ttl);
    }

    /// Renew a port's TTL with custom duration.
    pub fn renew_with_ttl(&self, port: u16, ttl: Duration) {
        let mut inner = self.inner.lock();
        if let Some(record) = inner.records.get_mut(&port) {
            record.allocated_at = Instant::now();
            record.ttl = ttl;
        }
    }

    /// Clean up expired ports. Returns number of released ports.
    pub fn cleanup_expired(&self) -> usize {
        let mut inner = self.inner.lock();
        let expired: Vec<u16> = inner.records.iter()
            .filter(|(_, record)| record.is_expired())
            .map(|(&port, _)| port)
            .collect();

        let count = expired.len();
        for port in expired {
            inner.bitmap.clear(port);
            inner.records.remove(&port);
        }
        count
    }

    /// Get number of allocated ports.
    pub fn allocated_count(&self) -> u16 {
        let inner = self.inner.lock();
        inner.records.len() as u16
    }

    /// Get number of expired ports (not yet cleaned up).
    pub fn expired_count(&self) -> usize {
        let inner = self.inner.lock();
        inner.records.values().filter(|r| r.is_expired()).count()
    }

    /// Get total capacity.
    pub fn capacity(&self) -> u16 {
        self.end - self.start + 1
    }

    /// Get the port range.
    pub fn port_range(&self) -> (u16, u16) {
        (self.start, self.end)
    }

    /// Get remaining TTL for a port.
    pub fn remaining_ttl(&self, port: u16) -> Option<Duration> {
        let inner = self.inner.lock();
        inner.records.get(&port).map(|r| r.remaining())
    }

    /// Start a background cleanup task that runs periodically.
    /// Returns a JoinHandle that can be used to stop the task.
    pub fn start_cleanup_task(self, interval: Duration) -> tokio::task::JoinHandle<()> {
        tokio::spawn(async move {
            let mut timer = tokio::time::interval(interval);
            loop {
                timer.tick().await;
                let released = self.cleanup_expired();
                if released > 0 {
                    tracing::debug!("Port allocator: released {} expired ports", released);
                }
            }
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::thread;

    #[test]
    fn test_port_allocator_basic() {
        let allocator = PortAllocator::new(1000, 1009);
        assert_eq!(allocator.capacity(), 10);

        let port = allocator.allocate().unwrap();
        assert!(port >= 1000 && port <= 1009);
        assert_eq!(allocator.allocated_count(), 1);

        allocator.release(port);
        assert_eq!(allocator.allocated_count(), 0);
    }

    #[test]
    fn test_port_allocator_ttl_expiry() {
        // Create allocator with 100ms TTL
        let allocator = PortAllocator::with_ttl(1000, 1004, Duration::from_millis(100));

        let port = allocator.allocate().unwrap();
        assert_eq!(allocator.allocated_count(), 1);
        assert!(allocator.expired_count() == 0);

        // Wait for TTL to expire
        thread::sleep(Duration::from_millis(150));

        assert_eq!(allocator.expired_count(), 1);

        // Cleanup should release the port
        let released = allocator.cleanup_expired();
        assert_eq!(released, 1);
        assert_eq!(allocator.allocated_count(), 0);
    }

    #[test]
    fn test_port_allocator_renew() {
        let allocator = PortAllocator::with_ttl(1000, 1004, Duration::from_millis(100));

        let port = allocator.allocate().unwrap();

        // Wait 80ms, then renew
        thread::sleep(Duration::from_millis(80));
        allocator.renew(port);

        // Wait another 80ms (total 160ms > 100ms TTL, but renewed at 80ms)
        thread::sleep(Duration::from_millis(80));

        // Should NOT be expired (renewed at 80ms, TTL is 100ms from renewal)
        assert_eq!(allocator.expired_count(), 0, "Port should not be expired after renewal");

        // Wait another 50ms to exceed the renewal TTL
        thread::sleep(Duration::from_millis(50));
        assert_eq!(allocator.expired_count(), 1, "Port should be expired after renewal TTL");
    }

    #[test]
    fn test_port_allocator_thread_safety() {
        let allocator = Arc::new(PortAllocator::new(10000, 19999));
        let mut handles = vec![];

        // Spawn 50 threads, each allocating 20 ports
        for _ in 0..50 {
            let alloc = allocator.clone();
            handles.push(thread::spawn(move || {
                let mut ports = vec![];
                for _ in 0..20 {
                    if let Some(port) = alloc.allocate_even() {
                        ports.push(port);
                    }
                }
                ports
            }));
        }

        let mut all_ports = vec![];
        for h in handles {
            all_ports.extend(h.join().unwrap());
        }

        // All ports should be unique
        let unique_count = {
            all_ports.sort();
            all_ports.dedup();
            all_ports.len()
        };
        assert_eq!(unique_count, 1000);
    }

    #[test]
    fn test_port_allocator_exhaustion_and_recycling() {
        let allocator = PortAllocator::with_ttl(30000, 30001, Duration::from_millis(50));

        // Allocate the only even port
        let p1 = allocator.allocate_even().unwrap();
        assert_eq!(p1, 30000);

        // Should fail - no more even ports
        assert!(allocator.allocate_even().is_none());

        // Wait for TTL to expire
        thread::sleep(Duration::from_millis(100));

        // Cleanup expired ports
        allocator.cleanup_expired();

        // Should be able to allocate again
        let p2 = allocator.allocate_even().unwrap();
        assert_eq!(p2, 30000);
    }

    #[test]
    fn test_port_allocator_manual_release_before_ttl() {
        let allocator = PortAllocator::with_ttl(40000, 40004, Duration::from_secs(60));

        let port = allocator.allocate().unwrap();
        assert_eq!(allocator.allocated_count(), 1);

        // Manually release before TTL
        allocator.release(port);
        assert_eq!(allocator.allocated_count(), 0);

        // Port should be available again
        let port2 = allocator.allocate().unwrap();
        assert_eq!(port, port2);
    }

    #[tokio::test]
    async fn test_port_allocator_cleanup_task() {
        let allocator = PortAllocator::with_ttl(50000, 50004, Duration::from_millis(100));

        let _port = allocator.allocate().unwrap();
        assert_eq!(allocator.allocated_count(), 1);

        // Start cleanup task (runs every 50ms)
        let handle = allocator.clone().start_cleanup_task(Duration::from_millis(50));

        // Wait for TTL + cleanup cycle
        tokio::time::sleep(Duration::from_millis(300)).await;

        // Port should be cleaned up
        assert_eq!(allocator.allocated_count(), 0);

        handle.abort();
    }

    #[test]
    fn test_port_allocator_high_concurrency_performance() {
        let allocator = PortAllocator::new(10000, 59999);
        let start = Instant::now();

        // Allocate 10000 even ports
        let mut ports = Vec::with_capacity(10000);
        for _ in 0..10000 {
            if let Some(port) = allocator.allocate_even() {
                ports.push(port);
            }
        }

        let elapsed = start.elapsed();
        assert_eq!(ports.len(), 10000);

        // Verify uniqueness
        let mut sorted = ports.clone();
        sorted.sort();
        sorted.dedup();
        assert_eq!(sorted.len(), 10000);

        // Performance: should be < 50ms
        assert!(
            elapsed.as_millis() < 50,
            "10000 allocations took {:?}, expected < 50ms",
            elapsed
        );

        // Release all
        for port in &ports {
            allocator.release(*port);
        }
        assert_eq!(allocator.allocated_count(), 0);
    }
}