From e28bb4bd6cf0eab7de399ee81782cc8a60cbce52 Mon Sep 17 00:00:00 2001 From: flub Date: Sun, 23 Nov 2025 13:15:17 +0000 Subject: [PATCH] deploy: 8a0f87aa69b873aff00c550718fb544d7d5d2d5b --- .../docs/iroh/endpoint/struct.PathInfo.html | 18 +- .../iroh/endpoint/struct.PathInfoList.html | 14 +- .../magicsock/remote_map/remote_state.rs.html | 1280 +++++++++-------- 3 files changed, 657 insertions(+), 655 deletions(-) diff --git a/pr/3595/docs/iroh/endpoint/struct.PathInfo.html b/pr/3595/docs/iroh/endpoint/struct.PathInfo.html index 83fae6e659..b46c7b8f63 100644 --- a/pr/3595/docs/iroh/endpoint/struct.PathInfo.html +++ b/pr/3595/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/3595/docs/iroh/endpoint/struct.PathInfoList.html b/pr/3595/docs/iroh/endpoint/struct.PathInfoList.html index 2862d78f3a..ed59eae774 100644 --- a/pr/3595/docs/iroh/endpoint/struct.PathInfoList.html +++ b/pr/3595/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/3595/docs/src/iroh/magicsock/remote_map/remote_state.rs.html b/pr/3595/docs/src/iroh/magicsock/remote_map/remote_state.rs.html index 59e14554e8..fedc26d87b 100644 --- a/pr/3595/docs/src/iroh/magicsock/remote_map/remote_state.rs.html +++ b/pr/3595/docs/src/iroh/magicsock/remote_map/remote_state.rs.html @@ -704,645 +704,647 @@ 704 .iter() 705 .map(|addr| SocketAddr::new(addr.ip().to_canonical(), addr.port())) 706 .collect(); -707 trace!( -708 ?local_candidates, -709 ?remote_candidates, -710 "nat traversal initiated" -711 ); -712 self.last_holepunch = Some(HolepunchAttempt { -713 when: Instant::now(), -714 local_candidates, -715 remote_candidates, -716 }); -717 } -718 Err(err) => { -719 warn!("failed to initiate NAT traversal: {err:#}"); -720 } -721 } -722 } -723 -724 /// Open the path on all connections. -725 /// -726 /// This goes through all the connections for which we are the client, and makes sure -727 /// the path exists, or opens it. -728 #[instrument(level = "warn", skip(self))] -729 fn open_path(&mut self, open_addr: &transports::Addr) { -730 let path_status = match open_addr { -731 transports::Addr::Ip(_) => PathStatus::Available, -732 transports::Addr::Relay(_, _) => PathStatus::Backup, -733 }; -734 let quic_addr = match &open_addr { -735 transports::Addr::Ip(socket_addr) => *socket_addr, -736 transports::Addr::Relay(relay_url, eid) => self -737 .relay_mapped_addrs -738 .get(&(relay_url.clone(), *eid)) -739 .private_socket_addr(), -740 }; -741 -742 for (conn_id, conn_state) in self.connections.iter_mut() { -743 if conn_state.path_ids.contains_key(open_addr) { -744 continue; -745 } -746 let Some(conn) = conn_state.handle.upgrade() else { -747 continue; -748 }; -749 if conn.side().is_server() { -750 continue; -751 } -752 let fut = conn.open_path_ensure(quic_addr, path_status); -753 match fut.path_id() { -754 Some(path_id) => { -755 trace!(?conn_id, ?path_id, "opening new path"); -756 conn_state.add_path(open_addr.clone(), path_id); -757 } -758 None => { -759 let ret = now_or_never(fut); -760 match ret { -761 Some(Err(PathError::RemoteCidsExhausted)) => { -762 self.scheduled_open_path = -763 Some(Instant::now() + Duration::from_millis(333)); -764 self.pending_open_paths.push_back(open_addr.clone()); -765 trace!(?open_addr, "scheduling open_path"); -766 } -767 _ => warn!(?ret, "Opening path failed"), -768 } -769 } -770 } -771 } -772 } -773 -774 #[instrument(skip(self))] -775 fn handle_path_event( -776 &mut self, -777 conn_id: ConnId, -778 event: Result<PathEvent, BroadcastStreamRecvError>, -779 ) { -780 let Ok(event) = event else { -781 warn!("missed a PathEvent, RemoteStateActor lagging"); -782 // TODO: Is it possible to recover using the sync APIs to figure out what the -783 // state of the connection and it's paths are? -784 return; -785 }; -786 let Some(conn_state) = self.connections.get_mut(&conn_id) else { -787 trace!("event for removed connection"); -788 return; -789 }; -790 let Some(conn) = conn_state.handle.upgrade() else { -791 trace!("event for closed connection"); -792 return; -793 }; -794 trace!("path event"); -795 match event { -796 PathEvent::Opened { id: path_id } => { -797 let Some(path) = conn.path(path_id) else { -798 trace!("path open event for unknown path"); -799 return; -800 }; -801 // TODO: We configure this as defaults when we setup the endpoint, do we -802 // really need to duplicate this? -803 path.set_keep_alive_interval(Some(HEARTBEAT_INTERVAL)).ok(); -804 path.set_max_idle_timeout(Some(PATH_MAX_IDLE_TIMEOUT)).ok(); -805 -806 if let Ok(socketaddr) = path.remote_address() -807 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr) -808 { -809 event!( -810 target: "iroh::_events::path::open", -811 Level::DEBUG, -812 remote = %self.endpoint_id.fmt_short(), -813 ?path_remote, -814 ?conn_id, -815 ?path_id, -816 ); -817 conn_state.add_open_path(path_remote.clone(), path_id); -818 self.paths -819 .insert(path_remote, Source::Connection { _0: Private }); -820 } -821 -822 self.select_path(); -823 } -824 PathEvent::Abandoned { id, path_stats } => { -825 trace!(?path_stats, "path abandoned"); -826 // This is the last event for this path. -827 conn_state.remove_path(&id); -828 } -829 PathEvent::Closed { id, .. } | PathEvent::LocallyClosed { id, .. } => { -830 let Some(path_remote) = conn_state.paths.get(&id).cloned() else { -831 debug!("path not in path_id_map"); -832 return; -833 }; -834 event!( -835 target: "iroh::_events::path::closed", -836 Level::DEBUG, -837 remote = %self.endpoint_id.fmt_short(), -838 ?path_remote, -839 ?conn_id, -840 path_id = ?id, -841 ); -842 conn_state.remove_open_path(&id); -843 -844 // If one connection closes this path, close it on all connections. -845 for (conn_id, conn_state) in self.connections.iter_mut() { -846 let Some(path_id) = conn_state.path_ids.get(&path_remote) else { -847 continue; -848 }; -849 let Some(conn) = conn_state.handle.upgrade() else { -850 continue; -851 }; -852 if let Some(path) = conn.path(*path_id) { -853 trace!(?path_remote, ?conn_id, ?path_id, "closing path"); -854 if let Err(err) = path.close(APPLICATION_ABANDON_PATH.into()) { -855 trace!( -856 ?path_remote, -857 ?conn_id, -858 ?path_id, -859 "path close failed: {err:#}" -860 ); -861 } -862 } -863 } -864 } -865 PathEvent::RemoteStatus { .. } | PathEvent::ObservedAddr { .. } => { -866 // Nothing to do for these events. -867 } -868 } -869 } -870 -871 /// Selects the path with the lowest RTT, prefers direct paths. -872 /// -873 /// If there are direct paths, this selects the direct path with the lowest RTT. If -874 /// there are only relay paths, the relay path with the lowest RTT is chosen. -875 /// -876 /// The selected path is added to any connections which do not yet have it. Any unused -877 /// direct paths are closed for all connections. -878 #[instrument(skip_all)] -879 fn select_path(&mut self) { -880 // Find the lowest RTT across all connections for each open path. The long way, so -881 // we get to log *all* RTTs. -882 let mut all_path_rtts: FxHashMap<transports::Addr, Vec<Duration>> = FxHashMap::default(); -883 for conn_state in self.connections.values() { -884 let Some(conn) = conn_state.handle.upgrade() else { -885 continue; -886 }; -887 for (path_id, addr) in conn_state.open_paths.iter() { -888 if let Some(stats) = conn.path_stats(*path_id) { -889 all_path_rtts -890 .entry(addr.clone()) -891 .or_default() -892 .push(stats.rtt); -893 } -894 } -895 } -896 trace!(?all_path_rtts, "dumping all path RTTs"); -897 let path_rtts: FxHashMap<transports::Addr, Duration> = all_path_rtts -898 .into_iter() -899 .filter_map(|(addr, rtts)| rtts.into_iter().min().map(|rtt| (addr, rtt))) -900 .collect(); -901 -902 // Find the fastest direct or relay path. -903 const IPV6_RTT_ADVANTAGE: Duration = Duration::from_millis(3); -904 let direct_path = path_rtts -905 .iter() -906 .filter(|(addr, _rtt)| addr.is_ip()) -907 .map(|(addr, rtt)| { -908 if addr.is_ipv4() { -909 (*rtt + IPV6_RTT_ADVANTAGE, addr) -910 } else { -911 (*rtt, addr) -912 } -913 }) -914 .min(); -915 let selected_path = direct_path.or_else(|| { -916 // Find the fasted relay path. -917 path_rtts -918 .iter() -919 .filter(|(addr, _rtt)| addr.is_relay()) -920 .map(|(addr, rtt)| (*rtt, addr)) -921 .min() -922 }); -923 if let Some((rtt, addr)) = selected_path { -924 let prev = self.selected_path.set(Some(addr.clone())); -925 if prev.is_ok() { -926 debug!(?addr, ?rtt, ?prev, "selected new path"); -927 } -928 self.open_path(addr); -929 self.close_redundant_paths(addr); -930 } -931 } -932 -933 /// Closes any direct paths not selected. -934 /// -935 /// Makes sure not to close the last direct path. Relay paths are never closed -936 /// currently, because we only have one relay path at this time. -937 // TODO: Need to handle this on a timer as well probably. In .select_path() we open new -938 // paths and immediately call this. But the new paths are probably not yet open on -939 // all connections. -940 fn close_redundant_paths(&mut self, selected_path: &transports::Addr) { -941 debug_assert_eq!(self.selected_path.get().as_ref(), Some(selected_path),); -942 -943 for (conn_id, conn_state) in self.connections.iter() { -944 for (path_id, path_remote) in conn_state -945 .open_paths -946 .iter() -947 .filter(|(_, addr)| addr.is_ip()) -948 .filter(|(_, addr)| *addr != selected_path) -949 { -950 if conn_state.open_paths.values().filter(|a| a.is_ip()).count() <= 1 { -951 continue; // Do not close the last direct path. -952 } -953 if let Some(path) = conn_state -954 .handle -955 .upgrade() -956 .and_then(|conn| conn.path(*path_id)) -957 { -958 trace!(?path_remote, ?conn_id, ?path_id, "closing direct path"); -959 match path.close(APPLICATION_ABANDON_PATH.into()) { -960 Err(quinn_proto::ClosePathError::LastOpenPath) => { -961 error!("could not close last open path"); -962 } -963 Err(quinn_proto::ClosePathError::ClosedPath) => { -964 // We already closed this. -965 } -966 Ok(_fut) => { -967 // We will handle the event in Self::handle_path_events. -968 } -969 } -970 } -971 } -972 } -973 } -974} -975 -976/// Messages to send to the [`RemoteStateActor`]. -977#[derive(derive_more::Debug)] -978pub(crate) enum RemoteStateMessage { -979 /// Sends a datagram to all known paths. -980 /// -981 /// Used to send QUIC Initial packets. If there is no working direct path this will -982 /// trigger holepunching. -983 /// -984 /// This is not acceptable to use on the normal send path, as it is an async send -985 /// operation with a bunch more copying. So it should only be used for sending QUIC -986 /// Initial packets. -987 #[debug("SendDatagram(..)")] -988 SendDatagram(OwnedTransmit), -989 /// Adds an active connection to this remote endpoint. -990 /// -991 /// The connection will now be managed by this actor. Holepunching will happen when -992 /// needed, any new paths discovered via holepunching will be added. And closed paths -993 /// will be removed etc. -994 #[debug("AddConnection(..)")] -995 AddConnection(WeakConnectionHandle, oneshot::Sender<PathsWatcher>), -996 /// Asks if there is any possible path that could be used. -997 /// -998 /// This adds the provided transport addresses to the list of potential paths for this remote -999 /// and starts discovery if needed. -1000 /// -1001 /// Returns `Ok` immediately if the provided address list is non-empy or we have are other known paths. -1002 /// Otherwise returns `Ok` once discovery produces a result, or the discovery error if discovery fails -1003 /// or produces no results, -1004 #[debug("ResolveRemote(..)")] -1005 ResolveRemote( -1006 BTreeSet<TransportAddr>, -1007 oneshot::Sender<Result<(), DiscoveryError>>, -1008 ), -1009 /// Returns the current latency to the remote endpoint. -1010 /// -1011 /// TODO: This is more of a placeholder message currently. Check MagicSock::latency. -1012 #[debug("Latency(..)")] -1013 Latency(oneshot::Sender<Option<Duration>>), -1014} -1015 -1016/// A handle to a [`RemoteStateActor`]. -1017/// -1018/// Dropping this will stop the actor. The actor will also stop after an idle timeout -1019/// if it has no connections, an empty inbox, and no other senders than the one stored -1020/// in the endpoint map exist. -1021#[derive(Debug)] -1022pub(super) struct RemoteStateHandle { -1023 /// Sender for the channel into the [`RemoteStateActor`]. -1024 /// -1025 /// This is a [`GuardedSender`], from which we can get a sender but only if the receiver -1026 /// hasn't been closed. -1027 pub(super) sender: GuardedSender<RemoteStateMessage>, -1028 _task: AbortOnDropHandle<()>, -1029} -1030 -1031/// Information about a holepunch attempt. -1032/// -1033/// Addresses are always stored in canonical form. -1034#[derive(Debug)] -1035struct HolepunchAttempt { -1036 when: Instant, -1037 /// The set of local addresses which could take part in holepunching. -1038 /// -1039 /// This does not mean every address here participated in the holepunching. E.g. we -1040 /// could have tried only a sub-set of the addresses because a previous attempt already -1041 /// covered part of the range. -1042 /// -1043 /// We do not store this as a [`DirectAddr`] because this is checked for equality and we -1044 /// do not want to compare the sources of these addresses. -1045 local_candidates: BTreeSet<SocketAddr>, -1046 /// The set of remote addresses which could take part in holepunching. -1047 /// -1048 /// Like [`Self::local_candidates`] we may not have used them. -1049 remote_candidates: BTreeSet<SocketAddr>, -1050} -1051 -1052/// Newtype to track Connections. -1053/// -1054/// The wrapped value is the [`quinn::Connection::stable_id`] value, and is thus only valid -1055/// for active connections. -1056#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -1057struct ConnId(usize); -1058 -1059/// State about one connection. -1060#[derive(Debug)] -1061struct ConnectionState { -1062 /// Weak handle to the connection. -1063 handle: WeakConnectionHandle, -1064 /// The information we publish to users about the paths used in this connection. -1065 pub_open_paths: Watchable<PathAddrList>, -1066 /// The paths that exist on this connection. -1067 /// -1068 /// This could be in any state, e.g. while still validating the path or already closed -1069 /// but not yet fully removed from the connection. This exists as long as Quinn knows -1070 /// about the [`PathId`]. -1071 paths: FxHashMap<PathId, transports::Addr>, -1072 /// The open paths on this connection, a subset of [`Self::paths`]. -1073 open_paths: FxHashMap<PathId, transports::Addr>, -1074 /// Reverse map of [`Self::paths]. -1075 path_ids: FxHashMap<transports::Addr, PathId>, -1076} -1077 -1078impl ConnectionState { -1079 /// Tracks a path for the connection. -1080 fn add_path(&mut self, remote: transports::Addr, path_id: PathId) { -1081 self.paths.insert(path_id, remote.clone()); -1082 self.path_ids.insert(remote, path_id); -1083 } -1084 -1085 /// Tracks an open path for the connection. -1086 fn add_open_path(&mut self, remote: transports::Addr, path_id: PathId) { -1087 self.paths.insert(path_id, remote.clone()); -1088 self.open_paths.insert(path_id, remote.clone()); -1089 self.path_ids.insert(remote, path_id); -1090 -1091 self.update_pub_path_info(); -1092 } -1093 -1094 /// Completely removes a path from this connection. -1095 fn remove_path(&mut self, path_id: &PathId) { -1096 if let Some(addr) = self.paths.remove(path_id) { -1097 self.path_ids.remove(&addr); -1098 } -1099 self.open_paths.remove(path_id); -1100 } -1101 -1102 /// Removes the path from the open paths. -1103 fn remove_open_path(&mut self, path_id: &PathId) { -1104 self.open_paths.remove(path_id); -1105 -1106 self.update_pub_path_info(); -1107 } -1108 -1109 /// Sets the new [`PathInfo`] structs for the public [`Connection`]. -1110 /// -1111 /// [`Connection`]: crate::endpoint::Connection -1112 fn update_pub_path_info(&self) { -1113 let new = self -1114 .open_paths -1115 .iter() -1116 .map(|(path_id, remote)| { -1117 let remote = TransportAddr::from(remote.clone()); -1118 (remote, *path_id) -1119 }) -1120 .collect::<PathAddrList>(); -1121 -1122 self.pub_open_paths.set(new).ok(); -1123 } -1124} -1125 -1126/// Watcher for the open paths and selected transmission path in a connection. -1127/// -1128/// This is stored in the [`Connection`], and the watchables are set from within the endpoint state actor. +707 event!( +708 target: "iroh::_events::qnt::init", +709 Level::DEBUG, +710 remote = %self.endpoint_id.fmt_short(), +711 ?local_candidates, +712 ?remote_candidates, +713 ); +714 self.last_holepunch = Some(HolepunchAttempt { +715 when: Instant::now(), +716 local_candidates, +717 remote_candidates, +718 }); +719 } +720 Err(err) => { +721 warn!("failed to initiate NAT traversal: {err:#}"); +722 } +723 } +724 } +725 +726 /// Open the path on all connections. +727 /// +728 /// This goes through all the connections for which we are the client, and makes sure +729 /// the path exists, or opens it. +730 #[instrument(level = "warn", skip(self))] +731 fn open_path(&mut self, open_addr: &transports::Addr) { +732 let path_status = match open_addr { +733 transports::Addr::Ip(_) => PathStatus::Available, +734 transports::Addr::Relay(_, _) => PathStatus::Backup, +735 }; +736 let quic_addr = match &open_addr { +737 transports::Addr::Ip(socket_addr) => *socket_addr, +738 transports::Addr::Relay(relay_url, eid) => self +739 .relay_mapped_addrs +740 .get(&(relay_url.clone(), *eid)) +741 .private_socket_addr(), +742 }; +743 +744 for (conn_id, conn_state) in self.connections.iter_mut() { +745 if conn_state.path_ids.contains_key(open_addr) { +746 continue; +747 } +748 let Some(conn) = conn_state.handle.upgrade() else { +749 continue; +750 }; +751 if conn.side().is_server() { +752 continue; +753 } +754 let fut = conn.open_path_ensure(quic_addr, path_status); +755 match fut.path_id() { +756 Some(path_id) => { +757 trace!(?conn_id, ?path_id, "opening new path"); +758 conn_state.add_path(open_addr.clone(), path_id); +759 } +760 None => { +761 let ret = now_or_never(fut); +762 match ret { +763 Some(Err(PathError::RemoteCidsExhausted)) => { +764 self.scheduled_open_path = +765 Some(Instant::now() + Duration::from_millis(333)); +766 self.pending_open_paths.push_back(open_addr.clone()); +767 trace!(?open_addr, "scheduling open_path"); +768 } +769 _ => warn!(?ret, "Opening path failed"), +770 } +771 } +772 } +773 } +774 } +775 +776 #[instrument(skip(self))] +777 fn handle_path_event( +778 &mut self, +779 conn_id: ConnId, +780 event: Result<PathEvent, BroadcastStreamRecvError>, +781 ) { +782 let Ok(event) = event else { +783 warn!("missed a PathEvent, RemoteStateActor lagging"); +784 // TODO: Is it possible to recover using the sync APIs to figure out what the +785 // state of the connection and it's paths are? +786 return; +787 }; +788 let Some(conn_state) = self.connections.get_mut(&conn_id) else { +789 trace!("event for removed connection"); +790 return; +791 }; +792 let Some(conn) = conn_state.handle.upgrade() else { +793 trace!("event for closed connection"); +794 return; +795 }; +796 trace!("path event"); +797 match event { +798 PathEvent::Opened { id: path_id } => { +799 let Some(path) = conn.path(path_id) else { +800 trace!("path open event for unknown path"); +801 return; +802 }; +803 // TODO: We configure this as defaults when we setup the endpoint, do we +804 // really need to duplicate this? +805 path.set_keep_alive_interval(Some(HEARTBEAT_INTERVAL)).ok(); +806 path.set_max_idle_timeout(Some(PATH_MAX_IDLE_TIMEOUT)).ok(); +807 +808 if let Ok(socketaddr) = path.remote_address() +809 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr) +810 { +811 event!( +812 target: "iroh::_events::path::open", +813 Level::DEBUG, +814 remote = %self.endpoint_id.fmt_short(), +815 ?path_remote, +816 ?conn_id, +817 ?path_id, +818 ); +819 conn_state.add_open_path(path_remote.clone(), path_id); +820 self.paths +821 .insert(path_remote, Source::Connection { _0: Private }); +822 } +823 +824 self.select_path(); +825 } +826 PathEvent::Abandoned { id, path_stats } => { +827 trace!(?path_stats, "path abandoned"); +828 // This is the last event for this path. +829 conn_state.remove_path(&id); +830 } +831 PathEvent::Closed { id, .. } | PathEvent::LocallyClosed { id, .. } => { +832 let Some(path_remote) = conn_state.paths.get(&id).cloned() else { +833 debug!("path not in path_id_map"); +834 return; +835 }; +836 event!( +837 target: "iroh::_events::path::closed", +838 Level::DEBUG, +839 remote = %self.endpoint_id.fmt_short(), +840 ?path_remote, +841 ?conn_id, +842 path_id = ?id, +843 ); +844 conn_state.remove_open_path(&id); +845 +846 // If one connection closes this path, close it on all connections. +847 for (conn_id, conn_state) in self.connections.iter_mut() { +848 let Some(path_id) = conn_state.path_ids.get(&path_remote) else { +849 continue; +850 }; +851 let Some(conn) = conn_state.handle.upgrade() else { +852 continue; +853 }; +854 if let Some(path) = conn.path(*path_id) { +855 trace!(?path_remote, ?conn_id, ?path_id, "closing path"); +856 if let Err(err) = path.close(APPLICATION_ABANDON_PATH.into()) { +857 trace!( +858 ?path_remote, +859 ?conn_id, +860 ?path_id, +861 "path close failed: {err:#}" +862 ); +863 } +864 } +865 } +866 } +867 PathEvent::RemoteStatus { .. } | PathEvent::ObservedAddr { .. } => { +868 // Nothing to do for these events. +869 } +870 } +871 } +872 +873 /// Selects the path with the lowest RTT, prefers direct paths. +874 /// +875 /// If there are direct paths, this selects the direct path with the lowest RTT. If +876 /// there are only relay paths, the relay path with the lowest RTT is chosen. +877 /// +878 /// The selected path is added to any connections which do not yet have it. Any unused +879 /// direct paths are closed for all connections. +880 #[instrument(skip_all)] +881 fn select_path(&mut self) { +882 // Find the lowest RTT across all connections for each open path. The long way, so +883 // we get to log *all* RTTs. +884 let mut all_path_rtts: FxHashMap<transports::Addr, Vec<Duration>> = FxHashMap::default(); +885 for conn_state in self.connections.values() { +886 let Some(conn) = conn_state.handle.upgrade() else { +887 continue; +888 }; +889 for (path_id, addr) in conn_state.open_paths.iter() { +890 if let Some(stats) = conn.path_stats(*path_id) { +891 all_path_rtts +892 .entry(addr.clone()) +893 .or_default() +894 .push(stats.rtt); +895 } +896 } +897 } +898 trace!(?all_path_rtts, "dumping all path RTTs"); +899 let path_rtts: FxHashMap<transports::Addr, Duration> = all_path_rtts +900 .into_iter() +901 .filter_map(|(addr, rtts)| rtts.into_iter().min().map(|rtt| (addr, rtt))) +902 .collect(); +903 +904 // Find the fastest direct or relay path. +905 const IPV6_RTT_ADVANTAGE: Duration = Duration::from_millis(3); +906 let direct_path = path_rtts +907 .iter() +908 .filter(|(addr, _rtt)| addr.is_ip()) +909 .map(|(addr, rtt)| { +910 if addr.is_ipv4() { +911 (*rtt + IPV6_RTT_ADVANTAGE, addr) +912 } else { +913 (*rtt, addr) +914 } +915 }) +916 .min(); +917 let selected_path = direct_path.or_else(|| { +918 // Find the fasted relay path. +919 path_rtts +920 .iter() +921 .filter(|(addr, _rtt)| addr.is_relay()) +922 .map(|(addr, rtt)| (*rtt, addr)) +923 .min() +924 }); +925 if let Some((rtt, addr)) = selected_path { +926 let prev = self.selected_path.set(Some(addr.clone())); +927 if prev.is_ok() { +928 debug!(?addr, ?rtt, ?prev, "selected new path"); +929 } +930 self.open_path(addr); +931 self.close_redundant_paths(addr); +932 } +933 } +934 +935 /// Closes any direct paths not selected. +936 /// +937 /// Makes sure not to close the last direct path. Relay paths are never closed +938 /// currently, because we only have one relay path at this time. +939 // TODO: Need to handle this on a timer as well probably. In .select_path() we open new +940 // paths and immediately call this. But the new paths are probably not yet open on +941 // all connections. +942 fn close_redundant_paths(&mut self, selected_path: &transports::Addr) { +943 debug_assert_eq!(self.selected_path.get().as_ref(), Some(selected_path),); +944 +945 for (conn_id, conn_state) in self.connections.iter() { +946 for (path_id, path_remote) in conn_state +947 .open_paths +948 .iter() +949 .filter(|(_, addr)| addr.is_ip()) +950 .filter(|(_, addr)| *addr != selected_path) +951 { +952 if conn_state.open_paths.values().filter(|a| a.is_ip()).count() <= 1 { +953 continue; // Do not close the last direct path. +954 } +955 if let Some(path) = conn_state +956 .handle +957 .upgrade() +958 .and_then(|conn| conn.path(*path_id)) +959 { +960 trace!(?path_remote, ?conn_id, ?path_id, "closing direct path"); +961 match path.close(APPLICATION_ABANDON_PATH.into()) { +962 Err(quinn_proto::ClosePathError::LastOpenPath) => { +963 error!("could not close last open path"); +964 } +965 Err(quinn_proto::ClosePathError::ClosedPath) => { +966 // We already closed this. +967 } +968 Ok(_fut) => { +969 // We will handle the event in Self::handle_path_events. +970 } +971 } +972 } +973 } +974 } +975 } +976} +977 +978/// Messages to send to the [`RemoteStateActor`]. +979#[derive(derive_more::Debug)] +980pub(crate) enum RemoteStateMessage { +981 /// Sends a datagram to all known paths. +982 /// +983 /// Used to send QUIC Initial packets. If there is no working direct path this will +984 /// trigger holepunching. +985 /// +986 /// This is not acceptable to use on the normal send path, as it is an async send +987 /// operation with a bunch more copying. So it should only be used for sending QUIC +988 /// Initial packets. +989 #[debug("SendDatagram(..)")] +990 SendDatagram(OwnedTransmit), +991 /// Adds an active connection to this remote endpoint. +992 /// +993 /// The connection will now be managed by this actor. Holepunching will happen when +994 /// needed, any new paths discovered via holepunching will be added. And closed paths +995 /// will be removed etc. +996 #[debug("AddConnection(..)")] +997 AddConnection(WeakConnectionHandle, oneshot::Sender<PathsWatcher>), +998 /// Asks if there is any possible path that could be used. +999 /// +1000 /// This adds the provided transport addresses to the list of potential paths for this remote +1001 /// and starts discovery if needed. +1002 /// +1003 /// Returns `Ok` immediately if the provided address list is non-empy or we have are other known paths. +1004 /// Otherwise returns `Ok` once discovery produces a result, or the discovery error if discovery fails +1005 /// or produces no results, +1006 #[debug("ResolveRemote(..)")] +1007 ResolveRemote( +1008 BTreeSet<TransportAddr>, +1009 oneshot::Sender<Result<(), DiscoveryError>>, +1010 ), +1011 /// Returns the current latency to the remote endpoint. +1012 /// +1013 /// TODO: This is more of a placeholder message currently. Check MagicSock::latency. +1014 #[debug("Latency(..)")] +1015 Latency(oneshot::Sender<Option<Duration>>), +1016} +1017 +1018/// A handle to a [`RemoteStateActor`]. +1019/// +1020/// Dropping this will stop the actor. The actor will also stop after an idle timeout +1021/// if it has no connections, an empty inbox, and no other senders than the one stored +1022/// in the endpoint map exist. +1023#[derive(Debug)] +1024pub(super) struct RemoteStateHandle { +1025 /// Sender for the channel into the [`RemoteStateActor`]. +1026 /// +1027 /// This is a [`GuardedSender`], from which we can get a sender but only if the receiver +1028 /// hasn't been closed. +1029 pub(super) sender: GuardedSender<RemoteStateMessage>, +1030 _task: AbortOnDropHandle<()>, +1031} +1032 +1033/// Information about a holepunch attempt. +1034/// +1035/// Addresses are always stored in canonical form. +1036#[derive(Debug)] +1037struct HolepunchAttempt { +1038 when: Instant, +1039 /// The set of local addresses which could take part in holepunching. +1040 /// +1041 /// This does not mean every address here participated in the holepunching. E.g. we +1042 /// could have tried only a sub-set of the addresses because a previous attempt already +1043 /// covered part of the range. +1044 /// +1045 /// We do not store this as a [`DirectAddr`] because this is checked for equality and we +1046 /// do not want to compare the sources of these addresses. +1047 local_candidates: BTreeSet<SocketAddr>, +1048 /// The set of remote addresses which could take part in holepunching. +1049 /// +1050 /// Like [`Self::local_candidates`] we may not have used them. +1051 remote_candidates: BTreeSet<SocketAddr>, +1052} +1053 +1054/// Newtype to track Connections. +1055/// +1056/// The wrapped value is the [`quinn::Connection::stable_id`] value, and is thus only valid +1057/// for active connections. +1058#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +1059struct ConnId(usize); +1060 +1061/// State about one connection. +1062#[derive(Debug)] +1063struct ConnectionState { +1064 /// Weak handle to the connection. +1065 handle: WeakConnectionHandle, +1066 /// The information we publish to users about the paths used in this connection. +1067 pub_open_paths: Watchable<PathAddrList>, +1068 /// The paths that exist on this connection. +1069 /// +1070 /// This could be in any state, e.g. while still validating the path or already closed +1071 /// but not yet fully removed from the connection. This exists as long as Quinn knows +1072 /// about the [`PathId`]. +1073 paths: FxHashMap<PathId, transports::Addr>, +1074 /// The open paths on this connection, a subset of [`Self::paths`]. +1075 open_paths: FxHashMap<PathId, transports::Addr>, +1076 /// Reverse map of [`Self::paths]. +1077 path_ids: FxHashMap<transports::Addr, PathId>, +1078} +1079 +1080impl ConnectionState { +1081 /// Tracks a path for the connection. +1082 fn add_path(&mut self, remote: transports::Addr, path_id: PathId) { +1083 self.paths.insert(path_id, remote.clone()); +1084 self.path_ids.insert(remote, path_id); +1085 } +1086 +1087 /// Tracks an open path for the connection. +1088 fn add_open_path(&mut self, remote: transports::Addr, path_id: PathId) { +1089 self.paths.insert(path_id, remote.clone()); +1090 self.open_paths.insert(path_id, remote.clone()); +1091 self.path_ids.insert(remote, path_id); +1092 +1093 self.update_pub_path_info(); +1094 } +1095 +1096 /// Completely removes a path from this connection. +1097 fn remove_path(&mut self, path_id: &PathId) { +1098 if let Some(addr) = self.paths.remove(path_id) { +1099 self.path_ids.remove(&addr); +1100 } +1101 self.open_paths.remove(path_id); +1102 } +1103 +1104 /// Removes the path from the open paths. +1105 fn remove_open_path(&mut self, path_id: &PathId) { +1106 self.open_paths.remove(path_id); +1107 +1108 self.update_pub_path_info(); +1109 } +1110 +1111 /// Sets the new [`PathInfo`] structs for the public [`Connection`]. +1112 /// +1113 /// [`Connection`]: crate::endpoint::Connection +1114 fn update_pub_path_info(&self) { +1115 let new = self +1116 .open_paths +1117 .iter() +1118 .map(|(path_id, remote)| { +1119 let remote = TransportAddr::from(remote.clone()); +1120 (remote, *path_id) +1121 }) +1122 .collect::<PathAddrList>(); +1123 +1124 self.pub_open_paths.set(new).ok(); +1125 } +1126} +1127 +1128/// Watcher for the open paths and selected transmission path in a connection. 1129/// -1130/// Internally, this contains a boxed-mapped-joined watcher over the open paths in the connection and the -1131/// selected path to the remote endpoint. The watcher is boxed because the mapped-joined watcher with -1132/// `SmallVec<PathInfoList>` has a size of over 800 bytes, which we don't want to put upon the [`Connection`]. -1133/// -1134/// [`Connection`]: crate::endpoint::Connection -1135#[derive(Clone, derive_more::Debug)] -1136#[debug("PathsWatcher")] -1137#[allow(clippy::type_complexity)] -1138pub(crate) struct PathsWatcher( -1139 Box< -1140 n0_watcher::Map< -1141 n0_watcher::Tuple< -1142 n0_watcher::Direct<PathAddrList>, -1143 n0_watcher::Direct<Option<transports::Addr>>, -1144 >, -1145 PathInfoList, -1146 >, -1147 >, -1148); -1149 -1150impl n0_watcher::Watcher for PathsWatcher { -1151 type Value = PathInfoList; -1152 -1153 fn update(&mut self) -> bool { -1154 self.0.update() -1155 } -1156 -1157 fn peek(&self) -> &Self::Value { -1158 self.0.peek() -1159 } -1160 -1161 fn is_connected(&self) -> bool { -1162 self.0.is_connected() -1163 } -1164 -1165 fn poll_updated( -1166 &mut self, -1167 cx: &mut std::task::Context<'_>, -1168 ) -> Poll<Result<(), n0_watcher::Disconnected>> { -1169 self.0.poll_updated(cx) -1170 } -1171} -1172 -1173impl PathsWatcher { -1174 fn new( -1175 open_paths: n0_watcher::Direct<PathAddrList>, -1176 selected_path: n0_watcher::Direct<Option<transports::Addr>>, -1177 conn_handle: WeakConnectionHandle, -1178 ) -> Self { -1179 Self(Box::new(open_paths.or(selected_path).map( -1180 move |(open_paths, selected_path)| { -1181 let selected_path: Option<TransportAddr> = selected_path.map(Into::into); -1182 let Some(conn) = conn_handle.upgrade() else { -1183 return PathInfoList(Default::default()); -1184 }; -1185 let list = open_paths -1186 .into_iter() -1187 .flat_map(move |(remote, path_id)| { -1188 PathInfo::new(path_id, &conn, remote, selected_path.as_ref()) -1189 }) -1190 .collect(); -1191 PathInfoList(list) -1192 }, -1193 ))) -1194 } -1195} -1196 -1197/// List of [`PathInfo`] for the network paths of a [`Connection`]. -1198/// -1199/// This struct implements [`IntoIterator`]. +1130/// This is stored in the [`Connection`], and the watchables are set from within the endpoint state actor. +1131/// +1132/// Internally, this contains a boxed-mapped-joined watcher over the open paths in the connection and the +1133/// selected path to the remote endpoint. The watcher is boxed because the mapped-joined watcher with +1134/// `SmallVec<PathInfoList>` has a size of over 800 bytes, which we don't want to put upon the [`Connection`]. +1135/// +1136/// [`Connection`]: crate::endpoint::Connection +1137#[derive(Clone, derive_more::Debug)] +1138#[debug("PathsWatcher")] +1139#[allow(clippy::type_complexity)] +1140pub(crate) struct PathsWatcher( +1141 Box< +1142 n0_watcher::Map< +1143 n0_watcher::Tuple< +1144 n0_watcher::Direct<PathAddrList>, +1145 n0_watcher::Direct<Option<transports::Addr>>, +1146 >, +1147 PathInfoList, +1148 >, +1149 >, +1150); +1151 +1152impl n0_watcher::Watcher for PathsWatcher { +1153 type Value = PathInfoList; +1154 +1155 fn update(&mut self) -> bool { +1156 self.0.update() +1157 } +1158 +1159 fn peek(&self) -> &Self::Value { +1160 self.0.peek() +1161 } +1162 +1163 fn is_connected(&self) -> bool { +1164 self.0.is_connected() +1165 } +1166 +1167 fn poll_updated( +1168 &mut self, +1169 cx: &mut std::task::Context<'_>, +1170 ) -> Poll<Result<(), n0_watcher::Disconnected>> { +1171 self.0.poll_updated(cx) +1172 } +1173} +1174 +1175impl PathsWatcher { +1176 fn new( +1177 open_paths: n0_watcher::Direct<PathAddrList>, +1178 selected_path: n0_watcher::Direct<Option<transports::Addr>>, +1179 conn_handle: WeakConnectionHandle, +1180 ) -> Self { +1181 Self(Box::new(open_paths.or(selected_path).map( +1182 move |(open_paths, selected_path)| { +1183 let selected_path: Option<TransportAddr> = selected_path.map(Into::into); +1184 let Some(conn) = conn_handle.upgrade() else { +1185 return PathInfoList(Default::default()); +1186 }; +1187 let list = open_paths +1188 .into_iter() +1189 .flat_map(move |(remote, path_id)| { +1190 PathInfo::new(path_id, &conn, remote, selected_path.as_ref()) +1191 }) +1192 .collect(); +1193 PathInfoList(list) +1194 }, +1195 ))) +1196 } +1197} +1198 +1199/// List of [`PathInfo`] for the network paths of a [`Connection`]. 1200/// -1201/// [`Connection`]: crate::endpoint::Connection -1202#[derive(derive_more::Debug, derive_more::IntoIterator, Eq, PartialEq, Clone)] -1203#[debug("{_0:?}")] -1204pub struct PathInfoList(SmallVec<[PathInfo; 4]>); -1205 -1206impl PathInfoList { -1207 /// Returns an iterator over the path infos. -1208 pub fn iter(&self) -> impl Iterator<Item = &PathInfo> { -1209 self.0.iter() -1210 } -1211 -1212 /// Returns `true` if the list is empty. -1213 pub fn is_empty(&self) -> bool { -1214 self.0.is_empty() -1215 } -1216 -1217 /// Returns the number of paths. -1218 pub fn len(&self) -> usize { -1219 self.0.len() -1220 } -1221} -1222 -1223/// Information about a network path used by a [`Connection`]. -1224/// -1225/// [`Connection`]: crate::endpoint::Connection -1226#[derive(derive_more::Debug, Clone)] -1227pub struct PathInfo { -1228 path_id: PathId, -1229 #[debug(skip)] -1230 handle: WeakConnectionHandle, -1231 stats: PathStats, -1232 remote: TransportAddr, -1233 is_selected: bool, -1234} -1235 -1236impl PartialEq for PathInfo { -1237 fn eq(&self, other: &Self) -> bool { -1238 self.path_id == other.path_id -1239 && self.remote == other.remote -1240 && self.is_selected == other.is_selected -1241 } -1242} -1243 -1244impl Eq for PathInfo {} +1201/// This struct implements [`IntoIterator`]. +1202/// +1203/// [`Connection`]: crate::endpoint::Connection +1204#[derive(derive_more::Debug, derive_more::IntoIterator, Eq, PartialEq, Clone)] +1205#[debug("{_0:?}")] +1206pub struct PathInfoList(SmallVec<[PathInfo; 4]>); +1207 +1208impl PathInfoList { +1209 /// Returns an iterator over the path infos. +1210 pub fn iter(&self) -> impl Iterator<Item = &PathInfo> { +1211 self.0.iter() +1212 } +1213 +1214 /// Returns `true` if the list is empty. +1215 pub fn is_empty(&self) -> bool { +1216 self.0.is_empty() +1217 } +1218 +1219 /// Returns the number of paths. +1220 pub fn len(&self) -> usize { +1221 self.0.len() +1222 } +1223} +1224 +1225/// Information about a network path used by a [`Connection`]. +1226/// +1227/// [`Connection`]: crate::endpoint::Connection +1228#[derive(derive_more::Debug, Clone)] +1229pub struct PathInfo { +1230 path_id: PathId, +1231 #[debug(skip)] +1232 handle: WeakConnectionHandle, +1233 stats: PathStats, +1234 remote: TransportAddr, +1235 is_selected: bool, +1236} +1237 +1238impl PartialEq for PathInfo { +1239 fn eq(&self, other: &Self) -> bool { +1240 self.path_id == other.path_id +1241 && self.remote == other.remote +1242 && self.is_selected == other.is_selected +1243 } +1244} 1245 -1246impl PathInfo { -1247 fn new( -1248 path_id: PathId, -1249 conn: &quinn::Connection, -1250 remote: TransportAddr, -1251 selected_path: Option<&TransportAddr>, -1252 ) -> Option<Self> { -1253 let stats = conn.path_stats(path_id)?; -1254 Some(Self { -1255 path_id, -1256 handle: conn.weak_handle(), -1257 is_selected: Some(&remote) == selected_path, -1258 remote, -1259 stats, -1260 }) -1261 } -1262 -1263 /// The remote transport address used by this network path. -1264 pub fn remote_addr(&self) -> &TransportAddr { -1265 &self.remote -1266 } -1267 -1268 /// Returns `true` if this path is currently the main transmission path for this [`Connection`]. -1269 /// -1270 /// [`Connection`]: crate::endpoint::Connection -1271 pub fn is_selected(&self) -> bool { -1272 self.is_selected -1273 } -1274 -1275 /// Whether this is an IP transport address. -1276 pub fn is_ip(&self) -> bool { -1277 self.remote.is_ip() -1278 } -1279 -1280 /// Whether this is a transport address via a relay server. -1281 pub fn is_relay(&self) -> bool { -1282 self.remote.is_relay() -1283 } -1284 -1285 /// Returns stats for this transmission path. -1286 pub fn stats(&self) -> PathStats { -1287 self.handle -1288 .upgrade() -1289 .and_then(|conn| conn.path_stats(self.path_id)) -1290 .unwrap_or(self.stats) -1291 } -1292 -1293 /// Current best estimate of this paths's latency (round-trip-time) -1294 pub fn rtt(&self) -> Duration { -1295 self.stats().rtt -1296 } -1297} -1298 -1299/// Poll a future once, like n0_future::future::poll_once but sync. -1300fn now_or_never<T, F: Future<Output = T>>(fut: F) -> Option<T> { -1301 let fut = std::pin::pin!(fut); -1302 match fut.poll(&mut std::task::Context::from_waker(std::task::Waker::noop())) { -1303 Poll::Ready(res) => Some(res), -1304 Poll::Pending => None, -1305 } -1306} -1307 -1308/// Future that resolves to the `conn_id` once a connection is closed. -1309/// -1310/// This uses [`quinn::Connection::on_closed`], which does not keep the connection alive -1311/// while awaiting the future. -1312struct OnClosed { -1313 conn_id: ConnId, -1314 inner: quinn::OnClosed, -1315} -1316 -1317impl OnClosed { -1318 fn new(conn: &quinn::Connection) -> Self { -1319 Self { -1320 conn_id: ConnId(conn.stable_id()), -1321 inner: conn.on_closed(), -1322 } -1323 } -1324} -1325 -1326impl Future for OnClosed { -1327 type Output = ConnId; -1328 -1329 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { -1330 let (_close_reason, _stats) = std::task::ready!(Pin::new(&mut self.inner).poll(cx)); -1331 Poll::Ready(self.conn_id) -1332 } -1333} -1334 -1335/// Converts an iterator of [`TransportAddr'] into an iterator of [`transports::Addr`]. -1336fn to_transports_addr( -1337 endpoint_id: EndpointId, -1338 addrs: impl IntoIterator<Item = TransportAddr>, -1339) -> impl Iterator<Item = transports::Addr> { -1340 addrs.into_iter().filter_map(move |addr| match addr { -1341 TransportAddr::Relay(relay_url) => Some(transports::Addr::from((relay_url, endpoint_id))), -1342 TransportAddr::Ip(sockaddr) => Some(transports::Addr::from(sockaddr)), -1343 _ => { -1344 warn!(?addr, "Unsupported TransportAddr"); -1345 None -1346 } -1347 }) -1348}

