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,
15 coding::{self, Decodable, Encodable},
16 congestion,
17 frame::ObservedAddr,
18 packet::SpaceId,
19};
20
21#[cfg(feature = "qlog")]
22use qlog::events::quic::RecoveryMetricsUpdated;
23
24#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default)]
26pub struct PathId(pub(crate) u32);
27
28impl std::hash::Hash for PathId {
29 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
30 state.write_u32(self.0);
31 }
32}
33
34impl identity_hash::IdentityHashable for PathId {}
35
36impl Decodable for PathId {
37 fn decode<B: bytes::Buf>(r: &mut B) -> coding::Result<Self> {
38 let v = VarInt::decode(r)?;
39 let v = u32::try_from(v.0).map_err(|_| coding::UnexpectedEnd)?;
40 Ok(Self(v))
41 }
42}
43
44impl Encodable for PathId {
45 fn encode<B: bytes::BufMut>(&self, w: &mut B) {
46 VarInt(self.0.into()).encode(w)
47 }
48}
49
50impl PathId {
51 pub const MAX: Self = Self(u32::MAX);
53
54 pub const ZERO: Self = Self(0);
56
57 pub(crate) const fn size(&self) -> usize {
59 VarInt(self.0 as u64).size()
60 }
61
62 pub fn saturating_add(self, rhs: impl Into<Self>) -> Self {
65 let rhs = rhs.into();
66 let inner = self.0.saturating_add(rhs.0);
67 Self(inner)
68 }
69
70 pub fn saturating_sub(self, rhs: impl Into<Self>) -> Self {
73 let rhs = rhs.into();
74 let inner = self.0.saturating_sub(rhs.0);
75 Self(inner)
76 }
77
78 pub(crate) fn next(&self) -> Self {
80 self.saturating_add(Self(1))
81 }
82
83 pub(crate) fn as_u32(&self) -> u32 {
85 self.0
86 }
87}
88
89impl std::fmt::Display for PathId {
90 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91 self.0.fmt(f)
92 }
93}
94
95impl<T: Into<u32>> From<T> for PathId {
96 fn from(source: T) -> Self {
97 Self(source.into())
98 }
99}
100
101#[derive(Debug)]
108pub(super) struct PathState {
109 pub(super) data: PathData,
110 pub(super) prev: Option<(ConnectionId, PathData)>,
111}
112
113impl PathState {
114 pub(super) fn remove_in_flight(&mut self, packet: &SentPacket) {
116 for path_data in [&mut self.data]
118 .into_iter()
119 .chain(self.prev.as_mut().map(|(_, data)| data))
120 {
121 if path_data.remove_in_flight(packet) {
122 return;
123 }
124 }
125 }
126}
127
128#[derive(Debug)]
129pub(super) struct SentChallengeInfo {
130 pub(super) sent_instant: Instant,
132 pub(super) remote: SocketAddr,
134}
135
136#[derive(Debug)]
138pub(super) struct PathData {
139 pub(super) remote: SocketAddr,
140 pub(super) rtt: RttEstimator,
141 pub(super) sending_ecn: bool,
143 pub(super) congestion: Box<dyn congestion::Controller>,
145 pub(super) pacing: Pacer,
147 pub(super) challenges_sent: IntMap<u64, SentChallengeInfo>,
149 pub(super) send_new_challenge: bool,
153 pub(super) path_responses: PathResponses,
155 pub(super) validated: bool,
160 pub(super) total_sent: u64,
162 pub(super) total_recvd: u64,
164 pub(super) mtud: MtuDiscovery,
166 pub(super) first_packet_after_rtt_sample: Option<(SpaceId, u64)>,
170 pub(super) in_flight: InFlight,
174 pub(super) observed_addr_sent: bool,
177 pub(super) last_observed_addr_report: Option<ObservedAddr>,
179 pub(super) status: PathStatusState,
181 first_packet: Option<u64>,
188 pub(super) pto_count: u32,
190
191 pub(super) idle_timeout: Option<Duration>,
199 pub(super) keep_alive: Option<Duration>,
207
208 pub(super) open: bool,
214
215 pub(super) last_allowed_receive: Option<Instant>,
222
223 #[cfg(feature = "qlog")]
225 recovery_metrics: RecoveryMetrics,
226
227 generation: u64,
229}
230
231impl PathData {
232 pub(super) fn new(
233 remote: SocketAddr,
234 allow_mtud: bool,
235 peer_max_udp_payload_size: Option<u16>,
236 generation: u64,
237 now: Instant,
238 config: &TransportConfig,
239 ) -> Self {
240 let congestion = config
241 .congestion_controller_factory
242 .clone()
243 .build(now, config.get_initial_mtu());
244 Self {
245 remote,
246 rtt: RttEstimator::new(config.initial_rtt),
247 sending_ecn: true,
248 pacing: Pacer::new(
249 config.initial_rtt,
250 congestion.initial_window(),
251 config.get_initial_mtu(),
252 now,
253 ),
254 congestion,
255 challenges_sent: Default::default(),
256 send_new_challenge: false,
257 path_responses: PathResponses::default(),
258 validated: false,
259 total_sent: 0,
260 total_recvd: 0,
261 mtud: config
262 .mtu_discovery_config
263 .as_ref()
264 .filter(|_| allow_mtud)
265 .map_or(
266 MtuDiscovery::disabled(config.get_initial_mtu(), config.min_mtu),
267 |mtud_config| {
268 MtuDiscovery::new(
269 config.get_initial_mtu(),
270 config.min_mtu,
271 peer_max_udp_payload_size,
272 mtud_config.clone(),
273 )
274 },
275 ),
276 first_packet_after_rtt_sample: None,
277 in_flight: InFlight::new(),
278 observed_addr_sent: false,
279 last_observed_addr_report: None,
280 status: Default::default(),
281 first_packet: None,
282 pto_count: 0,
283 idle_timeout: config.default_path_max_idle_timeout,
284 keep_alive: config.default_path_keep_alive_interval,
285 open: false,
286 last_allowed_receive: None,
287 #[cfg(feature = "qlog")]
288 recovery_metrics: RecoveryMetrics::default(),
289 generation,
290 }
291 }
292
293 pub(super) fn from_previous(
297 remote: SocketAddr,
298 prev: &Self,
299 generation: u64,
300 now: Instant,
301 ) -> Self {
302 let congestion = prev.congestion.clone_box();
303 let smoothed_rtt = prev.rtt.get();
304 Self {
305 remote,
306 rtt: prev.rtt,
307 pacing: Pacer::new(smoothed_rtt, congestion.window(), prev.current_mtu(), now),
308 sending_ecn: true,
309 congestion,
310 challenges_sent: Default::default(),
311 send_new_challenge: false,
312 path_responses: PathResponses::default(),
313 validated: false,
314 total_sent: 0,
315 total_recvd: 0,
316 mtud: prev.mtud.clone(),
317 first_packet_after_rtt_sample: prev.first_packet_after_rtt_sample,
318 in_flight: InFlight::new(),
319 observed_addr_sent: false,
320 last_observed_addr_report: None,
321 status: prev.status.clone(),
322 first_packet: None,
323 pto_count: 0,
324 idle_timeout: prev.idle_timeout,
325 keep_alive: prev.keep_alive,
326 open: false,
327 last_allowed_receive: None,
328 #[cfg(feature = "qlog")]
329 recovery_metrics: prev.recovery_metrics.clone(),
330 generation,
331 }
332 }
333
334 pub(super) fn is_validating_path(&self) -> bool {
336 !self.challenges_sent.is_empty() || self.send_new_challenge
337 }
338
339 pub(super) fn anti_amplification_blocked(&self, bytes_to_send: u64) -> bool {
342 !self.validated && self.total_recvd * 3 < self.total_sent + bytes_to_send
343 }
344
345 pub(super) fn current_mtu(&self) -> u16 {
347 self.mtud.current_mtu()
348 }
349
350 pub(super) fn sent(&mut self, pn: u64, packet: SentPacket, space: &mut PacketNumberSpace) {
352 self.in_flight.insert(&packet);
353 if self.first_packet.is_none() {
354 self.first_packet = Some(pn);
355 }
356 if let Some(forgotten) = space.sent(pn, packet) {
357 self.remove_in_flight(&forgotten);
358 }
359 }
360
361 pub(super) fn remove_in_flight(&mut self, packet: &SentPacket) -> bool {
364 if packet.path_generation != self.generation {
365 return false;
366 }
367 self.in_flight.remove(packet);
368 true
369 }
370
371 pub(super) fn inc_total_sent(&mut self, inc: u64) {
373 self.total_sent = self.total_sent.saturating_add(inc);
374 if !self.validated {
375 trace!(
376 remote = %self.remote,
377 anti_amplification_budget = %(self.total_recvd * 3).saturating_sub(self.total_sent),
378 "anti amplification budget decreased"
379 );
380 }
381 }
382
383 pub(super) fn inc_total_recvd(&mut self, inc: u64) {
385 self.total_recvd = self.total_recvd.saturating_add(inc);
386 if !self.validated {
387 trace!(
388 remote = %self.remote,
389 anti_amplification_budget = %(self.total_recvd * 3).saturating_sub(self.total_sent),
390 "anti amplification budget increased"
391 );
392 }
393 }
394
395 pub(super) fn earliest_expiring_challenge(&self) -> Option<Instant> {
397 if self.challenges_sent.is_empty() {
398 return None;
399 }
400 let pto = self.rtt.pto_base();
401 self.challenges_sent
402 .values()
403 .map(|info| info.sent_instant)
404 .min()
405 .map(|sent_instant| sent_instant + pto)
406 }
407
408 pub(super) fn on_path_response_received(
410 &mut self,
411 now: Instant,
412 token: u64,
413 remote: SocketAddr,
414 ) -> OnPathResponseReceived {
415 match self.challenges_sent.get(&token) {
416 Some(info) if info.remote == remote && self.remote == remote => {
418 let sent_instant = info.sent_instant;
419 if !std::mem::replace(&mut self.validated, true) {
420 trace!("new path validated");
421 }
422 self.challenges_sent
424 .retain(|_token, info| info.remote != remote);
425
426 self.send_new_challenge = false;
427
428 let rtt = now.saturating_duration_since(sent_instant);
431 self.rtt.reset_initial_rtt(rtt);
432
433 let was_open = std::mem::replace(&mut self.open, true);
434 OnPathResponseReceived::OnPath { was_open }
435 }
436 Some(info) if info.remote == remote => {
438 self.challenges_sent
439 .retain(|_token, info| info.remote != remote);
440 OnPathResponseReceived::OffPath
441 }
442 Some(info) => OnPathResponseReceived::Invalid {
444 expected: info.remote,
445 },
446 None => OnPathResponseReceived::Unknown,
448 }
449 }
450
451 #[cfg(feature = "qlog")]
452 pub(super) fn qlog_recovery_metrics(
453 &mut self,
454 path_id: PathId,
455 ) -> Option<RecoveryMetricsUpdated> {
456 let controller_metrics = self.congestion.metrics();
457
458 let metrics = RecoveryMetrics {
459 min_rtt: Some(self.rtt.min),
460 smoothed_rtt: Some(self.rtt.get()),
461 latest_rtt: Some(self.rtt.latest),
462 rtt_variance: Some(self.rtt.var),
463 pto_count: Some(self.pto_count),
464 bytes_in_flight: Some(self.in_flight.bytes),
465 packets_in_flight: Some(self.in_flight.ack_eliciting),
466
467 congestion_window: Some(controller_metrics.congestion_window),
468 ssthresh: controller_metrics.ssthresh,
469 pacing_rate: controller_metrics.pacing_rate,
470 };
471
472 let event = metrics.to_qlog_event(path_id, &self.recovery_metrics);
473 self.recovery_metrics = metrics;
474 event
475 }
476
477 pub(super) fn pacing_delay(&mut self, bytes_to_send: u64, now: Instant) -> Option<Instant> {
481 let smoothed_rtt = self.rtt.get();
482 self.pacing.delay(
483 smoothed_rtt,
484 bytes_to_send,
485 self.current_mtu(),
486 self.congestion.window(),
487 now,
488 )
489 }
490
491 #[must_use = "updated observed address must be reported to the application"]
495 pub(super) fn update_observed_addr_report(
496 &mut self,
497 observed: ObservedAddr,
498 ) -> Option<SocketAddr> {
499 match self.last_observed_addr_report.as_mut() {
500 Some(prev) => {
501 if prev.seq_no >= observed.seq_no {
502 None
504 } else if prev.ip == observed.ip && prev.port == observed.port {
505 prev.seq_no = observed.seq_no;
507 None
508 } else {
509 let addr = observed.socket_addr();
510 self.last_observed_addr_report = Some(observed);
511 Some(addr)
512 }
513 }
514 None => {
515 let addr = observed.socket_addr();
516 self.last_observed_addr_report = Some(observed);
517 Some(addr)
518 }
519 }
520 }
521
522 pub(crate) fn remote_status(&self) -> Option<PathStatus> {
523 self.status.remote_status.map(|(_seq, status)| status)
524 }
525
526 pub(crate) fn local_status(&self) -> PathStatus {
527 self.status.local_status
528 }
529
530 pub(super) fn generation(&self) -> u64 {
531 self.generation
532 }
533}
534
535pub(super) enum OnPathResponseReceived {
536 OnPath { was_open: bool },
538 OffPath,
540 Unknown,
542 Invalid {
544 expected: SocketAddr,
546 },
547}
548
549#[cfg(feature = "qlog")]
553#[derive(Default, Clone, PartialEq, Debug)]
554#[non_exhaustive]
555struct RecoveryMetrics {
556 pub min_rtt: Option<Duration>,
557 pub smoothed_rtt: Option<Duration>,
558 pub latest_rtt: Option<Duration>,
559 pub rtt_variance: Option<Duration>,
560 pub pto_count: Option<u32>,
561 pub bytes_in_flight: Option<u64>,
562 pub packets_in_flight: Option<u64>,
563 pub congestion_window: Option<u64>,
564 pub ssthresh: Option<u64>,
565 pub pacing_rate: Option<u64>,
566}
567
568#[cfg(feature = "qlog")]
569impl RecoveryMetrics {
570 fn retain_updated(&self, previous: &Self) -> Self {
572 macro_rules! keep_if_changed {
573 ($name:ident) => {
574 if previous.$name == self.$name {
575 None
576 } else {
577 self.$name
578 }
579 };
580 }
581
582 Self {
583 min_rtt: keep_if_changed!(min_rtt),
584 smoothed_rtt: keep_if_changed!(smoothed_rtt),
585 latest_rtt: keep_if_changed!(latest_rtt),
586 rtt_variance: keep_if_changed!(rtt_variance),
587 pto_count: keep_if_changed!(pto_count),
588 bytes_in_flight: keep_if_changed!(bytes_in_flight),
589 packets_in_flight: keep_if_changed!(packets_in_flight),
590 congestion_window: keep_if_changed!(congestion_window),
591 ssthresh: keep_if_changed!(ssthresh),
592 pacing_rate: keep_if_changed!(pacing_rate),
593 }
594 }
595
596 fn to_qlog_event(&self, path_id: PathId, previous: &Self) -> Option<RecoveryMetricsUpdated> {
598 let updated = self.retain_updated(previous);
599
600 if updated == Self::default() {
601 return None;
602 }
603
604 Some(RecoveryMetricsUpdated {
605 min_rtt: updated.min_rtt.map(|rtt| rtt.as_secs_f32()),
606 smoothed_rtt: updated.smoothed_rtt.map(|rtt| rtt.as_secs_f32()),
607 latest_rtt: updated.latest_rtt.map(|rtt| rtt.as_secs_f32()),
608 rtt_variance: updated.rtt_variance.map(|rtt| rtt.as_secs_f32()),
609 pto_count: updated
610 .pto_count
611 .map(|count| count.try_into().unwrap_or(u16::MAX)),
612 bytes_in_flight: updated.bytes_in_flight,
613 packets_in_flight: updated.packets_in_flight,
614 congestion_window: updated.congestion_window,
615 ssthresh: updated.ssthresh,
616 pacing_rate: updated.pacing_rate,
617 path_id: Some(path_id.as_u32() as u64),
618 })
619 }
620}
621
622#[derive(Copy, Clone, Debug)]
624pub struct RttEstimator {
625 latest: Duration,
627 smoothed: Option<Duration>,
629 var: Duration,
631 min: Duration,
633}
634
635impl RttEstimator {
636 pub(super) fn new(initial_rtt: Duration) -> Self {
637 Self {
638 latest: initial_rtt,
639 smoothed: None,
640 var: initial_rtt / 2,
641 min: initial_rtt,
642 }
643 }
644
645 pub(crate) fn reset_initial_rtt(&mut self, initial_rtt: Duration) {
658 if self.smoothed.is_none() {
659 self.latest = initial_rtt;
660 self.var = initial_rtt / 2;
661 self.min = initial_rtt;
662 }
663 }
664
665 pub fn get(&self) -> Duration {
667 self.smoothed.unwrap_or(self.latest)
668 }
669
670 pub fn conservative(&self) -> Duration {
675 self.get().max(self.latest)
676 }
677
678 pub fn min(&self) -> Duration {
680 self.min
681 }
682
683 pub(crate) fn pto_base(&self) -> Duration {
685 self.get() + cmp::max(4 * self.var, TIMER_GRANULARITY)
686 }
687
688 pub(crate) fn update(&mut self, ack_delay: Duration, rtt: Duration) {
690 self.latest = rtt;
691 self.min = cmp::min(self.min, self.latest);
694 if let Some(smoothed) = self.smoothed {
696 let adjusted_rtt = if self.min + ack_delay <= self.latest {
697 self.latest - ack_delay
698 } else {
699 self.latest
700 };
701 let var_sample = smoothed.abs_diff(adjusted_rtt);
702 self.var = (3 * self.var + var_sample) / 4;
703 self.smoothed = Some((7 * smoothed + adjusted_rtt) / 8);
704 } else {
705 self.smoothed = Some(self.latest);
706 self.var = self.latest / 2;
707 self.min = self.latest;
708 }
709 }
710}
711
712#[derive(Default, Debug)]
713pub(crate) struct PathResponses {
714 pending: Vec<PathResponse>,
715}
716
717impl PathResponses {
718 pub(crate) fn push(&mut self, packet: u64, token: u64, remote: SocketAddr) {
719 const MAX_PATH_RESPONSES: usize = 16;
721 let response = PathResponse {
722 packet,
723 token,
724 remote,
725 };
726 let existing = self.pending.iter_mut().find(|x| x.remote == remote);
727 if let Some(existing) = existing {
728 if existing.packet <= packet {
730 *existing = response;
731 }
732 return;
733 }
734 if self.pending.len() < MAX_PATH_RESPONSES {
735 self.pending.push(response);
736 } else {
737 trace!("ignoring excessive PATH_CHALLENGE");
740 }
741 }
742
743 pub(crate) fn pop_off_path(&mut self, remote: SocketAddr) -> Option<(u64, SocketAddr)> {
744 let response = *self.pending.last()?;
745 if response.remote == remote {
746 return None;
749 }
750 self.pending.pop();
751 Some((response.token, response.remote))
752 }
753
754 pub(crate) fn pop_on_path(&mut self, remote: SocketAddr) -> Option<u64> {
755 let response = *self.pending.last()?;
756 if response.remote != remote {
757 return None;
760 }
761 self.pending.pop();
762 Some(response.token)
763 }
764
765 pub(crate) fn is_empty(&self) -> bool {
766 self.pending.is_empty()
767 }
768}
769
770#[derive(Copy, Clone, Debug)]
771struct PathResponse {
772 packet: u64,
774 token: u64,
776 remote: SocketAddr,
778}
779
780#[derive(Debug)]
783pub(super) struct InFlight {
784 pub(super) bytes: u64,
789 pub(super) ack_eliciting: u64,
795}
796
797impl InFlight {
798 fn new() -> Self {
799 Self {
800 bytes: 0,
801 ack_eliciting: 0,
802 }
803 }
804
805 fn insert(&mut self, packet: &SentPacket) {
806 self.bytes += u64::from(packet.size);
807 self.ack_eliciting += u64::from(packet.ack_eliciting);
808 }
809
810 fn remove(&mut self, packet: &SentPacket) {
812 self.bytes -= u64::from(packet.size);
813 self.ack_eliciting -= u64::from(packet.ack_eliciting);
814 }
815}
816
817#[derive(Debug, Clone, Default)]
819pub(super) struct PathStatusState {
820 local_status: PathStatus,
822 local_seq: VarInt,
826 remote_status: Option<(VarInt, PathStatus)>,
828}
829
830impl PathStatusState {
831 pub(super) fn remote_update(&mut self, status: PathStatus, seq: VarInt) {
833 if self.remote_status.is_some_and(|(curr, _)| curr >= seq) {
834 return trace!(%seq, "ignoring path status update");
835 }
836
837 let prev = self.remote_status.replace((seq, status)).map(|(_, s)| s);
838 if prev != Some(status) {
839 debug!(?status, ?seq, "remote changed path status");
840 }
841 }
842
843 pub(super) fn local_update(&mut self, status: PathStatus) -> Option<PathStatus> {
847 if self.local_status == status {
848 return None;
849 }
850
851 self.local_seq = self.local_seq.saturating_add(1u8);
852 Some(std::mem::replace(&mut self.local_status, status))
853 }
854
855 pub(crate) fn seq(&self) -> VarInt {
856 self.local_seq
857 }
858}
859
860#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)]
865pub enum PathStatus {
866 #[default]
871 Available,
872 Backup,
877}
878
879#[derive(Debug, Clone, PartialEq, Eq)]
881pub enum PathEvent {
882 Opened {
884 id: PathId,
886 },
887 Closed {
889 id: PathId,
891 error_code: VarInt,
895 },
896 Abandoned {
900 id: PathId,
902 path_stats: PathStats,
906 },
907 LocallyClosed {
909 id: PathId,
911 error: PathError,
913 },
914 RemoteStatus {
920 id: PathId,
922 status: PathStatus,
924 },
925 ObservedAddr {
927 id: PathId,
930 addr: SocketAddr,
932 },
933}
934
935#[derive(Debug, Error, Clone, PartialEq, Eq)]
937pub enum SetPathStatusError {
938 #[error("closed path")]
940 ClosedPath,
941 #[error("multipath not negotiated")]
943 MultipathNotNegotiated,
944}
945
946#[derive(Debug, Default, Error, Clone, PartialEq, Eq)]
948#[error("closed path")]
949pub struct ClosedPath {
950 pub(super) _private: (),
951}
952
953#[cfg(test)]
954mod tests {
955 use super::*;
956
957 #[test]
958 fn test_path_id_saturating_add() {
959 let large: PathId = u16::MAX.into();
961 let next = u32::from(u16::MAX) + 1;
962 assert_eq!(large.saturating_add(1u8), PathId::from(next));
963
964 assert_eq!(PathId::MAX.saturating_add(1u8), PathId::MAX)
966 }
967}