ant-quic 0.27.24

QUIC transport protocol with advanced NAT traversal for P2P networks
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
// Copyright 2024 Saorsa Labs Ltd.
//
// This Saorsa Network Software is licensed under the General Public License (GPL), version 3.
// Please see the file LICENSE-GPL, or visit <http://www.gnu.org/licenses/> for the full text.
//
// Full details available at https://saorsalabs.com/licenses

//! Read-only path handles for observing per-path connection state.

use std::{
    fmt,
    net::SocketAddr,
    sync::{Arc, Mutex},
};

use crate::{connection::PathStats, high_level::WeakConnectionHandle};

/// Identifier for a QUIC connection path.
///
/// The current read-only skeleton exposes only the primary single-path route.
/// Future multipath support will allocate additional IDs.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PathId(u64);

impl PathId {
    /// The primary single-path route used before multipath is negotiated.
    pub const PRIMARY: Self = Self(0);

    /// Return the numeric path identifier.
    pub const fn get(self) -> u64 {
        self.0
    }
}

impl From<u64> for PathId {
    fn from(value: u64) -> Self {
        Self(value)
    }
}

impl From<PathId> for u64 {
    fn from(value: PathId) -> Self {
        value.0
    }
}

impl fmt::Display for PathId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::connection::PathStats;

    // ── PathId tests ──

    #[test]
    fn path_id_primary_is_zero() {
        assert_eq!(PathId::PRIMARY.get(), 0);
    }

    #[test]
    fn path_id_from_u64() {
        let id: PathId = 42u64.into();
        assert_eq!(id.get(), 42);
    }

    #[test]
    fn path_id_into_u64() {
        let id = PathId::PRIMARY;
        let val: u64 = id.into();
        assert_eq!(val, 0);
    }

    #[test]
    fn path_id_default_is_zero() {
        let id = PathId::default();
        assert_eq!(id.get(), 0);
        assert_eq!(id, PathId::PRIMARY);
    }

    #[test]
    fn path_id_equality() {
        assert_eq!(PathId::from(1u64), PathId::from(1u64));
        assert_ne!(PathId::from(1u64), PathId::from(2u64));
    }

    #[test]
    fn path_id_ordering() {
        assert!(PathId::from(0u64) < PathId::from(1u64));
        assert!(PathId::from(1u64) > PathId::from(0u64));
    }

    #[test]
    fn path_id_display() {
        assert_eq!(format!("{}", PathId::PRIMARY), "0");
        assert_eq!(format!("{}", PathId::from(42u64)), "42");
    }

    #[test]
    fn path_id_debug() {
        let debug = format!("{:?}", PathId::from(42u64));
        assert!(debug.contains("42"));
    }

    #[test]
    fn path_id_clone() {
        let a = PathId::from(5u64);
        let b = a;
        assert_eq!(a, b);
    }

    #[test]
    fn path_id_hash() {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let a = PathId::from(10u64);
        let b = PathId::from(10u64);
        let mut ha = DefaultHasher::new();
        let mut hb = DefaultHasher::new();
        a.hash(&mut ha);
        b.hash(&mut hb);
        assert_eq!(ha.finish(), hb.finish());
    }

    // ── PathSnapshot tests ──

    #[test]
    fn path_snapshot_default() {
        let stats = PathStats::default();
        // PathSnapshot is pub(crate), test via construction
        let snapshot = PathSnapshot {
            stats,
            remote_address: "127.0.0.1:9000".parse().unwrap(),
            observed_external_addr: None,
        };
        assert_eq!(snapshot.remote_address.port(), 9000);
        assert!(snapshot.observed_external_addr.is_none());
    }

    #[test]
    fn path_snapshot_with_external_addr() {
        let stats = PathStats::default();
        let snapshot = PathSnapshot {
            stats,
            remote_address: "192.168.1.1:9000".parse().unwrap(),
            observed_external_addr: Some("10.0.0.1:9001".parse().unwrap()),
        };
        assert!(snapshot.observed_external_addr.is_some());
        assert_eq!(
            snapshot.observed_external_addr.unwrap().to_string(),
            "10.0.0.1:9001"
        );
    }

    #[test]
    fn path_snapshot_clone_copy() {
        let stats = PathStats::default();
        let s1 = PathSnapshot {
            stats,
            remote_address: "127.0.0.1:80".parse().unwrap(),
            observed_external_addr: None,
        };
        let s2 = s1;
        assert_eq!(s1.remote_address, s2.remote_address);
    }

    // ── RetainedPathSnapshot tests ──

    #[test]
    fn retained_path_snapshot_store_and_load() {
        let stats = PathStats::default();
        let snapshot = PathSnapshot {
            stats,
            remote_address: "127.0.0.1:9000".parse().unwrap(),
            observed_external_addr: None,
        };
        let retained = RetainedPathSnapshot::new(snapshot);
        let loaded = retained.load();
        assert_eq!(loaded.remote_address.port(), 9000);
    }

    #[test]
    fn retained_path_snapshot_overwrite() {
        let stats = PathStats::default();
        let snapshot1 = PathSnapshot {
            stats,
            remote_address: "127.0.0.1:1".parse().unwrap(),
            observed_external_addr: None,
        };
        let retained = RetainedPathSnapshot::new(snapshot1);

        let snapshot2 = PathSnapshot {
            stats: PathStats::default(),
            remote_address: "127.0.0.1:2".parse().unwrap(),
            observed_external_addr: None,
        };
        retained.store(snapshot2);

        let loaded = retained.load();
        assert_eq!(loaded.remote_address.port(), 2);
    }

    #[test]
    fn retained_path_snapshot_clone() {
        let stats = PathStats::default();
        let snapshot = PathSnapshot {
            stats,
            remote_address: "10.0.0.1:8000".parse().unwrap(),
            observed_external_addr: None,
        };
        let retained = RetainedPathSnapshot::new(snapshot);
        let cloned = retained.clone();
        assert_eq!(retained.load().remote_address, cloned.load().remote_address);
    }

    #[test]
    fn retained_path_snapshot_concurrent_independence() {
        let stats = PathStats::default();
        let snapshot = PathSnapshot {
            stats,
            remote_address: "127.0.0.1:9000".parse().unwrap(),
            observed_external_addr: None,
        };
        let retained = RetainedPathSnapshot::new(snapshot);
        let cloned = retained.clone();

        // Update one, the other should still see the old value
        let new_snapshot = PathSnapshot {
            stats: PathStats::default(),
            remote_address: "127.0.0.1:9999".parse().unwrap(),
            observed_external_addr: None,
        };
        retained.store(new_snapshot);

        assert_eq!(retained.load().remote_address.port(), 9999);
        assert_eq!(cloned.load().remote_address.port(), 9999); // shared Arc
    }
}

