zudp 0.4.2

Zero-overhead UDP protocol with optional reliability, fragmentation, and relay support
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
use std::{
    collections::{BTreeMap, HashMap, HashSet},
    hash::{Hash, Hasher},
    sync::{
        Arc,
        atomic::{AtomicU32, AtomicU64, Ordering},
    },
    time::{Duration, Instant, SystemTime},
};

#[cfg(feature = "security")]
use std::{net::SocketAddr, sync::atomic::AtomicBool};

use tokio::sync::oneshot;

use bytes::Bytes;
use parking_lot::{Mutex, RwLock};

use crate::PeerAddr;
use crate::cc::CongestionCtrl;
use crate::frame::MAX_NACK_SEQS;
#[cfg(feature = "security")]
use crate::security::SecureChannel;

/// A fully encoded frame retained for NACK-triggered retransmission.
pub struct SentPacket {
    pub frame: Bytes,
    pub sent_at: Instant,
}

/// Send-side state for one remote peer, shared between the caller and the engine task.
pub struct PeerState {
    /// Current remote address; updated transparently on network migration.
    addr: Arc<RwLock<PeerAddr>>,
    /// Unique per `PeerState`; receive state tagged with another generation is stale.
    pub generation: u64,
    /// Engine instance id the remote puts in its Pings and Pongs.  A different id from the
    /// same address means the remote process restarted.
    their_session_id: Mutex<Option<u64>>,
    /// Per-stream sequence counters; each stream starts at 1 and advances independently.
    next_seqs: Mutex<HashMap<u16, u64>>,
    /// Per-stream send buffers for NACK-triggered retransmission.
    pub sent: Mutex<HashMap<u16, BTreeMap<u64, SentPacket>>>,
    pub last_sent: Mutex<Instant>,
    pub last_seen: Mutex<Instant>,
    /// RTT-based congestion controller; updated on every Pong.
    pub cc: Mutex<CongestionCtrl>,
    /// Path MTU discovered by PLPMTUD; 0 = discovery not yet complete, use config default.
    effective_mtu: AtomicU32,
    /// Pending MTU probe acks: maps `probe_id → oneshot sender` woken by the engine on `MtuAck`.
    pub probe_acks: Mutex<HashMap<u16, oneshot::Sender<()>>>,
    /// Established Noise transport channel; replaced on every completed handshake so
    /// reconnecting peers get fresh keys instead of silently reusing stale ones.
    #[cfg(feature = "security")]
    pub channel: RwLock<Option<SecureChannel>>,
    /// The remote peer's X25519 static public key from the handshake that set `channel`.
    #[cfg(feature = "security")]
    remote_static_key: RwLock<Option<[u8; 32]>>,
    /// Set once an authenticated frame arrived on the current channel.
    #[cfg(feature = "security")]
    confirmed: AtomicBool,
    /// Woken (`notify_waiters`) when `confirmed` becomes true.
    #[cfg(feature = "security")]
    pub confirmed_notify: tokio::sync::Notify,
    /// Our msg3, resent until the responder confirms it has the session too.
    #[cfg(feature = "security")]
    finish_wire: Mutex<Option<Bytes>>,
    /// We initiated this session, so we are the side that re-handshakes when it is lost.
    #[cfg(feature = "security")]
    initiator: AtomicBool,
    /// When a re-handshake for this session was last started.
    #[cfg(feature = "security")]
    rehandshake_started: Mutex<Option<Instant>>,
    /// Highest nonce authenticated so far; only a newer frame may move the session to a
    /// new address, so a replayed old datagram cannot redirect it.
    #[cfg(feature = "security")]
    highest_nonce: AtomicU64,
    /// For a relayed peer: the punched direct address now carrying its traffic, and when
    /// an authenticated frame last arrived there.  `None` while traffic goes via the relay.
    #[cfg(feature = "security")]
    direct: Mutex<Option<(SocketAddr, Instant)>>,
    /// For a relayed peer: when we last asked the relay for an introduction.
    #[cfg(feature = "security")]
    last_intro: Mutex<Option<Instant>>,
    /// For a relayed peer: an introduction we asked for and have not received yet.
    #[cfg(feature = "security")]
    intro_open: Mutex<Option<Instant>>,
    /// For a relayed peer: a punch campaign is running.
    #[cfg(feature = "security")]
    punching: AtomicBool,
    /// For a relayed peer: outstanding path challenges per candidate address.
    #[cfg(feature = "security")]
    challenges: Mutex<HashMap<SocketAddr, Challenge>>,
    /// Total bytes received from this peer (payload bytes, not wire bytes).
    pub rx_bytes: AtomicU64,
    /// Total bytes sent to this peer (payload bytes, not wire bytes).
    pub tx_bytes: AtomicU64,
    /// Number of frames retransmitted due to NACKs from this peer.
    pub retransmit_count: AtomicU64,
    /// Streams with a tail-loss probe task running (see `engine::arm_tail_probe`).
    pub tail_probe_armed: Mutex<HashSet<u16>>,
    /// Whether `PeerEvent::Connected` (or `Reset`) was emitted for this state.
    announced: std::sync::atomic::AtomicBool,
}

