From 4dcedb70a4eccf81cac35ffb39f2a8933fbe6b3a Mon Sep 17 00:00:00 2001 From: dignifiedquire Date: Fri, 12 Dec 2025 22:19:55 +0000 Subject: [PATCH] deploy: b6e363bcc75fbd2218e98ee59e52082be20e1591 --- .../docs/iroh/endpoint/struct.PathInfo.html | 18 +- .../iroh/endpoint/struct.PathInfoList.html | 14 +- .../magicsock/remote_map/remote_state.rs.html | 1459 +++++++++-------- 3 files changed, 750 insertions(+), 741 deletions(-) diff --git a/pr/3763/docs/iroh/endpoint/struct.PathInfo.html b/pr/3763/docs/iroh/endpoint/struct.PathInfo.html index b5a96808e4..2bc36e4d24 100644 --- a/pr/3763/docs/iroh/endpoint/struct.PathInfo.html +++ b/pr/3763/docs/iroh/endpoint/struct.PathInfo.html @@ -1,12 +1,12 @@ -PathInfo in iroh::endpoint - Rust

PathInfo

Struct PathInfo 

Source
pub struct PathInfo { /* private fields */ }
Expand description

Information about a network path used by a Connection.

-

Implementations§

Source§

impl PathInfo

Source

pub fn remote_addr(&self) -> &TransportAddr

The remote transport address used by this network path.

-
Source

pub fn is_selected(&self) -> bool

Returns true if this path is currently the main transmission path for this Connection.

-
Source

pub fn is_ip(&self) -> bool

Whether this is an IP transport address.

-
Source

pub fn is_relay(&self) -> bool

Whether this is a transport address via a relay server.

-
Source

pub fn stats(&self) -> PathStats

Returns stats for this transmission path.

-
Source

pub fn rtt(&self) -> Duration

Current best estimate of this paths’s latency (round-trip-time)

-

Trait Implementations§

Source§

impl Clone for PathInfo

Source§

fn clone(&self) -> PathInfo

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for PathInfo

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for PathInfo

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, -and should not be overridden without very good reason.
Source§

impl Eq for PathInfo

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +PathInfo in iroh::endpoint - Rust

PathInfo

Struct PathInfo 

Source
pub struct PathInfo { /* private fields */ }
Expand description

Information about a network path used by a Connection.

+

Implementations§

Source§

impl PathInfo

Source

pub fn remote_addr(&self) -> &TransportAddr

The remote transport address used by this network path.

+
Source

pub fn is_selected(&self) -> bool

Returns true if this path is currently the main transmission path for this Connection.

+
Source

pub fn is_ip(&self) -> bool

Whether this is an IP transport address.

+
Source

pub fn is_relay(&self) -> bool

Whether this is a transport address via a relay server.

+
Source

pub fn stats(&self) -> PathStats

Returns stats for this transmission path.

+
Source

pub fn rtt(&self) -> Duration

Current best estimate of this paths’s latency (round-trip-time)

+

Trait Implementations§

Source§

impl Clone for PathInfo

Source§

fn clone(&self) -> PathInfo

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for PathInfo

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for PathInfo

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +and should not be overridden without very good reason.
Source§

impl Eq for PathInfo

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3763/docs/iroh/endpoint/struct.PathInfoList.html b/pr/3763/docs/iroh/endpoint/struct.PathInfoList.html index fbf2dd944f..41995bc635 100644 --- a/pr/3763/docs/iroh/endpoint/struct.PathInfoList.html +++ b/pr/3763/docs/iroh/endpoint/struct.PathInfoList.html @@ -1,11 +1,11 @@ -PathInfoList in iroh::endpoint - Rust

PathInfoList

Struct PathInfoList 

Source
pub struct PathInfoList(/* private fields */);
Expand description

List of PathInfo for the network paths of a Connection.

+PathInfoList in iroh::endpoint - Rust

PathInfoList

Struct PathInfoList 

Source
pub struct PathInfoList(/* private fields */);
Expand description

List of PathInfo for the network paths of a Connection.

This struct implements IntoIterator.

-

Implementations§

Source§

impl PathInfoList

Source

pub fn iter(&self) -> impl Iterator<Item = &PathInfo>

Returns an iterator over the path infos.

-
Source

pub fn is_empty(&self) -> bool

Returns true if the list is empty.

-
Source

pub fn len(&self) -> usize

Returns the number of paths.

-

Trait Implementations§

Source§

impl Clone for PathInfoList

Source§

fn clone(&self) -> PathInfoList

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for PathInfoList

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl IntoIterator for PathInfoList
where - SmallVec<[PathInfo; 4]>: IntoIterator,

Source§

type Item = <SmallVec<[PathInfo; 4]> as IntoIterator>::Item

The type of the elements being iterated over.
Source§

type IntoIter = <SmallVec<[PathInfo; 4]> as IntoIterator>::IntoIter

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl PartialEq for PathInfoList

Source§

fn eq(&self, other: &PathInfoList) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, -and should not be overridden without very good reason.
Source§

impl Eq for PathInfoList

Source§

impl StructuralPartialEq for PathInfoList

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Implementations§

Source§

impl PathInfoList

Source

pub fn iter(&self) -> impl Iterator<Item = &PathInfo>

Returns an iterator over the path infos.

+
Source

pub fn is_empty(&self) -> bool

Returns true if the list is empty.

+
Source

pub fn len(&self) -> usize

Returns the number of paths.

+

Trait Implementations§

Source§

impl Clone for PathInfoList

Source§

fn clone(&self) -> PathInfoList

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for PathInfoList

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl IntoIterator for PathInfoList
where + SmallVec<[PathInfo; 4]>: IntoIterator,

Source§

type Item = <SmallVec<[PathInfo; 4]> as IntoIterator>::Item

The type of the elements being iterated over.
Source§

type IntoIter = <SmallVec<[PathInfo; 4]> as IntoIterator>::IntoIter

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl PartialEq for PathInfoList

Source§

fn eq(&self, other: &PathInfoList) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +and should not be overridden without very good reason.
Source§

impl Eq for PathInfoList

Source§

