diff --git a/pr/3775/docs/iroh/endpoint/struct.PathInfo.html b/pr/3775/docs/iroh/endpoint/struct.PathInfo.html index 3c9a3060d6..c08df8a992 100644 --- a/pr/3775/docs/iroh/endpoint/struct.PathInfo.html +++ b/pr/3775/docs/iroh/endpoint/struct.PathInfo.html @@ -1,12 +1,12 @@ -PathInfo in iroh::endpoint - Rust

PathInfo

Struct PathInfo 

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

Information about a network path used by a Connection.

-

Implementations§

Source§

impl PathInfo

Source

pub fn remote_addr(&self) -> &TransportAddr

The remote transport address used by this network path.

-
Source

pub fn is_selected(&self) -> bool

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

-
Source

pub fn is_ip(&self) -> bool

Whether this is an IP transport address.

-
Source

pub fn is_relay(&self) -> bool

Whether this is a transport address via a relay server.

-
Source

pub fn stats(&self) -> PathStats

Returns stats for this transmission path.

-
Source

pub fn rtt(&self) -> Duration

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

-

Trait Implementations§

Source§

impl Clone for PathInfo

Source§

fn clone(&self) -> PathInfo

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for PathInfo

Source§

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

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

impl PartialEq for PathInfo

Source§

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

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

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

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

impl Eq for PathInfo

Auto Trait Implementations§

Blanket Implementations§

Source§

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

PathInfo

Struct PathInfo 

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

Information about a network path used by a Connection.

+

Implementations§

Source§

impl PathInfo

Source

pub fn remote_addr(&self) -> &TransportAddr

The remote transport address used by this network path.

+
Source

pub fn is_selected(&self) -> bool

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

+
Source

pub fn is_ip(&self) -> bool

Whether this is an IP transport address.

+
Source

pub fn is_relay(&self) -> bool

Whether this is a transport address via a relay server.

+
Source

pub fn stats(&self) -> PathStats

Returns stats for this transmission path.

+
Source

pub fn rtt(&self) -> Duration

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

+

Trait Implementations§

Source§

impl Clone for PathInfo

Source§

fn clone(&self) -> PathInfo

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for PathInfo

Source§

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

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

impl PartialEq for PathInfo

Source§

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

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

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

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

impl Eq for PathInfo

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

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

§

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

§