impl PeerState {
    #[must_use]
    pub fn new(addr: PeerAddr) -> Self {
        Self::with_addr(Arc::new(RwLock::new(addr)))
    }

    /// A fresh session state that keeps tracking the same live address handle, so a
    /// [`ZudpConn`](crate::ZudpConn) survives its peer being reset.
    #[must_use]
    pub fn with_addr(addr: Arc<RwLock<PeerAddr>>) -> Self {
        let now = Instant::now();
        Self {
            addr,
            generation: random_u64(),
            their_session_id: Mutex::new(None),
            next_seqs: Mutex::new(HashMap::new()),
            sent: Mutex::new(HashMap::new()),
            last_sent: Mutex::new(now),
            last_seen: Mutex::new(now),
            cc: Mutex::new(CongestionCtrl::new()),
            effective_mtu: AtomicU32::new(0),
            probe_acks: Mutex::new(HashMap::new()),
            #[cfg(feature = "security")]
            channel: RwLock::new(None),
            #[cfg(feature = "security")]
            remote_static_key: RwLock::new(None),
            #[cfg(feature = "security")]
            confirmed: AtomicBool::new(false),
            #[cfg(feature = "security")]
            confirmed_notify: tokio::sync::Notify::new(),
            #[cfg(feature = "security")]
            finish_wire: Mutex::new(None),
            #[cfg(feature = "security")]
            initiator: AtomicBool::new(false),
            #[cfg(feature = "security")]
            rehandshake_started: Mutex::new(None),
            #[cfg(feature = "security")]
            highest_nonce: AtomicU64::new(0),
            #[cfg(feature = "security")]
            direct: Mutex::new(None),
            #[cfg(feature = "security")]
            last_intro: Mutex::new(None),
            #[cfg(feature = "security")]
            intro_open: Mutex::new(None),
            #[cfg(feature = "security")]
            punching: AtomicBool::new(false),
            #[cfg(feature = "security")]
            challenges: Mutex::new(HashMap::new()),
            rx_bytes: AtomicU64::new(0),
            tx_bytes: AtomicU64::new(0),
            retransmit_count: AtomicU64::new(0),
            tail_probe_armed: Mutex::new(HashSet::new()),
            announced: std::sync::atomic::AtomicBool::new(false),
        }
    }

    /// Current remote address.
    pub fn addr(&self) -> PeerAddr {
        *self.addr.read()
    }

    /// Shared handle to the live address so `ZudpConn` tracks migrations automatically.
    pub fn addr_arc(&self) -> Arc<RwLock<PeerAddr>> {
        self.addr.clone()
    }