impl StructuralPartialEq for PathInfoList

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3763/docs/src/iroh/magicsock/remote_map/remote_state.rs.html b/pr/3763/docs/src/iroh/magicsock/remote_map/remote_state.rs.html index 03721fbf82..698e4eaea5 100644 --- a/pr/3763/docs/src/iroh/magicsock/remote_map/remote_state.rs.html +++ b/pr/3763/docs/src/iroh/magicsock/remote_map/remote_state.rs.html @@ -726,742 +726,751 @@ 726 Some(path_id) => { 727 trace!(?conn_id, ?path_id, "opening new path"); 728 conn_state.add_path(open_addr.clone(), path_id); -729 } -730 None => { -731 let ret = now_or_never(fut); -732 match ret { -733 Some(Err(PathError::RemoteCidsExhausted)) => { -734 self.scheduled_open_path = -735 Some(Instant::now() + Duration::from_millis(333)); -736 self.pending_open_paths.push_back(open_addr.clone()); -737 trace!(?open_addr, "scheduling open_path"); -738 } -739 _ => warn!(?ret, "Opening path failed"), -740 } -741 } -742 } -743 } -744 } -745 -746 #[instrument(skip(self))] -747 fn handle_path_event( -748 &mut self, -749 conn_id: ConnId, -750 event: Result<PathEvent, BroadcastStreamRecvError>, -751 ) { -752 let Ok(event) = event else { -753 warn!("missed a PathEvent, RemoteStateActor lagging"); -754 // TODO: Is it possible to recover using the sync APIs to figure out what the -755 // state of the connection and it's paths are? -756 return; -757 }; -758 let Some(conn_state) = self.connections.get_mut(&conn_id) else { -759 trace!("event for removed connection"); -760 return; -761 }; -762 let Some(conn) = conn_state.handle.upgrade() else { -763 trace!("event for closed connection"); -764 return; -765 }; -766 trace!("path event"); -767 match event { -768 PathEvent::Opened { id: path_id } => { -769 let Some(path) = conn.path(path_id) else { -770 trace!("path open event for unknown path"); -771 return; -772 }; -773 -774 if let Ok(socketaddr) = path.remote_address() -775 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr) -776 { -777 event!( -778 target: "iroh::_events::path::open", -779 Level::DEBUG, -780 remote = %self.endpoint_id.fmt_short(), -781 ?path_remote, -782 ?conn_id, -783 ?path_id, -784 ); -785 conn_state.add_open_path(path_remote.clone(), path_id); -786 self.paths -787 .insert_open_path(path_remote.clone(), Source::Connection { _0: Private }); -788 } -789 -790 self.select_path(); -791 } -792 PathEvent::Abandoned { id, path_stats } => { -793 trace!(?path_stats, "path abandoned"); -794 // This is the last event for this path. -795 if let Some(addr) = conn_state.remove_path(&id) { -796 self.paths.abandoned_path(&addr); +729 // We still need to ensure that the path status is set correctly, +730 // in case the path was opened by QNT, which opens all IP paths +731 // using PATH_STATUS_BACKUP. We need to switch the selected path +732 // to use PATH_STATUS_AVAILABLE though! +733 if let Some(path) = conn.path(path_id) { +734 if let Err(e) = path.set_status(path_status) { +735 warn!(?e, ?open_addr, ?path_status, "Setting path status failed"); +736 } +737 } +738 } +739 None => { +740 let ret = now_or_never(fut); +741 match ret { +742 Some(Err(PathError::RemoteCidsExhausted)) => { +743 self.scheduled_open_path = +744 Some(Instant::now() + Duration::from_millis(333)); +745 self.pending_open_paths.push_back(open_addr.clone()); +746 trace!(?open_addr, "scheduling open_path"); +747 } +748 _ => warn!(?ret, "Opening path failed"), +749 } +750 } +751 } +752 } +753 } +754 +755 #[instrument(skip(self))] +756 fn handle_path_event( +757 &mut self, +758 conn_id: ConnId, +759 event: Result<PathEvent, BroadcastStreamRecvError>, +760 ) { +761 let Ok(event) = event else { +762 warn!("missed a PathEvent, RemoteStateActor lagging"); +763 // TODO: Is it possible to recover using the sync APIs to figure out what the +764 // state of the connection and it's paths are? +765 return; +766 }; +767 let Some(conn_state) = self.connections.get_mut(&conn_id) else { +768 trace!("event for removed connection"); +769 return; +770 }; +771 let Some(conn) = conn_state.handle.upgrade() else { +772 trace!("event for closed connection"); +773 return; +774 }; +775 trace!("path event"); +776 match event { +777 PathEvent::Opened { id: path_id } => { +778 let Some(path) = conn.path(path_id) else { +779 trace!("path open event for unknown path"); +780 return; +781 }; +782 +783 if let Ok(socketaddr) = path.remote_address() +784 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr) +785 { +786 event!( +787 target: "iroh::_events::path::open", +788 Level::DEBUG, +789 remote = %self.endpoint_id.fmt_short(), +790 ?path_remote, +791 ?conn_id, +792 ?path_id, +793 ); +794 conn_state.add_open_path(path_remote.clone(), path_id); +795 self.paths +796 .insert_open_path(path_remote.clone(), Source::Connection { _0: Private }); 797 } -798 } -799 PathEvent::Closed { id, .. } | PathEvent::LocallyClosed { id, .. } => { -800 let Some(path_remote) = conn_state.paths.get(&id).cloned() else { -801 debug!("path not in path_id_map"); -802 return; -803 }; -804 event!( -805 target: "iroh::_events::path::closed", -806 Level::DEBUG, -807 remote = %self.endpoint_id.fmt_short(), -808 ?path_remote, -809 ?conn_id, -810 path_id = ?id, -811 ); -812 conn_state.remove_open_path(&id); -813 -814 // If one connection closes this path, close it on all connections. -815 for (conn_id, conn_state) in self.connections.iter_mut() { -816 let Some(path_id) = conn_state.path_ids.get(&path_remote) else { -817 continue; -818 }; -819 let Some(conn) = conn_state.handle.upgrade() else { -820 continue; -821 }; -822 if let Some(path) = conn.path(*path_id) { -823 trace!(?path_remote, ?conn_id, ?path_id, "closing path"); -824 if let Err(err) = path.close() { -825 trace!( -826 ?path_remote, -827 ?conn_id, -828 ?path_id, -829 "path close failed: {err:#}" -830 ); -831 } -832 } -833 } -834 -835 // If the remote closed our selected path, select a new one. -836 self.select_path(); -837 } -838 PathEvent::RemoteStatus { .. } | PathEvent::ObservedAddr { .. } => { -839 // Nothing to do for these events. -840 } -841 } -842 } +798 +799 self.select_path(); +800 } +801 PathEvent::Abandoned { id, path_stats } => { +802 trace!(?path_stats, "path abandoned"); +803 // This is the last event for this path. +804 if let Some(addr) = conn_state.remove_path(&id) { +805 self.paths.abandoned_path(&addr); +806 } +807 } +808 PathEvent::Closed { id, .. } | PathEvent::LocallyClosed { id, .. } => { +809 let Some(path_remote) = conn_state.paths.get(&id).cloned() else { +810 debug!("path not in path_id_map"); +811 return; +812 }; +813 event!( +814 target: "iroh::_events::path::closed", +815 Level::DEBUG, +816 remote = %self.endpoint_id.fmt_short(), +817 ?path_remote, +818 ?conn_id, +819 path_id = ?id, +820 ); +821 conn_state.remove_open_path(&id); +822 +823 // If one connection closes this path, close it on all connections. +824 for (conn_id, conn_state) in self.connections.iter_mut() { +825 let Some(path_id) = conn_state.path_ids.get(&path_remote) else { +826 continue; +827 }; +828 let Some(conn) = conn_state.handle.upgrade() else { +829 continue; +830 }; +831 if let Some(path) = conn.path(*path_id) { +832 trace!(?path_remote, ?conn_id, ?path_id, "closing path"); +833 if let Err(err) = path.close() { +834 trace!( +835 ?path_remote, +836 ?conn_id, +837 ?path_id, +838 "path close failed: {err:#}" +839 ); +840 } +841 } +842 } 843 -844 /// Selects the path with the lowest RTT, prefers direct paths. -845 /// -846 /// If there are direct paths, this selects the direct path with the lowest RTT. If -847 /// there are only relay paths, the relay path with the lowest RTT is chosen. -848 /// -849 /// The selected path is added to any connections which do not yet have it. Any unused -850 /// direct paths are closed for all connections. -851 #[instrument(skip_all)] -852 fn select_path(&mut self) { -853 // Find the lowest RTT across all connections for each open path. The long way, so -854 // we get to log *all* RTTs. -855 let mut all_path_rtts: FxHashMap<transports::Addr, Vec<Duration>> = FxHashMap::default(); -856 for conn_state in self.connections.values() { -857 let Some(conn) = conn_state.handle.upgrade() else { -858 continue; -859 }; -860 for (path_id, addr) in conn_state.open_paths.iter() { -861 if let Some(stats) = conn.path_stats(*path_id) { -862 all_path_rtts -863 .entry(addr.clone()) -864 .or_default() -865 .push(stats.rtt); -866 } -867 } -868 } -869 trace!(?all_path_rtts, "dumping all path RTTs"); -870 let path_rtts: FxHashMap<transports::Addr, Duration> = all_path_rtts -871 .into_iter() -872 .filter_map(|(addr, rtts)| rtts.into_iter().min().map(|rtt| (addr, rtt))) -873 .collect(); -874 -875 // Find the fastest direct IPv4 path. -876 let direct_path_ipv4 = path_rtts -877 .iter() -878 .filter_map(|(addr, rtt)| { -879 if let transports::Addr::Ip(SocketAddr::V4(addr)) = *addr { -880 Some((addr, *rtt)) -881 } else { -882 None -883 } -884 }) -885 .min_by_key(|(_addr, rtt)| *rtt); -886 -887 // Find the fastest direct IPv6 path. -888 let direct_path_ipv6 = path_rtts -889 .iter() -890 .filter_map(|(addr, rtt)| { -891 if let transports::Addr::Ip(SocketAddr::V6(addr)) = *addr { -892 Some((addr, *rtt)) -893 } else { -894 None -895 } -896 }) -897 .min_by_key(|(_addr, rtt)| *rtt); -898 -899 // Find the fastest relay path. -900 let relay_path = path_rtts -901 .iter() -902 .filter(|(addr, _rtt)| addr.is_relay()) -903 .min_by_key(|(_addr, rtt)| *rtt) -904 .map(|(addr, rtt)| (addr.clone(), *rtt)); -905 -906 let current_path = self -907 .selected_path -908 .get() -909 .and_then(|addr| path_rtts.get(&addr).copied().map(|rtt| (addr, rtt))); -910 let selected_path = select_best_path( -911 current_path.clone(), -912 direct_path_ipv4, -913 direct_path_ipv6, -914 relay_path, -915 ); -916 -917 // Apply our new path -918 if let Some((addr, rtt)) = selected_path { -919 let prev = self.selected_path.set(Some(addr.clone())); -920 if prev.is_ok() { -921 debug!(?addr, ?rtt, ?prev, "selected new path"); -922 } -923 self.open_path(&addr); -924 self.close_redundant_paths(&addr); -925 } else { -926 trace!(?current_path, "keeping current path"); -927 } -928 } -929 -930 /// Closes any direct paths not selected if we are the client. -931 /// -932 /// Makes sure not to close the last direct path. Relay paths are never closed -933 /// currently, because we only have one relay path at this time. -934 /// -935 /// Only the client closes paths, just like only the client opens paths. This is to -936 /// avoid the client and server selecting different paths and accidentally closing all -937 /// paths. -938 fn close_redundant_paths(&mut self, selected_path: &transports::Addr) { -939 debug_assert_eq!(self.selected_path.get().as_ref(), Some(selected_path),); -940 -941 for (conn_id, conn_state) in self.connections.iter() { -942 for (path_id, path_remote) in conn_state -943 .open_paths -944 .iter() -945 .filter(|(_, addr)| addr.is_ip()) -946 .filter(|(_, addr)| *addr != selected_path) -947 { -948 if conn_state.open_paths.values().filter(|a| a.is_ip()).count() <= 1 { -949 continue; // Do not close the last direct path. -950 } -951 if let Some(path) = conn_state -952 .handle -953 .upgrade() -954 .filter(|conn| conn.side().is_client()) -955 .and_then(|conn| conn.path(*path_id)) -956 { -957 trace!(?path_remote, ?conn_id, ?path_id, "closing direct path"); -958 match path.close() { -959 Err(quinn_proto::ClosePathError::LastOpenPath) => { -960 error!("could not close last open path"); -961 } -962 Err(quinn_proto::ClosePathError::ClosedPath) => { -963 // We already closed this. -964 } -965 Ok(_fut) => { -966 // We will handle the event in Self::handle_path_events. -967 } -968 } -969 } -970 } -971 } -972 } -973} -974 -975/// Returns `Some` if a new path should be selected, `None` if the `current_path` should -976/// continued to be used. -977fn select_best_path( -978 current_path: Option<(transports::Addr, Duration)>, -979 direct_path_ipv4: Option<(SocketAddrV4, Duration)>, -980 direct_path_ipv6: Option<(SocketAddrV6, Duration)>, -981 new_relay_path: Option<(transports::Addr, Duration)>, -982) -> Option<(transports::Addr, Duration)> { -983 // Determine the best new IP path. -984 let best_ip_path = match (direct_path_ipv4, direct_path_ipv6) { -985 (Some((addr_v4, rtt_v4)), Some((addr_v6, rtt_v6))) => { -986 Some(select_v4_v6(addr_v4, rtt_v4, addr_v6, rtt_v6)) -987 } -988 (None, Some((addr_v6, rtt_v6))) => Some((addr_v6.into(), rtt_v6)), -989 (Some((addr_v4, rtt_v4)), None) => Some((addr_v4.into(), rtt_v4)), -990 (None, None) => None, -991 }; -992 let best_ip_path = best_ip_path.map(|(addr, rtt)| (transports::Addr::Ip(addr), rtt)); -993 -994 match current_path { -995 None => { -996 // If we currently have no path -997 if best_ip_path.is_some() { -998 // Use the best IP path -999 best_ip_path -1000 } else { -1001 // Use the new relay path -1002 new_relay_path -1003 } -1004 } -1005 Some((transports::Addr::Relay(..), _)) => { -1006 // If we have a current path, but it is relay -1007 if best_ip_path.is_some() { -1008 // Use the best IP path -1009 best_ip_path -1010 } else { -1011 // Use the new relay path -1012 new_relay_path -1013 } -1014 } -1015 Some((transports::Addr::Ip(_), current_rtt)) => { -1016 match &best_ip_path { -1017 Some((_, new_rtt)) => { -1018 // Comparing available IP paths -1019 if current_rtt >= *new_rtt + RTT_SWITCHING_MIN_IP { -1020 // New IP path is faster -1021 best_ip_path -1022 } else { -1023 // New IP is not faster -1024 None -1025 } -1026 } -1027 None => { -1028 // No new IP path, don't switch away -1029 None -1030 } -1031 } -1032 } -1033 } -1034} -1035 -1036/// Compare two IP addrs v4 & v6 and selects the "best" one. -1037/// -1038/// This prefers IPv6 paths over IPv4 paths. -1039fn select_v4_v6( -1040 addr_v4: SocketAddrV4, -1041 rtt_v4: Duration, -1042 addr_v6: SocketAddrV6, -1043 rtt_v6: Duration, -1044) -> (SocketAddr, Duration) { -1045 if rtt_v6 <= rtt_v4 + IPV6_RTT_ADVANTAGE { -1046 (addr_v6.into(), rtt_v6) -1047 } else { -1048 (addr_v4.into(), rtt_v4) -1049 } -1050} -1051 -1052fn send_datagram<'a>( -1053 sender: &'a mut TransportsSender, -1054 dst: transports::Addr, -1055 owned_transmit: OwnedTransmit, -1056) -> impl Future<Output = n0_error::Result<()>> + 'a { -1057 std::future::poll_fn(move |cx| { -1058 let transmit = transports::Transmit { -1059 ecn: owned_transmit.ecn, -1060 contents: owned_transmit.contents.as_ref(), -1061 segment_size: owned_transmit.segment_size, -1062 }; -1063 -1064 Pin::new(&mut *sender) -1065 .poll_send(cx, &dst, None, &transmit) -1066 .map(|res| res.with_context(|_| format!("failed to send datagram to {dst:?}"))) -1067 }) -1068} -1069 -1070/// Messages to send to the [`RemoteStateActor`]. -1071#[derive(derive_more::Debug)] -1072pub(crate) enum RemoteStateMessage { -1073 /// Sends a datagram to all known paths. -1074 /// -1075 /// Used to send QUIC Initial packets. If there is no working direct path this will -1076 /// trigger holepunching. -1077 /// -1078 /// This is not acceptable to use on the normal send path, as it is an async send -1079 /// operation with a bunch more copying. So it should only be used for sending QUIC -1080 /// Initial packets. -1081 #[debug("SendDatagram(..)")] -1082 SendDatagram(TransportsSender, OwnedTransmit), -1083 /// Adds an active connection to this remote endpoint. -1084 /// -1085 /// The connection will now be managed by this actor. Holepunching will happen when -1086 /// needed, any new paths discovered via holepunching will be added. And closed paths -1087 /// will be removed etc. -1088 #[debug("AddConnection(..)")] -1089 AddConnection(WeakConnectionHandle, oneshot::Sender<PathsWatcher>), -1090 /// Asks if there is any possible path that could be used. -1091 /// -1092 /// This adds the provided transport addresses to the list of potential paths for this remote -1093 /// and starts discovery if needed. -1094 /// -1095 /// Returns `Ok` immediately if the provided address list is non-empy or we have are other known paths. -1096 /// Otherwise returns `Ok` once discovery produces a result, or the discovery error if discovery fails -1097 /// or produces no results, -1098 #[debug("ResolveRemote(..)")] -1099 ResolveRemote( -1100 BTreeSet<TransportAddr>, -1101 oneshot::Sender<Result<(), DiscoveryError>>, -1102 ), -1103} -1104 -1105/// A handle to a [`RemoteStateActor`]. -1106/// -1107/// Dropping this will stop the actor. The actor will also stop after an idle timeout -1108/// if it has no connections, an empty inbox, and no other senders than the one stored -1109/// in the endpoint map exist. -1110#[derive(Debug)] -1111pub(super) struct RemoteStateHandle { -1112 /// Sender for the channel into the [`RemoteStateActor`]. -1113 /// -1114 /// This is a [`GuardedSender`], from which we can get a sender but only if the receiver -1115 /// hasn't been closed. -1116 pub(super) sender: GuardedSender<RemoteStateMessage>, -1117 _task: AbortOnDropHandle<()>, -1118} -1119 -1120/// Information about a holepunch attempt. -1121/// -1122/// Addresses are always stored in canonical form. -1123#[derive(Debug)] -1124struct HolepunchAttempt { -1125 when: Instant, -1126 /// The set of local addresses which could take part in holepunching. -1127 /// -1128 /// This does not mean every address here participated in the holepunching. E.g. we -1129 /// could have tried only a sub-set of the addresses because a previous attempt already -1130 /// covered part of the range. -1131 /// -1132 /// We do not store this as a [`DirectAddr`] because this is checked for equality and we -1133 /// do not want to compare the sources of these addresses. -1134 local_candidates: BTreeSet<SocketAddr>, -1135 /// The set of remote addresses which could take part in holepunching. +844 // If the remote closed our selected path, select a new one. +845 self.select_path(); +846 } +847 PathEvent::RemoteStatus { .. } | PathEvent::ObservedAddr { .. } => { +848 // Nothing to do for these events. +849 } +850 } +851 } +852 +853 /// Selects the path with the lowest RTT, prefers direct paths. +854 /// +855 /// If there are direct paths, this selects the direct path with the lowest RTT. If +856 /// there are only relay paths, the relay path with the lowest RTT is chosen. +857 /// +858 /// The selected path is added to any connections which do not yet have it. Any unused +859 /// direct paths are closed for all connections. +860 #[instrument(skip_all)] +861 fn select_path(&mut self) { +862 // Find the lowest RTT across all connections for each open path. The long way, so +863 // we get to log *all* RTTs. +864 let mut all_path_rtts: FxHashMap<transports::Addr, Vec<Duration>> = FxHashMap::default(); +865 for conn_state in self.connections.values() { +866 let Some(conn) = conn_state.handle.upgrade() else { +867 continue; +868 }; +869 for (path_id, addr) in conn_state.open_paths.iter() { +870 if let Some(stats) = conn.path_stats(*path_id) { +871 all_path_rtts +872 .entry(addr.clone()) +873 .or_default() +874 .push(stats.rtt); +875 } +876 } +877 } +878 trace!(?all_path_rtts, "dumping all path RTTs"); +879 let path_rtts: FxHashMap<transports::Addr, Duration> = all_path_rtts +880 .into_iter() +881 .filter_map(|(addr, rtts)| rtts.into_iter().min().map(|rtt| (addr, rtt))) +882 .collect(); +883 +884 // Find the fastest direct IPv4 path. +885 let direct_path_ipv4 = path_rtts +886 .iter() +887 .filter_map(|(addr, rtt)| { +888 if let transports::Addr::Ip(SocketAddr::V4(addr)) = *addr { +889 Some((addr, *rtt)) +890 } else { +891 None +892 } +893 }) +894 .min_by_key(|(_addr, rtt)| *rtt); +895 +896 // Find the fastest direct IPv6 path. +897 let direct_path_ipv6 = path_rtts +898 .iter() +899 .filter_map(|(addr, rtt)| { +900 if let transports::Addr::Ip(SocketAddr::V6(addr)) = *addr { +901 Some((addr, *rtt)) +902 } else { +903 None +904 } +905 }) +906 .min_by_key(|(_addr, rtt)| *rtt); +907 +908 // Find the fastest relay path. +909 let relay_path = path_rtts +910 .iter() +911 .filter(|(addr, _rtt)| addr.is_relay()) +912 .min_by_key(|(_addr, rtt)| *rtt) +913 .map(|(addr, rtt)| (addr.clone(), *rtt)); +914 +915 let current_path = self +916 .selected_path +917 .get() +918 .and_then(|addr| path_rtts.get(&addr).copied().map(|rtt| (addr, rtt))); +919 let selected_path = select_best_path( +920 current_path.clone(), +921 direct_path_ipv4, +922 direct_path_ipv6, +923 relay_path, +924 ); +925 +926 // Apply our new path +927 if let Some((addr, rtt)) = selected_path { +928 let prev = self.selected_path.set(Some(addr.clone())); +929 if prev.is_ok() { +930 debug!(?addr, ?rtt, ?prev, "selected new path"); +931 } +932 self.open_path(&addr); +933 self.close_redundant_paths(&addr); +934 } else { +935 trace!(?current_path, "keeping current path"); +936 } +937 } +938 +939 /// Closes any direct paths not selected if we are the client. +940 /// +941 /// Makes sure not to close the last direct path. Relay paths are never closed +942 /// currently, because we only have one relay path at this time. +943 /// +944 /// Only the client closes paths, just like only the client opens paths. This is to +945 /// avoid the client and server selecting different paths and accidentally closing all +946 /// paths. +947 fn close_redundant_paths(&mut self, selected_path: &transports::Addr) { +948 debug_assert_eq!(self.selected_path.get().as_ref(), Some(selected_path),); +949 +950 for (conn_id, conn_state) in self.connections.iter() { +951 for (path_id, path_remote) in conn_state +952 .open_paths +953 .iter() +954 .filter(|(_, addr)| addr.is_ip()) +955 .filter(|(_, addr)| *addr != selected_path) +956 { +957 if conn_state.open_paths.values().filter(|a| a.is_ip()).count() <= 1 { +958 continue; // Do not close the last direct path. +959 } +960 if let Some(path) = conn_state +961 .handle +962 .upgrade() +963 .filter(|conn| conn.side().is_client()) +964 .and_then(|conn| conn.path(*path_id)) +965 { +966 trace!(?path_remote, ?conn_id, ?path_id, "closing direct path"); +967 match path.close() { +968 Err(quinn_proto::ClosePathError::LastOpenPath) => { +969 error!("could not close last open path"); +970 } +971 Err(quinn_proto::ClosePathError::ClosedPath) => { +972 // We already closed this. +973 } +974 Ok(_fut) => { +975 // We will handle the event in Self::handle_path_events. +976 } +977 } +978 } +979 } +980 } +981 } +982} +983 +984/// Returns `Some` if a new path should be selected, `None` if the `current_path` should +985/// continued to be used. +986fn select_best_path( +987 current_path: Option<(transports::Addr, Duration)>, +988 direct_path_ipv4: Option<(SocketAddrV4, Duration)>, +989 direct_path_ipv6: Option<(SocketAddrV6, Duration)>, +990 new_relay_path: Option<(transports::Addr, Duration)>, +991) -> Option<(transports::Addr, Duration)> { +992 // Determine the best new IP path. +993 let best_ip_path = match (direct_path_ipv4, direct_path_ipv6) { +994 (Some((addr_v4, rtt_v4)), Some((addr_v6, rtt_v6))) => { +995 Some(select_v4_v6(addr_v4, rtt_v4, addr_v6, rtt_v6)) +996 } +997 (None, Some((addr_v6, rtt_v6))) => Some((addr_v6.into(), rtt_v6)), +998 (Some((addr_v4, rtt_v4)), None) => Some((addr_v4.into(), rtt_v4)), +999 (None, None) => None, +1000 }; +1001 let best_ip_path = best_ip_path.map(|(addr, rtt)| (transports::Addr::Ip(addr), rtt)); +1002 +1003 match current_path { +1004 None => { +1005 // If we currently have no path +1006 if best_ip_path.is_some() { +1007 // Use the best IP path +1008 best_ip_path +1009 } else { +1010 // Use the new relay path +1011 new_relay_path +1012 } +1013 } +1014 Some((transports::Addr::Relay(..), _)) => { +1015 // If we have a current path, but it is relay +1016 if best_ip_path.is_some() { +1017 // Use the best IP path +1018 best_ip_path +1019 } else { +1020 // Use the new relay path +1021 new_relay_path +1022 } +1023 } +1024 Some((transports::Addr::Ip(_), current_rtt)) => { +1025 match &best_ip_path { +1026 Some((_, new_rtt)) => { +1027 // Comparing available IP paths +1028 if current_rtt >= *new_rtt + RTT_SWITCHING_MIN_IP { +1029 // New IP path is faster +1030 best_ip_path +1031 } else { +1032 // New IP is not faster +1033 None +1034 } +1035 } +1036 None => { +1037 // No new IP path, don't switch away +1038 None +1039 } +1040 } +1041 } +1042 } +1043} +1044 +1045/// Compare two IP addrs v4 & v6 and selects the "best" one. +1046/// +1047/// This prefers IPv6 paths over IPv4 paths. +1048fn select_v4_v6( +1049 addr_v4: SocketAddrV4, +1050 rtt_v4: Duration, +1051 addr_v6: SocketAddrV6, +1052 rtt_v6: Duration, +1053) -> (SocketAddr, Duration) { +1054 if rtt_v6 <= rtt_v4 + IPV6_RTT_ADVANTAGE { +1055 (addr_v6.into(), rtt_v6) +1056 } else { +1057 (addr_v4.into(), rtt_v4) +1058 } +1059} +1060 +1061fn send_datagram<'a>( +1062 sender: &'a mut TransportsSender, +1063 dst: transports::Addr, +1064 owned_transmit: OwnedTransmit, +1065) -> impl Future<Output = n0_error::Result<()>> + 'a { +1066 std::future::poll_fn(move |cx| { +1067 let transmit = transports::Transmit { +1068 ecn: owned_transmit.ecn, +1069 contents: owned_transmit.contents.as_ref(), +1070 segment_size: owned_transmit.segment_size, +1071 }; +1072 +1073 Pin::new(&mut *sender) +1074 .poll_send(cx, &dst, None, &transmit) +1075 .map(|res| res.with_context(|_| format!("failed to send datagram to {dst:?}"))) +1076 }) +1077} +1078 +1079/// Messages to send to the [`RemoteStateActor`]. +1080#[derive(derive_more::Debug)] +1081pub(crate) enum RemoteStateMessage { +1082 /// Sends a datagram to all known paths. +1083 /// +1084 /// Used to send QUIC Initial packets. If there is no working direct path this will +1085 /// trigger holepunching. +1086 /// +1087 /// This is not acceptable to use on the normal send path, as it is an async send +1088 /// operation with a bunch more copying. So it should only be used for sending QUIC +1089 /// Initial packets. +1090 #[debug("SendDatagram(..)")] +1091 SendDatagram(TransportsSender, OwnedTransmit), +1092 /// Adds an active connection to this remote endpoint. +1093 /// +1094 /// The connection will now be managed by this actor. Holepunching will happen when +1095 /// needed, any new paths discovered via holepunching will be added. And closed paths +1096 /// will be removed etc. +1097 #[debug("AddConnection(..)")] +1098 AddConnection(WeakConnectionHandle, oneshot::Sender<PathsWatcher>), +1099 /// Asks if there is any possible path that could be used. +1100 /// +1101 /// This adds the provided transport addresses to the list of potential paths for this remote +1102 /// and starts discovery if needed. +1103 /// +1104 /// Returns `Ok` immediately if the provided address list is non-empy or we have are other known paths. +1105 /// Otherwise returns `Ok` once discovery produces a result, or the discovery error if discovery fails +1106 /// or produces no results, +1107 #[debug("ResolveRemote(..)")] +1108 ResolveRemote( +1109 BTreeSet<TransportAddr>, +1110 oneshot::Sender<Result<(), DiscoveryError>>, +1111 ), +1112} +1113 +1114/// A handle to a [`RemoteStateActor`]. +1115/// +1116/// Dropping this will stop the actor. The actor will also stop after an idle timeout +1117/// if it has no connections, an empty inbox, and no other senders than the one stored +1118/// in the endpoint map exist. +1119#[derive(Debug)] +1120pub(super) struct RemoteStateHandle { +1121 /// Sender for the channel into the [`RemoteStateActor`]. +1122 /// +1123 /// This is a [`GuardedSender`], from which we can get a sender but only if the receiver +1124 /// hasn't been closed. +1125 pub(super) sender: GuardedSender<RemoteStateMessage>, +1126 _task: AbortOnDropHandle<()>, +1127} +1128 +1129/// Information about a holepunch attempt. +1130/// +1131/// Addresses are always stored in canonical form. +1132#[derive(Debug)] +1133struct HolepunchAttempt { +1134 when: Instant, +1135 /// The set of local addresses which could take part in holepunching. 1136 /// -1137 /// Like [`Self::local_candidates`] we may not have used them. -1138 remote_candidates: BTreeSet<SocketAddr>, -1139} -1140 -1141/// Newtype to track Connections. -1142/// -1143/// The wrapped value is the [`quinn::Connection::stable_id`] value, and is thus only valid -1144/// for active connections. -1145#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -1146struct ConnId(usize); -1147 -1148/// State about one connection. -1149#[derive(Debug)] -1150struct ConnectionState { -1151 /// Weak handle to the connection. -1152 handle: WeakConnectionHandle, -1153 /// The information we publish to users about the paths used in this connection. -1154 pub_open_paths: Watchable<PathAddrList>, -1155 /// The paths that exist on this connection. -1156 /// -1157 /// This could be in any state, e.g. while still validating the path or already closed -1158 /// but not yet fully removed from the connection. This exists as long as Quinn knows -1159 /// about the [`PathId`]. -1160 paths: FxHashMap<PathId, transports::Addr>, -1161 /// The open paths on this connection, a subset of [`Self::paths`]. -1162 open_paths: FxHashMap<PathId, transports::Addr>, -1163 /// Reverse map of [`Self::paths]. -1164 path_ids: FxHashMap<transports::Addr, PathId>, -1165} -1166 -1167impl ConnectionState { -1168 /// Tracks a path for the connection. -1169 fn add_path(&mut self, remote: transports::Addr, path_id: PathId) { -1170 self.paths.insert(path_id, remote.clone()); -1171 self.path_ids.insert(remote, path_id); -1172 } -1173 -1174 /// Tracks an open path for the connection. -1175 fn add_open_path(&mut self, remote: transports::Addr, path_id: PathId) { -1176 self.paths.insert(path_id, remote.clone()); -1177 self.open_paths.insert(path_id, remote.clone()); -1178 self.path_ids.insert(remote, path_id); -1179 self.update_pub_path_info(); -1180 } -1181 -1182 /// Completely removes a path from this connection. -1183 fn remove_path(&mut self, path_id: &PathId) -> Option<transports::Addr> { -1184 let addr = self.paths.remove(path_id); -1185 if let Some(ref addr) = addr { -1186 self.path_ids.remove(addr); -1187 } -1188 self.open_paths.remove(path_id); -1189 addr -1190 } -1191 -1192 /// Removes the path from the open paths. -1193 fn remove_open_path(&mut self, path_id: &PathId) { -1194 self.open_paths.remove(path_id); -1195 -1196 self.update_pub_path_info(); -1197 } -1198 -1199 /// Sets the new [`PathInfo`] structs for the public [`Connection`]. -1200 /// -1201 /// [`Connection`]: crate::endpoint::Connection -1202 fn update_pub_path_info(&self) { -1203 let new = self -1204 .open_paths -1205 .iter() -1206 .map(|(path_id, remote)| { -1207 let remote = TransportAddr::from(remote.clone()); -1208 (remote, *path_id) -1209 }) -1210 .collect::<PathAddrList>(); -1211 -1212 self.pub_open_paths.set(new).ok(); -1213 } -1214} -1215 -1216/// Watcher for the open paths and selected transmission path in a connection. -1217/// -1218/// This is stored in the [`Connection`], and the watchables are set from within the endpoint state actor. -1219/// -1220/// Internally, this contains a boxed-mapped-joined watcher over the open paths in the connection and the -1221/// selected path to the remote endpoint. The watcher is boxed because the mapped-joined watcher with -1222/// `SmallVec<PathInfoList>` has a size of over 800 bytes, which we don't want to put upon the [`Connection`]. -1223/// -1224/// [`Connection`]: crate::endpoint::Connection -1225#[derive(Clone, derive_more::Debug)] -1226#[debug("PathsWatcher")] -1227#[allow(clippy::type_complexity)] -1228pub(crate) struct PathsWatcher( -1229 Box< -1230 n0_watcher::Map< -1231 n0_watcher::Tuple< -1232 n0_watcher::Direct<PathAddrList>, -1233 n0_watcher::Direct<Option<transports::Addr>>, -1234 >, -1235 PathInfoList, -1236 >, -1237 >, -1238); -1239 -1240impl n0_watcher::Watcher for PathsWatcher { -1241 type Value = PathInfoList; -1242 -1243 fn update(&mut self) -> bool { -1244 self.0.update() -1245 } -1246 -1247 fn peek(&self) -> &Self::Value { -1248 self.0.peek() -1249 } -1250 -1251 fn is_connected(&self) -> bool { -1252 self.0.is_connected() -1253 } -1254 -1255 fn poll_updated( -1256 &mut self, -1257 cx: &mut std::task::Context<'_>, -1258 ) -> Poll<Result<(), n0_watcher::Disconnected>> { -1259 self.0.poll_updated(cx) -1260 } -1261} -1262 -1263impl PathsWatcher { -1264 fn new( -1265 open_paths: n0_watcher::Direct<PathAddrList>, -1266 selected_path: n0_watcher::Direct<Option<transports::Addr>>, -1267 conn_handle: WeakConnectionHandle, -1268 ) -> Self { -1269 Self(Box::new(open_paths.or(selected_path).map( -1270 move |(open_paths, selected_path)| { -1271 let selected_path: Option<TransportAddr> = selected_path.map(Into::into); -1272 let Some(conn) = conn_handle.upgrade() else { -1273 return PathInfoList(Default::default()); -1274 }; -1275 let list = open_paths -1276 .into_iter() -1277 .flat_map(move |(remote, path_id)| { -1278 PathInfo::new(path_id, &conn, remote, selected_path.as_ref()) -1279 }) -1280 .collect(); -1281 PathInfoList(list) -1282 }, -1283 ))) -1284 } -1285} -1286 -1287/// List of [`PathInfo`] for the network paths of a [`Connection`]. -1288/// -1289/// This struct implements [`IntoIterator`]. -1290/// -1291/// [`Connection`]: crate::endpoint::Connection -1292#[derive(derive_more::Debug, derive_more::IntoIterator, Eq, PartialEq, Clone)] -1293#[debug("{_0:?}")] -1294pub struct PathInfoList(SmallVec<[PathInfo; 4]>); +1137 /// This does not mean every address here participated in the holepunching. E.g. we +1138 /// could have tried only a sub-set of the addresses because a previous attempt already +1139 /// covered part of the range. +1140 /// +1141 /// We do not store this as a [`DirectAddr`] because this is checked for equality and we +1142 /// do not want to compare the sources of these addresses. +1143 local_candidates: BTreeSet<SocketAddr>, +1144 /// The set of remote addresses which could take part in holepunching. +1145 /// +1146 /// Like [`Self::local_candidates`] we may not have used them. +1147 remote_candidates: BTreeSet<SocketAddr>, +1148} +1149 +1150/// Newtype to track Connections. +1151/// +1152/// The wrapped value is the [`quinn::Connection::stable_id`] value, and is thus only valid +1153/// for active connections. +1154#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +1155struct ConnId(usize); +1156 +1157/// State about one connection. +1158#[derive(Debug)] +1159struct ConnectionState { +1160 /// Weak handle to the connection. +1161 handle: WeakConnectionHandle, +1162 /// The information we publish to users about the paths used in this connection. +1163 pub_open_paths: Watchable<PathAddrList>, +1164 /// The paths that exist on this connection. +1165 /// +1166 /// This could be in any state, e.g. while still validating the path or already closed +1167 /// but not yet fully removed from the connection. This exists as long as Quinn knows +1168 /// about the [`PathId`]. +1169 paths: FxHashMap<PathId, transports::Addr>, +1170 /// The open paths on this connection, a subset of [`Self::paths`]. +1171 open_paths: FxHashMap<PathId, transports::Addr>, +1172 /// Reverse map of [`Self::paths]. +1173 path_ids: FxHashMap<transports::Addr, PathId>, +1174} +1175 +1176impl ConnectionState { +1177 /// Tracks a path for the connection. +1178 fn add_path(&mut self, remote: transports::Addr, path_id: PathId) { +1179 self.paths.insert(path_id, remote.clone()); +1180 self.path_ids.insert(remote, path_id); +1181 } +1182 +1183 /// Tracks an open path for the connection. +1184 fn add_open_path(&mut self, remote: transports::Addr, path_id: PathId) { +1185 self.paths.insert(path_id, remote.clone()); +1186 self.open_paths.insert(path_id, remote.clone()); +1187 self.path_ids.insert(remote, path_id); +1188 self.update_pub_path_info(); +1189 } +1190 +1191 /// Completely removes a path from this connection. +1192 fn remove_path(&mut self, path_id: &PathId) -> Option<transports::Addr> { +1193 let addr = self.paths.remove(path_id); +1194 if let Some(ref addr) = addr { +1195 self.path_ids.remove(addr); +1196 } +1197 self.open_paths.remove(path_id); +1198 addr +1199 } +1200 +1201 /// Removes the path from the open paths. +1202 fn remove_open_path(&mut self, path_id: &PathId) { +1203 self.open_paths.remove(path_id); +1204 +1205 self.update_pub_path_info(); +1206 } +1207 +1208 /// Sets the new [`PathInfo`] structs for the public [`Connection`]. +1209 /// +1210 /// [`Connection`]: crate::endpoint::Connection +1211 fn update_pub_path_info(&self) { +1212 let new = self +1213 .open_paths +1214 .iter() +1215 .map(|(path_id, remote)| { +1216 let remote = TransportAddr::from(remote.clone()); +1217 (remote, *path_id) +1218 }) +1219 .collect::<PathAddrList>(); +1220 +1221 self.pub_open_paths.set(new).ok(); +1222 } +1223} +1224 +1225/// Watcher for the open paths and selected transmission path in a connection. +1226/// +1227/// This is stored in the [`Connection`], and the watchables are set from within the endpoint state actor. +1228/// +1229/// Internally, this contains a boxed-mapped-joined watcher over the open paths in the connection and the +1230/// selected path to the remote endpoint. The watcher is boxed because the mapped-joined watcher with +1231/// `SmallVec<PathInfoList>` has a size of over 800 bytes, which we don't want to put upon the [`Connection`]. +1232/// +1233/// [`Connection`]: crate::endpoint::Connection +1234#[derive(Clone, derive_more::Debug)] +1235#[debug("PathsWatcher")] +1236#[allow(clippy::type_complexity)] +1237pub(crate) struct PathsWatcher( +1238 Box< +1239 n0_watcher::Map< +1240 n0_watcher::Tuple< +1241 n0_watcher::Direct<PathAddrList>, +1242 n0_watcher::Direct<Option<transports::Addr>>, +1243 >, +1244 PathInfoList, +1245 >, +1246 >, +1247); +1248 +1249impl n0_watcher::Watcher for PathsWatcher { +1250 type Value = PathInfoList; +1251 +1252 fn update(&mut self) -> bool { +1253 self.0.update() +1254 } +1255 +1256 fn peek(&self) -> &Self::Value { +1257 self.0.peek() +1258 } +1259 +1260 fn is_connected(&self) -> bool { +1261 self.0.is_connected() +1262 } +1263 +1264 fn poll_updated( +1265 &mut self, +1266 cx: &mut std::task::Context<'_>, +1267 ) -> Poll<Result<(), n0_watcher::Disconnected>> { +1268 self.0.poll_updated(cx) +1269 } +1270} +1271 +1272impl PathsWatcher { +1273 fn new( +1274 open_paths: n0_watcher::Direct<PathAddrList>, +1275 selected_path: n0_watcher::Direct<Option<transports::Addr>>, +1276 conn_handle: WeakConnectionHandle, +1277 ) -> Self { +1278 Self(Box::new(open_paths.or(selected_path).map( +1279 move |(open_paths, selected_path)| { +1280 let selected_path: Option<TransportAddr> = selected_path.map(Into::into); +1281 let Some(conn) = conn_handle.upgrade() else { +1282 return PathInfoList(Default::default()); +1283 }; +1284 let list = open_paths +1285 .into_iter() +1286 .flat_map(move |(remote, path_id)| { +1287 PathInfo::new(path_id, &conn, remote, selected_path.as_ref()) +1288 }) +1289 .collect(); +1290 PathInfoList(list) +1291 }, +1292 ))) +1293 } +1294} 1295 -1296impl PathInfoList { -1297 /// Returns an iterator over the path infos. -1298 pub fn iter(&self) -> impl Iterator<Item = &PathInfo> { -1299 self.0.iter() -1300 } -1301 -1302 /// Returns `true` if the list is empty. -1303 pub fn is_empty(&self) -> bool { -1304 self.0.is_empty() -1305 } -1306 -1307 /// Returns the number of paths. -1308 pub fn len(&self) -> usize { -1309 self.0.len() -1310 } -1311} -1312 -1313/// Information about a network path used by a [`Connection`]. -1314/// -1315/// [`Connection`]: crate::endpoint::Connection -1316#[derive(derive_more::Debug, Clone)] -1317pub struct PathInfo { -1318 path_id: PathId, -1319 #[debug(skip)] -1320 handle: WeakConnectionHandle, -1321 stats: PathStats, -1322 remote: TransportAddr, -1323 is_selected: bool, -1324} -1325 -1326impl PartialEq for PathInfo { -1327 fn eq(&self, other: &Self) -> bool { -1328 self.path_id == other.path_id -1329 && self.remote == other.remote -1330 && self.is_selected == other.is_selected -1331 } -1332} -1333 -1334impl Eq for PathInfo {} -1335 -1336impl PathInfo { -1337 fn new( -1338 path_id: PathId, -1339 conn: &quinn::Connection, -1340 remote: TransportAddr, -1341 selected_path: Option<&TransportAddr>, -1342 ) -> Option<Self> { -1343 let stats = conn.path_stats(path_id)?; -1344 Some(Self { -1345 path_id, -1346 handle: conn.weak_handle(), -1347 is_selected: Some(&remote) == selected_path, -1348 remote, -1349 stats, -1350 }) -1351 } -1352 -1353 /// The remote transport address used by this network path. -1354 pub fn remote_addr(&self) -> &TransportAddr { -1355 &self.remote -1356 } -1357 -1358 /// Returns `true` if this path is currently the main transmission path for this [`Connection`]. -1359 /// -1360 /// [`Connection`]: crate::endpoint::Connection -1361 pub fn is_selected(&self) -> bool { -1362 self.is_selected -1363 } -1364 -1365 /// Whether this is an IP transport address. -1366 pub fn is_ip(&self) -> bool { -1367 self.remote.is_ip() -1368 } -1369 -1370 /// Whether this is a transport address via a relay server. -1371 pub fn is_relay(&self) -> bool { -1372 self.remote.is_relay() -1373 } -1374 -1375 /// Returns stats for this transmission path. -1376 pub fn stats(&self) -> PathStats { -1377 self.handle -1378 .upgrade() -1379 .and_then(|conn| conn.path_stats(self.path_id)) -1380 .unwrap_or(self.stats) -1381 } -1382 -1383 /// Current best estimate of this paths's latency (round-trip-time) -1384 pub fn rtt(&self) -> Duration { -1385 self.stats().rtt -1386 } -1387} -1388 -1389/// Poll a future once, like n0_future::future::poll_once but sync. -1390fn now_or_never<T, F: Future<Output = T>>(fut: F) -> Option<T> { -1391 let fut = std::pin::pin!(fut); -1392 match fut.poll(&mut std::task::Context::from_waker(std::task::Waker::noop())) { -1393 Poll::Ready(res) => Some(res), -1394 Poll::Pending => None, +1296/// List of [`PathInfo`] for the network paths of a [`Connection`]. +1297/// +1298/// This struct implements [`IntoIterator`]. +1299/// +1300/// [`Connection`]: crate::endpoint::Connection +1301#[derive(derive_more::Debug, derive_more::IntoIterator, Eq, PartialEq, Clone)] +1302#[debug("{_0:?}")] +1303pub struct PathInfoList(SmallVec<[PathInfo; 4]>); +1304 +1305impl PathInfoList { +1306 /// Returns an iterator over the path infos. +1307 pub fn iter(&self) -> impl Iterator<Item = &PathInfo> { +1308 self.0.iter() +1309 } +1310 +1311 /// Returns `true` if the list is empty. +1312 pub fn is_empty(&self) -> bool { +1313 self.0.is_empty() +1314 } +1315 +1316 /// Returns the number of paths. +1317 pub fn len(&self) -> usize { +1318 self.0.len() +1319 } +1320} +1321 +1322/// Information about a network path used by a [`Connection`]. +1323/// +1324/// [`Connection`]: crate::endpoint::Connection +1325#[derive(derive_more::Debug, Clone)] +1326pub struct PathInfo { +1327 path_id: PathId, +1328 #[debug(skip)] +1329 handle: WeakConnectionHandle, +1330 stats: PathStats, +1331 remote: TransportAddr, +1332 is_selected: bool, +1333} +1334 +1335impl PartialEq for PathInfo { +1336 fn eq(&self, other: &Self) -> bool { +1337 self.path_id == other.path_id +1338 && self.remote == other.remote +1339 && self.is_selected == other.is_selected +1340 } +1341} +1342 +1343impl Eq for PathInfo {} +1344 +1345impl PathInfo { +1346 fn new( +1347 path_id: PathId, +1348 conn: &quinn::Connection, +1349 remote: TransportAddr, +1350 selected_path: Option<&TransportAddr>, +1351 ) -> Option<Self> { +1352 let stats = conn.path_stats(path_id)?; +1353 Some(Self { +1354 path_id, +1355 handle: conn.weak_handle(), +1356 is_selected: Some(&remote) == selected_path, +1357 remote, +1358 stats, +1359 }) +1360 } +1361 +1362 /// The remote transport address used by this network path. +1363 pub fn remote_addr(&self) -> &TransportAddr { +1364 &self.remote +1365 } +1366 +1367 /// Returns `true` if this path is currently the main transmission path for this [`Connection`]. +1368 /// +1369 /// [`Connection`]: crate::endpoint::Connection +1370 pub fn is_selected(&self) -> bool { +1371 self.is_selected +1372 } +1373 +1374 /// Whether this is an IP transport address. +1375 pub fn is_ip(&self) -> bool { +1376 self.remote.is_ip() +1377 } +1378 +1379 /// Whether this is a transport address via a relay server. +1380 pub fn is_relay(&self) -> bool { +1381 self.remote.is_relay() +1382 } +1383 +1384 /// Returns stats for this transmission path. +1385 pub fn stats(&self) -> PathStats { +1386 self.handle +1387 .upgrade() +1388 .and_then(|conn| conn.path_stats(self.path_id)) +1389 .unwrap_or(self.stats) +1390 } +1391 +1392 /// Current best estimate of this paths's latency (round-trip-time) +1393 pub fn rtt(&self) -> Duration { +1394 self.stats().rtt 1395 } 1396} 1397 -1398/// Future that resolves to the `conn_id` once a connection is closed. -1399/// -1400/// This uses [`quinn::Connection::on_closed`], which does not keep the connection alive -1401/// while awaiting the future. -1402struct OnClosed { -1403 conn_id: ConnId, -1404 inner: quinn::OnClosed, +1398/// Poll a future once, like n0_future::future::poll_once but sync. +1399fn now_or_never<T, F: Future<Output = T>>(fut: F) -> Option<T> { +1400 let fut = std::pin::pin!(fut); +1401 match fut.poll(&mut std::task::Context::from_waker(std::task::Waker::noop())) { +1402 Poll::Ready(res) => Some(res), +1403 Poll::Pending => None, +1404 } 1405} 1406 -1407impl OnClosed { -1408 fn new(conn: &quinn::Connection) -> Self { -1409 Self { -1410 conn_id: ConnId(conn.stable_id()), -1411 inner: conn.on_closed(), -1412 } -1413 } +1407/// Future that resolves to the `conn_id` once a connection is closed. +1408/// +1409/// This uses [`quinn::Connection::on_closed`], which does not keep the connection alive +1410/// while awaiting the future. +1411struct OnClosed { +1412 conn_id: ConnId, +1413 inner: quinn::OnClosed, 1414} 1415 -1416impl Future for OnClosed { -1417 type Output = ConnId; -1418 -1419 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { -1420 let (_close_reason, _stats) = std::task::ready!(Pin::new(&mut self.inner).poll(cx)); -1421 Poll::Ready(self.conn_id) +1416impl OnClosed { +1417 fn new(conn: &quinn::Connection) -> Self { +1418 Self { +1419 conn_id: ConnId(conn.stable_id()), +1420 inner: conn.on_closed(), +1421 } 1422 } 1423} 1424 -1425/// Converts an iterator of [`TransportAddr'] into an iterator of [`transports::Addr`]. -1426fn to_transports_addr( -1427 endpoint_id: EndpointId, -1428 addrs: impl IntoIterator<Item = TransportAddr>, -1429) -> impl Iterator<Item = transports::Addr> { -1430 addrs.into_iter().filter_map(move |addr| match addr { -1431 TransportAddr::Relay(relay_url) => Some(transports::Addr::from((relay_url, endpoint_id))), -1432 TransportAddr::Ip(sockaddr) => Some(transports::Addr::from(sockaddr)), -1433 _ => { -1434 warn!(?addr, "Unsupported TransportAddr"); -1435 None -1436 } -1437 }) -1438} -1439 -1440#[cfg(test)] -1441mod tests { -1442 use std::net::{Ipv4Addr, Ipv6Addr}; -1443 -1444 use super::*; -1445 -1446 #[test] -1447 fn test_select_v4_v6_addr() { -1448 let v4 = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 1); -1449 let v6 = SocketAddrV6::new(Ipv6Addr::LOCALHOST, 1, 0, 0); -1450 -1451 // Same RTT, prefer v6 -1452 let (addr, rtt) = -1453 select_v4_v6(v4, Duration::from_millis(10), v6, Duration::from_millis(10)); -1454 assert_eq!(addr, v6.into()); -1455 assert_eq!(rtt, Duration::from_millis(10)); -1456 -1457 // v4 better -1458 let (addr, rtt) = select_v4_v6(v4, Duration::from_millis(1), v6, Duration::from_millis(10)); -1459 assert_eq!(addr, v4.into()); -1460 assert_eq!(rtt, Duration::from_millis(1)); -1461 -1462 // v6 better -1463 let (addr, rtt) = select_v4_v6(v4, Duration::from_millis(10), v6, Duration::from_millis(1)); -1464 assert_eq!(addr, v6.into()); -1465 assert_eq!(rtt, Duration::from_millis(1)); -1466 } -1467}

