diff --git a/pr/4273/docs/src/iroh/socket/remote_map/remote_state.rs.html b/pr/4273/docs/src/iroh/socket/remote_map/remote_state.rs.html index 867ce8b3e8..b97cbc06da 100644 --- a/pr/4273/docs/src/iroh/socket/remote_map/remote_state.rs.html +++ b/pr/4273/docs/src/iroh/socket/remote_map/remote_state.rs.html @@ -612,7 +612,7 @@ 612 613 // We track all known remote addresses for the peer in `State::paths`. The paths are tracked 614 // by remote address only (we ignore the local IP). Therefore, we mark a remote addr as abandoned -615 // in the remote-global state only once no connections has any path to that remote addr. +615 // in the remote-global state only once no connections have any path to that remote addr. 616 if !conn_state 617 .paths 618 .values() @@ -848,827 +848,830 @@ 848 849 // TODO(Frando): We might want to include a local IP here in the future, if we confidently 850 // know that it is the correct one. -851 if let Err(err) = send_datagram(&mut sender, addr.remote.clone(), transmit).await { -852 debug!(?addr, "failed to send datagram on selected_path: {err:#}"); -853 } -854 } else { -855 trace!( -856 paths = ?self.paths.addrs().collect::<Vec<_>>(), -857 "sending datagram to all known paths", -858 ); -859 if self.paths.is_empty() { -860 warn!("Cannot send datagrams: No paths to remote endpoint known"); -861 } -862 -863 for addr in self.paths.addrs() { -864 // We never want to send to our local addresses. -865 // The local address set is updated in the main loop so we can use `peek` here. -866 if let transports::Addr::Ip(sockaddr) = addr -867 && self -868 .local_direct_addrs -869 .peek() -870 .iter() -871 .any(|a| a.addr == *sockaddr) -872 { -873 trace!(%sockaddr, "not sending datagram to our own address"); -874 -875 // TODO(Frando): We might want to include a local IP here in the future, if we confidently -876 // know that it is the correct one. -877 } else if let Err(err) = -878 send_datagram(&mut sender, addr.clone(), transmit.clone()).await -879 { -880 debug!(?addr, "failed to send datagram: {err:#}"); -881 } -882 } -883 // This message is received *before* a connection is added. So we do -884 // not yet have a connection to holepunch. Instead we trigger -885 // holepunching when AddConnection is received. -886 } -887 } -888 -889 /// Handles [`RemoteStateMessage::ResolveRemote`]. -890 fn handle_msg_resolve_remote( -891 &mut self, -892 addrs: BTreeSet<TransportAddr>, -893 tx: oneshot::Sender<Result<(), AddressLookupFailed>>, -894 ) { -895 let addrs = to_transports_addr(self.endpoint_id, addrs); -896 self.paths.insert_multiple(addrs, Source::App); -897 self.paths.resolve_remote(tx); -898 // Start Address Lookup if we have no selected path. -899 self.trigger_address_lookup(); -900 } -901 -902 /// Triggers Address Lookup for the remote endpoint, if needed. -903 /// -904 /// Does not start Address Lookup if we have a selected path or if Address Lookup is -905 /// currently running. -906 fn trigger_address_lookup(&mut self) { -907 if self.selected_path.is_some() || self.address_lookup_stream.is_some() { -908 return; -909 } -910 let stream = self.address_lookup.resolve(self.endpoint_id); -911 let stream = stream.filter_map(|item| match item { -912 // We don't care about errors from individual services, we just continue. -913 // Individual errors are buffered into the final error by `AddressLookupServices::resolve`, -914 // and if the lookup fails we return them upstream with the final `AddressLookupFailed` error. -915 Ok(Err(_err)) => None, -916 Ok(Ok(item)) => Some(Ok(item)), -917 Err(err) => Some(Err(err)), -918 }); -919 self.address_lookup_stream = Some(Box::pin(stream)); -920 } -921 -922 /// Handles an address lookup result. -923 /// -924 /// All address lookup results end up being sent here. It takes care of updating the -925 /// [`RemotePathState`] with the results. -926 fn handle_address_lookup_item( -927 &mut self, -928 item: Option<Result<AddressLookupItem, AddressLookupFailed>>, -929 ) { -930 match item { -931 None => { -932 self.paths.address_lookup_finished(Ok(())); -933 self.address_lookup_stream = None; -934 } -935 Some(Err(err)) => { -936 warn!("Address Lookup failed: {err:#}"); -937 self.paths.address_lookup_finished(Err(err)); -938 self.address_lookup_stream = None; -939 } -940 Some(Ok(item)) => { -941 if item.endpoint_id() != self.endpoint_id { -942 warn!( -943 ?item, -944 "Address Lookup emitted item for wrong remote endpoint" -945 ); -946 } else { -947 let source = Source::AddressLookup { -948 name: item.provenance().to_string(), -949 }; -950 let addrs = -951 to_transports_addr(self.endpoint_id, item.into_endpoint_addr().addrs); -952 self.paths.insert_multiple(addrs, source); -953 } -954 } -955 } -956 } -957 -958 /// Unconditionally perform holepunching. -959 #[instrument(skip_all)] -960 fn do_holepunching(&mut self, conn: noq::Connection) { -961 self.metrics.holepunch_attempts.inc(); -962 let local_candidates = self.local_candidates(); -963 match conn.initiate_nat_traversal_round() { -964 Ok(remote_candidates) => { -965 let remote_candidates = remote_candidates -966 .iter() -967 .map(|addr| SocketAddr::new(addr.ip().to_canonical(), addr.port())) -968 .collect(); -969 event!( -970 target: "iroh::_events::qnt::init", -971 Level::DEBUG, -972 remote = %self.endpoint_id.fmt_short(), -973 ?local_candidates, -974 ?remote_candidates, -975 ); -976 self.last_holepunch = Some(HolepunchAttempt { -977 when: Instant::now(), -978 local_candidates, -979 remote_candidates, -980 }); -981 } -982 Err(err) => { -983 debug!("failed to initiate NAT traversal: {err:#}"); -984 use noq_proto::n0_nat_traversal::Error; -985 match err { -986 Error::Closed -987 | Error::TooManyAddresses -988 | Error::WrongConnectionSide -989 | Error::ExtensionNotNegotiated => { -990 // Fatal, no need to retry for now -991 } -992 Error::Multipath(_) | Error::NotEnoughAddresses => { -993 // Retry in a bit -994 let now = Instant::now(); -995 let next_hp = now + Duration::from_millis(100); -996 trace!(scheduled_in = ?(next_hp - now), "holepunching retry"); -997 self.scheduled_holepunch = Some(next_hp); -998 } -999 } -1000 } -1001 } -1002 } -1003 -1004 /// Register a path with our state and configure path-specific settings. -1005 /// -1006 /// This inserts the path in the [`ConnectionState`] and [`Self::paths`]. -1007 /// -1008 /// It configures the path with the correct path status (see [`Self::set_path_status`]), -1009 /// and applies path-type-specific settings: -1010 /// Relay paths get a longer idle timeout to accommodate transparent reconnection -1011 /// by the relay actor (see [`RELAY_PATH_MAX_IDLE_TIMEOUT`]). -1012 fn register_and_configure_path( -1013 &mut self, -1014 conn_id: ConnId, -1015 conn_state: &mut ConnectionState, -1016 path: &noq::Path, -1017 ) -> Option<TransportFourTuple> { -1018 let network_path = self.transport_addr_for_path(path)?; -1019 event!( -1020 target: "iroh::_events::path::open", -1021 Level::DEBUG, -1022 remote = %self.endpoint_id.fmt_short(), -1023 ?network_path, -1024 %conn_id, -1025 path_id=%path.id(), -1026 ); -1027 conn_state.add_open_path(network_path.clone(), path.id(), &self.metrics); -1028 if matches!(network_path.remote(), transports::Addr::Relay(..)) -1029 && let Err(e) = path.set_max_idle_timeout(Some(RELAY_PATH_MAX_IDLE_TIMEOUT)) -1030 { -1031 debug!(?e, "failed to set relay path idle timeout"); -1032 } -1033 -1034 self.set_path_status(conn_id, path, &network_path); -1035 self.paths -1036 .insert_open_path(network_path.remote().clone(), Source::Connection); -1037 Some(network_path) -1038 } -1039 -1040 fn set_path_status( -1041 &mut self, -1042 conn_id: ConnId, -1043 path: &noq::Path, -1044 network_path: &TransportFourTuple, -1045 ) { -1046 let status = self.path_status_for_addr(network_path); -1047 match path.set_status(status) { -1048 Err(error) => warn!(?error, ?network_path, ?status, "set_status failed"), -1049 Ok(prev_status) if prev_status != status => { -1050 event!( -1051 target: "iroh::_events::path::set_status", -1052 Level::DEBUG, -1053 remote = %self.endpoint_id.fmt_short(), -1054 path_remote = ?network_path, -1055 ?status, -1056 %conn_id, -1057 path_id=%path.id(), -1058 ?prev_status, -1059 ); -1060 } -1061 Ok(_) => {} -1062 } -1063 } -1064 -1065 fn open_path_on_conn( -1066 &mut self, -1067 conn_id: ConnId, -1068 conn_state: &ConnectionState, -1069 conn: &noq::Connection, -1070 open_addr: &TransportFourTuple, -1071 ) { -1072 // Only the client opens paths; the server receives them via -1073 // QUIC frames and reacts to PathOpened events. -1074 if conn.side().is_server() { -1075 return; -1076 } -1077 // Already open on this connection; nothing to do. -1078 if conn_state.paths.values().any(|a| a == open_addr) { -1079 return; -1080 } -1081 -1082 let quic_addr = self.quic_mapped_four_tuple(open_addr); -1083 let path_status = self.path_status_for_addr(open_addr); +851 // See https://github.com/n0-computer/iroh/issues/4280. +852 if let Err(err) = send_datagram(&mut sender, addr.remote.clone(), None, transmit).await +853 { +854 debug!(?addr, "failed to send datagram on selected_path: {err:#}"); +855 } +856 } else { +857 trace!( +858 paths = ?self.paths.addrs().collect::<Vec<_>>(), +859 "sending datagram to all known paths", +860 ); +861 if self.paths.is_empty() { +862 warn!("Cannot send datagrams: No paths to remote endpoint known"); +863 } +864 +865 for addr in self.paths.addrs() { +866 // We never want to send to our local addresses. +867 // The local address set is updated in the main loop so we can use `peek` here. +868 if let transports::Addr::Ip(sockaddr) = addr +869 && self +870 .local_direct_addrs +871 .peek() +872 .iter() +873 .any(|a| a.addr == *sockaddr) +874 { +875 trace!(%sockaddr, "not sending datagram to our own address"); +876 +877 // TODO(Frando): We might want to include a local IP here in the future, if we confidently +878 // know that it is the correct one. +879 // See https://github.com/n0-computer/iroh/issues/4280. +880 } else if let Err(err) = +881 send_datagram(&mut sender, addr.clone(), None, transmit.clone()).await +882 { +883 debug!(?addr, "failed to send datagram: {err:#}"); +884 } +885 } +886 // This message is received *before* a connection is added. So we do +887 // not yet have a connection to holepunch. Instead we trigger +888 // holepunching when AddConnection is received. +889 } +890 } +891 +892 /// Handles [`RemoteStateMessage::ResolveRemote`]. +893 fn handle_msg_resolve_remote( +894 &mut self, +895 addrs: BTreeSet<TransportAddr>, +896 tx: oneshot::Sender<Result<(), AddressLookupFailed>>, +897 ) { +898 let addrs = to_transports_addr(self.endpoint_id, addrs); +899 self.paths.insert_multiple(addrs, Source::App); +900 self.paths.resolve_remote(tx); +901 // Start Address Lookup if we have no selected path. +902 self.trigger_address_lookup(); +903 } +904 +905 /// Triggers Address Lookup for the remote endpoint, if needed. +906 /// +907 /// Does not start Address Lookup if we have a selected path or if Address Lookup is +908 /// currently running. +909 fn trigger_address_lookup(&mut self) { +910 if self.selected_path.is_some() || self.address_lookup_stream.is_some() { +911 return; +912 } +913 let stream = self.address_lookup.resolve(self.endpoint_id); +914 let stream = stream.filter_map(|item| match item { +915 // We don't care about errors from individual services, we just continue. +916 // Individual errors are buffered into the final error by `AddressLookupServices::resolve`, +917 // and if the lookup fails we return them upstream with the final `AddressLookupFailed` error. +918 Ok(Err(_err)) => None, +919 Ok(Ok(item)) => Some(Ok(item)), +920 Err(err) => Some(Err(err)), +921 }); +922 self.address_lookup_stream = Some(Box::pin(stream)); +923 } +924 +925 /// Handles an address lookup result. +926 /// +927 /// All address lookup results end up being sent here. It takes care of updating the +928 /// [`RemotePathState`] with the results. +929 fn handle_address_lookup_item( +930 &mut self, +931 item: Option<Result<AddressLookupItem, AddressLookupFailed>>, +932 ) { +933 match item { +934 None => { +935 self.paths.address_lookup_finished(Ok(())); +936 self.address_lookup_stream = None; +937 } +938 Some(Err(err)) => { +939 warn!("Address Lookup failed: {err:#}"); +940 self.paths.address_lookup_finished(Err(err)); +941 self.address_lookup_stream = None; +942 } +943 Some(Ok(item)) => { +944 if item.endpoint_id() != self.endpoint_id { +945 warn!( +946 ?item, +947 "Address Lookup emitted item for wrong remote endpoint" +948 ); +949 } else { +950 let source = Source::AddressLookup { +951 name: item.provenance().to_string(), +952 }; +953 let addrs = +954 to_transports_addr(self.endpoint_id, item.into_endpoint_addr().addrs); +955 self.paths.insert_multiple(addrs, source); +956 } +957 } +958 } +959 } +960 +961 /// Unconditionally perform holepunching. +962 #[instrument(skip_all)] +963 fn do_holepunching(&mut self, conn: noq::Connection) { +964 self.metrics.holepunch_attempts.inc(); +965 let local_candidates = self.local_candidates(); +966 match conn.initiate_nat_traversal_round() { +967 Ok(remote_candidates) => { +968 let remote_candidates = remote_candidates +969 .iter() +970 .map(|addr| SocketAddr::new(addr.ip().to_canonical(), addr.port())) +971 .collect(); +972 event!( +973 target: "iroh::_events::qnt::init", +974 Level::DEBUG, +975 remote = %self.endpoint_id.fmt_short(), +976 ?local_candidates, +977 ?remote_candidates, +978 ); +979 self.last_holepunch = Some(HolepunchAttempt { +980 when: Instant::now(), +981 local_candidates, +982 remote_candidates, +983 }); +984 } +985 Err(err) => { +986 debug!("failed to initiate NAT traversal: {err:#}"); +987 use noq_proto::n0_nat_traversal::Error; +988 match err { +989 Error::Closed +990 | Error::TooManyAddresses +991 | Error::WrongConnectionSide +992 | Error::ExtensionNotNegotiated => { +993 // Fatal, no need to retry for now +994 } +995 Error::Multipath(_) | Error::NotEnoughAddresses => { +996 // Retry in a bit +997 let now = Instant::now(); +998 let next_hp = now + Duration::from_millis(100); +999 trace!(scheduled_in = ?(next_hp - now), "holepunching retry"); +1000 self.scheduled_holepunch = Some(next_hp); +1001 } +1002 } +1003 } +1004 } +1005 } +1006 +1007 /// Register a path with our state and configure path-specific settings. +1008 /// +1009 /// This inserts the path in the [`ConnectionState`] and [`Self::paths`]. +1010 /// +1011 /// It configures the path with the correct path status (see [`Self::set_path_status`]), +1012 /// and applies path-type-specific settings: +1013 /// Relay paths get a longer idle timeout to accommodate transparent reconnection +1014 /// by the relay actor (see [`RELAY_PATH_MAX_IDLE_TIMEOUT`]). +1015 fn register_and_configure_path( +1016 &mut self, +1017 conn_id: ConnId, +1018 conn_state: &mut ConnectionState, +1019 path: &noq::Path, +1020 ) -> Option<TransportFourTuple> { +1021 let network_path = self.transport_addr_for_path(path)?; +1022 event!( +1023 target: "iroh::_events::path::open", +1024 Level::DEBUG, +1025 remote = %self.endpoint_id.fmt_short(), +1026 ?network_path, +1027 %conn_id, +1028 path_id=%path.id(), +1029 ); +1030 conn_state.add_open_path(network_path.clone(), path.id(), &self.metrics); +1031 if matches!(network_path.remote(), transports::Addr::Relay(..)) +1032 && let Err(e) = path.set_max_idle_timeout(Some(RELAY_PATH_MAX_IDLE_TIMEOUT)) +1033 { +1034 debug!(?e, "failed to set relay path idle timeout"); +1035 } +1036 +1037 self.set_path_status(conn_id, path, &network_path); +1038 self.paths +1039 .insert_open_path(network_path.remote().clone(), Source::Connection); +1040 Some(network_path) +1041 } +1042 +1043 fn set_path_status( +1044 &mut self, +1045 conn_id: ConnId, +1046 path: &noq::Path, +1047 network_path: &TransportFourTuple, +1048 ) { +1049 let status = self.path_status_for_addr(network_path); +1050 match path.set_status(status) { +1051 Err(error) => warn!(?error, ?network_path, ?status, "set_status failed"), +1052 Ok(prev_status) if prev_status != status => { +1053 event!( +1054 target: "iroh::_events::path::set_status", +1055 Level::DEBUG, +1056 remote = %self.endpoint_id.fmt_short(), +1057 path_remote = ?network_path, +1058 ?status, +1059 %conn_id, +1060 path_id=%path.id(), +1061 ?prev_status, +1062 ); +1063 } +1064 Ok(_) => {} +1065 } +1066 } +1067 +1068 fn open_path_on_conn( +1069 &mut self, +1070 conn_id: ConnId, +1071 conn_state: &ConnectionState, +1072 conn: &noq::Connection, +1073 open_addr: &TransportFourTuple, +1074 ) { +1075 // Only the client opens paths; the server receives them via +1076 // QUIC frames and reacts to PathOpened events. +1077 if conn.side().is_server() { +1078 return; +1079 } +1080 // Already open on this connection; nothing to do. +1081 if conn_state.paths.values().any(|a| a == open_addr) { +1082 return; +1083 } 1084 -1085 let fut = conn.open_path_ensure(quic_addr, path_status); -1086 match fut.path_id() { -1087 Some(path_id) => { -1088 trace!(%conn_id, %path_id, ?path_status, "opening new path"); -1089 } -1090 None => { -1091 let ret = now_or_never(fut); -1092 match ret { -1093 Some(Err(PathError::RemoteCidsExhausted)) => { -1094 self.scheduled_open_path = -1095 Some(Instant::now() + Duration::from_millis(333)); -1096 self.pending_open_paths.push_back(open_addr.clone()); -1097 trace!(?open_addr, "scheduling open_path"); -1098 } -1099 _ => warn!(?ret, "Opening path failed"), -1100 } -1101 } -1102 } -1103 } -1104 -1105 /// Returns the [`PathStatus`] for `addr`. -1106 /// -1107 /// Returns [`PathStatus::Available`] if `addr` is the currently-selected path, -1108 /// or [`PathStatus::Backup`] otherwise. -1109 fn path_status_for_addr(&self, addr: &TransportFourTuple) -> PathStatus { -1110 if Some(addr) == self.selected_path.as_ref() { -1111 PathStatus::Available -1112 } else { -1113 PathStatus::Backup -1114 } -1115 } -1116 -1117 /// Returns the QUIC-mapped [`FourTuple`] for a [`TransportFourTuple`]. -1118 fn quic_mapped_four_tuple(&self, network_path: &TransportFourTuple) -> FourTuple { -1119 let remote = match &network_path.remote { -1120 transports::Addr::Ip(socket_addr) => *socket_addr, -1121 transports::Addr::Relay(relay_url, eid) => self -1122 .relay_mapped_addrs -1123 .get(&(relay_url.clone(), *eid)) -1124 .private_socket_addr(), -1125 transports::Addr::Custom(remote) => { -1126 self.custom_mapped_addrs.get(remote).private_socket_addr() -1127 } -1128 }; -1129 FourTuple::new(remote, network_path.noq_local_ip) -1130 } -1131 -1132 /// Returns the [`transports::Addr] for a path. -1133 fn transport_addr_for_path(&self, path: &noq::Path) -> Option<TransportFourTuple> { -1134 let noq_network_path = path.network_path().ok()?; -1135 let remote = to_transport_addr( -1136 noq_network_path.remote(), -1137 &self.relay_mapped_addrs, -1138 &self.custom_mapped_addrs, -1139 )?; -1140 -1141 Some(TransportFourTuple::new(remote, noq_network_path.local_ip())) -1142 } +1085 let quic_addr = self.quic_mapped_four_tuple(open_addr); +1086 let path_status = self.path_status_for_addr(open_addr); +1087 +1088 let fut = conn.open_path_ensure(quic_addr, path_status); +1089 match fut.path_id() { +1090 Some(path_id) => { +1091 trace!(%conn_id, %path_id, ?path_status, "opening new path"); +1092 } +1093 None => { +1094 let ret = now_or_never(fut); +1095 match ret { +1096 Some(Err(PathError::RemoteCidsExhausted)) => { +1097 self.scheduled_open_path = +1098 Some(Instant::now() + Duration::from_millis(333)); +1099 self.pending_open_paths.push_back(open_addr.clone()); +1100 trace!(?open_addr, "scheduling open_path"); +1101 } +1102 _ => warn!(?ret, "Opening path failed"), +1103 } +1104 } +1105 } +1106 } +1107 +1108 /// Returns the [`PathStatus`] for `addr`. +1109 /// +1110 /// Returns [`PathStatus::Available`] if `addr` is the currently-selected path, +1111 /// or [`PathStatus::Backup`] otherwise. +1112 fn path_status_for_addr(&self, addr: &TransportFourTuple) -> PathStatus { +1113 if Some(addr) == self.selected_path.as_ref() { +1114 PathStatus::Available +1115 } else { +1116 PathStatus::Backup +1117 } +1118 } +1119 +1120 /// Returns the QUIC-mapped [`FourTuple`] for a [`TransportFourTuple`]. +1121 fn quic_mapped_four_tuple(&self, network_path: &TransportFourTuple) -> FourTuple { +1122 let remote = match &network_path.remote { +1123 transports::Addr::Ip(socket_addr) => *socket_addr, +1124 transports::Addr::Relay(relay_url, eid) => self +1125 .relay_mapped_addrs +1126 .get(&(relay_url.clone(), *eid)) +1127 .private_socket_addr(), +1128 transports::Addr::Custom(remote) => { +1129 self.custom_mapped_addrs.get(remote).private_socket_addr() +1130 } +1131 }; +1132 FourTuple::new(remote, network_path.noq_local_ip) +1133 } +1134 +1135 /// Returns the [`transports::Addr] for a path. +1136 fn transport_addr_for_path(&self, path: &noq::Path) -> Option<TransportFourTuple> { +1137 let noq_network_path = path.network_path().ok()?; +1138 let remote = to_transport_addr( +1139 noq_network_path.remote(), +1140 &self.relay_mapped_addrs, +1141 &self.custom_mapped_addrs, +1142 )?; 1143 -1144 /// Returns the current set of local direct addresses. -1145 fn local_candidates(&mut self) -> BTreeSet<SocketAddr> { -1146 self.local_direct_addrs -1147 .get() -1148 .iter() -1149 .map(|d| d.addr) -1150 .collect() -1151 } -1152} -1153 -1154/// Identifies a network path by the combination of remote and local addresses. -1155/// -1156/// Mirrors [`noq::FourTuple`] but uses [`transports::Addr`] for the remote address. -1157#[derive(Debug, Hash, Eq, PartialEq, Clone)] -1158pub(super) struct TransportFourTuple { -1159 /// The remote side of this tuple. -1160 remote: transports::Addr, -1161 /// The local side of this tuple. -1162 /// -1163 /// This is the IP address, unmodified as returned from [`noq::Path::local_ip`]. -1164 /// We pass it back to noq as-is when opening paths on other connections. +1144 Some(TransportFourTuple::new(remote, noq_network_path.local_ip())) +1145 } +1146 +1147 /// Returns the current set of local direct addresses. +1148 fn local_candidates(&mut self) -> BTreeSet<SocketAddr> { +1149 self.local_direct_addrs +1150 .get() +1151 .iter() +1152 .map(|d| d.addr) +1153 .collect() +1154 } +1155} +1156 +1157/// Identifies a network path by the combination of remote and local addresses. +1158/// +1159/// Mirrors [`noq::FourTuple`] but uses [`transports::Addr`] for the remote address. +1160#[derive(Debug, Hash, Eq, PartialEq, Clone)] +1161pub(super) struct TransportFourTuple { +1162 /// The remote side of this tuple. +1163 remote: transports::Addr, +1164 /// The local side of this tuple. 1165 /// -1166 /// Its meaning is a bit particular: -1167 /// * For IP transports this is the interface IP, if known. -1168 /// * For custom transports this is a mapped custom transport address. -1169 /// * For relay transports this is never set. -1170 noq_local_ip: Option<IpAddr>, -1171} -1172 -1173impl std::fmt::Display for TransportFourTuple { -1174 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { -1175 write!(f, "{:?}->{:?}", self.noq_local_ip, self.remote) -1176 } -1177} -1178 -1179impl TransportFourTuple { -1180 /// Creates a new [`TransportFourTuple`]. -1181 pub(super) fn new(remote: transports::Addr, noq_local_ip: Option<IpAddr>) -> Self { -1182 Self { -1183 remote, -1184 noq_local_ip, -1185 } -1186 } -1187 -1188 /// Returns the remote address of the network path. -1189 pub(super) fn remote(&self) -> &transports::Addr { -1190 &self.remote -1191 } -1192 -1193 /// Returns the [`LocalTransportAddr`] for this network path. -1194 /// -1195 /// * For IP transports, it is the address of the local socket. -1196 /// * For relay transports, we never set the local_ip in the recv meta. -1197 /// We take the relay URL of the remote address here instead. -1198 /// * For custom transports, the custom transport implementation can set a [`CustomAddr`] -1199 /// which we convert back into here from the mapped address. -1200 pub(super) fn local( -1201 &self, -1202 custom_mapped_addrs: &AddrMap<CustomAddr, CustomMappedAddr>, -1203 ) -> LocalTransportAddr { -1204 LocalTransportAddr::from_noq_local_ip_with_custom_addr_map( -1205 self.noq_local_ip, -1206 &self.remote, -1207 custom_mapped_addrs, -1208 ) -1209 } -1210 -1211 /// Returns whether the remote of this tuple is an IP address. -1212 pub(super) fn is_ip(&self) -> bool { -1213 self.remote.is_ip() -1214 } -1215 -1216 /// Returns whether the remote of this tuple is a relay address. -1217 pub(super) fn is_relay(&self) -> bool { -1218 self.remote.is_relay() -1219 } -1220} -1221 -1222/// Returns `Some` if a new path should be selected, `None` if the `current_path` should -1223/// continued to be used. -1224fn select_best_path<'a>( -1225 all_paths: FxHashMap<&'a TransportFourTuple, PathSelectionData>, -1226 current_path: Option<&'a TransportFourTuple>, -1227) -> Option<(TransportFourTuple, Duration)> { -1228 // Determine the best new path according to sort_key. -1229 // If there is no path, return None. -1230 let (best_addr, best_data) = all_paths.iter().min_by_key(|(_, psd)| psd.sort_key())?; -1231 // If there is no current path, always switch to the best path. -1232 let Some(addr) = current_path else { -1233 return Some(((*best_addr).clone(), best_data.rtt)); -1234 }; -1235 // Get current data. If we don't have data for the current path, switch to the best path. -1236 let Some(current_data) = all_paths.get(addr) else { -1237 return Some(((*best_addr).clone(), best_data.rtt)); -1238 }; -1239 if current_data.transport_type != best_data.transport_type { -1240 // Always switch if the status is different (better). -1241 Some(((*best_addr).clone(), best_data.rtt)) -1242 } else if best_data.biased_rtt + RTT_SWITCHING_MIN_IP.as_nanos() as i128 -1243 <= current_data.biased_rtt -1244 { -1245 // For the same status, only switch if the biased RTT is significantly better. -1246 Some(((*best_addr).clone(), best_data.rtt)) -1247 } else { -1248 None -1249 } -1250} -1251 -1252/// Updates QNT's candidate addresses to be the current set of direct addresses. -1253/// -1254/// `direct_addrs` must be a set of addresses extracted from the endpoint's current -1255/// [`DirectAddr`]s. -1256fn update_qnt_candidates(conn: &noq::Connection, direct_addrs: &BTreeSet<SocketAddr>) { -1257 let noq_candidates = match conn.get_local_nat_traversal_addresses() { -1258 Ok(addrs) => BTreeSet::from_iter(addrs), -1259 Err(err) => { -1260 warn!("failed to get local nat candidates: {err:#}"); -1261 return; -1262 } -1263 }; -1264 for addr in direct_addrs.difference(&noq_candidates) { -1265 if let Err(err) = conn.add_nat_traversal_address(*addr) { -1266 warn!("failed adding local addr: {err:#}",); -1267 } -1268 } -1269 for addr in noq_candidates.difference(direct_addrs) { -1270 if let Err(err) = conn.remove_nat_traversal_address(*addr) { -1271 warn!("failed removing local addr: {err:#}"); -1272 } -1273 } -1274 trace!(?direct_addrs, "updated local QNT addresses"); -1275} -1276 -1277fn send_datagram<'a>( -1278 sender: &'a mut TransportsSender, -1279 addr: transports::Addr, -1280 owned_transmit: OwnedTransmit, -1281) -> impl Future<Output = n0_error::Result<()>> + 'a { -1282 std::future::poll_fn(move |cx| { -1283 let transmit = transports::Transmit { -1284 ecn: owned_transmit.ecn, -1285 contents: owned_transmit.contents.as_ref(), -1286 segment_size: owned_transmit.segment_size, -1287 }; -1288 -1289 // TODO: Add support for source address here? -1290 Pin::new(&mut *sender) -1291 .poll_send(cx, &addr, None, &transmit) -1292 .map(|res| res.with_context(|_| format!("failed to send datagram to {:?}", addr))) -1293 }) -1294} -1295 -1296/// Messages to send to the [`RemoteStateActor`]. -1297#[derive(derive_more::Debug)] -1298pub(crate) enum RemoteStateMessage { -1299 /// Sends a datagram to all known paths. -1300 /// -1301 /// Used to send QUIC Initial packets. If there is no working direct path this will -1302 /// trigger holepunching. +1166 /// This is the IP address, unmodified as returned from [`noq::Path::local_ip`]. +1167 /// We pass it back to noq as-is when opening paths on other connections. +1168 /// +1169 /// Its meaning is a bit particular: +1170 /// * For IP transports this is the interface IP, if known. +1171 /// * For custom transports this is a mapped custom transport address. +1172 /// * For relay transports this is never set. +1173 noq_local_ip: Option<IpAddr>, +1174} +1175 +1176impl std::fmt::Display for TransportFourTuple { +1177 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +1178 write!(f, "{:?}->{:?}", self.noq_local_ip, self.remote) +1179 } +1180} +1181 +1182impl TransportFourTuple { +1183 /// Creates a new [`TransportFourTuple`]. +1184 pub(super) fn new(remote: transports::Addr, noq_local_ip: Option<IpAddr>) -> Self { +1185 Self { +1186 remote, +1187 noq_local_ip, +1188 } +1189 } +1190 +1191 /// Returns the remote address of the network path. +1192 pub(super) fn remote(&self) -> &transports::Addr { +1193 &self.remote +1194 } +1195 +1196 /// Returns the [`LocalTransportAddr`] for this network path. +1197 /// +1198 /// * For IP transports, it is the address of the local socket. +1199 /// * For relay transports, we never set the local_ip in the recv meta. +1200 /// We take the relay URL of the remote address here instead. +1201 /// * For custom transports, the custom transport implementation can set a [`CustomAddr`] +1202 /// which we convert back into here from the mapped address. +1203 pub(super) fn local( +1204 &self, +1205 custom_mapped_addrs: &AddrMap<CustomAddr, CustomMappedAddr>, +1206 ) -> LocalTransportAddr { +1207 LocalTransportAddr::from_noq_local_ip_with_custom_addr_map( +1208 self.noq_local_ip, +1209 &self.remote, +1210 custom_mapped_addrs, +1211 ) +1212 } +1213 +1214 /// Returns whether the remote of this tuple is an IP address. +1215 pub(super) fn is_ip(&self) -> bool { +1216 self.remote.is_ip() +1217 } +1218 +1219 /// Returns whether the remote of this tuple is a relay address. +1220 pub(super) fn is_relay(&self) -> bool { +1221 self.remote.is_relay() +1222 } +1223} +1224 +1225/// Returns `Some` if a new path should be selected, `None` if the `current_path` should +1226/// continued to be used. +1227fn select_best_path<'a>( +1228 all_paths: FxHashMap<&'a TransportFourTuple, PathSelectionData>, +1229 current_path: Option<&'a TransportFourTuple>, +1230) -> Option<(TransportFourTuple, Duration)> { +1231 // Determine the best new path according to sort_key. +1232 // If there is no path, return None. +1233 let (best_addr, best_data) = all_paths.iter().min_by_key(|(_, psd)| psd.sort_key())?; +1234 // If there is no current path, always switch to the best path. +1235 let Some(addr) = current_path else { +1236 return Some(((*best_addr).clone(), best_data.rtt)); +1237 }; +1238 // Get current data. If we don't have data for the current path, switch to the best path. +1239 let Some(current_data) = all_paths.get(addr) else { +1240 return Some(((*best_addr).clone(), best_data.rtt)); +1241 }; +1242 if current_data.transport_type != best_data.transport_type { +1243 // Always switch if the status is different (better). +1244 Some(((*best_addr).clone(), best_data.rtt)) +1245 } else if best_data.biased_rtt + RTT_SWITCHING_MIN_IP.as_nanos() as i128 +1246 <= current_data.biased_rtt +1247 { +1248 // For the same status, only switch if the biased RTT is significantly better. +1249 Some(((*best_addr).clone(), best_data.rtt)) +1250 } else { +1251 None +1252 } +1253} +1254 +1255/// Updates QNT's candidate addresses to be the current set of direct addresses. +1256/// +1257/// `direct_addrs` must be a set of addresses extracted from the endpoint's current +1258/// [`DirectAddr`]s. +1259fn update_qnt_candidates(conn: &noq::Connection, direct_addrs: &BTreeSet<SocketAddr>) { +1260 let noq_candidates = match conn.get_local_nat_traversal_addresses() { +1261 Ok(addrs) => BTreeSet::from_iter(addrs), +1262 Err(err) => { +1263 warn!("failed to get local nat candidates: {err:#}"); +1264 return; +1265 } +1266 }; +1267 for addr in direct_addrs.difference(&noq_candidates) { +1268 if let Err(err) = conn.add_nat_traversal_address(*addr) { +1269 warn!("failed adding local addr: {err:#}",); +1270 } +1271 } +1272 for addr in noq_candidates.difference(direct_addrs) { +1273 if let Err(err) = conn.remove_nat_traversal_address(*addr) { +1274 warn!("failed removing local addr: {err:#}"); +1275 } +1276 } +1277 trace!(?direct_addrs, "updated local QNT addresses"); +1278} +1279 +1280fn send_datagram<'a>( +1281 sender: &'a mut TransportsSender, +1282 addr: transports::Addr, +1283 local_ip: Option<IpAddr>, +1284 owned_transmit: OwnedTransmit, +1285) -> impl Future<Output = n0_error::Result<()>> + 'a { +1286 std::future::poll_fn(move |cx| { +1287 let transmit = transports::Transmit { +1288 ecn: owned_transmit.ecn, +1289 contents: owned_transmit.contents.as_ref(), +1290 segment_size: owned_transmit.segment_size, +1291 }; +1292 +1293 Pin::new(&mut *sender) +1294 .poll_send(cx, &addr, local_ip, &transmit) +1295 .map(|res| res.with_context(|_| format!("failed to send datagram to {:?}", addr))) +1296 }) +1297} +1298 +1299/// Messages to send to the [`RemoteStateActor`]. +1300#[derive(derive_more::Debug)] +1301pub(crate) enum RemoteStateMessage { +1302 /// Sends a datagram to all known paths. 1303 /// -1304 /// This is not acceptable to use on the normal send path, as it is an async send -1305 /// operation with a bunch more copying. So it should only be used for sending QUIC -1306 /// Initial packets. -1307 #[debug("SendDatagram(..)")] -1308 SendDatagram(Box<TransportsSender>, OwnedTransmit), -1309 /// Adds an active connection to this remote endpoint. -1310 /// -1311 /// The actor will downgrade the connection to a [`noq::WeakConnectionHandle`] as soon -1312 /// as it processes the message. It will keep hold of the weak handle until it closes, -1313 /// but only update to a strong [`noq::Connection`] for brief moments. -1314 /// -1315 /// The actor will actively manage paths on the connection and start holepunching as needed. -1316 #[debug("AddConnection(..)")] -1317 AddConnection(noq::Connection, oneshot::Sender<PathStateReceiver>), -1318 /// Asks if there is any possible path that could be used. -1319 /// -1320 /// This adds the provided transport addresses to the list of potential paths for this -1321 /// remote and starts Address Lookup if needed. +1304 /// Used to send QUIC Initial packets. If there is no working direct path this will +1305 /// trigger holepunching. +1306 /// +1307 /// This is not acceptable to use on the normal send path, as it is an async send +1308 /// operation with a bunch more copying. So it should only be used for sending QUIC +1309 /// Initial packets. +1310 #[debug("SendDatagram(..)")] +1311 SendDatagram(Box<TransportsSender>, OwnedTransmit), +1312 /// Adds an active connection to this remote endpoint. +1313 /// +1314 /// The actor will downgrade the connection to a [`noq::WeakConnectionHandle`] as soon +1315 /// as it processes the message. It will keep hold of the weak handle until it closes, +1316 /// but only update to a strong [`noq::Connection`] for brief moments. +1317 /// +1318 /// The actor will actively manage paths on the connection and start holepunching as needed. +1319 #[debug("AddConnection(..)")] +1320 AddConnection(noq::Connection, oneshot::Sender<PathStateReceiver>), +1321 /// Asks if there is any possible path that could be used. 1322 /// -1323 /// Sends back `Ok` immediately if the provided address list is non-empy or we have are -1324 /// other known paths. Otherwise sends back `Ok` once Address Lookup produces a result, -1325 /// or the Address Lookup error if Address Lookup fails or produces no results, -1326 #[debug("ResolveRemote(..)")] -1327 ResolveRemote( -1328 BTreeSet<TransportAddr>, -1329 oneshot::Sender<Result<(), AddressLookupFailed>>, -1330 ), -1331 /// Returns information about the remote. -1332 /// -1333 /// This currently only includes a list of all known transport addresses for the remote. -1334 RemoteInfo(oneshot::Sender<RemoteInfo>), -1335 /// The network status has changed in some way -1336 NetworkChange { is_major: bool }, -1337} -1338 -1339/// Information about a holepunch attempt. -1340/// -1341/// Addresses are always stored in canonical form. -1342#[derive(Debug)] -1343struct HolepunchAttempt { -1344 when: Instant, -1345 /// The set of local addresses which could take part in holepunching. -1346 /// -1347 /// This does not mean every address here participated in the holepunching. E.g. we -1348 /// could have tried only a sub-set of the addresses because a previous attempt already -1349 /// covered part of the range. -1350 /// -1351 /// We do not store this as a [`DirectAddr`] because this is checked for equality and we -1352 /// do not want to compare the sources of these addresses. -1353 local_candidates: BTreeSet<SocketAddr>, -1354 /// The set of remote addresses which could take part in holepunching. -1355 /// -1356 /// Like [`Self::local_candidates`] we may not have used them. -1357 remote_candidates: BTreeSet<SocketAddr>, -1358} -1359 -1360/// Newtype to track Connections. -1361/// -1362/// The wrapped value is the [`noq::Connection::stable_id`] value, and is thus only valid -1363/// for active connections. -1364#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, derive_more::Display)] -1365#[display("{_0}")] -1366struct ConnId(usize); -1367 -1368/// State about one connection. -1369#[derive(Debug)] -1370struct ConnectionState { -1371 /// Weak handle to the connection. -1372 handle: WeakConnectionHandle, -1373 /// Writer-side handle for the connection's path observation state. -1374 /// -1375 /// The matching [`PathStateReceiver`] is held by the [`Connection`]. -1376 /// -1377 /// [`Connection`]: crate::endpoint::Connection -1378 path_state: PathStateSender, -1379 /// The open paths that exist on this connection. -1380 paths: FxHashMap<PathId, TransportFourTuple>, -1381 /// Whether this connection has ever had a direct path. -1382 /// -1383 /// Used for recording metrics. -1384 has_been_direct: bool, -1385} -1386 -1387impl ConnectionState { -1388 /// Tracks an open path for the connection. -1389 fn add_open_path( -1390 &mut self, -1391 network_path: TransportFourTuple, -1392 path_id: PathId, -1393 metrics: &Arc<SocketMetrics>, -1394 ) { -1395 match &network_path.remote { -1396 transports::Addr::Ip(_) => metrics.paths_direct.inc(), -1397 transports::Addr::Relay(_, _) => metrics.paths_relay.inc(), -1398 transports::Addr::Custom(_) => metrics.paths_custom.inc(), -1399 }; -1400 if !self.has_been_direct && network_path.is_ip() { -1401 self.has_been_direct = true; -1402 metrics.num_conns_direct.inc(); -1403 } -1404 -1405 self.paths.insert(path_id, network_path.clone()); -1406 if let Some(conn) = self.handle.upgrade() -1407 && let Some(path) = conn.path(path_id) -1408 { -1409 let handle = path.weak_handle(); -1410 self.path_state.record_opened(handle, network_path); -1411 } -1412 } -1413 -1414 /// Removes a path from this connection. -1415 fn remove_path( -1416 &mut self, -1417 path_id: &PathId, -1418 conn: &noq::Connection, -1419 ) -> Option<TransportFourTuple> { -1420 let addr = self.paths.remove(path_id)?; -1421 self.path_state.record_abandoned(*path_id, conn); -1422 Some(addr) -1423 } -1424} -1425 -1426/// Poll a future once, like n0_future::future::poll_once but sync. -1427fn now_or_never<T, F: Future<Output = T>>(fut: F) -> Option<T> { -1428 let fut = std::pin::pin!(fut); -1429 match fut.poll(&mut std::task::Context::from_waker(std::task::Waker::noop())) { -1430 Poll::Ready(res) => Some(res), -1431 Poll::Pending => None, -1432 } -1433} -1434 -1435/// Future that resolves to the `conn_id` once a connection is closed. -1436/// -1437/// This uses [`noq::Connection::on_closed`], which does not keep the connection alive -1438/// while awaiting the future. -1439struct OnClosed { -1440 conn_id: ConnId, -1441 inner: noq::OnClosed, -1442} -1443 -1444impl OnClosed { -1445 fn new(conn: &noq::Connection) -> Self { -1446 Self { -1447 conn_id: ConnId(conn.stable_id()), -1448 inner: conn.on_closed(), -1449 } -1450 } -1451} -1452 -1453impl Future for OnClosed { -1454 type Output = (ConnId, Closed); +1323 /// This adds the provided transport addresses to the list of potential paths for this +1324 /// remote and starts Address Lookup if needed. +1325 /// +1326 /// Sends back `Ok` immediately if the provided address list is non-empy or we have are +1327 /// other known paths. Otherwise sends back `Ok` once Address Lookup produces a result, +1328 /// or the Address Lookup error if Address Lookup fails or produces no results, +1329 #[debug("ResolveRemote(..)")] +1330 ResolveRemote( +1331 BTreeSet<TransportAddr>, +1332 oneshot::Sender<Result<(), AddressLookupFailed>>, +1333 ), +1334 /// Returns information about the remote. +1335 /// +1336 /// This currently only includes a list of all known transport addresses for the remote. +1337 RemoteInfo(oneshot::Sender<RemoteInfo>), +1338 /// The network status has changed in some way +1339 NetworkChange { is_major: bool }, +1340} +1341 +1342/// Information about a holepunch attempt. +1343/// +1344/// Addresses are always stored in canonical form. +1345#[derive(Debug)] +1346struct HolepunchAttempt { +1347 when: Instant, +1348 /// The set of local addresses which could take part in holepunching. +1349 /// +1350 /// This does not mean every address here participated in the holepunching. E.g. we +1351 /// could have tried only a sub-set of the addresses because a previous attempt already +1352 /// covered part of the range. +1353 /// +1354 /// We do not store this as a [`DirectAddr`] because this is checked for equality and we +1355 /// do not want to compare the sources of these addresses. +1356 local_candidates: BTreeSet<SocketAddr>, +1357 /// The set of remote addresses which could take part in holepunching. +1358 /// +1359 /// Like [`Self::local_candidates`] we may not have used them. +1360 remote_candidates: BTreeSet<SocketAddr>, +1361} +1362 +1363/// Newtype to track Connections. +1364/// +1365/// The wrapped value is the [`noq::Connection::stable_id`] value, and is thus only valid +1366/// for active connections. +1367#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, derive_more::Display)] +1368#[display("{_0}")] +1369struct ConnId(usize); +1370 +1371/// State about one connection. +1372#[derive(Debug)] +1373struct ConnectionState { +1374 /// Weak handle to the connection. +1375 handle: WeakConnectionHandle, +1376 /// Writer-side handle for the connection's path observation state. +1377 /// +1378 /// The matching [`PathStateReceiver`] is held by the [`Connection`]. +1379 /// +1380 /// [`Connection`]: crate::endpoint::Connection +1381 path_state: PathStateSender, +1382 /// The open paths that exist on this connection. +1383 paths: FxHashMap<PathId, TransportFourTuple>, +1384 /// Whether this connection has ever had a direct path. +1385 /// +1386 /// Used for recording metrics. +1387 has_been_direct: bool, +1388} +1389 +1390impl ConnectionState { +1391 /// Tracks an open path for the connection. +1392 fn add_open_path( +1393 &mut self, +1394 network_path: TransportFourTuple, +1395 path_id: PathId, +1396 metrics: &Arc<SocketMetrics>, +1397 ) { +1398 match &network_path.remote { +1399 transports::Addr::Ip(_) => metrics.paths_direct.inc(), +1400 transports::Addr::Relay(_, _) => metrics.paths_relay.inc(), +1401 transports::Addr::Custom(_) => metrics.paths_custom.inc(), +1402 }; +1403 if !self.has_been_direct && network_path.is_ip() { +1404 self.has_been_direct = true; +1405 metrics.num_conns_direct.inc(); +1406 } +1407 +1408 self.paths.insert(path_id, network_path.clone()); +1409 if let Some(conn) = self.handle.upgrade() +1410 && let Some(path) = conn.path(path_id) +1411 { +1412 let handle = path.weak_handle(); +1413 self.path_state.record_opened(handle, network_path); +1414 } +1415 } +1416 +1417 /// Removes a path from this connection. +1418 fn remove_path( +1419 &mut self, +1420 path_id: &PathId, +1421 conn: &noq::Connection, +1422 ) -> Option<TransportFourTuple> { +1423 let addr = self.paths.remove(path_id)?; +1424 self.path_state.record_abandoned(*path_id, conn); +1425 Some(addr) +1426 } +1427} +1428 +1429/// Poll a future once, like n0_future::future::poll_once but sync. +1430fn now_or_never<T, F: Future<Output = T>>(fut: F) -> Option<T> { +1431 let fut = std::pin::pin!(fut); +1432 match fut.poll(&mut std::task::Context::from_waker(std::task::Waker::noop())) { +1433 Poll::Ready(res) => Some(res), +1434 Poll::Pending => None, +1435 } +1436} +1437 +1438/// Future that resolves to the `conn_id` once a connection is closed. +1439/// +1440/// This uses [`noq::Connection::on_closed`], which does not keep the connection alive +1441/// while awaiting the future. +1442struct OnClosed { +1443 conn_id: ConnId, +1444 inner: noq::OnClosed, +1445} +1446 +1447impl OnClosed { +1448 fn new(conn: &noq::Connection) -> Self { +1449 Self { +1450 conn_id: ConnId(conn.stable_id()), +1451 inner: conn.on_closed(), +1452 } +1453 } +1454} 1455 -1456 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { -1457 let closed = std::task::ready!(Pin::new(&mut self.inner).poll(cx)); -1458 Poll::Ready((self.conn_id, closed)) -1459 } -1460} -1461 -1462/// Converts an iterator of [`TransportAddr'] into an iterator of [`transports::Addr`]. -1463fn to_transports_addr( -1464 endpoint_id: EndpointId, -1465 addrs: impl IntoIterator<Item = TransportAddr>, -1466) -> impl Iterator<Item = transports::Addr> { -1467 addrs.into_iter().filter_map(move |addr| match addr { -1468 TransportAddr::Relay(relay_url) => Some(transports::Addr::from((relay_url, endpoint_id))), -1469 TransportAddr::Ip(sockaddr) => Some(transports::Addr::from(sockaddr)), -1470 TransportAddr::Custom(custom_addr) => Some(transports::Addr::from(custom_addr)), -1471 _ => { -1472 warn!(?addr, "Unsupported TransportAddr"); -1473 None -1474 } -1475 }) -1476} -1477 -1478/// Returns the next item if `maybe_stream` is `Some`, or `None` otherwise. -1479async fn maybe_next<S: Stream + Unpin>(maybe_stream: Option<&mut S>) -> Option<Option<S::Item>> { -1480 match maybe_stream { -1481 None => None, -1482 Some(s) => Some(s.next().await), -1483 } -1484} -1485 -1486#[cfg(test)] -1487mod tests { -1488 use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6}; -1489 -1490 use super::*; -1491 use crate::socket::transports::TransportType; +1456impl Future for OnClosed { +1457 type Output = (ConnId, Closed); +1458 +1459 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { +1460 let closed = std::task::ready!(Pin::new(&mut self.inner).poll(cx)); +1461 Poll::Ready((self.conn_id, closed)) +1462 } +1463} +1464 +1465/// Converts an iterator of [`TransportAddr'] into an iterator of [`transports::Addr`]. +1466fn to_transports_addr( +1467 endpoint_id: EndpointId, +1468 addrs: impl IntoIterator<Item = TransportAddr>, +1469) -> impl Iterator<Item = transports::Addr> { +1470 addrs.into_iter().filter_map(move |addr| match addr { +1471 TransportAddr::Relay(relay_url) => Some(transports::Addr::from((relay_url, endpoint_id))), +1472 TransportAddr::Ip(sockaddr) => Some(transports::Addr::from(sockaddr)), +1473 TransportAddr::Custom(custom_addr) => Some(transports::Addr::from(custom_addr)), +1474 _ => { +1475 warn!(?addr, "Unsupported TransportAddr"); +1476 None +1477 } +1478 }) +1479} +1480 +1481/// Returns the next item if `maybe_stream` is `Some`, or `None` otherwise. +1482async fn maybe_next<S: Stream + Unpin>(maybe_stream: Option<&mut S>) -> Option<Option<S::Item>> { +1483 match maybe_stream { +1484 None => None, +1485 Some(s) => Some(s.next().await), +1486 } +1487} +1488 +1489#[cfg(test)] +1490mod tests { +1491 use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6}; 1492 -1493 fn v4(port: u16) -> TransportFourTuple { -1494 let remote = -1495 transports::Addr::Ip(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port))); -1496 TransportFourTuple::new(remote, None) -1497 } -1498 -1499 fn v6(port: u16) -> TransportFourTuple { -1500 let remote = transports::Addr::Ip(SocketAddr::V6(SocketAddrV6::new( -1501 Ipv6Addr::LOCALHOST, -1502 port, -1503 0, -1504 0, -1505 ))); -1506 TransportFourTuple::new(remote, None) -1507 } -1508 -1509 fn relay(port: u16) -> TransportFourTuple { -1510 let url = format!("https://relay{port}.iroh.computer") -1511 .parse::<RelayUrl>() -1512 .unwrap(); -1513 let remote = transports::Addr::Relay(url, EndpointId::from_bytes(&[0u8; 32]).unwrap()); -1514 TransportFourTuple::new(remote, None) -1515 } -1516 -1517 fn psd(transport_type: TransportType, rtt_ms: u64) -> PathSelectionData { -1518 let rtt = Duration::from_millis(rtt_ms); -1519 let biased_rtt = rtt.as_nanos() as i128; -1520 PathSelectionData { -1521 transport_type, -1522 rtt, -1523 biased_rtt, -1524 } -1525 } -1526 -1527 fn psd_v6(transport_type: TransportType, rtt_ms: u64) -> PathSelectionData { -1528 let rtt = Duration::from_millis(rtt_ms); -1529 // IPv6 gets a bias advantage -1530 let biased_rtt = rtt.as_nanos() as i128 - transports::IPV6_RTT_ADVANTAGE.as_nanos() as i128; -1531 PathSelectionData { -1532 transport_type, -1533 rtt, -1534 biased_rtt, -1535 } -1536 } -1537 -1538 #[test] -1539 fn test_ipv6_wins_over_ipv4_within_bias() { -1540 let v4 = v4(1); -1541 let v6 = v6(1); -1542 // IPv6 should win over IPv4 when RTTs are the same -1543 let mut paths = FxHashMap::default(); -1544 paths.insert(&v4, psd(TransportType::Primary, 10)); -1545 paths.insert(&v6, psd_v6(TransportType::Primary, 10)); -1546 -1547 let result = select_best_path(paths, None); -1548 assert!(result.is_some()); -1549 let (addr, _) = result.unwrap(); -1550 assert!(matches!( -1551 addr.remote, -1552 transports::Addr::Ip(SocketAddr::V6(_)) -1553 )); -1554 -1555 // IPv6 should still win when it's slightly slower (within bias range) -1556 let mut paths = FxHashMap::default(); -1557 paths.insert(&v4, psd(TransportType::Primary, 10)); -1558 paths.insert(&v6, psd_v6(TransportType::Primary, 12)); // 2ms slower, but 3ms bias -1559 -1560 let result = select_best_path(paths, None); -1561 assert!(result.is_some()); -1562 let (addr, _) = result.unwrap(); -1563 assert!(matches!( -1564 addr.remote, -1565 transports::Addr::Ip(SocketAddr::V6(_)) -1566 )); -1567 -1568 // IPv4 should win when IPv6 is significantly slower -1569 let mut paths = FxHashMap::default(); -1570 paths.insert(&v4, psd(TransportType::Primary, 10)); -1571 paths.insert(&v6, psd_v6(TransportType::Primary, 20)); // 10ms slower, exceeds 3ms bias -1572 -1573 let result = select_best_path(paths, None); -1574 assert!(result.is_some()); -1575 let (addr, _) = result.unwrap(); -1576 assert!(matches!( -1577 addr.remote, -1578 transports::Addr::Ip(SocketAddr::V4(_)) -1579 )); -1580 } -1581 -1582 #[test] -1583 fn test_available_wins_over_backup_regardless_of_rtt() { -1584 let v4 = v4(1); -1585 let relay = relay(1); -1586 // Available path should win even with much higher RTT -1587 let mut paths = FxHashMap::default(); -1588 paths.insert(&v4, psd(TransportType::Primary, 100)); // High RTT but Available -1589 paths.insert(&relay, psd(TransportType::Backup, 10)); // Low RTT but Backup -1590 -1591 let result = select_best_path(paths, None); -1592 assert!(result.is_some()); -1593 let (addr, _) = result.unwrap(); -1594 assert!(addr.is_ip()); -1595 -1596 // Even more extreme: 1000ms Available vs 1ms Backup -1597 let mut paths = FxHashMap::default(); -1598 paths.insert(&v4, psd(TransportType::Primary, 1000)); -1599 paths.insert(&relay, psd(TransportType::Backup, 1)); -1600 -1601 let result = select_best_path(paths, None); -1602 assert!(result.is_some()); -1603 let (addr, _) = result.unwrap(); -1604 assert!(addr.is_ip()); -1605 } -1606 -1607 #[test] -1608 fn test_same_category_only_switches_with_significant_rtt_diff() { -1609 let v4_1 = v4(1); -1610 let v4_2 = v4(2); -1611 let current = v4(1); -1612 -1613 // Should NOT switch: new path is only slightly better (2ms < 5ms threshold) -1614 let mut paths = FxHashMap::default(); -1615 paths.insert(&v4_1, psd(TransportType::Primary, 20)); -1616 paths.insert(&v4_2, psd(TransportType::Primary, 18)); -1617 -1618 let result = select_best_path(paths, Some(&current)); -1619 assert!(result.is_none()); // Should keep current +1493 use super::*; +1494 use crate::socket::transports::TransportType; +1495 +1496 fn v4(port: u16) -> TransportFourTuple { +1497 let remote = +1498 transports::Addr::Ip(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port))); +1499 TransportFourTuple::new(remote, None) +1500 } +1501 +1502 fn v6(port: u16) -> TransportFourTuple { +1503 let remote = transports::Addr::Ip(SocketAddr::V6(SocketAddrV6::new( +1504 Ipv6Addr::LOCALHOST, +1505 port, +1506 0, +1507 0, +1508 ))); +1509 TransportFourTuple::new(remote, None) +1510 } +1511 +1512 fn relay(port: u16) -> TransportFourTuple { +1513 let url = format!("https://relay{port}.iroh.computer") +1514 .parse::<RelayUrl>() +1515 .unwrap(); +1516 let remote = transports::Addr::Relay(url, EndpointId::from_bytes(&[0u8; 32]).unwrap()); +1517 TransportFourTuple::new(remote, None) +1518 } +1519 +1520 fn psd(transport_type: TransportType, rtt_ms: u64) -> PathSelectionData { +1521 let rtt = Duration::from_millis(rtt_ms); +1522 let biased_rtt = rtt.as_nanos() as i128; +1523 PathSelectionData { +1524 transport_type, +1525 rtt, +1526 biased_rtt, +1527 } +1528 } +1529 +1530 fn psd_v6(transport_type: TransportType, rtt_ms: u64) -> PathSelectionData { +1531 let rtt = Duration::from_millis(rtt_ms); +1532 // IPv6 gets a bias advantage +1533 let biased_rtt = rtt.as_nanos() as i128 - transports::IPV6_RTT_ADVANTAGE.as_nanos() as i128; +1534 PathSelectionData { +1535 transport_type, +1536 rtt, +1537 biased_rtt, +1538 } +1539 } +1540 +1541 #[test] +1542 fn test_ipv6_wins_over_ipv4_within_bias() { +1543 let v4 = v4(1); +1544 let v6 = v6(1); +1545 // IPv6 should win over IPv4 when RTTs are the same +1546 let mut paths = FxHashMap::default(); +1547 paths.insert(&v4, psd(TransportType::Primary, 10)); +1548 paths.insert(&v6, psd_v6(TransportType::Primary, 10)); +1549 +1550 let result = select_best_path(paths, None); +1551 assert!(result.is_some()); +1552 let (addr, _) = result.unwrap(); +1553 assert!(matches!( +1554 addr.remote, +1555 transports::Addr::Ip(SocketAddr::V6(_)) +1556 )); +1557 +1558 // IPv6 should still win when it's slightly slower (within bias range) +1559 let mut paths = FxHashMap::default(); +1560 paths.insert(&v4, psd(TransportType::Primary, 10)); +1561 paths.insert(&v6, psd_v6(TransportType::Primary, 12)); // 2ms slower, but 3ms bias +1562 +1563 let result = select_best_path(paths, None); +1564 assert!(result.is_some()); +1565 let (addr, _) = result.unwrap(); +1566 assert!(matches!( +1567 addr.remote, +1568 transports::Addr::Ip(SocketAddr::V6(_)) +1569 )); +1570 +1571 // IPv4 should win when IPv6 is significantly slower +1572 let mut paths = FxHashMap::default(); +1573 paths.insert(&v4, psd(TransportType::Primary, 10)); +1574 paths.insert(&v6, psd_v6(TransportType::Primary, 20)); // 10ms slower, exceeds 3ms bias +1575 +1576 let result = select_best_path(paths, None); +1577 assert!(result.is_some()); +1578 let (addr, _) = result.unwrap(); +1579 assert!(matches!( +1580 addr.remote, +1581 transports::Addr::Ip(SocketAddr::V4(_)) +1582 )); +1583 } +1584 +1585 #[test] +1586 fn test_available_wins_over_backup_regardless_of_rtt() { +1587 let v4 = v4(1); +1588 let relay = relay(1); +1589 // Available path should win even with much higher RTT +1590 let mut paths = FxHashMap::default(); +1591 paths.insert(&v4, psd(TransportType::Primary, 100)); // High RTT but Available +1592 paths.insert(&relay, psd(TransportType::Backup, 10)); // Low RTT but Backup +1593 +1594 let result = select_best_path(paths, None); +1595 assert!(result.is_some()); +1596 let (addr, _) = result.unwrap(); +1597 assert!(addr.is_ip()); +1598 +1599 // Even more extreme: 1000ms Available vs 1ms Backup +1600 let mut paths = FxHashMap::default(); +1601 paths.insert(&v4, psd(TransportType::Primary, 1000)); +1602 paths.insert(&relay, psd(TransportType::Backup, 1)); +1603 +1604 let result = select_best_path(paths, None); +1605 assert!(result.is_some()); +1606 let (addr, _) = result.unwrap(); +1607 assert!(addr.is_ip()); +1608 } +1609 +1610 #[test] +1611 fn test_same_category_only_switches_with_significant_rtt_diff() { +1612 let v4_1 = v4(1); +1613 let v4_2 = v4(2); +1614 let current = v4(1); +1615 +1616 // Should NOT switch: new path is only slightly better (2ms < 5ms threshold) +1617 let mut paths = FxHashMap::default(); +1618 paths.insert(&v4_1, psd(TransportType::Primary, 20)); +1619 paths.insert(&v4_2, psd(TransportType::Primary, 18)); 1620 -1621 // Should NOT switch: new path is just under threshold (4ms < 5ms) -1622 let mut paths = FxHashMap::default(); -1623 paths.insert(&v4_1, psd(TransportType::Primary, 20)); -1624 paths.insert(&v4_2, psd(TransportType::Primary, 16)); -1625 -1626 let result = select_best_path(paths, Some(&current)); -1627 assert!(result.is_none()); // Should keep current +1621 let result = select_best_path(paths, Some(&current)); +1622 assert!(result.is_none()); // Should keep current +1623 +1624 // Should NOT switch: new path is just under threshold (4ms < 5ms) +1625 let mut paths = FxHashMap::default(); +1626 paths.insert(&v4_1, psd(TransportType::Primary, 20)); +1627 paths.insert(&v4_2, psd(TransportType::Primary, 16)); 1628 -1629 // SHOULD switch: new path is exactly at threshold (5ms, condition is <=) -1630 let mut paths = FxHashMap::default(); -1631 paths.insert(&v4_1, psd(TransportType::Primary, 20)); -1632 paths.insert(&v4_2, psd(TransportType::Primary, 15)); -1633 -1634 let result = select_best_path(paths, Some(&current)); -1635 assert!(result.is_some()); -1636 let (addr, _) = result.unwrap(); -1637 assert_eq!(addr, v4(2)); -1638 -1639 // SHOULD switch: new path is significantly better (6ms > 5ms threshold) -1640 let mut paths = FxHashMap::default(); -1641 paths.insert(&v4_1, psd(TransportType::Primary, 20)); -1642 paths.insert(&v4_2, psd(TransportType::Primary, 14)); -1643 -1644 let result = select_best_path(paths, Some(&current)); -1645 assert!(result.is_some()); -1646 let (addr, _) = result.unwrap(); -1647 assert_eq!(addr, v4(2)); -1648 } -1649 -1650 #[test] -1651 fn test_no_current_path_selects_best() { -1652 let v4_1 = v4(1); -1653 let v4_2 = v4(2); -1654 let mut paths = FxHashMap::default(); -1655 paths.insert(&v4_1, psd(TransportType::Primary, 20)); -1656 paths.insert(&v4_2, psd(TransportType::Primary, 10)); -1657 -1658 let result = select_best_path(paths, None); -1659 assert!(result.is_some()); -1660 let (addr, _) = result.unwrap(); -1661 assert_eq!(addr, v4(2)); // Lower RTT wins -1662 } -1663 -1664 #[test] -1665 fn test_empty_paths_returns_none() { -1666 let paths: FxHashMap<&TransportFourTuple, PathSelectionData> = FxHashMap::default(); -1667 let result = select_best_path(paths, None); -1668 assert!(result.is_none()); -1669 -1670 let paths: FxHashMap<&TransportFourTuple, PathSelectionData> = FxHashMap::default(); -1671 let result = select_best_path(paths, Some(&v4(1))); -1672 assert!(result.is_none()); -1673 } -1674} \ No newline at end of file +1629 let result = select_best_path(paths, Some(&current)); +1630 assert!(result.is_none()); // Should keep current +1631 +1632 // SHOULD switch: new path is exactly at threshold (5ms, condition is <=) +1633 let mut paths = FxHashMap::default(); +1634 paths.insert(&v4_1, psd(TransportType::Primary, 20)); +1635 paths.insert(&v4_2, psd(TransportType::Primary, 15)); +1636 +1637 let result = select_best_path(paths, Some(&current)); +1638 assert!(result.is_some()); +1639 let (addr, _) = result.unwrap(); +1640 assert_eq!(addr, v4(2)); +1641 +1642 // SHOULD switch: new path is significantly better (6ms > 5ms threshold) +1643 let mut paths = FxHashMap::default(); +1644 paths.insert(&v4_1, psd(TransportType::Primary, 20)); +1645 paths.insert(&v4_2, psd(TransportType::Primary, 14)); +1646 +1647 let result = select_best_path(paths, Some(&current)); +1648 assert!(result.is_some()); +1649 let (addr, _) = result.unwrap(); +1650 assert_eq!(addr, v4(2)); +1651 } +1652 +1653 #[test] +1654 fn test_no_current_path_selects_best() { +1655 let v4_1 = v4(1); +1656 let v4_2 = v4(2); +1657 let mut paths = FxHashMap::default(); +1658 paths.insert(&v4_1, psd(TransportType::Primary, 20)); +1659 paths.insert(&v4_2, psd(TransportType::Primary, 10)); +1660 +1661 let result = select_best_path(paths, None); +1662 assert!(result.is_some()); +1663 let (addr, _) = result.unwrap(); +1664 assert_eq!(addr, v4(2)); // Lower RTT wins +1665 } +1666 +1667 #[test] +1668 fn test_empty_paths_returns_none() { +1669 let paths: FxHashMap<&TransportFourTuple, PathSelectionData> = FxHashMap::default(); +1670 let result = select_best_path(paths, None); +1671 assert!(result.is_none()); +1672 +1673 let paths: FxHashMap<&TransportFourTuple, PathSelectionData> = FxHashMap::default(); +1674 let result = select_best_path(paths, Some(&v4(1))); +1675 assert!(result.is_none()); +1676 } +1677} \ No newline at end of file