    /// Update the stored address after the remote migrates to a new network.
    pub fn migrate_to(&self, new_addr: PeerAddr) {
        *self.addr.write() = new_addr;
    }

    #[must_use]
    pub fn their_session_id(&self) -> Option<u64> {
        *self.their_session_id.lock()
    }

    pub fn set_their_session_id(&self, id: u64) {
        *self.their_session_id.lock() = Some(id);
    }

    /// Allocate the next sequence number for `stream_id`.  Each stream starts at 1.
    pub fn alloc_seq(&self, stream_id: u16) -> u64 {
        let mut map = self.next_seqs.lock();
        let counter = map.entry(stream_id).or_insert(1);
        let seq = *counter;
        *counter += 1;
        seq
    }

    pub fn record_sent(&self, stream_id: u16, seq: u64, frame: Bytes, max_frames: usize) {
        self.tx_bytes
            .fetch_add(frame.len() as u64, Ordering::Relaxed);
        let mut map = self.sent.lock();
        let stream_buf = map.entry(stream_id).or_default();
        if stream_buf.len() >= max_frames
            && let Some((evicted_seq, _)) = stream_buf.pop_first()
        {
            tracing::warn!(
                target: "zudp::peer",
                stream_id,
                evicted_seq,
                cap = max_frames,
                "sent buffer full — evicting oldest frame (NACK for it will not retransmit)"
            );
        }
        stream_buf.insert(
            seq,
            SentPacket {
                frame,
                sent_at: Instant::now(),
            },
        );
        drop(map);
        *self.last_sent.lock() = Instant::now();
    }

    pub fn frames_for_retransmit(&self, stream_id: u16, seqs: &[u64]) -> Vec<(u64, Bytes)> {
        let map = self.sent.lock();
        let Some(stream_buf) = map.get(&stream_id) else {
            return vec![];
        };
        let frames: Vec<(u64, Bytes)> = seqs
            .iter()
            .filter_map(|seq| stream_buf.get(seq).map(|p| (*seq, p.frame.clone())))
            .collect();
        self.retransmit_count
            .fetch_add(frames.len() as u64, Ordering::Relaxed);
        frames
    }

    /// The most recently sent frame still buffered on `stream_id`: `(seq, plain_frame, sent_at)`.
    pub fn newest_sent(&self, stream_id: u16) -> Option<(u64, Bytes, Instant)> {
        let map = self.sent.lock();
        let (seq, packet) = map.get(&stream_id)?.last_key_value()?;
        Some((*seq, packet.frame.clone(), packet.sent_at))
    }

    pub fn prune_sent(&self, max_age: Duration) {
        if let Some(cutoff) = Instant::now().checked_sub(max_age) {
            let mut map = self.sent.lock();
            for stream_buf in map.values_mut() {
                stream_buf.retain(|_, p| p.sent_at > cutoff);
            }
        }
    }

    pub fn mark_seen(&self) {
        *self.last_seen.lock() = Instant::now();
    }

    pub fn mark_sent(&self) {
        *self.last_sent.lock() = Instant::now();
    }

    pub fn since_sent(&self) -> Duration {
        self.last_sent.lock().elapsed()
    }

    pub fn since_seen(&self) -> Duration {
        self.last_seen.lock().elapsed()
    }

    /// `true` the first time it is called: the caller emits `PeerEvent::Connected`.
    pub fn announce(&self) -> bool {
        !self.announced.swap(true, Ordering::AcqRel)
    }

    /// Effective path MTU discovered by PLPMTUD; falls back to `default` until discovery completes.
    pub fn effective_mtu_or(&self, default: usize) -> usize {
        match self.effective_mtu.load(Ordering::Relaxed) {
            0 => default,
            v => v as usize,
        }
    }

    pub fn set_effective_mtu(&self, mtu: usize) {
        self.effective_mtu
            .store(u32::try_from(mtu).unwrap_or(u32::MAX), Ordering::Relaxed);
    }

