diff --git a/pr/4271/docs/src/iroh/socket/remote_map/remote_state.rs.html b/pr/4271/docs/src/iroh/socket/remote_map/remote_state.rs.html index 004615e12a..e1bb4ccf15 100644 --- a/pr/4271/docs/src/iroh/socket/remote_map/remote_state.rs.html +++ b/pr/4271/docs/src/iroh/socket/remote_map/remote_state.rs.html @@ -267,7 +267,7 @@ 267 None => MaybeFuture::None, 268 }; 269 n0_future::pin!(scheduled_hp); -270 if !inbox.is_empty() || !self.connections.is_empty() { +270 if !self.is_idle(&inbox) { 271 idle_timeout 272 .as_mut() 273 .reset(Instant::now() + ACTOR_MAX_IDLE_TIMEOUT); @@ -325,7 +325,7 @@ 325 self.check_connections(); 326 } 327 _ = &mut idle_timeout => { -328 if self.connections.is_empty() && inbox.is_empty() && !self.state.paths.has_pending_resolve_requests() { +328 if self.is_idle(&inbox) { 329 trace!("idle timeout expired and still idle: terminate actor"); 330 break; 331 } else { @@ -346,1219 +346,1226 @@ 346 (self.state.endpoint_id, leftover_msgs) 347 } 348 -349 /// Handles an actor message. -350 /// -351 /// Error returns are fatal and kill the actor. -352 #[instrument(skip(self))] -353 async fn handle_message(&mut self, msg: RemoteStateMessage) { -354 // trace!("handling message"); -355 match msg { -356 RemoteStateMessage::SendDatagram(sender, transmit) => { -357 self.state.handle_msg_send_datagram(sender, transmit).await; -358 } -359 RemoteStateMessage::AddConnection(handle, tx) => { -360 self.handle_msg_add_connection(handle, tx); -361 } -362 RemoteStateMessage::ResolveRemote(addrs, tx) => { -363 self.state.handle_msg_resolve_remote(addrs, tx); -364 } -365 RemoteStateMessage::RemoteInfo(tx) => { -366 let addrs = self.state.paths.to_remote_addrs(); -367 let info = RemoteInfo { -368 endpoint_id: self.state.endpoint_id, -369 addrs, -370 }; -371 tx.send(info).ok(); -372 } -373 RemoteStateMessage::NetworkChange { is_major } => { -374 self.handle_msg_network_change(is_major); -375 } -376 } -377 } -378 -379 /// Handles [`RemoteStateMessage::AddConnection`]. -380 /// -381 /// Error returns are fatal and kill the actor. -382 fn handle_msg_add_connection( -383 &mut self, -384 conn: noq::Connection, -385 tx: oneshot::Sender<PathStateReceiver>, -386 ) { -387 let (path_state_sender, path_state_receiver) = PathStateSender::new(); -388 self.state.metrics.num_conns_opened.inc(); -389 // Remove any conflicting stable_ids from the local state. -390 let conn_id = ConnId(conn.stable_id()); -391 self.connections.remove(&conn_id); -392 -393 // Hook up paths, NAT addresses and connection closed event streams. -394 self.state -395 .path_events -396 .push(Box::pin(conn.path_events().map(move |evt| (conn_id, evt)))); -397 self.state.addr_events.push(Box::pin( -398 conn.nat_traversal_updates().map(move |evt| (conn_id, evt)), -399 )); -400 self.state.connections_close.push(OnClosed::new(&conn)); -401 -402 // Add local addrs to the connection -403 let local_addrs = self.state.local_candidates(); -404 update_qnt_candidates(&conn, &local_addrs); -405 -406 // Store the connection -407 let conn_state = self -408 .connections -409 .entry(conn_id) -410 .insert_entry(ConnectionState { -411 handle: conn.weak_handle(), -412 path_state: path_state_sender, -413 paths: Default::default(), -414 has_been_direct: false, -415 }) -416 .into_mut(); -417 -418 // Store PathId(0), set path_status and select best path, check if holepunching -419 // is needed. -420 if let Some(path) = conn.path(PathId::ZERO) { -421 let path_remote = self -422 .state -423 .register_and_configure_path(conn_id, conn_state, &path); +349 /// Returns `true` if the actor is fully idle. +350 fn is_idle(&self, inbox: &mpsc::Receiver<RemoteStateMessage>) -> bool { +351 self.connections.is_empty() +352 && inbox.is_empty() +353 && self.state.paths.resolve_requests_is_empty() +354 } +355 +356 /// Handles an actor message. +357 /// +358 /// Error returns are fatal and kill the actor. +359 #[instrument(skip(self))] +360 async fn handle_message(&mut self, msg: RemoteStateMessage) { +361 // trace!("handling message"); +362 match msg { +363 RemoteStateMessage::SendDatagram(sender, transmit) => { +364 self.state.handle_msg_send_datagram(sender, transmit).await; +365 } +366 RemoteStateMessage::AddConnection(handle, tx) => { +367 self.handle_msg_add_connection(handle, tx); +368 } +369 RemoteStateMessage::ResolveRemote(addrs, tx) => { +370 self.state.handle_msg_resolve_remote(addrs, tx); +371 } +372 RemoteStateMessage::RemoteInfo(tx) => { +373 let addrs = self.state.paths.to_remote_addrs(); +374 let info = RemoteInfo { +375 endpoint_id: self.state.endpoint_id, +376 addrs, +377 }; +378 tx.send(info).ok(); +379 } +380 RemoteStateMessage::NetworkChange { is_major } => { +381 self.handle_msg_network_change(is_major); +382 } +383 } +384 } +385 +386 /// Handles [`RemoteStateMessage::AddConnection`]. +387 /// +388 /// Error returns are fatal and kill the actor. +389 fn handle_msg_add_connection( +390 &mut self, +391 conn: noq::Connection, +392 tx: oneshot::Sender<PathStateReceiver>, +393 ) { +394 let (path_state_sender, path_state_receiver) = PathStateSender::new(); +395 self.state.metrics.num_conns_opened.inc(); +396 // Remove any conflicting stable_ids from the local state. +397 let conn_id = ConnId(conn.stable_id()); +398 self.connections.remove(&conn_id); +399 +400 // Hook up paths, NAT addresses and connection closed event streams. +401 self.state +402 .path_events +403 .push(Box::pin(conn.path_events().map(move |evt| (conn_id, evt)))); +404 self.state.addr_events.push(Box::pin( +405 conn.nat_traversal_updates().map(move |evt| (conn_id, evt)), +406 )); +407 self.state.connections_close.push(OnClosed::new(&conn)); +408 +409 // Add local addrs to the connection +410 let local_addrs = self.state.local_candidates(); +411 update_qnt_candidates(&conn, &local_addrs); +412 +413 // Store the connection +414 let conn_state = self +415 .connections +416 .entry(conn_id) +417 .insert_entry(ConnectionState { +418 handle: conn.weak_handle(), +419 path_state: path_state_sender, +420 paths: Default::default(), +421 has_been_direct: false, +422 }) +423 .into_mut(); 424 -425 if let Some(path_remote) = path_remote -426 && !path_remote.is_relay() -427 && conn.side().is_client() -428 { -429 // We may have raced this with a relay address. Try and add any -430 // relay addresses we have back. -431 let relays = self -432 .state -433 .paths -434 .addrs() -435 .filter(|a| a.is_relay()) -436 .cloned() -437 .collect::<Vec<_>>(); -438 for open_addr in relays { -439 self.state -440 .open_path_on_conn(conn_id, conn_state, &conn, &open_addr); -441 } -442 } -443 } -444 self.trigger_holepunching(); -445 self.select_path(); -446 tx.send(path_state_receiver).ok(); -447 } -448 -449 /// Handles [`RemoteStateMessage::NetworkChange`]. -450 fn handle_msg_network_change(&mut self, is_major: bool) { -451 // Ping all the paths so loss-detection starts ASAP. -452 for conn in self.connections.values() { -453 if let Some(noq_conn) = conn.handle.upgrade() { -454 for (path_id, addr) in &conn.paths { -455 if let Some(path) = noq_conn.path(*path_id) { -456 // Ping the current path -457 if let Err(err) = path.ping() { -458 warn!(%err, %path_id, ?addr, "failed to ping path"); -459 } -460 } -461 } -462 } -463 } -464 -465 if is_major { -466 self.trigger_holepunching(); -467 } -468 } -469 -470 fn handle_connection_close(&mut self, conn_id: ConnId, closed: Closed) { -471 event!( -472 target: "iroh::_events::conn::closed", -473 Level::DEBUG, -474 %conn_id, -475 remote_id = %self.state.endpoint_id.fmt_short(), -476 reason=?closed.reason, -477 ); -478 -479 if let Some(conn_state) = self.connections.remove(&conn_id) { -480 self.state.metrics.num_conns_closed.inc(); -481 conn_state.path_state.close(closed); -482 } -483 if self.connections.is_empty() { -484 trace!("last connection closed - clearing selected_path"); -485 self.state.selected_path = None; -486 } -487 } -488 -489 /// Updates the local [`DirectAddr`]s to all connections. -490 /// -491 /// Each connection needs to have the local direct addresses to use as QNT address -492 /// candidates. -493 fn update_local_direct_address(&mut self) { -494 let local_addrs = self.state.local_candidates(); -495 for conn in self.connections.values().filter_map(|s| s.handle.upgrade()) { -496 update_qnt_candidates(&conn, &local_addrs); -497 } -498 // todo: trace -499 } -500 -501 /// Triggers holepunching to the remote endpoint. -502 /// -503 /// This will manage the entire process of holepunching with the remote endpoint. -504 /// -505 /// - Holepunching happens on the Connection with the lowest [`ConnId`] which is a -506 /// client. -507 /// - Both endpoints may initiate holepunching if both have a client connection. -508 /// - Any opened paths are opened on all other connections without holepunching. -509 /// - If there are no changes in local or remote candidate addresses since the -510 /// last attempt **and** there was a recent attempt, a trigger_holepunching call -511 /// will be scheduled instead. -512 fn trigger_holepunching(&mut self) { -513 if self.connections.is_empty() { -514 trace!("not holepunching: no connections"); -515 return; -516 } -517 -518 let Some(conn) = self -519 .connections -520 .iter() -521 .filter_map(|(id, state)| state.handle.upgrade().map(|conn| (*id, conn))) -522 .filter(|(_, conn)| conn.side().is_client()) -523 .min_by_key(|(id, _)| *id) -524 .map(|(_, conn)| conn) -525 else { -526 trace!("not holepunching: no client connection"); -527 return; -528 }; -529 let remote_candidates = match conn.get_remote_nat_traversal_addresses() { -530 Ok(addrs) => BTreeSet::from_iter(addrs), -531 Err(err) => { -532 warn!("failed to get nat candidate addresses: {err:#}"); -533 return; -534 } +425 // Store PathId(0), set path_status and select best path, check if holepunching +426 // is needed. +427 if let Some(path) = conn.path(PathId::ZERO) { +428 let path_remote = self +429 .state +430 .register_and_configure_path(conn_id, conn_state, &path); +431 +432 if let Some(path_remote) = path_remote +433 && !path_remote.is_relay() +434 && conn.side().is_client() +435 { +436 // We may have raced this with a relay address. Try and add any +437 // relay addresses we have back. +438 let relays = self +439 .state +440 .paths +441 .addrs() +442 .filter(|a| a.is_relay()) +443 .cloned() +444 .collect::<Vec<_>>(); +445 for open_addr in relays { +446 self.state +447 .open_path_on_conn(conn_id, conn_state, &conn, &open_addr); +448 } +449 } +450 } +451 self.trigger_holepunching(); +452 self.select_path(); +453 tx.send(path_state_receiver).ok(); +454 } +455 +456 /// Handles [`RemoteStateMessage::NetworkChange`]. +457 fn handle_msg_network_change(&mut self, is_major: bool) { +458 // Ping all the paths so loss-detection starts ASAP. +459 for conn in self.connections.values() { +460 if let Some(noq_conn) = conn.handle.upgrade() { +461 for (path_id, addr) in &conn.paths { +462 if let Some(path) = noq_conn.path(*path_id) { +463 // Ping the current path +464 if let Err(err) = path.ping() { +465 warn!(%err, %path_id, ?addr, "failed to ping path"); +466 } +467 } +468 } +469 } +470 } +471 +472 if is_major { +473 self.trigger_holepunching(); +474 } +475 } +476 +477 fn handle_connection_close(&mut self, conn_id: ConnId, closed: Closed) { +478 event!( +479 target: "iroh::_events::conn::closed", +480 Level::DEBUG, +481 %conn_id, +482 remote_id = %self.state.endpoint_id.fmt_short(), +483 reason=?closed.reason, +484 ); +485 +486 if let Some(conn_state) = self.connections.remove(&conn_id) { +487 self.state.metrics.num_conns_closed.inc(); +488 conn_state.path_state.close(closed); +489 } +490 if self.connections.is_empty() { +491 trace!("last connection closed - clearing selected_path"); +492 self.state.selected_path = None; +493 } +494 } +495 +496 /// Updates the local [`DirectAddr`]s to all connections. +497 /// +498 /// Each connection needs to have the local direct addresses to use as QNT address +499 /// candidates. +500 fn update_local_direct_address(&mut self) { +501 let local_addrs = self.state.local_candidates(); +502 for conn in self.connections.values().filter_map(|s| s.handle.upgrade()) { +503 update_qnt_candidates(&conn, &local_addrs); +504 } +505 // todo: trace +506 } +507 +508 /// Triggers holepunching to the remote endpoint. +509 /// +510 /// This will manage the entire process of holepunching with the remote endpoint. +511 /// +512 /// - Holepunching happens on the Connection with the lowest [`ConnId`] which is a +513 /// client. +514 /// - Both endpoints may initiate holepunching if both have a client connection. +515 /// - Any opened paths are opened on all other connections without holepunching. +516 /// - If there are no changes in local or remote candidate addresses since the +517 /// last attempt **and** there was a recent attempt, a trigger_holepunching call +518 /// will be scheduled instead. +519 fn trigger_holepunching(&mut self) { +520 if self.connections.is_empty() { +521 trace!("not holepunching: no connections"); +522 return; +523 } +524 +525 let Some(conn) = self +526 .connections +527 .iter() +528 .filter_map(|(id, state)| state.handle.upgrade().map(|conn| (*id, conn))) +529 .filter(|(_, conn)| conn.side().is_client()) +530 .min_by_key(|(id, _)| *id) +531 .map(|(_, conn)| conn) +532 else { +533 trace!("not holepunching: no client connection"); +534 return; 535 }; -536 let local_candidates = self.state.local_candidates(); -537 let new_candidates = self -538 .state -539 .last_holepunch -540 .as_ref() -541 .map(|last_hp| { -542 // Addrs are allowed to disappear, but if there are new ones we need to -543 // holepunch again. -544 trace!( -545 ?last_hp, -546 ?local_candidates, -547 ?remote_candidates, -548 "candidates to holepunch?" -549 ); -550 !remote_candidates.is_subset(&last_hp.remote_candidates) -551 || !local_candidates.is_subset(&last_hp.local_candidates) -552 }) -553 .unwrap_or(true); -554 if !new_candidates && let Some(ref last_hp) = self.state.last_holepunch { -555 let next_hp = last_hp.when + HOLEPUNCH_ATTEMPTS_INTERVAL; -556 let now = Instant::now(); -557 if next_hp > now { -558 trace!(scheduled_in = ?(next_hp - now), "not holepunching: no new addresses"); -559 self.state.scheduled_holepunch = Some(next_hp); -560 return; -561 } -562 } -563 -564 self.state.do_holepunching(conn); -565 } -566 -567 #[instrument(skip(self))] -568 fn handle_path_event(&mut self, conn_id: ConnId, event: Result<NoqPathEvent, noq::Lagged>) { -569 let Ok(event) = event else { -570 warn!("missed a PathEvent, RemoteStateActor lagging"); -571 // TODO: Is it possible to recover using the sync APIs to figure out what the -572 // state of the connection and it's paths are? -573 return; -574 }; -575 let Some(conn_state) = self.connections.get_mut(&conn_id) else { -576 trace!("event for removed connection"); -577 return; -578 }; -579 let Some(conn) = conn_state.handle.upgrade() else { -580 trace!("event for closed connection"); -581 return; -582 }; -583 trace!("path event"); -584 match event { -585 NoqPathEvent::Established { id: path_id } => { -586 let Some(path) = conn.path(path_id) else { -587 trace!("path open event for unknown path"); -588 return; -589 }; -590 -591 self.state -592 .register_and_configure_path(conn_id, conn_state, &path); -593 self.select_path(); -594 } -595 NoqPathEvent::Abandoned { id, reason } => { -596 // Remove abandoned path from the conn state. -597 let Some(path_remote) = conn_state.remove_path(&id, &conn) else { -598 debug!(%id, "path not in path_id_map"); -599 return; -600 }; -601 // Also remove the path from the remote-global path tracking. -602 self.state.paths.abandoned_path(&path_remote); -603 -604 event!( -605 target: "iroh::_events::path::abandoned", -606 Level::DEBUG, -607 remote = %self.state.endpoint_id.fmt_short(), -608 ?path_remote, -609 %conn_id, -610 path_id = ?id, -611 ?reason -612 ); -613 -614 // If one connection abandons a path, close it on all connections. -615 for (conn_id, conn_state) in self.connections.iter() { -616 let Some(conn) = conn_state.handle.upgrade() else { -617 continue; -618 }; -619 // Close all paths with the remote address that was abandoned. -620 for path in conn_state -621 .paths -622 .iter() -623 .filter(|(_id, addr)| **addr == path_remote) -624 .filter_map(|(id, _addr)| conn.path(*id)) -625 { -626 trace!(?path_remote, %conn_id, path_id=%path.id(), "closing path"); -627 if let Err(err) = path.close() { -628 trace!( -629 ?path_remote, -630 %conn_id, -631 path_id=%path.id(), -632 "path close failed: {err:#}" -633 ); -634 } -635 } -636 } -637 -638 // If the remote closed our selected path, select a new one. -639 self.select_path(); -640 } -641 NoqPathEvent::Discarded { id, path_stats } => { -642 trace!(%id, ?path_stats, "path discarded"); -643 } -644 NoqPathEvent::RemoteStatus { .. } | NoqPathEvent::ObservedAddr { .. } => { -645 // Nothing to do for these events. -646 } -647 } -648 } -649 -650 /// Selects the path with the lowest RTT, prefers direct paths. -651 /// -652 /// If there are direct paths, this selects the direct path with the lowest RTT. If -653 /// there are only relay paths, the relay path with the lowest RTT is chosen. -654 /// -655 /// The selected path is added to any connections which do not yet have it. Any unused -656 /// direct paths are closed for all connections. -657 #[instrument(skip_all)] -658 fn select_path(&mut self) { -659 // Find the lowest RTT across all connections for each open path. The long way, so -660 // we get to log *all* RTTs. -661 let mut all_path_rtts: FxHashMap<&transports::Addr, Vec<Duration>> = FxHashMap::default(); -662 for conn_state in self.connections.values() { -663 let Some(conn) = conn_state.handle.upgrade() else { -664 continue; -665 }; -666 for (path_id, addr) in conn_state.paths.iter() { -667 if let Some(stats) = conn.path_stats(*path_id) { -668 all_path_rtts.entry(addr).or_default().push(stats.rtt); -669 } -670 } -671 } -672 trace!(?all_path_rtts, "dumping all path RTTs"); -673 let path_rtts: FxHashMap<&transports::Addr, PathSelectionData> = all_path_rtts -674 .into_iter() -675 .filter_map(|(addr, rtts)| rtts.into_iter().min().map(|rtt| (addr, rtt))) -676 .map(|(addr, rtt)| { -677 ( -678 addr, -679 self.state.transport_bias.path_selection_data(addr, rtt), -680 ) -681 }) -682 .collect(); -683 -684 let current_path = self.state.selected_path.as_ref(); -685 let selected_path = select_best_path(path_rtts, current_path); -686 -687 // Apply our new path -688 if let Some((addr, rtt)) = selected_path -689 && self.state.selected_path.as_ref() != Some(&addr) -690 { -691 let prev_remote = self.state.selected_path.replace(addr.clone()); -692 event!( -693 target: "iroh::_events::path::selected", -694 Level::DEBUG, -695 remote = %self.state.endpoint_id.fmt_short(), -696 path_remote = ?addr, -697 ?rtt, -698 ?prev_remote, -699 ); -700 self.apply_selected_change(&addr); -701 } else { -702 trace!(?current_path, "keeping current path"); -703 } -704 } -705 -706 /// Propagates a change of [`State::selected_path`] to noq. -707 /// -708 /// Iterates over all connections and applies the selected path as follows: -709 /// - Closes non-selected IP paths (but keeps one IP path open still) -710 /// - Sets all non-selected paths to [`PathStatus::Backup`] -711 /// - Opens the selected path if it does not exist on the connection -712 /// - Sets the selected path to [`PathStatus::Available`] -713 fn apply_selected_change(&mut self, selected: &transports::Addr) { -714 for (conn_id, conn_state) in self.connections.iter() { -715 let Some(conn) = conn_state.handle.upgrade() else { -716 continue; -717 }; -718 -719 // Open path if it doesn't exist yet. -720 self.state -721 .open_path_on_conn(*conn_id, conn_state, &conn, selected); -722 -723 for (path_id, path_remote) in conn_state.paths.iter() { -724 let Some(path) = conn.path(*path_id) else { -725 continue; -726 }; -727 -728 // Closes redundant IP paths so that at most one remains per connection. -729 // -730 // Relay and custom paths are kept open. Only the client closes paths, -731 // to avoid the client and server independently closing different paths -732 // and racing to abandon the last one. -733 if conn.side().is_client() -734 && path_remote.is_ip() -735 && path_remote != selected -736 && conn_state.paths.values().filter(|a| a.is_ip()).count() > 1 -737 { -738 trace!(?path_remote, %conn_id, %path_id, "closing direct path"); -739 match path.close() { -740 Err(noq_proto::ClosePathError::MultipathNotNegotiated) => { -741 error!("multipath not negotiated"); -742 } -743 Err(noq_proto::ClosePathError::LastOpenPath) => { -744 error!("could not close last open path"); -745 } -746 Err(noq_proto::ClosePathError::ClosedPath) => { -747 // We already closed this. -748 } -749 Ok(()) => {} -750 } -751 continue; -752 } -753 -754 // Set path status: The selected path becomes Available, all other paths become Backup. -755 self.state.set_path_status(*conn_id, &path, path_remote); -756 } -757 -758 // Record the new selected path in the path watcher. -759 conn_state -760 .path_state -761 .record_selected(selected.clone().into()); -762 } -763 } +536 let remote_candidates = match conn.get_remote_nat_traversal_addresses() { +537 Ok(addrs) => BTreeSet::from_iter(addrs), +538 Err(err) => { +539 warn!("failed to get nat candidate addresses: {err:#}"); +540 return; +541 } +542 }; +543 let local_candidates = self.state.local_candidates(); +544 let new_candidates = self +545 .state +546 .last_holepunch +547 .as_ref() +548 .map(|last_hp| { +549 // Addrs are allowed to disappear, but if there are new ones we need to +550 // holepunch again. +551 trace!( +552 ?last_hp, +553 ?local_candidates, +554 ?remote_candidates, +555 "candidates to holepunch?" +556 ); +557 !remote_candidates.is_subset(&last_hp.remote_candidates) +558 || !local_candidates.is_subset(&last_hp.local_candidates) +559 }) +560 .unwrap_or(true); +561 if !new_candidates && let Some(ref last_hp) = self.state.last_holepunch { +562 let next_hp = last_hp.when + HOLEPUNCH_ATTEMPTS_INTERVAL; +563 let now = Instant::now(); +564 if next_hp > now { +565 trace!(scheduled_in = ?(next_hp - now), "not holepunching: no new addresses"); +566 self.state.scheduled_holepunch = Some(next_hp); +567 return; +568 } +569 } +570 +571 self.state.do_holepunching(conn); +572 } +573 +574 #[instrument(skip(self))] +575 fn handle_path_event(&mut self, conn_id: ConnId, event: Result<NoqPathEvent, noq::Lagged>) { +576 let Ok(event) = event else { +577 warn!("missed a PathEvent, RemoteStateActor lagging"); +578 // TODO: Is it possible to recover using the sync APIs to figure out what the +579 // state of the connection and it's paths are? +580 return; +581 }; +582 let Some(conn_state) = self.connections.get_mut(&conn_id) else { +583 trace!("event for removed connection"); +584 return; +585 }; +586 let Some(conn) = conn_state.handle.upgrade() else { +587 trace!("event for closed connection"); +588 return; +589 }; +590 trace!("path event"); +591 match event { +592 NoqPathEvent::Established { id: path_id } => { +593 let Some(path) = conn.path(path_id) else { +594 trace!("path open event for unknown path"); +595 return; +596 }; +597 +598 self.state +599 .register_and_configure_path(conn_id, conn_state, &path); +600 self.select_path(); +601 } +602 NoqPathEvent::Abandoned { id, reason } => { +603 // Remove abandoned path from the conn state. +604 let Some(path_remote) = conn_state.remove_path(&id, &conn) else { +605 debug!(%id, "path not in path_id_map"); +606 return; +607 }; +608 // Also remove the path from the remote-global path tracking. +609 self.state.paths.abandoned_path(&path_remote); +610 +611 event!( +612 target: "iroh::_events::path::abandoned", +613 Level::DEBUG, +614 remote = %self.state.endpoint_id.fmt_short(), +615 ?path_remote, +616 %conn_id, +617 path_id = ?id, +618 ?reason +619 ); +620 +621 // If one connection abandons a path, close it on all connections. +622 for (conn_id, conn_state) in self.connections.iter() { +623 let Some(conn) = conn_state.handle.upgrade() else { +624 continue; +625 }; +626 // Close all paths with the remote address that was abandoned. +627 for path in conn_state +628 .paths +629 .iter() +630 .filter(|(_id, addr)| **addr == path_remote) +631 .filter_map(|(id, _addr)| conn.path(*id)) +632 { +633 trace!(?path_remote, %conn_id, path_id=%path.id(), "closing path"); +634 if let Err(err) = path.close() { +635 trace!( +636 ?path_remote, +637 %conn_id, +638 path_id=%path.id(), +639 "path close failed: {err:#}" +640 ); +641 } +642 } +643 } +644 +645 // If the remote closed our selected path, select a new one. +646 self.select_path(); +647 } +648 NoqPathEvent::Discarded { id, path_stats } => { +649 trace!(%id, ?path_stats, "path discarded"); +650 } +651 NoqPathEvent::RemoteStatus { .. } | NoqPathEvent::ObservedAddr { .. } => { +652 // Nothing to do for these events. +653 } +654 } +655 } +656 +657 /// Selects the path with the lowest RTT, prefers direct paths. +658 /// +659 /// If there are direct paths, this selects the direct path with the lowest RTT. If +660 /// there are only relay paths, the relay path with the lowest RTT is chosen. +661 /// +662 /// The selected path is added to any connections which do not yet have it. Any unused +663 /// direct paths are closed for all connections. +664 #[instrument(skip_all)] +665 fn select_path(&mut self) { +666 // Find the lowest RTT across all connections for each open path. The long way, so +667 // we get to log *all* RTTs. +668 let mut all_path_rtts: FxHashMap<&transports::Addr, Vec<Duration>> = FxHashMap::default(); +669 for conn_state in self.connections.values() { +670 let Some(conn) = conn_state.handle.upgrade() else { +671 continue; +672 }; +673 for (path_id, addr) in conn_state.paths.iter() { +674 if let Some(stats) = conn.path_stats(*path_id) { +675 all_path_rtts.entry(addr).or_default().push(stats.rtt); +676 } +677 } +678 } +679 trace!(?all_path_rtts, "dumping all path RTTs"); +680 let path_rtts: FxHashMap<&transports::Addr, PathSelectionData> = all_path_rtts +681 .into_iter() +682 .filter_map(|(addr, rtts)| rtts.into_iter().min().map(|rtt| (addr, rtt))) +683 .map(|(addr, rtt)| { +684 ( +685 addr, +686 self.state.transport_bias.path_selection_data(addr, rtt), +687 ) +688 }) +689 .collect(); +690 +691 let current_path = self.state.selected_path.as_ref(); +692 let selected_path = select_best_path(path_rtts, current_path); +693 +694 // Apply our new path +695 if let Some((addr, rtt)) = selected_path +696 && self.state.selected_path.as_ref() != Some(&addr) +697 { +698 let prev_remote = self.state.selected_path.replace(addr.clone()); +699 event!( +700 target: "iroh::_events::path::selected", +701 Level::DEBUG, +702 remote = %self.state.endpoint_id.fmt_short(), +703 path_remote = ?addr, +704 ?rtt, +705 ?prev_remote, +706 ); +707 self.apply_selected_change(&addr); +708 } else { +709 trace!(?current_path, "keeping current path"); +710 } +711 } +712 +713 /// Propagates a change of [`State::selected_path`] to noq. +714 /// +715 /// Iterates over all connections and applies the selected path as follows: +716 /// - Closes non-selected IP paths (but keeps one IP path open still) +717 /// - Sets all non-selected paths to [`PathStatus::Backup`] +718 /// - Opens the selected path if it does not exist on the connection +719 /// - Sets the selected path to [`PathStatus::Available`] +720 fn apply_selected_change(&mut self, selected: &transports::Addr) { +721 for (conn_id, conn_state) in self.connections.iter() { +722 let Some(conn) = conn_state.handle.upgrade() else { +723 continue; +724 }; +725 +726 // Open path if it doesn't exist yet. +727 self.state +728 .open_path_on_conn(*conn_id, conn_state, &conn, selected); +729 +730 for (path_id, path_remote) in conn_state.paths.iter() { +731 let Some(path) = conn.path(*path_id) else { +732 continue; +733 }; +734 +735 // Closes redundant IP paths so that at most one remains per connection. +736 // +737 // Relay and custom paths are kept open. Only the client closes paths, +738 // to avoid the client and server independently closing different paths +739 // and racing to abandon the last one. +740 if conn.side().is_client() +741 && path_remote.is_ip() +742 && path_remote != selected +743 && conn_state.paths.values().filter(|a| a.is_ip()).count() > 1 +744 { +745 trace!(?path_remote, %conn_id, %path_id, "closing direct path"); +746 match path.close() { +747 Err(noq_proto::ClosePathError::MultipathNotNegotiated) => { +748 error!("multipath not negotiated"); +749 } +750 Err(noq_proto::ClosePathError::LastOpenPath) => { +751 error!("could not close last open path"); +752 } +753 Err(noq_proto::ClosePathError::ClosedPath) => { +754 // We already closed this. +755 } +756 Ok(()) => {} +757 } +758 continue; +759 } +760 +761 // Set path status: The selected path becomes Available, all other paths become Backup. +762 self.state.set_path_status(*conn_id, &path, path_remote); +763 } 764 -765 fn open_path_on_all_conns(&mut self, open_addr: &transports::Addr) { -766 for (conn_id, conn_state) in self.connections.iter() { -767 let Some(conn) = conn_state.handle.upgrade() else { -768 continue; -769 }; -770 self.state -771 .open_path_on_conn(*conn_id, conn_state, &conn, open_addr); -772 } -773 } -774 -775 /// Handles regularly checking if any paths need hole punching currently -776 /// -777 /// Currently we need to have 1 IP path, with a good enough latency. -778 fn check_connections(&mut self) { -779 let mut is_goodenough = true; -780 for conn_state in self.connections.values() { -781 let mut is_conn_goodenough = false; -782 if let Some(conn) = conn_state.handle.upgrade() { -783 let min_ip_rtt = conn_state -784 .paths -785 .iter() -786 .filter_map(|(path_id, addr)| { -787 if addr.is_ip() { -788 conn.path_stats(*path_id).map(|stats| stats.rtt) -789 } else { -790 None -791 } -792 }) -793 .min(); -794 -795 if let Some(min_ip_rtt) = min_ip_rtt { -796 let is_latency_goodenough = min_ip_rtt <= GOOD_ENOUGH_LATENCY; -797 is_conn_goodenough = is_latency_goodenough; -798 } else { -799 // No IP transport found -800 is_conn_goodenough = false; -801 } -802 } -803 is_goodenough &= is_conn_goodenough; -804 } -805 -806 if !is_goodenough { -807 debug!("connections are not good enough, triggering holepunching"); -808 self.trigger_holepunching(); -809 } -810 } -811} +765 // Record the new selected path in the path watcher. +766 conn_state +767 .path_state +768 .record_selected(selected.clone().into()); +769 } +770 } +771 +772 fn open_path_on_all_conns(&mut self, open_addr: &transports::Addr) { +773 for (conn_id, conn_state) in self.connections.iter() { +774 let Some(conn) = conn_state.handle.upgrade() else { +775 continue; +776 }; +777 self.state +778 .open_path_on_conn(*conn_id, conn_state, &conn, open_addr); +779 } +780 } +781 +782 /// Handles regularly checking if any paths need hole punching currently +783 /// +784 /// Currently we need to have 1 IP path, with a good enough latency. +785 fn check_connections(&mut self) { +786 let mut is_goodenough = true; +787 for conn_state in self.connections.values() { +788 let mut is_conn_goodenough = false; +789 if let Some(conn) = conn_state.handle.upgrade() { +790 let min_ip_rtt = conn_state +791 .paths +792 .iter() +793 .filter_map(|(path_id, addr)| { +794 if addr.is_ip() { +795 conn.path_stats(*path_id).map(|stats| stats.rtt) +796 } else { +797 None +798 } +799 }) +800 .min(); +801 +802 if let Some(min_ip_rtt) = min_ip_rtt { +803 let is_latency_goodenough = min_ip_rtt <= GOOD_ENOUGH_LATENCY; +804 is_conn_goodenough = is_latency_goodenough; +805 } else { +806 // No IP transport found +807 is_conn_goodenough = false; +808 } +809 } +810 is_goodenough &= is_conn_goodenough; +811 } 812 -813impl State { -814 /// Handles [`RemoteStateMessage::SendDatagram`]. -815 async fn handle_msg_send_datagram( -816 &mut self, -817 mut sender: Box<TransportsSender>, -818 transmit: OwnedTransmit, -819 ) { -820 // Sending datagrams might fail, e.g. because we don't have the right transports set -821 // up to handle sending this owned transmit to. -822 // After all, we try every single path that we know (relay URL, IP address), even -823 // though we might not have a relay transport or ip-capable transport set up. -824 // So these errors must not be fatal for this actor (or even this operation). -825 -826 if let Some(addr) = self.selected_path.as_ref() { -827 trace!(?addr, "sending datagram to selected path"); -828 -829 if let Err(err) = send_datagram(&mut sender, addr.clone(), transmit).await { -830 debug!(?addr, "failed to send datagram on selected_path: {err:#}"); -831 } -832 } else { -833 trace!( -834 paths = ?self.paths.addrs().collect::<Vec<_>>(), -835 "sending datagram to all known paths", -836 ); -837 if self.paths.is_empty() { -838 warn!("Cannot send datagrams: No paths to remote endpoint known"); -839 } -840 -841 for addr in self.paths.addrs() { -842 // We never want to send to our local addresses. -843 // The local address set is updated in the main loop so we can use `peek` here. -844 if let transports::Addr::Ip(sockaddr) = addr -845 && self -846 .local_direct_addrs -847 .peek() -848 .iter() -849 .any(|a| a.addr == *sockaddr) -850 { -851 trace!(%sockaddr, "not sending datagram to our own address"); -852 } else if let Err(err) = -853 send_datagram(&mut sender, addr.clone(), transmit.clone()).await -854 { -855 debug!(?addr, "failed to send datagram: {err:#}"); -856 } -857 } -858 // This message is received *before* a connection is added. So we do -859 // not yet have a connection to holepunch. Instead we trigger -860 // holepunching when AddConnection is received. -861 } -862 } -863 -864 /// Handles [`RemoteStateMessage::ResolveRemote`]. -865 fn handle_msg_resolve_remote( -866 &mut self, -867 addrs: BTreeSet<TransportAddr>, -868 tx: oneshot::Sender<Result<(), AddressLookupFailed>>, -869 ) { -870 let addrs = to_transports_addr(self.endpoint_id, addrs); -871 self.paths.insert_multiple(addrs, Source::App); -872 self.paths.resolve_remote(tx); -873 // Start Address Lookup if we have no selected path. -874 self.trigger_address_lookup(); -875 } -876 -877 /// Triggers Address Lookup for the remote endpoint, if needed. -878 /// -879 /// Does not start Address Lookup if we have a selected path or if Address Lookup is -880 /// currently running. -881 fn trigger_address_lookup(&mut self) { -882 if self.selected_path.is_some() || self.address_lookup_stream.is_some() { -883 return; -884 } -885 let stream = self.address_lookup.resolve(self.endpoint_id); -886 let stream = stream.filter_map(|item| match item { -887 // We don't care about errors from individual services, we just continue. -888 // Individual errors are buffered into the final error by `AddressLookupServices::resolve`, -889 // and if the lookup fails we return them upstream with the final `AddressLookupFailed` error. -890 Ok(Err(_err)) => None, -891 Ok(Ok(item)) => Some(Ok(item)), -892 Err(err) => Some(Err(err)), -893 }); -894 self.address_lookup_stream = Some(Box::pin(stream)); -895 } -896 -897 /// Handles an address lookup result. -898 /// -899 /// All address lookup results end up being sent here. It takes care of updating the -900 /// [`RemotePathState`] with the results. -901 fn handle_address_lookup_item( -902 &mut self, -903 item: Option<Result<AddressLookupItem, AddressLookupFailed>>, -904 ) { -905 match item { -906 None => { -907 self.paths.address_lookup_finished(Ok(())); -908 self.address_lookup_stream = None; -909 } -910 Some(Err(err)) => { -911 warn!("Address Lookup failed: {err:#}"); -912 self.paths.address_lookup_finished(Err(err)); -913 self.address_lookup_stream = None; -914 } -915 Some(Ok(item)) => { -916 if item.endpoint_id() != self.endpoint_id { -917 warn!( -918 ?item, -919 "Address Lookup emitted item for wrong remote endpoint" -920 ); -921 } else { -922 let source = Source::AddressLookup { -923 name: item.provenance().to_string(), -924 }; -925 let addrs = -926 to_transports_addr(self.endpoint_id, item.into_endpoint_addr().addrs); -927 self.paths.insert_multiple(addrs, source); -928 } -929 } -930 } -931 } -932 -933 /// Unconditionally perform holepunching. -934 #[instrument(skip_all)] -935 fn do_holepunching(&mut self, conn: noq::Connection) { -936 self.metrics.holepunch_attempts.inc(); -937 let local_candidates = self.local_candidates(); -938 match conn.initiate_nat_traversal_round() { -939 Ok(remote_candidates) => { -940 let remote_candidates = remote_candidates -941 .iter() -942 .map(|addr| SocketAddr::new(addr.ip().to_canonical(), addr.port())) -943 .collect(); -944 event!( -945 target: "iroh::_events::qnt::init", -946 Level::DEBUG, -947 remote = %self.endpoint_id.fmt_short(), -948 ?local_candidates, -949 ?remote_candidates, -950 ); -951 self.last_holepunch = Some(HolepunchAttempt { -952 when: Instant::now(), -953 local_candidates, -954 remote_candidates, -955 }); -956 } -957 Err(err) => { -958 debug!("failed to initiate NAT traversal: {err:#}"); -959 use noq_proto::n0_nat_traversal::Error; -960 match err { -961 Error::Closed -962 | Error::TooManyAddresses -963 | Error::WrongConnectionSide -964 | Error::ExtensionNotNegotiated => { -965 // Fatal, no need to retry for now -966 } -967 Error::Multipath(_) | Error::NotEnoughAddresses => { -968 // Retry in a bit -969 let now = Instant::now(); -970 let next_hp = now + Duration::from_millis(100); -971 trace!(scheduled_in = ?(next_hp - now), "holepunching retry"); -972 self.scheduled_holepunch = Some(next_hp); -973 } -974 } -975 } -976 } -977 } -978 -979 /// Register a path with our state and configure path-specific settings. -980 /// -981 /// This inserts the path in the [`ConnectionState`] and [`Self::paths`]. -982 /// -983 /// It configures the path with the correct path status (see [`Self::set_path_status`]), -984 /// and applies path-type-specific settings: -985 /// Relay paths get a longer idle timeout to accommodate transparent reconnection -986 /// by the relay actor (see [`RELAY_PATH_MAX_IDLE_TIMEOUT`]). -987 fn register_and_configure_path( -988 &mut self, -989 conn_id: ConnId, -990 conn_state: &mut ConnectionState, -991 path: &noq::Path, -992 ) -> Option<transports::Addr> { -993 let path_remote = self.transport_addr_for_path(path)?; -994 event!( -995 target: "iroh::_events::path::open", -996 Level::DEBUG, -997 remote = %self.endpoint_id.fmt_short(), -998 ?path_remote, -999 %conn_id, -1000 path_id=%path.id(), -1001 ); -1002 conn_state.add_open_path(path_remote.clone(), path.id(), &self.metrics); -1003 if matches!(path_remote, transports::Addr::Relay(..)) -1004 && let Err(e) = path.set_max_idle_timeout(Some(RELAY_PATH_MAX_IDLE_TIMEOUT)) -1005 { -1006 debug!(?e, "failed to set relay path idle timeout"); -1007 } -1008 -1009 self.set_path_status(conn_id, path, &path_remote); -1010 self.paths -1011 .insert_open_path(path_remote.clone(), Source::Connection); -1012 Some(path_remote) -1013 } -1014 -1015 fn set_path_status( -1016 &mut self, -1017 conn_id: ConnId, -1018 path: &noq::Path, -1019 path_remote: &transports::Addr, -1020 ) { -1021 let status = self.path_status_for_addr(path_remote); -1022 match path.set_status(status) { -1023 Err(error) => warn!(?error, ?path_remote, ?status, "set_status failed"), -1024 Ok(prev_status) if prev_status != status => { -1025 event!( -1026 target: "iroh::_events::path::set_status", -1027 Level::DEBUG, -1028 remote = %self.endpoint_id.fmt_short(), -1029 path_remote = ?path_remote, -1030 ?status, -1031 %conn_id, -1032 path_id=%path.id(), -1033 ?prev_status, -1034 ); -1035 } -1036 Ok(_) => {} -1037 } -1038 } -1039 -1040 fn open_path_on_conn( -1041 &mut self, -1042 conn_id: ConnId, -1043 conn_state: &ConnectionState, -1044 conn: &noq::Connection, -1045 open_addr: &transports::Addr, -1046 ) { -1047 // Only the client opens paths; the server receives them via -1048 // QUIC frames and reacts to PathOpened events. -1049 if conn.side().is_server() { -1050 return; -1051 } -1052 // Already open on this connection; nothing to do. -1053 if conn_state.paths.values().any(|a| a == open_addr) { -1054 return; -1055 } -1056 -1057 let quic_addr = self.quic_mapped_addr(open_addr); -1058 let path_status = self.path_status_for_addr(open_addr); -1059 -1060 let fut = conn.open_path_ensure(quic_addr, path_status); -1061 match fut.path_id() { -1062 Some(path_id) => { -1063 trace!(%conn_id, %path_id, ?path_status, "opening new path"); -1064 } -1065 None => { -1066 let ret = now_or_never(fut); -1067 match ret { -1068 Some(Err(PathError::RemoteCidsExhausted)) => { -1069 self.scheduled_open_path = -1070 Some(Instant::now() + Duration::from_millis(333)); -1071 self.pending_open_paths.push_back(open_addr.clone()); -1072 trace!(?open_addr, "scheduling open_path"); -1073 } -1074 _ => warn!(?ret, "Opening path failed"), -1075 } -1076 } -1077 } -1078 } -1079 -1080 /// Returns the [`PathStatus`] for `addr`. -1081 /// -1082 /// Returns [`PathStatus::Available`] if `addr` is the currently-selected path, -1083 /// or [`PathStatus::Backup`] otherwise. -1084 fn path_status_for_addr(&self, addr: &transports::Addr) -> PathStatus { -1085 if Some(addr) == self.selected_path.as_ref() { -1086 PathStatus::Available -1087 } else { -1088 PathStatus::Backup -1089 } -1090 } -1091 -1092 /// Returns the QUIC-mapped address for a [`transports::Addr`]. -1093 fn quic_mapped_addr(&self, open_addr: &transports::Addr) -> SocketAddr { -1094 match open_addr { -1095 transports::Addr::Ip(socket_addr) => *socket_addr, -1096 transports::Addr::Relay(relay_url, eid) => self -1097 .relay_mapped_addrs -1098 .get(&(relay_url.clone(), *eid)) -1099 .private_socket_addr(), -1100 transports::Addr::Custom(remote) => { -1101 self.custom_mapped_addrs.get(remote).private_socket_addr() -1102 } -1103 } -1104 } -1105 -1106 /// Returns the [`transports::Addr] for a path. -1107 fn transport_addr_for_path(&self, path: &noq::Path) -> Option<transports::Addr> { -1108 let socketaddr = path.remote_address().ok()?; -1109 to_transport_addr( -1110 socketaddr, -1111 &self.relay_mapped_addrs, -1112 &self.custom_mapped_addrs, -1113 ) -1114 } -1115 -1116 /// Returns the current set of local direct addresses. -1117 fn local_candidates(&mut self) -> BTreeSet<SocketAddr> { -1118 self.local_direct_addrs -1119 .get() -1120 .iter() -1121 .map(|d| d.addr) -1122 .collect() -1123 } -1124} -1125 -1126/// Returns `Some` if a new path should be selected, `None` if the `current_path` should -1127/// continued to be used. -1128fn select_best_path<'a>( -1129 all_paths: FxHashMap<&'a transports::Addr, PathSelectionData>, -1130 current_path: Option<&'a transports::Addr>, -1131) -> Option<(transports::Addr, Duration)> { -1132 // Determine the best new path according to sort_key. -1133 // If there is no path, return None. -1134 let (best_addr, best_data) = all_paths.iter().min_by_key(|(_, psd)| psd.sort_key())?; -1135 // If there is no current path, always switch to the best path. -1136 let Some(addr) = current_path else { -1137 return Some(((*best_addr).clone(), best_data.rtt)); -1138 }; -1139 // Get current data. If we don't have data for the current path, switch to the best path. -1140 let Some(current_data) = all_paths.get(addr) else { -1141 return Some(((*best_addr).clone(), best_data.rtt)); -1142 }; -1143 if current_data.transport_type != best_data.transport_type { -1144 // Always switch if the status is different (better). -1145 Some(((*best_addr).clone(), best_data.rtt)) -1146 } else if best_data.biased_rtt + RTT_SWITCHING_MIN_IP.as_nanos() as i128 -1147 <= current_data.biased_rtt -1148 { -1149 // For the same status, only switch if the biased RTT is significantly better. -1150 Some(((*best_addr).clone(), best_data.rtt)) -1151 } else { -1152 None -1153 } -1154} -1155 -1156/// Updates QNT's candidate addresses to be the current set of direct addresses. -1157/// -1158/// `direct_addrs` must be a set of addresses extracted from the endpoint's current -1159/// [`DirectAddr`]s. -1160fn update_qnt_candidates(conn: &noq::Connection, direct_addrs: &BTreeSet<SocketAddr>) { -1161 let noq_candidates = match conn.get_local_nat_traversal_addresses() { -1162 Ok(addrs) => BTreeSet::from_iter(addrs), -1163 Err(err) => { -1164 warn!("failed to get local nat candidates: {err:#}"); -1165 return; -1166 } -1167 }; -1168 for addr in direct_addrs.difference(&noq_candidates) { -1169 if let Err(err) = conn.add_nat_traversal_address(*addr) { -1170 warn!("failed adding local addr: {err:#}",); -1171 } -1172 } -1173 for addr in noq_candidates.difference(direct_addrs) { -1174 if let Err(err) = conn.remove_nat_traversal_address(*addr) { -1175 warn!("failed removing local addr: {err:#}"); -1176 } -1177 } -1178 trace!(?direct_addrs, "updated local QNT addresses"); -1179} -1180 -1181fn send_datagram<'a>( -1182 sender: &'a mut TransportsSender, -1183 dst: transports::Addr, -1184 owned_transmit: OwnedTransmit, -1185) -> impl Future<Output = n0_error::Result<()>> + 'a { -1186 std::future::poll_fn(move |cx| { -1187 let transmit = transports::Transmit { -1188 ecn: owned_transmit.ecn, -1189 contents: owned_transmit.contents.as_ref(), -1190 segment_size: owned_transmit.segment_size, -1191 }; -1192 -1193 Pin::new(&mut *sender) -1194 .poll_send(cx, &dst, None, &transmit) -1195 .map(|res| res.with_context(|_| format!("failed to send datagram to {dst:?}"))) -1196 }) -1197} -1198 -1199/// Messages to send to the [`RemoteStateActor`]. -1200#[derive(derive_more::Debug)] -1201pub(crate) enum RemoteStateMessage { -1202 /// Sends a datagram to all known paths. -1203 /// -1204 /// Used to send QUIC Initial packets. If there is no working direct path this will -1205 /// trigger holepunching. -1206 /// -1207 /// This is not acceptable to use on the normal send path, as it is an async send -1208 /// operation with a bunch more copying. So it should only be used for sending QUIC -1209 /// Initial packets. -1210 #[debug("SendDatagram(..)")] -1211 SendDatagram(Box<TransportsSender>, OwnedTransmit), -1212 /// Adds an active connection to this remote endpoint. +813 if !is_goodenough { +814 debug!("connections are not good enough, triggering holepunching"); +815 self.trigger_holepunching(); +816 } +817 } +818} +819 +820impl State { +821 /// Handles [`RemoteStateMessage::SendDatagram`]. +822 async fn handle_msg_send_datagram( +823 &mut self, +824 mut sender: Box<TransportsSender>, +825 transmit: OwnedTransmit, +826 ) { +827 // Sending datagrams might fail, e.g. because we don't have the right transports set +828 // up to handle sending this owned transmit to. +829 // After all, we try every single path that we know (relay URL, IP address), even +830 // though we might not have a relay transport or ip-capable transport set up. +831 // So these errors must not be fatal for this actor (or even this operation). +832 +833 if let Some(addr) = self.selected_path.as_ref() { +834 trace!(?addr, "sending datagram to selected path"); +835 +836 if let Err(err) = send_datagram(&mut sender, addr.clone(), transmit).await { +837 debug!(?addr, "failed to send datagram on selected_path: {err:#}"); +838 } +839 } else { +840 trace!( +841 paths = ?self.paths.addrs().collect::<Vec<_>>(), +842 "sending datagram to all known paths", +843 ); +844 if self.paths.is_empty() { +845 warn!("Cannot send datagrams: No paths to remote endpoint known"); +846 } +847 +848 for addr in self.paths.addrs() { +849 // We never want to send to our local addresses. +850 // The local address set is updated in the main loop so we can use `peek` here. +851 if let transports::Addr::Ip(sockaddr) = addr +852 && self +853 .local_direct_addrs +854 .peek() +855 .iter() +856 .any(|a| a.addr == *sockaddr) +857 { +858 trace!(%sockaddr, "not sending datagram to our own address"); +859 } else if let Err(err) = +860 send_datagram(&mut sender, addr.clone(), transmit.clone()).await +861 { +862 debug!(?addr, "failed to send datagram: {err:#}"); +863 } +864 } +865 // This message is received *before* a connection is added. So we do +866 // not yet have a connection to holepunch. Instead we trigger +867 // holepunching when AddConnection is received. +868 } +869 } +870 +871 /// Handles [`RemoteStateMessage::ResolveRemote`]. +872 fn handle_msg_resolve_remote( +873 &mut self, +874 addrs: BTreeSet<TransportAddr>, +875 tx: oneshot::Sender<Result<(), AddressLookupFailed>>, +876 ) { +877 let addrs = to_transports_addr(self.endpoint_id, addrs); +878 self.paths.insert_multiple(addrs, Source::App); +879 self.paths.resolve_remote(tx); +880 // Start Address Lookup if we have no selected path. +881 self.trigger_address_lookup(); +882 } +883 +884 /// Triggers Address Lookup for the remote endpoint, if needed. +885 /// +886 /// Does not start Address Lookup if we have a selected path or if Address Lookup is +887 /// currently running. +888 fn trigger_address_lookup(&mut self) { +889 if self.selected_path.is_some() || self.address_lookup_stream.is_some() { +890 return; +891 } +892 let stream = self.address_lookup.resolve(self.endpoint_id); +893 let stream = stream.filter_map(|item| match item { +894 // We don't care about errors from individual services, we just continue. +895 // Individual errors are buffered into the final error by `AddressLookupServices::resolve`, +896 // and if the lookup fails we return them upstream with the final `AddressLookupFailed` error. +897 Ok(Err(_err)) => None, +898 Ok(Ok(item)) => Some(Ok(item)), +899 Err(err) => Some(Err(err)), +900 }); +901 self.address_lookup_stream = Some(Box::pin(stream)); +902 } +903 +904 /// Handles an address lookup result. +905 /// +906 /// All address lookup results end up being sent here. It takes care of updating the +907 /// [`RemotePathState`] with the results. +908 fn handle_address_lookup_item( +909 &mut self, +910 item: Option<Result<AddressLookupItem, AddressLookupFailed>>, +911 ) { +912 match item { +913 None => { +914 self.paths.address_lookup_finished(Ok(())); +915 self.address_lookup_stream = None; +916 } +917 Some(Err(err)) => { +918 warn!("Address Lookup failed: {err:#}"); +919 self.paths.address_lookup_finished(Err(err)); +920 self.address_lookup_stream = None; +921 } +922 Some(Ok(item)) => { +923 if item.endpoint_id() != self.endpoint_id { +924 warn!( +925 ?item, +926 "Address Lookup emitted item for wrong remote endpoint" +927 ); +928 } else { +929 let source = Source::AddressLookup { +930 name: item.provenance().to_string(), +931 }; +932 let addrs = +933 to_transports_addr(self.endpoint_id, item.into_endpoint_addr().addrs); +934 self.paths.insert_multiple(addrs, source); +935 } +936 } +937 } +938 } +939 +940 /// Unconditionally perform holepunching. +941 #[instrument(skip_all)] +942 fn do_holepunching(&mut self, conn: noq::Connection) { +943 self.metrics.holepunch_attempts.inc(); +944 let local_candidates = self.local_candidates(); +945 match conn.initiate_nat_traversal_round() { +946 Ok(remote_candidates) => { +947 let remote_candidates = remote_candidates +948 .iter() +949 .map(|addr| SocketAddr::new(addr.ip().to_canonical(), addr.port())) +950 .collect(); +951 event!( +952 target: "iroh::_events::qnt::init", +953 Level::DEBUG, +954 remote = %self.endpoint_id.fmt_short(), +955 ?local_candidates, +956 ?remote_candidates, +957 ); +958 self.last_holepunch = Some(HolepunchAttempt { +959 when: Instant::now(), +960 local_candidates, +961 remote_candidates, +962 }); +963 } +964 Err(err) => { +965 debug!("failed to initiate NAT traversal: {err:#}"); +966 use noq_proto::n0_nat_traversal::Error; +967 match err { +968 Error::Closed +969 | Error::TooManyAddresses +970 | Error::WrongConnectionSide +971 | Error::ExtensionNotNegotiated => { +972 // Fatal, no need to retry for now +973 } +974 Error::Multipath(_) | Error::NotEnoughAddresses => { +975 // Retry in a bit +976 let now = Instant::now(); +977 let next_hp = now + Duration::from_millis(100); +978 trace!(scheduled_in = ?(next_hp - now), "holepunching retry"); +979 self.scheduled_holepunch = Some(next_hp); +980 } +981 } +982 } +983 } +984 } +985 +986 /// Register a path with our state and configure path-specific settings. +987 /// +988 /// This inserts the path in the [`ConnectionState`] and [`Self::paths`]. +989 /// +990 /// It configures the path with the correct path status (see [`Self::set_path_status`]), +991 /// and applies path-type-specific settings: +992 /// Relay paths get a longer idle timeout to accommodate transparent reconnection +993 /// by the relay actor (see [`RELAY_PATH_MAX_IDLE_TIMEOUT`]). +994 fn register_and_configure_path( +995 &mut self, +996 conn_id: ConnId, +997 conn_state: &mut ConnectionState, +998 path: &noq::Path, +999 ) -> Option<transports::Addr> { +1000 let path_remote = self.transport_addr_for_path(path)?; +1001 event!( +1002 target: "iroh::_events::path::open", +1003 Level::DEBUG, +1004 remote = %self.endpoint_id.fmt_short(), +1005 ?path_remote, +1006 %conn_id, +1007 path_id=%path.id(), +1008 ); +1009 conn_state.add_open_path(path_remote.clone(), path.id(), &self.metrics); +1010 if matches!(path_remote, transports::Addr::Relay(..)) +1011 && let Err(e) = path.set_max_idle_timeout(Some(RELAY_PATH_MAX_IDLE_TIMEOUT)) +1012 { +1013 debug!(?e, "failed to set relay path idle timeout"); +1014 } +1015 +1016 self.set_path_status(conn_id, path, &path_remote); +1017 self.paths +1018 .insert_open_path(path_remote.clone(), Source::Connection); +1019 Some(path_remote) +1020 } +1021 +1022 fn set_path_status( +1023 &mut self, +1024 conn_id: ConnId, +1025 path: &noq::Path, +1026 path_remote: &transports::Addr, +1027 ) { +1028 let status = self.path_status_for_addr(path_remote); +1029 match path.set_status(status) { +1030 Err(error) => warn!(?error, ?path_remote, ?status, "set_status failed"), +1031 Ok(prev_status) if prev_status != status => { +1032 event!( +1033 target: "iroh::_events::path::set_status", +1034 Level::DEBUG, +1035 remote = %self.endpoint_id.fmt_short(), +1036 path_remote = ?path_remote, +1037 ?status, +1038 %conn_id, +1039 path_id=%path.id(), +1040 ?prev_status, +1041 ); +1042 } +1043 Ok(_) => {} +1044 } +1045 } +1046 +1047 fn open_path_on_conn( +1048 &mut self, +1049 conn_id: ConnId, +1050 conn_state: &ConnectionState, +1051 conn: &noq::Connection, +1052 open_addr: &transports::Addr, +1053 ) { +1054 // Only the client opens paths; the server receives them via +1055 // QUIC frames and reacts to PathOpened events. +1056 if conn.side().is_server() { +1057 return; +1058 } +1059 // Already open on this connection; nothing to do. +1060 if conn_state.paths.values().any(|a| a == open_addr) { +1061 return; +1062 } +1063 +1064 let quic_addr = self.quic_mapped_addr(open_addr); +1065 let path_status = self.path_status_for_addr(open_addr); +1066 +1067 let fut = conn.open_path_ensure(quic_addr, path_status); +1068 match fut.path_id() { +1069 Some(path_id) => { +1070 trace!(%conn_id, %path_id, ?path_status, "opening new path"); +1071 } +1072 None => { +1073 let ret = now_or_never(fut); +1074 match ret { +1075 Some(Err(PathError::RemoteCidsExhausted)) => { +1076 self.scheduled_open_path = +1077 Some(Instant::now() + Duration::from_millis(333)); +1078 self.pending_open_paths.push_back(open_addr.clone()); +1079 trace!(?open_addr, "scheduling open_path"); +1080 } +1081 _ => warn!(?ret, "Opening path failed"), +1082 } +1083 } +1084 } +1085 } +1086 +1087 /// Returns the [`PathStatus`] for `addr`. +1088 /// +1089 /// Returns [`PathStatus::Available`] if `addr` is the currently-selected path, +1090 /// or [`PathStatus::Backup`] otherwise. +1091 fn path_status_for_addr(&self, addr: &transports::Addr) -> PathStatus { +1092 if Some(addr) == self.selected_path.as_ref() { +1093 PathStatus::Available +1094 } else { +1095 PathStatus::Backup +1096 } +1097 } +1098 +1099 /// Returns the QUIC-mapped address for a [`transports::Addr`]. +1100 fn quic_mapped_addr(&self, open_addr: &transports::Addr) -> SocketAddr { +1101 match open_addr { +1102 transports::Addr::Ip(socket_addr) => *socket_addr, +1103 transports::Addr::Relay(relay_url, eid) => self +1104 .relay_mapped_addrs +1105 .get(&(relay_url.clone(), *eid)) +1106 .private_socket_addr(), +1107 transports::Addr::Custom(remote) => { +1108 self.custom_mapped_addrs.get(remote).private_socket_addr() +1109 } +1110 } +1111 } +1112 +1113 /// Returns the [`transports::Addr] for a path. +1114 fn transport_addr_for_path(&self, path: &noq::Path) -> Option<transports::Addr> { +1115 let socketaddr = path.remote_address().ok()?; +1116 to_transport_addr( +1117 socketaddr, +1118 &self.relay_mapped_addrs, +1119 &self.custom_mapped_addrs, +1120 ) +1121 } +1122 +1123 /// Returns the current set of local direct addresses. +1124 fn local_candidates(&mut self) -> BTreeSet<SocketAddr> { +1125 self.local_direct_addrs +1126 .get() +1127 .iter() +1128 .map(|d| d.addr) +1129 .collect() +1130 } +1131} +1132 +1133/// Returns `Some` if a new path should be selected, `None` if the `current_path` should +1134/// continued to be used. +1135fn select_best_path<'a>( +1136 all_paths: FxHashMap<&'a transports::Addr, PathSelectionData>, +1137 current_path: Option<&'a transports::Addr>, +1138) -> Option<(transports::Addr, Duration)> { +1139 // Determine the best new path according to sort_key. +1140 // If there is no path, return None. +1141 let (best_addr, best_data) = all_paths.iter().min_by_key(|(_, psd)| psd.sort_key())?; +1142 // If there is no current path, always switch to the best path. +1143 let Some(addr) = current_path else { +1144 return Some(((*best_addr).clone(), best_data.rtt)); +1145 }; +1146 // Get current data. If we don't have data for the current path, switch to the best path. +1147 let Some(current_data) = all_paths.get(addr) else { +1148 return Some(((*best_addr).clone(), best_data.rtt)); +1149 }; +1150 if current_data.transport_type != best_data.transport_type { +1151 // Always switch if the status is different (better). +1152 Some(((*best_addr).clone(), best_data.rtt)) +1153 } else if best_data.biased_rtt + RTT_SWITCHING_MIN_IP.as_nanos() as i128 +1154 <= current_data.biased_rtt +1155 { +1156 // For the same status, only switch if the biased RTT is significantly better. +1157 Some(((*best_addr).clone(), best_data.rtt)) +1158 } else { +1159 None +1160 } +1161} +1162 +1163/// Updates QNT's candidate addresses to be the current set of direct addresses. +1164/// +1165/// `direct_addrs` must be a set of addresses extracted from the endpoint's current +1166/// [`DirectAddr`]s. +1167fn update_qnt_candidates(conn: &noq::Connection, direct_addrs: &BTreeSet<SocketAddr>) { +1168 let noq_candidates = match conn.get_local_nat_traversal_addresses() { +1169 Ok(addrs) => BTreeSet::from_iter(addrs), +1170 Err(err) => { +1171 warn!("failed to get local nat candidates: {err:#}"); +1172 return; +1173 } +1174 }; +1175 for addr in direct_addrs.difference(&noq_candidates) { +1176 if let Err(err) = conn.add_nat_traversal_address(*addr) { +1177 warn!("failed adding local addr: {err:#}",); +1178 } +1179 } +1180 for addr in noq_candidates.difference(direct_addrs) { +1181 if let Err(err) = conn.remove_nat_traversal_address(*addr) { +1182 warn!("failed removing local addr: {err:#}"); +1183 } +1184 } +1185 trace!(?direct_addrs, "updated local QNT addresses"); +1186} +1187 +1188fn send_datagram<'a>( +1189 sender: &'a mut TransportsSender, +1190 dst: transports::Addr, +1191 owned_transmit: OwnedTransmit, +1192) -> impl Future<Output = n0_error::Result<()>> + 'a { +1193 std::future::poll_fn(move |cx| { +1194 let transmit = transports::Transmit { +1195 ecn: owned_transmit.ecn, +1196 contents: owned_transmit.contents.as_ref(), +1197 segment_size: owned_transmit.segment_size, +1198 }; +1199 +1200 Pin::new(&mut *sender) +1201 .poll_send(cx, &dst, None, &transmit) +1202 .map(|res| res.with_context(|_| format!("failed to send datagram to {dst:?}"))) +1203 }) +1204} +1205 +1206/// Messages to send to the [`RemoteStateActor`]. +1207#[derive(derive_more::Debug)] +1208pub(crate) enum RemoteStateMessage { +1209 /// Sends a datagram to all known paths. +1210 /// +1211 /// Used to send QUIC Initial packets. If there is no working direct path this will +1212 /// trigger holepunching. 1213 /// -1214 /// The actor will downgrade the connection to a [`noq::WeakConnectionHandle`] as soon -1215 /// as it processes the message. It will keep hold of the weak handle until it closes, -1216 /// but only update to a strong [`noq::Connection`] for brief moments. -1217 /// -1218 /// The actor will actively manage paths on the connection and start holepunching as needed. -1219 #[debug("AddConnection(..)")] -1220 AddConnection(noq::Connection, oneshot::Sender<PathStateReceiver>), -1221 /// Asks if there is any possible path that could be used. -1222 /// -1223 /// This adds the provided transport addresses to the list of potential paths for this -1224 /// remote and starts Address Lookup if needed. -1225 /// -1226 /// Sends back `Ok` immediately if the provided address list is non-empy or we have are -1227 /// other known paths. Otherwise sends back `Ok` once Address Lookup produces a result, -1228 /// or the Address Lookup error if Address Lookup fails or produces no results, -1229 #[debug("ResolveRemote(..)")] -1230 ResolveRemote( -1231 BTreeSet<TransportAddr>, -1232 oneshot::Sender<Result<(), AddressLookupFailed>>, -1233 ), -1234 /// Returns information about the remote. -1235 /// -1236 /// This currently only includes a list of all known transport addresses for the remote. -1237 RemoteInfo(oneshot::Sender<RemoteInfo>), -1238 /// The network status has changed in some way -1239 NetworkChange { is_major: bool }, -1240} -1241 -1242/// Information about a holepunch attempt. -1243/// -1244/// Addresses are always stored in canonical form. -1245#[derive(Debug)] -1246struct HolepunchAttempt { -1247 when: Instant, -1248 /// The set of local addresses which could take part in holepunching. -1249 /// -1250 /// This does not mean every address here participated in the holepunching. E.g. we -1251 /// could have tried only a sub-set of the addresses because a previous attempt already -1252 /// covered part of the range. -1253 /// -1254 /// We do not store this as a [`DirectAddr`] because this is checked for equality and we -1255 /// do not want to compare the sources of these addresses. -1256 local_candidates: BTreeSet<SocketAddr>, -1257 /// The set of remote addresses which could take part in holepunching. -1258 /// -1259 /// Like [`Self::local_candidates`] we may not have used them. -1260 remote_candidates: BTreeSet<SocketAddr>, -1261} -1262 -1263/// Newtype to track Connections. -1264/// -1265/// The wrapped value is the [`noq::Connection::stable_id`] value, and is thus only valid -1266/// for active connections. -1267#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, derive_more::Display)] -1268#[display("{_0}")] -1269struct ConnId(usize); -1270 -1271/// State about one connection. -1272#[derive(Debug)] -1273struct ConnectionState { -1274 /// Weak handle to the connection. -1275 handle: WeakConnectionHandle, -1276 /// Writer-side handle for the connection's path observation state. -1277 /// -1278 /// The matching [`PathStateReceiver`] is held by the [`Connection`]. -1279 /// -1280 /// [`Connection`]: crate::endpoint::Connection -1281 path_state: PathStateSender, -1282 /// The open paths that exist on this connection. -1283 paths: FxHashMap<PathId, transports::Addr>, -1284 /// Whether this connection has ever had a direct path. -1285 /// -1286 /// Used for recording metrics. -1287 has_been_direct: bool, -1288} -1289 -1290impl ConnectionState { -1291 /// Tracks an open path for the connection. -1292 fn add_open_path( -1293 &mut self, -1294 remote: transports::Addr, -1295 path_id: PathId, -1296 metrics: &Arc<SocketMetrics>, -1297 ) { -1298 match remote { -1299 transports::Addr::Ip(_) => metrics.paths_direct.inc(), -1300 transports::Addr::Relay(_, _) => metrics.paths_relay.inc(), -1301 transports::Addr::Custom(_) => metrics.paths_custom.inc(), -1302 }; -1303 if !self.has_been_direct && remote.is_ip() { -1304 self.has_been_direct = true; -1305 metrics.num_conns_direct.inc(); -1306 } -1307 -1308 self.paths.insert(path_id, remote.clone()); -1309 if let Some(conn) = self.handle.upgrade() -1310 && let Some(path) = conn.path(path_id) -1311 { -1312 let handle = path.weak_handle(); -1313 self.path_state.record_opened(handle, remote.into()); -1314 } -1315 } -1316 -1317 /// Removes a path from this connection. -1318 fn remove_path( -1319 &mut self, -1320 path_id: &PathId, -1321 conn: &noq::Connection, -1322 ) -> Option<transports::Addr> { -1323 let addr = self.paths.remove(path_id)?; -1324 self.path_state.record_abandoned(*path_id, conn); -1325 Some(addr) -1326 } -1327} -1328 -1329/// Poll a future once, like n0_future::future::poll_once but sync. -1330fn now_or_never<T, F: Future<Output = T>>(fut: F) -> Option<T> { -1331 let fut = std::pin::pin!(fut); -1332 match fut.poll(&mut std::task::Context::from_waker(std::task::Waker::noop())) { -1333 Poll::Ready(res) => Some(res), -1334 Poll::Pending => None, -1335 } -1336} -1337 -1338/// Future that resolves to the `conn_id` once a connection is closed. -1339/// -1340/// This uses [`noq::Connection::on_closed`], which does not keep the connection alive -1341/// while awaiting the future. -1342struct OnClosed { -1343 conn_id: ConnId, -1344 inner: noq::OnClosed, -1345} -1346 -1347impl OnClosed { -1348 fn new(conn: &noq::Connection) -> Self { -1349 Self { -1350 conn_id: ConnId(conn.stable_id()), -1351 inner: conn.on_closed(), -1352 } -1353 } -1354} -1355 -1356impl Future for OnClosed { -1357 type Output = (ConnId, Closed); -1358 -1359 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { -1360 let closed = std::task::ready!(Pin::new(&mut self.inner).poll(cx)); -1361 Poll::Ready((self.conn_id, closed)) -1362 } -1363} -1364 -1365/// Converts an iterator of [`TransportAddr'] into an iterator of [`transports::Addr`]. -1366fn to_transports_addr( -1367 endpoint_id: EndpointId, -1368 addrs: impl IntoIterator<Item = TransportAddr>, -1369) -> impl Iterator<Item = transports::Addr> { -1370 addrs.into_iter().filter_map(move |addr| match addr { -1371 TransportAddr::Relay(relay_url) => Some(transports::Addr::from((relay_url, endpoint_id))), -1372 TransportAddr::Ip(sockaddr) => Some(transports::Addr::from(sockaddr)), -1373 TransportAddr::Custom(custom_addr) => Some(transports::Addr::from(custom_addr)), -1374 _ => { -1375 warn!(?addr, "Unsupported TransportAddr"); -1376 None -1377 } -1378 }) -1379} -1380 -1381/// Returns the next item if `maybe_stream` is `Some`, or `None` otherwise. -1382async fn maybe_next<S: Stream + Unpin>(maybe_stream: Option<&mut S>) -> Option<Option<S::Item>> { -1383 match maybe_stream { -1384 None => None, -1385 Some(s) => Some(s.next().await), -1386 } -1387} -1388 -1389#[cfg(test)] -1390mod tests { -1391 use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6}; -1392 -1393 use super::*; -1394 use crate::socket::transports::TransportType; +1214 /// This is not acceptable to use on the normal send path, as it is an async send +1215 /// operation with a bunch more copying. So it should only be used for sending QUIC +1216 /// Initial packets. +1217 #[debug("SendDatagram(..)")] +1218 SendDatagram(Box<TransportsSender>, OwnedTransmit), +1219 /// Adds an active connection to this remote endpoint. +1220 /// +1221 /// The actor will downgrade the connection to a [`noq::WeakConnectionHandle`] as soon +1222 /// as it processes the message. It will keep hold of the weak handle until it closes, +1223 /// but only update to a strong [`noq::Connection`] for brief moments. +1224 /// +1225 /// The actor will actively manage paths on the connection and start holepunching as needed. +1226 #[debug("AddConnection(..)")] +1227 AddConnection(noq::Connection, oneshot::Sender<PathStateReceiver>), +1228 /// Asks if there is any possible path that could be used. +1229 /// +1230 /// This adds the provided transport addresses to the list of potential paths for this +1231 /// remote and starts Address Lookup if needed. +1232 /// +1233 /// Sends back `Ok` immediately if the provided address list is non-empy or we have are +1234 /// other known paths. Otherwise sends back `Ok` once Address Lookup produces a result, +1235 /// or the Address Lookup error if Address Lookup fails or produces no results, +1236 #[debug("ResolveRemote(..)")] +1237 ResolveRemote( +1238 BTreeSet<TransportAddr>, +1239 oneshot::Sender<Result<(), AddressLookupFailed>>, +1240 ), +1241 /// Returns information about the remote. +1242 /// +1243 /// This currently only includes a list of all known transport addresses for the remote. +1244 RemoteInfo(oneshot::Sender<RemoteInfo>), +1245 /// The network status has changed in some way +1246 NetworkChange { is_major: bool }, +1247} +1248 +1249/// Information about a holepunch attempt. +1250/// +1251/// Addresses are always stored in canonical form. +1252#[derive(Debug)] +1253struct HolepunchAttempt { +1254 when: Instant, +1255 /// The set of local addresses which could take part in holepunching. +1256 /// +1257 /// This does not mean every address here participated in the holepunching. E.g. we +1258 /// could have tried only a sub-set of the addresses because a previous attempt already +1259 /// covered part of the range. +1260 /// +1261 /// We do not store this as a [`DirectAddr`] because this is checked for equality and we +1262 /// do not want to compare the sources of these addresses. +1263 local_candidates: BTreeSet<SocketAddr>, +1264 /// The set of remote addresses which could take part in holepunching. +1265 /// +1266 /// Like [`Self::local_candidates`] we may not have used them. +1267 remote_candidates: BTreeSet<SocketAddr>, +1268} +1269 +1270/// Newtype to track Connections. +1271/// +1272/// The wrapped value is the [`noq::Connection::stable_id`] value, and is thus only valid +1273/// for active connections. +1274#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, derive_more::Display)] +1275#[display("{_0}")] +1276struct ConnId(usize); +1277 +1278/// State about one connection. +1279#[derive(Debug)] +1280struct ConnectionState { +1281 /// Weak handle to the connection. +1282 handle: WeakConnectionHandle, +1283 /// Writer-side handle for the connection's path observation state. +1284 /// +1285 /// The matching [`PathStateReceiver`] is held by the [`Connection`]. +1286 /// +1287 /// [`Connection`]: crate::endpoint::Connection +1288 path_state: PathStateSender, +1289 /// The open paths that exist on this connection. +1290 paths: FxHashMap<PathId, transports::Addr>, +1291 /// Whether this connection has ever had a direct path. +1292 /// +1293 /// Used for recording metrics. +1294 has_been_direct: bool, +1295} +1296 +1297impl ConnectionState { +1298 /// Tracks an open path for the connection. +1299 fn add_open_path( +1300 &mut self, +1301 remote: transports::Addr, +1302 path_id: PathId, +1303 metrics: &Arc<SocketMetrics>, +1304 ) { +1305 match remote { +1306 transports::Addr::Ip(_) => metrics.paths_direct.inc(), +1307 transports::Addr::Relay(_, _) => metrics.paths_relay.inc(), +1308 transports::Addr::Custom(_) => metrics.paths_custom.inc(), +1309 }; +1310 if !self.has_been_direct && remote.is_ip() { +1311 self.has_been_direct = true; +1312 metrics.num_conns_direct.inc(); +1313 } +1314 +1315 self.paths.insert(path_id, remote.clone()); +1316 if let Some(conn) = self.handle.upgrade() +1317 && let Some(path) = conn.path(path_id) +1318 { +1319 let handle = path.weak_handle(); +1320 self.path_state.record_opened(handle, remote.into()); +1321 } +1322 } +1323 +1324 /// Removes a path from this connection. +1325 fn remove_path( +1326 &mut self, +1327 path_id: &PathId, +1328 conn: &noq::Connection, +1329 ) -> Option<transports::Addr> { +1330 let addr = self.paths.remove(path_id)?; +1331 self.path_state.record_abandoned(*path_id, conn); +1332 Some(addr) +1333 } +1334} +1335 +1336/// Poll a future once, like n0_future::future::poll_once but sync. +1337fn now_or_never<T, F: Future<Output = T>>(fut: F) -> Option<T> { +1338 let fut = std::pin::pin!(fut); +1339 match fut.poll(&mut std::task::Context::from_waker(std::task::Waker::noop())) { +1340 Poll::Ready(res) => Some(res), +1341 Poll::Pending => None, +1342 } +1343} +1344 +1345/// Future that resolves to the `conn_id` once a connection is closed. +1346/// +1347/// This uses [`noq::Connection::on_closed`], which does not keep the connection alive +1348/// while awaiting the future. +1349struct OnClosed { +1350 conn_id: ConnId, +1351 inner: noq::OnClosed, +1352} +1353 +1354impl OnClosed { +1355 fn new(conn: &noq::Connection) -> Self { +1356 Self { +1357 conn_id: ConnId(conn.stable_id()), +1358 inner: conn.on_closed(), +1359 } +1360 } +1361} +1362 +1363impl Future for OnClosed { +1364 type Output = (ConnId, Closed); +1365 +1366 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { +1367 let closed = std::task::ready!(Pin::new(&mut self.inner).poll(cx)); +1368 Poll::Ready((self.conn_id, closed)) +1369 } +1370} +1371 +1372/// Converts an iterator of [`TransportAddr'] into an iterator of [`transports::Addr`]. +1373fn to_transports_addr( +1374 endpoint_id: EndpointId, +1375 addrs: impl IntoIterator<Item = TransportAddr>, +1376) -> impl Iterator<Item = transports::Addr> { +1377 addrs.into_iter().filter_map(move |addr| match addr { +1378 TransportAddr::Relay(relay_url) => Some(transports::Addr::from((relay_url, endpoint_id))), +1379 TransportAddr::Ip(sockaddr) => Some(transports::Addr::from(sockaddr)), +1380 TransportAddr::Custom(custom_addr) => Some(transports::Addr::from(custom_addr)), +1381 _ => { +1382 warn!(?addr, "Unsupported TransportAddr"); +1383 None +1384 } +1385 }) +1386} +1387 +1388/// Returns the next item if `maybe_stream` is `Some`, or `None` otherwise. +1389async fn maybe_next<S: Stream + Unpin>(maybe_stream: Option<&mut S>) -> Option<Option<S::Item>> { +1390 match maybe_stream { +1391 None => None, +1392 Some(s) => Some(s.next().await), +1393 } +1394} 1395 -1396 fn v4(port: u16) -> transports::Addr { -1397 transports::Addr::Ip(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port))) -1398 } +1396#[cfg(test)] +1397mod tests { +1398 use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6}; 1399 -1400 fn v6(port: u16) -> transports::Addr { -1401 transports::Addr::Ip(SocketAddr::V6(SocketAddrV6::new( -1402 Ipv6Addr::LOCALHOST, -1403 port, -1404 0, -1405 0, -1406 ))) -1407 } -1408 -1409 fn relay(port: u16) -> transports::Addr { -1410 let url = format!("https://relay{port}.iroh.computer") -1411 .parse::<RelayUrl>() -1412 .unwrap(); -1413 transports::Addr::Relay(url, EndpointId::from_bytes(&[0u8; 32]).unwrap()) +1400 use super::*; +1401 use crate::socket::transports::TransportType; +1402 +1403 fn v4(port: u16) -> transports::Addr { +1404 transports::Addr::Ip(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port))) +1405 } +1406 +1407 fn v6(port: u16) -> transports::Addr { +1408 transports::Addr::Ip(SocketAddr::V6(SocketAddrV6::new( +1409 Ipv6Addr::LOCALHOST, +1410 port, +1411 0, +1412 0, +1413 ))) 1414 } 1415 -1416 fn psd(transport_type: TransportType, rtt_ms: u64) -> PathSelectionData { -1417 let rtt = Duration::from_millis(rtt_ms); -1418 let biased_rtt = rtt.as_nanos() as i128; -1419 PathSelectionData { -1420 transport_type, -1421 rtt, -1422 biased_rtt, -1423 } -1424 } -1425 -1426 fn psd_v6(transport_type: TransportType, rtt_ms: u64) -> PathSelectionData { -1427 let rtt = Duration::from_millis(rtt_ms); -1428 // IPv6 gets a bias advantage -1429 let biased_rtt = rtt.as_nanos() as i128 - transports::IPV6_RTT_ADVANTAGE.as_nanos() as i128; -1430 PathSelectionData { -1431 transport_type, -1432 rtt, -1433 biased_rtt, -1434 } -1435 } -1436 -1437 #[test] -1438 fn test_ipv6_wins_over_ipv4_within_bias() { -1439 let v4 = v4(1); -1440 let v6 = v6(1); -1441 // IPv6 should win over IPv4 when RTTs are the same -1442 let mut paths = FxHashMap::default(); -1443 paths.insert(&v4, psd(TransportType::Primary, 10)); -1444 paths.insert(&v6, psd_v6(TransportType::Primary, 10)); -1445 -1446 let result = select_best_path(paths, None); -1447 assert!(result.is_some()); -1448 let (addr, _) = result.unwrap(); -1449 assert!(matches!(addr, transports::Addr::Ip(SocketAddr::V6(_)))); -1450 -1451 // IPv6 should still win when it's slightly slower (within bias range) -1452 let mut paths = FxHashMap::default(); -1453 paths.insert(&v4, psd(TransportType::Primary, 10)); -1454 paths.insert(&v6, psd_v6(TransportType::Primary, 12)); // 2ms slower, but 3ms bias -1455 -1456 let result = select_best_path(paths, None); -1457 assert!(result.is_some()); -1458 let (addr, _) = result.unwrap(); -1459 assert!(matches!(addr, transports::Addr::Ip(SocketAddr::V6(_)))); -1460 -1461 // IPv4 should win when IPv6 is significantly slower -1462 let mut paths = FxHashMap::default(); -1463 paths.insert(&v4, psd(TransportType::Primary, 10)); -1464 paths.insert(&v6, psd_v6(TransportType::Primary, 20)); // 10ms slower, exceeds 3ms bias -1465 -1466 let result = select_best_path(paths, None); -1467 assert!(result.is_some()); -1468 let (addr, _) = result.unwrap(); -1469 assert!(matches!(addr, transports::Addr::Ip(SocketAddr::V4(_)))); -1470 } -1471 -1472 #[test] -1473 fn test_available_wins_over_backup_regardless_of_rtt() { -1474 let v4 = v4(1); -1475 let relay = relay(1); -1476 // Available path should win even with much higher RTT -1477 let mut paths = FxHashMap::default(); -1478 paths.insert(&v4, psd(TransportType::Primary, 100)); // High RTT but Available -1479 paths.insert(&relay, psd(TransportType::Backup, 10)); // Low RTT but Backup -1480 -1481 let result = select_best_path(paths, None); -1482 assert!(result.is_some()); -1483 let (addr, _) = result.unwrap(); -1484 assert!(addr.is_ip()); -1485 -1486 // Even more extreme: 1000ms Available vs 1ms Backup -1487 let mut paths = FxHashMap::default(); -1488 paths.insert(&v4, psd(TransportType::Primary, 1000)); -1489 paths.insert(&relay, psd(TransportType::Backup, 1)); -1490 -1491 let result = select_best_path(paths, None); -1492 assert!(result.is_some()); -1493 let (addr, _) = result.unwrap(); -1494 assert!(addr.is_ip()); -1495 } -1496 -1497 #[test] -1498 fn test_same_category_only_switches_with_significant_rtt_diff() { -1499 let v4_1 = v4(1); -1500 let v4_2 = v4(2); -1501 let current = v4(1); -1502 -1503 // Should NOT switch: new path is only slightly better (2ms < 5ms threshold) -1504 let mut paths = FxHashMap::default(); -1505 paths.insert(&v4_1, psd(TransportType::Primary, 20)); -1506 paths.insert(&v4_2, psd(TransportType::Primary, 18)); -1507 -1508 let result = select_best_path(paths, Some(&current)); -1509 assert!(result.is_none()); // Should keep current -1510 -1511 // Should NOT switch: new path is just under threshold (4ms < 5ms) -1512 let mut paths = FxHashMap::default(); -1513 paths.insert(&v4_1, psd(TransportType::Primary, 20)); -1514 paths.insert(&v4_2, psd(TransportType::Primary, 16)); -1515 -1516 let result = select_best_path(paths, Some(&current)); -1517 assert!(result.is_none()); // Should keep current -1518 -1519 // SHOULD switch: new path is exactly at threshold (5ms, condition is <=) -1520 let mut paths = FxHashMap::default(); -1521 paths.insert(&v4_1, psd(TransportType::Primary, 20)); -1522 paths.insert(&v4_2, psd(TransportType::Primary, 15)); -1523 -1524 let result = select_best_path(paths, Some(&current)); -1525 assert!(result.is_some()); -1526 let (addr, _) = result.unwrap(); -1527 assert_eq!(addr, v4(2)); -1528 -1529 // SHOULD switch: new path is significantly better (6ms > 5ms threshold) -1530 let mut paths = FxHashMap::default(); -1531 paths.insert(&v4_1, psd(TransportType::Primary, 20)); -1532 paths.insert(&v4_2, psd(TransportType::Primary, 14)); -1533 -1534 let result = select_best_path(paths, Some(&current)); -1535 assert!(result.is_some()); -1536 let (addr, _) = result.unwrap(); -1537 assert_eq!(addr, v4(2)); -1538 } -1539 -1540 #[test] -1541 fn test_no_current_path_selects_best() { -1542 let v4_1 = v4(1); -1543 let v4_2 = v4(2); -1544 let mut paths = FxHashMap::default(); -1545 paths.insert(&v4_1, psd(TransportType::Primary, 20)); -1546 paths.insert(&v4_2, psd(TransportType::Primary, 10)); -1547 -1548 let result = select_best_path(paths, None); -1549 assert!(result.is_some()); -1550 let (addr, _) = result.unwrap(); -1551 assert_eq!(addr, v4(2)); // Lower RTT wins -1552 } -1553 -1554 #[test] -1555 fn test_empty_paths_returns_none() { -1556 let paths: FxHashMap<&transports::Addr, PathSelectionData> = FxHashMap::default(); -1557 let result = select_best_path(paths, None); -1558 assert!(result.is_none()); -1559 -1560 let paths: FxHashMap<&transports::Addr, PathSelectionData> = FxHashMap::default(); -1561 let result = select_best_path(paths, Some(&v4(1))); -1562 assert!(result.is_none()); -1563 } -1564} \ No newline at end of file +1416 fn relay(port: u16) -> transports::Addr { +1417 let url = format!("https://relay{port}.iroh.computer") +1418 .parse::<RelayUrl>() +1419 .unwrap(); +1420 transports::Addr::Relay(url, EndpointId::from_bytes(&[0u8; 32]).unwrap()) +1421 } +1422 +1423 fn psd(transport_type: TransportType, rtt_ms: u64) -> PathSelectionData { +1424 let rtt = Duration::from_millis(rtt_ms); +1425 let biased_rtt = rtt.as_nanos() as i128; +1426 PathSelectionData { +1427 transport_type, +1428 rtt, +1429 biased_rtt, +1430 } +1431 } +1432 +1433 fn psd_v6(transport_type: TransportType, rtt_ms: u64) -> PathSelectionData { +1434 let rtt = Duration::from_millis(rtt_ms); +1435 // IPv6 gets a bias advantage +1436 let biased_rtt = rtt.as_nanos() as i128 - transports::IPV6_RTT_ADVANTAGE.as_nanos() as i128; +1437 PathSelectionData { +1438 transport_type, +1439 rtt, +1440 biased_rtt, +1441 } +1442 } +1443 +1444 #[test] +1445 fn test_ipv6_wins_over_ipv4_within_bias() { +1446 let v4 = v4(1); +1447 let v6 = v6(1); +1448 // IPv6 should win over IPv4 when RTTs are the same +1449 let mut paths = FxHashMap::default(); +1450 paths.insert(&v4, psd(TransportType::Primary, 10)); +1451 paths.insert(&v6, psd_v6(TransportType::Primary, 10)); +1452 +1453 let result = select_best_path(paths, None); +1454 assert!(result.is_some()); +1455 let (addr, _) = result.unwrap(); +1456 assert!(matches!(addr, transports::Addr::Ip(SocketAddr::V6(_)))); +1457 +1458 // IPv6 should still win when it's slightly slower (within bias range) +1459 let mut paths = FxHashMap::default(); +1460 paths.insert(&v4, psd(TransportType::Primary, 10)); +1461 paths.insert(&v6, psd_v6(TransportType::Primary, 12)); // 2ms slower, but 3ms bias +1462 +1463 let result = select_best_path(paths, None); +1464 assert!(result.is_some()); +1465 let (addr, _) = result.unwrap(); +1466 assert!(matches!(addr, transports::Addr::Ip(SocketAddr::V6(_)))); +1467 +1468 // IPv4 should win when IPv6 is significantly slower +1469 let mut paths = FxHashMap::default(); +1470 paths.insert(&v4, psd(TransportType::Primary, 10)); +1471 paths.insert(&v6, psd_v6(TransportType::Primary, 20)); // 10ms slower, exceeds 3ms bias +1472 +1473 let result = select_best_path(paths, None); +1474 assert!(result.is_some()); +1475 let (addr, _) = result.unwrap(); +1476 assert!(matches!(addr, transports::Addr::Ip(SocketAddr::V4(_)))); +1477 } +1478 +1479 #[test] +1480 fn test_available_wins_over_backup_regardless_of_rtt() { +1481 let v4 = v4(1); +1482 let relay = relay(1); +1483 // Available path should win even with much higher RTT +1484 let mut paths = FxHashMap::default(); +1485 paths.insert(&v4, psd(TransportType::Primary, 100)); // High RTT but Available +1486 paths.insert(&relay, psd(TransportType::Backup, 10)); // Low RTT but Backup +1487 +1488 let result = select_best_path(paths, None); +1489 assert!(result.is_some()); +1490 let (addr, _) = result.unwrap(); +1491 assert!(addr.is_ip()); +1492 +1493 // Even more extreme: 1000ms Available vs 1ms Backup +1494 let mut paths = FxHashMap::default(); +1495 paths.insert(&v4, psd(TransportType::Primary, 1000)); +1496 paths.insert(&relay, psd(TransportType::Backup, 1)); +1497 +1498 let result = select_best_path(paths, None); +1499 assert!(result.is_some()); +1500 let (addr, _) = result.unwrap(); +1501 assert!(addr.is_ip()); +1502 } +1503 +1504 #[test] +1505 fn test_same_category_only_switches_with_significant_rtt_diff() { +1506 let v4_1 = v4(1); +1507 let v4_2 = v4(2); +1508 let current = v4(1); +1509 +1510 // Should NOT switch: new path is only slightly better (2ms < 5ms threshold) +1511 let mut paths = FxHashMap::default(); +1512 paths.insert(&v4_1, psd(TransportType::Primary, 20)); +1513 paths.insert(&v4_2, psd(TransportType::Primary, 18)); +1514 +1515 let result = select_best_path(paths, Some(&current)); +1516 assert!(result.is_none()); // Should keep current +1517 +1518 // Should NOT switch: new path is just under threshold (4ms < 5ms) +1519 let mut paths = FxHashMap::default(); +1520 paths.insert(&v4_1, psd(TransportType::Primary, 20)); +1521 paths.insert(&v4_2, psd(TransportType::Primary, 16)); +1522 +1523 let result = select_best_path(paths, Some(&current)); +1524 assert!(result.is_none()); // Should keep current +1525 +1526 // SHOULD switch: new path is exactly at threshold (5ms, condition is <=) +1527 let mut paths = FxHashMap::default(); +1528 paths.insert(&v4_1, psd(TransportType::Primary, 20)); +1529 paths.insert(&v4_2, psd(TransportType::Primary, 15)); +1530 +1531 let result = select_best_path(paths, Some(&current)); +1532 assert!(result.is_some()); +1533 let (addr, _) = result.unwrap(); +1534 assert_eq!(addr, v4(2)); +1535 +1536 // SHOULD switch: new path is significantly better (6ms > 5ms threshold) +1537 let mut paths = FxHashMap::default(); +1538 paths.insert(&v4_1, psd(TransportType::Primary, 20)); +1539 paths.insert(&v4_2, psd(TransportType::Primary, 14)); +1540 +1541 let result = select_best_path(paths, Some(&current)); +1542 assert!(result.is_some()); +1543 let (addr, _) = result.unwrap(); +1544 assert_eq!(addr, v4(2)); +1545 } +1546 +1547 #[test] +1548 fn test_no_current_path_selects_best() { +1549 let v4_1 = v4(1); +1550 let v4_2 = v4(2); +1551 let mut paths = FxHashMap::default(); +1552 paths.insert(&v4_1, psd(TransportType::Primary, 20)); +1553 paths.insert(&v4_2, psd(TransportType::Primary, 10)); +1554 +1555 let result = select_best_path(paths, None); +1556 assert!(result.is_some()); +1557 let (addr, _) = result.unwrap(); +1558 assert_eq!(addr, v4(2)); // Lower RTT wins +1559 } +1560 +1561 #[test] +1562 fn test_empty_paths_returns_none() { +1563 let paths: FxHashMap<&transports::Addr, PathSelectionData> = FxHashMap::default(); +1564 let result = select_best_path(paths, None); +1565 assert!(result.is_none()); +1566 +1567 let paths: FxHashMap<&transports::Addr, PathSelectionData> = FxHashMap::default(); +1568 let result = select_best_path(paths, Some(&v4(1))); +1569 assert!(result.is_none()); +1570 } +1571} \ No newline at end of file diff --git a/pr/4271/docs/src/iroh/socket/remote_map/remote_state/path_state.rs.html b/pr/4271/docs/src/iroh/socket/remote_map/remote_state/path_state.rs.html index ead9075696..cc39dead64 100644 --- a/pr/4271/docs/src/iroh/socket/remote_map/remote_state/path_state.rs.html +++ b/pr/4271/docs/src/iroh/socket/remote_map/remote_state/path_state.rs.html @@ -167,8 +167,8 @@ 167 } 168 169 /// Returns `true` if there are any queued resolve requests from [`Self::resolve_remote`]. -170 pub(super) fn has_pending_resolve_requests(&self) -> bool { -171 !self.pending_resolve_requests.is_empty() +170 pub(super) fn resolve_requests_is_empty(&self) -> bool { +171 self.pending_resolve_requests.is_empty() 172 } 173 174 /// Notifies that a Address Lookup run has finished.