\ No newline at end of file +1246impl Eq for PathInfo {} +1247 +1248impl PathInfo { +1249 fn new( +1250 path_id: PathId, +1251 conn: &quinn::Connection, +1252 remote: TransportAddr, +1253 selected_path: Option<&TransportAddr>, +1254 ) -> Option<Self> { +1255 let stats = conn.path_stats(path_id)?; +1256 Some(Self { +1257 path_id, +1258 handle: conn.weak_handle(), +1259 is_selected: Some(&remote) == selected_path, +1260 remote, +1261 stats, +1262 }) +1263 } +1264 +1265 /// The remote transport address used by this network path. +1266 pub fn remote_addr(&self) -> &TransportAddr { +1267 &self.remote +1268 } +1269 +1270 /// Returns `true` if this path is currently the main transmission path for this [`Connection`]. +1271 /// +1272 /// [`Connection`]: crate::endpoint::Connection +1273 pub fn is_selected(&self) -> bool { +1274 self.is_selected +1275 } +1276 +1277 /// Whether this is an IP transport address. +1278 pub fn is_ip(&self) -> bool { +1279 self.remote.is_ip() +1280 } +1281 +1282 /// Whether this is a transport address via a relay server. +1283 pub fn is_relay(&self) -> bool { +1284 self.remote.is_relay() +1285 } +1286 +1287 /// Returns stats for this transmission path. +1288 pub fn stats(&self) -> PathStats { +1289 self.handle +1290 .upgrade() +1291 .and_then(|conn| conn.path_stats(self.path_id)) +1292 .unwrap_or(self.stats) +1293 } +1294 +1295 /// Current best estimate of this paths's latency (round-trip-time) +1296 pub fn rtt(&self) -> Duration { +1297 self.stats().rtt +1298 } +1299} +1300 +1301/// Poll a future once, like n0_future::future::poll_once but sync. +1302fn now_or_never<T, F: Future<Output = T>>(fut: F) -> Option<T> { +1303 let fut = std::pin::pin!(fut); +1304 match fut.poll(&mut std::task::Context::from_waker(std::task::Waker::noop())) { +1305 Poll::Ready(res) => Some(res), +1306 Poll::Pending => None, +1307 } +1308} +1309 +1310/// Future that resolves to the `conn_id` once a connection is closed. +1311/// +1312/// This uses [`quinn::Connection::on_closed`], which does not keep the connection alive +1313/// while awaiting the future. +1314struct OnClosed { +1315 conn_id: ConnId, +1316 inner: quinn::OnClosed, +1317} +1318 +1319impl OnClosed { +1320 fn new(conn: &quinn::Connection) -> Self { +1321 Self { +1322 conn_id: ConnId(conn.stable_id()), +1323 inner: conn.on_closed(), +1324 } +1325 } +1326} +1327 +1328impl Future for OnClosed { +1329 type Output = ConnId; +1330 +1331 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { +1332 let (_close_reason, _stats) = std::task::ready!(Pin::new(&mut self.inner).poll(cx)); +1333 Poll::Ready(self.conn_id) +1334 } +1335} +1336 +1337/// Converts an iterator of [`TransportAddr'] into an iterator of [`transports::Addr`]. +1338fn to_transports_addr( +1339 endpoint_id: EndpointId, +1340 addrs: impl IntoIterator<Item = TransportAddr>, +1341) -> impl Iterator<Item = transports::Addr> { +1342 addrs.into_iter().filter_map(move |addr| match addr { +1343 TransportAddr::Relay(relay_url) => Some(transports::Addr::from((relay_url, endpoint_id))), +1344 TransportAddr::Ip(sockaddr) => Some(transports::Addr::from(sockaddr)), +1345 _ => { +1346 warn!(?addr, "Unsupported TransportAddr"); +1347 None +1348 } +1349 }) +1350}
\ No newline at end of file