    /// The remote peer's X25519 static public key, extracted from the Noise handshake.
    ///
    /// Returns `None` until the handshake completes.
    #[cfg(feature = "security")]
    #[must_use]
    pub fn remote_static_key(&self) -> Option<[u8; 32]> {
        *self.remote_static_key.read()
    }

    /// Install a freshly negotiated channel.
    #[cfg(feature = "security")]
    pub fn set_channel(
        &self,
        channel: SecureChannel,
        remote_static: Option<[u8; 32]>,
        finish_wire: Option<Bytes>,
        initiator: bool,
    ) {
        self.initiator.store(initiator, Ordering::Release);
        *self.channel.write() = Some(channel);
        *self.remote_static_key.write() = remote_static;
        *self.finish_wire.lock() = finish_wire;
        self.confirmed.store(false, Ordering::Release);
    }

    /// Our session index for this peer, if a session is installed.
    #[cfg(feature = "security")]
    #[must_use]
    pub fn local_index(&self) -> Option<u64> {
        self.channel.read().as_ref().map(SecureChannel::local_index)
    }

    /// The remote's session index, if a session is installed.
    #[cfg(feature = "security")]
    #[must_use]
    pub fn remote_index(&self) -> Option<u64> {
        self.channel
            .read()
            .as_ref()
            .map(SecureChannel::remote_index)
    }

    #[cfg(feature = "security")]
    #[must_use]
    pub fn is_initiator(&self) -> bool {
        self.initiator.load(Ordering::Acquire)
    }

    /// Claim the right to start a re-handshake; `false` if one started within `cooldown`.
    #[cfg(feature = "security")]
    pub fn begin_rehandshake(&self, cooldown: Duration) -> bool {
        let mut started = self.rehandshake_started.lock();
        if started.is_some_and(|t| t.elapsed() < cooldown) {
            return false;
        }
        *started = Some(Instant::now());
        true
    }

    /// Record an authenticated nonce; `true` when it is the newest seen so far.
    #[cfg(feature = "security")]
    pub fn advance_nonce(&self, nonce: u64) -> bool {
        self.highest_nonce.fetch_max(nonce, Ordering::AcqRel) < nonce
    }

    /// The punched direct address of a relayed peer, if its traffic currently goes there.
    #[cfg(feature = "security")]
    #[must_use]
    pub fn direct_path(&self) -> Option<SocketAddr> {
        self.direct.lock().map(|(addr, _)| addr)
    }

    /// Record an authenticated frame from the relayed peer at `addr`, which arrived
    /// outside the relay.  Returns the previous direct address when the path changed.
    #[cfg(feature = "security")]
    pub fn touch_direct(&self, addr: SocketAddr, may_switch: bool) -> Option<Option<SocketAddr>> {
        let mut direct = self.direct.lock();
        match *direct {
            Some((current, ref mut seen)) if current == addr => {
                *seen = Instant::now();
                None
            }
            previous if may_switch => {
                *direct = Some((addr, Instant::now()));
                Some(previous.map(|(old, _)| old))
            }
            _ => None,
        }
    }

    /// Drop the direct path if nothing authenticated arrived on it for `timeout`.
    /// Returns the address given up.
    #[cfg(feature = "security")]
    pub fn expire_direct(&self, timeout: Duration) -> Option<SocketAddr> {
        let mut direct = self.direct.lock();
        let (addr, seen) = (*direct)?;
        if seen.elapsed() < timeout {
            return None;
        }
        *direct = None;
        Some(addr)
    }

    /// Claim the right to ask the relay for an introduction; `false` if one was asked for
    /// within `cooldown` (pass zero to ask regardless).
    #[cfg(feature = "security")]
    pub fn begin_intro(&self, cooldown: Duration) -> bool {
        let mut last = self.last_intro.lock();
        if last.is_some_and(|t| t.elapsed() < cooldown) {
            return false;
        }
        let now = Instant::now();
        *last = Some(now);
        *self.intro_open.lock() = Some(now);
        true
    }