/// Snapshot of read-only path state.
#[derive(Debug, Clone, Copy)]
pub(crate) struct PathSnapshot {
    pub(crate) stats: PathStats,
    pub(crate) remote_address: SocketAddr,
    pub(crate) observed_external_addr: Option<SocketAddr>,
}

#[derive(Debug, Clone)]
struct RetainedPathSnapshot(Arc<Mutex<PathSnapshot>>);

impl RetainedPathSnapshot {
    fn new(snapshot: PathSnapshot) -> Self {
        Self(Arc::new(Mutex::new(snapshot)))
    }

    fn load(&self) -> PathSnapshot {
        match self.0.lock() {
            Ok(snapshot) => *snapshot,
            Err(poisoned) => *poisoned.into_inner(),
        }
    }

    fn store(&self, snapshot: PathSnapshot) {
        match self.0.lock() {
            Ok(mut retained) => *retained = snapshot,
            Err(poisoned) => *poisoned.into_inner() = snapshot,
        }
    }
}

/// Read-only handle to a QUIC connection path.
///
/// `Path` does not keep the underlying connection alive. Accessors read live
/// state while the connection exists and fall back to the retained snapshot
/// after the connection/path has gone away.
#[derive(Debug, Clone)]
pub struct Path {
    conn_handle: WeakConnectionHandle,
    id: PathId,
    retained: RetainedPathSnapshot,
}