fn implicit( diff --git a/pr/3775/docs/iroh/endpoint/struct.PathInfoList.html b/pr/3775/docs/iroh/endpoint/struct.PathInfoList.html index dd7d9839ed..84c4be783b 100644 --- a/pr/3775/docs/iroh/endpoint/struct.PathInfoList.html +++ b/pr/3775/docs/iroh/endpoint/struct.PathInfoList.html @@ -1,11 +1,11 @@ -PathInfoList in iroh::endpoint - Rust

PathInfoList

Struct PathInfoList 

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

List of PathInfo for the network paths of a Connection.

+PathInfoList in iroh::endpoint - Rust

PathInfoList

Struct PathInfoList 

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

List of PathInfo for the network paths of a Connection.

This struct implements IntoIterator.

-

Implementations§

Source§

impl PathInfoList

Source

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

Returns an iterator over the path infos.

-
Source

pub fn is_empty(&self) -> bool

Returns true if the list is empty.

-
Source

pub fn len(&self) -> usize

Returns the number of paths.

-

Trait Implementations§

Source§

impl Clone for PathInfoList

Source§

fn clone(&self) -> PathInfoList

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for PathInfoList

Source§

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

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

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

Source§

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

The type of the elements being iterated over.
Source§

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

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

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl PartialEq for PathInfoList

Source§

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

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

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

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

impl Eq for PathInfoList

Source§

impl StructuralPartialEq for PathInfoList

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Implementations§

Source§

impl PathInfoList

Source

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

Returns an iterator over the path infos.

+
Source

pub fn is_empty(&self) -> bool

Returns true if the list is empty.

+
Source

pub fn len(&self) -> usize

Returns the number of paths.

+

Trait Implementations§

Source§

impl Clone for PathInfoList

Source§

fn clone(&self) -> PathInfoList

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for PathInfoList

Source§

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

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

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

Source§

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

The type of the elements being iterated over.
Source§

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

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

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl PartialEq for PathInfoList

Source§

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

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

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

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

impl Eq for PathInfoList

Source§

impl StructuralPartialEq for PathInfoList

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

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

§

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

§

fn implicit( diff --git a/pr/3775/docs/src/iroh/magicsock/remote_map/remote_state.rs.html b/pr/3775/docs/src/iroh/magicsock/remote_map/remote_state.rs.html index 83e39216fb..fab0f527ef 100644 --- a/pr/3775/docs/src/iroh/magicsock/remote_map/remote_state.rs.html +++ b/pr/3775/docs/src/iroh/magicsock/remote_map/remote_state.rs.html @@ -166,1362 +166,1367 @@ 166 paths: RemotePathState, 167 /// Information about the last holepunching attempt. 168 last_holepunch: Option<HolepunchAttempt>, -169 /// If we have any indication that we want to holepunch asap. -170 needs_holepunching: Watchable<bool>, -171 -172 /// The path we currently consider the preferred path to the remote endpoint. -173 /// -174 /// **We expect this path to work.** If we become aware this path is broken then it is -175 /// set back to `None`. Having a selected path does not mean we may not be able to get -176 /// a better path: e.g. when the selected path is a relay path we still need to trigger -177 /// holepunching regularly. -178 /// -179 /// We only select a path once the path is functional in Quinn. -180 selected_path: Watchable<Option<transports::Addr>>, -181 /// Time at which we should schedule the next holepunch attempt. -182 scheduled_holepunch: Option<Instant>, -183 /// When to next attempt opening paths in [`Self::pending_open_paths`]. -184 scheduled_open_path: Option<Instant>, -185 /// Paths which we still need to open. -186 /// -187 /// They failed to open because we did not have enough CIDs issued by the remote. -188 pending_open_paths: VecDeque<transports::Addr>, -189 -190 // Internal state - Discovery -191 // -192 /// Stream of discovery results, or always pending if discovery is not running. -193 discovery_stream: DiscoveryStream, -194} -195 -196impl RemoteStateActor { -197 #[allow(clippy::too_many_arguments)] -198 pub(super) fn new( -199 endpoint_id: EndpointId, -200 local_endpoint_id: EndpointId, -201 local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>, -202 relay_mapped_addrs: AddrMap<(RelayUrl, EndpointId), RelayMappedAddr>, -203 metrics: Arc<MagicsockMetrics>, -204 discovery: ConcurrentDiscovery, -205 ) -> Self { -206 Self { -207 endpoint_id, -208 local_endpoint_id, -209 metrics: metrics.clone(), -210 local_direct_addrs, -211 relay_mapped_addrs, -212 discovery, -213 connections: FxHashMap::default(), -214 connections_close: Default::default(), -215 path_events: Default::default(), -216 addr_events: Default::default(), -217 paths: RemotePathState::new(metrics), -218 last_holepunch: None, -219 needs_holepunching: Default::default(), -220 selected_path: Default::default(), -221 scheduled_holepunch: None, -222 scheduled_open_path: None, -223 pending_open_paths: VecDeque::new(), -224 discovery_stream: Either::Left(n0_future::stream::pending()), -225 } -226 } -227 -228 pub(super) fn start(self) -> RemoteStateHandle { -229 let (tx, rx) = guarded_channel(16); -230 let me = self.local_endpoint_id; -231 let endpoint_id = self.endpoint_id; -232 -233 // Ideally we'd use the endpoint span as parent. We'd have to plug that span into -234 // here somehow. Instead we have no parent and explicitly set the me attribute. If -235 // we don't explicitly set a span we get the spans from whatever call happens to -236 // first create the actor, which is often very confusing as it then keeps those -237 // spans for all logging of the actor. -238 let task = task::spawn(self.run(rx).instrument(info_span!( -239 parent: None, -240 "RemoteStateActor", -241 me = %me.fmt_short(), -242 remote = %endpoint_id.fmt_short(), -243 ))); -244 RemoteStateHandle { -245 sender: tx, -246 _task: AbortOnDropHandle::new(task), -247 } -248 } -249 -250 /// Runs the main loop of the actor. -251 /// -252 /// Note that the actor uses async handlers for tasks from the main loop. The actor is -253 /// not processing items from the inbox while waiting on any async calls. So some -254 /// discipline is needed to not turn pending for a long time. -255 async fn run(mut self, mut inbox: GuardedReceiver<RemoteStateMessage>) { -256 trace!("actor started"); -257 let idle_timeout = time::sleep(ACTOR_MAX_IDLE_TIMEOUT); -258 n0_future::pin!(idle_timeout); -259 let mut needs_holepunching_watcher = self.needs_holepunching.watch(); -260 -261 let check_connections = time::interval(CHECK_CONNECTIONS_INTERVAL); -262 n0_future::pin!(check_connections); -263 -264 loop { -265 let scheduled_path_open = match self.scheduled_open_path { -266 Some(when) => MaybeFuture::Some(time::sleep_until(when)), -267 None => MaybeFuture::None, -268 }; -269 n0_future::pin!(scheduled_path_open); -270 let scheduled_hp = match self.scheduled_holepunch { -271 Some(when) => MaybeFuture::Some(time::sleep_until(when)), -272 None => MaybeFuture::None, -273 }; -274 n0_future::pin!(scheduled_hp); -275 if !inbox.is_idle() || !self.connections.is_empty() { -276 idle_timeout -277 .as_mut() -278 .reset(Instant::now() + ACTOR_MAX_IDLE_TIMEOUT); -279 } -280 -281 tokio::select! { -282 biased; -283 msg = inbox.recv() => { -284 match msg { -285 Some(msg) => self.handle_message(msg).await, -286 None => break, -287 } -288 } -289 Some((id, evt)) = self.path_events.next() => { -290 self.handle_path_event(id, evt); +169 +170 /// The path we currently consider the preferred path to the remote endpoint. +171 /// +172 /// **We expect this path to work.** If we become aware this path is broken then it is +173 /// set back to `None`. Having a selected path does not mean we may not be able to get +174 /// a better path: e.g. when the selected path is a relay path we still need to trigger +175 /// holepunching regularly. +176 /// +177 /// We only select a path once the path is functional in Quinn. +178 selected_path: Watchable<Option<transports::Addr>>, +179 /// Time at which we should schedule the next holepunch attempt. +180 scheduled_holepunch: Option<Instant>, +181 /// When to next attempt opening paths in [`Self::pending_open_paths`]. +182 scheduled_open_path: Option<Instant>, +183 /// Paths which we still need to open. +184 /// +185 /// They failed to open because we did not have enough CIDs issued by the remote. +186 pending_open_paths: VecDeque<transports::Addr>, +187 +188 // Internal state - Discovery +189 // +190 /// Stream of discovery results, or always pending if discovery is not running. +191 discovery_stream: DiscoveryStream, +192} +193 +194impl RemoteStateActor { +195 #[allow(clippy::too_many_arguments)] +196 pub(super) fn new( +197 endpoint_id: EndpointId, +198 local_endpoint_id: EndpointId, +199 local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>, +200 relay_mapped_addrs: AddrMap<(RelayUrl, EndpointId), RelayMappedAddr>, +201 metrics: Arc<MagicsockMetrics>, +202 discovery: ConcurrentDiscovery, +203 ) -> Self { +204 Self { +205 endpoint_id, +206 local_endpoint_id, +207 metrics: metrics.clone(), +208 local_direct_addrs, +209 relay_mapped_addrs, +210 discovery, +211 connections: FxHashMap::default(), +212 connections_close: Default::default(), +213 path_events: Default::default(), +214 addr_events: Default::default(), +215 paths: RemotePathState::new(metrics), +216 last_holepunch: None, +217 selected_path: Default::default(), +218 scheduled_holepunch: None, +219 scheduled_open_path: None, +220 pending_open_paths: VecDeque::new(), +221 discovery_stream: Either::Left(n0_future::stream::pending()), +222 } +223 } +224 +225 pub(super) fn start(self) -> RemoteStateHandle { +226 let (tx, rx) = guarded_channel(16); +227 let me = self.local_endpoint_id; +228 let endpoint_id = self.endpoint_id; +229 +230 // Ideally we'd use the endpoint span as parent. We'd have to plug that span into +231 // here somehow. Instead we have no parent and explicitly set the me attribute. If +232 // we don't explicitly set a span we get the spans from whatever call happens to +233 // first create the actor, which is often very confusing as it then keeps those +234 // spans for all logging of the actor. +235 let task = task::spawn(self.run(rx).instrument(info_span!( +236 parent: None, +237 "RemoteStateActor", +238 me = %me.fmt_short(), +239 remote = %endpoint_id.fmt_short(), +240 ))); +241 RemoteStateHandle { +242 sender: tx, +243 _task: AbortOnDropHandle::new(task), +244 } +245 } +246 +247 /// Runs the main loop of the actor. +248 /// +249 /// Note that the actor uses async handlers for tasks from the main loop. The actor is +250 /// not processing items from the inbox while waiting on any async calls. So some +251 /// discipline is needed to not turn pending for a long time. +252 async fn run(mut self, mut inbox: GuardedReceiver<RemoteStateMessage>) { +253 trace!("actor started"); +254 let idle_timeout = time::sleep(ACTOR_MAX_IDLE_TIMEOUT); +255 n0_future::pin!(idle_timeout); +256 +257 let check_connections = time::interval(CHECK_CONNECTIONS_INTERVAL); +258 n0_future::pin!(check_connections); +259 +260 loop { +261 let scheduled_path_open = match self.scheduled_open_path { +262 Some(when) => MaybeFuture::Some(time::sleep_until(when)), +263 None => MaybeFuture::None, +264 }; +265 n0_future::pin!(scheduled_path_open); +266 let scheduled_hp = match self.scheduled_holepunch { +267 Some(when) => MaybeFuture::Some(time::sleep_until(when)), +268 None => MaybeFuture::None, +269 }; +270 n0_future::pin!(scheduled_hp); +271 if !inbox.is_idle() || !self.connections.is_empty() { +272 idle_timeout +273 .as_mut() +274 .reset(Instant::now() + ACTOR_MAX_IDLE_TIMEOUT); +275 } +276 +277 tokio::select! { +278 biased; +279 msg = inbox.recv() => { +280 match msg { +281 Some(msg) => self.handle_message(msg).await, +282 None => break, +283 } +284 } +285 Some((id, evt)) = self.path_events.next() => { +286 self.handle_path_event(id, evt); +287 } +288 Some((id, evt)) = self.addr_events.next() => { +289 trace!(?id, ?evt, "remote addrs updated, triggering holepunching"); +290 self.trigger_holepunching(); 291 } -292 Some((id, evt)) = self.addr_events.next() => { -293 trace!(?id, ?evt, "remote addrs updated, triggering holepunching"); -294 self.trigger_holepunching(); -295 } -296 Some(conn_id) = self.connections_close.next(), if !self.connections_close.is_empty() => { -297 self.handle_connection_close(conn_id); -298 } -299 res = self.local_direct_addrs.updated() => { -300 if let Err(n0_watcher::Disconnected) = res { -301 trace!("direct address watcher disconnected, shutting down"); -302 break; -303 } -304 self.local_addrs_updated(); -305 trace!("local addrs updated, triggering holepunching"); -306 self.trigger_holepunching(); -307 } -308 _ = &mut scheduled_path_open => { -309 trace!("triggering scheduled path_open"); -310 self.scheduled_open_path = None; -311 let mut addrs = std::mem::take(&mut self.pending_open_paths); -312 while let Some(addr) = addrs.pop_front() { -313 self.open_path(&addr); -314 } -315 } -316 _ = &mut scheduled_hp => { -317 trace!("triggering scheduled holepunching"); -318 self.scheduled_holepunch = None; -319 self.trigger_holepunching(); -320 } -321 item = self.discovery_stream.next() => { -322 self.handle_discovery_item(item); -323 } -324 need_hp = needs_holepunching_watcher.updated() => { -325 if matches!(need_hp, Ok(true)) { -326 self.trigger_holepunching(); -327 } -328 } -329 _ = check_connections.tick() => { -330 self.check_connections(); +292 Some(conn_id) = self.connections_close.next(), if !self.connections_close.is_empty() => { +293 self.handle_connection_close(conn_id); +294 } +295 res = self.local_direct_addrs.updated() => { +296 if let Err(n0_watcher::Disconnected) = res { +297 trace!("direct address watcher disconnected, shutting down"); +298 break; +299 } +300 self.local_addrs_updated(); +301 trace!("local addrs updated, triggering holepunching"); +302 self.trigger_holepunching(); +303 } +304 _ = &mut scheduled_path_open => { +305 trace!("triggering scheduled path_open"); +306 self.scheduled_open_path = None; +307 let mut addrs = std::mem::take(&mut self.pending_open_paths); +308 while let Some(addr) = addrs.pop_front() { +309 self.open_path(&addr); +310 } +311 } +312 _ = &mut scheduled_hp => { +313 trace!("triggering scheduled holepunching"); +314 self.scheduled_holepunch = None; +315 self.trigger_holepunching(); +316 } +317 item = self.discovery_stream.next() => { +318 self.handle_discovery_item(item); +319 } +320 _ = check_connections.tick() => { +321 self.check_connections(); +322 } +323 _ = &mut idle_timeout => { +324 if self.connections.is_empty() && inbox.close_if_idle() { +325 trace!("idle timeout expired and still idle: terminate actor"); +326 break; +327 } else { +328 // Seems like we weren't really idle, so we reset +329 idle_timeout.as_mut().reset(Instant::now() + ACTOR_MAX_IDLE_TIMEOUT); +330 } 331 } -332 _ = &mut idle_timeout => { -333 if self.connections.is_empty() && inbox.close_if_idle() { -334 trace!("idle timeout expired and still idle: terminate actor"); -335 break; -336 } else { -337 // Seems like we weren't really idle, so we reset -338 idle_timeout.as_mut().reset(Instant::now() + ACTOR_MAX_IDLE_TIMEOUT); -339 } -340 } -341 } -342 } -343 trace!("actor terminating"); -344 } -345 -346 /// Handles an actor message. -347 /// -348 /// Error returns are fatal and kill the actor. -349 #[instrument(skip(self))] -350 async fn handle_message(&mut self, msg: RemoteStateMessage) { -351 // trace!("handling message"); -352 match msg { -353 RemoteStateMessage::SendDatagram(sender, transmit) => { -354 self.handle_msg_send_datagram(sender, transmit).await; -355 } -356 RemoteStateMessage::AddConnection(handle, tx) => { -357 self.handle_msg_add_connection(handle, tx); -358 } -359 RemoteStateMessage::ResolveRemote(addrs, tx) => { -360 self.handle_msg_resolve_remote(addrs, tx); -361 } -362 RemoteStateMessage::RemoteInfo(tx) => { -363 let addrs = self.paths.to_remote_addrs(); -364 let info = RemoteInfo { -365 endpoint_id: self.endpoint_id, -366 addrs, -367 }; -368 tx.send(info).ok(); -369 } -370 } -371 } -372 -373 /// Handles regularly checking if any paths need hole punching currently -374 fn check_connections(&mut self) { -375 let mut is_goodenough = true; -376 for conn in self.connections.values() { -377 // If we have at least 1 non relay path, we consider the connection good enough for now -378 // TODO: evaluate other criteria, like current RTT etc -379 let is_conn_goodenough = conn.open_paths.iter().any(|(_, addr)| !addr.is_relay()); -380 is_goodenough &= is_conn_goodenough; -381 } -382 -383 if !is_goodenough { -384 debug!("connections are not good enough, noting holepunch"); -385 self.trigger_holepunching(); -386 } -387 } -388 -389 /// Handles [`RemoteStateMessage::SendDatagram`]. -390 async fn handle_msg_send_datagram( -391 &mut self, -392 mut sender: TransportsSender, -393 transmit: OwnedTransmit, -394 ) { -395 // Sending datagrams might fail, e.g. because we don't have the right transports set -396 // up to handle sending this owned transmit to. -397 // After all, we try every single path that we know (relay URL, IP address), even -398 // though we might not have a relay transport or ip-capable transport set up. -399 // So these errors must not be fatal for this actor (or even this operation). -400 -401 if let Some(addr) = self.selected_path.get() { -402 trace!(?addr, "sending datagram to selected path"); -403 -404 if let Err(err) = send_datagram(&mut sender, addr.clone(), transmit).await { -405 debug!(?addr, "failed to send datagram on selected_path: {err:#}"); -406 } -407 } else { -408 trace!( -409 paths = ?self.paths.addrs().collect::<Vec<_>>(), -410 "sending datagram to all known paths", -411 ); -412 if self.paths.is_empty() { -413 warn!("Cannot send datagrams: No paths to remote endpoint known"); -414 } -415 -416 for addr in self.paths.addrs() { -417 // We never want to send to our local addresses. -418 // The local address set is updated in the main loop so we can use `peek` here. -419 if let transports::Addr::Ip(sockaddr) = addr -420 && self -421 .local_direct_addrs -422 .peek() -423 .iter() -424 .any(|a| a.addr == *sockaddr) -425 { -426 trace!(%sockaddr, "not sending datagram to our own address"); -427 } else if let Err(err) = -428 send_datagram(&mut sender, addr.clone(), transmit.clone()).await -429 { -430 debug!(?addr, "failed to send datagram: {err:#}"); -431 } -432 } -433 // This message is received *before* a connection is added. So we do -434 // not yet have a connection to holepunch. Instead we trigger -435 // holepunching when AddConnection is received. -436 } -437 } -438 -439 /// Handles [`RemoteStateMessage::AddConnection`]. -440 /// -441 /// Error returns are fatal and kill the actor. -442 fn handle_msg_add_connection( -443 &mut self, -444 handle: WeakConnectionHandle, -445 tx: oneshot::Sender<PathsWatcher>, -446 ) { -447 let pub_open_paths = Watchable::default(); -448 if let Some(conn) = handle.upgrade() { -449 self.metrics.num_conns_opened.inc(); -450 // Remove any conflicting stable_ids from the local state. -451 let conn_id = ConnId(conn.stable_id()); -452 self.connections.remove(&conn_id); +332 } +333 } +334 trace!("actor terminating"); +335 } +336 +337 /// Handles an actor message. +338 /// +339 /// Error returns are fatal and kill the actor. +340 #[instrument(skip(self))] +341 async fn handle_message(&mut self, msg: RemoteStateMessage) { +342 // trace!("handling message"); +343 match msg { +344 RemoteStateMessage::SendDatagram(sender, transmit) => { +345 self.handle_msg_send_datagram(sender, transmit).await; +346 } +347 RemoteStateMessage::AddConnection(handle, tx) => { +348 self.handle_msg_add_connection(handle, tx); +349 } +350 RemoteStateMessage::ResolveRemote(addrs, tx) => { +351 self.handle_msg_resolve_remote(addrs, tx); +352 } +353 RemoteStateMessage::RemoteInfo(tx) => { +354 let addrs = self.paths.to_remote_addrs(); +355 let info = RemoteInfo { +356 endpoint_id: self.endpoint_id, +357 addrs, +358 }; +359 tx.send(info).ok(); +360 } +361 } +362 } +363 +364 /// Handles regularly checking if any paths need hole punching currently +365 fn check_connections(&mut self) { +366 let mut is_goodenough = true; +367 for conn in self.connections.values() { +368 // If we have at least 1 non relay path, we consider the connection good enough for now +369 // TODO: evaluate other criteria, like current RTT etc +370 let is_conn_goodenough = conn.open_paths.iter().any(|(_, addr)| !addr.is_relay()); +371 is_goodenough &= is_conn_goodenough; +372 } +373 +374 if !is_goodenough { +375 debug!("connections are not good enough, noting holepunch"); +376 self.trigger_holepunching(); +377 } +378 } +379 +380 /// Handles [`RemoteStateMessage::SendDatagram`]. +381 async fn handle_msg_send_datagram( +382 &mut self, +383 mut sender: TransportsSender, +384 transmit: OwnedTransmit, +385 ) { +386 // Sending datagrams might fail, e.g. because we don't have the right transports set +387 // up to handle sending this owned transmit to. +388 // After all, we try every single path that we know (relay URL, IP address), even +389 // though we might not have a relay transport or ip-capable transport set up. +390 // So these errors must not be fatal for this actor (or even this operation). +391 +392 if let Some(addr) = self.selected_path.get() { +393 trace!(?addr, "sending datagram to selected path"); +394 +395 if let Err(err) = send_datagram(&mut sender, addr.clone(), transmit).await { +396 debug!(?addr, "failed to send datagram on selected_path: {err:#}"); +397 } +398 } else { +399 trace!( +400 paths = ?self.paths.addrs().collect::<Vec<_>>(), +401 "sending datagram to all known paths", +402 ); +403 if self.paths.is_empty() { +404 warn!("Cannot send datagrams: No paths to remote endpoint known"); +405 } +406 +407 for addr in self.paths.addrs() { +408 // We never want to send to our local addresses. +409 // The local address set is updated in the main loop so we can use `peek` here. +410 if let transports::Addr::Ip(sockaddr) = addr +411 && self +412 .local_direct_addrs +413 .peek() +414 .iter() +415 .any(|a| a.addr == *sockaddr) +416 { +417 trace!(%sockaddr, "not sending datagram to our own address"); +418 } else if let Err(err) = +419 send_datagram(&mut sender, addr.clone(), transmit.clone()).await +420 { +421 debug!(?addr, "failed to send datagram: {err:#}"); +422 } +423 } +424 // This message is received *before* a connection is added. So we do +425 // not yet have a connection to holepunch. Instead we trigger +426 // holepunching when AddConnection is received. +427 } +428 } +429 +430 /// Handles [`RemoteStateMessage::AddConnection`]. +431 /// +432 /// Error returns are fatal and kill the actor. +433 fn handle_msg_add_connection( +434 &mut self, +435 handle: WeakConnectionHandle, +436 tx: oneshot::Sender<PathsWatcher>, +437 ) { +438 let pub_open_paths = Watchable::default(); +439 if let Some(conn) = handle.upgrade() { +440 self.metrics.num_conns_opened.inc(); +441 // Remove any conflicting stable_ids from the local state. +442 let conn_id = ConnId(conn.stable_id()); +443 self.connections.remove(&conn_id); +444 +445 // Hook up paths, NAT addresses and connection closed event streams. +446 self.path_events.push(Box::pin( +447 BroadcastStream::new(conn.path_events()).map(move |evt| (conn_id, evt)), +448 )); +449 self.addr_events.push(Box::pin( +450 BroadcastStream::new(conn.nat_traversal_updates()).map(move |evt| (conn_id, evt)), +451 )); +452 self.connections_close.push(OnClosed::new(&conn)); 453 -454 // Hook up paths, NAT addresses and connection closed event streams. -455 self.path_events.push(Box::pin( -456 BroadcastStream::new(conn.path_events()).map(move |evt| (conn_id, evt)), -457 )); -458 self.addr_events.push(Box::pin( -459 BroadcastStream::new(conn.nat_traversal_updates()).map(move |evt| (conn_id, evt)), -460 )); -461 self.connections_close.push(OnClosed::new(&conn)); +454 // Add local addrs to the connection +455 let local_addrs = self +456 .local_direct_addrs +457 .get() +458 .iter() +459 .map(|d| d.addr) +460 .collect::<BTreeSet<_>>(); +461 Self::set_local_addrs(&conn, &local_addrs); 462 -463 // Add local addrs to the connection -464 let local_addrs = self -465 .local_direct_addrs -466 .get() -467 .iter() -468 .map(|d| d.addr) -469 .collect::<BTreeSet<_>>(); -470 Self::set_local_addrs(&conn, &local_addrs); -471 -472 // Store the connection -473 let conn_state = self -474 .connections -475 .entry(conn_id) -476 .insert_entry(ConnectionState { -477 handle: handle.clone(), -478 pub_open_paths: pub_open_paths.clone(), -479 paths: Default::default(), -480 open_paths: Default::default(), -481 path_ids: Default::default(), -482 }) -483 .into_mut(); -484 -485 // Store PathId(0), set path_status and select best path, check if holepunching -486 // is needed. -487 if let Some(path) = conn.path(PathId::ZERO) -488 && let Ok(socketaddr) = path.remote_address() -489 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr) -490 { -491 trace!(?path_remote, "added new connection"); -492 let path_remote_is_ip = path_remote.is_ip(); -493 let status = match path_remote { -494 transports::Addr::Ip(_) => PathStatus::Available, -495 transports::Addr::Relay(_, _) => PathStatus::Backup, -496 }; -497 path.set_status(status).ok(); -498 conn_state.add_open_path(path_remote.clone(), PathId::ZERO); -499 self.paths -500 .insert_open_path(path_remote.clone(), Source::Connection { _0: Private }); -501 self.select_path(); -502 -503 if path_remote_is_ip { -504 // We may have raced this with a relay address. Try and add any -505 // relay addresses we have back. -506 let relays = self -507 .paths -508 .addrs() -509 .filter(|a| a.is_relay()) -510 .cloned() -511 .collect::<Vec<_>>(); -512 for remote in relays { -513 self.open_path(&remote); -514 } -515 } -516 } -517 self.trigger_holepunching(); -518 } -519 tx.send(PathsWatcher::new( -520 pub_open_paths.watch(), -521 self.selected_path.watch(), -522 handle, -523 )) -524 .ok(); -525 } -526 -527 /// Handles [`RemoteStateMessage::ResolveRemote`]. -528 fn handle_msg_resolve_remote( -529 &mut self, -530 addrs: BTreeSet<TransportAddr>, -531 tx: oneshot::Sender<Result<(), DiscoveryError>>, -532 ) { -533 let addrs = to_transports_addr(self.endpoint_id, addrs); -534 self.paths.insert_multiple(addrs, Source::App); -535 self.paths.resolve_remote(tx); -536 // Start discovery if we have no selected path. -537 self.trigger_discovery(); -538 } -539 -540 fn handle_connection_close(&mut self, conn_id: ConnId) { -541 if self.connections.remove(&conn_id).is_some() { -542 self.metrics.num_conns_closed.inc(); -543 } -544 if self.connections.is_empty() { -545 trace!("last connection closed - clearing selected_path"); -546 self.selected_path.set(None).ok(); -547 } -548 } -549 -550 fn handle_discovery_item(&mut self, item: Option<Result<DiscoveryItem, DiscoveryError>>) { -551 match item { -552 None => { -553 self.discovery_stream = Either::Left(n0_future::stream::pending()); -554 self.paths.discovery_finished(Ok(())); -555 } -556 Some(Err(err)) => { -557 warn!("Discovery failed: {err:#}"); -558 self.discovery_stream = Either::Left(n0_future::stream::pending()); -559 self.paths.discovery_finished(Err(err)); -560 } -561 Some(Ok(item)) => { -562 if item.endpoint_id() != self.endpoint_id { -563 warn!(?item, "Discovery emitted item for wrong remote endpoint"); -564 } else { -565 let source = Source::Discovery { -566 name: item.provenance().to_string(), -567 }; -568 let addrs = -569 to_transports_addr(self.endpoint_id, item.into_endpoint_addr().addrs); -570 self.paths.insert_multiple(addrs, source); -571 } -572 } +463 // Store the connection +464 let conn_state = self +465 .connections +466 .entry(conn_id) +467 .insert_entry(ConnectionState { +468 handle: handle.clone(), +469 pub_open_paths: pub_open_paths.clone(), +470 paths: Default::default(), +471 open_paths: Default::default(), +472 path_ids: Default::default(), +473 }) +474 .into_mut(); +475 +476 // Store PathId(0), set path_status and select best path, check if holepunching +477 // is needed. +478 if let Some(path) = conn.path(PathId::ZERO) +479 && let Ok(socketaddr) = path.remote_address() +480 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr) +481 { +482 trace!(?path_remote, "added new connection"); +483 let path_remote_is_ip = path_remote.is_ip(); +484 let status = match path_remote { +485 transports::Addr::Ip(_) => PathStatus::Available, +486 transports::Addr::Relay(_, _) => PathStatus::Backup, +487 }; +488 path.set_status(status).ok(); +489 conn_state.add_open_path(path_remote.clone(), PathId::ZERO); +490 self.paths +491 .insert_open_path(path_remote.clone(), Source::Connection { _0: Private }); +492 self.select_path(); +493 +494 if path_remote_is_ip { +495 // We may have raced this with a relay address. Try and add any +496 // relay addresses we have back. +497 let relays = self +498 .paths +499 .addrs() +500 .filter(|a| a.is_relay()) +501 .cloned() +502 .collect::<Vec<_>>(); +503 for remote in relays { +504 self.open_path(&remote); +505 } +506 } +507 } +508 self.trigger_holepunching(); +509 } +510 tx.send(PathsWatcher::new( +511 pub_open_paths.watch(), +512 self.selected_path.watch(), +513 handle, +514 )) +515 .ok(); +516 } +517 +518 /// Handles [`RemoteStateMessage::ResolveRemote`]. +519 fn handle_msg_resolve_remote( +520 &mut self, +521 addrs: BTreeSet<TransportAddr>, +522 tx: oneshot::Sender<Result<(), DiscoveryError>>, +523 ) { +524 let addrs = to_transports_addr(self.endpoint_id, addrs); +525 self.paths.insert_multiple(addrs, Source::App); +526 self.paths.resolve_remote(tx); +527 // Start discovery if we have no selected path. +528 self.trigger_discovery(); +529 } +530 +531 fn handle_connection_close(&mut self, conn_id: ConnId) { +532 if self.connections.remove(&conn_id).is_some() { +533 self.metrics.num_conns_closed.inc(); +534 } +535 if self.connections.is_empty() { +536 trace!("last connection closed - clearing selected_path"); +537 self.selected_path.set(None).ok(); +538 } +539 } +540 +541 fn handle_discovery_item(&mut self, item: Option<Result<DiscoveryItem, DiscoveryError>>) { +542 match item { +543 None => { +544 self.discovery_stream = Either::Left(n0_future::stream::pending()); +545 self.paths.discovery_finished(Ok(())); +546 } +547 Some(Err(err)) => { +548 warn!("Discovery failed: {err:#}"); +549 self.discovery_stream = Either::Left(n0_future::stream::pending()); +550 self.paths.discovery_finished(Err(err)); +551 } +552 Some(Ok(item)) => { +553 if item.endpoint_id() != self.endpoint_id { +554 warn!(?item, "Discovery emitted item for wrong remote endpoint"); +555 } else { +556 let source = Source::Discovery { +557 name: item.provenance().to_string(), +558 }; +559 let addrs = +560 to_transports_addr(self.endpoint_id, item.into_endpoint_addr().addrs); +561 self.paths.insert_multiple(addrs, source); +562 } +563 } +564 } +565 } +566 +567 /// Triggers discovery for the remote endpoint, if needed. +568 /// +569 /// Does not start discovery if we have a selected path or if discovery is currently running. +570 fn trigger_discovery(&mut self) { +571 if self.selected_path.get().is_some() || matches!(self.discovery_stream, Either::Right(_)) { +572 return; 573 } -574 } -575 -576 /// Triggers discovery for the remote endpoint, if needed. -577 /// -578 /// Does not start discovery if we have a selected path or if discovery is currently running. -579 fn trigger_discovery(&mut self) { -580 if self.selected_path.get().is_some() || matches!(self.discovery_stream, Either::Right(_)) { -581 return; -582 } -583 match self.discovery.resolve(self.endpoint_id) { -584 Some(stream) => self.discovery_stream = Either::Right(SyncStream::new(stream)), -585 None => self.paths.discovery_finished(Ok(())), -586 } -587 } +574 match self.discovery.resolve(self.endpoint_id) { +575 Some(stream) => self.discovery_stream = Either::Right(SyncStream::new(stream)), +576 None => self.paths.discovery_finished(Ok(())), +577 } +578 } +579 +580 /// Sets the current local addresses to QNT's state to all connections +581 fn local_addrs_updated(&mut self) { +582 let local_addrs = self +583 .local_direct_addrs +584 .get() +585 .iter() +586 .map(|d| d.addr) +587 .collect::<BTreeSet<_>>(); 588 -589 /// Sets the current local addresses to QNT's state to all connections -590 fn local_addrs_updated(&mut self) { -591 let local_addrs = self -592 .local_direct_addrs -593 .get() -594 .iter() -595 .map(|d| d.addr) -596 .collect::<BTreeSet<_>>(); -597 -598 for conn in self.connections.values().filter_map(|s| s.handle.upgrade()) { -599 Self::set_local_addrs(&conn, &local_addrs); -600 } -601 // todo: trace -602 } -603 -604 /// Sets the current local addresses to QNT's state -605 fn set_local_addrs(conn: &quinn::Connection, local_addrs: &BTreeSet<SocketAddr>) { -606 let quinn_local_addrs = match conn.get_local_nat_traversal_addresses() { -607 Ok(addrs) => BTreeSet::from_iter(addrs), -608 Err(err) => { -609 warn!("failed to get local nat candidates: {err:#}"); -610 return; -611 } -612 }; -613 for addr in local_addrs.difference(&quinn_local_addrs) { -614 if let Err(err) = conn.add_nat_traversal_address(*addr) { -615 warn!("failed adding local addr: {err:#}",); -616 } -617 } -618 for addr in quinn_local_addrs.difference(local_addrs) { -619 if let Err(err) = conn.remove_nat_traversal_address(*addr) { -620 warn!("failed removing local addr: {err:#}"); -621 } -622 } -623 trace!(?local_addrs, "updated local QNT addresses"); -624 } -625 -626 /// Triggers holepunching to the remote endpoint. -627 /// -628 /// This will manage the entire process of holepunching with the remote endpoint. -629 /// -630 /// - Holepunching happens on the Connection with the lowest [`ConnId`] which is a -631 /// client. -632 /// - Both endpoints may initiate holepunching if both have a client connection. -633 /// - Any opened paths are opened on all other connections without holepunching. -634 /// - If there are no changes in local or remote candidate addresses since the -635 /// last attempt **and** there was a recent attempt, a trigger_holepunching call -636 /// will be scheduled instead. -637 fn trigger_holepunching(&mut self) { -638 if self.connections.is_empty() { -639 trace!("not holepunching: no connections"); -640 return; -641 } -642 -643 let Some(conn) = self -644 .connections -645 .iter() -646 .filter_map(|(id, state)| state.handle.upgrade().map(|conn| (*id, conn))) -647 .filter(|(_, conn)| conn.side().is_client()) -648 .min_by_key(|(id, _)| *id) -649 .map(|(_, conn)| conn) -650 else { -651 trace!("not holepunching: no client connection"); -652 return; -653 }; -654 let remote_candidates = match conn.get_remote_nat_traversal_addresses() { -655 Ok(addrs) => BTreeSet::from_iter(addrs), -656 Err(err) => { -657 warn!("failed to get nat candidate addresses: {err:#}"); -658 return; -659 } -660 }; -661 let local_candidates: BTreeSet<SocketAddr> = self -662 .local_direct_addrs -663 .get() -664 .iter() -665 .map(|daddr| daddr.addr) -666 .collect(); -667 let new_candidates = self -668 .last_holepunch -669 .as_ref() -670 .map(|last_hp| { -671 // Addrs are allowed to disappear, but if there are new ones we need to -672 // holepunch again. -673 trace!( -674 ?last_hp, -675 ?local_candidates, -676 ?remote_candidates, -677 "candidates to holepunch?" -678 ); -679 !remote_candidates.is_subset(&last_hp.remote_candidates) -680 || !local_candidates.is_subset(&last_hp.local_candidates) -681 }) -682 .unwrap_or(true); -683 if !new_candidates { -684 if let Some(ref last_hp) = self.last_holepunch { -685 let next_hp = last_hp.when + HOLEPUNCH_ATTEMPTS_INTERVAL; -686 let now = Instant::now(); -687 if next_hp > now { -688 trace!(scheduled_in = ?(next_hp - now), "not holepunching: no new addresses"); -689 self.scheduled_holepunch = Some(next_hp); -690 return; -691 } -692 } -693 } -694 -695 self.do_holepunching(conn); -696 } -697 -698 /// Unconditionally perform holepunching. -699 #[instrument(skip_all)] -700 fn do_holepunching(&mut self, conn: quinn::Connection) { -701 self.metrics.nat_traversal.inc(); -702 let local_candidates = self -703 .local_direct_addrs -704 .get() -705 .iter() -706 .map(|daddr| daddr.addr) -707 .collect::<BTreeSet<_>>(); -708 -709 match conn.initiate_nat_traversal_round() { -710 Ok(remote_candidates) => { -711 let remote_candidates = remote_candidates -712 .iter() -713 .map(|addr| SocketAddr::new(addr.ip().to_canonical(), addr.port())) -714 .collect(); -715 event!( -716 target: "iroh::_events::qnt::init", -717 Level::DEBUG, -718 remote = %self.endpoint_id.fmt_short(), -719 ?local_candidates, -720 ?remote_candidates, -721 ); -722 self.last_holepunch = Some(HolepunchAttempt { -723 when: Instant::now(), -724 local_candidates, -725 remote_candidates, -726 }); -727 } -728 Err(err) => { -729 // TODO: distinguish between fatal and temporary errors -730 warn!("failed to initiate NAT traversal: {err:#}"); -731 self.needs_holepunching.set(true).ok(); -732 } -733 } -734 } -735 -736 /// Open the path on all connections. -737 /// -738 /// This goes through all the connections for which we are the client, and makes sure -739 /// the path exists, or opens it. -740 #[instrument(level = "warn", skip(self))] -741 fn open_path(&mut self, open_addr: &transports::Addr) { -742 let path_status = match open_addr { -743 transports::Addr::Ip(_) => PathStatus::Available, -744 transports::Addr::Relay(_, _) => PathStatus::Backup, -745 }; -746 let quic_addr = match &open_addr { -747 transports::Addr::Ip(socket_addr) => *socket_addr, -748 transports::Addr::Relay(relay_url, eid) => self -749 .relay_mapped_addrs -750 .get(&(relay_url.clone(), *eid)) -751 .private_socket_addr(), -752 }; -753 -754 for (conn_id, conn_state) in self.connections.iter_mut() { -755 if conn_state.path_ids.contains_key(open_addr) { -756 continue; -757 } -758 let Some(conn) = conn_state.handle.upgrade() else { -759 continue; -760 }; -761 if conn.side().is_server() { -762 continue; -763 } -764 let fut = conn.open_path_ensure(quic_addr, path_status); -765 match fut.path_id() { -766 Some(path_id) => { -767 trace!(?conn_id, ?path_id, "opening new path"); -768 conn_state.add_path(open_addr.clone(), path_id); -769 // We still need to ensure that the path status is set correctly, -770 // in case the path was opened by QNT, which opens all IP paths -771 // using PATH_STATUS_BACKUP. We need to switch the selected path -772 // to use PATH_STATUS_AVAILABLE though! -773 if let Some(path) = conn.path(path_id) { -774 if let Err(e) = path.set_status(path_status) { -775 warn!(?e, ?open_addr, ?path_status, "Setting path status failed"); -776 } -777 } -778 } -779 None => { -780 let ret = now_or_never(fut); -781 match ret { -782 Some(Err(PathError::RemoteCidsExhausted)) => { -783 self.scheduled_open_path = -784 Some(Instant::now() + Duration::from_millis(333)); -785 self.pending_open_paths.push_back(open_addr.clone()); -786 trace!(?open_addr, "scheduling open_path"); -787 } -788 _ => warn!(?ret, "Opening path failed"), -789 } -790 } -791 } -792 } -793 } -794 -795 #[instrument(skip(self))] -796 fn handle_path_event( -797 &mut self, -798 conn_id: ConnId, -799 event: Result<PathEvent, BroadcastStreamRecvError>, -800 ) { -801 let Ok(event) = event else { -802 warn!("missed a PathEvent, RemoteStateActor lagging"); -803 // TODO: Is it possible to recover using the sync APIs to figure out what the -804 // state of the connection and it's paths are? -805 return; -806 }; -807 let Some(conn_state) = self.connections.get_mut(&conn_id) else { -808 trace!("event for removed connection"); -809 return; -810 }; -811 let Some(conn) = conn_state.handle.upgrade() else { -812 trace!("event for closed connection"); -813 return; -814 }; -815 trace!("path event"); -816 match event { -817 PathEvent::Opened { id: path_id } => { -818 let Some(path) = conn.path(path_id) else { -819 trace!("path open event for unknown path"); -820 return; -821 }; -822 -823 if let Ok(socketaddr) = path.remote_address() -824 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr) -825 { -826 event!( -827 target: "iroh::_events::path::open", -828 Level::DEBUG, -829 remote = %self.endpoint_id.fmt_short(), -830 ?path_remote, -831 ?conn_id, -832 ?path_id, -833 ); -834 conn_state.add_open_path(path_remote.clone(), path_id); -835 self.paths -836 .insert_open_path(path_remote.clone(), Source::Connection { _0: Private }); -837 } -838 -839 self.select_path(); -840 } -841 PathEvent::Abandoned { id, path_stats } => { -842 trace!(?path_stats, "path abandoned"); -843 // This is the last event for this path. -844 if let Some(addr) = conn_state.remove_path(&id) { -845 self.paths.abandoned_path(&addr); -846 } -847 } -848 PathEvent::Closed { id, .. } | PathEvent::LocallyClosed { id, .. } => { -849 let Some(path_remote) = conn_state.paths.get(&id).cloned() else { -850 debug!("path not in path_id_map"); -851 return; -852 }; -853 event!( -854 target: "iroh::_events::path::closed", -855 Level::DEBUG, -856 remote = %self.endpoint_id.fmt_short(), -857 ?path_remote, -858 ?conn_id, -859 path_id = ?id, -860 ); -861 conn_state.remove_open_path(&id); -862 -863 // If one connection closes this path, close it on all connections. -864 for (conn_id, conn_state) in self.connections.iter_mut() { -865 let Some(path_id) = conn_state.path_ids.get(&path_remote) else { -866 continue; -867 }; -868 let Some(conn) = conn_state.handle.upgrade() else { -869 continue; -870 }; -871 if let Some(path) = conn.path(*path_id) { -872 trace!(?path_remote, ?conn_id, ?path_id, "closing path"); -873 if let Err(err) = path.close() { -874 trace!( -875 ?path_remote, -876 ?conn_id, -877 ?path_id, -878 "path close failed: {err:#}" -879 ); -880 } -881 } -882 } -883 -884 // If the remote closed our selected path, select a new one. -885 self.select_path(); -886 } -887 PathEvent::RemoteStatus { .. } | PathEvent::ObservedAddr { .. } => { -888 // Nothing to do for these events. -889 } -890 } -891 } -892 -893 /// Selects the path with the lowest RTT, prefers direct paths. -894 /// -895 /// If there are direct paths, this selects the direct path with the lowest RTT. If -896 /// there are only relay paths, the relay path with the lowest RTT is chosen. -897 /// -898 /// The selected path is added to any connections which do not yet have it. Any unused -899 /// direct paths are closed for all connections. -900 #[instrument(skip_all)] -901 fn select_path(&mut self) { -902 // Find the lowest RTT across all connections for each open path. The long way, so -903 // we get to log *all* RTTs. -904 let mut all_path_rtts: FxHashMap<transports::Addr, Vec<Duration>> = FxHashMap::default(); -905 for conn_state in self.connections.values() { -906 let Some(conn) = conn_state.handle.upgrade() else { -907 continue; -908 }; -909 for (path_id, addr) in conn_state.open_paths.iter() { -910 if let Some(stats) = conn.path_stats(*path_id) { -911 all_path_rtts -912 .entry(addr.clone()) -913 .or_default() -914 .push(stats.rtt); -915 } -916 } -917 } -918 trace!(?all_path_rtts, "dumping all path RTTs"); -919 let path_rtts: FxHashMap<transports::Addr, Duration> = all_path_rtts -920 .into_iter() -921 .filter_map(|(addr, rtts)| rtts.into_iter().min().map(|rtt| (addr, rtt))) -922 .collect(); -923 -924 // Find the fastest direct IPv4 path. -925 let direct_path_ipv4 = path_rtts -926 .iter() -927 .filter_map(|(addr, rtt)| { -928 if let transports::Addr::Ip(SocketAddr::V4(addr)) = *addr { -929 Some((addr, *rtt)) -930 } else { -931 None -932 } -933 }) -934 .min_by_key(|(_addr, rtt)| *rtt); -935 -936 // Find the fastest direct IPv6 path. -937 let direct_path_ipv6 = path_rtts -938 .iter() -939 .filter_map(|(addr, rtt)| { -940 if let transports::Addr::Ip(SocketAddr::V6(addr)) = *addr { -941 Some((addr, *rtt)) -942 } else { -943 None -944 } -945 }) -946 .min_by_key(|(_addr, rtt)| *rtt); -947 -948 // Find the fastest relay path. -949 let relay_path = path_rtts -950 .iter() -951 .filter(|(addr, _rtt)| addr.is_relay()) -952 .min_by_key(|(_addr, rtt)| *rtt) -953 .map(|(addr, rtt)| (addr.clone(), *rtt)); -954 -955 let current_path = self -956 .selected_path -957 .get() -958 .and_then(|addr| path_rtts.get(&addr).copied().map(|rtt| (addr, rtt))); -959 let selected_path = select_best_path( -960 current_path.clone(), -961 direct_path_ipv4, -962 direct_path_ipv6, -963 relay_path, -964 ); -965 -966 // Apply our new path -967 if let Some((addr, rtt)) = selected_path { -968 let prev = self.selected_path.set(Some(addr.clone())); -969 if prev.is_ok() { -970 event!( -971 target: "iroh::_events::path::selected", -972 Level::DEBUG, -973 remote = %self.endpoint_id.fmt_short(), -974 path_remote = ?addr, -975 ?rtt, -976 prev_remote = ?prev, -977 ); -978 } -979 self.open_path(&addr); -980 self.close_redundant_paths(&addr); -981 } else { -982 trace!(?current_path, "keeping current path"); -983 } -984 } -985 -986 /// Closes any direct paths not selected if we are the client. -987 /// -988 /// Makes sure not to close the last direct path. Relay paths are never closed -989 /// currently, because we only have one relay path at this time. -990 /// -991 /// Only the client closes paths, just like only the client opens paths. This is to -992 /// avoid the client and server selecting different paths and accidentally closing all -993 /// paths. -994 fn close_redundant_paths(&mut self, selected_path: &transports::Addr) { -995 debug_assert_eq!(self.selected_path.get().as_ref(), Some(selected_path),); -996 -997 for (conn_id, conn_state) in self.connections.iter() { -998 for (path_id, path_remote) in conn_state -999 .open_paths -1000 .iter() -1001 .filter(|(_, addr)| addr.is_ip()) -1002 .filter(|(_, addr)| *addr != selected_path) -1003 { -1004 if conn_state.open_paths.values().filter(|a| a.is_ip()).count() <= 1 { -1005 continue; // Do not close the last direct path. -1006 } -1007 if let Some(path) = conn_state -1008 .handle -1009 .upgrade() -1010 .filter(|conn| conn.side().is_client()) -1011 .and_then(|conn| conn.path(*path_id)) -1012 { -1013 trace!(?path_remote, ?conn_id, ?path_id, "closing direct path"); -1014 match path.close() { -1015 Err(quinn_proto::ClosePathError::LastOpenPath) => { -1016 error!("could not close last open path"); -1017 } -1018 Err(quinn_proto::ClosePathError::ClosedPath) => { -1019 // We already closed this. -1020 } -1021 Ok(_fut) => { -1022 // We will handle the event in Self::handle_path_events. -1023 } -1024 } -1025 } -1026 } -1027 } -1028 } -1029} -1030 -1031/// Returns `Some` if a new path should be selected, `None` if the `current_path` should -1032/// continued to be used. -1033fn select_best_path( -1034 current_path: Option<(transports::Addr, Duration)>, -1035 direct_path_ipv4: Option<(SocketAddrV4, Duration)>, -1036 direct_path_ipv6: Option<(SocketAddrV6, Duration)>, -1037 new_relay_path: Option<(transports::Addr, Duration)>, -1038) -> Option<(transports::Addr, Duration)> { -1039 // Determine the best new IP path. -1040 let best_ip_path = match (direct_path_ipv4, direct_path_ipv6) { -1041 (Some((addr_v4, rtt_v4)), Some((addr_v6, rtt_v6))) => { -1042 Some(select_v4_v6(addr_v4, rtt_v4, addr_v6, rtt_v6)) -1043 } -1044 (None, Some((addr_v6, rtt_v6))) => Some((addr_v6.into(), rtt_v6)), -1045 (Some((addr_v4, rtt_v4)), None) => Some((addr_v4.into(), rtt_v4)), -1046 (None, None) => None, -1047 }; -1048 let best_ip_path = best_ip_path.map(|(addr, rtt)| (transports::Addr::Ip(addr), rtt)); -1049 -1050 match current_path { -1051 None => { -1052 // If we currently have no path -1053 if best_ip_path.is_some() { -1054 // Use the best IP path -1055 best_ip_path -1056 } else { -1057 // Use the new relay path -1058 new_relay_path -1059 } -1060 } -1061 Some((transports::Addr::Relay(..), _)) => { -1062 // If we have a current path, but it is relay -1063 if best_ip_path.is_some() { -1064 // Use the best IP path -1065 best_ip_path -1066 } else { -1067 // Use the new relay path -1068 new_relay_path -1069 } -1070 } -1071 Some((transports::Addr::Ip(_), current_rtt)) => { -1072 match &best_ip_path { -1073 Some((_, new_rtt)) => { -1074 // Comparing available IP paths -1075 if current_rtt >= *new_rtt + RTT_SWITCHING_MIN_IP { -1076 // New IP path is faster -1077 best_ip_path -1078 } else { -1079 // New IP is not faster -1080 None -1081 } -1082 } -1083 None => { -1084 // No new IP path, don't switch away -1085 None -1086 } -1087 } -1088 } -1089 } -1090} -1091 -1092/// Compare two IP addrs v4 & v6 and selects the "best" one. -1093/// -1094/// This prefers IPv6 paths over IPv4 paths. -1095fn select_v4_v6( -1096 addr_v4: SocketAddrV4, -1097 rtt_v4: Duration, -1098 addr_v6: SocketAddrV6, -1099 rtt_v6: Duration, -1100) -> (SocketAddr, Duration) { -1101 if rtt_v6 <= rtt_v4 + IPV6_RTT_ADVANTAGE { -1102 (addr_v6.into(), rtt_v6) -1103 } else { -1104 (addr_v4.into(), rtt_v4) -1105 } -1106} -1107 -1108fn send_datagram<'a>( -1109 sender: &'a mut TransportsSender, -1110 dst: transports::Addr, -1111 owned_transmit: OwnedTransmit, -1112) -> impl Future<Output = n0_error::Result<()>> + 'a { -1113 std::future::poll_fn(move |cx| { -1114 let transmit = transports::Transmit { -1115 ecn: owned_transmit.ecn, -1116 contents: owned_transmit.contents.as_ref(), -1117 segment_size: owned_transmit.segment_size, -1118 }; -1119 -1120 Pin::new(&mut *sender) -1121 .poll_send(cx, &dst, None, &transmit) -1122 .map(|res| res.with_context(|_| format!("failed to send datagram to {dst:?}"))) -1123 }) -1124} -1125 -1126/// Messages to send to the [`RemoteStateActor`]. -1127#[derive(derive_more::Debug)] -1128pub(crate) enum RemoteStateMessage { -1129 /// Sends a datagram to all known paths. -1130 /// -1131 /// Used to send QUIC Initial packets. If there is no working direct path this will -1132 /// trigger holepunching. -1133 /// -1134 /// This is not acceptable to use on the normal send path, as it is an async send -1135 /// operation with a bunch more copying. So it should only be used for sending QUIC -1136 /// Initial packets. -1137 #[debug("SendDatagram(..)")] -1138 SendDatagram(TransportsSender, OwnedTransmit), -1139 /// Adds an active connection to this remote endpoint. -1140 /// -1141 /// The connection will now be managed by this actor. Holepunching will happen when -1142 /// needed, any new paths discovered via holepunching will be added. And closed paths -1143 /// will be removed etc. -1144 #[debug("AddConnection(..)")] -1145 AddConnection(WeakConnectionHandle, oneshot::Sender<PathsWatcher>), -1146 /// Asks if there is any possible path that could be used. -1147 /// -1148 /// This adds the provided transport addresses to the list of potential paths for this remote -1149 /// and starts discovery if needed. -1150 /// -1151 /// Returns `Ok` immediately if the provided address list is non-empy or we have are other known paths. -1152 /// Otherwise returns `Ok` once discovery produces a result, or the discovery error if discovery fails -1153 /// or produces no results, -1154 #[debug("ResolveRemote(..)")] -1155 ResolveRemote( -1156 BTreeSet<TransportAddr>, -1157 oneshot::Sender<Result<(), DiscoveryError>>, -1158 ), -1159 /// Returns information about the remote. -1160 /// -1161 /// This currently only includes a list of all known transport addresses for the remote. -1162 RemoteInfo(oneshot::Sender<RemoteInfo>), -1163} -1164 -1165/// A handle to a [`RemoteStateActor`]. -1166/// -1167/// Dropping this will stop the actor. The actor will also stop after an idle timeout -1168/// if it has no connections, an empty inbox, and no other senders than the one stored -1169/// in the endpoint map exist. -1170#[derive(Debug)] -1171pub(super) struct RemoteStateHandle { -1172 /// Sender for the channel into the [`RemoteStateActor`]. -1173 /// -1174 /// This is a [`GuardedSender`], from which we can get a sender but only if the receiver -1175 /// hasn't been closed. -1176 pub(super) sender: GuardedSender<RemoteStateMessage>, -1177 _task: AbortOnDropHandle<()>, -1178} -1179 -1180/// Information about a holepunch attempt. -1181/// -1182/// Addresses are always stored in canonical form. -1183#[derive(Debug)] -1184struct HolepunchAttempt { -1185 when: Instant, -1186 /// The set of local addresses which could take part in holepunching. -1187 /// -1188 /// This does not mean every address here participated in the holepunching. E.g. we -1189 /// could have tried only a sub-set of the addresses because a previous attempt already -1190 /// covered part of the range. -1191 /// -1192 /// We do not store this as a [`DirectAddr`] because this is checked for equality and we -1193 /// do not want to compare the sources of these addresses. -1194 local_candidates: BTreeSet<SocketAddr>, -1195 /// The set of remote addresses which could take part in holepunching. +589 for conn in self.connections.values().filter_map(|s| s.handle.upgrade()) { +590 Self::set_local_addrs(&conn, &local_addrs); +591 } +592 // todo: trace +593 } +594 +595 /// Sets the current local addresses to QNT's state +596 fn set_local_addrs(conn: &quinn::Connection, local_addrs: &BTreeSet<SocketAddr>) { +597 let quinn_local_addrs = match conn.get_local_nat_traversal_addresses() { +598 Ok(addrs) => BTreeSet::from_iter(addrs), +599 Err(err) => { +600 warn!("failed to get local nat candidates: {err:#}"); +601 return; +602 } +603 }; +604 for addr in local_addrs.difference(&quinn_local_addrs) { +605 if let Err(err) = conn.add_nat_traversal_address(*addr) { +606 warn!("failed adding local addr: {err:#}",); +607 } +608 } +609 for addr in quinn_local_addrs.difference(local_addrs) { +610 if let Err(err) = conn.remove_nat_traversal_address(*addr) { +611 warn!("failed removing local addr: {err:#}"); +612 } +613 } +614 trace!(?local_addrs, "updated local QNT addresses"); +615 } +616 +617 /// Triggers holepunching to the remote endpoint. +618 /// +619 /// This will manage the entire process of holepunching with the remote endpoint. +620 /// +621 /// - Holepunching happens on the Connection with the lowest [`ConnId`] which is a +622 /// client. +623 /// - Both endpoints may initiate holepunching if both have a client connection. +624 /// - Any opened paths are opened on all other connections without holepunching. +625 /// - If there are no changes in local or remote candidate addresses since the +626 /// last attempt **and** there was a recent attempt, a trigger_holepunching call +627 /// will be scheduled instead. +628 fn trigger_holepunching(&mut self) { +629 if self.connections.is_empty() { +630 trace!("not holepunching: no connections"); +631 return; +632 } +633 +634 let Some(conn) = self +635 .connections +636 .iter() +637 .filter_map(|(id, state)| state.handle.upgrade().map(|conn| (*id, conn))) +638 .filter(|(_, conn)| conn.side().is_client()) +639 .min_by_key(|(id, _)| *id) +640 .map(|(_, conn)| conn) +641 else { +642 trace!("not holepunching: no client connection"); +643 return; +644 }; +645 let remote_candidates = match conn.get_remote_nat_traversal_addresses() { +646 Ok(addrs) => BTreeSet::from_iter(addrs), +647 Err(err) => { +648 warn!("failed to get nat candidate addresses: {err:#}"); +649 return; +650 } +651 }; +652 let local_candidates: BTreeSet<SocketAddr> = self +653 .local_direct_addrs +654 .get() +655 .iter() +656 .map(|daddr| daddr.addr) +657 .collect(); +658 let new_candidates = self +659 .last_holepunch +660 .as_ref() +661 .map(|last_hp| { +662 // Addrs are allowed to disappear, but if there are new ones we need to +663 // holepunch again. +664 trace!( +665 ?last_hp, +666 ?local_candidates, +667 ?remote_candidates, +668 "candidates to holepunch?" +669 ); +670 !remote_candidates.is_subset(&last_hp.remote_candidates) +671 || !local_candidates.is_subset(&last_hp.local_candidates) +672 }) +673 .unwrap_or(true); +674 if !new_candidates { +675 if let Some(ref last_hp) = self.last_holepunch { +676 let next_hp = last_hp.when + HOLEPUNCH_ATTEMPTS_INTERVAL; +677 let now = Instant::now(); +678 if next_hp > now { +679 trace!(scheduled_in = ?(next_hp - now), "not holepunching: no new addresses"); +680 self.scheduled_holepunch = Some(next_hp); +681 return; +682 } +683 } +684 } +685 +686 self.do_holepunching(conn); +687 } +688 +689 /// Unconditionally perform holepunching. +690 #[instrument(skip_all)] +691 fn do_holepunching(&mut self, conn: quinn::Connection) { +692 self.metrics.nat_traversal.inc(); +693 let local_candidates = self +694 .local_direct_addrs +695 .get() +696 .iter() +697 .map(|daddr| daddr.addr) +698 .collect::<BTreeSet<_>>(); +699 +700 match conn.initiate_nat_traversal_round() { +701 Ok(remote_candidates) => { +702 let remote_candidates = remote_candidates +703 .iter() +704 .map(|addr| SocketAddr::new(addr.ip().to_canonical(), addr.port())) +705 .collect(); +706 event!( +707 target: "iroh::_events::qnt::init", +708 Level::DEBUG, +709 remote = %self.endpoint_id.fmt_short(), +710 ?local_candidates, +711 ?remote_candidates, +712 ); +713 self.last_holepunch = Some(HolepunchAttempt { +714 when: Instant::now(), +715 local_candidates, +716 remote_candidates, +717 }); +718 } +719 Err(err) => { +720 debug!("failed to initiate NAT traversal: {err:#}"); +721 use quinn_proto::iroh_hp::Error; +722 match err { +723 Error::Closed +724 | Error::TooManyAddresses +725 | Error::WrongConnectionSide +726 | Error::ExtensionNotNegotiated => { +727 // Fatal, no need to retry for now +728 } +729 Error::Multipath(_) | Error::NotEnoughAddresses => { +730 // Retry in a bit +731 let now = Instant::now(); +732 let next_hp = now + Duration::from_millis(100); +733 trace!(scheduled_in = ?(next_hp - now), "holepunching retry"); +734 self.scheduled_holepunch = Some(next_hp); +735 } +736 } +737 } +738 } +739 } +740 +741 /// Open the path on all connections. +742 /// +743 /// This goes through all the connections for which we are the client, and makes sure +744 /// the path exists, or opens it. +745 #[instrument(level = "warn", skip(self))] +746 fn open_path(&mut self, open_addr: &transports::Addr) { +747 let path_status = match open_addr { +748 transports::Addr::Ip(_) => PathStatus::Available, +749 transports::Addr::Relay(_, _) => PathStatus::Backup, +750 }; +751 let quic_addr = match &open_addr { +752 transports::Addr::Ip(socket_addr) => *socket_addr, +753 transports::Addr::Relay(relay_url, eid) => self +754 .relay_mapped_addrs +755 .get(&(relay_url.clone(), *eid)) +756 .private_socket_addr(), +757 }; +758 +759 for (conn_id, conn_state) in self.connections.iter_mut() { +760 if conn_state.path_ids.contains_key(open_addr) { +761 continue; +762 } +763 let Some(conn) = conn_state.handle.upgrade() else { +764 continue; +765 }; +766 if conn.side().is_server() { +767 continue; +768 } +769 let fut = conn.open_path_ensure(quic_addr, path_status); +770 match fut.path_id() { +771 Some(path_id) => { +772 trace!(?conn_id, ?path_id, "opening new path"); +773 conn_state.add_path(open_addr.clone(), path_id); +774 // We still need to ensure that the path status is set correctly, +775 // in case the path was opened by QNT, which opens all IP paths +776 // using PATH_STATUS_BACKUP. We need to switch the selected path +777 // to use PATH_STATUS_AVAILABLE though! +778 if let Some(path) = conn.path(path_id) { +779 if let Err(e) = path.set_status(path_status) { +780 warn!(?e, ?open_addr, ?path_status, "Setting path status failed"); +781 } +782 } +783 } +784 None => { +785 let ret = now_or_never(fut); +786 match ret { +787 Some(Err(PathError::RemoteCidsExhausted)) => { +788 self.scheduled_open_path = +789 Some(Instant::now() + Duration::from_millis(333)); +790 self.pending_open_paths.push_back(open_addr.clone()); +791 trace!(?open_addr, "scheduling open_path"); +792 } +793 _ => warn!(?ret, "Opening path failed"), +794 } +795 } +796 } +797 } +798 } +799 +800 #[instrument(skip(self))] +801 fn handle_path_event( +802 &mut self, +803 conn_id: ConnId, +804 event: Result<PathEvent, BroadcastStreamRecvError>, +805 ) { +806 let Ok(event) = event else { +807 warn!("missed a PathEvent, RemoteStateActor lagging"); +808 // TODO: Is it possible to recover using the sync APIs to figure out what the +809 // state of the connection and it's paths are? +810 return; +811 }; +812 let Some(conn_state) = self.connections.get_mut(&conn_id) else { +813 trace!("event for removed connection"); +814 return; +815 }; +816 let Some(conn) = conn_state.handle.upgrade() else { +817 trace!("event for closed connection"); +818 return; +819 }; +820 trace!("path event"); +821 match event { +822 PathEvent::Opened { id: path_id } => { +823 let Some(path) = conn.path(path_id) else { +824 trace!("path open event for unknown path"); +825 return; +826 }; +827 +828 if let Ok(socketaddr) = path.remote_address() +829 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr) +830 { +831 event!( +832 target: "iroh::_events::path::open", +833 Level::DEBUG, +834 remote = %self.endpoint_id.fmt_short(), +835 ?path_remote, +836 ?conn_id, +837 ?path_id, +838 ); +839 conn_state.add_open_path(path_remote.clone(), path_id); +840 self.paths +841 .insert_open_path(path_remote.clone(), Source::Connection { _0: Private }); +842 } +843 +844 self.select_path(); +845 } +846 PathEvent::Abandoned { id, path_stats } => { +847 trace!(?path_stats, "path abandoned"); +848 // This is the last event for this path. +849 if let Some(addr) = conn_state.remove_path(&id) { +850 self.paths.abandoned_path(&addr); +851 } +852 } +853 PathEvent::Closed { id, .. } | PathEvent::LocallyClosed { id, .. } => { +854 let Some(path_remote) = conn_state.paths.get(&id).cloned() else { +855 debug!("path not in path_id_map"); +856 return; +857 }; +858 event!( +859 target: "iroh::_events::path::closed", +860 Level::DEBUG, +861 remote = %self.endpoint_id.fmt_short(), +862 ?path_remote, +863 ?conn_id, +864 path_id = ?id, +865 ); +866 conn_state.remove_open_path(&id); +867 +868 // If one connection closes this path, close it on all connections. +869 for (conn_id, conn_state) in self.connections.iter_mut() { +870 let Some(path_id) = conn_state.path_ids.get(&path_remote) else { +871 continue; +872 }; +873 let Some(conn) = conn_state.handle.upgrade() else { +874 continue; +875 }; +876 if let Some(path) = conn.path(*path_id) { +877 trace!(?path_remote, ?conn_id, ?path_id, "closing path"); +878 if let Err(err) = path.close() { +879 trace!( +880 ?path_remote, +881 ?conn_id, +882 ?path_id, +883 "path close failed: {err:#}" +884 ); +885 } +886 } +887 } +888 +889 // If the remote closed our selected path, select a new one. +890 self.select_path(); +891 } +892 PathEvent::RemoteStatus { .. } | PathEvent::ObservedAddr { .. } => { +893 // Nothing to do for these events. +894 } +895 } +896 } +897 +898 /// Selects the path with the lowest RTT, prefers direct paths. +899 /// +900 /// If there are direct paths, this selects the direct path with the lowest RTT. If +901 /// there are only relay paths, the relay path with the lowest RTT is chosen. +902 /// +903 /// The selected path is added to any connections which do not yet have it. Any unused +904 /// direct paths are closed for all connections. +905 #[instrument(skip_all)] +906 fn select_path(&mut self) { +907 // Find the lowest RTT across all connections for each open path. The long way, so +908 // we get to log *all* RTTs. +909 let mut all_path_rtts: FxHashMap<transports::Addr, Vec<Duration>> = FxHashMap::default(); +910 for conn_state in self.connections.values() { +911 let Some(conn) = conn_state.handle.upgrade() else { +912 continue; +913 }; +914 for (path_id, addr) in conn_state.open_paths.iter() { +915 if let Some(stats) = conn.path_stats(*path_id) { +916 all_path_rtts +917 .entry(addr.clone()) +918 .or_default() +919 .push(stats.rtt); +920 } +921 } +922 } +923 trace!(?all_path_rtts, "dumping all path RTTs"); +924 let path_rtts: FxHashMap<transports::Addr, Duration> = all_path_rtts +925 .into_iter() +926 .filter_map(|(addr, rtts)| rtts.into_iter().min().map(|rtt| (addr, rtt))) +927 .collect(); +928 +929 // Find the fastest direct IPv4 path. +930 let direct_path_ipv4 = path_rtts +931 .iter() +932 .filter_map(|(addr, rtt)| { +933 if let transports::Addr::Ip(SocketAddr::V4(addr)) = *addr { +934 Some((addr, *rtt)) +935 } else { +936 None +937 } +938 }) +939 .min_by_key(|(_addr, rtt)| *rtt); +940 +941 // Find the fastest direct IPv6 path. +942 let direct_path_ipv6 = path_rtts +943 .iter() +944 .filter_map(|(addr, rtt)| { +945 if let transports::Addr::Ip(SocketAddr::V6(addr)) = *addr { +946 Some((addr, *rtt)) +947 } else { +948 None +949 } +950 }) +951 .min_by_key(|(_addr, rtt)| *rtt); +952 +953 // Find the fastest relay path. +954 let relay_path = path_rtts +955 .iter() +956 .filter(|(addr, _rtt)| addr.is_relay()) +957 .min_by_key(|(_addr, rtt)| *rtt) +958 .map(|(addr, rtt)| (addr.clone(), *rtt)); +959 +960 let current_path = self +961 .selected_path +962 .get() +963 .and_then(|addr| path_rtts.get(&addr).copied().map(|rtt| (addr, rtt))); +964 let selected_path = select_best_path( +965 current_path.clone(), +966 direct_path_ipv4, +967 direct_path_ipv6, +968 relay_path, +969 ); +970 +971 // Apply our new path +972 if let Some((addr, rtt)) = selected_path { +973 let prev = self.selected_path.set(Some(addr.clone())); +974 if prev.is_ok() { +975 event!( +976 target: "iroh::_events::path::selected", +977 Level::DEBUG, +978 remote = %self.endpoint_id.fmt_short(), +979 path_remote = ?addr, +980 ?rtt, +981 prev_remote = ?prev, +982 ); +983 } +984 self.open_path(&addr); +985 self.close_redundant_paths(&addr); +986 } else { +987 trace!(?current_path, "keeping current path"); +988 } +989 } +990 +991 /// Closes any direct paths not selected if we are the client. +992 /// +993 /// Makes sure not to close the last direct path. Relay paths are never closed +994 /// currently, because we only have one relay path at this time. +995 /// +996 /// Only the client closes paths, just like only the client opens paths. This is to +997 /// avoid the client and server selecting different paths and accidentally closing all +998 /// paths. +999 fn close_redundant_paths(&mut self, selected_path: &transports::Addr) { +1000 debug_assert_eq!(self.selected_path.get().as_ref(), Some(selected_path),); +1001 +1002 for (conn_id, conn_state) in self.connections.iter() { +1003 for (path_id, path_remote) in conn_state +1004 .open_paths +1005 .iter() +1006 .filter(|(_, addr)| addr.is_ip()) +1007 .filter(|(_, addr)| *addr != selected_path) +1008 { +1009 if conn_state.open_paths.values().filter(|a| a.is_ip()).count() <= 1 { +1010 continue; // Do not close the last direct path. +1011 } +1012 if let Some(path) = conn_state +1013 .handle +1014 .upgrade() +1015 .filter(|conn| conn.side().is_client()) +1016 .and_then(|conn| conn.path(*path_id)) +1017 { +1018 trace!(?path_remote, ?conn_id, ?path_id, "closing direct path"); +1019 match path.close() { +1020 Err(quinn_proto::ClosePathError::LastOpenPath) => { +1021 error!("could not close last open path"); +1022 } +1023 Err(quinn_proto::ClosePathError::ClosedPath) => { +1024 // We already closed this. +1025 } +1026 Ok(_fut) => { +1027 // We will handle the event in Self::handle_path_events. +1028 } +1029 } +1030 } +1031 } +1032 } +1033 } +1034} +1035 +1036/// Returns `Some` if a new path should be selected, `None` if the `current_path` should +1037/// continued to be used. +1038fn select_best_path( +1039 current_path: Option<(transports::Addr, Duration)>, +1040 direct_path_ipv4: Option<(SocketAddrV4, Duration)>, +1041 direct_path_ipv6: Option<(SocketAddrV6, Duration)>, +1042 new_relay_path: Option<(transports::Addr, Duration)>, +1043) -> Option<(transports::Addr, Duration)> { +1044 // Determine the best new IP path. +1045 let best_ip_path = match (direct_path_ipv4, direct_path_ipv6) { +1046 (Some((addr_v4, rtt_v4)), Some((addr_v6, rtt_v6))) => { +1047 Some(select_v4_v6(addr_v4, rtt_v4, addr_v6, rtt_v6)) +1048 } +1049 (None, Some((addr_v6, rtt_v6))) => Some((addr_v6.into(), rtt_v6)), +1050 (Some((addr_v4, rtt_v4)), None) => Some((addr_v4.into(), rtt_v4)), +1051 (None, None) => None, +1052 }; +1053 let best_ip_path = best_ip_path.map(|(addr, rtt)| (transports::Addr::Ip(addr), rtt)); +1054 +1055 match current_path { +1056 None => { +1057 // If we currently have no path +1058 if best_ip_path.is_some() { +1059 // Use the best IP path +1060 best_ip_path +1061 } else { +1062 // Use the new relay path +1063 new_relay_path +1064 } +1065 } +1066 Some((transports::Addr::Relay(..), _)) => { +1067 // If we have a current path, but it is relay +1068 if best_ip_path.is_some() { +1069 // Use the best IP path +1070 best_ip_path +1071 } else { +1072 // Use the new relay path +1073 new_relay_path +1074 } +1075 } +1076 Some((transports::Addr::Ip(_), current_rtt)) => { +1077 match &best_ip_path { +1078 Some((_, new_rtt)) => { +1079 // Comparing available IP paths +1080 if current_rtt >= *new_rtt + RTT_SWITCHING_MIN_IP { +1081 // New IP path is faster +1082 best_ip_path +1083 } else { +1084 // New IP is not faster +1085 None +1086 } +1087 } +1088 None => { +1089 // No new IP path, don't switch away +1090 None +1091 } +1092 } +1093 } +1094 } +1095} +1096 +1097/// Compare two IP addrs v4 & v6 and selects the "best" one. +1098/// +1099/// This prefers IPv6 paths over IPv4 paths. +1100fn select_v4_v6( +1101 addr_v4: SocketAddrV4, +1102 rtt_v4: Duration, +1103 addr_v6: SocketAddrV6, +1104 rtt_v6: Duration, +1105) -> (SocketAddr, Duration) { +1106 if rtt_v6 <= rtt_v4 + IPV6_RTT_ADVANTAGE { +1107 (addr_v6.into(), rtt_v6) +1108 } else { +1109 (addr_v4.into(), rtt_v4) +1110 } +1111} +1112 +1113fn send_datagram<'a>( +1114 sender: &'a mut TransportsSender, +1115 dst: transports::Addr, +1116 owned_transmit: OwnedTransmit, +1117) -> impl Future<Output = n0_error::Result<()>> + 'a { +1118 std::future::poll_fn(move |cx| { +1119 let transmit = transports::Transmit { +1120 ecn: owned_transmit.ecn, +1121 contents: owned_transmit.contents.as_ref(), +1122 segment_size: owned_transmit.segment_size, +1123 }; +1124 +1125 Pin::new(&mut *sender) +1126 .poll_send(cx, &dst, None, &transmit) +1127 .map(|res| res.with_context(|_| format!("failed to send datagram to {dst:?}"))) +1128 }) +1129} +1130 +1131/// Messages to send to the [`RemoteStateActor`]. +1132#[derive(derive_more::Debug)] +1133pub(crate) enum RemoteStateMessage { +1134 /// Sends a datagram to all known paths. +1135 /// +1136 /// Used to send QUIC Initial packets. If there is no working direct path this will +1137 /// trigger holepunching. +1138 /// +1139 /// This is not acceptable to use on the normal send path, as it is an async send +1140 /// operation with a bunch more copying. So it should only be used for sending QUIC +1141 /// Initial packets. +1142 #[debug("SendDatagram(..)")] +1143 SendDatagram(TransportsSender, OwnedTransmit), +1144 /// Adds an active connection to this remote endpoint. +1145 /// +1146 /// The connection will now be managed by this actor. Holepunching will happen when +1147 /// needed, any new paths discovered via holepunching will be added. And closed paths +1148 /// will be removed etc. +1149 #[debug("AddConnection(..)")] +1150 AddConnection(WeakConnectionHandle, oneshot::Sender<PathsWatcher>), +1151 /// Asks if there is any possible path that could be used. +1152 /// +1153 /// This adds the provided transport addresses to the list of potential paths for this remote +1154 /// and starts discovery if needed. +1155 /// +1156 /// Returns `Ok` immediately if the provided address list is non-empy or we have are other known paths. +1157 /// Otherwise returns `Ok` once discovery produces a result, or the discovery error if discovery fails +1158 /// or produces no results, +1159 #[debug("ResolveRemote(..)")] +1160 ResolveRemote( +1161 BTreeSet<TransportAddr>, +1162 oneshot::Sender<Result<(), DiscoveryError>>, +1163 ), +1164 /// Returns information about the remote. +1165 /// +1166 /// This currently only includes a list of all known transport addresses for the remote. +1167 RemoteInfo(oneshot::Sender<RemoteInfo>), +1168} +1169 +1170/// A handle to a [`RemoteStateActor`]. +1171/// +1172/// Dropping this will stop the actor. The actor will also stop after an idle timeout +1173/// if it has no connections, an empty inbox, and no other senders than the one stored +1174/// in the endpoint map exist. +1175#[derive(Debug)] +1176pub(super) struct RemoteStateHandle { +1177 /// Sender for the channel into the [`RemoteStateActor`]. +1178 /// +1179 /// This is a [`GuardedSender`], from which we can get a sender but only if the receiver +1180 /// hasn't been closed. +1181 pub(super) sender: GuardedSender<RemoteStateMessage>, +1182 _task: AbortOnDropHandle<()>, +1183} +1184 +1185/// Information about a holepunch attempt. +1186/// +1187/// Addresses are always stored in canonical form. +1188#[derive(Debug)] +1189struct HolepunchAttempt { +1190 when: Instant, +1191 /// The set of local addresses which could take part in holepunching. +1192 /// +1193 /// This does not mean every address here participated in the holepunching. E.g. we +1194 /// could have tried only a sub-set of the addresses because a previous attempt already +1195 /// covered part of the range. 1196 /// -1197 /// Like [`Self::local_candidates`] we may not have used them. -1198 remote_candidates: BTreeSet<SocketAddr>, -1199} -1200 -1201/// Newtype to track Connections. -1202/// -1203/// The wrapped value is the [`quinn::Connection::stable_id`] value, and is thus only valid -1204/// for active connections. -1205#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -1206struct ConnId(usize); -1207 -1208/// State about one connection. -1209#[derive(Debug)] -1210struct ConnectionState { -1211 /// Weak handle to the connection. -1212 handle: WeakConnectionHandle, -1213 /// The information we publish to users about the paths used in this connection. -1214 pub_open_paths: Watchable<PathAddrList>, -1215 /// The paths that exist on this connection. -1216 /// -1217 /// This could be in any state, e.g. while still validating the path or already closed -1218 /// but not yet fully removed from the connection. This exists as long as Quinn knows -1219 /// about the [`PathId`]. -1220 paths: FxHashMap<PathId, transports::Addr>, -1221 /// The open paths on this connection, a subset of [`Self::paths`]. -1222 open_paths: FxHashMap<PathId, transports::Addr>, -1223 /// Reverse map of [`Self::paths]. -1224 path_ids: FxHashMap<transports::Addr, PathId>, -1225} -1226 -1227impl ConnectionState { -1228 /// Tracks a path for the connection. -1229 fn add_path(&mut self, remote: transports::Addr, path_id: PathId) { -1230 self.paths.insert(path_id, remote.clone()); -1231 self.path_ids.insert(remote, path_id); -1232 } -1233 -1234 /// Tracks an open path for the connection. -1235 fn add_open_path(&mut self, remote: transports::Addr, path_id: PathId) { -1236 self.paths.insert(path_id, remote.clone()); -1237 self.open_paths.insert(path_id, remote.clone()); -1238 self.path_ids.insert(remote, path_id); -1239 self.update_pub_path_info(); -1240 } -1241 -1242 /// Completely removes a path from this connection. -1243 fn remove_path(&mut self, path_id: &PathId) -> Option<transports::Addr> { -1244 let addr = self.paths.remove(path_id); -1245 if let Some(ref addr) = addr { -1246 self.path_ids.remove(addr); -1247 } -1248 self.open_paths.remove(path_id); -1249 addr -1250 } -1251 -1252 /// Removes the path from the open paths. -1253 fn remove_open_path(&mut self, path_id: &PathId) { -1254 self.open_paths.remove(path_id); -1255 -1256 self.update_pub_path_info(); -1257 } -1258 -1259 /// Sets the new [`PathInfo`] structs for the public [`Connection`]. -1260 /// -1261 /// [`Connection`]: crate::endpoint::Connection -1262 fn update_pub_path_info(&self) { -1263 let new = self -1264 .open_paths -1265 .iter() -1266 .map(|(path_id, remote)| { -1267 let remote = TransportAddr::from(remote.clone()); -1268 (remote, *path_id) -1269 }) -1270 .collect::<PathAddrList>(); -1271 -1272 self.pub_open_paths.set(new).ok(); -1273 } -1274} -1275 -1276/// Watcher for the open paths and selected transmission path in a connection. -1277/// -1278/// This is stored in the [`Connection`], and the watchables are set from within the endpoint state actor. -1279/// -1280/// Internally, this contains a boxed-mapped-joined watcher over the open paths in the connection and the -1281/// selected path to the remote endpoint. The watcher is boxed because the mapped-joined watcher with -1282/// `SmallVec<PathInfoList>` has a size of over 800 bytes, which we don't want to put upon the [`Connection`]. -1283/// -1284/// [`Connection`]: crate::endpoint::Connection -1285#[derive(Clone, derive_more::Debug)] -1286#[debug("PathsWatcher")] -1287#[allow(clippy::type_complexity)] -1288pub(crate) struct PathsWatcher( -1289 Box< -1290 n0_watcher::Map< -1291 n0_watcher::Tuple< -1292 n0_watcher::Direct<PathAddrList>, -1293 n0_watcher::Direct<Option<transports::Addr>>, -1294 >, -1295 PathInfoList, -1296 >, -1297 >, -1298); -1299 -1300impl n0_watcher::Watcher for PathsWatcher { -1301 type Value = PathInfoList; -1302 -1303 fn update(&mut self) -> bool { -1304 self.0.update() -1305 } -1306 -1307 fn peek(&self) -> &Self::Value { -1308 self.0.peek() -1309 } -1310 -1311 fn is_connected(&self) -> bool { -1312 self.0.is_connected() -1313 } -1314 -1315 fn poll_updated( -1316 &mut self, -1317 cx: &mut std::task::Context<'_>, -1318 ) -> Poll<Result<(), n0_watcher::Disconnected>> { -1319 self.0.poll_updated(cx) -1320 } -1321} -1322 -1323impl PathsWatcher { -1324 fn new( -1325 open_paths: n0_watcher::Direct<PathAddrList>, -1326 selected_path: n0_watcher::Direct<Option<transports::Addr>>, -1327 conn_handle: WeakConnectionHandle, -1328 ) -> Self { -1329 Self(Box::new(open_paths.or(selected_path).map( -1330 move |(open_paths, selected_path)| { -1331 let selected_path: Option<TransportAddr> = selected_path.map(Into::into); -1332 let Some(conn) = conn_handle.upgrade() else { -1333 return PathInfoList(Default::default()); -1334 }; -1335 let list = open_paths -1336 .into_iter() -1337 .flat_map(move |(remote, path_id)| { -1338 PathInfo::new(path_id, &conn, remote, selected_path.as_ref()) -1339 }) -1340 .collect(); -1341 PathInfoList(list) -1342 }, -1343 ))) -1344 } -1345} -1346 -1347/// List of [`PathInfo`] for the network paths of a [`Connection`]. -1348/// -1349/// This struct implements [`IntoIterator`]. -1350/// -1351/// [`Connection`]: crate::endpoint::Connection -1352#[derive(derive_more::Debug, derive_more::IntoIterator, Eq, PartialEq, Clone)] -1353#[debug("{_0:?}")] -1354pub struct PathInfoList(SmallVec<[PathInfo; 4]>); -1355 -1356impl PathInfoList { -1357 /// Returns an iterator over the path infos. -1358 pub fn iter(&self) -> impl Iterator<Item = &PathInfo> { -1359 self.0.iter() -1360 } -1361 -1362 /// Returns `true` if the list is empty. -1363 pub fn is_empty(&self) -> bool { -1364 self.0.is_empty() +1197 /// We do not store this as a [`DirectAddr`] because this is checked for equality and we +1198 /// do not want to compare the sources of these addresses. +1199 local_candidates: BTreeSet<SocketAddr>, +1200 /// The set of remote addresses which could take part in holepunching. +1201 /// +1202 /// Like [`Self::local_candidates`] we may not have used them. +1203 remote_candidates: BTreeSet<SocketAddr>, +1204} +1205 +1206/// Newtype to track Connections. +1207/// +1208/// The wrapped value is the [`quinn::Connection::stable_id`] value, and is thus only valid +1209/// for active connections. +1210#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +1211struct ConnId(usize); +1212 +1213/// State about one connection. +1214#[derive(Debug)] +1215struct ConnectionState { +1216 /// Weak handle to the connection. +1217 handle: WeakConnectionHandle, +1218 /// The information we publish to users about the paths used in this connection. +1219 pub_open_paths: Watchable<PathAddrList>, +1220 /// The paths that exist on this connection. +1221 /// +1222 /// This could be in any state, e.g. while still validating the path or already closed +1223 /// but not yet fully removed from the connection. This exists as long as Quinn knows +1224 /// about the [`PathId`]. +1225 paths: FxHashMap<PathId, transports::Addr>, +1226 /// The open paths on this connection, a subset of [`Self::paths`]. +1227 open_paths: FxHashMap<PathId, transports::Addr>, +1228 /// Reverse map of [`Self::paths]. +1229 path_ids: FxHashMap<transports::Addr, PathId>, +1230} +1231 +1232impl ConnectionState { +1233 /// Tracks a path for the connection. +1234 fn add_path(&mut self, remote: transports::Addr, path_id: PathId) { +1235 self.paths.insert(path_id, remote.clone()); +1236 self.path_ids.insert(remote, path_id); +1237 } +1238 +1239 /// Tracks an open path for the connection. +1240 fn add_open_path(&mut self, remote: transports::Addr, path_id: PathId) { +1241 self.paths.insert(path_id, remote.clone()); +1242 self.open_paths.insert(path_id, remote.clone()); +1243 self.path_ids.insert(remote, path_id); +1244 self.update_pub_path_info(); +1245 } +1246 +1247 /// Completely removes a path from this connection. +1248 fn remove_path(&mut self, path_id: &PathId) -> Option<transports::Addr> { +1249 let addr = self.paths.remove(path_id); +1250 if let Some(ref addr) = addr { +1251 self.path_ids.remove(addr); +1252 } +1253 self.open_paths.remove(path_id); +1254 addr +1255 } +1256 +1257 /// Removes the path from the open paths. +1258 fn remove_open_path(&mut self, path_id: &PathId) { +1259 self.open_paths.remove(path_id); +1260 +1261 self.update_pub_path_info(); +1262 } +1263 +1264 /// Sets the new [`PathInfo`] structs for the public [`Connection`]. +1265 /// +1266 /// [`Connection`]: crate::endpoint::Connection +1267 fn update_pub_path_info(&self) { +1268 let new = self +1269 .open_paths +1270 .iter() +1271 .map(|(path_id, remote)| { +1272 let remote = TransportAddr::from(remote.clone()); +1273 (remote, *path_id) +1274 }) +1275 .collect::<PathAddrList>(); +1276 +1277 self.pub_open_paths.set(new).ok(); +1278 } +1279} +1280 +1281/// Watcher for the open paths and selected transmission path in a connection. +1282/// +1283/// This is stored in the [`Connection`], and the watchables are set from within the endpoint state actor. +1284/// +1285/// Internally, this contains a boxed-mapped-joined watcher over the open paths in the connection and the +1286/// selected path to the remote endpoint. The watcher is boxed because the mapped-joined watcher with +1287/// `SmallVec<PathInfoList>` has a size of over 800 bytes, which we don't want to put upon the [`Connection`]. +1288/// +1289/// [`Connection`]: crate::endpoint::Connection +1290#[derive(Clone, derive_more::Debug)] +1291#[debug("PathsWatcher")] +1292#[allow(clippy::type_complexity)] +1293pub(crate) struct PathsWatcher( +1294 Box< +1295 n0_watcher::Map< +1296 n0_watcher::Tuple< +1297 n0_watcher::Direct<PathAddrList>, +1298 n0_watcher::Direct<Option<transports::Addr>>, +1299 >, +1300 PathInfoList, +1301 >, +1302 >, +1303); +1304 +1305impl n0_watcher::Watcher for PathsWatcher { +1306 type Value = PathInfoList; +1307 +1308 fn update(&mut self) -> bool { +1309 self.0.update() +1310 } +1311 +1312 fn peek(&self) -> &Self::Value { +1313 self.0.peek() +1314 } +1315 +1316 fn is_connected(&self) -> bool { +1317 self.0.is_connected() +1318 } +1319 +1320 fn poll_updated( +1321 &mut self, +1322 cx: &mut std::task::Context<'_>, +1323 ) -> Poll<Result<(), n0_watcher::Disconnected>> { +1324 self.0.poll_updated(cx) +1325 } +1326} +1327 +1328impl PathsWatcher { +1329 fn new( +1330 open_paths: n0_watcher::Direct<PathAddrList>, +1331 selected_path: n0_watcher::Direct<Option<transports::Addr>>, +1332 conn_handle: WeakConnectionHandle, +1333 ) -> Self { +1334 Self(Box::new(open_paths.or(selected_path).map( +1335 move |(open_paths, selected_path)| { +1336 let selected_path: Option<TransportAddr> = selected_path.map(Into::into); +1337 let Some(conn) = conn_handle.upgrade() else { +1338 return PathInfoList(Default::default()); +1339 }; +1340 let list = open_paths +1341 .into_iter() +1342 .flat_map(move |(remote, path_id)| { +1343 PathInfo::new(path_id, &conn, remote, selected_path.as_ref()) +1344 }) +1345 .collect(); +1346 PathInfoList(list) +1347 }, +1348 ))) +1349 } +1350} +1351 +1352/// List of [`PathInfo`] for the network paths of a [`Connection`]. +1353/// +1354/// This struct implements [`IntoIterator`]. +1355/// +1356/// [`Connection`]: crate::endpoint::Connection +1357#[derive(derive_more::Debug, derive_more::IntoIterator, Eq, PartialEq, Clone)] +1358#[debug("{_0:?}")] +1359pub struct PathInfoList(SmallVec<[PathInfo; 4]>); +1360 +1361impl PathInfoList { +1362 /// Returns an iterator over the path infos. +1363 pub fn iter(&self) -> impl Iterator<Item = &PathInfo> { +1364 self.0.iter() 1365 } 1366 -1367 /// Returns the number of paths. -1368 pub fn len(&self) -> usize { -1369 self.0.len() +1367 /// Returns `true` if the list is empty. +1368 pub fn is_empty(&self) -> bool { +1369 self.0.is_empty() 1370 } -1371} -1372 -1373/// Information about a network path used by a [`Connection`]. -1374/// -1375/// [`Connection`]: crate::endpoint::Connection -1376#[derive(derive_more::Debug, Clone)] -1377pub struct PathInfo { -1378 path_id: PathId, -1379 #[debug(skip)] -1380 handle: WeakConnectionHandle, -1381 stats: PathStats, -1382 remote: TransportAddr, -1383 is_selected: bool, -1384} -1385 -1386impl PartialEq for PathInfo { -1387 fn eq(&self, other: &Self) -> bool { -1388 self.path_id == other.path_id -1389 && self.remote == other.remote -1390 && self.is_selected == other.is_selected -1391 } -1392} -1393 -1394impl Eq for PathInfo {} -1395 -1396impl PathInfo { -1397 fn new( -1398 path_id: PathId, -1399 conn: &quinn::Connection, -1400 remote: TransportAddr, -1401 selected_path: Option<&TransportAddr>, -1402 ) -> Option<Self> { -1403 let stats = conn.path_stats(path_id)?; -1404 Some(Self { -1405 path_id, -1406 handle: conn.weak_handle(), -1407 is_selected: Some(&remote) == selected_path, -1408 remote, -1409 stats, -1410 }) -1411 } -1412 -1413 /// The remote transport address used by this network path. -1414 pub fn remote_addr(&self) -> &TransportAddr { -1415 &self.remote +1371 +1372 /// Returns the number of paths. +1373 pub fn len(&self) -> usize { +1374 self.0.len() +1375 } +1376} +1377 +1378/// Information about a network path used by a [`Connection`]. +1379/// +1380/// [`Connection`]: crate::endpoint::Connection +1381#[derive(derive_more::Debug, Clone)] +1382pub struct PathInfo { +1383 path_id: PathId, +1384 #[debug(skip)] +1385 handle: WeakConnectionHandle, +1386 stats: PathStats, +1387 remote: TransportAddr, +1388 is_selected: bool, +1389} +1390 +1391impl PartialEq for PathInfo { +1392 fn eq(&self, other: &Self) -> bool { +1393 self.path_id == other.path_id +1394 && self.remote == other.remote +1395 && self.is_selected == other.is_selected +1396 } +1397} +1398 +1399impl Eq for PathInfo {} +1400 +1401impl PathInfo { +1402 fn new( +1403 path_id: PathId, +1404 conn: &quinn::Connection, +1405 remote: TransportAddr, +1406 selected_path: Option<&TransportAddr>, +1407 ) -> Option<Self> { +1408 let stats = conn.path_stats(path_id)?; +1409 Some(Self { +1410 path_id, +1411 handle: conn.weak_handle(), +1412 is_selected: Some(&remote) == selected_path, +1413 remote, +1414 stats, +1415 }) 1416 } 1417 -1418 /// Returns `true` if this path is currently the main transmission path for this [`Connection`]. -1419 /// -1420 /// [`Connection`]: crate::endpoint::Connection -1421 pub fn is_selected(&self) -> bool { -1422 self.is_selected -1423 } -1424 -1425 /// Whether this is an IP transport address. -1426 pub fn is_ip(&self) -> bool { -1427 self.remote.is_ip() +1418 /// The remote transport address used by this network path. +1419 pub fn remote_addr(&self) -> &TransportAddr { +1420 &self.remote +1421 } +1422 +1423 /// Returns `true` if this path is currently the main transmission path for this [`Connection`]. +1424 /// +1425 /// [`Connection`]: crate::endpoint::Connection +1426 pub fn is_selected(&self) -> bool { +1427 self.is_selected 1428 } 1429 -1430 /// Whether this is a transport address via a relay server. -1431 pub fn is_relay(&self) -> bool { -1432 self.remote.is_relay() +1430 /// Whether this is an IP transport address. +1431 pub fn is_ip(&self) -> bool { +1432 self.remote.is_ip() 1433 } 1434 -1435 /// Returns stats for this transmission path. -1436 pub fn stats(&self) -> PathStats { -1437 self.handle -1438 .upgrade() -1439 .and_then(|conn| conn.path_stats(self.path_id)) -1440 .unwrap_or(self.stats) -1441 } -1442 -1443 /// Current best estimate of this paths's latency (round-trip-time) -1444 pub fn rtt(&self) -> Duration { -1445 self.stats().rtt +1435 /// Whether this is a transport address via a relay server. +1436 pub fn is_relay(&self) -> bool { +1437 self.remote.is_relay() +1438 } +1439 +1440 /// Returns stats for this transmission path. +1441 pub fn stats(&self) -> PathStats { +1442 self.handle +1443 .upgrade() +1444 .and_then(|conn| conn.path_stats(self.path_id)) +1445 .unwrap_or(self.stats) 1446 } -1447} -1448 -1449/// Poll a future once, like n0_future::future::poll_once but sync. -1450fn now_or_never<T, F: Future<Output = T>>(fut: F) -> Option<T> { -1451 let fut = std::pin::pin!(fut); -1452 match fut.poll(&mut std::task::Context::from_waker(std::task::Waker::noop())) { -1453 Poll::Ready(res) => Some(res), -1454 Poll::Pending => None, -1455 } -1456} -1457 -1458/// Future that resolves to the `conn_id` once a connection is closed. -1459/// -1460/// This uses [`quinn::Connection::on_closed`], which does not keep the connection alive -1461/// while awaiting the future. -1462struct OnClosed { -1463 conn_id: ConnId, -1464 inner: quinn::OnClosed, -1465} -1466 -1467impl OnClosed { -1468 fn new(conn: &quinn::Connection) -> Self { -1469 Self { -1470 conn_id: ConnId(conn.stable_id()), -1471 inner: conn.on_closed(), -1472 } -1473 } -1474} -1475 -1476impl Future for OnClosed { -1477 type Output = ConnId; -1478 -1479 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { -1480 let (_close_reason, _stats) = std::task::ready!(Pin::new(&mut self.inner).poll(cx)); -1481 Poll::Ready(self.conn_id) -1482 } -1483} -1484 -1485/// Converts an iterator of [`TransportAddr'] into an iterator of [`transports::Addr`]. -1486fn to_transports_addr( -1487 endpoint_id: EndpointId, -1488 addrs: impl IntoIterator<Item = TransportAddr>, -1489) -> impl Iterator<Item = transports::Addr> { -1490 addrs.into_iter().filter_map(move |addr| match addr { -1491 TransportAddr::Relay(relay_url) => Some(transports::Addr::from((relay_url, endpoint_id))), -1492 TransportAddr::Ip(sockaddr) => Some(transports::Addr::from(sockaddr)), -1493 _ => { -1494 warn!(?addr, "Unsupported TransportAddr"); -1495 None -1496 } -1497 }) -1498} -1499 -1500#[cfg(test)] -1501mod tests { -1502 use std::net::{Ipv4Addr, Ipv6Addr}; -1503 -1504 use super::*; -1505 -1506 #[test] -1507 fn test_select_v4_v6_addr() { -1508 let v4 = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 1); -1509 let v6 = SocketAddrV6::new(Ipv6Addr::LOCALHOST, 1, 0, 0); +1447 +1448 /// Current best estimate of this paths's latency (round-trip-time) +1449 pub fn rtt(&self) -> Duration { +1450 self.stats().rtt +1451 } +1452} +1453 +1454/// Poll a future once, like n0_future::future::poll_once but sync. +1455fn now_or_never<T, F: Future<Output = T>>(fut: F) -> Option<T> { +1456 let fut = std::pin::pin!(fut); +1457 match fut.poll(&mut std::task::Context::from_waker(std::task::Waker::noop())) { +1458 Poll::Ready(res) => Some(res), +1459 Poll::Pending => None, +1460 } +1461} +1462 +1463/// Future that resolves to the `conn_id` once a connection is closed. +1464/// +1465/// This uses [`quinn::Connection::on_closed`], which does not keep the connection alive +1466/// while awaiting the future. +1467struct OnClosed { +1468 conn_id: ConnId, +1469 inner: quinn::OnClosed, +1470} +1471 +1472impl OnClosed { +1473 fn new(conn: &quinn::Connection) -> Self { +1474 Self { +1475 conn_id: ConnId(conn.stable_id()), +1476 inner: conn.on_closed(), +1477 } +1478 } +1479} +1480 +1481impl Future for OnClosed { +1482 type Output = ConnId; +1483 +1484 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { +1485 let (_close_reason, _stats) = std::task::ready!(Pin::new(&mut self.inner).poll(cx)); +1486 Poll::Ready(self.conn_id) +1487 } +1488} +1489 +1490/// Converts an iterator of [`TransportAddr'] into an iterator of [`transports::Addr`]. +1491fn to_transports_addr( +1492 endpoint_id: EndpointId, +1493 addrs: impl IntoIterator<Item = TransportAddr>, +1494) -> impl Iterator<Item = transports::Addr> { +1495 addrs.into_iter().filter_map(move |addr| match addr { +1496 TransportAddr::Relay(relay_url) => Some(transports::Addr::from((relay_url, endpoint_id))), +1497 TransportAddr::Ip(sockaddr) => Some(transports::Addr::from(sockaddr)), +1498 _ => { +1499 warn!(?addr, "Unsupported TransportAddr"); +1500 None +1501 } +1502 }) +1503} +1504 +1505#[cfg(test)] +1506mod tests { +1507 use std::net::{Ipv4Addr, Ipv6Addr}; +1508 +1509 use super::*; 1510 -1511 // Same RTT, prefer v6 -1512 let (addr, rtt) = -1513 select_v4_v6(v4, Duration::from_millis(10), v6, Duration::from_millis(10)); -1514 assert_eq!(addr, v6.into()); -1515 assert_eq!(rtt, Duration::from_millis(10)); -1516 -1517 // v4 better -1518 let (addr, rtt) = select_v4_v6(v4, Duration::from_millis(1), v6, Duration::from_millis(10)); -1519 assert_eq!(addr, v4.into()); -1520 assert_eq!(rtt, Duration::from_millis(1)); +1511 #[test] +1512 fn test_select_v4_v6_addr() { +1513 let v4 = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 1); +1514 let v6 = SocketAddrV6::new(Ipv6Addr::LOCALHOST, 1, 0, 0); +1515 +1516 // Same RTT, prefer v6 +1517 let (addr, rtt) = +1518 select_v4_v6(v4, Duration::from_millis(10), v6, Duration::from_millis(10)); +1519 assert_eq!(addr, v6.into()); +1520 assert_eq!(rtt, Duration::from_millis(10)); 1521 -1522 // v6 better -1523 let (addr, rtt) = select_v4_v6(v4, Duration::from_millis(10), v6, Duration::from_millis(1)); -1524 assert_eq!(addr, v6.into()); +1522 // v4 better +1523 let (addr, rtt) = select_v4_v6(v4, Duration::from_millis(1), v6, Duration::from_millis(10)); +1524 assert_eq!(addr, v4.into()); 1525 assert_eq!(rtt, Duration::from_millis(1)); -1526 } -1527}

\ No newline at end of file +1526 +1527 // v6 better +1528 let (addr, rtt) = select_v4_v6(v4, Duration::from_millis(10), v6, Duration::from_millis(1)); +1529 assert_eq!(addr, v6.into()); +1530 assert_eq!(rtt, Duration::from_millis(1)); +1531 } +1532}
\ No newline at end of file