    /// Consume the introduction we asked for; `false` when none was asked for within
    /// `window` — an unsolicited introduction is ignored.
    #[cfg(feature = "security")]
    pub fn take_intro(&self, window: Duration) -> bool {
        self.intro_open
            .lock()
            .take()
            .is_some_and(|asked| asked.elapsed() < window)
    }

    /// Claim the single punch campaign of this peer; `false` while one is running.
    #[cfg(feature = "security")]
    pub fn begin_punch(&self) -> bool {
        !self.punching.swap(true, Ordering::AcqRel)
    }

    #[cfg(feature = "security")]
    pub fn end_punch(&self) {
        self.punching.store(false, Ordering::Release);
    }

    /// The challenge token to (re)send to the candidate address `addr`, or `None` when it
    /// went there less than `retry` ago.  A token stays the same for `lifetime`, so an
    /// answer that takes longer than `retry` (a long path) still matches; each candidate has
    /// its own challenge, so one address cannot overwrite another's.  At most
    /// [`MAX_PATH_CANDIDATES`] candidates are tracked; more are ignored until one expires.
    #[cfg(feature = "security")]
    pub fn begin_challenge(
        &self,
        addr: SocketAddr,
        retry: Duration,
        lifetime: Duration,
    ) -> Option<u64> {
        let mut challenges = self.challenges.lock();
        challenges.retain(|_, c| c.issued.elapsed() < lifetime);
        if let Some(c) = challenges.get_mut(&addr) {
            if c.sent.elapsed() < retry {
                return None;
            }
            c.sent = Instant::now();
            return Some(c.token);
        }
        if challenges.len() >= MAX_PATH_CANDIDATES {
            return None;
        }
        let now = Instant::now();
        let token = random_u64();
        challenges.insert(
            addr,
            Challenge {
                token,
                issued: now,
                sent: now,
            },
        );
        Some(token)
    }

    /// `true` (and every challenge is settled) when `token` answers the challenge sent to
    /// `addr`.
    #[cfg(feature = "security")]
    pub fn answer_challenge(&self, addr: SocketAddr, token: u64) -> bool {
        let mut challenges = self.challenges.lock();
        if challenges.get(&addr).is_some_and(|c| c.token == token) {
            challenges.clear();
            return true;
        }
        false
    }

    /// `true` once a Noise session is installed for this peer.
    #[must_use]
    #[cfg_attr(not(feature = "security"), allow(clippy::unused_self))]
    pub fn has_channel(&self) -> bool {
        #[cfg(feature = "security")]
        {
            self.channel.read().is_some()
        }
        #[cfg(not(feature = "security"))]
        {
            false
        }
    }

    /// Record that the remote proved it holds the current session.
    #[cfg(feature = "security")]
    pub fn mark_confirmed(&self) {
        if !self.confirmed.swap(true, Ordering::AcqRel) {
            self.confirmed_notify.notify_waiters();
        }
    }

    #[cfg(feature = "security")]
    #[must_use]
    pub fn is_confirmed(&self) -> bool {
        self.confirmed.load(Ordering::Acquire)
    }

    #[cfg(feature = "security")]
    #[must_use]
    pub fn finish_wire(&self) -> Option<Bytes> {
        self.finish_wire.lock().clone()
    }

    #[cfg(feature = "security")]
    pub fn clear_finish_wire(&self) {
        self.finish_wire.lock().take();
    }
}

/// Candidate direct addresses of one relayed peer validated at the same time.
#[cfg(feature = "security")]
pub const MAX_PATH_CANDIDATES: usize = 4;

/// An outstanding path challenge to one candidate address.
#[cfg(feature = "security")]
struct Challenge {
    token: u64,
    /// When the token was made; it is honoured for the challenge lifetime from here.
    issued: Instant,
    /// When it was last sent.
    sent: Instant,
}