\ No newline at end of file +1425impl Future for OnClosed { +1426 type Output = ConnId; +1427 +1428 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { +1429 let (_close_reason, _stats) = std::task::ready!(Pin::new(&mut self.inner).poll(cx)); +1430 Poll::Ready(self.conn_id) +1431 } +1432} +1433 +1434/// Converts an iterator of [`TransportAddr'] into an iterator of [`transports::Addr`]. +1435fn to_transports_addr( +1436 endpoint_id: EndpointId, +1437 addrs: impl IntoIterator<Item = TransportAddr>, +1438) -> impl Iterator<Item = transports::Addr> { +1439 addrs.into_iter().filter_map(move |addr| match addr { +1440 TransportAddr::Relay(relay_url) => Some(transports::Addr::from((relay_url, endpoint_id))), +1441 TransportAddr::Ip(sockaddr) => Some(transports::Addr::from(sockaddr)), +1442 _ => { +1443 warn!(?addr, "Unsupported TransportAddr"); +1444 None +1445 } +1446 }) +1447} +1448 +1449#[cfg(test)] +1450mod tests { +1451 use std::net::{Ipv4Addr, Ipv6Addr}; +1452 +1453 use super::*; +1454 +1455 #[test] +1456 fn test_select_v4_v6_addr() { +1457 let v4 = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 1); +1458 let v6 = SocketAddrV6::new(Ipv6Addr::LOCALHOST, 1, 0, 0); +1459 +1460 // Same RTT, prefer v6 +1461 let (addr, rtt) = +1462 select_v4_v6(v4, Duration::from_millis(10), v6, Duration::from_millis(10)); +1463 assert_eq!(addr, v6.into()); +1464 assert_eq!(rtt, Duration::from_millis(10)); +1465 +1466 // v4 better +1467 let (addr, rtt) = select_v4_v6(v4, Duration::from_millis(1), v6, Duration::from_millis(10)); +1468 assert_eq!(addr, v4.into()); +1469 assert_eq!(rtt, Duration::from_millis(1)); +1470 +1471 // v6 better +1472 let (addr, rtt) = select_v4_v6(v4, Duration::from_millis(10), v6, Duration::from_millis(1)); +1473 assert_eq!(addr, v6.into()); +1474 assert_eq!(rtt, Duration::from_millis(1)); +1475 } +1476}
\ No newline at end of file