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#[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 pub const MAX: Self = Self(u32::MAX);
48
49 pub const ZERO: Self = Self(0);
51
52 pub(crate) const fn size(&self) -> usize {
54 VarInt(self.0 as u64).size()
55 }
56
57 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 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 pub(crate) fn next(&self) -> Self {
75 self.saturating_add(Self(1))
76 }
77
78 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#[derive(Debug)]
103pub(super) struct PathState {
104 pub(super) data: PathData,
105 pub(super) prev: Option<(ConnectionId, PathData)>,
106}
107
108impl PathState {
109 pub(super) fn remove_in_flight(&mut self, packet: &SentPacket) {
111 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 pub(super) sent_instant: Instant,
127 pub(super) remote: SocketAddr,
129}
130
131#[derive(Debug)]
133pub(super) struct PathData {
134 pub(super) remote: SocketAddr,
135 pub(super) rtt: RttEstimator,
136 pub(super) sending_ecn: bool,
138 pub(super) congestion: Box<dyn congestion::Controller>,
140 pub(super) pacing: Pacer,
142 pub(super) challenges_sent: IntMap<u64, SentChallengeInfo>,
144 pub(super) send_new_challenge: bool,
146 pub(super) path_responses: PathResponses,
148 pub(super) validated: bool,
153 pub(super) total_sent: u64,
155 pub(super) total_recvd: u64,
157 pub(super) mtud: MtuDiscovery,
159 pub(super) first_packet_after_rtt_sample: Option<(SpaceId, u64)>,
163 pub(super) in_flight: InFlight,
167 pub(super) observed_addr_sent: bool,
170 pub(super) last_observed_addr_report: Option<ObservedAddr>,
172 pub(super) status: PathStatusState,
174 first_packet: Option<u64>,
181 pub(super) pto_count: u32,
183
184 pub(super) idle_timeout: Option<Duration>,
192 pub(super) keep_alive: Option<Duration>,
200
201 pub(super) open: bool,
207
208 pub(super) last_allowed_receive: Option<Instant>,
215
216 #[cfg(feature = "qlog")]
218 recovery_metrics: RecoveryMetrics,
219
220 generation: u64,
222}
223
224impl PathData {
225 pub(super) fn new(
226 remote: SocketAddr,
227 allow_mtud: bool,
228 peer_max_udp_payload_size: Option<u16>,
229 generation: u64,
230 now: Instant,
231 config: &TransportConfig,
232 ) -> Self {
233 let congestion = config
234 .congestion_controller_factory
235 .clone()
236 .build(now, config.get_initial_mtu());
237 Self {
238 remote,
239 rtt: RttEstimator::new(config.initial_rtt),
240 sending_ecn: true,
241 pacing: Pacer::new(
242 config.initial_rtt,
243 congestion.initial_window(),
244 config.get_initial_mtu(),
245 now,
246 ),
247 congestion,
248 challenges_sent: Default::default(),
249 send_new_challenge: false,
250 path_responses: PathResponses::default(),
251 validated: false,
252 total_sent: 0,
253 total_recvd: 0,
254 mtud: config
255 .mtu_discovery_config
256 .as_ref()
257 .filter(|_| allow_mtud)
258 .map_or(
259 MtuDiscovery::disabled(config.get_initial_mtu(), config.min_mtu),
260 |mtud_config| {
261 MtuDiscovery::new(
262 config.get_initial_mtu(),
263 config.min_mtu,
264 peer_max_udp_payload_size,
265 mtud_config.clone(),
266 )
267 },
268 ),
269 first_packet_after_rtt_sample: None,
270 in_flight: InFlight::new(),
271 observed_addr_sent: false,
272 last_observed_addr_report: None,
273 status: Default::default(),
274 first_packet: None,
275 pto_count: 0,
276 idle_timeout: None,
277 keep_alive: None,
278 open: false,
279 last_allowed_receive: None,
280 #[cfg(feature = "qlog")]
281 recovery_metrics: RecoveryMetrics::default(),
282 generation,
283 }
284 }
285
286 pub(super) fn from_previous(
290 remote: SocketAddr,
291 prev: &Self,
292 generation: u64,
293 now: Instant,
294 ) -> Self {
295 let congestion = prev.congestion.clone_box();
296 let smoothed_rtt = prev.rtt.get();
297 Self {
298 remote,
299 rtt: prev.rtt,
300 pacing: Pacer::new(smoothed_rtt, congestion.window(), prev.current_mtu(), now),
301 sending_ecn: true,
302 congestion,
303 challenges_sent: Default::default(),
304 send_new_challenge: false,
305 path_responses: PathResponses::default(),
306 validated: false,
307 total_sent: 0,
308 total_recvd: 0,
309 mtud: prev.mtud.clone(),
310 first_packet_after_rtt_sample: prev.first_packet_after_rtt_sample,
311 in_flight: InFlight::new(),
312 observed_addr_sent: false,
313 last_observed_addr_report: None,
314 status: prev.status.clone(),
315 first_packet: None,
316 pto_count: 0,
317 idle_timeout: prev.idle_timeout,
318 keep_alive: prev.keep_alive,
319 open: false,
320 last_allowed_receive: None,
321 #[cfg(feature = "qlog")]
322 recovery_metrics: prev.recovery_metrics.clone(),
323 generation,
324 }
325 }
326
327 pub(super) fn is_validating_path(&self) -> bool {
329 !self.challenges_sent.is_empty() || self.send_new_challenge
330 }
331
332 pub(super) fn anti_amplification_blocked(&self, bytes_to_send: u64) -> bool {
335 !self.validated && self.total_recvd * 3 < self.total_sent + bytes_to_send
336 }
337
338 pub(super) fn current_mtu(&self) -> u16 {
340 self.mtud.current_mtu()
341 }
342
343 pub(super) fn sent(&mut self, pn: u64, packet: SentPacket, space: &mut PacketNumberSpace) {
345 self.in_flight.insert(&packet);
346 if self.first_packet.is_none() {
347 self.first_packet = Some(pn);
348 }
349 if let Some(forgotten) = space.sent(pn, packet) {
350 self.remove_in_flight(&forgotten);
351 }
352 }
353
354 pub(super) fn remove_in_flight(&mut self, packet: &SentPacket) -> bool {
357 if packet.path_generation != self.generation {
358 return false;
359 }
360 self.in_flight.remove(packet);
361 true
362 }
363
364 pub(super) fn inc_total_sent(&mut self, inc: u64) {
366 self.total_sent = self.total_sent.saturating_add(inc);
367 if !self.validated {
368 trace!(
369 remote = %self.remote,
370 anti_amplification_budget = %(self.total_recvd * 3).saturating_sub(self.total_sent),
371 "anti amplification budget decreased"
372 );
373 }
374 }
375
376 pub(super) fn inc_total_recvd(&mut self, inc: u64) {
378 self.total_recvd = self.total_recvd.saturating_add(inc);
379 if !self.validated {
380 trace!(
381 remote = %self.remote,
382 anti_amplification_budget = %(self.total_recvd * 3).saturating_sub(self.total_sent),
383 "anti amplification budget increased"
384 );
385 }
386 }
387
388 pub(super) fn on_path_response_received(
390 &mut self,
391 now: Instant,
392 token: u64,
393 remote: SocketAddr,
394 ) -> OnPathResponseReceived {
395 match self.challenges_sent.get(&token) {
396 Some(info) if info.remote == remote && self.remote == remote => {
398 let sent_instant = info.sent_instant;
399 if !std::mem::replace(&mut self.validated, true) {
400 trace!("new path validated");
401 }
402 self.challenges_sent
404 .retain(|_token, info| info.remote != remote);
405
406 self.send_new_challenge = false;
407
408 let rtt = now.saturating_duration_since(sent_instant);
411 self.rtt.reset_initial_rtt(rtt);
412
413 let was_open = std::mem::replace(&mut self.open, true);
414 OnPathResponseReceived::OnPath { was_open }
415 }
416 Some(info) if info.remote == remote => {
418 self.challenges_sent
419 .retain(|_token, info| info.remote != remote);
420 OnPathResponseReceived::OffPath
421 }
422 Some(info) => OnPathResponseReceived::Invalid {
424 expected: info.remote,
425 },
426 None => OnPathResponseReceived::Unknown,
428 }
429 }
430
431 #[cfg(feature = "qlog")]
432 pub(super) fn qlog_recovery_metrics(
433 &mut self,
434 path_id: PathId,
435 ) -> Option<RecoveryMetricsUpdated> {
436 let controller_metrics = self.congestion.metrics();
437
438 let metrics = RecoveryMetrics {
439 min_rtt: Some(self.rtt.min),
440 smoothed_rtt: Some(self.rtt.get()),
441 latest_rtt: Some(self.rtt.latest),
442 rtt_variance: Some(self.rtt.var),
443 pto_count: Some(self.pto_count),
444 bytes_in_flight: Some(self.in_flight.bytes),
445 packets_in_flight: Some(self.in_flight.ack_eliciting),
446
447 congestion_window: Some(controller_metrics.congestion_window),
448 ssthresh: controller_metrics.ssthresh,
449 pacing_rate: controller_metrics.pacing_rate,
450 };
451
452 let event = metrics.to_qlog_event(path_id, &self.recovery_metrics);
453 self.recovery_metrics = metrics;
454 event
455 }
456
457 pub(super) fn pacing_delay(&mut self, bytes_to_send: u64, now: Instant) -> Option<Instant> {
461 let smoothed_rtt = self.rtt.get();
462 self.pacing.delay(
463 smoothed_rtt,
464 bytes_to_send,
465 self.current_mtu(),
466 self.congestion.window(),
467 now,
468 )
469 }
470
471 #[must_use = "updated observed address must be reported to the application"]
475 pub(super) fn update_observed_addr_report(
476 &mut self,
477 observed: ObservedAddr,
478 ) -> Option<SocketAddr> {
479 match self.last_observed_addr_report.as_mut() {
480 Some(prev) => {
481 if prev.seq_no >= observed.seq_no {
482 None
484 } else if prev.ip == observed.ip && prev.port == observed.port {
485 prev.seq_no = observed.seq_no;
487 None
488 } else {
489 let addr = observed.socket_addr();
490 self.last_observed_addr_report = Some(observed);
491 Some(addr)
492 }
493 }
494 None => {
495 let addr = observed.socket_addr();
496 self.last_observed_addr_report = Some(observed);
497 Some(addr)
498 }
499 }
500 }
501
502 pub(crate) fn remote_status(&self) -> Option<PathStatus> {
503 self.status.remote_status.map(|(_seq, status)| status)
504 }
505
506 pub(crate) fn local_status(&self) -> PathStatus {
507 self.status.local_status
508 }
509
510 pub(super) fn generation(&self) -> u64 {
511 self.generation
512 }
513}
514
515pub(super) enum OnPathResponseReceived {
516 OnPath { was_open: bool },
518 OffPath,
520 Unknown,
522 Invalid {
524 expected: SocketAddr,
526 },
527}
528
529#[cfg(feature = "qlog")]
533#[derive(Default, Clone, PartialEq, Debug)]
534#[non_exhaustive]
535struct RecoveryMetrics {
536 pub min_rtt: Option<Duration>,
537 pub smoothed_rtt: Option<Duration>,
538 pub latest_rtt: Option<Duration>,
539 pub rtt_variance: Option<Duration>,
540 pub pto_count: Option<u32>,
541 pub bytes_in_flight: Option<u64>,
542 pub packets_in_flight: Option<u64>,
543 pub congestion_window: Option<u64>,
544 pub ssthresh: Option<u64>,
545 pub pacing_rate: Option<u64>,
546}
547
548#[cfg(feature = "qlog")]
549impl RecoveryMetrics {
550 fn retain_updated(&self, previous: &Self) -> Self {
552 macro_rules! keep_if_changed {
553 ($name:ident) => {
554 if previous.$name == self.$name {
555 None
556 } else {
557 self.$name
558 }
559 };
560 }
561
562 Self {
563 min_rtt: keep_if_changed!(min_rtt),
564 smoothed_rtt: keep_if_changed!(smoothed_rtt),
565 latest_rtt: keep_if_changed!(latest_rtt),
566 rtt_variance: keep_if_changed!(rtt_variance),
567 pto_count: keep_if_changed!(pto_count),
568 bytes_in_flight: keep_if_changed!(bytes_in_flight),
569 packets_in_flight: keep_if_changed!(packets_in_flight),
570 congestion_window: keep_if_changed!(congestion_window),
571 ssthresh: keep_if_changed!(ssthresh),
572 pacing_rate: keep_if_changed!(pacing_rate),
573 }
574 }
575
576 fn to_qlog_event(&self, path_id: PathId, previous: &Self) -> Option<RecoveryMetricsUpdated> {
578 let updated = self.retain_updated(previous);
579
580 if updated == Self::default() {
581 return None;
582 }
583
584 Some(RecoveryMetricsUpdated {
585 min_rtt: updated.min_rtt.map(|rtt| rtt.as_secs_f32()),
586 smoothed_rtt: updated.smoothed_rtt.map(|rtt| rtt.as_secs_f32()),
587 latest_rtt: updated.latest_rtt.map(|rtt| rtt.as_secs_f32()),
588 rtt_variance: updated.rtt_variance.map(|rtt| rtt.as_secs_f32()),
589 pto_count: updated
590 .pto_count
591 .map(|count| count.try_into().unwrap_or(u16::MAX)),
592 bytes_in_flight: updated.bytes_in_flight,
593 packets_in_flight: updated.packets_in_flight,
594 congestion_window: updated.congestion_window,
595 ssthresh: updated.ssthresh,
596 pacing_rate: updated.pacing_rate,
597 path_id: Some(path_id.as_u32() as u64),
598 })
599 }
600}
601
602#[derive(Copy, Clone, Debug)]
604pub struct RttEstimator {
605 latest: Duration,
607 smoothed: Option<Duration>,
609 var: Duration,
611 min: Duration,
613}
614
615impl RttEstimator {
616 pub(super) fn new(initial_rtt: Duration) -> Self {
617 Self {
618 latest: initial_rtt,
619 smoothed: None,
620 var: initial_rtt / 2,
621 min: initial_rtt,
622 }
623 }
624
625 pub(crate) fn reset_initial_rtt(&mut self, initial_rtt: Duration) {
638 if self.smoothed.is_none() {
639 self.latest = initial_rtt;
640 self.var = initial_rtt / 2;
641 self.min = initial_rtt;
642 }
643 }
644
645 pub fn get(&self) -> Duration {
647 self.smoothed.unwrap_or(self.latest)
648 }
649
650 pub fn conservative(&self) -> Duration {
655 self.get().max(self.latest)
656 }
657
658 pub fn min(&self) -> Duration {
660 self.min
661 }
662
663 pub(crate) fn pto_base(&self) -> Duration {
665 self.get() + cmp::max(4 * self.var, TIMER_GRANULARITY)
666 }
667
668 pub(crate) fn update(&mut self, ack_delay: Duration, rtt: Duration) {
670 self.latest = rtt;
671 self.min = cmp::min(self.min, self.latest);
674 if let Some(smoothed) = self.smoothed {
676 let adjusted_rtt = if self.min + ack_delay <= self.latest {
677 self.latest - ack_delay
678 } else {
679 self.latest
680 };
681 let var_sample = smoothed.abs_diff(adjusted_rtt);
682 self.var = (3 * self.var + var_sample) / 4;
683 self.smoothed = Some((7 * smoothed + adjusted_rtt) / 8);
684 } else {
685 self.smoothed = Some(self.latest);
686 self.var = self.latest / 2;
687 self.min = self.latest;
688 }
689 }
690}
691
692#[derive(Default, Debug)]
693pub(crate) struct PathResponses {
694 pending: Vec<PathResponse>,
695}
696
697impl PathResponses {
698 pub(crate) fn push(&mut self, packet: u64, token: u64, remote: SocketAddr) {
699 const MAX_PATH_RESPONSES: usize = 16;
701 let response = PathResponse {
702 packet,
703 token,
704 remote,
705 };
706 let existing = self.pending.iter_mut().find(|x| x.remote == remote);
707 if let Some(existing) = existing {
708 if existing.packet <= packet {
710 *existing = response;
711 }
712 return;
713 }
714 if self.pending.len() < MAX_PATH_RESPONSES {
715 self.pending.push(response);
716 } else {
717 trace!("ignoring excessive PATH_CHALLENGE");
720 }
721 }
722
723 pub(crate) fn pop_off_path(&mut self, remote: SocketAddr) -> Option<(u64, SocketAddr)> {
724 let response = *self.pending.last()?;
725 if response.remote == remote {
726 return None;
729 }
730 self.pending.pop();
731 Some((response.token, response.remote))
732 }
733
734 pub(crate) fn pop_on_path(&mut self, remote: SocketAddr) -> Option<u64> {
735 let response = *self.pending.last()?;
736 if response.remote != remote {
737 return None;
740 }
741 self.pending.pop();
742 Some(response.token)
743 }
744
745 pub(crate) fn is_empty(&self) -> bool {
746 self.pending.is_empty()
747 }
748}
749
750#[derive(Copy, Clone, Debug)]
751struct PathResponse {
752 packet: u64,
754 token: u64,
756 remote: SocketAddr,
758}
759
760#[derive(Debug)]
763pub(super) struct InFlight {
764 pub(super) bytes: u64,
769 pub(super) ack_eliciting: u64,
775}
776
777impl InFlight {
778 fn new() -> Self {
779 Self {
780 bytes: 0,
781 ack_eliciting: 0,
782 }
783 }
784
785 fn insert(&mut self, packet: &SentPacket) {
786 self.bytes += u64::from(packet.size);
787 self.ack_eliciting += u64::from(packet.ack_eliciting);
788 }
789
790 fn remove(&mut self, packet: &SentPacket) {
792 self.bytes -= u64::from(packet.size);
793 self.ack_eliciting -= u64::from(packet.ack_eliciting);
794 }
795}
796
797#[derive(Debug, Clone, Default)]
799pub(super) struct PathStatusState {
800 local_status: PathStatus,
802 local_seq: VarInt,
806 remote_status: Option<(VarInt, PathStatus)>,
808}
809
810impl PathStatusState {
811 pub(super) fn remote_update(&mut self, status: PathStatus, seq: VarInt) {
813 if self.remote_status.is_some_and(|(curr, _)| curr >= seq) {
814 return trace!(%seq, "ignoring path status update");
815 }
816
817 let prev = self.remote_status.replace((seq, status)).map(|(_, s)| s);
818 if prev != Some(status) {
819 debug!(?status, ?seq, "remote changed path status");
820 }
821 }
822
823 pub(super) fn local_update(&mut self, status: PathStatus) -> Option<PathStatus> {
827 if self.local_status == status {
828 return None;
829 }
830
831 self.local_seq = self.local_seq.saturating_add(1u8);
832 Some(std::mem::replace(&mut self.local_status, status))
833 }
834
835 pub(crate) fn seq(&self) -> VarInt {
836 self.local_seq
837 }
838}
839
840#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)]
845pub enum PathStatus {
846 #[default]
851 Available,
852 Backup,
857}
858
859#[derive(Debug, Clone, PartialEq, Eq)]
861pub enum PathEvent {
862 Opened {
864 id: PathId,
866 },
867 Closed {
869 id: PathId,
871 error_code: VarInt,
875 },
876 Abandoned {
880 id: PathId,
882 path_stats: PathStats,
886 },
887 LocallyClosed {
889 id: PathId,
891 error: PathError,
893 },
894 RemoteStatus {
900 id: PathId,
902 status: PathStatus,
904 },
905 ObservedAddr {
907 id: PathId,
910 addr: SocketAddr,
912 },
913}
914
915#[derive(Debug, Error, Clone, PartialEq, Eq)]
917pub enum SetPathStatusError {
918 #[error("closed path")]
920 ClosedPath,
921 #[error("multipath not negotiated")]
923 MultipathNotNegotiated,
924}
925
926#[derive(Debug, Default, Error, Clone, PartialEq, Eq)]
928#[error("closed path")]
929pub struct ClosedPath {
930 pub(super) _private: (),
931}
932
933#[cfg(test)]
934mod tests {
935 use super::*;
936
937 #[test]
938 fn test_path_id_saturating_add() {
939 let large: PathId = u16::MAX.into();
941 let next = u32::from(u16::MAX) + 1;
942 assert_eq!(large.saturating_add(1u8), PathId::from(next));
943
944 assert_eq!(PathId::MAX.saturating_add(1u8), PathId::MAX)
946 }
947}