/// A random, non-cryptographic `u64` (session ids and session indices).
///
/// `RandomState` is seeded per process from the OS, so values differ across restarts; the
/// counter keeps them distinct within one.
#[must_use]
pub fn random_u64() -> u64 {
    use std::hash::{BuildHasher, RandomState};

    static SEQ: AtomicU64 = AtomicU64::new(0);

    let mut h = RandomState::new().build_hasher();
    SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap_or_default()
        .hash(&mut h);
    SEQ.fetch_add(1, Ordering::Relaxed).hash(&mut h);
    h.finish()
}

/// An in-order payload element delivered by [`RecvState::ingest`].
#[derive(Debug)]
pub enum Inbound {
    /// A complete reliable message payload.
    Data(Bytes),
    /// One slice of a fragmented reliable message.
    Fragment {
        msg_id: u32,
        frag_idx: u16,
        frag_total: u16,
        data: Bytes,
    },
}

/// Per-(peer, stream) receive state, owned exclusively by the engine task.
///
/// Frames are buffered by sequence number and handed out in order through
/// [`pop_ready`](Self::pop_ready), so a frame is only consumed once the caller has
/// room to deliver it.
pub struct RecvState {
    expected_seq: u64,
    buf: BTreeMap<u64, Inbound>,
    /// Frames at or beyond `expected_seq + window` are dropped: they cannot be requested back
    /// into place anyway, and accepting them would let one forged sequence number make the
    /// receiver track an unbounded gap.
    window: u64,
    /// When a sequence gap was first detected.  Used by [`prune_gap`](Self::prune_gap)
    /// to skip a hole the sender can no longer retransmit.
    gap_since: Option<Instant>,
}

impl RecvState {
    #[must_use]
    pub fn new(window: usize) -> Self {
        Self {
            expected_seq: 1,
            buf: BTreeMap::new(),
            window: u64::try_from(window).unwrap_or(u64::MAX).max(1),
            gap_since: None,
        }
    }

    /// Buffer a reliable payload received at `seq`.
    ///
    /// Returns the sequence numbers still missing before `seq` (at most
    /// [`MAX_NACK_SEQS`]); already-buffered ones are not asked for again.  With
    /// `allow_reorder == false` only the next in-order frame is accepted.
    pub fn ingest(&mut self, seq: u64, payload: Inbound, allow_reorder: bool) -> Vec<u64> {
        if seq < self.expected_seq
            || seq - self.expected_seq >= self.window
            || (seq != self.expected_seq && !allow_reorder)
            || self.buf.contains_key(&seq)
        {
            return vec![];
        }
        let nack_seqs = (self.expected_seq..seq)
            .filter(|missing| !self.buf.contains_key(missing))
            .take(MAX_NACK_SEQS)
            .collect();
        self.buf.insert(seq, payload);
        self.refresh_gap();
        nack_seqs
    }

    /// `true` when the next in-order payload is buffered.
    #[must_use]
    pub fn has_ready(&self) -> bool {
        self.buf.contains_key(&self.expected_seq)
    }

    /// Take the next in-order payload, if it has arrived.
    pub fn pop_ready(&mut self) -> Option<Inbound> {
        let next = self.buf.remove(&self.expected_seq)?;
        self.expected_seq += 1;
        self.refresh_gap();
        Some(next)
    }

    fn refresh_gap(&mut self) {
        if self.buf.is_empty() || self.has_ready() {
            self.gap_since = None;
        } else if self.gap_since.is_none() {
            self.gap_since = Some(Instant::now());
        }
    }