impl Path {
    pub(crate) fn new(
        conn_handle: WeakConnectionHandle,
        id: PathId,
        snapshot: PathSnapshot,
    ) -> Self {
        Self {
            conn_handle,
            id,
            retained: RetainedPathSnapshot::new(snapshot),
        }
    }

    fn live_snapshot(&self) -> Option<PathSnapshot> {
        self.conn_handle
            .upgrade()
            .and_then(|conn| conn.path_snapshot(self.id))
    }

    fn snapshot(&self) -> PathSnapshot {
        if let Some(snapshot) = self.live_snapshot() {
            self.retained.store(snapshot);
            snapshot
        } else {
            self.retained.load()
        }
    }

    /// Return this path's identifier.
    pub fn id(&self) -> PathId {
        self.id
    }

    /// Return the latest readable statistics for this path.
    pub fn stats(&self) -> PathStats {
        self.snapshot().stats
    }

    /// Return the peer UDP address associated with this path.
    pub fn remote_address(&self) -> SocketAddr {
        self.snapshot().remote_address
    }

    /// Return the external/reflexive address observed for this path.
    pub fn observed_external_addr(&self) -> Option<SocketAddr> {
        self.snapshot().observed_external_addr
    }

    /// Downgrade this path to a weak handle.
    pub fn weak_handle(&self) -> WeakPathHandle {
        WeakPathHandle {
            conn_handle: self.conn_handle.clone(),
            id: self.id,
            retained: self.retained.clone(),
        }
    }
}

impl Drop for Path {
    fn drop(&mut self) {
        if let Some(snapshot) = self.live_snapshot() {
            self.retained.store(snapshot);
        }
    }
}

/// Weak read-only handle to a QUIC connection path.
///
/// The handle can expose retained path state after the connection/path has
/// closed without keeping the connection alive.
#[derive(Debug, Clone)]
pub struct WeakPathHandle {
    conn_handle: WeakConnectionHandle,
    id: PathId,
    retained: RetainedPathSnapshot,
}

impl WeakPathHandle {
    fn live_snapshot(&self) -> Option<PathSnapshot> {
        self.conn_handle
            .upgrade()
            .and_then(|conn| conn.path_snapshot(self.id))
    }

    fn snapshot(&self) -> PathSnapshot {
        if let Some(snapshot) = self.live_snapshot() {
            self.retained.store(snapshot);
            snapshot
        } else {
            self.retained.load()
        }
    }

    /// Return this path's identifier.
    pub fn id(&self) -> PathId {
        self.id
    }

    /// Upgrade to a live path handle if the path's connection is still alive.
    pub fn upgrade(&self) -> Option<Path> {
        if !self.conn_handle.is_alive() {
            return None;
        }

        let snapshot = self.live_snapshot()?;
        Some(Path {
            conn_handle: self.conn_handle.clone(),
            id: self.id,
            retained: RetainedPathSnapshot::new(snapshot),
        })
    }

    /// Return true while the underlying path's connection is still alive.
    pub fn is_alive(&self) -> bool {
        self.conn_handle.is_alive() && self.live_snapshot().is_some()
    }

    /// Return the latest readable statistics for this path.
    pub fn stats(&self) -> PathStats {
        self.snapshot().stats
    }

    /// Return the retained or live peer UDP address associated with this path.
    pub fn remote_address(&self) -> SocketAddr {
        self.snapshot().remote_address
    }

    /// Return the retained or live external/reflexive address for this path.
    pub fn observed_external_addr(&self) -> Option<SocketAddr> {
        self.snapshot().observed_external_addr
    }
}