iroh/socket/remote_map/
remote_state.rs

1use std::{
2    collections::{BTreeSet, VecDeque},
3    net::SocketAddr,
4    pin::Pin,
5    sync::Arc,
6    task::Poll,
7};
8
9use iroh_base::{EndpointId, TransportAddr};
10use n0_error::StackResultExt;
11use n0_future::{
12    FuturesUnordered, FuturesUnorderedBounded, MaybeFuture, MergeUnbounded, Stream, StreamExt,
13    boxed::BoxStream,
14    future::{Boxed, now_or_never},
15    task::JoinSet,
16    time::{self, Duration, Instant},
17};
18use n0_watcher::Watcher;
19use noq::{Closed, PathStats, PathStatus, WeakConnectionHandle};
20use noq_proto::{PathError, PathEvent as NoqPathEvent, PathId, n0_nat_traversal};
21use rustc_hash::FxHashMap;
22use smallvec::{SmallVec, smallvec};
23use tokio::sync::{mpsc, oneshot};
24use tokio_util::sync::CancellationToken;
25use tracing::{Instrument, Level, Span, debug, error, event, info_span, instrument, trace, warn};
26
27use self::path_state::RemotePathState;
28pub(crate) use self::path_watcher::PathStateReceiver;
29pub use self::{
30    path_watcher::{Path, PathEvent, PathEventStream, PathList, PathListIter, PathListStream},
31    remote_info::{RemoteInfo, TransportAddrInfo, TransportAddrUsage},
32};
33use super::{MappedAddrs, Source};
34use crate::{
35    address_lookup::{AddressLookupFailed, AddressLookupServices, Item as AddressLookupItem},
36    endpoint::DirectAddr,
37    socket::{
38        Metrics as SocketMetrics, RELAY_PATH_MAX_IDLE_TIMEOUT,
39        remote_map::remote_state::path_watcher::PathStateSender,
40        transports::{self, OwnedTransmit, TransportsSender},
41    },
42};
43
44mod path_state;
45mod path_watcher;
46mod remote_info;
47
48/// How often to attempt holepunching.
49///
50/// If there have been no changes to the NAT address candidates, holepunching will not be
51/// attempted more frequently than at this interval.
52const HOLEPUNCH_ATTEMPTS_INTERVAL: Duration = Duration::from_secs(5);
53
54/// The latency at or under which we don't try to upgrade to a better path.
55const GOOD_ENOUGH_LATENCY: Duration = Duration::from_millis(10);
56
57// TODO: use this
58// /// How long since the last activity we try to keep an established endpoint peering alive.
59// ///
60// /// It's also the idle time at which we stop doing QAD queries to keep NAT mappings alive.
61// pub(super) const SESSION_ACTIVE_TIMEOUT: Duration = Duration::from_secs(45);
62
63/// How often we try to upgrade to a better path.
64///
65/// Even if we have some non-relay route that works.
66const UPGRADE_INTERVAL: Duration = Duration::from_secs(60);
67
68/// The time after which an idle [`RemoteStateActor`] stops.
69///
70/// The actor only enters the idle state if no connections are active and no inbox senders exist
71/// apart from the one stored in the endpoint map. Stopping and restarting the actor in this state
72/// is not an issue; a timeout here serves the purpose of not stopping-and-recreating actors
73/// in a high frequency, and to keep data about previous path around for subsequent connections.
74const ACTOR_MAX_IDLE_TIMEOUT: Duration = Duration::from_secs(60);
75
76// QUIC retransmits dropped Initials; a blocked transport must not retain them indefinitely.
77const DATAGRAM_SEND_TIMEOUT: Duration = Duration::from_secs(3);
78const MAX_DATAGRAM_SEND_TASKS: usize = 16;
79
80/// A stream of events from all paths for all connections.
81///
82/// The connection is identified using [`ConnId`].  The event `Err` variant happens when the
83/// actor has lagged processing the events, which is rather critical for us.
84type PathEvents = MergeUnbounded<
85    Pin<Box<dyn Stream<Item = (ConnId, Result<NoqPathEvent, noq::Lagged>)> + Send + Sync>>,
86>;
87
88/// A stream of events of announced NAT traversal candidate addresses for all connections.
89///
90/// The connection is identified using [`ConnId`].
91type AddrEvents = MergeUnbounded<
92    Pin<
93        Box<
94            dyn Stream<Item = (ConnId, Result<n0_nat_traversal::Event, noq::Lagged>)> + Send + Sync,
95        >,
96    >,
97>;
98
99/// The state we need to know about a single remote endpoint.
100///
101/// This actor manages all connections to the remote endpoint.  It will trigger holepunching
102/// and select the best path etc.
103pub(super) struct RemoteStateActor {
104    /// All connections we have to this remote endpoint.
105    connections: FxHashMap<ConnId, ConnectionState>,
106    /// State of the actor and hooks into the rest of the remote endpoint.
107    ///
108    /// This is on a separate struct so that we can have parallel mutable borrows to
109    /// `connections` and `state`.
110    state: State,
111}
112
113/// State of the [`RemoteStateActor`] and hooks into the rest of the remote endpoint.
114struct State {
115    /// The endpoint ID of the remote endpoint.
116    endpoint_id: EndpointId,
117
118    // Hooks into the rest of the Socket.
119    //
120    /// Metrics.
121    metrics: Arc<SocketMetrics>,
122    /// Our local addresses.
123    ///
124    /// These are our local addresses and any reflexive transport addresses.
125    local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>,
126    /// The mapped addresses for this endpoint.
127    mapped_addrs: MappedAddrs,
128    /// Address lookup service, cloned from the socket.
129    address_lookup: AddressLookupServices,
130
131    // Internal state - Noq Connections we are managing.
132    //
133    /// Notifications when connections are closed.
134    connections_close: FuturesUnordered<OnClosed>,
135    /// Events emitted by Noq about path changes, for all paths, all connections.
136    path_events: PathEvents,
137    /// A stream of events of announced NAT traversal candidate addresses for all connections.
138    addr_events: AddrEvents,
139
140    // Internal state - Holepunching and path state.
141    //
142    /// All possible paths we are aware of.
143    ///
144    /// These paths might be entirely impossible to use, since they are added by Address Lookup
145    /// mechanisms.  The are only potentially usable.
146    paths: RemotePathState,
147    /// Information about the last holepunching attempt.
148    last_holepunch: Option<HolepunchAttempt>,
149
150    /// The path we currently consider the preferred path to the remote endpoint.
151    ///
152    /// **We expect this path to work.** If we become aware this path is broken then it is
153    /// set back to `None`.  Having a selected path does not mean we may not be able to get
154    /// a better path: e.g. when the selected path is a relay path we still need to trigger
155    /// holepunching regularly.
156    ///
157    /// We only select a path once the path is functional in Noq.
158    selected_path: Option<transports::FourTuple>,
159    /// Time at which we should schedule the next holepunch attempt.
160    scheduled_holepunch: Option<Instant>,
161    /// When to next attempt opening paths in [`Self::pending_open_paths`].
162    scheduled_open_path: Option<Instant>,
163    /// Paths which we still need to open.
164    ///
165    /// They failed to open because we did not have enough CIDs issued by the remote.
166    pending_open_paths: VecDeque<transports::FourTuple>,
167
168    // Internal state - address lookup
169    //
170    /// Stream of Address Lookup results, or always pending if Address Lookup is not running.
171    address_lookup_stream: Option<BoxStream<Result<AddressLookupItem, AddressLookupFailed>>>,
172
173    /// The path selector used to pick the preferred path among the candidates.
174    path_selector: Arc<dyn PathSelector>,
175}
176
177impl RemoteStateActor {
178    #[allow(clippy::too_many_arguments)]
179    pub(super) fn new(
180        endpoint_id: EndpointId,
181        local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>,
182        mapped_addrs: MappedAddrs,
183        metrics: Arc<SocketMetrics>,
184        address_lookup: AddressLookupServices,
185        path_selector: Arc<dyn PathSelector>,
186    ) -> Self {
187        Self {
188            connections: FxHashMap::default(),
189            state: State {
190                endpoint_id,
191                metrics: metrics.clone(),
192                local_direct_addrs,
193                mapped_addrs,
194                address_lookup,
195                connections_close: Default::default(),
196                path_events: Default::default(),
197                addr_events: Default::default(),
198                paths: RemotePathState::new(metrics),
199                last_holepunch: None,
200                selected_path: Default::default(),
201                scheduled_holepunch: None,
202                scheduled_open_path: None,
203                pending_open_paths: VecDeque::new(),
204                address_lookup_stream: None,
205                path_selector,
206            },
207        }
208    }
209
210    pub(super) fn start(
211        self,
212        initial_msgs: Vec<RemoteStateMessage>,
213        tasks: &mut JoinSet<(EndpointId, Vec<RemoteStateMessage>)>,
214        shutdown_token: CancellationToken,
215        parent_span: Span,
216    ) -> mpsc::Sender<RemoteStateMessage> {
217        let (tx, rx) = mpsc::channel(16);
218        let endpoint_id = self.state.endpoint_id;
219
220        // Ideally we'd use the endpoint span as parent.  We'd have to plug that span into
221        // here somehow.  Instead we have no parent and explicitly set the me attribute.  If
222        // we don't explicitly set a span we get the spans from whatever call happens to
223        // first create the actor, which is often very confusing as it then keeps those
224        // spans for all logging of the actor.
225        tasks.spawn(
226            self.run(initial_msgs, rx, shutdown_token)
227                .instrument(info_span!(
228                    parent: parent_span,
229                    "RemoteStateActor",
230                    remote = %endpoint_id.fmt_short(),
231                )),
232        );
233        tx
234    }
235
236    /// Runs the main loop of the actor.
237    async fn run(
238        mut self,
239        initial_msgs: Vec<RemoteStateMessage>,
240        mut inbox: mpsc::Receiver<RemoteStateMessage>,
241        shutdown_token: CancellationToken,
242    ) -> (EndpointId, Vec<RemoteStateMessage>) {
243        trace!("actor started");
244        let mut send_tasks = FuturesUnorderedBounded::new(MAX_DATAGRAM_SEND_TASKS);
245        for msg in initial_msgs {
246            self.handle_message(msg, &mut send_tasks);
247        }
248        let idle_timeout = time::sleep(ACTOR_MAX_IDLE_TIMEOUT);
249        n0_future::pin!(idle_timeout);
250
251        let check_connections = time::interval(UPGRADE_INTERVAL);
252        n0_future::pin!(check_connections);
253
254        loop {
255            let scheduled_path_open = match self.state.scheduled_open_path {
256                Some(when) => MaybeFuture::Some(time::sleep_until(when)),
257                None => MaybeFuture::None,
258            };
259            n0_future::pin!(scheduled_path_open);
260            let scheduled_hp = match self.state.scheduled_holepunch {
261                Some(when) => MaybeFuture::Some(time::sleep_until(when)),
262                None => MaybeFuture::None,
263            };
264            n0_future::pin!(scheduled_hp);
265            if !self.is_idle(&inbox) {
266                idle_timeout
267                    .as_mut()
268                    .reset(Instant::now() + ACTOR_MAX_IDLE_TIMEOUT);
269            }
270
271            tokio::select! {
272                biased;
273
274                _ = shutdown_token.cancelled() => {
275                    trace!("actor cancelled");
276                    break;
277                }
278                Some(()) = send_tasks.next(), if !send_tasks.is_empty() => {}
279                msg = inbox.recv() => {
280                    match msg {
281                        Some(msg) => self.handle_message(msg, &mut send_tasks),
282                        None => break,
283                    }
284                }
285                Some((id, evt)) = self.state.path_events.next() => {
286                    self.handle_path_event(id, evt);
287                }
288                Some((id, evt)) = self.state.addr_events.next() => {
289                    trace!(?id, ?evt, "remote addrs updated, triggering holepunching");
290                    self.trigger_holepunching();
291                }
292                Some((conn_id, closed)) = self.state.connections_close.next(), if !self.state.connections_close.is_empty() => {
293                    self.handle_connection_close(conn_id, closed);
294                }
295                res = self.state.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.update_local_direct_address();
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.state.scheduled_open_path = None;
307                    let mut addrs = std::mem::take(&mut self.state.pending_open_paths);
308                    while let Some(addr) = addrs.pop_front() {
309                        self.open_path_on_all_conns(&addr);
310                    }
311                }
312                _ = &mut scheduled_hp => {
313                    trace!("triggering scheduled holepunching");
314                    self.state.scheduled_holepunch = None;
315                    self.trigger_holepunching();
316                }
317                Some(item) = maybe_next(self.state.address_lookup_stream.as_mut()), if self.state.address_lookup_stream.is_some() => {
318                    self.state.handle_address_lookup_item(item);
319                }
320                _ = check_connections.tick() => {
321                    self.check_connections();
322                }
323                _ = &mut idle_timeout => {
324                    if self.is_idle(&inbox) {
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            }
333        }
334
335        inbox.close();
336        // There might be a race between checking `inbox.is_empty()` and `inbox.close()`,
337        // so we pull out all messages that are left over.
338        let mut leftover_msgs = Vec::with_capacity(inbox.len());
339        inbox.recv_many(&mut leftover_msgs, inbox.len()).await;
340
341        trace!("actor terminating");
342        (self.state.endpoint_id, leftover_msgs)
343    }
344
345    /// Returns `true` if the actor is fully idle.
346    fn is_idle(&self, inbox: &mpsc::Receiver<RemoteStateMessage>) -> bool {
347        self.connections.is_empty()
348            && inbox.is_empty()
349            && self.state.paths.resolve_requests_is_empty()
350    }
351
352    /// Handles an actor message.
353    #[instrument(skip(self))]
354    fn handle_message(
355        &mut self,
356        msg: RemoteStateMessage,
357        send_tasks: &mut FuturesUnorderedBounded<Boxed<()>>,
358    ) {
359        match msg {
360            RemoteStateMessage::SendDatagram(sender, transmit) => {
361                self.state
362                    .handle_msg_send_datagram(sender, transmit, send_tasks);
363            }
364            RemoteStateMessage::AddConnection(handle, tx) => {
365                self.handle_msg_add_connection(handle, tx);
366            }
367            RemoteStateMessage::ResolveRemote(addrs, tx) => {
368                self.state.handle_msg_resolve_remote(addrs, tx);
369            }
370            RemoteStateMessage::RemoteInfo(tx) => {
371                let addrs = self.state.paths.to_remote_addrs();
372                let info = RemoteInfo {
373                    endpoint_id: self.state.endpoint_id,
374                    addrs,
375                };
376                tx.send(info).ok();
377            }
378            RemoteStateMessage::NetworkChange { is_major } => {
379                self.handle_msg_network_change(is_major);
380            }
381        }
382    }
383
384    /// Handles [`RemoteStateMessage::AddConnection`].
385    ///
386    /// Error returns are fatal and kill the actor.
387    fn handle_msg_add_connection(
388        &mut self,
389        conn: noq::Connection,
390        tx: oneshot::Sender<PathStateReceiver>,
391    ) {
392        let (path_state_sender, path_state_receiver) = PathStateSender::new();
393        self.state.metrics.num_conns_opened.inc();
394        // Remove any conflicting stable_ids from the local state.
395        let conn_id = ConnId(conn.stable_id());
396        self.connections.remove(&conn_id);
397
398        // Hook up paths, NAT addresses and connection closed event streams.
399        self.state
400            .path_events
401            .push(Box::pin(conn.path_events().map(move |evt| (conn_id, evt))));
402        self.state.addr_events.push(Box::pin(
403            conn.nat_traversal_updates().map(move |evt| (conn_id, evt)),
404        ));
405        self.state.connections_close.push(OnClosed::new(&conn));
406
407        // Add local addrs to the connection
408        let local_addrs = self.state.local_candidates();
409        update_qnt_candidates(&conn, &local_addrs);
410
411        // Store the connection
412        let conn_state = self
413            .connections
414            .entry(conn_id)
415            .insert_entry(ConnectionState {
416                handle: conn.weak_handle(),
417                path_state: path_state_sender,
418                paths: Default::default(),
419                has_been_direct: false,
420            })
421            .into_mut();
422
423        // Store PathId(0), set path_status and select best path, check if holepunching
424        // is needed.
425        if let Some(path) = conn.path(PathId::ZERO) {
426            let path_remote = self
427                .state
428                .register_and_configure_path(conn_id, conn_state, &path);
429
430            if let Some(path_remote) = path_remote
431                && !path_remote.is_relay()
432                && conn.side().is_client()
433            {
434                // We may have raced this with a relay address.  Try and add any
435                // relay addresses we have back.
436                let relays = self
437                    .state
438                    .paths
439                    .addrs()
440                    .filter(|addr| addr.is_relay())
441                    .map(|addr| transports::FourTuple::from_remote(addr.clone()))
442                    .collect::<Vec<_>>();
443                for open_addr in relays {
444                    self.state
445                        .open_path_on_conn(conn_id, conn_state, &conn, &open_addr);
446                }
447            }
448        }
449        self.trigger_holepunching();
450        self.select_path();
451        tx.send(path_state_receiver).ok();
452    }
453
454    /// Handles [`RemoteStateMessage::NetworkChange`].
455    fn handle_msg_network_change(&mut self, is_major: bool) {
456        // Ping all the paths so loss-detection starts ASAP.
457        for conn in self.connections.values() {
458            if let Some(noq_conn) = conn.handle.upgrade() {
459                for (path_id, addr) in &conn.paths {
460                    if let Some(path) = noq_conn.path(*path_id) {
461                        // Ping the current path
462                        if let Err(err) = path.ping() {
463                            warn!(%err, %path_id, ?addr, "failed to ping path");
464                        }
465                    }
466                }
467            }
468        }
469
470        if is_major {
471            self.trigger_holepunching();
472        }
473    }
474
475    fn handle_connection_close(&mut self, conn_id: ConnId, closed: Closed) {
476        event!(
477            target: "iroh::_events::conn::closed",
478            Level::DEBUG,
479            %conn_id,
480            remote_id = %self.state.endpoint_id.fmt_short(),
481            reason=?closed.reason,
482        );
483
484        if let Some(conn_state) = self.connections.remove(&conn_id) {
485            self.state.metrics.num_conns_closed.inc();
486            conn_state.path_state.close(closed);
487        }
488        if self.connections.is_empty() {
489            trace!("last connection closed - clearing selected_path");
490            self.state.selected_path = None;
491        }
492    }
493
494    /// Updates the local [`DirectAddr`]s to all connections.
495    ///
496    /// Each connection needs to have the local direct addresses to use as QNT address
497    /// candidates.
498    fn update_local_direct_address(&mut self) {
499        let local_addrs = self.state.local_candidates();
500        for conn in self.connections.values().filter_map(|s| s.handle.upgrade()) {
501            update_qnt_candidates(&conn, &local_addrs);
502        }
503        // todo: trace
504    }
505
506    /// Triggers holepunching to the remote endpoint.
507    ///
508    /// This will manage the entire process of holepunching with the remote endpoint.
509    ///
510    /// - Holepunching happens on the Connection with the lowest [`ConnId`] which is a
511    ///   client.
512    ///   - Both endpoints may initiate holepunching if both have a client connection.
513    ///   - Any opened paths are opened on all other connections without holepunching.
514    /// - If there are no changes in local or remote candidate addresses since the
515    ///   last attempt **and** there was a recent attempt, a trigger_holepunching call
516    ///   will be scheduled instead.
517    fn trigger_holepunching(&mut self) {
518        if self.connections.is_empty() {
519            trace!("not holepunching: no connections");
520            return;
521        }
522
523        let Some(conn) = self
524            .connections
525            .iter()
526            .filter_map(|(id, state)| state.handle.upgrade().map(|conn| (*id, conn)))
527            .filter(|(_, conn)| conn.side().is_client())
528            .min_by_key(|(id, _)| *id)
529            .map(|(_, conn)| conn)
530        else {
531            trace!("not holepunching: no client connection");
532            return;
533        };
534        let remote_candidates = match conn.get_remote_nat_traversal_addresses() {
535            Ok(addrs) => BTreeSet::from_iter(addrs),
536            Err(err) => {
537                warn!("failed to get nat candidate addresses: {err:#}");
538                return;
539            }
540        };
541        let local_candidates = self.state.local_candidates();
542        let new_candidates = self
543            .state
544            .last_holepunch
545            .as_ref()
546            .map(|last_hp| {
547                // Addrs are allowed to disappear, but if there are new ones we need to
548                // holepunch again.
549                trace!(
550                    ?last_hp,
551                    ?local_candidates,
552                    ?remote_candidates,
553                    "candidates to holepunch?"
554                );
555                !remote_candidates.is_subset(&last_hp.remote_candidates)
556                    || !local_candidates.is_subset(&last_hp.local_candidates)
557            })
558            .unwrap_or(true);
559        if !new_candidates && let Some(ref last_hp) = self.state.last_holepunch {
560            let next_hp = last_hp.when + HOLEPUNCH_ATTEMPTS_INTERVAL;
561            let now = Instant::now();
562            if next_hp > now {
563                trace!(scheduled_in = ?(next_hp - now), "not holepunching: no new addresses");
564                self.state.scheduled_holepunch = Some(next_hp);
565                return;
566            }
567        }
568
569        self.state.do_holepunching(conn);
570    }
571
572    #[instrument(skip(self))]
573    fn handle_path_event(&mut self, conn_id: ConnId, event: Result<NoqPathEvent, noq::Lagged>) {
574        let Ok(event) = event else {
575            warn!("missed a PathEvent, RemoteStateActor lagging");
576            // TODO: Is it possible to recover using the sync APIs to figure out what the
577            //    state of the connection and it's paths are?
578            return;
579        };
580        let Some(conn_state) = self.connections.get_mut(&conn_id) else {
581            trace!("event for removed connection");
582            return;
583        };
584        let Some(conn) = conn_state.handle.upgrade() else {
585            trace!("event for closed connection");
586            return;
587        };
588        trace!("path event");
589        match event {
590            NoqPathEvent::Established { id: path_id, .. } => {
591                let Some(path) = conn.path(path_id) else {
592                    trace!("path open event for unknown path");
593                    return;
594                };
595
596                self.state
597                    .register_and_configure_path(conn_id, conn_state, &path);
598                self.select_path();
599            }
600            NoqPathEvent::Abandoned { id, reason, .. } => {
601                // Remove abandoned path from the conn state.
602                let Some(network_path) = conn_state.remove_path(&id, &conn) else {
603                    debug!(%id, "path not in path_id_map");
604                    return;
605                };
606
607                // We track all known remote addresses for the peer in `State::paths`. The
608                // paths are tracked by remote address only (we ignore the local
609                // IP). Therefore, we mark a remote addr as abandoned in the remote-global
610                // state only once no connections have any path to that remote addr.
611                if !conn_state
612                    .paths
613                    .values()
614                    .any(|tuple| tuple.remote() == network_path.remote())
615                {
616                    self.state.paths.abandoned_path(&network_path.remote());
617                }
618
619                event!(
620                    target: "iroh::_events::path::abandoned",
621                    Level::DEBUG,
622                    remote = %self.state.endpoint_id.fmt_short(),
623                    %conn_id,
624                    path_id = %id,
625                    %network_path,
626                    ?reason
627                );
628
629                // If the remote closed our selected path, select a new one.
630                self.select_path();
631            }
632            NoqPathEvent::Discarded { id, path_stats, .. } => {
633                trace!(%id, ?path_stats, "path discarded");
634            }
635            NoqPathEvent::RemoteStatus { .. } | NoqPathEvent::ObservedAddr { .. } => {
636                // Nothing to do for these events.
637            }
638            _ => {
639                // We expect to keep noq and iroh in sync in all test setups, but in production it's totally possible
640                // that iroh itself is linked against a newer version of noq with additional events we don't yet
641                // know how to handle.
642                #[cfg(test)]
643                panic!("Unhandled path event: {event:?}");
644            }
645        }
646    }
647
648    /// Selects the preferred path by invoking the configured [`PathSelector`].
649    ///
650    /// The selected path is added to any connections which do not yet have it.  Any unused
651    /// direct paths are closed for all connections.
652    #[instrument(skip_all)]
653    fn select_path(&mut self) {
654        let current_path = self.state.selected_path.as_ref();
655        let selected_addr = {
656            let ctx = PathSelectionContext::new(current_path, &self.connections);
657            self.state.path_selector.select(&ctx).selected().cloned()
658        };
659
660        if let Some(addr) = selected_addr
661            && self.state.selected_path.as_ref() != Some(&addr)
662        {
663            let prev_remote = self.state.selected_path.replace(addr.clone());
664            event!(
665                target: "iroh::_events::path::selected",
666                Level::DEBUG,
667                remote = %self.state.endpoint_id.fmt_short(),
668                network_path = %addr,
669                prev_network_path = %prev_remote.map(|p| format!("{p}")).unwrap_or("None".to_string()),
670            );
671        } else {
672            trace!(?current_path, "keeping current path");
673        }
674
675        self.apply_selected_path();
676    }
677
678    /// Propagates a change of [`State::selected_path`] to noq.
679    ///
680    /// Iterates over all connections and applies the selected path as follows:
681    /// - Closes non-selected IP paths (but keeps one IP path open still)
682    /// - Sets all non-selected paths to [`PathStatus::Backup`]
683    /// - Opens the selected path if it does not exist on the connection
684    /// - Sets the selected path to [`PathStatus::Available`]
685    fn apply_selected_path(&mut self) {
686        let Some(selected) = self.state.selected_path.clone() else {
687            // We can't open the selected path on all paths if we don't have one yet.  And
688            // we can't close all "unselected" paths either, because we don't know which one
689            // is selected.
690            return;
691        };
692
693        for (conn_id, conn_state) in self.connections.iter() {
694            let Some(conn) = conn_state.handle.upgrade() else {
695                continue;
696            };
697
698            // Open path if it doesn't exist yet.
699            self.state
700                .open_path_on_conn(*conn_id, conn_state, &conn, &selected);
701
702            for (path_id, path_fourtuple) in conn_state.paths.iter() {
703                let Some(path) = conn.path(*path_id) else {
704                    continue;
705                };
706
707                // Closes redundant IP paths so that at most one remains per connection.
708                //
709                // Relay and custom paths are kept open. Only the client closes paths,
710                // to avoid the client and server independently closing different paths
711                // and racing to abandon the last one.
712                if conn.side().is_client()
713                    && path_fourtuple.is_ip()
714                    && path_fourtuple != &selected
715                    && conn_state.paths.values().filter(|a| a.is_ip()).count() > 1
716                {
717                    trace!(?path_fourtuple, %conn_id, %path_id, "closing direct path");
718                    match path.close() {
719                        Err(noq_proto::ClosePathError::MultipathNotNegotiated) => {
720                            error!("multipath not negotiated");
721                        }
722                        Err(noq_proto::ClosePathError::LastOpenPath) => {
723                            error!("could not close last open path");
724                        }
725                        Err(noq_proto::ClosePathError::ClosedPath) => {
726                            // We already closed this.
727                        }
728                        Ok(()) => {}
729                    }
730                    continue;
731                }
732
733                // Set path status: The selected path becomes Available, all other paths
734                // become Backup.
735                self.state.set_path_status(*conn_id, &path, path_fourtuple);
736            }
737
738            // Record the new selected path in the path watcher.
739            conn_state.path_state.record_selected(&selected);
740        }
741    }
742
743    fn open_path_on_all_conns(&mut self, open_addr: &transports::FourTuple) {
744        for (conn_id, conn_state) in self.connections.iter() {
745            let Some(conn) = conn_state.handle.upgrade() else {
746                continue;
747            };
748            self.state
749                .open_path_on_conn(*conn_id, conn_state, &conn, open_addr);
750        }
751    }
752
753    /// Handles regularly checking if any paths need hole punching currently
754    ///
755    /// Currently we need to have 1 IP path, with a good enough latency.
756    fn check_connections(&mut self) {
757        let mut is_goodenough = true;
758        for conn_state in self.connections.values() {
759            let mut is_conn_goodenough = false;
760            if let Some(conn) = conn_state.handle.upgrade() {
761                let min_ip_rtt = conn_state
762                    .paths
763                    .iter()
764                    .filter_map(|(path_id, addr)| {
765                        if addr.is_ip() {
766                            conn.path_stats(*path_id).map(|stats| stats.rtt)
767                        } else {
768                            None
769                        }
770                    })
771                    .min();
772
773                if let Some(min_ip_rtt) = min_ip_rtt {
774                    let is_latency_goodenough = min_ip_rtt <= GOOD_ENOUGH_LATENCY;
775                    is_conn_goodenough = is_latency_goodenough;
776                } else {
777                    // No IP transport found
778                    is_conn_goodenough = false;
779                }
780            }
781            is_goodenough &= is_conn_goodenough;
782        }
783
784        if !is_goodenough {
785            debug!("connections are not good enough, triggering holepunching");
786            self.trigger_holepunching();
787        }
788    }
789}
790
791impl State {
792    /// Handles [`RemoteStateMessage::SendDatagram`].
793    fn handle_msg_send_datagram(
794        &mut self,
795        sender: Box<TransportsSender>,
796        transmit: OwnedTransmit,
797        send_tasks: &mut FuturesUnorderedBounded<Boxed<()>>,
798    ) {
799        // Sending datagrams might fail, e.g. because we don't have the right transports set
800        // up to handle sending this owned transmit to.
801        // After all, we try every single path that we know (relay URL, IP address), even
802        // though we might not have a relay transport or ip-capable transport set up.
803        // So these errors must not be fatal for this actor (or even this operation).
804
805        let targets = if let Some(addr) = self.selected_path.as_ref() {
806            trace!(?addr, "sending datagram to selected path");
807
808            // TODO(Frando): We might want to include a local IP here in the future, if we confidently
809            // know that it is the correct one.
810            // See https://github.com/n0-computer/iroh/issues/4280.
811            smallvec![transports::FourTuple::from_remote(addr.remote())]
812        } else {
813            trace!(
814                paths = ?self.paths.addrs().collect::<Vec<_>>(),
815                "sending datagram to all known paths",
816            );
817            if self.paths.is_empty() {
818                warn!("Cannot send datagrams: No paths to remote endpoint known");
819            }
820
821            let mut targets = SmallVec::new();
822            for addr in self.paths.addrs() {
823                // We never want to send to our local addresses.
824                // The local address set is updated in the main loop so we can use `peek` here.
825                if let transports::Addr::Ip(sockaddr) = addr
826                    && self
827                        .local_direct_addrs
828                        .peek()
829                        .iter()
830                        .any(|a| a.addr == *sockaddr)
831                {
832                    trace!(%sockaddr, "not sending datagram to our own address");
833
834                // TODO(Frando): We might want to include a local IP here in the future, if we confidently
835                // know that it is the correct one.
836                // See https://github.com/n0-computer/iroh/issues/4280.
837                } else {
838                    targets.push(transports::FourTuple::from_remote(addr.clone()));
839                }
840            }
841            // This message is received *before* a connection is added.  So we do
842            // not yet have a connection to holepunch.  Instead we trigger
843            // holepunching when AddConnection is received.
844            targets
845        };
846
847        if targets.is_empty() {
848            return;
849        }
850        let send = Box::pin(
851            async move {
852                if time::timeout(
853                    DATAGRAM_SEND_TIMEOUT,
854                    send_datagram_to_targets(sender, transmit, targets),
855                )
856                .await
857                .is_err()
858                {
859                    debug!("Datagram send timed out");
860                }
861            }
862            .instrument(Span::current()),
863        );
864        if send_tasks.try_push(send).is_err() {
865            debug!("dropping datagram: send task limit reached");
866        }
867    }
868
869    /// Handles [`RemoteStateMessage::ResolveRemote`].
870    fn handle_msg_resolve_remote(
871        &mut self,
872        addrs: BTreeSet<TransportAddr>,
873        tx: oneshot::Sender<Result<(), AddressLookupFailed>>,
874    ) {
875        let addrs = to_transports_addr(self.endpoint_id, addrs);
876        self.paths.insert_multiple(addrs, Source::App);
877        self.paths.resolve_remote(tx);
878        // Start Address Lookup if we have no selected path.
879        self.trigger_address_lookup();
880    }
881
882    /// Triggers Address Lookup for the remote endpoint, if needed.
883    ///
884    /// Does not start Address Lookup if we have a selected path or if Address Lookup is
885    /// currently running.
886    fn trigger_address_lookup(&mut self) {
887        if self.selected_path.is_some() || self.address_lookup_stream.is_some() {
888            return;
889        }
890        let stream = self.address_lookup.resolve(self.endpoint_id);
891        let stream = stream.filter_map(|item| match item {
892            // We don't care about errors from individual services, we just continue.
893            // Individual errors are buffered into the final error by `AddressLookupServices::resolve`,
894            // and if the lookup fails we return them upstream with the final `AddressLookupFailed` error.
895            Ok(Err(_err)) => None,
896            Ok(Ok(item)) => Some(Ok(item)),
897            Err(err) => Some(Err(err)),
898        });
899        self.address_lookup_stream = Some(Box::pin(stream));
900    }
901
902    /// Handles an address lookup result.
903    ///
904    /// All address lookup results end up being sent here. It takes care of updating the
905    /// [`RemotePathState`] with the results.
906    fn handle_address_lookup_item(
907        &mut self,
908        item: Option<Result<AddressLookupItem, AddressLookupFailed>>,
909    ) {
910        match item {
911            None => {
912                self.paths.address_lookup_finished(Ok(()));
913                self.address_lookup_stream = None;
914            }
915            Some(Err(err)) => {
916                if let AddressLookupFailed::NoServiceConfigured { .. } = err {
917                    trace!("Address Lookup not configured");
918                } else {
919                    debug!("Address Lookup failed: {err:#}");
920                }
921                self.paths.address_lookup_finished(Err(err));
922                self.address_lookup_stream = None;
923            }
924            Some(Ok(item)) => {
925                if item.endpoint_id() != self.endpoint_id {
926                    warn!(
927                        ?item,
928                        "Address Lookup emitted item for wrong remote endpoint"
929                    );
930                } else {
931                    let source = Source::AddressLookup {
932                        name: item.provenance().to_string(),
933                    };
934                    let addrs =
935                        to_transports_addr(self.endpoint_id, item.into_endpoint_addr().addrs);
936                    self.paths.insert_multiple(addrs, source);
937                }
938            }
939        }
940    }
941
942    /// Unconditionally perform holepunching.
943    #[instrument(skip_all)]
944    fn do_holepunching(&mut self, conn: noq::Connection) {
945        self.metrics.holepunch_attempts.inc();
946        let local_candidates = self.local_candidates();
947        match conn.initiate_nat_traversal_round() {
948            Ok(remote_candidates) => {
949                let remote_candidates = remote_candidates
950                    .iter()
951                    .map(|addr| SocketAddr::new(addr.ip().to_canonical(), addr.port()))
952                    .collect();
953                event!(
954                    target: "iroh::_events::qnt::init",
955                    Level::DEBUG,
956                    remote = %self.endpoint_id.fmt_short(),
957                    ?local_candidates,
958                    ?remote_candidates,
959                );
960                self.last_holepunch = Some(HolepunchAttempt {
961                    when: Instant::now(),
962                    local_candidates,
963                    remote_candidates,
964                });
965            }
966            Err(err) => {
967                debug!("failed to initiate NAT traversal: {err:#}");
968                use noq_proto::n0_nat_traversal::Error;
969                match err {
970                    Error::Closed
971                    | Error::TooManyAddresses
972                    | Error::WrongConnectionSide
973                    | Error::ExtensionNotNegotiated => {
974                        // Fatal, no need to retry for now
975                    }
976                    Error::Multipath(_) | Error::NotEnoughAddresses => {
977                        // Retry in a bit
978                        let now = Instant::now();
979                        let next_hp = now + Duration::from_millis(100);
980                        trace!(scheduled_in = ?(next_hp - now), "holepunching retry");
981                        self.scheduled_holepunch = Some(next_hp);
982                    }
983                }
984            }
985        }
986    }
987
988    /// Register a path with our state and configure path-specific settings.
989    ///
990    /// This inserts the path in the [`ConnectionState`] and [`Self::paths`].
991    ///
992    /// It configures the path with the correct path status (see [`Self::set_path_status`]),
993    /// and applies path-type-specific settings:
994    /// Relay paths get a longer idle timeout to accommodate transparent reconnection
995    /// by the relay actor (see [`RELAY_PATH_MAX_IDLE_TIMEOUT`]).
996    fn register_and_configure_path(
997        &mut self,
998        conn_id: ConnId,
999        conn_state: &mut ConnectionState,
1000        path: &noq::Path,
1001    ) -> Option<transports::FourTuple> {
1002        let network_path = self
1003            .mapped_addrs
1004            .to_transport_tuple(&path.network_path().ok()?)?;
1005        event!(
1006            target: "iroh::_events::path::open",
1007            Level::DEBUG,
1008            remote = %self.endpoint_id.fmt_short(),
1009            %conn_id,
1010            path_id=%path.id(),
1011            %network_path,
1012        );
1013        conn_state.add_open_path(network_path.clone(), path.id(), &self.metrics);
1014        if network_path.is_relay()
1015            && let Err(e) = path.set_max_idle_timeout(Some(RELAY_PATH_MAX_IDLE_TIMEOUT))
1016        {
1017            debug!(?e, "failed to set relay path idle timeout");
1018        }
1019
1020        self.set_path_status(conn_id, path, &network_path);
1021        self.paths
1022            .insert_open_path(network_path.remote(), Source::Connection);
1023        Some(network_path)
1024    }
1025
1026    fn set_path_status(
1027        &mut self,
1028        conn_id: ConnId,
1029        path: &noq::Path,
1030        network_path: &transports::FourTuple,
1031    ) {
1032        let status = self.path_status_for_addr(network_path);
1033        match path.set_status(status) {
1034            Err(error) => warn!(?error, ?network_path, ?status, "set_status failed"),
1035            Ok(prev_status) if prev_status != status => {
1036                event!(
1037                    target: "iroh::_events::path::set_status",
1038                    Level::DEBUG,
1039                    remote = %self.endpoint_id.fmt_short(),
1040                    %conn_id,
1041                    path_id=%path.id(),
1042                    %network_path,
1043                    ?status,
1044                    ?prev_status,
1045                );
1046            }
1047            Ok(_) => {}
1048        }
1049    }
1050
1051    fn open_path_on_conn(
1052        &mut self,
1053        conn_id: ConnId,
1054        conn_state: &ConnectionState,
1055        conn: &noq::Connection,
1056        open_4tuple: &transports::FourTuple,
1057    ) {
1058        // Only the client opens paths; the server receives them via
1059        // QUIC frames and reacts to PathOpened events.
1060        if conn.side().is_server() {
1061            return;
1062        }
1063        // Already open on this connection; nothing to do.
1064        if conn_state.paths.values().any(|a| a == open_4tuple) {
1065            return;
1066        }
1067
1068        let mapped_4tuple = self.mapped_addrs.to_mapped_tuple(open_4tuple);
1069        let path_status = self.path_status_for_addr(open_4tuple);
1070
1071        let fut = conn.open_path_ensure(mapped_4tuple, path_status);
1072        match fut.path_id() {
1073            Some(path_id) => {
1074                trace!(%conn_id, %path_id, ?path_status, "opening new path");
1075            }
1076            None => {
1077                let ret = now_or_never(fut);
1078                match ret {
1079                    Some(Err(PathError::RemoteCidsExhausted))
1080                    | Some(Err(PathError::MaxPathIdReached)) => {
1081                        self.scheduled_open_path =
1082                            Some(Instant::now() + Duration::from_millis(333));
1083                        // The number of distinct candidate 4-tuples for a remote is
1084                        // small (single digits), so `contains` is a short linear scan
1085                        // and bounds the queue to that set.
1086                        if !self.pending_open_paths.contains(open_4tuple) {
1087                            self.pending_open_paths.push_back(open_4tuple.clone());
1088                        }
1089                        trace!(?open_4tuple, ?ret, "scheduling open_path");
1090                    }
1091                    _ => warn!(?ret, "Opening path failed"),
1092                }
1093            }
1094        }
1095    }
1096
1097    /// Returns the [`PathStatus`] for `addr`.
1098    ///
1099    /// Returns [`PathStatus::Available`] if `addr` is the currently-selected path,
1100    /// or [`PathStatus::Backup`] otherwise.
1101    fn path_status_for_addr(&self, addr: &transports::FourTuple) -> PathStatus {
1102        if Some(addr) == self.selected_path.as_ref() {
1103            PathStatus::Available
1104        } else {
1105            PathStatus::Backup
1106        }
1107    }
1108
1109    /// Returns the current set of local direct addresses.
1110    fn local_candidates(&mut self) -> BTreeSet<SocketAddr> {
1111        self.local_direct_addrs
1112            .get()
1113            .iter()
1114            .map(|d| d.addr)
1115            .collect()
1116    }
1117}
1118
1119/// Updates QNT's candidate addresses to be the current set of direct addresses.
1120///
1121/// `direct_addrs` must be a set of addresses extracted from the endpoint's current
1122/// [`DirectAddr`]s.
1123fn update_qnt_candidates(conn: &noq::Connection, direct_addrs: &BTreeSet<SocketAddr>) {
1124    let noq_candidates = match conn.get_local_nat_traversal_addresses() {
1125        Ok(addrs) => BTreeSet::from_iter(addrs),
1126        Err(err) => {
1127            warn!("failed to get local nat candidates: {err:#}");
1128            return;
1129        }
1130    };
1131    for addr in direct_addrs.difference(&noq_candidates) {
1132        if let Err(err) = conn.add_nat_traversal_address(*addr) {
1133            warn!("failed adding local addr: {err:#}",);
1134        }
1135    }
1136    for addr in noq_candidates.difference(direct_addrs) {
1137        if let Err(err) = conn.remove_nat_traversal_address(*addr) {
1138            warn!("failed removing local addr: {err:#}");
1139        }
1140    }
1141    trace!(?direct_addrs, "updated local QNT addresses");
1142}
1143
1144fn send_datagram<'a>(
1145    sender: &'a mut TransportsSender,
1146    addr: transports::FourTuple,
1147    owned_transmit: OwnedTransmit,
1148) -> impl Future<Output = n0_error::Result<()>> + 'a {
1149    std::future::poll_fn(move |cx| {
1150        let transmit = transports::Transmit {
1151            ecn: owned_transmit.ecn,
1152            contents: owned_transmit.contents.as_ref(),
1153            segment_size: owned_transmit.segment_size,
1154        };
1155
1156        Pin::new(&mut *sender)
1157            .poll_send(cx, &addr, &transmit)
1158            .map(|res| res.with_context(|_| format!("failed to send datagram to {:?}", addr)))
1159    })
1160}
1161
1162async fn send_datagram_to_targets(
1163    sender: Box<TransportsSender>,
1164    transmit: OwnedTransmit,
1165    targets: SmallVec<[transports::FourTuple; 8]>,
1166) {
1167    let mut sends = targets
1168        .into_iter()
1169        .map(|target| {
1170            let mut sender = sender.clone();
1171            let transmit = transmit.clone();
1172            async move {
1173                if let Err(err) = send_datagram(&mut sender, target.clone(), transmit).await {
1174                    debug!(?target, "failed to send datagram: {err:#}");
1175                }
1176            }
1177        })
1178        .collect::<FuturesUnordered<_>>();
1179    while sends.next().await.is_some() {}
1180}
1181
1182/// Messages to send to the [`RemoteStateActor`].
1183#[derive(derive_more::Debug)]
1184pub(crate) enum RemoteStateMessage {
1185    /// Sends a datagram to all known paths.
1186    ///
1187    /// Used to send QUIC Initial packets.  If there is no working direct path this will
1188    /// trigger holepunching.
1189    ///
1190    /// This is not acceptable to use on the normal send path, as it is an async send
1191    /// operation with a bunch more copying.  So it should only be used for sending QUIC
1192    /// Initial packets.
1193    #[debug("SendDatagram(..)")]
1194    SendDatagram(Box<TransportsSender>, OwnedTransmit),
1195    /// Adds an active connection to this remote endpoint.
1196    ///
1197    /// The actor will downgrade the connection to a [`noq::WeakConnectionHandle`] as soon
1198    /// as it processes the message. It will keep hold of the weak handle until it closes,
1199    /// but only update to a strong [`noq::Connection`] for brief moments.
1200    ///
1201    /// The actor will actively manage paths on the connection and start holepunching as needed.
1202    #[debug("AddConnection({})", _0.stable_id())]
1203    AddConnection(noq::Connection, oneshot::Sender<PathStateReceiver>),
1204    /// Asks if there is any possible path that could be used.
1205    ///
1206    /// This adds the provided transport addresses to the list of potential paths for this
1207    /// remote and starts Address Lookup if needed.
1208    ///
1209    /// Sends back `Ok` immediately if the provided address list is non-empy or we have are
1210    /// other known paths.  Otherwise sends back `Ok` once Address Lookup produces a result,
1211    /// or the Address Lookup error if Address Lookup fails or produces no results,
1212    #[debug("ResolveRemote(..)")]
1213    ResolveRemote(
1214        BTreeSet<TransportAddr>,
1215        oneshot::Sender<Result<(), AddressLookupFailed>>,
1216    ),
1217    /// Returns information about the remote.
1218    ///
1219    /// This currently only includes a list of all known transport addresses for the remote.
1220    RemoteInfo(oneshot::Sender<RemoteInfo>),
1221    /// The network status has changed in some way
1222    NetworkChange { is_major: bool },
1223}
1224
1225/// Information about a holepunch attempt.
1226///
1227/// Addresses are always stored in canonical form.
1228#[derive(Debug)]
1229struct HolepunchAttempt {
1230    when: Instant,
1231    /// The set of local addresses which could take part in holepunching.
1232    ///
1233    /// This does not mean every address here participated in the holepunching.  E.g. we
1234    /// could have tried only a sub-set of the addresses because a previous attempt already
1235    /// covered part of the range.
1236    ///
1237    /// We do not store this as a [`DirectAddr`] because this is checked for equality and we
1238    /// do not want to compare the sources of these addresses.
1239    local_candidates: BTreeSet<SocketAddr>,
1240    /// The set of remote addresses which could take part in holepunching.
1241    ///
1242    /// Like [`Self::local_candidates`] we may not have used them.
1243    remote_candidates: BTreeSet<SocketAddr>,
1244}
1245
1246/// Newtype to track Connections.
1247///
1248/// The wrapped value is the [`noq::Connection::stable_id`] value, and is thus only valid
1249/// for active connections.
1250#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, derive_more::Display)]
1251#[display("{_0}")]
1252struct ConnId(usize);
1253
1254/// A connection managed by the [`RemoteStateActor`].
1255///
1256/// - A handle to the connection.
1257/// - The paths we know about.
1258/// - Some stuff to make observers happy.
1259#[derive(Debug)]
1260struct ConnectionState {
1261    /// Weak handle to the connection.
1262    handle: WeakConnectionHandle,
1263    /// Writer-side handle for the connection's path observation state.
1264    ///
1265    /// The matching [`PathStateReceiver`] is held by the [`Connection`].
1266    ///
1267    /// [`Connection`]: crate::endpoint::Connection
1268    path_state: PathStateSender,
1269    /// The open paths that exist on this connection.
1270    ///
1271    /// This might be lagging from the connection state inside noq itself as this can only
1272    /// be updated once we received the event from noq.
1273    ///
1274    /// IP paths *should* have the local IP address filled in by the time we receive the
1275    /// event. The noq established event is only emitted once at least one datagram is
1276    /// received from the peer on the path.
1277    paths: FxHashMap<PathId, transports::FourTuple>,
1278    /// Whether this connection has ever had a direct path.
1279    ///
1280    /// Used for recording metrics.
1281    has_been_direct: bool,
1282}
1283
1284impl ConnectionState {
1285    /// Tracks an open path for the connection.
1286    fn add_open_path(
1287        &mut self,
1288        network_path: transports::FourTuple,
1289        path_id: PathId,
1290        metrics: &Arc<SocketMetrics>,
1291    ) {
1292        match network_path {
1293            transports::FourTuple::Ip { .. } => metrics.paths_direct.inc(),
1294            transports::FourTuple::Relay { .. } => metrics.paths_relay.inc(),
1295            transports::FourTuple::Custom { .. } => metrics.paths_custom.inc(),
1296        };
1297        if !self.has_been_direct && network_path.is_ip() {
1298            self.has_been_direct = true;
1299            metrics.num_conns_direct.inc();
1300        }
1301
1302        self.paths.insert(path_id, network_path.clone());
1303        if let Some(conn) = self.handle.upgrade()
1304            && let Some(path) = conn.path(path_id)
1305        {
1306            let handle = path.weak_handle();
1307            self.path_state.record_opened(handle, network_path);
1308        }
1309    }
1310
1311    /// Removes a path from this connection.
1312    fn remove_path(
1313        &mut self,
1314        path_id: &PathId,
1315        conn: &noq::Connection,
1316    ) -> Option<transports::FourTuple> {
1317        let addr = self.paths.remove(path_id)?;
1318        self.path_state.record_abandoned(*path_id, conn);
1319        Some(addr)
1320    }
1321}
1322
1323/// State of the endpoint relevant for path selection.
1324///
1325/// Constructed by the endpoint and passed to [`PathSelector::select`].  Borrows from
1326/// the endpoint's internal data.
1327#[derive(Debug)]
1328#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
1329pub struct PathSelectionContext<'a> {
1330    current: Option<&'a transports::FourTuple>,
1331    source: PathsSource<'a>,
1332}
1333
1334/// Either a reference to live connection state, or a synthesized list of paths
1335/// (for unit-testing selectors).
1336#[derive(Debug)]
1337enum PathsSource<'a> {
1338    Live(&'a FxHashMap<ConnId, ConnectionState>),
1339    #[cfg(test)]
1340    Test(Vec<PathSelectionData<'a>>),
1341}
1342
1343#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
1344impl<'a> PathSelectionContext<'a> {
1345    fn new(
1346        current: Option<&'a transports::FourTuple>,
1347        connections: &'a FxHashMap<ConnId, ConnectionState>,
1348    ) -> Self {
1349        Self {
1350            current,
1351            source: PathsSource::Live(connections),
1352        }
1353    }
1354
1355    /// Constructs a context with synthetic path data for testing.
1356    #[cfg(test)]
1357    pub(crate) fn for_test(
1358        current: Option<&'a transports::FourTuple>,
1359        paths: Vec<PathSelectionData<'a>>,
1360    ) -> Self {
1361        Self {
1362            current,
1363            source: PathsSource::Test(paths),
1364        }
1365    }
1366
1367    /// The path currently considered the preferred path to the remote endpoint, if any.
1368    pub fn current(&self) -> Option<&transports::FourTuple> {
1369        self.current
1370    }
1371
1372    /// Iterator over candidate paths.
1373    ///
1374    /// The same address may appear more than once when it is a path on multiple
1375    /// connections to the remote.  Selectors that care should aggregate as appropriate.
1376    pub fn paths(&self) -> Box<dyn Iterator<Item = PathSelectionData<'a>> + '_> {
1377        match &self.source {
1378            PathsSource::Live(connections) => Box::new(
1379                connections
1380                    .values()
1381                    .filter_map(|state| state.handle.upgrade().map(|conn| (state, conn)))
1382                    .flat_map(|(state, conn)| {
1383                        state.paths.iter().map(move |(path_id, addr)| {
1384                            PathSelectionData::live(addr, *path_id, conn.clone())
1385                        })
1386                    }),
1387            ),
1388            #[cfg(test)]
1389            PathsSource::Test(paths) => Box::new(paths.iter().cloned()),
1390        }
1391    }
1392}
1393
1394/// Data the selector sees about one candidate path.
1395//
1396// In production this borrows from a live connection and looks up stats from noq on
1397// demand.  In `#[cfg(test)]` builds it can also wrap synthesized stats so selectors
1398// can be unit-tested without standing up real connections.
1399#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
1400#[derive(derive_more::Debug, Clone)]
1401pub struct PathSelectionData<'a> {
1402    network_path: &'a transports::FourTuple,
1403    #[debug(skip)]
1404    source: StatsSource,
1405}
1406
1407#[derive(Clone)]
1408enum StatsSource {
1409    Live {
1410        path_id: PathId,
1411        conn: noq::Connection,
1412    },
1413    /// Boxed so `PathStats` (100+ bytes, 14 fields) doesn't inflate the enum's
1414    /// size in production where only the `Live` variant is ever constructed.
1415    #[cfg(test)]
1416    Test(Option<Box<PathStats>>),
1417}
1418
1419#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
1420impl<'a> PathSelectionData<'a> {
1421    fn live(
1422        network_path: &'a transports::FourTuple,
1423        path_id: PathId,
1424        conn: noq::Connection,
1425    ) -> Self {
1426        Self {
1427            network_path,
1428            source: StatsSource::Live { path_id, conn },
1429        }
1430    }
1431
1432    /// Constructs a [`PathSelectionData`] with synthetic stats for testing.
1433    ///
1434    /// `PathStats` is `#[non_exhaustive]` so callers build it via
1435    /// `let mut s = PathStats::default(); s.rtt = ...;`.
1436    #[cfg(test)]
1437    pub(crate) fn for_test(
1438        network_path: &'a transports::FourTuple,
1439        stats: Option<PathStats>,
1440    ) -> Self {
1441        Self {
1442            network_path,
1443            source: StatsSource::Test(stats.map(Box::new)),
1444        }
1445    }
1446
1447    /// The network path of the candidate path.
1448    pub fn network_path(&self) -> &transports::FourTuple {
1449        self.network_path
1450    }
1451
1452    /// Returns path statistics if available.
1453    pub fn stats(&self) -> Option<PathStats> {
1454        match &self.source {
1455            StatsSource::Live { path_id, conn } => conn.path_stats(*path_id),
1456            #[cfg(test)]
1457            StatsSource::Test(stats) => stats.as_deref().copied(),
1458        }
1459    }
1460}
1461
1462/// Trait to configure path selection.
1463///
1464/// Most users do not need to provide their own selector.
1465#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
1466pub trait PathSelector: Send + Sync + std::fmt::Debug + 'static {
1467    /// Pick the selected path to carry application data among the currently
1468    /// open network paths to the remote endpoint.
1469    ///
1470    /// Build the result by starting from [`PathSelection::none`] and calling
1471    /// [`PathSelection::set`] for the path the selector wants active.
1472    ///
1473    /// Returning an empty [`PathSelection`] keeps the current selection unchanged.
1474    fn select(&self, ctx: &PathSelectionContext<'_>) -> PathSelection;
1475}
1476
1477/// The set of paths a [`PathSelector`] has chosen.
1478///
1479/// Today this holds at most one path.  Build via [`PathSelection::none`] +
1480/// [`PathSelection::set`].
1481#[derive(Debug, Clone)]
1482#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
1483pub struct PathSelection {
1484    selection: Option<transports::FourTuple>,
1485}
1486
1487#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
1488impl PathSelection {
1489    /// An empty selection.
1490    pub fn none() -> Self {
1491        Self { selection: None }
1492    }
1493
1494    /// Sets the path as the selected path.
1495    ///
1496    /// This discards any previously selected path and sets this one as a single selected
1497    /// path.
1498    pub fn set(&mut self, path: &PathSelectionData<'_>) {
1499        if self.selection.is_some() {
1500            tracing::warn!(
1501                path = %path.network_path(),
1502                "PathSelection already contains a path; ignoring additional path"
1503            );
1504            return;
1505        }
1506        self.selection = Some(path.network_path.clone());
1507    }
1508
1509    /// The selected path: the one data should be sent on. This is not public so
1510    /// we can later allow for selecting multiple paths without changing the
1511    /// public API of `PathSelection`.
1512    ///
1513    /// Returns `None` when nothing has been selected.
1514    pub(crate) fn selected(&self) -> Option<&transports::FourTuple> {
1515        self.selection.as_ref()
1516    }
1517}
1518
1519/// Future that resolves to the `conn_id` once a connection is closed.
1520///
1521/// This uses [`noq::Connection::on_closed`], which does not keep the connection alive
1522/// while awaiting the future.
1523struct OnClosed {
1524    conn_id: ConnId,
1525    inner: noq::OnClosed,
1526}
1527
1528impl OnClosed {
1529    fn new(conn: &noq::Connection) -> Self {
1530        Self {
1531            conn_id: ConnId(conn.stable_id()),
1532            inner: conn.on_closed(),
1533        }
1534    }
1535}
1536
1537impl Future for OnClosed {
1538    type Output = (ConnId, Closed);
1539
1540    fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
1541        let closed = std::task::ready!(Pin::new(&mut self.inner).poll(cx));
1542        Poll::Ready((self.conn_id, closed))
1543    }
1544}
1545
1546/// Converts an iterator of [`TransportAddr'] into an iterator of [`transports::Addr`].
1547fn to_transports_addr(
1548    endpoint_id: EndpointId,
1549    addrs: impl IntoIterator<Item = TransportAddr>,
1550) -> impl Iterator<Item = transports::Addr> {
1551    addrs.into_iter().filter_map(move |addr| match addr {
1552        TransportAddr::Relay(relay_url) => Some(transports::Addr::from((relay_url, endpoint_id))),
1553        TransportAddr::Ip(sockaddr) => Some(transports::Addr::from(sockaddr)),
1554        TransportAddr::Custom(custom_addr) => Some(transports::Addr::from(custom_addr)),
1555        _ => {
1556            warn!(?addr, "Unsupported TransportAddr");
1557            None
1558        }
1559    })
1560}
1561
1562/// Returns the next item if `maybe_stream` is `Some`, or `None` otherwise.
1563async fn maybe_next<S: Stream + Unpin>(maybe_stream: Option<&mut S>) -> Option<Option<S::Item>> {
1564    match maybe_stream {
1565        None => None,
1566        Some(s) => Some(s.next().await),
1567    }
1568}
1569
1570#[cfg(all(test, not(wasm_browser)))]
1571mod tests {
1572    use super::*;
1573
1574    #[tokio::test]
1575    async fn blocked_relay_does_not_delay_direct_initial() {
1576        let receiver = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
1577        let (mut sender, _relay_receiver) = TransportsSender::with_bounded_relay(
1578            1,
1579            [transports::IpConfig::V4 {
1580                ip_net: "127.0.0.1/8".parse().unwrap(),
1581                port: 0,
1582                is_required: true,
1583                is_default: true,
1584            }]
1585            .into_iter(),
1586        );
1587        let relay = transports::FourTuple::Relay {
1588            url: "https://relay.example.invalid".parse().unwrap(),
1589            endpoint_id: iroh_base::SecretKey::from_bytes(&[1; 32]).public(),
1590        };
1591        let transmit = OwnedTransmit {
1592            ecn: None,
1593            contents: bytes::Bytes::from_static(b"initial"),
1594            segment_size: None,
1595        };
1596        send_datagram(&mut sender, relay.clone(), transmit.clone())
1597            .await
1598            .unwrap();
1599        let sends = send_datagram_to_targets(
1600            Box::new(sender),
1601            transmit,
1602            smallvec![
1603                relay,
1604                transports::FourTuple::from_remote(transports::Addr::Ip(
1605                    receiver.local_addr().unwrap(),
1606                )),
1607            ],
1608        );
1609        let mut buf = [0; 64];
1610        // The Relay queue stays full while the later Direct target receives its Initial.
1611        tokio::select! {
1612            _ = sends => panic!("blocked Relay send unexpectedly completed"),
1613            received = time::timeout(Duration::from_secs(1), receiver.recv(&mut buf)) => {
1614                let len = received.expect("Direct send blocked behind Relay").unwrap();
1615                assert_eq!(&buf[..len], b"initial");
1616            }
1617        }
1618    }
1619}