    /// Skip a gap that has been unresolved for longer than `max_age`.
    ///
    /// Called periodically by the engine background task.  Returns `true` when a skip
    /// occurred so the caller can emit a warning.  Only the missing sequence numbers are
    /// skipped; everything buffered after the hole is still delivered.
    pub fn prune_gap(&mut self, max_age: Duration) -> bool {
        let Some(since) = self.gap_since else {
            return false;
        };
        if since.elapsed() < max_age {
            return false;
        }
        if let Some((&first, _)) = self.buf.first_key_value() {
            self.expected_seq = first;
        }
        self.gap_since = None;
        true
    }
}

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

    fn data() -> Inbound {
        Inbound::Data(Bytes::from_static(b"x"))
    }

    fn drain(recv: &mut RecvState) -> usize {
        std::iter::from_fn(|| recv.pop_ready()).count()
    }

    #[cfg(feature = "security")]
    #[test]
    fn path_challenges_survive_slow_answers_and_other_candidates() {
        let peer = PeerState::new(PeerAddr::Direct("127.0.0.1:1".parse().unwrap()));
        let (x, y): (SocketAddr, SocketAddr) = (
            "192.0.2.1:1".parse().unwrap(),
            "192.0.2.2:1".parse().unwrap(),
        );
        let retry = Duration::from_millis(10);
        let life = Duration::from_secs(5);
        let token = peer.begin_challenge(x, retry, life).unwrap();
        assert_eq!(
            peer.begin_challenge(x, retry, life),
            None,
            "resent too soon"
        );
        std::thread::sleep(Duration::from_millis(20));
        assert_eq!(
            peer.begin_challenge(x, retry, life),
            Some(token),
            "token rotated"
        );
        assert!(peer.begin_challenge(y, retry, life).is_some());
        assert!(
            peer.answer_challenge(x, token),
            "another candidate clobbered x"
        );
        for port in 0..10u16 {
            let candidate = SocketAddr::new(x.ip(), 1000 + port);
            let _ = peer.begin_challenge(candidate, retry, life);
        }
        assert!(peer.challenges.lock().len() <= MAX_PATH_CANDIDATES);
    }

    #[test]
    fn nack_skips_seqs_already_buffered() {
        let mut recv = RecvState::new(1024);
        assert_eq!(recv.ingest(3, data(), true), vec![1, 2]);
        assert_eq!(recv.ingest(5, data(), true), vec![1, 2, 4], "3 is buffered");
        assert!(recv.ingest(1, data(), true).is_empty());
        assert_eq!(
            drain(&mut recv),
            1,
            "2 still missing, so only 1 is delivered"
        );
    }

    #[test]
    fn huge_sequence_number_is_dropped_without_allocating() {
        let mut recv = RecvState::new(1024);
        assert!(recv.ingest(u64::MAX - 1, data(), true).is_empty());
        assert!(recv.ingest(1 << 40, data(), true).is_empty());
        assert!(recv.buf.is_empty());
        assert!(recv.ingest(1, data(), true).is_empty());
        assert_eq!(drain(&mut recv), 1);
    }

    #[test]
    fn nack_list_is_capped() {
        let mut recv = RecvState::new(4096);
        assert_eq!(recv.ingest(4000, data(), true).len(), MAX_NACK_SEQS);
    }

    #[test]
    fn undelivered_frames_stay_buffered() {
        let mut recv = RecvState::new(1024);
        recv.ingest(1, data(), true);
        recv.ingest(2, data(), true);
        assert!(recv.has_ready());
        assert!(
            recv.ingest(1, data(), true).is_empty(),
            "duplicate of a buffered frame"
        );
        assert_eq!(drain(&mut recv), 2);
        assert!(!recv.has_ready());
    }

    #[test]
    fn in_order_only_rejects_out_of_order() {
        let mut recv = RecvState::new(1024);
        assert!(recv.ingest(2, data(), false).is_empty());
        assert!(!recv.has_ready());
        recv.ingest(1, data(), false);
        assert_eq!(drain(&mut recv), 1);
    }

    #[test]
    fn gap_timeout_keeps_frames_after_the_hole() {
        let mut recv = RecvState::new(1024);
        recv.ingest(3, data(), true);
        recv.ingest(4, data(), true);
        assert!(recv.prune_gap(Duration::ZERO));
        assert_eq!(drain(&mut recv), 2);
    }
}