pub struct PathInfo { /* private fields */ }Expand description
Information about a network path used by a Connection.
Implementations§
Source§impl PathInfo
impl PathInfo
Sourcepub fn remote_addr(&self) -> &TransportAddr
pub fn remote_addr(&self) -> &TransportAddr
The remote transport address used by this network path.
-Sourcepub fn is_selected(&self) -> bool
pub fn is_selected(&self) -> bool
Returns true if this path is currently the main transmission path for this Connection.
Trait Implementations§
impl Eq for PathInfo
Auto Trait Implementations§
impl Freeze for PathInfo
impl RefUnwindSafe for PathInfo
impl Send for PathInfo
impl Sync for PathInfo
impl Unpin for PathInfo
impl UnwindSafe for PathInfo
Blanket Implementations§
Source§impl<T> Any for Twhere
+PathInfo in iroh::endpoint - Rust PathInfo
pub struct PathInfo { /* private fields */ }
Expand description
Information about a network path used by a Connection.
+Implementations§
Source§impl PathInfo
Sourcepub fn remote_addr(&self) -> &TransportAddr
The remote transport address used by this network path.
+Sourcepub fn is_selected(&self) -> bool
Returns true if this path is currently the main transmission path for this Connection.
+Trait Implementations§
Source§impl Eq for PathInfo
Auto Trait Implementations§
§impl Freeze for PathInfo
§impl RefUnwindSafe for PathInfo
§impl Send for PathInfo
§impl Sync for PathInfo
§impl Unpin for PathInfo
§impl UnwindSafe for PathInfo
Blanket Implementations§
§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
§fn implicit(
diff --git a/pr/3645/docs/iroh/endpoint/struct.PathInfoList.html b/pr/3645/docs/iroh/endpoint/struct.PathInfoList.html
index 330e5c6ae1..404a8509cb 100644
--- a/pr/3645/docs/iroh/endpoint/struct.PathInfoList.html
+++ b/pr/3645/docs/iroh/endpoint/struct.PathInfoList.html
@@ -1,11 +1,11 @@
-PathInfoList in iroh::endpoint - Rust PathInfoList
pub struct PathInfoList(/* private fields */);
Expand description
List of PathInfo for the network paths of a Connection.
+PathInfoList in iroh::endpoint - Rust PathInfoList
pub struct PathInfoList(/* private fields */);
Expand description
List of PathInfo for the network paths of a Connection.
This struct implements IntoIterator.
-Implementations§
Trait Implementations§
Source§impl Clone for PathInfoList
Source§fn clone(&self) -> PathInfoList
Returns a duplicate of the value. Read more1.0.0 · Source§fn clone_from(&mut self, source: &Self)
Performs copy-assignment from source. Read moreSource§impl Debug for PathInfoList
Source§impl IntoIterator for PathInfoList
Source§impl PartialEq for PathInfoList
Source§impl Eq for PathInfoList
Source§impl StructuralPartialEq for PathInfoList
Auto Trait Implementations§
§impl Freeze for PathInfoList
§impl RefUnwindSafe for PathInfoList
§impl Send for PathInfoList
§impl Sync for PathInfoList
§impl Unpin for PathInfoList
§impl UnwindSafe for PathInfoList
Blanket Implementations§
Implementations§
Trait Implementations§
Source§impl Clone for PathInfoList
Source§fn clone(&self) -> PathInfoList
Returns a duplicate of the value. Read more1.0.0 · Source§fn clone_from(&mut self, source: &Self)
Performs copy-assignment from source. Read moreSource§impl Debug for PathInfoList
Source§impl IntoIterator for PathInfoList
Source§impl PartialEq for PathInfoList
Source§impl Eq for PathInfoList
Source§impl StructuralPartialEq for PathInfoList
Auto Trait Implementations§
§impl Freeze for PathInfoList
§impl RefUnwindSafe for PathInfoList
§impl Send for PathInfoList
§impl Sync for PathInfoList
§impl Unpin for PathInfoList
§impl UnwindSafe for PathInfoList
Blanket Implementations§
§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
§fn implicit(
diff --git a/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state.rs.html b/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state.rs.html
index 383b3f0cc2..cd0545f907 100644
--- a/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state.rs.html
+++ b/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state.rs.html
@@ -729,712 +729,709 @@
729 let Some(relay_addr) = self
730 .paths
731 .addrs()
-732 .filter_map(|addr| match addr {
-733 transports::Addr::Ip(_) => None,
-734 transports::Addr::Relay(_, _) => Some(addr),
-735 })
-736 .next()
-737 .cloned()
-738 else {
-739 warn!("holepunching requested but have no relay address");
-740 return;
-741 };
-742 let remote_addrs = self.remote_hp_addrs();
-743
-744 // Send DISCO Ping messages to all CallMeMaybe-advertised paths.
-745 for dst in remote_addrs.iter() {
-746 let msg = disco::Ping::new(self.local_endpoint_id);
-747 event!(
-748 target: "iroh::_events::ping::sent",
-749 Level::DEBUG,
-750 remote = %self.endpoint_id.fmt_short(),
-751 ?dst,
-752 txn = ?msg.tx_id,
-753 );
-754 let addr = transports::Addr::Ip(*dst);
-755 self.paths.disco_ping_sent(addr.clone(), msg.tx_id);
-756 self.send_disco_message(addr, disco::Message::Ping(msg))
-757 .await;
-758 }
-759
-760 // Send the DISCO CallMeMaybe message over the relay.
-761 let my_numbers: Vec<SocketAddr> = self
-762 .local_addrs
-763 .get()
-764 .iter()
-765 .map(|daddr| daddr.addr)
-766 .collect();
-767 let local_addrs: BTreeSet<SocketAddr> = my_numbers.iter().copied().collect();
-768 let msg = disco::CallMeMaybe { my_numbers };
-769 event!(
-770 target: "iroh::_events::call_me_maybe::sent",
-771 Level::DEBUG,
-772 remote = %self.endpoint_id.fmt_short(),
-773 dst = ?relay_addr,
-774 my_numbers = ?msg.my_numbers,
-775 );
-776 self.send_disco_message(relay_addr, disco::Message::CallMeMaybe(msg))
-777 .await;
-778
-779 self.last_holepunch = Some(HolepunchAttempt {
-780 when: Instant::now(),
-781 local_addrs,
-782 remote_addrs,
-783 });
-784 }
-785
-786 /// Sends a DISCO message to the remote endpoint this actor manages.
-787 #[instrument(skip(self), fields(remote = %self.endpoint_id.fmt_short()))]
-788 async fn send_disco_message(&self, dst: transports::Addr, msg: disco::Message) {
-789 let pkt = self.disco.encode_and_seal(self.endpoint_id, &msg);
-790 let transmit = transports::OwnedTransmit {
-791 ecn: None,
-792 contents: pkt,
-793 segment_size: None,
-794 };
-795 let counter = match dst {
-796 transports::Addr::Ip(_) => &self.metrics.send_disco_udp,
-797 transports::Addr::Relay(_, _) => &self.metrics.send_disco_relay,
-798 };
-799 match self.send_datagram(dst, transmit).await {
-800 Ok(()) => {
-801 trace!("sent");
-802 counter.inc();
+732 .filter(|addr| addr.is_relay())
+733 .next()
+734 .cloned()
+735 else {
+736 warn!("holepunching requested but have no relay address");
+737 return;
+738 };
+739 let remote_addrs = self.remote_hp_addrs();
+740
+741 // Send DISCO Ping messages to all CallMeMaybe-advertised paths.
+742 for dst in remote_addrs.iter() {
+743 let msg = disco::Ping::new(self.local_endpoint_id);
+744 event!(
+745 target: "iroh::_events::ping::sent",
+746 Level::DEBUG,
+747 remote = %self.endpoint_id.fmt_short(),
+748 ?dst,
+749 txn = ?msg.tx_id,
+750 );
+751 let addr = transports::Addr::Ip(*dst);
+752 self.paths.disco_ping_sent(addr.clone(), msg.tx_id);
+753 self.send_disco_message(addr, disco::Message::Ping(msg))
+754 .await;
+755 }
+756
+757 // Send the DISCO CallMeMaybe message over the relay.
+758 let my_numbers: Vec<SocketAddr> = self
+759 .local_addrs
+760 .get()
+761 .iter()
+762 .map(|daddr| daddr.addr)
+763 .collect();
+764 let local_addrs: BTreeSet<SocketAddr> = my_numbers.iter().copied().collect();
+765 let msg = disco::CallMeMaybe { my_numbers };
+766 event!(
+767 target: "iroh::_events::call_me_maybe::sent",
+768 Level::DEBUG,
+769 remote = %self.endpoint_id.fmt_short(),
+770 dst = ?relay_addr,
+771 my_numbers = ?msg.my_numbers,
+772 );
+773 self.send_disco_message(relay_addr, disco::Message::CallMeMaybe(msg))
+774 .await;
+775
+776 self.last_holepunch = Some(HolepunchAttempt {
+777 when: Instant::now(),
+778 local_addrs,
+779 remote_addrs,
+780 });
+781 }
+782
+783 /// Sends a DISCO message to the remote endpoint this actor manages.
+784 #[instrument(skip(self), fields(remote = %self.endpoint_id.fmt_short()))]
+785 async fn send_disco_message(&self, dst: transports::Addr, msg: disco::Message) {
+786 let pkt = self.disco.encode_and_seal(self.endpoint_id, &msg);
+787 let transmit = transports::OwnedTransmit {
+788 ecn: None,
+789 contents: pkt,
+790 segment_size: None,
+791 };
+792 let counter = match dst {
+793 transports::Addr::Ip(_) => &self.metrics.send_disco_udp,
+794 transports::Addr::Relay(_, _) => &self.metrics.send_disco_relay,
+795 };
+796 match self.send_datagram(dst, transmit).await {
+797 Ok(()) => {
+798 trace!("sent");
+799 counter.inc();
+800 }
+801 Err(err) => {
+802 warn!("failed to send disco message: {err:#}");
803 }
-804 Err(err) => {
-805 warn!("failed to send disco message: {err:#}");
-806 }
-807 }
-808 }
-809
-810 /// Open the path on all connections.
-811 ///
-812 /// This goes through all the connections for which we are the client, and makes sure
-813 /// the path exists, or opens it.
-814 #[instrument(level = "warn", skip(self))]
-815 fn open_path(&mut self, open_addr: &transports::Addr) {
-816 let path_status = match open_addr {
-817 transports::Addr::Ip(_) => PathStatus::Available,
-818 transports::Addr::Relay(_, _) => PathStatus::Backup,
-819 };
-820 let quic_addr = match &open_addr {
-821 transports::Addr::Ip(socket_addr) => *socket_addr,
-822 transports::Addr::Relay(relay_url, eid) => self
-823 .relay_mapped_addrs
-824 .get(&(relay_url.clone(), *eid))
-825 .private_socket_addr(),
-826 };
-827
-828 for (conn_id, conn_state) in self.connections.iter_mut() {
-829 if conn_state.path_ids.contains_key(open_addr) {
+804 }
+805 }
+806
+807 /// Open the path on all connections.
+808 ///
+809 /// This goes through all the connections for which we are the client, and makes sure
+810 /// the path exists, or opens it.
+811 #[instrument(level = "warn", skip(self))]
+812 fn open_path(&mut self, open_addr: &transports::Addr) {
+813 let path_status = match open_addr {
+814 transports::Addr::Ip(_) => PathStatus::Available,
+815 transports::Addr::Relay(_, _) => PathStatus::Backup,
+816 };
+817 let quic_addr = match &open_addr {
+818 transports::Addr::Ip(socket_addr) => *socket_addr,
+819 transports::Addr::Relay(relay_url, eid) => self
+820 .relay_mapped_addrs
+821 .get(&(relay_url.clone(), *eid))
+822 .private_socket_addr(),
+823 };
+824
+825 for (conn_id, conn_state) in self.connections.iter_mut() {
+826 if conn_state.path_ids.contains_key(open_addr) {
+827 continue;
+828 }
+829 let Some(conn) = conn_state.handle.upgrade() else {
830 continue;
-831 }
-832 let Some(conn) = conn_state.handle.upgrade() else {
+831 };
+832 if conn.side().is_server() {
833 continue;
-834 };
-835 if conn.side().is_server() {
-836 continue;
-837 }
-838 let fut = conn.open_path_ensure(quic_addr, path_status);
-839 match fut.path_id() {
-840 Some(path_id) => {
-841 trace!(?conn_id, ?path_id, "opening new path");
-842 conn_state.add_path(open_addr.clone(), path_id);
-843 }
-844 None => {
-845 let ret = now_or_never(fut);
-846 match ret {
-847 Some(Err(PathError::RemoteCidsExhausted)) => {
-848 self.scheduled_open_path =
-849 Some(Instant::now() + Duration::from_millis(333));
-850 self.pending_open_paths.push_back(open_addr.clone());
-851 trace!(?open_addr, "scheduling open_path");
-852 }
-853 _ => warn!(?ret, "Opening path failed"),
-854 }
-855 }
-856 }
-857 }
-858 }
-859
-860 #[instrument(skip(self))]
-861 fn handle_path_event(
-862 &mut self,
-863 conn_id: ConnId,
-864 event: Result<PathEvent, BroadcastStreamRecvError>,
-865 ) {
-866 let Ok(event) = event else {
-867 warn!("missed a PathEvent, EndpointStateActor lagging");
-868 // TODO: Is it possible to recover using the sync APIs to figure out what the
-869 // state of the connection and it's paths are?
-870 return;
-871 };
-872 let Some(conn_state) = self.connections.get_mut(&conn_id) else {
-873 trace!("event for removed connection");
-874 return;
-875 };
-876 let Some(conn) = conn_state.handle.upgrade() else {
-877 trace!("event for closed connection");
-878 return;
-879 };
-880 trace!("path event");
-881 match event {
-882 PathEvent::Opened { id: path_id } => {
-883 let Some(path) = conn.path(path_id) else {
-884 trace!("path open event for unknown path");
-885 return;
-886 };
-887 // TODO: We configure this as defaults when we setup the endpoint, do we
-888 // really need to duplicate this?
-889 path.set_keep_alive_interval(Some(HEARTBEAT_INTERVAL)).ok();
-890 path.set_max_idle_timeout(Some(PATH_MAX_IDLE_TIMEOUT)).ok();
-891
-892 if let Ok(socketaddr) = path.remote_address()
-893 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr)
-894 {
-895 event!(
-896 target: "iroh::_events::path::open",
-897 Level::DEBUG,
-898 remote = %self.endpoint_id.fmt_short(),
-899 ?path_remote,
-900 ?conn_id,
-901 ?path_id,
-902 );
-903 conn_state.add_open_path(path_remote.clone(), path_id);
-904 self.paths
-905 .insert(path_remote, Source::Connection { _0: Private });
-906 }
-907
-908 self.select_path();
-909 }
-910 PathEvent::Abandoned { id, path_stats } => {
-911 trace!(?path_stats, "path abandoned");
-912 // This is the last event for this path.
-913 conn_state.remove_path(&id);
-914 }
-915 PathEvent::Closed { id, .. } | PathEvent::LocallyClosed { id, .. } => {
-916 let Some(path_remote) = conn_state.paths.get(&id).cloned() else {
-917 debug!("path not in path_id_map");
-918 return;
-919 };
-920 event!(
-921 target: "iroh::_events::path::closed",
-922 Level::DEBUG,
-923 remote = %self.endpoint_id.fmt_short(),
-924 ?path_remote,
-925 ?conn_id,
-926 path_id = ?id,
-927 );
-928 conn_state.remove_open_path(&id);
-929
-930 // If one connection closes this path, close it on all connections.
-931 for (conn_id, conn_state) in self.connections.iter_mut() {
-932 let Some(path_id) = conn_state.path_ids.get(&path_remote) else {
+834 }
+835 let fut = conn.open_path_ensure(quic_addr, path_status);
+836 match fut.path_id() {
+837 Some(path_id) => {
+838 trace!(?conn_id, ?path_id, "opening new path");
+839 conn_state.add_path(open_addr.clone(), path_id);
+840 }
+841 None => {
+842 let ret = now_or_never(fut);
+843 match ret {
+844 Some(Err(PathError::RemoteCidsExhausted)) => {
+845 self.scheduled_open_path =
+846 Some(Instant::now() + Duration::from_millis(333));
+847 self.pending_open_paths.push_back(open_addr.clone());
+848 trace!(?open_addr, "scheduling open_path");
+849 }
+850 _ => warn!(?ret, "Opening path failed"),
+851 }
+852 }
+853 }
+854 }
+855 }
+856
+857 #[instrument(skip(self))]
+858 fn handle_path_event(
+859 &mut self,
+860 conn_id: ConnId,
+861 event: Result<PathEvent, BroadcastStreamRecvError>,
+862 ) {
+863 let Ok(event) = event else {
+864 warn!("missed a PathEvent, EndpointStateActor lagging");
+865 // TODO: Is it possible to recover using the sync APIs to figure out what the
+866 // state of the connection and it's paths are?
+867 return;
+868 };
+869 let Some(conn_state) = self.connections.get_mut(&conn_id) else {
+870 trace!("event for removed connection");
+871 return;
+872 };
+873 let Some(conn) = conn_state.handle.upgrade() else {
+874 trace!("event for closed connection");
+875 return;
+876 };
+877 trace!("path event");
+878 match event {
+879 PathEvent::Opened { id: path_id } => {
+880 let Some(path) = conn.path(path_id) else {
+881 trace!("path open event for unknown path");
+882 return;
+883 };
+884 // TODO: We configure this as defaults when we setup the endpoint, do we
+885 // really need to duplicate this?
+886 path.set_keep_alive_interval(Some(HEARTBEAT_INTERVAL)).ok();
+887 path.set_max_idle_timeout(Some(PATH_MAX_IDLE_TIMEOUT)).ok();
+888
+889 if let Ok(socketaddr) = path.remote_address()
+890 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr)
+891 {
+892 event!(
+893 target: "iroh::_events::path::open",
+894 Level::DEBUG,
+895 remote = %self.endpoint_id.fmt_short(),
+896 ?path_remote,
+897 ?conn_id,
+898 ?path_id,
+899 );
+900 conn_state.add_open_path(path_remote.clone(), path_id);
+901 self.paths
+902 .insert(path_remote, Source::Connection { _0: Private });
+903 }
+904
+905 self.select_path();
+906 }
+907 PathEvent::Abandoned { id, path_stats } => {
+908 trace!(?path_stats, "path abandoned");
+909 // This is the last event for this path.
+910 conn_state.remove_path(&id);
+911 }
+912 PathEvent::Closed { id, .. } | PathEvent::LocallyClosed { id, .. } => {
+913 let Some(path_remote) = conn_state.paths.get(&id).cloned() else {
+914 debug!("path not in path_id_map");
+915 return;
+916 };
+917 event!(
+918 target: "iroh::_events::path::closed",
+919 Level::DEBUG,
+920 remote = %self.endpoint_id.fmt_short(),
+921 ?path_remote,
+922 ?conn_id,
+923 path_id = ?id,
+924 );
+925 conn_state.remove_open_path(&id);
+926
+927 // If one connection closes this path, close it on all connections.
+928 for (conn_id, conn_state) in self.connections.iter_mut() {
+929 let Some(path_id) = conn_state.path_ids.get(&path_remote) else {
+930 continue;
+931 };
+932 let Some(conn) = conn_state.handle.upgrade() else {
933 continue;
934 };
-935 let Some(conn) = conn_state.handle.upgrade() else {
-936 continue;
-937 };
-938 if let Some(path) = conn.path(*path_id) {
-939 trace!(?path_remote, ?conn_id, ?path_id, "closing path");
-940 if let Err(err) = path.close(APPLICATION_ABANDON_PATH.into()) {
-941 trace!(
-942 ?path_remote,
-943 ?conn_id,
-944 ?path_id,
-945 "path close failed: {err:#}"
-946 );
-947 }
-948 }
-949 }
-950 }
-951 PathEvent::RemoteStatus { .. } | PathEvent::ObservedAddr { .. } => {
-952 // Nothing to do for these events.
-953 }
-954 }
-955 }
-956
-957 /// Selects the path with the lowest RTT, prefers direct paths.
+935 if let Some(path) = conn.path(*path_id) {
+936 trace!(?path_remote, ?conn_id, ?path_id, "closing path");
+937 if let Err(err) = path.close(APPLICATION_ABANDON_PATH.into()) {
+938 trace!(
+939 ?path_remote,
+940 ?conn_id,
+941 ?path_id,
+942 "path close failed: {err:#}"
+943 );
+944 }
+945 }
+946 }
+947 }
+948 PathEvent::RemoteStatus { .. } | PathEvent::ObservedAddr { .. } => {
+949 // Nothing to do for these events.
+950 }
+951 }
+952 }
+953
+954 /// Selects the path with the lowest RTT, prefers direct paths.
+955 ///
+956 /// If there are direct paths, this selects the direct path with the lowest RTT. If
+957 /// there are only relay paths, the relay path with the lowest RTT is chosen.
958 ///
-959 /// If there are direct paths, this selects the direct path with the lowest RTT. If
-960 /// there are only relay paths, the relay path with the lowest RTT is chosen.
-961 ///
-962 /// The selected path is added to any connections which do not yet have it. Any unused
-963 /// direct paths are closed for all connections.
-964 #[instrument(skip_all)]
-965 fn select_path(&mut self) {
-966 // Find the lowest RTT across all connections for each open path. The long way, so
-967 // we get to log *all* RTTs.
-968 let mut all_path_rtts: FxHashMap<transports::Addr, Vec<Duration>> = FxHashMap::default();
-969 for conn_state in self.connections.values() {
-970 let Some(conn) = conn_state.handle.upgrade() else {
-971 continue;
-972 };
-973 for (path_id, addr) in conn_state.open_paths.iter() {
-974 if let Some(stats) = conn.path_stats(*path_id) {
-975 all_path_rtts
-976 .entry(addr.clone())
-977 .or_default()
-978 .push(stats.rtt);
-979 }
-980 }
-981 }
-982 trace!(?all_path_rtts, "dumping all path RTTs");
-983 let path_rtts: FxHashMap<transports::Addr, Duration> = all_path_rtts
-984 .into_iter()
-985 .filter_map(|(addr, rtts)| rtts.into_iter().min().map(|rtt| (addr, rtt)))
-986 .collect();
-987
-988 // Find the fastest direct or relay path.
-989 const IPV6_RTT_ADVANTAGE: Duration = Duration::from_millis(3);
-990 let direct_path = path_rtts
-991 .iter()
-992 .filter(|(addr, _rtt)| addr.is_ip())
-993 .map(|(addr, rtt)| {
-994 if addr.is_ipv4() {
-995 (*rtt + IPV6_RTT_ADVANTAGE, addr)
-996 } else {
-997 (*rtt, addr)
-998 }
-999 })
-1000 .min();
-1001 let selected_path = direct_path.or_else(|| {
-1002 // Find the fasted relay path.
-1003 path_rtts
-1004 .iter()
-1005 .filter(|(addr, _rtt)| addr.is_relay())
-1006 .map(|(addr, rtt)| (*rtt, addr))
-1007 .min()
-1008 });
-1009 if let Some((rtt, addr)) = selected_path {
-1010 let prev = self.selected_path.set(Some(addr.clone()));
-1011 if prev.is_ok() {
-1012 debug!(?addr, ?rtt, ?prev, "selected new path");
-1013 }
-1014 self.open_path(addr);
-1015 self.close_redundant_paths(addr);
-1016 }
-1017 }
-1018
-1019 /// Closes any direct paths not selected.
-1020 ///
-1021 /// Makes sure not to close the last direct path. Relay paths are never closed
-1022 /// currently, because we only have one relay path at this time.
-1023 // TODO: Need to handle this on a timer as well probably. In .select_path() we open new
-1024 // paths and immediately call this. But the new paths are probably not yet open on
-1025 // all connections.
-1026 fn close_redundant_paths(&mut self, selected_path: &transports::Addr) {
-1027 debug_assert_eq!(self.selected_path.get().as_ref(), Some(selected_path),);
-1028
-1029 for (conn_id, conn_state) in self.connections.iter() {
-1030 for (path_id, path_remote) in conn_state
-1031 .open_paths
-1032 .iter()
-1033 .filter(|(_, addr)| addr.is_ip())
-1034 .filter(|(_, addr)| *addr != selected_path)
-1035 {
-1036 if conn_state.open_paths.values().filter(|a| a.is_ip()).count() <= 1 {
-1037 continue; // Do not close the last direct path.
-1038 }
-1039 if let Some(path) = conn_state
-1040 .handle
-1041 .upgrade()
-1042 .and_then(|conn| conn.path(*path_id))
-1043 {
-1044 trace!(?path_remote, ?conn_id, ?path_id, "closing direct path");
-1045 match path.close(APPLICATION_ABANDON_PATH.into()) {
-1046 Err(quinn_proto::ClosePathError::LastOpenPath) => {
-1047 error!("could not close last open path");
-1048 }
-1049 Err(quinn_proto::ClosePathError::ClosedPath) => {
-1050 // We already closed this.
+959 /// The selected path is added to any connections which do not yet have it. Any unused
+960 /// direct paths are closed for all connections.
+961 #[instrument(skip_all)]
+962 fn select_path(&mut self) {
+963 // Find the lowest RTT across all connections for each open path. The long way, so
+964 // we get to log *all* RTTs.
+965 let mut all_path_rtts: FxHashMap<transports::Addr, Vec<Duration>> = FxHashMap::default();
+966 for conn_state in self.connections.values() {
+967 let Some(conn) = conn_state.handle.upgrade() else {
+968 continue;
+969 };
+970 for (path_id, addr) in conn_state.open_paths.iter() {
+971 if let Some(stats) = conn.path_stats(*path_id) {
+972 all_path_rtts
+973 .entry(addr.clone())
+974 .or_default()
+975 .push(stats.rtt);
+976 }
+977 }
+978 }
+979 trace!(?all_path_rtts, "dumping all path RTTs");
+980 let path_rtts: FxHashMap<transports::Addr, Duration> = all_path_rtts
+981 .into_iter()
+982 .filter_map(|(addr, rtts)| rtts.into_iter().min().map(|rtt| (addr, rtt)))
+983 .collect();
+984
+985 // Find the fastest direct or relay path.
+986 const IPV6_RTT_ADVANTAGE: Duration = Duration::from_millis(3);
+987 let direct_path = path_rtts
+988 .iter()
+989 .filter(|(addr, _rtt)| addr.is_ip())
+990 .map(|(addr, rtt)| {
+991 if addr.is_ipv4() {
+992 (*rtt + IPV6_RTT_ADVANTAGE, addr)
+993 } else {
+994 (*rtt, addr)
+995 }
+996 })
+997 .min();
+998 let selected_path = direct_path.or_else(|| {
+999 // Find the fasted relay path.
+1000 path_rtts
+1001 .iter()
+1002 .filter(|(addr, _rtt)| addr.is_relay())
+1003 .map(|(addr, rtt)| (*rtt, addr))
+1004 .min()
+1005 });
+1006 if let Some((rtt, addr)) = selected_path {
+1007 let prev = self.selected_path.set(Some(addr.clone()));
+1008 if prev.is_ok() {
+1009 debug!(?addr, ?rtt, ?prev, "selected new path");
+1010 }
+1011 self.open_path(addr);
+1012 self.close_redundant_paths(addr);
+1013 }
+1014 }
+1015
+1016 /// Closes any direct paths not selected.
+1017 ///
+1018 /// Makes sure not to close the last direct path. Relay paths are never closed
+1019 /// currently, because we only have one relay path at this time.
+1020 // TODO: Need to handle this on a timer as well probably. In .select_path() we open new
+1021 // paths and immediately call this. But the new paths are probably not yet open on
+1022 // all connections.
+1023 fn close_redundant_paths(&mut self, selected_path: &transports::Addr) {
+1024 debug_assert_eq!(self.selected_path.get().as_ref(), Some(selected_path),);
+1025
+1026 for (conn_id, conn_state) in self.connections.iter() {
+1027 for (path_id, path_remote) in conn_state
+1028 .open_paths
+1029 .iter()
+1030 .filter(|(_, addr)| addr.is_ip())
+1031 .filter(|(_, addr)| *addr != selected_path)
+1032 {
+1033 if conn_state.open_paths.values().filter(|a| a.is_ip()).count() <= 1 {
+1034 continue; // Do not close the last direct path.
+1035 }
+1036 if let Some(path) = conn_state
+1037 .handle
+1038 .upgrade()
+1039 .and_then(|conn| conn.path(*path_id))
+1040 {
+1041 trace!(?path_remote, ?conn_id, ?path_id, "closing direct path");
+1042 match path.close(APPLICATION_ABANDON_PATH.into()) {
+1043 Err(quinn_proto::ClosePathError::LastOpenPath) => {
+1044 error!("could not close last open path");
+1045 }
+1046 Err(quinn_proto::ClosePathError::ClosedPath) => {
+1047 // We already closed this.
+1048 }
+1049 Ok(_fut) => {
+1050 // We will handle the event in Self::handle_path_events.
1051 }
-1052 Ok(_fut) => {
-1053 // We will handle the event in Self::handle_path_events.
-1054 }
-1055 }
-1056 }
-1057 }
-1058 }
-1059 }
-1060}
-1061
-1062/// Messages to send to the [`EndpointStateActor`].
-1063#[derive(derive_more::Debug)]
-1064pub(crate) enum EndpointStateMessage {
-1065 /// Sends a datagram to all known paths.
+1052 }
+1053 }
+1054 }
+1055 }
+1056 }
+1057}
+1058
+1059/// Messages to send to the [`EndpointStateActor`].
+1060#[derive(derive_more::Debug)]
+1061pub(crate) enum EndpointStateMessage {
+1062 /// Sends a datagram to all known paths.
+1063 ///
+1064 /// Used to send QUIC Initial packets. If there is no working direct path this will
+1065 /// trigger holepunching.
1066 ///
-1067 /// Used to send QUIC Initial packets. If there is no working direct path this will
-1068 /// trigger holepunching.
-1069 ///
-1070 /// This is not acceptable to use on the normal send path, as it is an async send
-1071 /// operation with a bunch more copying. So it should only be used for sending QUIC
-1072 /// Initial packets.
-1073 #[debug("SendDatagram(..)")]
-1074 SendDatagram(OwnedTransmit),
-1075 /// Adds an active connection to this remote endpoint.
-1076 ///
-1077 /// The connection will now be managed by this actor. Holepunching will happen when
-1078 /// needed, any new paths discovered via holepunching will be added. And closed paths
-1079 /// will be removed etc.
-1080 #[debug("AddConnection(..)")]
-1081 AddConnection(WeakConnectionHandle, oneshot::Sender<PathsWatcher>),
-1082 /// Process a received DISCO CallMeMaybe message.
-1083 CallMeMaybeReceived(disco::CallMeMaybe),
-1084 /// Process a received DISCO Ping message.
-1085 #[debug("PingReceived({:?}, src: {_1:?})", _0.tx_id)]
-1086 PingReceived(disco::Ping, transports::Addr),
-1087 /// Process a received DISCO Pong message.
-1088 #[debug("PongReceived({:?}, src: {_1:?})", _0.tx_id)]
-1089 PongReceived(disco::Pong, transports::Addr),
-1090 /// Ensure we have at least one transport address for a remote.
+1067 /// This is not acceptable to use on the normal send path, as it is an async send
+1068 /// operation with a bunch more copying. So it should only be used for sending QUIC
+1069 /// Initial packets.
+1070 #[debug("SendDatagram(..)")]
+1071 SendDatagram(OwnedTransmit),
+1072 /// Adds an active connection to this remote endpoint.
+1073 ///
+1074 /// The connection will now be managed by this actor. Holepunching will happen when
+1075 /// needed, any new paths discovered via holepunching will be added. And closed paths
+1076 /// will be removed etc.
+1077 #[debug("AddConnection(..)")]
+1078 AddConnection(WeakConnectionHandle, oneshot::Sender<PathsWatcher>),
+1079 /// Process a received DISCO CallMeMaybe message.
+1080 CallMeMaybeReceived(disco::CallMeMaybe),
+1081 /// Process a received DISCO Ping message.
+1082 #[debug("PingReceived({:?}, src: {_1:?})", _0.tx_id)]
+1083 PingReceived(disco::Ping, transports::Addr),
+1084 /// Process a received DISCO Pong message.
+1085 #[debug("PongReceived({:?}, src: {_1:?})", _0.tx_id)]
+1086 PongReceived(disco::Pong, transports::Addr),
+1087 /// Ensure we have at least one transport address for a remote.
+1088 ///
+1089 /// This adds the provided transport addresses to the list of potential paths for this remote
+1090 /// and starts discovery if needed.
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 /// Returns the current latency to the remote endpoint.
-1104 ///
-1105 /// TODO: This is more of a placeholder message currently. Check MagicSock::latency.
-1106 #[debug("Latency(..)")]
-1107 Latency(oneshot::Sender<Option<Duration>>),
-1108}
-1109
-1110/// A handle to a [`EndpointStateActor`].
-1111///
-1112/// Dropping this will stop the actor. The actor will also stop after an idle timeout
-1113/// if it has no connections, an empty inbox, and no other senders than the one stored
-1114/// in the endpoint map exist.
-1115#[derive(Debug)]
-1116pub(super) struct EndpointStateHandle {
-1117 /// Sender for the channel into the [`EndpointStateActor`].
-1118 ///
-1119 /// This is a [`GuardedSender`], from which we can get a sender but only if the receiver
-1120 /// hasn't been closed.
-1121 pub(super) sender: GuardedSender<EndpointStateMessage>,
-1122 _task: AbortOnDropHandle<()>,
-1123}
-1124
-1125/// Information about a holepunch attempt.
-1126#[derive(Debug)]
-1127struct HolepunchAttempt {
-1128 when: Instant,
-1129 /// The set of local addresses which could take part in holepunching.
-1130 ///
-1131 /// This does not mean every address here participated in the holepunching. E.g. we
-1132 /// could have tried only a sub-set of the addresses because a previous attempt already
-1133 /// covered part of the range.
-1134 ///
-1135 /// We do not store this as a [`DirectAddr`] because this is checked for equality and we
-1136 /// do not want to compare the sources of these addresses.
-1137 local_addrs: BTreeSet<SocketAddr>,
-1138 /// The set of remote addresses which could take part in holepunching.
-1139 ///
-1140 /// Like `local_addrs` we may not have used them.
-1141 remote_addrs: BTreeSet<SocketAddr>,
-1142}
-1143
-1144/// Newtype to track Connections.
-1145///
-1146/// The wrapped value is the [`quinn::Connection::stable_id`] value, and is thus only valid
-1147/// for active connections.
-1148#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
-1149struct ConnId(usize);
-1150
-1151/// State about one connection.
-1152#[derive(Debug)]
-1153struct ConnectionState {
-1154 /// Weak handle to the connection.
-1155 handle: WeakConnectionHandle,
-1156 /// The information we publish to users about the paths used in this connection.
-1157 pub_open_paths: Watchable<PathAddrList>,
-1158 /// The paths that exist on this connection.
-1159 ///
-1160 /// This could be in any state, e.g. while still validating the path or already closed
-1161 /// but not yet fully removed from the connection. This exists as long as Quinn knows
-1162 /// about the [`PathId`].
-1163 paths: FxHashMap<PathId, transports::Addr>,
-1164 /// The open paths on this connection, a subset of [`Self::paths`].
-1165 open_paths: FxHashMap<PathId, transports::Addr>,
-1166 /// Reverse map of [`Self::paths].
-1167 path_ids: FxHashMap<transports::Addr, PathId>,
-1168}
-1169
-1170impl ConnectionState {
-1171 /// Tracks a path for the connection.
-1172 fn add_path(&mut self, remote: transports::Addr, path_id: PathId) {
-1173 self.paths.insert(path_id, remote.clone());
-1174 self.path_ids.insert(remote, path_id);
-1175 }
-1176
-1177 /// Tracks an open path for the connection.
-1178 fn add_open_path(&mut self, remote: transports::Addr, path_id: PathId) {
-1179 self.paths.insert(path_id, remote.clone());
-1180 self.open_paths.insert(path_id, remote.clone());
-1181 self.path_ids.insert(remote, path_id);
+1092 /// Returns `Ok` immediately if the provided address list is non-empy or we have are other known paths.
+1093 /// Otherwise returns `Ok` once discovery produces a result, or the discovery error if discovery fails
+1094 /// or produces no results,
+1095 #[debug("ResolveRemote(..)")]
+1096 ResolveRemote(
+1097 BTreeSet<TransportAddr>,
+1098 oneshot::Sender<Result<(), DiscoveryError>>,
+1099 ),
+1100 /// Returns the current latency to the remote endpoint.
+1101 ///
+1102 /// TODO: This is more of a placeholder message currently. Check MagicSock::latency.
+1103 #[debug("Latency(..)")]
+1104 Latency(oneshot::Sender<Option<Duration>>),
+1105}
+1106
+1107/// A handle to a [`EndpointStateActor`].
+1108///
+1109/// Dropping this will stop the actor. The actor will also stop after an idle timeout
+1110/// if it has no connections, an empty inbox, and no other senders than the one stored
+1111/// in the endpoint map exist.
+1112#[derive(Debug)]
+1113pub(super) struct EndpointStateHandle {
+1114 /// Sender for the channel into the [`EndpointStateActor`].
+1115 ///
+1116 /// This is a [`GuardedSender`], from which we can get a sender but only if the receiver
+1117 /// hasn't been closed.
+1118 pub(super) sender: GuardedSender<EndpointStateMessage>,
+1119 _task: AbortOnDropHandle<()>,
+1120}
+1121
+1122/// Information about a holepunch attempt.
+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_addrs: BTreeSet<SocketAddr>,
+1135 /// The set of remote addresses which could take part in holepunching.
+1136 ///
+1137 /// Like `local_addrs` we may not have used them.
+1138 remote_addrs: 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, 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
+1180 self.update_pub_path_info();
+1181 }
1182
-1183 self.update_pub_path_info();
-1184 }
-1185
-1186 /// Completely removes a path from this connection.
-1187 fn remove_path(&mut self, path_id: &PathId) {
-1188 if let Some(addr) = self.paths.remove(path_id) {
-1189 self.path_ids.remove(&addr);
-1190 }
-1191 self.open_paths.remove(path_id);
-1192 }
-1193
-1194 /// Removes the path from the open paths.
-1195 fn remove_open_path(&mut self, path_id: &PathId) {
-1196 self.open_paths.remove(path_id);
+1183 /// Completely removes a path from this connection.
+1184 fn remove_path(&mut self, path_id: &PathId) {
+1185 if let Some(addr) = self.paths.remove(path_id) {
+1186 self.path_ids.remove(&addr);
+1187 }
+1188 self.open_paths.remove(path_id);
+1189 }
+1190
+1191 /// Removes the path from the open paths.
+1192 fn remove_open_path(&mut self, path_id: &PathId) {
+1193 self.open_paths.remove(path_id);
+1194
+1195 self.update_pub_path_info();
+1196 }
1197
-1198 self.update_pub_path_info();
-1199 }
-1200
-1201 /// Sets the new [`PathInfo`] structs for the public [`Connection`].
-1202 ///
-1203 /// [`Connection`]: crate::endpoint::Connection
-1204 fn update_pub_path_info(&self) {
-1205 let new = self
-1206 .open_paths
-1207 .iter()
-1208 .map(|(path_id, remote)| {
-1209 let remote = TransportAddr::from(remote.clone());
-1210 (remote, *path_id)
-1211 })
-1212 .collect::<PathAddrList>();
-1213
-1214 self.pub_open_paths.set(new).ok();
-1215 }
-1216}
-1217
-1218/// Watcher for the open paths and selected transmission path in a connection.
-1219///
-1220/// This is stored in the [`Connection`], and the watchables are set from within the endpoint state actor.
-1221///
-1222/// Internally, this contains a boxed-mapped-joined watcher over the open paths in the connection and the
-1223/// selected path to the remote endpoint. The watcher is boxed because the mapped-joined watcher with
-1224/// `SmallVec<PathInfoList>` has a size of over 800 bytes, which we don't want to put upon the [`Connection`].
-1225///
-1226/// [`Connection`]: crate::endpoint::Connection
-1227#[derive(Clone, derive_more::Debug)]
-1228#[debug("PathsWatcher")]
-1229#[allow(clippy::type_complexity)]
-1230pub(crate) struct PathsWatcher(
-1231 Box<
-1232 n0_watcher::Map<
-1233 n0_watcher::Tuple<
-1234 n0_watcher::Direct<PathAddrList>,
-1235 n0_watcher::Direct<Option<transports::Addr>>,
-1236 >,
-1237 PathInfoList,
-1238 >,
-1239 >,
-1240);
+1198 /// Sets the new [`PathInfo`] structs for the public [`Connection`].
+1199 ///
+1200 /// [`Connection`]: crate::endpoint::Connection
+1201 fn update_pub_path_info(&self) {
+1202 let new = self
+1203 .open_paths
+1204 .iter()
+1205 .map(|(path_id, remote)| {
+1206 let remote = TransportAddr::from(remote.clone());
+1207 (remote, *path_id)
+1208 })
+1209 .collect::<PathAddrList>();
+1210
+1211 self.pub_open_paths.set(new).ok();
+1212 }
+1213}
+1214
+1215/// Watcher for the open paths and selected transmission path in a connection.
+1216///
+1217/// This is stored in the [`Connection`], and the watchables are set from within the endpoint state actor.
+1218///
+1219/// Internally, this contains a boxed-mapped-joined watcher over the open paths in the connection and the
+1220/// selected path to the remote endpoint. The watcher is boxed because the mapped-joined watcher with
+1221/// `SmallVec<PathInfoList>` has a size of over 800 bytes, which we don't want to put upon the [`Connection`].
+1222///
+1223/// [`Connection`]: crate::endpoint::Connection
+1224#[derive(Clone, derive_more::Debug)]
+1225#[debug("PathsWatcher")]
+1226#[allow(clippy::type_complexity)]
+1227pub(crate) struct PathsWatcher(
+1228 Box<
+1229 n0_watcher::Map<
+1230 n0_watcher::Tuple<
+1231 n0_watcher::Direct<PathAddrList>,
+1232 n0_watcher::Direct<Option<transports::Addr>>,
+1233 >,
+1234 PathInfoList,
+1235 >,
+1236 >,
+1237);
+1238
+1239impl n0_watcher::Watcher for PathsWatcher {
+1240 type Value = PathInfoList;
1241
-1242impl n0_watcher::Watcher for PathsWatcher {
-1243 type Value = PathInfoList;
-1244
-1245 fn update(&mut self) -> bool {
-1246 self.0.update()
-1247 }
-1248
-1249 fn peek(&self) -> &Self::Value {
-1250 self.0.peek()
-1251 }
-1252
-1253 fn is_connected(&self) -> bool {
-1254 self.0.is_connected()
-1255 }
-1256
-1257 fn poll_updated(
-1258 &mut self,
-1259 cx: &mut std::task::Context<'_>,
-1260 ) -> Poll<Result<(), n0_watcher::Disconnected>> {
-1261 self.0.poll_updated(cx)
-1262 }
-1263}
-1264
-1265impl PathsWatcher {
-1266 fn new(
-1267 open_paths: n0_watcher::Direct<PathAddrList>,
-1268 selected_path: n0_watcher::Direct<Option<transports::Addr>>,
-1269 conn_handle: WeakConnectionHandle,
-1270 ) -> Self {
-1271 Self(Box::new(open_paths.or(selected_path).map(
-1272 move |(open_paths, selected_path)| {
-1273 let selected_path: Option<TransportAddr> = selected_path.map(Into::into);
-1274 let Some(conn) = conn_handle.upgrade() else {
-1275 return PathInfoList(Default::default());
-1276 };
-1277 let list = open_paths
-1278 .into_iter()
-1279 .flat_map(move |(remote, path_id)| {
-1280 PathInfo::new(path_id, &conn, remote, selected_path.as_ref())
-1281 })
-1282 .collect();
-1283 PathInfoList(list)
-1284 },
-1285 )))
-1286 }
-1287}
-1288
-1289/// List of [`PathInfo`] for the network paths of a [`Connection`].
-1290///
-1291/// This struct implements [`IntoIterator`].
-1292///
-1293/// [`Connection`]: crate::endpoint::Connection
-1294#[derive(derive_more::Debug, derive_more::IntoIterator, Eq, PartialEq, Clone)]
-1295#[debug("{_0:?}")]
-1296pub struct PathInfoList(SmallVec<[PathInfo; 4]>);
-1297
-1298impl PathInfoList {
-1299 /// Returns an iterator over the path infos.
-1300 pub fn iter(&self) -> impl Iterator<Item = &PathInfo> {
-1301 self.0.iter()
-1302 }
-1303
-1304 /// Returns `true` if the list is empty.
-1305 pub fn is_empty(&self) -> bool {
-1306 self.0.is_empty()
-1307 }
-1308
-1309 /// Returns the number of paths.
-1310 pub fn len(&self) -> usize {
-1311 self.0.len()
-1312 }
-1313}
-1314
-1315/// Information about a network path used by a [`Connection`].
-1316///
-1317/// [`Connection`]: crate::endpoint::Connection
-1318#[derive(derive_more::Debug, Clone)]
-1319pub struct PathInfo {
-1320 path_id: PathId,
-1321 #[debug(skip)]
-1322 handle: WeakConnectionHandle,
-1323 stats: PathStats,
-1324 remote: TransportAddr,
-1325 is_selected: bool,
-1326}
-1327
-1328impl PartialEq for PathInfo {
-1329 fn eq(&self, other: &Self) -> bool {
-1330 self.path_id == other.path_id
-1331 && self.remote == other.remote
-1332 && self.is_selected == other.is_selected
-1333 }
-1334}
-1335
-1336impl Eq for PathInfo {}
-1337
-1338impl PathInfo {
-1339 fn new(
-1340 path_id: PathId,
-1341 conn: &quinn::Connection,
-1342 remote: TransportAddr,
-1343 selected_path: Option<&TransportAddr>,
-1344 ) -> Option<Self> {
-1345 let stats = conn.path_stats(path_id)?;
-1346 Some(Self {
-1347 path_id,
-1348 handle: conn.weak_handle(),
-1349 is_selected: Some(&remote) == selected_path,
-1350 remote,
-1351 stats,
-1352 })
-1353 }
-1354
-1355 /// The remote transport address used by this network path.
-1356 pub fn remote_addr(&self) -> &TransportAddr {
-1357 &self.remote
-1358 }
-1359
-1360 /// Returns `true` if this path is currently the main transmission path for this [`Connection`].
-1361 ///
-1362 /// [`Connection`]: crate::endpoint::Connection
-1363 pub fn is_selected(&self) -> bool {
-1364 self.is_selected
-1365 }
-1366
-1367 /// Whether this is an IP transport address.
-1368 pub fn is_ip(&self) -> bool {
-1369 self.remote.is_ip()
-1370 }
-1371
-1372 /// Whether this is a transport address via a relay server.
-1373 pub fn is_relay(&self) -> bool {
-1374 self.remote.is_relay()
-1375 }
-1376
-1377 /// Returns stats for this transmission path.
-1378 pub fn stats(&self) -> PathStats {
-1379 self.handle
-1380 .upgrade()
-1381 .and_then(|conn| conn.path_stats(self.path_id))
-1382 .unwrap_or(self.stats)
-1383 }
-1384
-1385 /// Current best estimate of this paths's latency (round-trip-time)
-1386 pub fn rtt(&self) -> Duration {
-1387 self.stats().rtt
-1388 }
-1389}
-1390
-1391/// Poll a future once, like n0_future::future::poll_once but sync.
-1392fn now_or_never<T, F: Future<Output = T>>(fut: F) -> Option<T> {
-1393 let fut = std::pin::pin!(fut);
-1394 match fut.poll(&mut std::task::Context::from_waker(std::task::Waker::noop())) {
-1395 Poll::Ready(res) => Some(res),
-1396 Poll::Pending => None,
-1397 }
-1398}
-1399
-1400/// Future that resolves to the `conn_id` once a connection is closed.
-1401///
-1402/// This uses [`quinn::Connection::on_closed`], which does not keep the connection alive
-1403/// while awaiting the future.
-1404struct OnClosed {
-1405 conn_id: ConnId,
-1406 inner: quinn::OnClosed,
-1407}
-1408
-1409impl OnClosed {
-1410 fn new(conn: &quinn::Connection) -> Self {
-1411 Self {
-1412 conn_id: ConnId(conn.stable_id()),
-1413 inner: conn.on_closed(),
-1414 }
-1415 }
-1416}
+1242 fn update(&mut self) -> bool {
+1243 self.0.update()
+1244 }
+1245
+1246 fn peek(&self) -> &Self::Value {
+1247 self.0.peek()
+1248 }
+1249
+1250 fn is_connected(&self) -> bool {
+1251 self.0.is_connected()
+1252 }
+1253
+1254 fn poll_updated(
+1255 &mut self,
+1256 cx: &mut std::task::Context<'_>,
+1257 ) -> Poll<Result<(), n0_watcher::Disconnected>> {
+1258 self.0.poll_updated(cx)
+1259 }
+1260}
+1261
+1262impl PathsWatcher {
+1263 fn new(
+1264 open_paths: n0_watcher::Direct<PathAddrList>,
+1265 selected_path: n0_watcher::Direct<Option<transports::Addr>>,
+1266 conn_handle: WeakConnectionHandle,
+1267 ) -> Self {
+1268 Self(Box::new(open_paths.or(selected_path).map(
+1269 move |(open_paths, selected_path)| {
+1270 let selected_path: Option<TransportAddr> = selected_path.map(Into::into);
+1271 let Some(conn) = conn_handle.upgrade() else {
+1272 return PathInfoList(Default::default());
+1273 };
+1274 let list = open_paths
+1275 .into_iter()
+1276 .flat_map(move |(remote, path_id)| {
+1277 PathInfo::new(path_id, &conn, remote, selected_path.as_ref())
+1278 })
+1279 .collect();
+1280 PathInfoList(list)
+1281 },
+1282 )))
+1283 }
+1284}
+1285
+1286/// List of [`PathInfo`] for the network paths of a [`Connection`].
+1287///
+1288/// This struct implements [`IntoIterator`].
+1289///
+1290/// [`Connection`]: crate::endpoint::Connection
+1291#[derive(derive_more::Debug, derive_more::IntoIterator, Eq, PartialEq, Clone)]
+1292#[debug("{_0:?}")]
+1293pub struct PathInfoList(SmallVec<[PathInfo; 4]>);
+1294
+1295impl PathInfoList {
+1296 /// Returns an iterator over the path infos.
+1297 pub fn iter(&self) -> impl Iterator<Item = &PathInfo> {
+1298 self.0.iter()
+1299 }
+1300
+1301 /// Returns `true` if the list is empty.
+1302 pub fn is_empty(&self) -> bool {
+1303 self.0.is_empty()
+1304 }
+1305
+1306 /// Returns the number of paths.
+1307 pub fn len(&self) -> usize {
+1308 self.0.len()
+1309 }
+1310}
+1311
+1312/// Information about a network path used by a [`Connection`].
+1313///
+1314/// [`Connection`]: crate::endpoint::Connection
+1315#[derive(derive_more::Debug, Clone)]
+1316pub struct PathInfo {
+1317 path_id: PathId,
+1318 #[debug(skip)]
+1319 handle: WeakConnectionHandle,
+1320 stats: PathStats,
+1321 remote: TransportAddr,
+1322 is_selected: bool,
+1323}
+1324
+1325impl PartialEq for PathInfo {
+1326 fn eq(&self, other: &Self) -> bool {
+1327 self.path_id == other.path_id
+1328 && self.remote == other.remote
+1329 && self.is_selected == other.is_selected
+1330 }
+1331}
+1332
+1333impl Eq for PathInfo {}
+1334
+1335impl PathInfo {
+1336 fn new(
+1337 path_id: PathId,
+1338 conn: &quinn::Connection,
+1339 remote: TransportAddr,
+1340 selected_path: Option<&TransportAddr>,
+1341 ) -> Option<Self> {
+1342 let stats = conn.path_stats(path_id)?;
+1343 Some(Self {
+1344 path_id,
+1345 handle: conn.weak_handle(),
+1346 is_selected: Some(&remote) == selected_path,
+1347 remote,
+1348 stats,
+1349 })
+1350 }
+1351
+1352 /// The remote transport address used by this network path.
+1353 pub fn remote_addr(&self) -> &TransportAddr {
+1354 &self.remote
+1355 }
+1356
+1357 /// Returns `true` if this path is currently the main transmission path for this [`Connection`].
+1358 ///
+1359 /// [`Connection`]: crate::endpoint::Connection
+1360 pub fn is_selected(&self) -> bool {
+1361 self.is_selected
+1362 }
+1363
+1364 /// Whether this is an IP transport address.
+1365 pub fn is_ip(&self) -> bool {
+1366 self.remote.is_ip()
+1367 }
+1368
+1369 /// Whether this is a transport address via a relay server.
+1370 pub fn is_relay(&self) -> bool {
+1371 self.remote.is_relay()
+1372 }
+1373
+1374 /// Returns stats for this transmission path.
+1375 pub fn stats(&self) -> PathStats {
+1376 self.handle
+1377 .upgrade()
+1378 .and_then(|conn| conn.path_stats(self.path_id))
+1379 .unwrap_or(self.stats)
+1380 }
+1381
+1382 /// Current best estimate of this paths's latency (round-trip-time)
+1383 pub fn rtt(&self) -> Duration {
+1384 self.stats().rtt
+1385 }
+1386}
+1387
+1388/// Poll a future once, like n0_future::future::poll_once but sync.
+1389fn now_or_never<T, F: Future<Output = T>>(fut: F) -> Option<T> {
+1390 let fut = std::pin::pin!(fut);
+1391 match fut.poll(&mut std::task::Context::from_waker(std::task::Waker::noop())) {
+1392 Poll::Ready(res) => Some(res),
+1393 Poll::Pending => None,
+1394 }
+1395}
+1396
+1397/// Future that resolves to the `conn_id` once a connection is closed.
+1398///
+1399/// This uses [`quinn::Connection::on_closed`], which does not keep the connection alive
+1400/// while awaiting the future.
+1401struct OnClosed {
+1402 conn_id: ConnId,
+1403 inner: quinn::OnClosed,
+1404}
+1405
+1406impl OnClosed {
+1407 fn new(conn: &quinn::Connection) -> Self {
+1408 Self {
+1409 conn_id: ConnId(conn.stable_id()),
+1410 inner: conn.on_closed(),
+1411 }
+1412 }
+1413}
+1414
+1415impl Future for OnClosed {
+1416 type Output = ConnId;
1417
-1418impl Future for OnClosed {
-1419 type Output = ConnId;
-1420
-1421 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
-1422 let (_close_reason, _stats) = std::task::ready!(Pin::new(&mut self.inner).poll(cx));
-1423 Poll::Ready(self.conn_id)
-1424 }
-1425}
-1426
-1427/// Converts an interator of [`TransportAddr'] into an iterator of [`transports::Addr`].
-1428fn to_transports_addr(
-1429 endpoint_id: EndpointId,
-1430 addrs: impl IntoIterator<Item = TransportAddr>,
-1431) -> impl Iterator<Item = transports::Addr> {
-1432 addrs.into_iter().filter_map(move |addr| match addr {
-1433 TransportAddr::Relay(relay_url) => Some(transports::Addr::from((relay_url, endpoint_id))),
-1434 TransportAddr::Ip(sockaddr) => Some(transports::Addr::from(sockaddr)),
-1435 _ => {
-1436 warn!(?addr, "Unsupported TransportAddr");
-1437 None
-1438 }
-1439 })
-1440}
\ No newline at end of file
+1418 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
+1419 let (_close_reason, _stats) = std::task::ready!(Pin::new(&mut self.inner).poll(cx));
+1420 Poll::Ready(self.conn_id)
+1421 }
+1422}
+1423
+1424/// Converts an iterator of [`TransportAddr'] into an iterator of [`transports::Addr`].
+1425fn to_transports_addr(
+1426 endpoint_id: EndpointId,
+1427 addrs: impl IntoIterator<Item = TransportAddr>,
+1428) -> impl Iterator<Item = transports::Addr> {
+1429 addrs.into_iter().filter_map(move |addr| match addr {
+1430 TransportAddr::Relay(relay_url) => Some(transports::Addr::from((relay_url, endpoint_id))),
+1431 TransportAddr::Ip(sockaddr) => Some(transports::Addr::from(sockaddr)),
+1432 _ => {
+1433 warn!(?addr, "Unsupported TransportAddr");
+1434 None
+1435 }
+1436 })
+1437}
\ No newline at end of file
diff --git a/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state/path_state.rs.html b/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state/path_state.rs.html
index a47e44b277..5a3a367891 100644
--- a/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state/path_state.rs.html
+++ b/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state/path_state.rs.html
@@ -117,7 +117,7 @@
117 self.paths.keys()
118 }
119
-120 /// Replies to all pending requests from [`EndpointStateMessage::ResolveRemote`].
+120 /// Replies to all pending resolve requests.
121 ///
122 /// This is a no-op if no requests are queued. Replies `Ok` if we have any known paths,
123 /// otherwise with the provided `discovery_error` or with [`DiscoveryError::NoResults`].
@@ -139,17 +139,14 @@
139/// The state of a single path to the remote endpoint.
140///
141/// Each path is identified by the destination [`transports::Addr`] and they are stored in
-142/// the [`EndpointStateActor::paths`] map.
-143///
-144/// [`transports::Addr`]: super::transports::Addr
-145/// [`EndpointStateActor::paths`]: super::endpoint_state::EndpointStateActor
-146#[derive(Debug, Default)]
-147pub(super) struct PathState {
-148 /// How we learned about this path, and when.
-149 ///
-150 /// We keep track of only the latest [`Instant`] for each [`Source`], keeping the size
-151 /// of the map of sources down to one entry per type of source.
-152 pub(super) sources: HashMap<Source, Instant>,
-153 /// The last ping sent on this path.
-154 pub(super) ping_sent: Option<TransactionId>,
-155}
\ No newline at end of file
+142/// the [`EndpointPathState::paths`] map.
+143#[derive(Debug, Default)]
+144pub(super) struct PathState {
+145 /// How we learned about this path, and when.
+146 ///
+147 /// We keep track of only the latest [`Instant`] for each [`Source`], keeping the size
+148 /// of the map of sources down to one entry per type of source.
+149 pub(super) sources: HashMap<Source, Instant>,
+150 /// The last ping sent on this path.
+151 pub(super) ping_sent: Option<TransactionId>,
+152}
\ No newline at end of file
impl<T> Any for Twhere
+PathInfo in iroh::endpoint - Rust PathInfo
pub struct PathInfo { /* private fields */ }
Expand description
Information about a network path used by a Connection.
+Implementations§
Source§impl PathInfo
Sourcepub fn remote_addr(&self) -> &TransportAddr
The remote transport address used by this network path.
+Sourcepub fn is_selected(&self) -> bool
Returns true if this path is currently the main transmission path for this Connection.
+Trait Implementations§
Source§impl Eq for PathInfo
Auto Trait Implementations§
§impl Freeze for PathInfo
§impl RefUnwindSafe for PathInfo
§impl Send for PathInfo
§impl Sync for PathInfo
§impl Unpin for PathInfo
§impl UnwindSafe for PathInfo
Blanket Implementations§
§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
§fn implicit(
diff --git a/pr/3645/docs/iroh/endpoint/struct.PathInfoList.html b/pr/3645/docs/iroh/endpoint/struct.PathInfoList.html
index 330e5c6ae1..404a8509cb 100644
--- a/pr/3645/docs/iroh/endpoint/struct.PathInfoList.html
+++ b/pr/3645/docs/iroh/endpoint/struct.PathInfoList.html
@@ -1,11 +1,11 @@
-PathInfoList in iroh::endpoint - Rust PathInfoList
pub struct PathInfoList(/* private fields */);
Expand description
List of PathInfo for the network paths of a Connection.
+PathInfoList in iroh::endpoint - Rust PathInfoList
pub struct PathInfoList(/* private fields */);
Expand description
List of PathInfo for the network paths of a Connection.
This struct implements IntoIterator.
-Implementations§
Trait Implementations§
Source§impl Clone for PathInfoList
Source§fn clone(&self) -> PathInfoList
Returns a duplicate of the value. Read more1.0.0 · Source§fn clone_from(&mut self, source: &Self)
Performs copy-assignment from source. Read moreSource§impl Debug for PathInfoList
Source§impl IntoIterator for PathInfoList
Source§impl PartialEq for PathInfoList
Source§impl Eq for PathInfoList
Source§impl StructuralPartialEq for PathInfoList
Auto Trait Implementations§
§impl Freeze for PathInfoList
§impl RefUnwindSafe for PathInfoList
§impl Send for PathInfoList
§impl Sync for PathInfoList
§impl Unpin for PathInfoList
§impl UnwindSafe for PathInfoList
Blanket Implementations§
Implementations§
Trait Implementations§
Source§impl Clone for PathInfoList
Source§fn clone(&self) -> PathInfoList
Returns a duplicate of the value. Read more1.0.0 · Source§fn clone_from(&mut self, source: &Self)
Performs copy-assignment from source. Read moreSource§impl Debug for PathInfoList
Source§impl IntoIterator for PathInfoList
Source§impl PartialEq for PathInfoList
Source§impl Eq for PathInfoList
Source§impl StructuralPartialEq for PathInfoList
Auto Trait Implementations§
§impl Freeze for PathInfoList
§impl RefUnwindSafe for PathInfoList
§impl Send for PathInfoList
§impl Sync for PathInfoList
§impl Unpin for PathInfoList
§impl UnwindSafe for PathInfoList
Blanket Implementations§
§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
§fn implicit(
diff --git a/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state.rs.html b/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state.rs.html
index 383b3f0cc2..cd0545f907 100644
--- a/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state.rs.html
+++ b/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state.rs.html
@@ -729,712 +729,709 @@
729 let Some(relay_addr) = self
730 .paths
731 .addrs()
-732 .filter_map(|addr| match addr {
-733 transports::Addr::Ip(_) => None,
-734 transports::Addr::Relay(_, _) => Some(addr),
-735 })
-736 .next()
-737 .cloned()
-738 else {
-739 warn!("holepunching requested but have no relay address");
-740 return;
-741 };
-742 let remote_addrs = self.remote_hp_addrs();
-743
-744 // Send DISCO Ping messages to all CallMeMaybe-advertised paths.
-745 for dst in remote_addrs.iter() {
-746 let msg = disco::Ping::new(self.local_endpoint_id);
-747 event!(
-748 target: "iroh::_events::ping::sent",
-749 Level::DEBUG,
-750 remote = %self.endpoint_id.fmt_short(),
-751 ?dst,
-752 txn = ?msg.tx_id,
-753 );
-754 let addr = transports::Addr::Ip(*dst);
-755 self.paths.disco_ping_sent(addr.clone(), msg.tx_id);
-756 self.send_disco_message(addr, disco::Message::Ping(msg))
-757 .await;
-758 }
-759
-760 // Send the DISCO CallMeMaybe message over the relay.
-761 let my_numbers: Vec<SocketAddr> = self
-762 .local_addrs
-763 .get()
-764 .iter()
-765 .map(|daddr| daddr.addr)
-766 .collect();
-767 let local_addrs: BTreeSet<SocketAddr> = my_numbers.iter().copied().collect();
-768 let msg = disco::CallMeMaybe { my_numbers };
-769 event!(
-770 target: "iroh::_events::call_me_maybe::sent",
-771 Level::DEBUG,
-772 remote = %self.endpoint_id.fmt_short(),
-773 dst = ?relay_addr,
-774 my_numbers = ?msg.my_numbers,
-775 );
-776 self.send_disco_message(relay_addr, disco::Message::CallMeMaybe(msg))
-777 .await;
-778
-779 self.last_holepunch = Some(HolepunchAttempt {
-780 when: Instant::now(),
-781 local_addrs,
-782 remote_addrs,
-783 });
-784 }
-785
-786 /// Sends a DISCO message to the remote endpoint this actor manages.
-787 #[instrument(skip(self), fields(remote = %self.endpoint_id.fmt_short()))]
-788 async fn send_disco_message(&self, dst: transports::Addr, msg: disco::Message) {
-789 let pkt = self.disco.encode_and_seal(self.endpoint_id, &msg);
-790 let transmit = transports::OwnedTransmit {
-791 ecn: None,
-792 contents: pkt,
-793 segment_size: None,
-794 };
-795 let counter = match dst {
-796 transports::Addr::Ip(_) => &self.metrics.send_disco_udp,
-797 transports::Addr::Relay(_, _) => &self.metrics.send_disco_relay,
-798 };
-799 match self.send_datagram(dst, transmit).await {
-800 Ok(()) => {
-801 trace!("sent");
-802 counter.inc();
+732 .filter(|addr| addr.is_relay())
+733 .next()
+734 .cloned()
+735 else {
+736 warn!("holepunching requested but have no relay address");
+737 return;
+738 };
+739 let remote_addrs = self.remote_hp_addrs();
+740
+741 // Send DISCO Ping messages to all CallMeMaybe-advertised paths.
+742 for dst in remote_addrs.iter() {
+743 let msg = disco::Ping::new(self.local_endpoint_id);
+744 event!(
+745 target: "iroh::_events::ping::sent",
+746 Level::DEBUG,
+747 remote = %self.endpoint_id.fmt_short(),
+748 ?dst,
+749 txn = ?msg.tx_id,
+750 );
+751 let addr = transports::Addr::Ip(*dst);
+752 self.paths.disco_ping_sent(addr.clone(), msg.tx_id);
+753 self.send_disco_message(addr, disco::Message::Ping(msg))
+754 .await;
+755 }
+756
+757 // Send the DISCO CallMeMaybe message over the relay.
+758 let my_numbers: Vec<SocketAddr> = self
+759 .local_addrs
+760 .get()
+761 .iter()
+762 .map(|daddr| daddr.addr)
+763 .collect();
+764 let local_addrs: BTreeSet<SocketAddr> = my_numbers.iter().copied().collect();
+765 let msg = disco::CallMeMaybe { my_numbers };
+766 event!(
+767 target: "iroh::_events::call_me_maybe::sent",
+768 Level::DEBUG,
+769 remote = %self.endpoint_id.fmt_short(),
+770 dst = ?relay_addr,
+771 my_numbers = ?msg.my_numbers,
+772 );
+773 self.send_disco_message(relay_addr, disco::Message::CallMeMaybe(msg))
+774 .await;
+775
+776 self.last_holepunch = Some(HolepunchAttempt {
+777 when: Instant::now(),
+778 local_addrs,
+779 remote_addrs,
+780 });
+781 }
+782
+783 /// Sends a DISCO message to the remote endpoint this actor manages.
+784 #[instrument(skip(self), fields(remote = %self.endpoint_id.fmt_short()))]
+785 async fn send_disco_message(&self, dst: transports::Addr, msg: disco::Message) {
+786 let pkt = self.disco.encode_and_seal(self.endpoint_id, &msg);
+787 let transmit = transports::OwnedTransmit {
+788 ecn: None,
+789 contents: pkt,
+790 segment_size: None,
+791 };
+792 let counter = match dst {
+793 transports::Addr::Ip(_) => &self.metrics.send_disco_udp,
+794 transports::Addr::Relay(_, _) => &self.metrics.send_disco_relay,
+795 };
+796 match self.send_datagram(dst, transmit).await {
+797 Ok(()) => {
+798 trace!("sent");
+799 counter.inc();
+800 }
+801 Err(err) => {
+802 warn!("failed to send disco message: {err:#}");
803 }
-804 Err(err) => {
-805 warn!("failed to send disco message: {err:#}");
-806 }
-807 }
-808 }
-809
-810 /// Open the path on all connections.
-811 ///
-812 /// This goes through all the connections for which we are the client, and makes sure
-813 /// the path exists, or opens it.
-814 #[instrument(level = "warn", skip(self))]
-815 fn open_path(&mut self, open_addr: &transports::Addr) {
-816 let path_status = match open_addr {
-817 transports::Addr::Ip(_) => PathStatus::Available,
-818 transports::Addr::Relay(_, _) => PathStatus::Backup,
-819 };
-820 let quic_addr = match &open_addr {
-821 transports::Addr::Ip(socket_addr) => *socket_addr,
-822 transports::Addr::Relay(relay_url, eid) => self
-823 .relay_mapped_addrs
-824 .get(&(relay_url.clone(), *eid))
-825 .private_socket_addr(),
-826 };
-827
-828 for (conn_id, conn_state) in self.connections.iter_mut() {
-829 if conn_state.path_ids.contains_key(open_addr) {
+804 }
+805 }
+806
+807 /// Open the path on all connections.
+808 ///
+809 /// This goes through all the connections for which we are the client, and makes sure
+810 /// the path exists, or opens it.
+811 #[instrument(level = "warn", skip(self))]
+812 fn open_path(&mut self, open_addr: &transports::Addr) {
+813 let path_status = match open_addr {
+814 transports::Addr::Ip(_) => PathStatus::Available,
+815 transports::Addr::Relay(_, _) => PathStatus::Backup,
+816 };
+817 let quic_addr = match &open_addr {
+818 transports::Addr::Ip(socket_addr) => *socket_addr,
+819 transports::Addr::Relay(relay_url, eid) => self
+820 .relay_mapped_addrs
+821 .get(&(relay_url.clone(), *eid))
+822 .private_socket_addr(),
+823 };
+824
+825 for (conn_id, conn_state) in self.connections.iter_mut() {
+826 if conn_state.path_ids.contains_key(open_addr) {
+827 continue;
+828 }
+829 let Some(conn) = conn_state.handle.upgrade() else {
830 continue;
-831 }
-832 let Some(conn) = conn_state.handle.upgrade() else {
+831 };
+832 if conn.side().is_server() {
833 continue;
-834 };
-835 if conn.side().is_server() {
-836 continue;
-837 }
-838 let fut = conn.open_path_ensure(quic_addr, path_status);
-839 match fut.path_id() {
-840 Some(path_id) => {
-841 trace!(?conn_id, ?path_id, "opening new path");
-842 conn_state.add_path(open_addr.clone(), path_id);
-843 }
-844 None => {
-845 let ret = now_or_never(fut);
-846 match ret {
-847 Some(Err(PathError::RemoteCidsExhausted)) => {
-848 self.scheduled_open_path =
-849 Some(Instant::now() + Duration::from_millis(333));
-850 self.pending_open_paths.push_back(open_addr.clone());
-851 trace!(?open_addr, "scheduling open_path");
-852 }
-853 _ => warn!(?ret, "Opening path failed"),
-854 }
-855 }
-856 }
-857 }
-858 }
-859
-860 #[instrument(skip(self))]
-861 fn handle_path_event(
-862 &mut self,
-863 conn_id: ConnId,
-864 event: Result<PathEvent, BroadcastStreamRecvError>,
-865 ) {
-866 let Ok(event) = event else {
-867 warn!("missed a PathEvent, EndpointStateActor lagging");
-868 // TODO: Is it possible to recover using the sync APIs to figure out what the
-869 // state of the connection and it's paths are?
-870 return;
-871 };
-872 let Some(conn_state) = self.connections.get_mut(&conn_id) else {
-873 trace!("event for removed connection");
-874 return;
-875 };
-876 let Some(conn) = conn_state.handle.upgrade() else {
-877 trace!("event for closed connection");
-878 return;
-879 };
-880 trace!("path event");
-881 match event {
-882 PathEvent::Opened { id: path_id } => {
-883 let Some(path) = conn.path(path_id) else {
-884 trace!("path open event for unknown path");
-885 return;
-886 };
-887 // TODO: We configure this as defaults when we setup the endpoint, do we
-888 // really need to duplicate this?
-889 path.set_keep_alive_interval(Some(HEARTBEAT_INTERVAL)).ok();
-890 path.set_max_idle_timeout(Some(PATH_MAX_IDLE_TIMEOUT)).ok();
-891
-892 if let Ok(socketaddr) = path.remote_address()
-893 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr)
-894 {
-895 event!(
-896 target: "iroh::_events::path::open",
-897 Level::DEBUG,
-898 remote = %self.endpoint_id.fmt_short(),
-899 ?path_remote,
-900 ?conn_id,
-901 ?path_id,
-902 );
-903 conn_state.add_open_path(path_remote.clone(), path_id);
-904 self.paths
-905 .insert(path_remote, Source::Connection { _0: Private });
-906 }
-907
-908 self.select_path();
-909 }
-910 PathEvent::Abandoned { id, path_stats } => {
-911 trace!(?path_stats, "path abandoned");
-912 // This is the last event for this path.
-913 conn_state.remove_path(&id);
-914 }
-915 PathEvent::Closed { id, .. } | PathEvent::LocallyClosed { id, .. } => {
-916 let Some(path_remote) = conn_state.paths.get(&id).cloned() else {
-917 debug!("path not in path_id_map");
-918 return;
-919 };
-920 event!(
-921 target: "iroh::_events::path::closed",
-922 Level::DEBUG,
-923 remote = %self.endpoint_id.fmt_short(),
-924 ?path_remote,
-925 ?conn_id,
-926 path_id = ?id,
-927 );
-928 conn_state.remove_open_path(&id);
-929
-930 // If one connection closes this path, close it on all connections.
-931 for (conn_id, conn_state) in self.connections.iter_mut() {
-932 let Some(path_id) = conn_state.path_ids.get(&path_remote) else {
+834 }
+835 let fut = conn.open_path_ensure(quic_addr, path_status);
+836 match fut.path_id() {
+837 Some(path_id) => {
+838 trace!(?conn_id, ?path_id, "opening new path");
+839 conn_state.add_path(open_addr.clone(), path_id);
+840 }
+841 None => {
+842 let ret = now_or_never(fut);
+843 match ret {
+844 Some(Err(PathError::RemoteCidsExhausted)) => {
+845 self.scheduled_open_path =
+846 Some(Instant::now() + Duration::from_millis(333));
+847 self.pending_open_paths.push_back(open_addr.clone());
+848 trace!(?open_addr, "scheduling open_path");
+849 }
+850 _ => warn!(?ret, "Opening path failed"),
+851 }
+852 }
+853 }
+854 }
+855 }
+856
+857 #[instrument(skip(self))]
+858 fn handle_path_event(
+859 &mut self,
+860 conn_id: ConnId,
+861 event: Result<PathEvent, BroadcastStreamRecvError>,
+862 ) {
+863 let Ok(event) = event else {
+864 warn!("missed a PathEvent, EndpointStateActor lagging");
+865 // TODO: Is it possible to recover using the sync APIs to figure out what the
+866 // state of the connection and it's paths are?
+867 return;
+868 };
+869 let Some(conn_state) = self.connections.get_mut(&conn_id) else {
+870 trace!("event for removed connection");
+871 return;
+872 };
+873 let Some(conn) = conn_state.handle.upgrade() else {
+874 trace!("event for closed connection");
+875 return;
+876 };
+877 trace!("path event");
+878 match event {
+879 PathEvent::Opened { id: path_id } => {
+880 let Some(path) = conn.path(path_id) else {
+881 trace!("path open event for unknown path");
+882 return;
+883 };
+884 // TODO: We configure this as defaults when we setup the endpoint, do we
+885 // really need to duplicate this?
+886 path.set_keep_alive_interval(Some(HEARTBEAT_INTERVAL)).ok();
+887 path.set_max_idle_timeout(Some(PATH_MAX_IDLE_TIMEOUT)).ok();
+888
+889 if let Ok(socketaddr) = path.remote_address()
+890 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr)
+891 {
+892 event!(
+893 target: "iroh::_events::path::open",
+894 Level::DEBUG,
+895 remote = %self.endpoint_id.fmt_short(),
+896 ?path_remote,
+897 ?conn_id,
+898 ?path_id,
+899 );
+900 conn_state.add_open_path(path_remote.clone(), path_id);
+901 self.paths
+902 .insert(path_remote, Source::Connection { _0: Private });
+903 }
+904
+905 self.select_path();
+906 }
+907 PathEvent::Abandoned { id, path_stats } => {
+908 trace!(?path_stats, "path abandoned");
+909 // This is the last event for this path.
+910 conn_state.remove_path(&id);
+911 }
+912 PathEvent::Closed { id, .. } | PathEvent::LocallyClosed { id, .. } => {
+913 let Some(path_remote) = conn_state.paths.get(&id).cloned() else {
+914 debug!("path not in path_id_map");
+915 return;
+916 };
+917 event!(
+918 target: "iroh::_events::path::closed",
+919 Level::DEBUG,
+920 remote = %self.endpoint_id.fmt_short(),
+921 ?path_remote,
+922 ?conn_id,
+923 path_id = ?id,
+924 );
+925 conn_state.remove_open_path(&id);
+926
+927 // If one connection closes this path, close it on all connections.
+928 for (conn_id, conn_state) in self.connections.iter_mut() {
+929 let Some(path_id) = conn_state.path_ids.get(&path_remote) else {
+930 continue;
+931 };
+932 let Some(conn) = conn_state.handle.upgrade() else {
933 continue;
934 };
-935 let Some(conn) = conn_state.handle.upgrade() else {
-936 continue;
-937 };
-938 if let Some(path) = conn.path(*path_id) {
-939 trace!(?path_remote, ?conn_id, ?path_id, "closing path");
-940 if let Err(err) = path.close(APPLICATION_ABANDON_PATH.into()) {
-941 trace!(
-942 ?path_remote,
-943 ?conn_id,
-944 ?path_id,
-945 "path close failed: {err:#}"
-946 );
-947 }
-948 }
-949 }
-950 }
-951 PathEvent::RemoteStatus { .. } | PathEvent::ObservedAddr { .. } => {
-952 // Nothing to do for these events.
-953 }
-954 }
-955 }
-956
-957 /// Selects the path with the lowest RTT, prefers direct paths.
+935 if let Some(path) = conn.path(*path_id) {
+936 trace!(?path_remote, ?conn_id, ?path_id, "closing path");
+937 if let Err(err) = path.close(APPLICATION_ABANDON_PATH.into()) {
+938 trace!(
+939 ?path_remote,
+940 ?conn_id,
+941 ?path_id,
+942 "path close failed: {err:#}"
+943 );
+944 }
+945 }
+946 }
+947 }
+948 PathEvent::RemoteStatus { .. } | PathEvent::ObservedAddr { .. } => {
+949 // Nothing to do for these events.
+950 }
+951 }
+952 }
+953
+954 /// Selects the path with the lowest RTT, prefers direct paths.
+955 ///
+956 /// If there are direct paths, this selects the direct path with the lowest RTT. If
+957 /// there are only relay paths, the relay path with the lowest RTT is chosen.
958 ///
-959 /// If there are direct paths, this selects the direct path with the lowest RTT. If
-960 /// there are only relay paths, the relay path with the lowest RTT is chosen.
-961 ///
-962 /// The selected path is added to any connections which do not yet have it. Any unused
-963 /// direct paths are closed for all connections.
-964 #[instrument(skip_all)]
-965 fn select_path(&mut self) {
-966 // Find the lowest RTT across all connections for each open path. The long way, so
-967 // we get to log *all* RTTs.
-968 let mut all_path_rtts: FxHashMap<transports::Addr, Vec<Duration>> = FxHashMap::default();
-969 for conn_state in self.connections.values() {
-970 let Some(conn) = conn_state.handle.upgrade() else {
-971 continue;
-972 };
-973 for (path_id, addr) in conn_state.open_paths.iter() {
-974 if let Some(stats) = conn.path_stats(*path_id) {
-975 all_path_rtts
-976 .entry(addr.clone())
-977 .or_default()
-978 .push(stats.rtt);
-979 }
-980 }
-981 }
-982 trace!(?all_path_rtts, "dumping all path RTTs");
-983 let path_rtts: FxHashMap<transports::Addr, Duration> = all_path_rtts
-984 .into_iter()
-985 .filter_map(|(addr, rtts)| rtts.into_iter().min().map(|rtt| (addr, rtt)))
-986 .collect();
-987
-988 // Find the fastest direct or relay path.
-989 const IPV6_RTT_ADVANTAGE: Duration = Duration::from_millis(3);
-990 let direct_path = path_rtts
-991 .iter()
-992 .filter(|(addr, _rtt)| addr.is_ip())
-993 .map(|(addr, rtt)| {
-994 if addr.is_ipv4() {
-995 (*rtt + IPV6_RTT_ADVANTAGE, addr)
-996 } else {
-997 (*rtt, addr)
-998 }
-999 })
-1000 .min();
-1001 let selected_path = direct_path.or_else(|| {
-1002 // Find the fasted relay path.
-1003 path_rtts
-1004 .iter()
-1005 .filter(|(addr, _rtt)| addr.is_relay())
-1006 .map(|(addr, rtt)| (*rtt, addr))
-1007 .min()
-1008 });
-1009 if let Some((rtt, addr)) = selected_path {
-1010 let prev = self.selected_path.set(Some(addr.clone()));
-1011 if prev.is_ok() {
-1012 debug!(?addr, ?rtt, ?prev, "selected new path");
-1013 }
-1014 self.open_path(addr);
-1015 self.close_redundant_paths(addr);
-1016 }
-1017 }
-1018
-1019 /// Closes any direct paths not selected.
-1020 ///
-1021 /// Makes sure not to close the last direct path. Relay paths are never closed
-1022 /// currently, because we only have one relay path at this time.
-1023 // TODO: Need to handle this on a timer as well probably. In .select_path() we open new
-1024 // paths and immediately call this. But the new paths are probably not yet open on
-1025 // all connections.
-1026 fn close_redundant_paths(&mut self, selected_path: &transports::Addr) {
-1027 debug_assert_eq!(self.selected_path.get().as_ref(), Some(selected_path),);
-1028
-1029 for (conn_id, conn_state) in self.connections.iter() {
-1030 for (path_id, path_remote) in conn_state
-1031 .open_paths
-1032 .iter()
-1033 .filter(|(_, addr)| addr.is_ip())
-1034 .filter(|(_, addr)| *addr != selected_path)
-1035 {
-1036 if conn_state.open_paths.values().filter(|a| a.is_ip()).count() <= 1 {
-1037 continue; // Do not close the last direct path.
-1038 }
-1039 if let Some(path) = conn_state
-1040 .handle
-1041 .upgrade()
-1042 .and_then(|conn| conn.path(*path_id))
-1043 {
-1044 trace!(?path_remote, ?conn_id, ?path_id, "closing direct path");
-1045 match path.close(APPLICATION_ABANDON_PATH.into()) {
-1046 Err(quinn_proto::ClosePathError::LastOpenPath) => {
-1047 error!("could not close last open path");
-1048 }
-1049 Err(quinn_proto::ClosePathError::ClosedPath) => {
-1050 // We already closed this.
+959 /// The selected path is added to any connections which do not yet have it. Any unused
+960 /// direct paths are closed for all connections.
+961 #[instrument(skip_all)]
+962 fn select_path(&mut self) {
+963 // Find the lowest RTT across all connections for each open path. The long way, so
+964 // we get to log *all* RTTs.
+965 let mut all_path_rtts: FxHashMap<transports::Addr, Vec<Duration>> = FxHashMap::default();
+966 for conn_state in self.connections.values() {
+967 let Some(conn) = conn_state.handle.upgrade() else {
+968 continue;
+969 };
+970 for (path_id, addr) in conn_state.open_paths.iter() {
+971 if let Some(stats) = conn.path_stats(*path_id) {
+972 all_path_rtts
+973 .entry(addr.clone())
+974 .or_default()
+975 .push(stats.rtt);
+976 }
+977 }
+978 }
+979 trace!(?all_path_rtts, "dumping all path RTTs");
+980 let path_rtts: FxHashMap<transports::Addr, Duration> = all_path_rtts
+981 .into_iter()
+982 .filter_map(|(addr, rtts)| rtts.into_iter().min().map(|rtt| (addr, rtt)))
+983 .collect();
+984
+985 // Find the fastest direct or relay path.
+986 const IPV6_RTT_ADVANTAGE: Duration = Duration::from_millis(3);
+987 let direct_path = path_rtts
+988 .iter()
+989 .filter(|(addr, _rtt)| addr.is_ip())
+990 .map(|(addr, rtt)| {
+991 if addr.is_ipv4() {
+992 (*rtt + IPV6_RTT_ADVANTAGE, addr)
+993 } else {
+994 (*rtt, addr)
+995 }
+996 })
+997 .min();
+998 let selected_path = direct_path.or_else(|| {
+999 // Find the fasted relay path.
+1000 path_rtts
+1001 .iter()
+1002 .filter(|(addr, _rtt)| addr.is_relay())
+1003 .map(|(addr, rtt)| (*rtt, addr))
+1004 .min()
+1005 });
+1006 if let Some((rtt, addr)) = selected_path {
+1007 let prev = self.selected_path.set(Some(addr.clone()));
+1008 if prev.is_ok() {
+1009 debug!(?addr, ?rtt, ?prev, "selected new path");
+1010 }
+1011 self.open_path(addr);
+1012 self.close_redundant_paths(addr);
+1013 }
+1014 }
+1015
+1016 /// Closes any direct paths not selected.
+1017 ///
+1018 /// Makes sure not to close the last direct path. Relay paths are never closed
+1019 /// currently, because we only have one relay path at this time.
+1020 // TODO: Need to handle this on a timer as well probably. In .select_path() we open new
+1021 // paths and immediately call this. But the new paths are probably not yet open on
+1022 // all connections.
+1023 fn close_redundant_paths(&mut self, selected_path: &transports::Addr) {
+1024 debug_assert_eq!(self.selected_path.get().as_ref(), Some(selected_path),);
+1025
+1026 for (conn_id, conn_state) in self.connections.iter() {
+1027 for (path_id, path_remote) in conn_state
+1028 .open_paths
+1029 .iter()
+1030 .filter(|(_, addr)| addr.is_ip())
+1031 .filter(|(_, addr)| *addr != selected_path)
+1032 {
+1033 if conn_state.open_paths.values().filter(|a| a.is_ip()).count() <= 1 {
+1034 continue; // Do not close the last direct path.
+1035 }
+1036 if let Some(path) = conn_state
+1037 .handle
+1038 .upgrade()
+1039 .and_then(|conn| conn.path(*path_id))
+1040 {
+1041 trace!(?path_remote, ?conn_id, ?path_id, "closing direct path");
+1042 match path.close(APPLICATION_ABANDON_PATH.into()) {
+1043 Err(quinn_proto::ClosePathError::LastOpenPath) => {
+1044 error!("could not close last open path");
+1045 }
+1046 Err(quinn_proto::ClosePathError::ClosedPath) => {
+1047 // We already closed this.
+1048 }
+1049 Ok(_fut) => {
+1050 // We will handle the event in Self::handle_path_events.
1051 }
-1052 Ok(_fut) => {
-1053 // We will handle the event in Self::handle_path_events.
-1054 }
-1055 }
-1056 }
-1057 }
-1058 }
-1059 }
-1060}
-1061
-1062/// Messages to send to the [`EndpointStateActor`].
-1063#[derive(derive_more::Debug)]
-1064pub(crate) enum EndpointStateMessage {
-1065 /// Sends a datagram to all known paths.
+1052 }
+1053 }
+1054 }
+1055 }
+1056 }
+1057}
+1058
+1059/// Messages to send to the [`EndpointStateActor`].
+1060#[derive(derive_more::Debug)]
+1061pub(crate) enum EndpointStateMessage {
+1062 /// Sends a datagram to all known paths.
+1063 ///
+1064 /// Used to send QUIC Initial packets. If there is no working direct path this will
+1065 /// trigger holepunching.
1066 ///
-1067 /// Used to send QUIC Initial packets. If there is no working direct path this will
-1068 /// trigger holepunching.
-1069 ///
-1070 /// This is not acceptable to use on the normal send path, as it is an async send
-1071 /// operation with a bunch more copying. So it should only be used for sending QUIC
-1072 /// Initial packets.
-1073 #[debug("SendDatagram(..)")]
-1074 SendDatagram(OwnedTransmit),
-1075 /// Adds an active connection to this remote endpoint.
-1076 ///
-1077 /// The connection will now be managed by this actor. Holepunching will happen when
-1078 /// needed, any new paths discovered via holepunching will be added. And closed paths
-1079 /// will be removed etc.
-1080 #[debug("AddConnection(..)")]
-1081 AddConnection(WeakConnectionHandle, oneshot::Sender<PathsWatcher>),
-1082 /// Process a received DISCO CallMeMaybe message.
-1083 CallMeMaybeReceived(disco::CallMeMaybe),
-1084 /// Process a received DISCO Ping message.
-1085 #[debug("PingReceived({:?}, src: {_1:?})", _0.tx_id)]
-1086 PingReceived(disco::Ping, transports::Addr),
-1087 /// Process a received DISCO Pong message.
-1088 #[debug("PongReceived({:?}, src: {_1:?})", _0.tx_id)]
-1089 PongReceived(disco::Pong, transports::Addr),
-1090 /// Ensure we have at least one transport address for a remote.
+1067 /// This is not acceptable to use on the normal send path, as it is an async send
+1068 /// operation with a bunch more copying. So it should only be used for sending QUIC
+1069 /// Initial packets.
+1070 #[debug("SendDatagram(..)")]
+1071 SendDatagram(OwnedTransmit),
+1072 /// Adds an active connection to this remote endpoint.
+1073 ///
+1074 /// The connection will now be managed by this actor. Holepunching will happen when
+1075 /// needed, any new paths discovered via holepunching will be added. And closed paths
+1076 /// will be removed etc.
+1077 #[debug("AddConnection(..)")]
+1078 AddConnection(WeakConnectionHandle, oneshot::Sender<PathsWatcher>),
+1079 /// Process a received DISCO CallMeMaybe message.
+1080 CallMeMaybeReceived(disco::CallMeMaybe),
+1081 /// Process a received DISCO Ping message.
+1082 #[debug("PingReceived({:?}, src: {_1:?})", _0.tx_id)]
+1083 PingReceived(disco::Ping, transports::Addr),
+1084 /// Process a received DISCO Pong message.
+1085 #[debug("PongReceived({:?}, src: {_1:?})", _0.tx_id)]
+1086 PongReceived(disco::Pong, transports::Addr),
+1087 /// Ensure we have at least one transport address for a remote.
+1088 ///
+1089 /// This adds the provided transport addresses to the list of potential paths for this remote
+1090 /// and starts discovery if needed.
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 /// Returns the current latency to the remote endpoint.
-1104 ///
-1105 /// TODO: This is more of a placeholder message currently. Check MagicSock::latency.
-1106 #[debug("Latency(..)")]
-1107 Latency(oneshot::Sender<Option<Duration>>),
-1108}
-1109
-1110/// A handle to a [`EndpointStateActor`].
-1111///
-1112/// Dropping this will stop the actor. The actor will also stop after an idle timeout
-1113/// if it has no connections, an empty inbox, and no other senders than the one stored
-1114/// in the endpoint map exist.
-1115#[derive(Debug)]
-1116pub(super) struct EndpointStateHandle {
-1117 /// Sender for the channel into the [`EndpointStateActor`].
-1118 ///
-1119 /// This is a [`GuardedSender`], from which we can get a sender but only if the receiver
-1120 /// hasn't been closed.
-1121 pub(super) sender: GuardedSender<EndpointStateMessage>,
-1122 _task: AbortOnDropHandle<()>,
-1123}
-1124
-1125/// Information about a holepunch attempt.
-1126#[derive(Debug)]
-1127struct HolepunchAttempt {
-1128 when: Instant,
-1129 /// The set of local addresses which could take part in holepunching.
-1130 ///
-1131 /// This does not mean every address here participated in the holepunching. E.g. we
-1132 /// could have tried only a sub-set of the addresses because a previous attempt already
-1133 /// covered part of the range.
-1134 ///
-1135 /// We do not store this as a [`DirectAddr`] because this is checked for equality and we
-1136 /// do not want to compare the sources of these addresses.
-1137 local_addrs: BTreeSet<SocketAddr>,
-1138 /// The set of remote addresses which could take part in holepunching.
-1139 ///
-1140 /// Like `local_addrs` we may not have used them.
-1141 remote_addrs: BTreeSet<SocketAddr>,
-1142}
-1143
-1144/// Newtype to track Connections.
-1145///
-1146/// The wrapped value is the [`quinn::Connection::stable_id`] value, and is thus only valid
-1147/// for active connections.
-1148#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
-1149struct ConnId(usize);
-1150
-1151/// State about one connection.
-1152#[derive(Debug)]
-1153struct ConnectionState {
-1154 /// Weak handle to the connection.
-1155 handle: WeakConnectionHandle,
-1156 /// The information we publish to users about the paths used in this connection.
-1157 pub_open_paths: Watchable<PathAddrList>,
-1158 /// The paths that exist on this connection.
-1159 ///
-1160 /// This could be in any state, e.g. while still validating the path or already closed
-1161 /// but not yet fully removed from the connection. This exists as long as Quinn knows
-1162 /// about the [`PathId`].
-1163 paths: FxHashMap<PathId, transports::Addr>,
-1164 /// The open paths on this connection, a subset of [`Self::paths`].
-1165 open_paths: FxHashMap<PathId, transports::Addr>,
-1166 /// Reverse map of [`Self::paths].
-1167 path_ids: FxHashMap<transports::Addr, PathId>,
-1168}
-1169
-1170impl ConnectionState {
-1171 /// Tracks a path for the connection.
-1172 fn add_path(&mut self, remote: transports::Addr, path_id: PathId) {
-1173 self.paths.insert(path_id, remote.clone());
-1174 self.path_ids.insert(remote, path_id);
-1175 }
-1176
-1177 /// Tracks an open path for the connection.
-1178 fn add_open_path(&mut self, remote: transports::Addr, path_id: PathId) {
-1179 self.paths.insert(path_id, remote.clone());
-1180 self.open_paths.insert(path_id, remote.clone());
-1181 self.path_ids.insert(remote, path_id);
+1092 /// Returns `Ok` immediately if the provided address list is non-empy or we have are other known paths.
+1093 /// Otherwise returns `Ok` once discovery produces a result, or the discovery error if discovery fails
+1094 /// or produces no results,
+1095 #[debug("ResolveRemote(..)")]
+1096 ResolveRemote(
+1097 BTreeSet<TransportAddr>,
+1098 oneshot::Sender<Result<(), DiscoveryError>>,
+1099 ),
+1100 /// Returns the current latency to the remote endpoint.
+1101 ///
+1102 /// TODO: This is more of a placeholder message currently. Check MagicSock::latency.
+1103 #[debug("Latency(..)")]
+1104 Latency(oneshot::Sender<Option<Duration>>),
+1105}
+1106
+1107/// A handle to a [`EndpointStateActor`].
+1108///
+1109/// Dropping this will stop the actor. The actor will also stop after an idle timeout
+1110/// if it has no connections, an empty inbox, and no other senders than the one stored
+1111/// in the endpoint map exist.
+1112#[derive(Debug)]
+1113pub(super) struct EndpointStateHandle {
+1114 /// Sender for the channel into the [`EndpointStateActor`].
+1115 ///
+1116 /// This is a [`GuardedSender`], from which we can get a sender but only if the receiver
+1117 /// hasn't been closed.
+1118 pub(super) sender: GuardedSender<EndpointStateMessage>,
+1119 _task: AbortOnDropHandle<()>,
+1120}
+1121
+1122/// Information about a holepunch attempt.
+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_addrs: BTreeSet<SocketAddr>,
+1135 /// The set of remote addresses which could take part in holepunching.
+1136 ///
+1137 /// Like `local_addrs` we may not have used them.
+1138 remote_addrs: 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, 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
+1180 self.update_pub_path_info();
+1181 }
1182
-1183 self.update_pub_path_info();
-1184 }
-1185
-1186 /// Completely removes a path from this connection.
-1187 fn remove_path(&mut self, path_id: &PathId) {
-1188 if let Some(addr) = self.paths.remove(path_id) {
-1189 self.path_ids.remove(&addr);
-1190 }
-1191 self.open_paths.remove(path_id);
-1192 }
-1193
-1194 /// Removes the path from the open paths.
-1195 fn remove_open_path(&mut self, path_id: &PathId) {
-1196 self.open_paths.remove(path_id);
+1183 /// Completely removes a path from this connection.
+1184 fn remove_path(&mut self, path_id: &PathId) {
+1185 if let Some(addr) = self.paths.remove(path_id) {
+1186 self.path_ids.remove(&addr);
+1187 }
+1188 self.open_paths.remove(path_id);
+1189 }
+1190
+1191 /// Removes the path from the open paths.
+1192 fn remove_open_path(&mut self, path_id: &PathId) {
+1193 self.open_paths.remove(path_id);
+1194
+1195 self.update_pub_path_info();
+1196 }
1197
-1198 self.update_pub_path_info();
-1199 }
-1200
-1201 /// Sets the new [`PathInfo`] structs for the public [`Connection`].
-1202 ///
-1203 /// [`Connection`]: crate::endpoint::Connection
-1204 fn update_pub_path_info(&self) {
-1205 let new = self
-1206 .open_paths
-1207 .iter()
-1208 .map(|(path_id, remote)| {
-1209 let remote = TransportAddr::from(remote.clone());
-1210 (remote, *path_id)
-1211 })
-1212 .collect::<PathAddrList>();
-1213
-1214 self.pub_open_paths.set(new).ok();
-1215 }
-1216}
-1217
-1218/// Watcher for the open paths and selected transmission path in a connection.
-1219///
-1220/// This is stored in the [`Connection`], and the watchables are set from within the endpoint state actor.
-1221///
-1222/// Internally, this contains a boxed-mapped-joined watcher over the open paths in the connection and the
-1223/// selected path to the remote endpoint. The watcher is boxed because the mapped-joined watcher with
-1224/// `SmallVec<PathInfoList>` has a size of over 800 bytes, which we don't want to put upon the [`Connection`].
-1225///
-1226/// [`Connection`]: crate::endpoint::Connection
-1227#[derive(Clone, derive_more::Debug)]
-1228#[debug("PathsWatcher")]
-1229#[allow(clippy::type_complexity)]
-1230pub(crate) struct PathsWatcher(
-1231 Box<
-1232 n0_watcher::Map<
-1233 n0_watcher::Tuple<
-1234 n0_watcher::Direct<PathAddrList>,
-1235 n0_watcher::Direct<Option<transports::Addr>>,
-1236 >,
-1237 PathInfoList,
-1238 >,
-1239 >,
-1240);
+1198 /// Sets the new [`PathInfo`] structs for the public [`Connection`].
+1199 ///
+1200 /// [`Connection`]: crate::endpoint::Connection
+1201 fn update_pub_path_info(&self) {
+1202 let new = self
+1203 .open_paths
+1204 .iter()
+1205 .map(|(path_id, remote)| {
+1206 let remote = TransportAddr::from(remote.clone());
+1207 (remote, *path_id)
+1208 })
+1209 .collect::<PathAddrList>();
+1210
+1211 self.pub_open_paths.set(new).ok();
+1212 }
+1213}
+1214
+1215/// Watcher for the open paths and selected transmission path in a connection.
+1216///
+1217/// This is stored in the [`Connection`], and the watchables are set from within the endpoint state actor.
+1218///
+1219/// Internally, this contains a boxed-mapped-joined watcher over the open paths in the connection and the
+1220/// selected path to the remote endpoint. The watcher is boxed because the mapped-joined watcher with
+1221/// `SmallVec<PathInfoList>` has a size of over 800 bytes, which we don't want to put upon the [`Connection`].
+1222///
+1223/// [`Connection`]: crate::endpoint::Connection
+1224#[derive(Clone, derive_more::Debug)]
+1225#[debug("PathsWatcher")]
+1226#[allow(clippy::type_complexity)]
+1227pub(crate) struct PathsWatcher(
+1228 Box<
+1229 n0_watcher::Map<
+1230 n0_watcher::Tuple<
+1231 n0_watcher::Direct<PathAddrList>,
+1232 n0_watcher::Direct<Option<transports::Addr>>,
+1233 >,
+1234 PathInfoList,
+1235 >,
+1236 >,
+1237);
+1238
+1239impl n0_watcher::Watcher for PathsWatcher {
+1240 type Value = PathInfoList;
1241
-1242impl n0_watcher::Watcher for PathsWatcher {
-1243 type Value = PathInfoList;
-1244
-1245 fn update(&mut self) -> bool {
-1246 self.0.update()
-1247 }
-1248
-1249 fn peek(&self) -> &Self::Value {
-1250 self.0.peek()
-1251 }
-1252
-1253 fn is_connected(&self) -> bool {
-1254 self.0.is_connected()
-1255 }
-1256
-1257 fn poll_updated(
-1258 &mut self,
-1259 cx: &mut std::task::Context<'_>,
-1260 ) -> Poll<Result<(), n0_watcher::Disconnected>> {
-1261 self.0.poll_updated(cx)
-1262 }
-1263}
-1264
-1265impl PathsWatcher {
-1266 fn new(
-1267 open_paths: n0_watcher::Direct<PathAddrList>,
-1268 selected_path: n0_watcher::Direct<Option<transports::Addr>>,
-1269 conn_handle: WeakConnectionHandle,
-1270 ) -> Self {
-1271 Self(Box::new(open_paths.or(selected_path).map(
-1272 move |(open_paths, selected_path)| {
-1273 let selected_path: Option<TransportAddr> = selected_path.map(Into::into);
-1274 let Some(conn) = conn_handle.upgrade() else {
-1275 return PathInfoList(Default::default());
-1276 };
-1277 let list = open_paths
-1278 .into_iter()
-1279 .flat_map(move |(remote, path_id)| {
-1280 PathInfo::new(path_id, &conn, remote, selected_path.as_ref())
-1281 })
-1282 .collect();
-1283 PathInfoList(list)
-1284 },
-1285 )))
-1286 }
-1287}
-1288
-1289/// List of [`PathInfo`] for the network paths of a [`Connection`].
-1290///
-1291/// This struct implements [`IntoIterator`].
-1292///
-1293/// [`Connection`]: crate::endpoint::Connection
-1294#[derive(derive_more::Debug, derive_more::IntoIterator, Eq, PartialEq, Clone)]
-1295#[debug("{_0:?}")]
-1296pub struct PathInfoList(SmallVec<[PathInfo; 4]>);
-1297
-1298impl PathInfoList {
-1299 /// Returns an iterator over the path infos.
-1300 pub fn iter(&self) -> impl Iterator<Item = &PathInfo> {
-1301 self.0.iter()
-1302 }
-1303
-1304 /// Returns `true` if the list is empty.
-1305 pub fn is_empty(&self) -> bool {
-1306 self.0.is_empty()
-1307 }
-1308
-1309 /// Returns the number of paths.
-1310 pub fn len(&self) -> usize {
-1311 self.0.len()
-1312 }
-1313}
-1314
-1315/// Information about a network path used by a [`Connection`].
-1316///
-1317/// [`Connection`]: crate::endpoint::Connection
-1318#[derive(derive_more::Debug, Clone)]
-1319pub struct PathInfo {
-1320 path_id: PathId,
-1321 #[debug(skip)]
-1322 handle: WeakConnectionHandle,
-1323 stats: PathStats,
-1324 remote: TransportAddr,
-1325 is_selected: bool,
-1326}
-1327
-1328impl PartialEq for PathInfo {
-1329 fn eq(&self, other: &Self) -> bool {
-1330 self.path_id == other.path_id
-1331 && self.remote == other.remote
-1332 && self.is_selected == other.is_selected
-1333 }
-1334}
-1335
-1336impl Eq for PathInfo {}
-1337
-1338impl PathInfo {
-1339 fn new(
-1340 path_id: PathId,
-1341 conn: &quinn::Connection,
-1342 remote: TransportAddr,
-1343 selected_path: Option<&TransportAddr>,
-1344 ) -> Option<Self> {
-1345 let stats = conn.path_stats(path_id)?;
-1346 Some(Self {
-1347 path_id,
-1348 handle: conn.weak_handle(),
-1349 is_selected: Some(&remote) == selected_path,
-1350 remote,
-1351 stats,
-1352 })
-1353 }
-1354
-1355 /// The remote transport address used by this network path.
-1356 pub fn remote_addr(&self) -> &TransportAddr {
-1357 &self.remote
-1358 }
-1359
-1360 /// Returns `true` if this path is currently the main transmission path for this [`Connection`].
-1361 ///
-1362 /// [`Connection`]: crate::endpoint::Connection
-1363 pub fn is_selected(&self) -> bool {
-1364 self.is_selected
-1365 }
-1366
-1367 /// Whether this is an IP transport address.
-1368 pub fn is_ip(&self) -> bool {
-1369 self.remote.is_ip()
-1370 }
-1371
-1372 /// Whether this is a transport address via a relay server.
-1373 pub fn is_relay(&self) -> bool {
-1374 self.remote.is_relay()
-1375 }
-1376
-1377 /// Returns stats for this transmission path.
-1378 pub fn stats(&self) -> PathStats {
-1379 self.handle
-1380 .upgrade()
-1381 .and_then(|conn| conn.path_stats(self.path_id))
-1382 .unwrap_or(self.stats)
-1383 }
-1384
-1385 /// Current best estimate of this paths's latency (round-trip-time)
-1386 pub fn rtt(&self) -> Duration {
-1387 self.stats().rtt
-1388 }
-1389}
-1390
-1391/// Poll a future once, like n0_future::future::poll_once but sync.
-1392fn now_or_never<T, F: Future<Output = T>>(fut: F) -> Option<T> {
-1393 let fut = std::pin::pin!(fut);
-1394 match fut.poll(&mut std::task::Context::from_waker(std::task::Waker::noop())) {
-1395 Poll::Ready(res) => Some(res),
-1396 Poll::Pending => None,
-1397 }
-1398}
-1399
-1400/// Future that resolves to the `conn_id` once a connection is closed.
-1401///
-1402/// This uses [`quinn::Connection::on_closed`], which does not keep the connection alive
-1403/// while awaiting the future.
-1404struct OnClosed {
-1405 conn_id: ConnId,
-1406 inner: quinn::OnClosed,
-1407}
-1408
-1409impl OnClosed {
-1410 fn new(conn: &quinn::Connection) -> Self {
-1411 Self {
-1412 conn_id: ConnId(conn.stable_id()),
-1413 inner: conn.on_closed(),
-1414 }
-1415 }
-1416}
+1242 fn update(&mut self) -> bool {
+1243 self.0.update()
+1244 }
+1245
+1246 fn peek(&self) -> &Self::Value {
+1247 self.0.peek()
+1248 }
+1249
+1250 fn is_connected(&self) -> bool {
+1251 self.0.is_connected()
+1252 }
+1253
+1254 fn poll_updated(
+1255 &mut self,
+1256 cx: &mut std::task::Context<'_>,
+1257 ) -> Poll<Result<(), n0_watcher::Disconnected>> {
+1258 self.0.poll_updated(cx)
+1259 }
+1260}
+1261
+1262impl PathsWatcher {
+1263 fn new(
+1264 open_paths: n0_watcher::Direct<PathAddrList>,
+1265 selected_path: n0_watcher::Direct<Option<transports::Addr>>,
+1266 conn_handle: WeakConnectionHandle,
+1267 ) -> Self {
+1268 Self(Box::new(open_paths.or(selected_path).map(
+1269 move |(open_paths, selected_path)| {
+1270 let selected_path: Option<TransportAddr> = selected_path.map(Into::into);
+1271 let Some(conn) = conn_handle.upgrade() else {
+1272 return PathInfoList(Default::default());
+1273 };
+1274 let list = open_paths
+1275 .into_iter()
+1276 .flat_map(move |(remote, path_id)| {
+1277 PathInfo::new(path_id, &conn, remote, selected_path.as_ref())
+1278 })
+1279 .collect();
+1280 PathInfoList(list)
+1281 },
+1282 )))
+1283 }
+1284}
+1285
+1286/// List of [`PathInfo`] for the network paths of a [`Connection`].
+1287///
+1288/// This struct implements [`IntoIterator`].
+1289///
+1290/// [`Connection`]: crate::endpoint::Connection
+1291#[derive(derive_more::Debug, derive_more::IntoIterator, Eq, PartialEq, Clone)]
+1292#[debug("{_0:?}")]
+1293pub struct PathInfoList(SmallVec<[PathInfo; 4]>);
+1294
+1295impl PathInfoList {
+1296 /// Returns an iterator over the path infos.
+1297 pub fn iter(&self) -> impl Iterator<Item = &PathInfo> {
+1298 self.0.iter()
+1299 }
+1300
+1301 /// Returns `true` if the list is empty.
+1302 pub fn is_empty(&self) -> bool {
+1303 self.0.is_empty()
+1304 }
+1305
+1306 /// Returns the number of paths.
+1307 pub fn len(&self) -> usize {
+1308 self.0.len()
+1309 }
+1310}
+1311
+1312/// Information about a network path used by a [`Connection`].
+1313///
+1314/// [`Connection`]: crate::endpoint::Connection
+1315#[derive(derive_more::Debug, Clone)]
+1316pub struct PathInfo {
+1317 path_id: PathId,
+1318 #[debug(skip)]
+1319 handle: WeakConnectionHandle,
+1320 stats: PathStats,
+1321 remote: TransportAddr,
+1322 is_selected: bool,
+1323}
+1324
+1325impl PartialEq for PathInfo {
+1326 fn eq(&self, other: &Self) -> bool {
+1327 self.path_id == other.path_id
+1328 && self.remote == other.remote
+1329 && self.is_selected == other.is_selected
+1330 }
+1331}
+1332
+1333impl Eq for PathInfo {}
+1334
+1335impl PathInfo {
+1336 fn new(
+1337 path_id: PathId,
+1338 conn: &quinn::Connection,
+1339 remote: TransportAddr,
+1340 selected_path: Option<&TransportAddr>,
+1341 ) -> Option<Self> {
+1342 let stats = conn.path_stats(path_id)?;
+1343 Some(Self {
+1344 path_id,
+1345 handle: conn.weak_handle(),
+1346 is_selected: Some(&remote) == selected_path,
+1347 remote,
+1348 stats,
+1349 })
+1350 }
+1351
+1352 /// The remote transport address used by this network path.
+1353 pub fn remote_addr(&self) -> &TransportAddr {
+1354 &self.remote
+1355 }
+1356
+1357 /// Returns `true` if this path is currently the main transmission path for this [`Connection`].
+1358 ///
+1359 /// [`Connection`]: crate::endpoint::Connection
+1360 pub fn is_selected(&self) -> bool {
+1361 self.is_selected
+1362 }
+1363
+1364 /// Whether this is an IP transport address.
+1365 pub fn is_ip(&self) -> bool {
+1366 self.remote.is_ip()
+1367 }
+1368
+1369 /// Whether this is a transport address via a relay server.
+1370 pub fn is_relay(&self) -> bool {
+1371 self.remote.is_relay()
+1372 }
+1373
+1374 /// Returns stats for this transmission path.
+1375 pub fn stats(&self) -> PathStats {
+1376 self.handle
+1377 .upgrade()
+1378 .and_then(|conn| conn.path_stats(self.path_id))
+1379 .unwrap_or(self.stats)
+1380 }
+1381
+1382 /// Current best estimate of this paths's latency (round-trip-time)
+1383 pub fn rtt(&self) -> Duration {
+1384 self.stats().rtt
+1385 }
+1386}
+1387
+1388/// Poll a future once, like n0_future::future::poll_once but sync.
+1389fn now_or_never<T, F: Future<Output = T>>(fut: F) -> Option<T> {
+1390 let fut = std::pin::pin!(fut);
+1391 match fut.poll(&mut std::task::Context::from_waker(std::task::Waker::noop())) {
+1392 Poll::Ready(res) => Some(res),
+1393 Poll::Pending => None,
+1394 }
+1395}
+1396
+1397/// Future that resolves to the `conn_id` once a connection is closed.
+1398///
+1399/// This uses [`quinn::Connection::on_closed`], which does not keep the connection alive
+1400/// while awaiting the future.
+1401struct OnClosed {
+1402 conn_id: ConnId,
+1403 inner: quinn::OnClosed,
+1404}
+1405
+1406impl OnClosed {
+1407 fn new(conn: &quinn::Connection) -> Self {
+1408 Self {
+1409 conn_id: ConnId(conn.stable_id()),
+1410 inner: conn.on_closed(),
+1411 }
+1412 }
+1413}
+1414
+1415impl Future for OnClosed {
+1416 type Output = ConnId;
1417
-1418impl Future for OnClosed {
-1419 type Output = ConnId;
-1420
-1421 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
-1422 let (_close_reason, _stats) = std::task::ready!(Pin::new(&mut self.inner).poll(cx));
-1423 Poll::Ready(self.conn_id)
-1424 }
-1425}
-1426
-1427/// Converts an interator of [`TransportAddr'] into an iterator of [`transports::Addr`].
-1428fn to_transports_addr(
-1429 endpoint_id: EndpointId,
-1430 addrs: impl IntoIterator<Item = TransportAddr>,
-1431) -> impl Iterator<Item = transports::Addr> {
-1432 addrs.into_iter().filter_map(move |addr| match addr {
-1433 TransportAddr::Relay(relay_url) => Some(transports::Addr::from((relay_url, endpoint_id))),
-1434 TransportAddr::Ip(sockaddr) => Some(transports::Addr::from(sockaddr)),
-1435 _ => {
-1436 warn!(?addr, "Unsupported TransportAddr");
-1437 None
-1438 }
-1439 })
-1440}
\ No newline at end of file
+1418 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
+1419 let (_close_reason, _stats) = std::task::ready!(Pin::new(&mut self.inner).poll(cx));
+1420 Poll::Ready(self.conn_id)
+1421 }
+1422}
+1423
+1424/// Converts an iterator of [`TransportAddr'] into an iterator of [`transports::Addr`].
+1425fn to_transports_addr(
+1426 endpoint_id: EndpointId,
+1427 addrs: impl IntoIterator<Item = TransportAddr>,
+1428) -> impl Iterator<Item = transports::Addr> {
+1429 addrs.into_iter().filter_map(move |addr| match addr {
+1430 TransportAddr::Relay(relay_url) => Some(transports::Addr::from((relay_url, endpoint_id))),
+1431 TransportAddr::Ip(sockaddr) => Some(transports::Addr::from(sockaddr)),
+1432 _ => {
+1433 warn!(?addr, "Unsupported TransportAddr");
+1434 None
+1435 }
+1436 })
+1437}
\ No newline at end of file
diff --git a/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state/path_state.rs.html b/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state/path_state.rs.html
index a47e44b277..5a3a367891 100644
--- a/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state/path_state.rs.html
+++ b/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state/path_state.rs.html
@@ -117,7 +117,7 @@
117 self.paths.keys()
118 }
119
-120 /// Replies to all pending requests from [`EndpointStateMessage::ResolveRemote`].
+120 /// Replies to all pending resolve requests.
121 ///
122 /// This is a no-op if no requests are queued. Replies `Ok` if we have any known paths,
123 /// otherwise with the provided `discovery_error` or with [`DiscoveryError::NoResults`].
@@ -139,17 +139,14 @@
139/// The state of a single path to the remote endpoint.
140///
141/// Each path is identified by the destination [`transports::Addr`] and they are stored in
-142/// the [`EndpointStateActor::paths`] map.
-143///
-144/// [`transports::Addr`]: super::transports::Addr
-145/// [`EndpointStateActor::paths`]: super::endpoint_state::EndpointStateActor
-146#[derive(Debug, Default)]
-147pub(super) struct PathState {
-148 /// How we learned about this path, and when.
-149 ///
-150 /// We keep track of only the latest [`Instant`] for each [`Source`], keeping the size
-151 /// of the map of sources down to one entry per type of source.
-152 pub(super) sources: HashMap<Source, Instant>,
-153 /// The last ping sent on this path.
-154 pub(super) ping_sent: Option<TransactionId>,
-155}
\ No newline at end of file
+142/// the [`EndpointPathState::paths`] map.
+143#[derive(Debug, Default)]
+144pub(super) struct PathState {
+145 /// How we learned about this path, and when.
+146 ///
+147 /// We keep track of only the latest [`Instant`] for each [`Source`], keeping the size
+148 /// of the map of sources down to one entry per type of source.
+149 pub(super) sources: HashMap<Source, Instant>,
+150 /// The last ping sent on this path.
+151 pub(super) ping_sent: Option<TransactionId>,
+152}
\ No newline at end of file
PathInfo
pub struct PathInfo { /* private fields */ }Expand description
Information about a network path used by a Connection.
Implementations§
Source§impl PathInfo
impl PathInfo
Sourcepub fn remote_addr(&self) -> &TransportAddr
pub fn remote_addr(&self) -> &TransportAddr
The remote transport address used by this network path.
+Sourcepub fn is_selected(&self) -> bool
pub fn is_selected(&self) -> bool
Returns true if this path is currently the main transmission path for this Connection.
Trait Implementations§
impl Eq for PathInfo
Auto Trait Implementations§
impl Freeze for PathInfo
impl RefUnwindSafe for PathInfo
impl Send for PathInfo
impl Sync for PathInfo
impl Unpin for PathInfo
impl UnwindSafe for PathInfo
Blanket Implementations§
§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
fn implicit(
diff --git a/pr/3645/docs/iroh/endpoint/struct.PathInfoList.html b/pr/3645/docs/iroh/endpoint/struct.PathInfoList.html
index 330e5c6ae1..404a8509cb 100644
--- a/pr/3645/docs/iroh/endpoint/struct.PathInfoList.html
+++ b/pr/3645/docs/iroh/endpoint/struct.PathInfoList.html
@@ -1,11 +1,11 @@
-PathInfoList in iroh::endpoint - Rust PathInfoList
pub struct PathInfoList(/* private fields */);
Expand description
List of PathInfo for the network paths of a Connection.
+PathInfoList in iroh::endpoint - Rust PathInfoList
pub struct PathInfoList(/* private fields */);
Expand description
List of PathInfo for the network paths of a Connection.
This struct implements IntoIterator.
-Implementations§
Trait Implementations§
Source§impl Clone for PathInfoList
Source§fn clone(&self) -> PathInfoList
Returns a duplicate of the value. Read more1.0.0 · Source§fn clone_from(&mut self, source: &Self)
Performs copy-assignment from source. Read moreSource§impl Debug for PathInfoList
Source§impl IntoIterator for PathInfoList
Source§impl PartialEq for PathInfoList
Source§impl Eq for PathInfoList
Source§impl StructuralPartialEq for PathInfoList
Auto Trait Implementations§
§impl Freeze for PathInfoList
§impl RefUnwindSafe for PathInfoList
§impl Send for PathInfoList
§impl Sync for PathInfoList
§impl Unpin for PathInfoList
§impl UnwindSafe for PathInfoList
Blanket Implementations§
Implementations§
Trait Implementations§
Source§impl Clone for PathInfoList
Source§fn clone(&self) -> PathInfoList
Returns a duplicate of the value. Read more1.0.0 · Source§fn clone_from(&mut self, source: &Self)
Performs copy-assignment from source. Read moreSource§impl Debug for PathInfoList
Source§impl IntoIterator for PathInfoList
Source§impl PartialEq for PathInfoList
Source§impl Eq for PathInfoList
Source§impl StructuralPartialEq for PathInfoList
Auto Trait Implementations§
§impl Freeze for PathInfoList
§impl RefUnwindSafe for PathInfoList
§impl Send for PathInfoList
§impl Sync for PathInfoList
§impl Unpin for PathInfoList
§impl UnwindSafe for PathInfoList
Blanket Implementations§
§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
§fn implicit(
diff --git a/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state.rs.html b/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state.rs.html
index 383b3f0cc2..cd0545f907 100644
--- a/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state.rs.html
+++ b/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state.rs.html
@@ -729,712 +729,709 @@
729 let Some(relay_addr) = self
730 .paths
731 .addrs()
-732 .filter_map(|addr| match addr {
-733 transports::Addr::Ip(_) => None,
-734 transports::Addr::Relay(_, _) => Some(addr),
-735 })
-736 .next()
-737 .cloned()
-738 else {
-739 warn!("holepunching requested but have no relay address");
-740 return;
-741 };
-742 let remote_addrs = self.remote_hp_addrs();
-743
-744 // Send DISCO Ping messages to all CallMeMaybe-advertised paths.
-745 for dst in remote_addrs.iter() {
-746 let msg = disco::Ping::new(self.local_endpoint_id);
-747 event!(
-748 target: "iroh::_events::ping::sent",
-749 Level::DEBUG,
-750 remote = %self.endpoint_id.fmt_short(),
-751 ?dst,
-752 txn = ?msg.tx_id,
-753 );
-754 let addr = transports::Addr::Ip(*dst);
-755 self.paths.disco_ping_sent(addr.clone(), msg.tx_id);
-756 self.send_disco_message(addr, disco::Message::Ping(msg))
-757 .await;
-758 }
-759
-760 // Send the DISCO CallMeMaybe message over the relay.
-761 let my_numbers: Vec<SocketAddr> = self
-762 .local_addrs
-763 .get()
-764 .iter()
-765 .map(|daddr| daddr.addr)
-766 .collect();
-767 let local_addrs: BTreeSet<SocketAddr> = my_numbers.iter().copied().collect();
-768 let msg = disco::CallMeMaybe { my_numbers };
-769 event!(
-770 target: "iroh::_events::call_me_maybe::sent",
-771 Level::DEBUG,
-772 remote = %self.endpoint_id.fmt_short(),
-773 dst = ?relay_addr,
-774 my_numbers = ?msg.my_numbers,
-775 );
-776 self.send_disco_message(relay_addr, disco::Message::CallMeMaybe(msg))
-777 .await;
-778
-779 self.last_holepunch = Some(HolepunchAttempt {
-780 when: Instant::now(),
-781 local_addrs,
-782 remote_addrs,
-783 });
-784 }
-785
-786 /// Sends a DISCO message to the remote endpoint this actor manages.
-787 #[instrument(skip(self), fields(remote = %self.endpoint_id.fmt_short()))]
-788 async fn send_disco_message(&self, dst: transports::Addr, msg: disco::Message) {
-789 let pkt = self.disco.encode_and_seal(self.endpoint_id, &msg);
-790 let transmit = transports::OwnedTransmit {
-791 ecn: None,
-792 contents: pkt,
-793 segment_size: None,
-794 };
-795 let counter = match dst {
-796 transports::Addr::Ip(_) => &self.metrics.send_disco_udp,
-797 transports::Addr::Relay(_, _) => &self.metrics.send_disco_relay,
-798 };
-799 match self.send_datagram(dst, transmit).await {
-800 Ok(()) => {
-801 trace!("sent");
-802 counter.inc();
+732 .filter(|addr| addr.is_relay())
+733 .next()
+734 .cloned()
+735 else {
+736 warn!("holepunching requested but have no relay address");
+737 return;
+738 };
+739 let remote_addrs = self.remote_hp_addrs();
+740
+741 // Send DISCO Ping messages to all CallMeMaybe-advertised paths.
+742 for dst in remote_addrs.iter() {
+743 let msg = disco::Ping::new(self.local_endpoint_id);
+744 event!(
+745 target: "iroh::_events::ping::sent",
+746 Level::DEBUG,
+747 remote = %self.endpoint_id.fmt_short(),
+748 ?dst,
+749 txn = ?msg.tx_id,
+750 );
+751 let addr = transports::Addr::Ip(*dst);
+752 self.paths.disco_ping_sent(addr.clone(), msg.tx_id);
+753 self.send_disco_message(addr, disco::Message::Ping(msg))
+754 .await;
+755 }
+756
+757 // Send the DISCO CallMeMaybe message over the relay.
+758 let my_numbers: Vec<SocketAddr> = self
+759 .local_addrs
+760 .get()
+761 .iter()
+762 .map(|daddr| daddr.addr)
+763 .collect();
+764 let local_addrs: BTreeSet<SocketAddr> = my_numbers.iter().copied().collect();
+765 let msg = disco::CallMeMaybe { my_numbers };
+766 event!(
+767 target: "iroh::_events::call_me_maybe::sent",
+768 Level::DEBUG,
+769 remote = %self.endpoint_id.fmt_short(),
+770 dst = ?relay_addr,
+771 my_numbers = ?msg.my_numbers,
+772 );
+773 self.send_disco_message(relay_addr, disco::Message::CallMeMaybe(msg))
+774 .await;
+775
+776 self.last_holepunch = Some(HolepunchAttempt {
+777 when: Instant::now(),
+778 local_addrs,
+779 remote_addrs,
+780 });
+781 }
+782
+783 /// Sends a DISCO message to the remote endpoint this actor manages.
+784 #[instrument(skip(self), fields(remote = %self.endpoint_id.fmt_short()))]
+785 async fn send_disco_message(&self, dst: transports::Addr, msg: disco::Message) {
+786 let pkt = self.disco.encode_and_seal(self.endpoint_id, &msg);
+787 let transmit = transports::OwnedTransmit {
+788 ecn: None,
+789 contents: pkt,
+790 segment_size: None,
+791 };
+792 let counter = match dst {
+793 transports::Addr::Ip(_) => &self.metrics.send_disco_udp,
+794 transports::Addr::Relay(_, _) => &self.metrics.send_disco_relay,
+795 };
+796 match self.send_datagram(dst, transmit).await {
+797 Ok(()) => {
+798 trace!("sent");
+799 counter.inc();
+800 }
+801 Err(err) => {
+802 warn!("failed to send disco message: {err:#}");
803 }
-804 Err(err) => {
-805 warn!("failed to send disco message: {err:#}");
-806 }
-807 }
-808 }
-809
-810 /// Open the path on all connections.
-811 ///
-812 /// This goes through all the connections for which we are the client, and makes sure
-813 /// the path exists, or opens it.
-814 #[instrument(level = "warn", skip(self))]
-815 fn open_path(&mut self, open_addr: &transports::Addr) {
-816 let path_status = match open_addr {
-817 transports::Addr::Ip(_) => PathStatus::Available,
-818 transports::Addr::Relay(_, _) => PathStatus::Backup,
-819 };
-820 let quic_addr = match &open_addr {
-821 transports::Addr::Ip(socket_addr) => *socket_addr,
-822 transports::Addr::Relay(relay_url, eid) => self
-823 .relay_mapped_addrs
-824 .get(&(relay_url.clone(), *eid))
-825 .private_socket_addr(),
-826 };
-827
-828 for (conn_id, conn_state) in self.connections.iter_mut() {
-829 if conn_state.path_ids.contains_key(open_addr) {
+804 }
+805 }
+806
+807 /// Open the path on all connections.
+808 ///
+809 /// This goes through all the connections for which we are the client, and makes sure
+810 /// the path exists, or opens it.
+811 #[instrument(level = "warn", skip(self))]
+812 fn open_path(&mut self, open_addr: &transports::Addr) {
+813 let path_status = match open_addr {
+814 transports::Addr::Ip(_) => PathStatus::Available,
+815 transports::Addr::Relay(_, _) => PathStatus::Backup,
+816 };
+817 let quic_addr = match &open_addr {
+818 transports::Addr::Ip(socket_addr) => *socket_addr,
+819 transports::Addr::Relay(relay_url, eid) => self
+820 .relay_mapped_addrs
+821 .get(&(relay_url.clone(), *eid))
+822 .private_socket_addr(),
+823 };
+824
+825 for (conn_id, conn_state) in self.connections.iter_mut() {
+826 if conn_state.path_ids.contains_key(open_addr) {
+827 continue;
+828 }
+829 let Some(conn) = conn_state.handle.upgrade() else {
830 continue;
-831 }
-832 let Some(conn) = conn_state.handle.upgrade() else {
+831 };
+832 if conn.side().is_server() {
833 continue;
-834 };
-835 if conn.side().is_server() {
-836 continue;
-837 }
-838 let fut = conn.open_path_ensure(quic_addr, path_status);
-839 match fut.path_id() {
-840 Some(path_id) => {
-841 trace!(?conn_id, ?path_id, "opening new path");
-842 conn_state.add_path(open_addr.clone(), path_id);
-843 }
-844 None => {
-845 let ret = now_or_never(fut);
-846 match ret {
-847 Some(Err(PathError::RemoteCidsExhausted)) => {
-848 self.scheduled_open_path =
-849 Some(Instant::now() + Duration::from_millis(333));
-850 self.pending_open_paths.push_back(open_addr.clone());
-851 trace!(?open_addr, "scheduling open_path");
-852 }
-853 _ => warn!(?ret, "Opening path failed"),
-854 }
-855 }
-856 }
-857 }
-858 }
-859
-860 #[instrument(skip(self))]
-861 fn handle_path_event(
-862 &mut self,
-863 conn_id: ConnId,
-864 event: Result<PathEvent, BroadcastStreamRecvError>,
-865 ) {
-866 let Ok(event) = event else {
-867 warn!("missed a PathEvent, EndpointStateActor lagging");
-868 // TODO: Is it possible to recover using the sync APIs to figure out what the
-869 // state of the connection and it's paths are?
-870 return;
-871 };
-872 let Some(conn_state) = self.connections.get_mut(&conn_id) else {
-873 trace!("event for removed connection");
-874 return;
-875 };
-876 let Some(conn) = conn_state.handle.upgrade() else {
-877 trace!("event for closed connection");
-878 return;
-879 };
-880 trace!("path event");
-881 match event {
-882 PathEvent::Opened { id: path_id } => {
-883 let Some(path) = conn.path(path_id) else {
-884 trace!("path open event for unknown path");
-885 return;
-886 };
-887 // TODO: We configure this as defaults when we setup the endpoint, do we
-888 // really need to duplicate this?
-889 path.set_keep_alive_interval(Some(HEARTBEAT_INTERVAL)).ok();
-890 path.set_max_idle_timeout(Some(PATH_MAX_IDLE_TIMEOUT)).ok();
-891
-892 if let Ok(socketaddr) = path.remote_address()
-893 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr)
-894 {
-895 event!(
-896 target: "iroh::_events::path::open",
-897 Level::DEBUG,
-898 remote = %self.endpoint_id.fmt_short(),
-899 ?path_remote,
-900 ?conn_id,
-901 ?path_id,
-902 );
-903 conn_state.add_open_path(path_remote.clone(), path_id);
-904 self.paths
-905 .insert(path_remote, Source::Connection { _0: Private });
-906 }
-907
-908 self.select_path();
-909 }
-910 PathEvent::Abandoned { id, path_stats } => {
-911 trace!(?path_stats, "path abandoned");
-912 // This is the last event for this path.
-913 conn_state.remove_path(&id);
-914 }
-915 PathEvent::Closed { id, .. } | PathEvent::LocallyClosed { id, .. } => {
-916 let Some(path_remote) = conn_state.paths.get(&id).cloned() else {
-917 debug!("path not in path_id_map");
-918 return;
-919 };
-920 event!(
-921 target: "iroh::_events::path::closed",
-922 Level::DEBUG,
-923 remote = %self.endpoint_id.fmt_short(),
-924 ?path_remote,
-925 ?conn_id,
-926 path_id = ?id,
-927 );
-928 conn_state.remove_open_path(&id);
-929
-930 // If one connection closes this path, close it on all connections.
-931 for (conn_id, conn_state) in self.connections.iter_mut() {
-932 let Some(path_id) = conn_state.path_ids.get(&path_remote) else {
+834 }
+835 let fut = conn.open_path_ensure(quic_addr, path_status);
+836 match fut.path_id() {
+837 Some(path_id) => {
+838 trace!(?conn_id, ?path_id, "opening new path");
+839 conn_state.add_path(open_addr.clone(), path_id);
+840 }
+841 None => {
+842 let ret = now_or_never(fut);
+843 match ret {
+844 Some(Err(PathError::RemoteCidsExhausted)) => {
+845 self.scheduled_open_path =
+846 Some(Instant::now() + Duration::from_millis(333));
+847 self.pending_open_paths.push_back(open_addr.clone());
+848 trace!(?open_addr, "scheduling open_path");
+849 }
+850 _ => warn!(?ret, "Opening path failed"),
+851 }
+852 }
+853 }
+854 }
+855 }
+856
+857 #[instrument(skip(self))]
+858 fn handle_path_event(
+859 &mut self,
+860 conn_id: ConnId,
+861 event: Result<PathEvent, BroadcastStreamRecvError>,
+862 ) {
+863 let Ok(event) = event else {
+864 warn!("missed a PathEvent, EndpointStateActor lagging");
+865 // TODO: Is it possible to recover using the sync APIs to figure out what the
+866 // state of the connection and it's paths are?
+867 return;
+868 };
+869 let Some(conn_state) = self.connections.get_mut(&conn_id) else {
+870 trace!("event for removed connection");
+871 return;
+872 };
+873 let Some(conn) = conn_state.handle.upgrade() else {
+874 trace!("event for closed connection");
+875 return;
+876 };
+877 trace!("path event");
+878 match event {
+879 PathEvent::Opened { id: path_id } => {
+880 let Some(path) = conn.path(path_id) else {
+881 trace!("path open event for unknown path");
+882 return;
+883 };
+884 // TODO: We configure this as defaults when we setup the endpoint, do we
+885 // really need to duplicate this?
+886 path.set_keep_alive_interval(Some(HEARTBEAT_INTERVAL)).ok();
+887 path.set_max_idle_timeout(Some(PATH_MAX_IDLE_TIMEOUT)).ok();
+888
+889 if let Ok(socketaddr) = path.remote_address()
+890 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr)
+891 {
+892 event!(
+893 target: "iroh::_events::path::open",
+894 Level::DEBUG,
+895 remote = %self.endpoint_id.fmt_short(),
+896 ?path_remote,
+897 ?conn_id,
+898 ?path_id,
+899 );
+900 conn_state.add_open_path(path_remote.clone(), path_id);
+901 self.paths
+902 .insert(path_remote, Source::Connection { _0: Private });
+903 }
+904
+905 self.select_path();
+906 }
+907 PathEvent::Abandoned { id, path_stats } => {
+908 trace!(?path_stats, "path abandoned");
+909 // This is the last event for this path.
+910 conn_state.remove_path(&id);
+911 }
+912 PathEvent::Closed { id, .. } | PathEvent::LocallyClosed { id, .. } => {
+913 let Some(path_remote) = conn_state.paths.get(&id).cloned() else {
+914 debug!("path not in path_id_map");
+915 return;
+916 };
+917 event!(
+918 target: "iroh::_events::path::closed",
+919 Level::DEBUG,
+920 remote = %self.endpoint_id.fmt_short(),
+921 ?path_remote,
+922 ?conn_id,
+923 path_id = ?id,
+924 );
+925 conn_state.remove_open_path(&id);
+926
+927 // If one connection closes this path, close it on all connections.
+928 for (conn_id, conn_state) in self.connections.iter_mut() {
+929 let Some(path_id) = conn_state.path_ids.get(&path_remote) else {
+930 continue;
+931 };
+932 let Some(conn) = conn_state.handle.upgrade() else {
933 continue;
934 };
-935 let Some(conn) = conn_state.handle.upgrade() else {
-936 continue;
-937 };
-938 if let Some(path) = conn.path(*path_id) {
-939 trace!(?path_remote, ?conn_id, ?path_id, "closing path");
-940 if let Err(err) = path.close(APPLICATION_ABANDON_PATH.into()) {
-941 trace!(
-942 ?path_remote,
-943 ?conn_id,
-944 ?path_id,
-945 "path close failed: {err:#}"
-946 );
-947 }
-948 }
-949 }
-950 }
-951 PathEvent::RemoteStatus { .. } | PathEvent::ObservedAddr { .. } => {
-952 // Nothing to do for these events.
-953 }
-954 }
-955 }
-956
-957 /// Selects the path with the lowest RTT, prefers direct paths.
+935 if let Some(path) = conn.path(*path_id) {
+936 trace!(?path_remote, ?conn_id, ?path_id, "closing path");
+937 if let Err(err) = path.close(APPLICATION_ABANDON_PATH.into()) {
+938 trace!(
+939 ?path_remote,
+940 ?conn_id,
+941 ?path_id,
+942 "path close failed: {err:#}"
+943 );
+944 }
+945 }
+946 }
+947 }
+948 PathEvent::RemoteStatus { .. } | PathEvent::ObservedAddr { .. } => {
+949 // Nothing to do for these events.
+950 }
+951 }
+952 }
+953
+954 /// Selects the path with the lowest RTT, prefers direct paths.
+955 ///
+956 /// If there are direct paths, this selects the direct path with the lowest RTT. If
+957 /// there are only relay paths, the relay path with the lowest RTT is chosen.
958 ///
-959 /// If there are direct paths, this selects the direct path with the lowest RTT. If
-960 /// there are only relay paths, the relay path with the lowest RTT is chosen.
-961 ///
-962 /// The selected path is added to any connections which do not yet have it. Any unused
-963 /// direct paths are closed for all connections.
-964 #[instrument(skip_all)]
-965 fn select_path(&mut self) {
-966 // Find the lowest RTT across all connections for each open path. The long way, so
-967 // we get to log *all* RTTs.
-968 let mut all_path_rtts: FxHashMap<transports::Addr, Vec<Duration>> = FxHashMap::default();
-969 for conn_state in self.connections.values() {
-970 let Some(conn) = conn_state.handle.upgrade() else {
-971 continue;
-972 };
-973 for (path_id, addr) in conn_state.open_paths.iter() {
-974 if let Some(stats) = conn.path_stats(*path_id) {
-975 all_path_rtts
-976 .entry(addr.clone())
-977 .or_default()
-978 .push(stats.rtt);
-979 }
-980 }
-981 }
-982 trace!(?all_path_rtts, "dumping all path RTTs");
-983 let path_rtts: FxHashMap<transports::Addr, Duration> = all_path_rtts
-984 .into_iter()
-985 .filter_map(|(addr, rtts)| rtts.into_iter().min().map(|rtt| (addr, rtt)))
-986 .collect();
-987
-988 // Find the fastest direct or relay path.
-989 const IPV6_RTT_ADVANTAGE: Duration = Duration::from_millis(3);
-990 let direct_path = path_rtts
-991 .iter()
-992 .filter(|(addr, _rtt)| addr.is_ip())
-993 .map(|(addr, rtt)| {
-994 if addr.is_ipv4() {
-995 (*rtt + IPV6_RTT_ADVANTAGE, addr)
-996 } else {
-997 (*rtt, addr)
-998 }
-999 })
-1000 .min();
-1001 let selected_path = direct_path.or_else(|| {
-1002 // Find the fasted relay path.
-1003 path_rtts
-1004 .iter()
-1005 .filter(|(addr, _rtt)| addr.is_relay())
-1006 .map(|(addr, rtt)| (*rtt, addr))
-1007 .min()
-1008 });
-1009 if let Some((rtt, addr)) = selected_path {
-1010 let prev = self.selected_path.set(Some(addr.clone()));
-1011 if prev.is_ok() {
-1012 debug!(?addr, ?rtt, ?prev, "selected new path");
-1013 }
-1014 self.open_path(addr);
-1015 self.close_redundant_paths(addr);
-1016 }
-1017 }
-1018
-1019 /// Closes any direct paths not selected.
-1020 ///
-1021 /// Makes sure not to close the last direct path. Relay paths are never closed
-1022 /// currently, because we only have one relay path at this time.
-1023 // TODO: Need to handle this on a timer as well probably. In .select_path() we open new
-1024 // paths and immediately call this. But the new paths are probably not yet open on
-1025 // all connections.
-1026 fn close_redundant_paths(&mut self, selected_path: &transports::Addr) {
-1027 debug_assert_eq!(self.selected_path.get().as_ref(), Some(selected_path),);
-1028
-1029 for (conn_id, conn_state) in self.connections.iter() {
-1030 for (path_id, path_remote) in conn_state
-1031 .open_paths
-1032 .iter()
-1033 .filter(|(_, addr)| addr.is_ip())
-1034 .filter(|(_, addr)| *addr != selected_path)
-1035 {
-1036 if conn_state.open_paths.values().filter(|a| a.is_ip()).count() <= 1 {
-1037 continue; // Do not close the last direct path.
-1038 }
-1039 if let Some(path) = conn_state
-1040 .handle
-1041 .upgrade()
-1042 .and_then(|conn| conn.path(*path_id))
-1043 {
-1044 trace!(?path_remote, ?conn_id, ?path_id, "closing direct path");
-1045 match path.close(APPLICATION_ABANDON_PATH.into()) {
-1046 Err(quinn_proto::ClosePathError::LastOpenPath) => {
-1047 error!("could not close last open path");
-1048 }
-1049 Err(quinn_proto::ClosePathError::ClosedPath) => {
-1050 // We already closed this.
+959 /// The selected path is added to any connections which do not yet have it. Any unused
+960 /// direct paths are closed for all connections.
+961 #[instrument(skip_all)]
+962 fn select_path(&mut self) {
+963 // Find the lowest RTT across all connections for each open path. The long way, so
+964 // we get to log *all* RTTs.
+965 let mut all_path_rtts: FxHashMap<transports::Addr, Vec<Duration>> = FxHashMap::default();
+966 for conn_state in self.connections.values() {
+967 let Some(conn) = conn_state.handle.upgrade() else {
+968 continue;
+969 };
+970 for (path_id, addr) in conn_state.open_paths.iter() {
+971 if let Some(stats) = conn.path_stats(*path_id) {
+972 all_path_rtts
+973 .entry(addr.clone())
+974 .or_default()
+975 .push(stats.rtt);
+976 }
+977 }
+978 }
+979 trace!(?all_path_rtts, "dumping all path RTTs");
+980 let path_rtts: FxHashMap<transports::Addr, Duration> = all_path_rtts
+981 .into_iter()
+982 .filter_map(|(addr, rtts)| rtts.into_iter().min().map(|rtt| (addr, rtt)))
+983 .collect();
+984
+985 // Find the fastest direct or relay path.
+986 const IPV6_RTT_ADVANTAGE: Duration = Duration::from_millis(3);
+987 let direct_path = path_rtts
+988 .iter()
+989 .filter(|(addr, _rtt)| addr.is_ip())
+990 .map(|(addr, rtt)| {
+991 if addr.is_ipv4() {
+992 (*rtt + IPV6_RTT_ADVANTAGE, addr)
+993 } else {
+994 (*rtt, addr)
+995 }
+996 })
+997 .min();
+998 let selected_path = direct_path.or_else(|| {
+999 // Find the fasted relay path.
+1000 path_rtts
+1001 .iter()
+1002 .filter(|(addr, _rtt)| addr.is_relay())
+1003 .map(|(addr, rtt)| (*rtt, addr))
+1004 .min()
+1005 });
+1006 if let Some((rtt, addr)) = selected_path {
+1007 let prev = self.selected_path.set(Some(addr.clone()));
+1008 if prev.is_ok() {
+1009 debug!(?addr, ?rtt, ?prev, "selected new path");
+1010 }
+1011 self.open_path(addr);
+1012 self.close_redundant_paths(addr);
+1013 }
+1014 }
+1015
+1016 /// Closes any direct paths not selected.
+1017 ///
+1018 /// Makes sure not to close the last direct path. Relay paths are never closed
+1019 /// currently, because we only have one relay path at this time.
+1020 // TODO: Need to handle this on a timer as well probably. In .select_path() we open new
+1021 // paths and immediately call this. But the new paths are probably not yet open on
+1022 // all connections.
+1023 fn close_redundant_paths(&mut self, selected_path: &transports::Addr) {
+1024 debug_assert_eq!(self.selected_path.get().as_ref(), Some(selected_path),);
+1025
+1026 for (conn_id, conn_state) in self.connections.iter() {
+1027 for (path_id, path_remote) in conn_state
+1028 .open_paths
+1029 .iter()
+1030 .filter(|(_, addr)| addr.is_ip())
+1031 .filter(|(_, addr)| *addr != selected_path)
+1032 {
+1033 if conn_state.open_paths.values().filter(|a| a.is_ip()).count() <= 1 {
+1034 continue; // Do not close the last direct path.
+1035 }
+1036 if let Some(path) = conn_state
+1037 .handle
+1038 .upgrade()
+1039 .and_then(|conn| conn.path(*path_id))
+1040 {
+1041 trace!(?path_remote, ?conn_id, ?path_id, "closing direct path");
+1042 match path.close(APPLICATION_ABANDON_PATH.into()) {
+1043 Err(quinn_proto::ClosePathError::LastOpenPath) => {
+1044 error!("could not close last open path");
+1045 }
+1046 Err(quinn_proto::ClosePathError::ClosedPath) => {
+1047 // We already closed this.
+1048 }
+1049 Ok(_fut) => {
+1050 // We will handle the event in Self::handle_path_events.
1051 }
-1052 Ok(_fut) => {
-1053 // We will handle the event in Self::handle_path_events.
-1054 }
-1055 }
-1056 }
-1057 }
-1058 }
-1059 }
-1060}
-1061
-1062/// Messages to send to the [`EndpointStateActor`].
-1063#[derive(derive_more::Debug)]
-1064pub(crate) enum EndpointStateMessage {
-1065 /// Sends a datagram to all known paths.
+1052 }
+1053 }
+1054 }
+1055 }
+1056 }
+1057}
+1058
+1059/// Messages to send to the [`EndpointStateActor`].
+1060#[derive(derive_more::Debug)]
+1061pub(crate) enum EndpointStateMessage {
+1062 /// Sends a datagram to all known paths.
+1063 ///
+1064 /// Used to send QUIC Initial packets. If there is no working direct path this will
+1065 /// trigger holepunching.
1066 ///
-1067 /// Used to send QUIC Initial packets. If there is no working direct path this will
-1068 /// trigger holepunching.
-1069 ///
-1070 /// This is not acceptable to use on the normal send path, as it is an async send
-1071 /// operation with a bunch more copying. So it should only be used for sending QUIC
-1072 /// Initial packets.
-1073 #[debug("SendDatagram(..)")]
-1074 SendDatagram(OwnedTransmit),
-1075 /// Adds an active connection to this remote endpoint.
-1076 ///
-1077 /// The connection will now be managed by this actor. Holepunching will happen when
-1078 /// needed, any new paths discovered via holepunching will be added. And closed paths
-1079 /// will be removed etc.
-1080 #[debug("AddConnection(..)")]
-1081 AddConnection(WeakConnectionHandle, oneshot::Sender<PathsWatcher>),
-1082 /// Process a received DISCO CallMeMaybe message.
-1083 CallMeMaybeReceived(disco::CallMeMaybe),
-1084 /// Process a received DISCO Ping message.
-1085 #[debug("PingReceived({:?}, src: {_1:?})", _0.tx_id)]
-1086 PingReceived(disco::Ping, transports::Addr),
-1087 /// Process a received DISCO Pong message.
-1088 #[debug("PongReceived({:?}, src: {_1:?})", _0.tx_id)]
-1089 PongReceived(disco::Pong, transports::Addr),
-1090 /// Ensure we have at least one transport address for a remote.
+1067 /// This is not acceptable to use on the normal send path, as it is an async send
+1068 /// operation with a bunch more copying. So it should only be used for sending QUIC
+1069 /// Initial packets.
+1070 #[debug("SendDatagram(..)")]
+1071 SendDatagram(OwnedTransmit),
+1072 /// Adds an active connection to this remote endpoint.
+1073 ///
+1074 /// The connection will now be managed by this actor. Holepunching will happen when
+1075 /// needed, any new paths discovered via holepunching will be added. And closed paths
+1076 /// will be removed etc.
+1077 #[debug("AddConnection(..)")]
+1078 AddConnection(WeakConnectionHandle, oneshot::Sender<PathsWatcher>),
+1079 /// Process a received DISCO CallMeMaybe message.
+1080 CallMeMaybeReceived(disco::CallMeMaybe),
+1081 /// Process a received DISCO Ping message.
+1082 #[debug("PingReceived({:?}, src: {_1:?})", _0.tx_id)]
+1083 PingReceived(disco::Ping, transports::Addr),
+1084 /// Process a received DISCO Pong message.
+1085 #[debug("PongReceived({:?}, src: {_1:?})", _0.tx_id)]
+1086 PongReceived(disco::Pong, transports::Addr),
+1087 /// Ensure we have at least one transport address for a remote.
+1088 ///
+1089 /// This adds the provided transport addresses to the list of potential paths for this remote
+1090 /// and starts discovery if needed.
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 /// Returns the current latency to the remote endpoint.
-1104 ///
-1105 /// TODO: This is more of a placeholder message currently. Check MagicSock::latency.
-1106 #[debug("Latency(..)")]
-1107 Latency(oneshot::Sender<Option<Duration>>),
-1108}
-1109
-1110/// A handle to a [`EndpointStateActor`].
-1111///
-1112/// Dropping this will stop the actor. The actor will also stop after an idle timeout
-1113/// if it has no connections, an empty inbox, and no other senders than the one stored
-1114/// in the endpoint map exist.
-1115#[derive(Debug)]
-1116pub(super) struct EndpointStateHandle {
-1117 /// Sender for the channel into the [`EndpointStateActor`].
-1118 ///
-1119 /// This is a [`GuardedSender`], from which we can get a sender but only if the receiver
-1120 /// hasn't been closed.
-1121 pub(super) sender: GuardedSender<EndpointStateMessage>,
-1122 _task: AbortOnDropHandle<()>,
-1123}
-1124
-1125/// Information about a holepunch attempt.
-1126#[derive(Debug)]
-1127struct HolepunchAttempt {
-1128 when: Instant,
-1129 /// The set of local addresses which could take part in holepunching.
-1130 ///
-1131 /// This does not mean every address here participated in the holepunching. E.g. we
-1132 /// could have tried only a sub-set of the addresses because a previous attempt already
-1133 /// covered part of the range.
-1134 ///
-1135 /// We do not store this as a [`DirectAddr`] because this is checked for equality and we
-1136 /// do not want to compare the sources of these addresses.
-1137 local_addrs: BTreeSet<SocketAddr>,
-1138 /// The set of remote addresses which could take part in holepunching.
-1139 ///
-1140 /// Like `local_addrs` we may not have used them.
-1141 remote_addrs: BTreeSet<SocketAddr>,
-1142}
-1143
-1144/// Newtype to track Connections.
-1145///
-1146/// The wrapped value is the [`quinn::Connection::stable_id`] value, and is thus only valid
-1147/// for active connections.
-1148#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
-1149struct ConnId(usize);
-1150
-1151/// State about one connection.
-1152#[derive(Debug)]
-1153struct ConnectionState {
-1154 /// Weak handle to the connection.
-1155 handle: WeakConnectionHandle,
-1156 /// The information we publish to users about the paths used in this connection.
-1157 pub_open_paths: Watchable<PathAddrList>,
-1158 /// The paths that exist on this connection.
-1159 ///
-1160 /// This could be in any state, e.g. while still validating the path or already closed
-1161 /// but not yet fully removed from the connection. This exists as long as Quinn knows
-1162 /// about the [`PathId`].
-1163 paths: FxHashMap<PathId, transports::Addr>,
-1164 /// The open paths on this connection, a subset of [`Self::paths`].
-1165 open_paths: FxHashMap<PathId, transports::Addr>,
-1166 /// Reverse map of [`Self::paths].
-1167 path_ids: FxHashMap<transports::Addr, PathId>,
-1168}
-1169
-1170impl ConnectionState {
-1171 /// Tracks a path for the connection.
-1172 fn add_path(&mut self, remote: transports::Addr, path_id: PathId) {
-1173 self.paths.insert(path_id, remote.clone());
-1174 self.path_ids.insert(remote, path_id);
-1175 }
-1176
-1177 /// Tracks an open path for the connection.
-1178 fn add_open_path(&mut self, remote: transports::Addr, path_id: PathId) {
-1179 self.paths.insert(path_id, remote.clone());
-1180 self.open_paths.insert(path_id, remote.clone());
-1181 self.path_ids.insert(remote, path_id);
+1092 /// Returns `Ok` immediately if the provided address list is non-empy or we have are other known paths.
+1093 /// Otherwise returns `Ok` once discovery produces a result, or the discovery error if discovery fails
+1094 /// or produces no results,
+1095 #[debug("ResolveRemote(..)")]
+1096 ResolveRemote(
+1097 BTreeSet<TransportAddr>,
+1098 oneshot::Sender<Result<(), DiscoveryError>>,
+1099 ),
+1100 /// Returns the current latency to the remote endpoint.
+1101 ///
+1102 /// TODO: This is more of a placeholder message currently. Check MagicSock::latency.
+1103 #[debug("Latency(..)")]
+1104 Latency(oneshot::Sender<Option<Duration>>),
+1105}
+1106
+1107/// A handle to a [`EndpointStateActor`].
+1108///
+1109/// Dropping this will stop the actor. The actor will also stop after an idle timeout
+1110/// if it has no connections, an empty inbox, and no other senders than the one stored
+1111/// in the endpoint map exist.
+1112#[derive(Debug)]
+1113pub(super) struct EndpointStateHandle {
+1114 /// Sender for the channel into the [`EndpointStateActor`].
+1115 ///
+1116 /// This is a [`GuardedSender`], from which we can get a sender but only if the receiver
+1117 /// hasn't been closed.
+1118 pub(super) sender: GuardedSender<EndpointStateMessage>,
+1119 _task: AbortOnDropHandle<()>,
+1120}
+1121
+1122/// Information about a holepunch attempt.
+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_addrs: BTreeSet<SocketAddr>,
+1135 /// The set of remote addresses which could take part in holepunching.
+1136 ///
+1137 /// Like `local_addrs` we may not have used them.
+1138 remote_addrs: 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, 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
+1180 self.update_pub_path_info();
+1181 }
1182
-1183 self.update_pub_path_info();
-1184 }
-1185
-1186 /// Completely removes a path from this connection.
-1187 fn remove_path(&mut self, path_id: &PathId) {
-1188 if let Some(addr) = self.paths.remove(path_id) {
-1189 self.path_ids.remove(&addr);
-1190 }
-1191 self.open_paths.remove(path_id);
-1192 }
-1193
-1194 /// Removes the path from the open paths.
-1195 fn remove_open_path(&mut self, path_id: &PathId) {
-1196 self.open_paths.remove(path_id);
+1183 /// Completely removes a path from this connection.
+1184 fn remove_path(&mut self, path_id: &PathId) {
+1185 if let Some(addr) = self.paths.remove(path_id) {
+1186 self.path_ids.remove(&addr);
+1187 }
+1188 self.open_paths.remove(path_id);
+1189 }
+1190
+1191 /// Removes the path from the open paths.
+1192 fn remove_open_path(&mut self, path_id: &PathId) {
+1193 self.open_paths.remove(path_id);
+1194
+1195 self.update_pub_path_info();
+1196 }
1197
-1198 self.update_pub_path_info();
-1199 }
-1200
-1201 /// Sets the new [`PathInfo`] structs for the public [`Connection`].
-1202 ///
-1203 /// [`Connection`]: crate::endpoint::Connection
-1204 fn update_pub_path_info(&self) {
-1205 let new = self
-1206 .open_paths
-1207 .iter()
-1208 .map(|(path_id, remote)| {
-1209 let remote = TransportAddr::from(remote.clone());
-1210 (remote, *path_id)
-1211 })
-1212 .collect::<PathAddrList>();
-1213
-1214 self.pub_open_paths.set(new).ok();
-1215 }
-1216}
-1217
-1218/// Watcher for the open paths and selected transmission path in a connection.
-1219///
-1220/// This is stored in the [`Connection`], and the watchables are set from within the endpoint state actor.
-1221///
-1222/// Internally, this contains a boxed-mapped-joined watcher over the open paths in the connection and the
-1223/// selected path to the remote endpoint. The watcher is boxed because the mapped-joined watcher with
-1224/// `SmallVec<PathInfoList>` has a size of over 800 bytes, which we don't want to put upon the [`Connection`].
-1225///
-1226/// [`Connection`]: crate::endpoint::Connection
-1227#[derive(Clone, derive_more::Debug)]
-1228#[debug("PathsWatcher")]
-1229#[allow(clippy::type_complexity)]
-1230pub(crate) struct PathsWatcher(
-1231 Box<
-1232 n0_watcher::Map<
-1233 n0_watcher::Tuple<
-1234 n0_watcher::Direct<PathAddrList>,
-1235 n0_watcher::Direct<Option<transports::Addr>>,
-1236 >,
-1237 PathInfoList,
-1238 >,
-1239 >,
-1240);
+1198 /// Sets the new [`PathInfo`] structs for the public [`Connection`].
+1199 ///
+1200 /// [`Connection`]: crate::endpoint::Connection
+1201 fn update_pub_path_info(&self) {
+1202 let new = self
+1203 .open_paths
+1204 .iter()
+1205 .map(|(path_id, remote)| {
+1206 let remote = TransportAddr::from(remote.clone());
+1207 (remote, *path_id)
+1208 })
+1209 .collect::<PathAddrList>();
+1210
+1211 self.pub_open_paths.set(new).ok();
+1212 }
+1213}
+1214
+1215/// Watcher for the open paths and selected transmission path in a connection.
+1216///
+1217/// This is stored in the [`Connection`], and the watchables are set from within the endpoint state actor.
+1218///
+1219/// Internally, this contains a boxed-mapped-joined watcher over the open paths in the connection and the
+1220/// selected path to the remote endpoint. The watcher is boxed because the mapped-joined watcher with
+1221/// `SmallVec<PathInfoList>` has a size of over 800 bytes, which we don't want to put upon the [`Connection`].
+1222///
+1223/// [`Connection`]: crate::endpoint::Connection
+1224#[derive(Clone, derive_more::Debug)]
+1225#[debug("PathsWatcher")]
+1226#[allow(clippy::type_complexity)]
+1227pub(crate) struct PathsWatcher(
+1228 Box<
+1229 n0_watcher::Map<
+1230 n0_watcher::Tuple<
+1231 n0_watcher::Direct<PathAddrList>,
+1232 n0_watcher::Direct<Option<transports::Addr>>,
+1233 >,
+1234 PathInfoList,
+1235 >,
+1236 >,
+1237);
+1238
+1239impl n0_watcher::Watcher for PathsWatcher {
+1240 type Value = PathInfoList;
1241
-1242impl n0_watcher::Watcher for PathsWatcher {
-1243 type Value = PathInfoList;
-1244
-1245 fn update(&mut self) -> bool {
-1246 self.0.update()
-1247 }
-1248
-1249 fn peek(&self) -> &Self::Value {
-1250 self.0.peek()
-1251 }
-1252
-1253 fn is_connected(&self) -> bool {
-1254 self.0.is_connected()
-1255 }
-1256
-1257 fn poll_updated(
-1258 &mut self,
-1259 cx: &mut std::task::Context<'_>,
-1260 ) -> Poll<Result<(), n0_watcher::Disconnected>> {
-1261 self.0.poll_updated(cx)
-1262 }
-1263}
-1264
-1265impl PathsWatcher {
-1266 fn new(
-1267 open_paths: n0_watcher::Direct<PathAddrList>,
-1268 selected_path: n0_watcher::Direct<Option<transports::Addr>>,
-1269 conn_handle: WeakConnectionHandle,
-1270 ) -> Self {
-1271 Self(Box::new(open_paths.or(selected_path).map(
-1272 move |(open_paths, selected_path)| {
-1273 let selected_path: Option<TransportAddr> = selected_path.map(Into::into);
-1274 let Some(conn) = conn_handle.upgrade() else {
-1275 return PathInfoList(Default::default());
-1276 };
-1277 let list = open_paths
-1278 .into_iter()
-1279 .flat_map(move |(remote, path_id)| {
-1280 PathInfo::new(path_id, &conn, remote, selected_path.as_ref())
-1281 })
-1282 .collect();
-1283 PathInfoList(list)
-1284 },
-1285 )))
-1286 }
-1287}
-1288
-1289/// List of [`PathInfo`] for the network paths of a [`Connection`].
-1290///
-1291/// This struct implements [`IntoIterator`].
-1292///
-1293/// [`Connection`]: crate::endpoint::Connection
-1294#[derive(derive_more::Debug, derive_more::IntoIterator, Eq, PartialEq, Clone)]
-1295#[debug("{_0:?}")]
-1296pub struct PathInfoList(SmallVec<[PathInfo; 4]>);
-1297
-1298impl PathInfoList {
-1299 /// Returns an iterator over the path infos.
-1300 pub fn iter(&self) -> impl Iterator<Item = &PathInfo> {
-1301 self.0.iter()
-1302 }
-1303
-1304 /// Returns `true` if the list is empty.
-1305 pub fn is_empty(&self) -> bool {
-1306 self.0.is_empty()
-1307 }
-1308
-1309 /// Returns the number of paths.
-1310 pub fn len(&self) -> usize {
-1311 self.0.len()
-1312 }
-1313}
-1314
-1315/// Information about a network path used by a [`Connection`].
-1316///
-1317/// [`Connection`]: crate::endpoint::Connection
-1318#[derive(derive_more::Debug, Clone)]
-1319pub struct PathInfo {
-1320 path_id: PathId,
-1321 #[debug(skip)]
-1322 handle: WeakConnectionHandle,
-1323 stats: PathStats,
-1324 remote: TransportAddr,
-1325 is_selected: bool,
-1326}
-1327
-1328impl PartialEq for PathInfo {
-1329 fn eq(&self, other: &Self) -> bool {
-1330 self.path_id == other.path_id
-1331 && self.remote == other.remote
-1332 && self.is_selected == other.is_selected
-1333 }
-1334}
-1335
-1336impl Eq for PathInfo {}
-1337
-1338impl PathInfo {
-1339 fn new(
-1340 path_id: PathId,
-1341 conn: &quinn::Connection,
-1342 remote: TransportAddr,
-1343 selected_path: Option<&TransportAddr>,
-1344 ) -> Option<Self> {
-1345 let stats = conn.path_stats(path_id)?;
-1346 Some(Self {
-1347 path_id,
-1348 handle: conn.weak_handle(),
-1349 is_selected: Some(&remote) == selected_path,
-1350 remote,
-1351 stats,
-1352 })
-1353 }
-1354
-1355 /// The remote transport address used by this network path.
-1356 pub fn remote_addr(&self) -> &TransportAddr {
-1357 &self.remote
-1358 }
-1359
-1360 /// Returns `true` if this path is currently the main transmission path for this [`Connection`].
-1361 ///
-1362 /// [`Connection`]: crate::endpoint::Connection
-1363 pub fn is_selected(&self) -> bool {
-1364 self.is_selected
-1365 }
-1366
-1367 /// Whether this is an IP transport address.
-1368 pub fn is_ip(&self) -> bool {
-1369 self.remote.is_ip()
-1370 }
-1371
-1372 /// Whether this is a transport address via a relay server.
-1373 pub fn is_relay(&self) -> bool {
-1374 self.remote.is_relay()
-1375 }
-1376
-1377 /// Returns stats for this transmission path.
-1378 pub fn stats(&self) -> PathStats {
-1379 self.handle
-1380 .upgrade()
-1381 .and_then(|conn| conn.path_stats(self.path_id))
-1382 .unwrap_or(self.stats)
-1383 }
-1384
-1385 /// Current best estimate of this paths's latency (round-trip-time)
-1386 pub fn rtt(&self) -> Duration {
-1387 self.stats().rtt
-1388 }
-1389}
-1390
-1391/// Poll a future once, like n0_future::future::poll_once but sync.
-1392fn now_or_never<T, F: Future<Output = T>>(fut: F) -> Option<T> {
-1393 let fut = std::pin::pin!(fut);
-1394 match fut.poll(&mut std::task::Context::from_waker(std::task::Waker::noop())) {
-1395 Poll::Ready(res) => Some(res),
-1396 Poll::Pending => None,
-1397 }
-1398}
-1399
-1400/// Future that resolves to the `conn_id` once a connection is closed.
-1401///
-1402/// This uses [`quinn::Connection::on_closed`], which does not keep the connection alive
-1403/// while awaiting the future.
-1404struct OnClosed {
-1405 conn_id: ConnId,
-1406 inner: quinn::OnClosed,
-1407}
-1408
-1409impl OnClosed {
-1410 fn new(conn: &quinn::Connection) -> Self {
-1411 Self {
-1412 conn_id: ConnId(conn.stable_id()),
-1413 inner: conn.on_closed(),
-1414 }
-1415 }
-1416}
+1242 fn update(&mut self) -> bool {
+1243 self.0.update()
+1244 }
+1245
+1246 fn peek(&self) -> &Self::Value {
+1247 self.0.peek()
+1248 }
+1249
+1250 fn is_connected(&self) -> bool {
+1251 self.0.is_connected()
+1252 }
+1253
+1254 fn poll_updated(
+1255 &mut self,
+1256 cx: &mut std::task::Context<'_>,
+1257 ) -> Poll<Result<(), n0_watcher::Disconnected>> {
+1258 self.0.poll_updated(cx)
+1259 }
+1260}
+1261
+1262impl PathsWatcher {
+1263 fn new(
+1264 open_paths: n0_watcher::Direct<PathAddrList>,
+1265 selected_path: n0_watcher::Direct<Option<transports::Addr>>,
+1266 conn_handle: WeakConnectionHandle,
+1267 ) -> Self {
+1268 Self(Box::new(open_paths.or(selected_path).map(
+1269 move |(open_paths, selected_path)| {
+1270 let selected_path: Option<TransportAddr> = selected_path.map(Into::into);
+1271 let Some(conn) = conn_handle.upgrade() else {
+1272 return PathInfoList(Default::default());
+1273 };
+1274 let list = open_paths
+1275 .into_iter()
+1276 .flat_map(move |(remote, path_id)| {
+1277 PathInfo::new(path_id, &conn, remote, selected_path.as_ref())
+1278 })
+1279 .collect();
+1280 PathInfoList(list)
+1281 },
+1282 )))
+1283 }
+1284}
+1285
+1286/// List of [`PathInfo`] for the network paths of a [`Connection`].
+1287///
+1288/// This struct implements [`IntoIterator`].
+1289///
+1290/// [`Connection`]: crate::endpoint::Connection
+1291#[derive(derive_more::Debug, derive_more::IntoIterator, Eq, PartialEq, Clone)]
+1292#[debug("{_0:?}")]
+1293pub struct PathInfoList(SmallVec<[PathInfo; 4]>);
+1294
+1295impl PathInfoList {
+1296 /// Returns an iterator over the path infos.
+1297 pub fn iter(&self) -> impl Iterator<Item = &PathInfo> {
+1298 self.0.iter()
+1299 }
+1300
+1301 /// Returns `true` if the list is empty.
+1302 pub fn is_empty(&self) -> bool {
+1303 self.0.is_empty()
+1304 }
+1305
+1306 /// Returns the number of paths.
+1307 pub fn len(&self) -> usize {
+1308 self.0.len()
+1309 }
+1310}
+1311
+1312/// Information about a network path used by a [`Connection`].
+1313///
+1314/// [`Connection`]: crate::endpoint::Connection
+1315#[derive(derive_more::Debug, Clone)]
+1316pub struct PathInfo {
+1317 path_id: PathId,
+1318 #[debug(skip)]
+1319 handle: WeakConnectionHandle,
+1320 stats: PathStats,
+1321 remote: TransportAddr,
+1322 is_selected: bool,
+1323}
+1324
+1325impl PartialEq for PathInfo {
+1326 fn eq(&self, other: &Self) -> bool {
+1327 self.path_id == other.path_id
+1328 && self.remote == other.remote
+1329 && self.is_selected == other.is_selected
+1330 }
+1331}
+1332
+1333impl Eq for PathInfo {}
+1334
+1335impl PathInfo {
+1336 fn new(
+1337 path_id: PathId,
+1338 conn: &quinn::Connection,
+1339 remote: TransportAddr,
+1340 selected_path: Option<&TransportAddr>,
+1341 ) -> Option<Self> {
+1342 let stats = conn.path_stats(path_id)?;
+1343 Some(Self {
+1344 path_id,
+1345 handle: conn.weak_handle(),
+1346 is_selected: Some(&remote) == selected_path,
+1347 remote,
+1348 stats,
+1349 })
+1350 }
+1351
+1352 /// The remote transport address used by this network path.
+1353 pub fn remote_addr(&self) -> &TransportAddr {
+1354 &self.remote
+1355 }
+1356
+1357 /// Returns `true` if this path is currently the main transmission path for this [`Connection`].
+1358 ///
+1359 /// [`Connection`]: crate::endpoint::Connection
+1360 pub fn is_selected(&self) -> bool {
+1361 self.is_selected
+1362 }
+1363
+1364 /// Whether this is an IP transport address.
+1365 pub fn is_ip(&self) -> bool {
+1366 self.remote.is_ip()
+1367 }
+1368
+1369 /// Whether this is a transport address via a relay server.
+1370 pub fn is_relay(&self) -> bool {
+1371 self.remote.is_relay()
+1372 }
+1373
+1374 /// Returns stats for this transmission path.
+1375 pub fn stats(&self) -> PathStats {
+1376 self.handle
+1377 .upgrade()
+1378 .and_then(|conn| conn.path_stats(self.path_id))
+1379 .unwrap_or(self.stats)
+1380 }
+1381
+1382 /// Current best estimate of this paths's latency (round-trip-time)
+1383 pub fn rtt(&self) -> Duration {
+1384 self.stats().rtt
+1385 }
+1386}
+1387
+1388/// Poll a future once, like n0_future::future::poll_once but sync.
+1389fn now_or_never<T, F: Future<Output = T>>(fut: F) -> Option<T> {
+1390 let fut = std::pin::pin!(fut);
+1391 match fut.poll(&mut std::task::Context::from_waker(std::task::Waker::noop())) {
+1392 Poll::Ready(res) => Some(res),
+1393 Poll::Pending => None,
+1394 }
+1395}
+1396
+1397/// Future that resolves to the `conn_id` once a connection is closed.
+1398///
+1399/// This uses [`quinn::Connection::on_closed`], which does not keep the connection alive
+1400/// while awaiting the future.
+1401struct OnClosed {
+1402 conn_id: ConnId,
+1403 inner: quinn::OnClosed,
+1404}
+1405
+1406impl OnClosed {
+1407 fn new(conn: &quinn::Connection) -> Self {
+1408 Self {
+1409 conn_id: ConnId(conn.stable_id()),
+1410 inner: conn.on_closed(),
+1411 }
+1412 }
+1413}
+1414
+1415impl Future for OnClosed {
+1416 type Output = ConnId;
1417
-1418impl Future for OnClosed {
-1419 type Output = ConnId;
-1420
-1421 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
-1422 let (_close_reason, _stats) = std::task::ready!(Pin::new(&mut self.inner).poll(cx));
-1423 Poll::Ready(self.conn_id)
-1424 }
-1425}
-1426
-1427/// Converts an interator of [`TransportAddr'] into an iterator of [`transports::Addr`].
-1428fn to_transports_addr(
-1429 endpoint_id: EndpointId,
-1430 addrs: impl IntoIterator<Item = TransportAddr>,
-1431) -> impl Iterator<Item = transports::Addr> {
-1432 addrs.into_iter().filter_map(move |addr| match addr {
-1433 TransportAddr::Relay(relay_url) => Some(transports::Addr::from((relay_url, endpoint_id))),
-1434 TransportAddr::Ip(sockaddr) => Some(transports::Addr::from(sockaddr)),
-1435 _ => {
-1436 warn!(?addr, "Unsupported TransportAddr");
-1437 None
-1438 }
-1439 })
-1440}
\ No newline at end of file
+1418 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
+1419 let (_close_reason, _stats) = std::task::ready!(Pin::new(&mut self.inner).poll(cx));
+1420 Poll::Ready(self.conn_id)
+1421 }
+1422}
+1423
+1424/// Converts an iterator of [`TransportAddr'] into an iterator of [`transports::Addr`].
+1425fn to_transports_addr(
+1426 endpoint_id: EndpointId,
+1427 addrs: impl IntoIterator<Item = TransportAddr>,
+1428) -> impl Iterator<Item = transports::Addr> {
+1429 addrs.into_iter().filter_map(move |addr| match addr {
+1430 TransportAddr::Relay(relay_url) => Some(transports::Addr::from((relay_url, endpoint_id))),
+1431 TransportAddr::Ip(sockaddr) => Some(transports::Addr::from(sockaddr)),
+1432 _ => {
+1433 warn!(?addr, "Unsupported TransportAddr");
+1434 None
+1435 }
+1436 })
+1437}
\ No newline at end of file
diff --git a/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state/path_state.rs.html b/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state/path_state.rs.html
index a47e44b277..5a3a367891 100644
--- a/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state/path_state.rs.html
+++ b/pr/3645/docs/src/iroh/magicsock/endpoint_map/endpoint_state/path_state.rs.html
@@ -117,7 +117,7 @@
117 self.paths.keys()
118 }
119
-120 /// Replies to all pending requests from [`EndpointStateMessage::ResolveRemote`].
+120 /// Replies to all pending resolve requests.
121 ///
122 /// This is a no-op if no requests are queued. Replies `Ok` if we have any known paths,
123 /// otherwise with the provided `discovery_error` or with [`DiscoveryError::NoResults`].
@@ -139,17 +139,14 @@
139/// The state of a single path to the remote endpoint.
140///
141/// Each path is identified by the destination [`transports::Addr`] and they are stored in
-142/// the [`EndpointStateActor::paths`] map.
-143///
-144/// [`transports::Addr`]: super::transports::Addr
-145/// [`EndpointStateActor::paths`]: super::endpoint_state::EndpointStateActor
-146#[derive(Debug, Default)]
-147pub(super) struct PathState {
-148 /// How we learned about this path, and when.
-149 ///
-150 /// We keep track of only the latest [`Instant`] for each [`Source`], keeping the size
-151 /// of the map of sources down to one entry per type of source.
-152 pub(super) sources: HashMap<Source, Instant>,
-153 /// The last ping sent on this path.
-154 pub(super) ping_sent: Option<TransactionId>,
-155}
\ No newline at end of file
+142/// the [`EndpointPathState::paths`] map.
+143#[derive(Debug, Default)]
+144pub(super) struct PathState {
+145 /// How we learned about this path, and when.
+146 ///
+147 /// We keep track of only the latest [`Instant`] for each [`Source`], keeping the size
+148 /// of the map of sources down to one entry per type of source.
+149 pub(super) sources: HashMap<Source, Instant>,
+150 /// The last ping sent on this path.
+151 pub(super) ping_sent: Option<TransactionId>,
+152}
\ No newline at end of file
PathInfoList
pub struct PathInfoList(/* private fields */);Expand description
List of PathInfo for the network paths of a Connection.
PathInfoList
pub struct PathInfoList(/* private fields */);Expand description
List of PathInfo for the network paths of a Connection.
This struct implements IntoIterator.
Implementations§
Trait Implementations§
Source§impl Clone for PathInfoList
impl Clone for PathInfoList
Source§fn clone(&self) -> PathInfoList
fn clone(&self) -> PathInfoList
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl Debug for PathInfoList
impl Debug for PathInfoList
Source§impl IntoIterator for PathInfoList
impl IntoIterator for PathInfoList
Source§impl PartialEq for PathInfoList
impl PartialEq for PathInfoList
impl Eq for PathInfoList
impl StructuralPartialEq for PathInfoList
Auto Trait Implementations§
impl Freeze for PathInfoList
impl RefUnwindSafe for PathInfoList
impl Send for PathInfoList
impl Sync for PathInfoList
impl Unpin for PathInfoList
impl UnwindSafe for PathInfoList
Blanket Implementations§
Implementations§
Trait Implementations§
Source§impl Clone for PathInfoList
impl Clone for PathInfoList
Source§fn clone(&self) -> PathInfoList
fn clone(&self) -> PathInfoList
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more