iroh_quinn_proto/connection/
paths.rs

1use std::{cmp, net::SocketAddr};
2
3use identity_hash::IntMap;
4use thiserror::Error;
5use tracing::{debug, trace};
6
7use super::{
8    PathError, PathStats,
9    mtud::MtuDiscovery,
10    pacing::Pacer,
11    spaces::{PacketNumberSpace, SentPacket},
12};
13use crate::{
14    ConnectionId, Duration, Instant, TIMER_GRANULARITY, TransportConfig, VarInt, coding,
15    congestion, frame::ObservedAddr, packet::SpaceId,
16};
17
18#[cfg(feature = "qlog")]
19use qlog::events::quic::RecoveryMetricsUpdated;
20
21/// Id representing different paths when using multipath extension
22#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default)]
23pub struct PathId(pub(crate) u32);
24
25impl std::hash::Hash for PathId {
26    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
27        state.write_u32(self.0);
28    }
29}
30
31impl identity_hash::IdentityHashable for PathId {}
32
33impl coding::Codec for PathId {
34    fn decode<B: bytes::Buf>(r: &mut B) -> coding::Result<Self> {
35        let v = VarInt::decode(r)?;
36        let v = u32::try_from(v.0).map_err(|_| coding::UnexpectedEnd)?;
37        Ok(Self(v))
38    }
39
40    fn encode<B: bytes::BufMut>(&self, w: &mut B) {
41        VarInt(self.0.into()).encode(w)
42    }
43}
44
45impl PathId {
46    /// The maximum path ID allowed.
47    pub const MAX: Self = Self(u32::MAX);
48
49    /// The 0 path id.
50    pub const ZERO: Self = Self(0);
51
52    /// The number of bytes this [`PathId`] uses when encoded as a [`VarInt`]
53    pub(crate) const fn size(&self) -> usize {
54        VarInt(self.0 as u64).size()
55    }
56
57    /// Saturating integer addition. Computes self + rhs, saturating at the numeric bounds instead
58    /// of overflowing.
59    pub fn saturating_add(self, rhs: impl Into<Self>) -> Self {
60        let rhs = rhs.into();
61        let inner = self.0.saturating_add(rhs.0);
62        Self(inner)
63    }
64
65    /// Saturating integer subtraction. Computes self - rhs, saturating at the numeric bounds
66    /// instead of overflowing.
67    pub fn saturating_sub(self, rhs: impl Into<Self>) -> Self {
68        let rhs = rhs.into();
69        let inner = self.0.saturating_sub(rhs.0);
70        Self(inner)
71    }
72
73    /// Get the next [`PathId`]
74    pub(crate) fn next(&self) -> Self {
75        self.saturating_add(Self(1))
76    }
77
78    /// Get the underlying u32
79    pub(crate) fn as_u32(&self) -> u32 {
80        self.0
81    }
82}
83
84impl std::fmt::Display for PathId {
85    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86        self.0.fmt(f)
87    }
88}
89
90impl<T: Into<u32>> From<T> for PathId {
91    fn from(source: T) -> Self {
92        Self(source.into())
93    }
94}
95
96/// State needed for a single path ID.
97///
98/// A single path ID can migrate according to the rules in RFC9000 §9, either voluntary or
99/// involuntary. We need to keep the [`PathData`] of the previously used such path available
100/// in order to defend against migration attacks (see RFC9000 §9.3.1, §9.3.2 and §9.3.3) as
101/// well as to support path probing (RFC9000 §9.1).
102#[derive(Debug)]
103pub(super) struct PathState {
104    pub(super) data: PathData,
105    pub(super) prev: Option<(ConnectionId, PathData)>,
106}
107
108impl PathState {
109    /// Update counters to account for a packet becoming acknowledged, lost, or abandoned
110    pub(super) fn remove_in_flight(&mut self, packet: &SentPacket) {
111        // Visit known paths from newest to oldest to find the one `pn` was sent on
112        for path_data in [&mut self.data]
113            .into_iter()
114            .chain(self.prev.as_mut().map(|(_, data)| data))
115        {
116            if path_data.remove_in_flight(packet) {
117                return;
118            }
119        }
120    }
121}
122
123#[derive(Debug)]
124pub(super) struct SentChallengeInfo {
125    /// When was the challenge sent on the wire.
126    pub(super) sent_instant: Instant,
127    /// The remote to which this path challenge was sent.
128    pub(super) remote: SocketAddr,
129}
130
131/// Description of a particular network path
132#[derive(Debug)]
133pub(super) struct PathData {
134    pub(super) remote: SocketAddr,
135    pub(super) rtt: RttEstimator,
136    /// Whether we're enabling ECN on outgoing packets
137    pub(super) sending_ecn: bool,
138    /// Congestion controller state
139    pub(super) congestion: Box<dyn congestion::Controller>,
140    /// Pacing state
141    pub(super) pacing: Pacer,
142    /// Actually sent challenges (on the wire).
143    pub(super) challenges_sent: IntMap<u64, SentChallengeInfo>,
144    /// Whether to *immediately* trigger another PATH_CHALLENGE.
145    ///
146    /// This is picked up by [`super::Connection::space_can_send`].
147    pub(super) send_new_challenge: bool,
148    /// Pending responses to PATH_CHALLENGE frames
149    pub(super) path_responses: PathResponses,
150    /// Whether we're certain the peer can both send and receive on this address
151    ///
152    /// Initially equal to `use_stateless_retry` for servers, and becomes false again on every
153    /// migration. Always true for clients.
154    pub(super) validated: bool,
155    /// Total size of all UDP datagrams sent on this path
156    pub(super) total_sent: u64,
157    /// Total size of all UDP datagrams received on this path
158    pub(super) total_recvd: u64,
159    /// The state of the MTU discovery process
160    pub(super) mtud: MtuDiscovery,
161    /// Packet number of the first packet sent after an RTT sample was collected on this path
162    ///
163    /// Used in persistent congestion determination.
164    pub(super) first_packet_after_rtt_sample: Option<(SpaceId, u64)>,
165    /// The in-flight packets and bytes
166    ///
167    /// Note that this is across all spaces on this path
168    pub(super) in_flight: InFlight,
169    /// Whether this path has had it's remote address reported back to the peer. This only happens
170    /// if both peers agree to so based on their transport parameters.
171    pub(super) observed_addr_sent: bool,
172    /// Observed address frame with the largest sequence number received from the peer on this path.
173    pub(super) last_observed_addr_report: Option<ObservedAddr>,
174    /// The QUIC-MULTIPATH path status
175    pub(super) status: PathStatusState,
176    /// Number of the first packet sent on this path
177    ///
178    /// With RFC9000 §9 style migration (i.e. not multipath) the PathId does not change and
179    /// hence packet numbers continue. This is used to determine whether a packet was sent
180    /// on such an earlier path. Insufficient to determine if a packet was sent on a later
181    /// path.
182    first_packet: Option<u64>,
183    /// The number of times a PTO has been sent without receiving an ack.
184    pub(super) pto_count: u32,
185
186    //
187    // Per-path idle & keep alive
188    //
189    /// Idle timeout for the path
190    ///
191    /// If expired, the path will be abandoned.  This is different from the connection-wide
192    /// idle timeout which closes the connection if expired.
193    pub(super) idle_timeout: Option<Duration>,
194    /// Keep alives to send on this path
195    ///
196    /// There is also a connection-level keep alive configured in the
197    /// [`TransportParameters`].  This triggers activity on any path which can keep the
198    /// connection alive.
199    ///
200    /// [`TransportParameters`]: crate::transport_parameters::TransportParameters
201    pub(super) keep_alive: Option<Duration>,
202
203    /// Whether the path has already been considered opened from an application perspective
204    ///
205    /// This means, for paths other than the original [`PathId::ZERO`], a first path challenge has
206    /// been responded to, regardless of the initial validation status of the path. This state is
207    /// irreversible, since it's not affected by the path being closed.
208    pub(super) open: bool,
209
210    /// The time at which this path state should've received a PATH_ABANDON already.
211    ///
212    /// Receiving data on this path generates a transport error after that point in time.
213    /// This is checked in [`crate::Connection::on_packet_authenticated`].
214    ///
215    /// If set to `None`, then this path isn't abandoned yet and is allowed to receive data.
216    pub(super) last_allowed_receive: Option<Instant>,
217
218    /// Snapshot of the qlog recovery metrics
219    #[cfg(feature = "qlog")]
220    recovery_metrics: RecoveryMetrics,
221
222    /// Tag uniquely identifying a path in a connection
223    generation: u64,
224}
225
226impl PathData {
227    pub(super) fn new(
228        remote: SocketAddr,
229        allow_mtud: bool,
230        peer_max_udp_payload_size: Option<u16>,
231        generation: u64,
232        now: Instant,
233        config: &TransportConfig,
234    ) -> Self {
235        let congestion = config
236            .congestion_controller_factory
237            .clone()
238            .build(now, config.get_initial_mtu());
239        Self {
240            remote,
241            rtt: RttEstimator::new(config.initial_rtt),
242            sending_ecn: true,
243            pacing: Pacer::new(
244                config.initial_rtt,
245                congestion.initial_window(),
246                config.get_initial_mtu(),
247                now,
248            ),
249            congestion,
250            challenges_sent: Default::default(),
251            send_new_challenge: false,
252            path_responses: PathResponses::default(),
253            validated: false,
254            total_sent: 0,
255            total_recvd: 0,
256            mtud: config
257                .mtu_discovery_config
258                .as_ref()
259                .filter(|_| allow_mtud)
260                .map_or(
261                    MtuDiscovery::disabled(config.get_initial_mtu(), config.min_mtu),
262                    |mtud_config| {
263                        MtuDiscovery::new(
264                            config.get_initial_mtu(),
265                            config.min_mtu,
266                            peer_max_udp_payload_size,
267                            mtud_config.clone(),
268                        )
269                    },
270                ),
271            first_packet_after_rtt_sample: None,
272            in_flight: InFlight::new(),
273            observed_addr_sent: false,
274            last_observed_addr_report: None,
275            status: Default::default(),
276            first_packet: None,
277            pto_count: 0,
278            idle_timeout: config.default_path_max_idle_timeout,
279            keep_alive: config.default_path_keep_alive_interval,
280            open: false,
281            last_allowed_receive: None,
282            #[cfg(feature = "qlog")]
283            recovery_metrics: RecoveryMetrics::default(),
284            generation,
285        }
286    }
287
288    /// Create a new path from a previous one.
289    ///
290    /// This should only be called when migrating paths.
291    pub(super) fn from_previous(
292        remote: SocketAddr,
293        prev: &Self,
294        generation: u64,
295        now: Instant,
296    ) -> Self {
297        let congestion = prev.congestion.clone_box();
298        let smoothed_rtt = prev.rtt.get();
299        Self {
300            remote,
301            rtt: prev.rtt,
302            pacing: Pacer::new(smoothed_rtt, congestion.window(), prev.current_mtu(), now),
303            sending_ecn: true,
304            congestion,
305            challenges_sent: Default::default(),
306            send_new_challenge: false,
307            path_responses: PathResponses::default(),
308            validated: false,
309            total_sent: 0,
310            total_recvd: 0,
311            mtud: prev.mtud.clone(),
312            first_packet_after_rtt_sample: prev.first_packet_after_rtt_sample,
313            in_flight: InFlight::new(),
314            observed_addr_sent: false,
315            last_observed_addr_report: None,
316            status: prev.status.clone(),
317            first_packet: None,
318            pto_count: 0,
319            idle_timeout: prev.idle_timeout,
320            keep_alive: prev.keep_alive,
321            open: false,
322            last_allowed_receive: None,
323            #[cfg(feature = "qlog")]
324            recovery_metrics: prev.recovery_metrics.clone(),
325            generation,
326        }
327    }
328
329    /// Whether we're in the process of validating this path with PATH_CHALLENGEs
330    pub(super) fn is_validating_path(&self) -> bool {
331        !self.challenges_sent.is_empty() || self.send_new_challenge
332    }
333
334    /// Indicates whether we're a server that hasn't validated the peer's address and hasn't
335    /// received enough data from the peer to permit sending `bytes_to_send` additional bytes
336    pub(super) fn anti_amplification_blocked(&self, bytes_to_send: u64) -> bool {
337        !self.validated && self.total_recvd * 3 < self.total_sent + bytes_to_send
338    }
339
340    /// Returns the path's current MTU
341    pub(super) fn current_mtu(&self) -> u16 {
342        self.mtud.current_mtu()
343    }
344
345    /// Account for transmission of `packet` with number `pn` in `space`
346    pub(super) fn sent(&mut self, pn: u64, packet: SentPacket, space: &mut PacketNumberSpace) {
347        self.in_flight.insert(&packet);
348        if self.first_packet.is_none() {
349            self.first_packet = Some(pn);
350        }
351        if let Some(forgotten) = space.sent(pn, packet) {
352            self.remove_in_flight(&forgotten);
353        }
354    }
355
356    /// Remove `packet` with number `pn` from this path's congestion control counters, or return
357    /// `false` if `pn` was sent before this path was established.
358    pub(super) fn remove_in_flight(&mut self, packet: &SentPacket) -> bool {
359        if packet.path_generation != self.generation {
360            return false;
361        }
362        self.in_flight.remove(packet);
363        true
364    }
365
366    /// Increment the total size of sent UDP datagrams
367    pub(super) fn inc_total_sent(&mut self, inc: u64) {
368        self.total_sent = self.total_sent.saturating_add(inc);
369        if !self.validated {
370            trace!(
371                remote = %self.remote,
372                anti_amplification_budget = %(self.total_recvd * 3).saturating_sub(self.total_sent),
373                "anti amplification budget decreased"
374            );
375        }
376    }
377
378    /// Increment the total size of received UDP datagrams
379    pub(super) fn inc_total_recvd(&mut self, inc: u64) {
380        self.total_recvd = self.total_recvd.saturating_add(inc);
381        if !self.validated {
382            trace!(
383                remote = %self.remote,
384                anti_amplification_budget = %(self.total_recvd * 3).saturating_sub(self.total_sent),
385                "anti amplification budget increased"
386            );
387        }
388    }
389
390    /// The earliest time at which a sent challenge is considered lost.
391    pub(super) fn earliest_expiring_challenge(&self) -> Option<Instant> {
392        if self.challenges_sent.is_empty() {
393            return None;
394        }
395        let pto = self.rtt.pto_base();
396        self.challenges_sent
397            .values()
398            .map(|info| info.sent_instant)
399            .min()
400            .map(|sent_instant| sent_instant + pto)
401    }
402
403    /// Handle receiving a PATH_RESPONSE.
404    pub(super) fn on_path_response_received(
405        &mut self,
406        now: Instant,
407        token: u64,
408        remote: SocketAddr,
409    ) -> OnPathResponseReceived {
410        match self.challenges_sent.get(&token) {
411            // Response to an on-path PathChallenge
412            Some(info) if info.remote == remote && self.remote == remote => {
413                let sent_instant = info.sent_instant;
414                if !std::mem::replace(&mut self.validated, true) {
415                    trace!("new path validated");
416                }
417                // Clear any other on-path sent challenge.
418                self.challenges_sent
419                    .retain(|_token, info| info.remote != remote);
420
421                self.send_new_challenge = false;
422
423                // This RTT can only be used for the initial RTT, not as a normal
424                // sample: https://www.rfc-editor.org/rfc/rfc9002#section-6.2.2-2.
425                let rtt = now.saturating_duration_since(sent_instant);
426                self.rtt.reset_initial_rtt(rtt);
427
428                let was_open = std::mem::replace(&mut self.open, true);
429                OnPathResponseReceived::OnPath { was_open }
430            }
431            // Response to an off-path PathChallenge
432            Some(info) if info.remote == remote => {
433                self.challenges_sent
434                    .retain(|_token, info| info.remote != remote);
435                OnPathResponseReceived::OffPath
436            }
437            // Response to a PathChallenge we recognize, but from an invalid remote
438            Some(info) => OnPathResponseReceived::Invalid {
439                expected: info.remote,
440            },
441            // Response to an unknown PathChallenge
442            None => OnPathResponseReceived::Unknown,
443        }
444    }
445
446    #[cfg(feature = "qlog")]
447    pub(super) fn qlog_recovery_metrics(
448        &mut self,
449        path_id: PathId,
450    ) -> Option<RecoveryMetricsUpdated> {
451        let controller_metrics = self.congestion.metrics();
452
453        let metrics = RecoveryMetrics {
454            min_rtt: Some(self.rtt.min),
455            smoothed_rtt: Some(self.rtt.get()),
456            latest_rtt: Some(self.rtt.latest),
457            rtt_variance: Some(self.rtt.var),
458            pto_count: Some(self.pto_count),
459            bytes_in_flight: Some(self.in_flight.bytes),
460            packets_in_flight: Some(self.in_flight.ack_eliciting),
461
462            congestion_window: Some(controller_metrics.congestion_window),
463            ssthresh: controller_metrics.ssthresh,
464            pacing_rate: controller_metrics.pacing_rate,
465        };
466
467        let event = metrics.to_qlog_event(path_id, &self.recovery_metrics);
468        self.recovery_metrics = metrics;
469        event
470    }
471
472    /// Return how long we need to wait before sending `bytes_to_send`
473    ///
474    /// See [`Pacer::delay`].
475    pub(super) fn pacing_delay(&mut self, bytes_to_send: u64, now: Instant) -> Option<Instant> {
476        let smoothed_rtt = self.rtt.get();
477        self.pacing.delay(
478            smoothed_rtt,
479            bytes_to_send,
480            self.current_mtu(),
481            self.congestion.window(),
482            now,
483        )
484    }
485
486    /// Updates the last observed address report received on this path.
487    ///
488    /// If the address was updated, it's returned to be informed to the application.
489    #[must_use = "updated observed address must be reported to the application"]
490    pub(super) fn update_observed_addr_report(
491        &mut self,
492        observed: ObservedAddr,
493    ) -> Option<SocketAddr> {
494        match self.last_observed_addr_report.as_mut() {
495            Some(prev) => {
496                if prev.seq_no >= observed.seq_no {
497                    // frames that do not increase the sequence number on this path are ignored
498                    None
499                } else if prev.ip == observed.ip && prev.port == observed.port {
500                    // keep track of the last seq_no but do not report the address as updated
501                    prev.seq_no = observed.seq_no;
502                    None
503                } else {
504                    let addr = observed.socket_addr();
505                    self.last_observed_addr_report = Some(observed);
506                    Some(addr)
507                }
508            }
509            None => {
510                let addr = observed.socket_addr();
511                self.last_observed_addr_report = Some(observed);
512                Some(addr)
513            }
514        }
515    }
516
517    pub(crate) fn remote_status(&self) -> Option<PathStatus> {
518        self.status.remote_status.map(|(_seq, status)| status)
519    }
520
521    pub(crate) fn local_status(&self) -> PathStatus {
522        self.status.local_status
523    }
524
525    pub(super) fn generation(&self) -> u64 {
526        self.generation
527    }
528}
529
530pub(super) enum OnPathResponseReceived {
531    /// This response validates the path on its current remote address.
532    OnPath { was_open: bool },
533    /// This response is valid, but it's for a remote other than the path's current remote address.
534    OffPath,
535    /// The received token is unknown.
536    Unknown,
537    /// The response is invalid.
538    Invalid {
539        /// The remote that was expected for this token.
540        expected: SocketAddr,
541    },
542}
543
544/// Congestion metrics as described in [`recovery_metrics_updated`].
545///
546/// [`recovery_metrics_updated`]: https://datatracker.ietf.org/doc/html/draft-ietf-quic-qlog-quic-events.html#name-recovery_metrics_updated
547#[cfg(feature = "qlog")]
548#[derive(Default, Clone, PartialEq, Debug)]
549#[non_exhaustive]
550struct RecoveryMetrics {
551    pub min_rtt: Option<Duration>,
552    pub smoothed_rtt: Option<Duration>,
553    pub latest_rtt: Option<Duration>,
554    pub rtt_variance: Option<Duration>,
555    pub pto_count: Option<u32>,
556    pub bytes_in_flight: Option<u64>,
557    pub packets_in_flight: Option<u64>,
558    pub congestion_window: Option<u64>,
559    pub ssthresh: Option<u64>,
560    pub pacing_rate: Option<u64>,
561}
562
563#[cfg(feature = "qlog")]
564impl RecoveryMetrics {
565    /// Retain only values that have been updated since the last snapshot.
566    fn retain_updated(&self, previous: &Self) -> Self {
567        macro_rules! keep_if_changed {
568            ($name:ident) => {
569                if previous.$name == self.$name {
570                    None
571                } else {
572                    self.$name
573                }
574            };
575        }
576
577        Self {
578            min_rtt: keep_if_changed!(min_rtt),
579            smoothed_rtt: keep_if_changed!(smoothed_rtt),
580            latest_rtt: keep_if_changed!(latest_rtt),
581            rtt_variance: keep_if_changed!(rtt_variance),
582            pto_count: keep_if_changed!(pto_count),
583            bytes_in_flight: keep_if_changed!(bytes_in_flight),
584            packets_in_flight: keep_if_changed!(packets_in_flight),
585            congestion_window: keep_if_changed!(congestion_window),
586            ssthresh: keep_if_changed!(ssthresh),
587            pacing_rate: keep_if_changed!(pacing_rate),
588        }
589    }
590
591    /// Emit a `MetricsUpdated` event containing only updated values
592    fn to_qlog_event(&self, path_id: PathId, previous: &Self) -> Option<RecoveryMetricsUpdated> {
593        let updated = self.retain_updated(previous);
594
595        if updated == Self::default() {
596            return None;
597        }
598
599        Some(RecoveryMetricsUpdated {
600            min_rtt: updated.min_rtt.map(|rtt| rtt.as_secs_f32()),
601            smoothed_rtt: updated.smoothed_rtt.map(|rtt| rtt.as_secs_f32()),
602            latest_rtt: updated.latest_rtt.map(|rtt| rtt.as_secs_f32()),
603            rtt_variance: updated.rtt_variance.map(|rtt| rtt.as_secs_f32()),
604            pto_count: updated
605                .pto_count
606                .map(|count| count.try_into().unwrap_or(u16::MAX)),
607            bytes_in_flight: updated.bytes_in_flight,
608            packets_in_flight: updated.packets_in_flight,
609            congestion_window: updated.congestion_window,
610            ssthresh: updated.ssthresh,
611            pacing_rate: updated.pacing_rate,
612            path_id: Some(path_id.as_u32() as u64),
613        })
614    }
615}
616
617/// RTT estimation for a particular network path
618#[derive(Copy, Clone, Debug)]
619pub struct RttEstimator {
620    /// The most recent RTT measurement made when receiving an ack for a previously unacked packet
621    latest: Duration,
622    /// The smoothed RTT of the connection, computed as described in RFC6298
623    smoothed: Option<Duration>,
624    /// The RTT variance, computed as described in RFC6298
625    var: Duration,
626    /// The minimum RTT seen in the connection, ignoring ack delay.
627    min: Duration,
628}
629
630impl RttEstimator {
631    pub(super) fn new(initial_rtt: Duration) -> Self {
632        Self {
633            latest: initial_rtt,
634            smoothed: None,
635            var: initial_rtt / 2,
636            min: initial_rtt,
637        }
638    }
639
640    /// Resets the estimator using a new initial_rtt value.
641    ///
642    /// This only resets the initial_rtt **if** no samples have been recorded yet. If there
643    /// are any recorded samples the initial estimate can not be adjusted after the fact.
644    ///
645    /// This is useful when you receive a PATH_RESPONSE in the first packet received on a
646    /// new path. In this case you can use the delay of the PATH_CHALLENGE-PATH_RESPONSE as
647    /// the initial RTT to get a better expected estimation.
648    ///
649    /// A PATH_CHALLENGE-PATH_RESPONSE pair later in the connection should not be used
650    /// explicitly as an estimation since PATH_CHALLENGE is an ACK-eliciting packet itself
651    /// already.
652    pub(crate) fn reset_initial_rtt(&mut self, initial_rtt: Duration) {
653        if self.smoothed.is_none() {
654            self.latest = initial_rtt;
655            self.var = initial_rtt / 2;
656            self.min = initial_rtt;
657        }
658    }
659
660    /// The current best RTT estimation.
661    pub fn get(&self) -> Duration {
662        self.smoothed.unwrap_or(self.latest)
663    }
664
665    /// Conservative estimate of RTT
666    ///
667    /// Takes the maximum of smoothed and latest RTT, as recommended
668    /// in 6.1.2 of the recovery spec (draft 29).
669    pub fn conservative(&self) -> Duration {
670        self.get().max(self.latest)
671    }
672
673    /// Minimum RTT registered so far for this estimator.
674    pub fn min(&self) -> Duration {
675        self.min
676    }
677
678    /// PTO computed as described in RFC9002#6.2.1.
679    pub(crate) fn pto_base(&self) -> Duration {
680        self.get() + cmp::max(4 * self.var, TIMER_GRANULARITY)
681    }
682
683    /// Records an RTT sample.
684    pub(crate) fn update(&mut self, ack_delay: Duration, rtt: Duration) {
685        self.latest = rtt;
686        // https://www.rfc-editor.org/rfc/rfc9002.html#section-5.2-3:
687        // min_rtt does not adjust for ack_delay to avoid underestimating.
688        self.min = cmp::min(self.min, self.latest);
689        // Based on RFC6298.
690        if let Some(smoothed) = self.smoothed {
691            let adjusted_rtt = if self.min + ack_delay <= self.latest {
692                self.latest - ack_delay
693            } else {
694                self.latest
695            };
696            let var_sample = smoothed.abs_diff(adjusted_rtt);
697            self.var = (3 * self.var + var_sample) / 4;
698            self.smoothed = Some((7 * smoothed + adjusted_rtt) / 8);
699        } else {
700            self.smoothed = Some(self.latest);
701            self.var = self.latest / 2;
702            self.min = self.latest;
703        }
704    }
705}
706
707#[derive(Default, Debug)]
708pub(crate) struct PathResponses {
709    pending: Vec<PathResponse>,
710}
711
712impl PathResponses {
713    pub(crate) fn push(&mut self, packet: u64, token: u64, remote: SocketAddr) {
714        /// Arbitrary permissive limit to prevent abuse
715        const MAX_PATH_RESPONSES: usize = 16;
716        let response = PathResponse {
717            packet,
718            token,
719            remote,
720        };
721        let existing = self.pending.iter_mut().find(|x| x.remote == remote);
722        if let Some(existing) = existing {
723            // Update a queued response
724            if existing.packet <= packet {
725                *existing = response;
726            }
727            return;
728        }
729        if self.pending.len() < MAX_PATH_RESPONSES {
730            self.pending.push(response);
731        } else {
732            // We don't expect to ever hit this with well-behaved peers, so we don't bother dropping
733            // older challenges.
734            trace!("ignoring excessive PATH_CHALLENGE");
735        }
736    }
737
738    pub(crate) fn pop_off_path(&mut self, remote: SocketAddr) -> Option<(u64, SocketAddr)> {
739        let response = *self.pending.last()?;
740        if response.remote == remote {
741            // We don't bother searching further because we expect that the on-path response will
742            // get drained in the immediate future by a call to `pop_on_path`
743            return None;
744        }
745        self.pending.pop();
746        Some((response.token, response.remote))
747    }
748
749    pub(crate) fn pop_on_path(&mut self, remote: SocketAddr) -> Option<u64> {
750        let response = *self.pending.last()?;
751        if response.remote != remote {
752            // We don't bother searching further because we expect that the off-path response will
753            // get drained in the immediate future by a call to `pop_off_path`
754            return None;
755        }
756        self.pending.pop();
757        Some(response.token)
758    }
759
760    pub(crate) fn is_empty(&self) -> bool {
761        self.pending.is_empty()
762    }
763}
764
765#[derive(Copy, Clone, Debug)]
766struct PathResponse {
767    /// The packet number the corresponding PATH_CHALLENGE was received in
768    packet: u64,
769    /// The token of the PATH_CHALLENGE
770    token: u64,
771    /// The address the corresponding PATH_CHALLENGE was received from
772    remote: SocketAddr,
773}
774
775/// Summary statistics of packets that have been sent on a particular path, but which have not yet
776/// been acked or deemed lost
777#[derive(Debug)]
778pub(super) struct InFlight {
779    /// Sum of the sizes of all sent packets considered "in flight" by congestion control
780    ///
781    /// The size does not include IP or UDP overhead. Packets only containing ACK frames do not
782    /// count towards this to ensure congestion control does not impede congestion feedback.
783    pub(super) bytes: u64,
784    /// Number of packets in flight containing frames other than ACK and PADDING
785    ///
786    /// This can be 0 even when bytes is not 0 because PADDING frames cause a packet to be
787    /// considered "in flight" by congestion control. However, if this is nonzero, bytes will always
788    /// also be nonzero.
789    pub(super) ack_eliciting: u64,
790}
791
792impl InFlight {
793    fn new() -> Self {
794        Self {
795            bytes: 0,
796            ack_eliciting: 0,
797        }
798    }
799
800    fn insert(&mut self, packet: &SentPacket) {
801        self.bytes += u64::from(packet.size);
802        self.ack_eliciting += u64::from(packet.ack_eliciting);
803    }
804
805    /// Update counters to account for a packet becoming acknowledged, lost, or abandoned
806    fn remove(&mut self, packet: &SentPacket) {
807        self.bytes -= u64::from(packet.size);
808        self.ack_eliciting -= u64::from(packet.ack_eliciting);
809    }
810}
811
812/// State for QUIC-MULTIPATH PATH_STATUS_AVAILABLE and PATH_STATUS_BACKUP frames
813#[derive(Debug, Clone, Default)]
814pub(super) struct PathStatusState {
815    /// The local status
816    local_status: PathStatus,
817    /// Local sequence number, for both PATH_STATUS_AVAILABLE and PATH_STATUS_BACKUP
818    ///
819    /// This is the number of the *next* path status frame to be sent.
820    local_seq: VarInt,
821    /// The status set by the remote
822    remote_status: Option<(VarInt, PathStatus)>,
823}
824
825impl PathStatusState {
826    /// To be called on received PATH_STATUS_AVAILABLE/PATH_STATUS_BACKUP frames
827    pub(super) fn remote_update(&mut self, status: PathStatus, seq: VarInt) {
828        if self.remote_status.is_some_and(|(curr, _)| curr >= seq) {
829            return trace!(%seq, "ignoring path status update");
830        }
831
832        let prev = self.remote_status.replace((seq, status)).map(|(_, s)| s);
833        if prev != Some(status) {
834            debug!(?status, ?seq, "remote changed path status");
835        }
836    }
837
838    /// Updates the local status
839    ///
840    /// If the local status changed, the previous value is returned
841    pub(super) fn local_update(&mut self, status: PathStatus) -> Option<PathStatus> {
842        if self.local_status == status {
843            return None;
844        }
845
846        self.local_seq = self.local_seq.saturating_add(1u8);
847        Some(std::mem::replace(&mut self.local_status, status))
848    }
849
850    pub(crate) fn seq(&self) -> VarInt {
851        self.local_seq
852    }
853}
854
855/// The QUIC-MULTIPATH path status
856///
857/// See section "3.3 Path Status Management":
858/// <https://quicwg.org/multipath/draft-ietf-quic-multipath.html#name-path-status-management>
859#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)]
860pub enum PathStatus {
861    /// Paths marked with as available will be used when scheduling packets
862    ///
863    /// If multiple paths are available, packets will be scheduled on whichever has
864    /// capacity.
865    #[default]
866    Available,
867    /// Paths marked as backup will only be used if there are no available paths
868    ///
869    /// If the max_idle_timeout is specified the path will be kept alive so that it does not
870    /// expire.
871    Backup,
872}
873
874/// Application events about paths
875#[derive(Debug, Clone, PartialEq, Eq)]
876pub enum PathEvent {
877    /// A new path has been opened
878    Opened {
879        /// Which path is now open
880        id: PathId,
881    },
882    /// A path has been closed
883    Closed {
884        /// Which path has been closed
885        id: PathId,
886        /// Error code supplied by the peer
887        /// See <https://www.ietf.org/archive/id/draft-ietf-quic-multipath-14.html#name-error-codes>
888        /// for a list of known errors.
889        error_code: VarInt,
890    },
891    /// All remaining state for a path has been removed
892    ///
893    /// The [`PathEvent::Closed`] would have been emitted for this path earlier.
894    Abandoned {
895        /// Which path had its state dropped
896        id: PathId,
897        /// The final path stats, they are no longer available via [`Connection::stats`]
898        ///
899        /// [`Connection::stats`]: super::Connection::stats
900        path_stats: PathStats,
901    },
902    /// Path was closed locally
903    LocallyClosed {
904        /// Path for which the error occurred
905        id: PathId,
906        /// The error that occurred
907        error: PathError,
908    },
909    /// The remote changed the status of the path
910    ///
911    /// The local status is not changed because of this event. It is up to the application
912    /// to update the local status, which is used for packet scheduling, when the remote
913    /// changes the status.
914    RemoteStatus {
915        /// Path which has changed status
916        id: PathId,
917        /// The new status set by the remote
918        status: PathStatus,
919    },
920    /// Received an observation of our external address from the peer.
921    ObservedAddr {
922        /// Path over which the observed address was reported, [`PathId::ZERO`] when multipath is
923        /// not negotiated
924        id: PathId,
925        /// The address observed by the remote over this path
926        addr: SocketAddr,
927    },
928}
929
930/// Error from setting path status
931#[derive(Debug, Error, Clone, PartialEq, Eq)]
932pub enum SetPathStatusError {
933    /// Error indicating that a path has not been opened or has already been abandoned
934    #[error("closed path")]
935    ClosedPath,
936    /// Error indicating that this operation requires multipath to be negotiated whereas it hasn't been
937    #[error("multipath not negotiated")]
938    MultipathNotNegotiated,
939}
940
941/// Error indicating that a path has not been opened or has already been abandoned
942#[derive(Debug, Default, Error, Clone, PartialEq, Eq)]
943#[error("closed path")]
944pub struct ClosedPath {
945    pub(super) _private: (),
946}
947
948#[cfg(test)]
949mod tests {
950    use super::*;
951
952    #[test]
953    fn test_path_id_saturating_add() {
954        // add within range behaves normally
955        let large: PathId = u16::MAX.into();
956        let next = u32::from(u16::MAX) + 1;
957        assert_eq!(large.saturating_add(1u8), PathId::from(next));
958
959        // outside range saturates
960        assert_eq!(PathId::MAX.saturating_add(1u8), PathId::MAX)
961    }
962}