iroh/socket/transports/relay/
actor.rs

1//! The relay actor.
2//!
3//! The [`RelayActor`] handles all the relay connections.  It is helped by the
4//! [`ActiveRelayActor`] which handles a single relay connection.
5//!
6//! - The [`RelayActor`] manages all connections to relay servers.
7//!   - It starts a new [`ActiveRelayActor`] for each relay server needed.
8//!   - The [`ActiveRelayActor`] will exit when unused.
9//!     - Unless it is for the home relay, this one never exits.
10//!   - Each [`ActiveRelayActor`] uses a relay [`Client`].
11//!     - The relay [`Client`] is a `Stream` and `Sink` directly connected to the
12//!       `TcpStream` connected to the relay server.
13//!   - Each [`ActiveRelayActor`] will try and maintain a connection with the relay server.
14//!     - If connections fail, exponential backoff is used for reconnections.
15//! - When `AsyncUdpSocket` needs to send datagrams:
16//!   - It puts them on a queue to the [`RelayActor`].
17//!   - The [`RelayActor`] ensures the correct [`ActiveRelayActor`] is running and
18//!     forwards datagrams to it.
19//!   - The ActiveRelayActor sends datagrams directly to the relay server.
20//! - The relay receive path is:
21//!   - Whenever [`ActiveRelayActor`] is connected it reads from the underlying `TcpStream`.
22//!   - Received datagrams are placed on an mpsc channel that now bypasses the
23//!     [`RelayActor`] and goes straight to the `AsyncUpdSocket` interface.
24//!
25//! [`Client`]: iroh_relay::client::Client
26
27#[cfg(test)]
28use std::net::SocketAddr;
29use std::{
30    collections::{BTreeMap, BTreeSet},
31    future::Future,
32    net::IpAddr,
33    pin::{Pin, pin},
34    sync::{
35        Arc,
36        atomic::{AtomicBool, Ordering},
37    },
38};
39
40use backon::{Backoff, BackoffBuilder, ExponentialBuilder};
41use iroh_base::{EndpointId, RelayUrl, SecretKey};
42use iroh_relay::{
43    self as relay, PingTracker, RelayMap,
44    client::{Client, ConnectError, RecvError, SendError},
45    protos::{
46        handshake,
47        relay::{ClientToRelayMsg, Datagrams, RelayToClientMsg, Status},
48    },
49};
50use n0_error::{AnyError, e, stack_error};
51use n0_future::{
52    FuturesUnorderedBounded, MaybeFuture, SinkExt, StreamExt,
53    task::{JoinError, JoinSet},
54    time::{self, Duration, Instant, MissedTickBehavior},
55};
56use n0_watcher::Watchable;
57use netwatch::interfaces;
58use tokio::sync::{mpsc, oneshot};
59use tokio_util::sync::CancellationToken;
60use tracing::{Instrument, Level, debug, error, event, info, info_span, instrument, trace, warn};
61use url::Url;
62
63#[cfg(not(wasm_browser))]
64use crate::dns::DnsResolver;
65use crate::{endpoint::RelayStatus, net_report::Report, socket::Metrics as SocketMetrics};
66
67/// How long a non-home relay connection needs to be idle (last written to) before we close it.
68const RELAY_INACTIVE_CLEANUP_TIME: Duration = Duration::from_secs(60);
69
70/// Maximum number of entries in [`ConnectedRelayState::endpoints_present`].
71///
72/// Caps memory growth from a relay advertising arbitrary source [`EndpointId`]s.
73const MAX_ENDPOINTS_PRESENT: usize = 4096;
74
75/// Interval in which we ping the relay server to ensure the connection is alive.
76///
77/// The default QUIC max_idle_timeout is 30s, so setting that to half this time gives some
78/// chance of recovering.
79const PING_INTERVAL: Duration = Duration::from_secs(15);
80
81/// Number of datagrams which can be sent to the relay server in one batch.
82///
83/// This means while this batch is sending to the server no other relay protocol frames can
84/// be sent to the server, e.g. no Ping frames or so.  While the maximum packet size is
85/// rather large, each item can typically be expected to up to 1500 or the max GSO size.
86const SEND_DATAGRAM_BATCH_SIZE: usize = 20;
87
88/// Timeout for establishing the relay connection.
89///
90/// This includes DNS, dialing the server, upgrading the connection, and completing the
91/// handshake.
92const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
93
94/// Time after which the [`ActiveRelayActor`] will drop undeliverable datagrams.
95///
96/// When the [`ActiveRelayActor`] is not connected it can not deliver datagrams.  However it
97/// will still receive datagrams to send from the [`RelayActor`].  If connecting takes
98/// longer than this timeout datagrams will be dropped.
99///
100/// This value is set to 3 times the QUIC initial Probe Timeout (PTO).
101const UNDELIVERABLE_DATAGRAM_TIMEOUT: Duration = Duration::from_secs(3);
102
103/// Timeout for closing the relay connection gracefully.
104///
105/// Must stay below the time the [`RelayActor`] waits for its [`ActiveRelayActor`]s to shut down.
106const CLOSE_TIMEOUT: Duration = Duration::from_secs(1);
107
108/// An actor which handles the connection to a single relay server.
109///
110/// It is responsible for maintaining the connection to the relay server and handling all
111/// communication with it.
112///
113/// The actor shuts down itself on inactivity: inactivity is determined when no more
114/// datagrams are being queued to send.
115///
116/// This actor has 3 main states it can be in, each has it's dedicated run loop:
117///
118/// - Dialing the relay server.
119///
120///   This will continuously dial the server until connected, using exponential backoff if
121///   it can not connect.  See [`ActiveRelayActor::run_dialing`].
122///
123/// - Connected to the relay server.
124///
125///   This state allows receiving from the relay server, though sending is idle in this
126///   state.  See [`ActiveRelayActor::run_connected`].
127///
128/// - Sending to the relay server.
129///
130///   This is a sub-state of `connected` so the actor can still be receiving from the relay
131///   server at this time.  However it is actively sending data to the server so can not
132///   consume any further items from inboxes which will result in sending more data to the
133///   server until the actor goes back to the `connected` state.
134///
135/// All these are driven from the top-level [`ActiveRelayActor::run`] loop.
136#[derive(Debug)]
137struct ActiveRelayActor {
138    // The inboxes and channels this actor communicates over.
139    /// Inbox for messages which should be handled without any blocking.
140    prio_inbox: mpsc::Receiver<ActiveRelayPrioMessage>,
141    /// Inbox for messages which involve sending to the relay server.
142    inbox: mpsc::Receiver<ActiveRelayMessage>,
143    /// Queue for received relay datagrams.
144    relay_datagrams_recv: mpsc::Sender<RelayRecvDatagram>,
145    /// Channel on which we queue packets to send to the relay.
146    relay_datagrams_send: mpsc::Receiver<RelaySendItem>,
147
148    // Other actor state.
149    /// The relay server for this actor.
150    url: RelayUrl,
151    /// Builder which can repeatedly build a relay client.
152    relay_client_builder: relay::client::ClientBuilder,
153    /// Whether or not this is the home relay server.
154    ///
155    /// The home relay server needs to maintain it's connection to the relay server, even if
156    /// the relay actor is otherwise idle.
157    is_home_relay: bool,
158    /// When this expires the actor has been idle and should shut down.
159    ///
160    /// Unless it is managing the home relay connection.  Inactivity is only tracked on the
161    /// last datagram sent to the relay, received datagrams will trigger QUIC ACKs which is
162    /// sufficient to keep active connections open.
163    inactive_timeout: Pin<Box<time::Sleep>>,
164    /// Token indicating the [`ActiveRelayActor`] should stop.
165    stop_token: CancellationToken,
166    metrics: Arc<SocketMetrics>,
167    my_relay: HomeRelayWatch,
168}
169
170#[derive(Debug)]
171enum ActiveRelayMessage {
172    /// Triggers a connection check to the relay server.
173    ///
174    /// Sometimes it is known the local network interfaces have changed in which case it
175    /// might be prudent to check if the relay connection is still working.  `Vec<IpAddr>`
176    /// should contain the current local IP addresses.  If the connection uses a local
177    /// socket with an IP address in this list the relay server will be pinged.  If the
178    /// connection uses a local socket with an IP address not in this list the server will
179    /// always re-connect.
180    CheckConnection { local_ips: Vec<IpAddr> },
181    /// Sets this relay as the home relay, or not.
182    SetHomeRelay(bool),
183    #[cfg(test)]
184    GetLocalAddr(oneshot::Sender<Option<SocketAddr>>),
185    #[cfg(test)]
186    PingServer(oneshot::Sender<()>),
187}
188
189/// Messages for the [`ActiveRelayActor`] which should never block.
190///
191/// Most messages in the [`ActiveRelayMessage`] enum trigger sending to the relay server,
192/// which can be blocking.  So the actor may not always be processing that inbox.  Messages
193/// here are processed immediately.
194#[derive(Debug)]
195enum ActiveRelayPrioMessage {
196    /// Returns whether or not this relay can reach the EndpointId.
197    HasEndpointRoute(EndpointId, oneshot::Sender<bool>),
198}
199
200/// Configuration needed to start an [`ActiveRelayActor`].
201#[derive(Debug)]
202struct ActiveRelayActorOptions {
203    url: RelayUrl,
204    prio_inbox_: mpsc::Receiver<ActiveRelayPrioMessage>,
205    inbox: mpsc::Receiver<ActiveRelayMessage>,
206    relay_datagrams_send: mpsc::Receiver<RelaySendItem>,
207    relay_datagrams_recv: mpsc::Sender<RelayRecvDatagram>,
208    connection_opts: RelayConnectionOptions,
209    stop_token: CancellationToken,
210    metrics: Arc<SocketMetrics>,
211    my_relay: HomeRelayWatch,
212}
213
214/// Configuration needed to create a connection to a relay server.
215#[derive(Debug, Clone)]
216struct RelayConnectionOptions {
217    secret_key: SecretKey,
218    #[cfg(not(wasm_browser))]
219    dns_resolver: DnsResolver,
220    proxy_url: Option<Url>,
221    prefer_ipv6: Arc<AtomicBool>,
222    tls_config: rustls::ClientConfig,
223    auth_token: Option<String>,
224}
225
226/// Possible reasons for a failed relay connection.
227#[allow(missing_docs)]
228#[stack_error(derive, add_meta)]
229enum RelayConnectionError {
230    #[error("Failed to connect to relay server")]
231    Dial { source: DialError },
232    #[error("Failed to handshake with relay server")]
233    Handshake { source: RunError },
234    #[error("Lost connection to relay server")]
235    Established { source: RunError },
236}
237
238#[allow(missing_docs)]
239#[stack_error(derive, add_meta)]
240enum RunError {
241    #[error("Send timeout")]
242    SendTimeout,
243    #[error("Ping timeout")]
244    PingTimeout,
245    #[error("Local IP no longer valid")]
246    LocalIpInvalid,
247    #[error("No local address")]
248    LocalAddrMissing,
249    #[error("Stream closed by server.")]
250    StreamClosedServer,
251    #[error("Client stream read failed")]
252    ClientStreamRead {
253        #[error(std_err)]
254        source: RecvError,
255    },
256    #[error("Client stream write failed")]
257    ClientStreamWrite {
258        #[error(std_err)]
259        source: SendError,
260    },
261}
262
263#[allow(missing_docs)]
264#[stack_error(derive, add_meta)]
265enum DialError {
266    #[error("timeout (>{timeout:?}) trying to establish a connection")]
267    Timeout { timeout: Duration },
268    #[error("unable to connect")]
269    Connect { source: ConnectError },
270}
271
272impl ActiveRelayActor {
273    fn new(opts: ActiveRelayActorOptions) -> Self {
274        let ActiveRelayActorOptions {
275            url,
276            prio_inbox_: prio_inbox,
277            inbox,
278            relay_datagrams_send,
279            relay_datagrams_recv,
280            connection_opts,
281            stop_token,
282            metrics,
283            my_relay,
284        } = opts;
285        let relay_client_builder = Self::create_relay_builder(url.clone(), connection_opts);
286        ActiveRelayActor {
287            prio_inbox,
288            inbox,
289            relay_datagrams_recv,
290            relay_datagrams_send,
291            url,
292            relay_client_builder,
293            is_home_relay: false,
294            inactive_timeout: Box::pin(time::sleep(RELAY_INACTIVE_CLEANUP_TIME)),
295            stop_token,
296            metrics,
297            my_relay,
298        }
299    }
300
301    fn create_relay_builder(
302        url: RelayUrl,
303        opts: RelayConnectionOptions,
304    ) -> relay::client::ClientBuilder {
305        let RelayConnectionOptions {
306            secret_key,
307            #[cfg(not(wasm_browser))]
308            dns_resolver,
309            proxy_url,
310            prefer_ipv6,
311            tls_config,
312            auth_token,
313        } = opts;
314
315        let mut builder = relay::client::ClientBuilder::new(
316            url,
317            secret_key,
318            #[cfg(not(wasm_browser))]
319            dns_resolver,
320        )
321        .tls_client_config(tls_config)
322        .address_family_selector(move || prefer_ipv6.load(Ordering::Relaxed));
323        if let Some(proxy_url) = proxy_url {
324            builder = builder.proxy_url(proxy_url);
325        }
326
327        if let Some(token) = auth_token {
328            builder = builder.auth_token(token);
329        }
330        builder
331    }
332
333    /// The main actor run loop.
334    ///
335    /// Primarily switches between the dialing and connected states.
336    async fn run(mut self) {
337        let mut backoff = Self::build_backoff();
338
339        while let Err(err) = self.run_once().await {
340            debug!("{err:#}");
341            let was_established = matches!(err, RelayConnectionError::Established { .. });
342            let last_failure = Some(Arc::new(RelayConnectionFailure::new(err)));
343            self.my_relay.set_status(
344                &self.url,
345                RelayConnectionState::Disconnected { last_failure },
346            );
347            if !was_established {
348                // If dialing failed, or if the relay connection failed before we received a pong,
349                // we wait an exponentially increasing time until we attempt to reconnect again.
350                let Some(delay) = backoff.next() else {
351                    debug!("retries exceeded");
352                    break;
353                };
354                debug!("retry in {delay:?}");
355                if !self.sleep_backoff(delay).await {
356                    break;
357                }
358            } else {
359                // If the relay connection remained established long enough so that we received a pong
360                // from the relay server, we reset the backoff and attempt to reconnect immediately.
361                backoff = Self::build_backoff();
362            }
363        }
364        debug!("exiting");
365    }
366
367    /// Waits out a reconnect backoff delay while still answering priority messages.
368    ///
369    /// Other active relays may query [`ActiveRelayPrioMessage::HasEndpointRoute`] on this
370    /// relay while it is backing off, e.g. when [`RelayActor`] is looking for an existing
371    /// relay connection to an endpoint. Answering immediately (with `false`, since a
372    /// disconnected relay cannot have an endpoint route) keeps that lookup from stalling
373    /// for however long is left of this relay's own unrelated backoff.
374    ///
375    /// The inbox and the inactivity timeout are served as in [`Self::run_dialing`], whose
376    /// dial can fail before it gets to them.
377    ///
378    /// Returns `false` if the actor should shut down instead of retrying.
379    async fn sleep_backoff(&mut self, delay: Duration) -> bool {
380        let sleep = time::sleep(delay);
381        tokio::pin!(sleep);
382        loop {
383            tokio::select! {
384                biased;
385                _ = self.stop_token.cancelled() => {
386                    debug!("Shutdown.");
387                    return false;
388                }
389                msg = self.prio_inbox.recv() => {
390                    let Some(msg) = msg else {
391                        warn!("Priority inbox closed, shutdown.");
392                        return false;
393                    };
394                    match msg {
395                        ActiveRelayPrioMessage::HasEndpointRoute(_peer, sender) => {
396                            sender.send(false).ok();
397                        }
398                    }
399                }
400                msg = self.inbox.recv() => {
401                    let Some(msg) = msg else {
402                        debug!("Inbox closed, shutdown.");
403                        return false;
404                    };
405                    self.handle_msg_while_disconnected(msg);
406                }
407                _ = &mut self.inactive_timeout, if !self.is_home_relay => {
408                    debug!(?RELAY_INACTIVE_CLEANUP_TIME, "Inactive, exiting.");
409                    return false;
410                }
411                _ = &mut sleep => return true,
412            }
413        }
414    }
415
416    /// Handles an inbox message while not connected to the relay server.
417    fn handle_msg_while_disconnected(&mut self, msg: ActiveRelayMessage) {
418        match msg {
419            ActiveRelayMessage::SetHomeRelay(is_home) => {
420                self.set_home_relay(is_home);
421            }
422            ActiveRelayMessage::CheckConnection { .. } => {}
423            #[cfg(test)]
424            ActiveRelayMessage::GetLocalAddr(sender) => {
425                sender.send(None).ok();
426            }
427            #[cfg(test)]
428            ActiveRelayMessage::PingServer(sender) => {
429                drop(sender);
430            }
431        }
432    }
433
434    fn build_backoff() -> impl Backoff {
435        ExponentialBuilder::new()
436            .with_min_delay(Duration::from_millis(10))
437            .with_max_delay(Duration::from_secs(16))
438            .with_jitter()
439            .without_max_times()
440            .build()
441    }
442
443    /// Attempt to connect to the relay, and run the connected actor loop.
444    ///
445    /// Returns `Ok(())` if the actor loop should shut down. Returns an error if dialing failed,
446    /// or if the relay connection failed while connected. In both cases, the connection should
447    /// be retried with a backoff.
448    #[allow(clippy::result_large_err)]
449    async fn run_once(&mut self) -> Result<(), RelayConnectionError> {
450        self.my_relay
451            .set_status(&self.url, RelayConnectionState::Connecting);
452        let client = match self.run_dialing().instrument(info_span!("dialing")).await {
453            Some(Ok(client)) => client,
454            Some(Err(err)) => {
455                self.metrics.relay_conns_failed.inc();
456                return Err(e!(RelayConnectionError::Dial, err));
457            }
458            None => return Ok(()),
459        };
460        self.my_relay
461            .set_status(&self.url, RelayConnectionState::Connected);
462        self.metrics.relay_conns_success.inc();
463        let res = self
464            .run_connected(client)
465            .instrument(info_span!("connected"))
466            .await;
467        self.metrics.relay_conns_closed.inc();
468        res
469    }
470
471    fn reset_inactive_timeout(&mut self) {
472        self.inactive_timeout
473            .as_mut()
474            .reset(Instant::now() + RELAY_INACTIVE_CLEANUP_TIME);
475    }
476
477    fn set_home_relay(&mut self, is_home: bool) {
478        let prev = std::mem::replace(&mut self.is_home_relay, is_home);
479        if self.is_home_relay != prev {
480            event!(
481                target: "iroh::_events::relay::home_changed",
482                Level::DEBUG,
483                url = %self.url,
484                home_relay = self.is_home_relay,
485            );
486        }
487    }
488
489    /// Actor loop when connecting to the relay server.
490    ///
491    /// Returns `None` if the actor needs to shut down.  Returns `Some(Ok(client))` when the
492    /// connection is established, and `Some(Err(err))` if dialing the relay failed.
493    async fn run_dialing(&mut self) -> Option<Result<iroh_relay::client::Client, DialError>> {
494        trace!("Actor loop: connecting to relay.");
495
496        // We regularly flush the relay_datagrams_send queue so it is not full of stale
497        // packets while reconnecting.  Those datagrams are dropped and the QUIC congestion
498        // controller will have to handle this (DISCO packets do not yet have retry).  This
499        // is not an ideal mechanism, an alternative approach would be to use
500        // e.g. ConcurrentQueue with force_push, though now you might still send very stale
501        // packets when eventually connected.  So perhaps this is a reasonable compromise.
502        let mut send_datagram_flush = time::interval(UNDELIVERABLE_DATAGRAM_TIMEOUT);
503        send_datagram_flush.set_missed_tick_behavior(MissedTickBehavior::Delay);
504        send_datagram_flush.reset(); // Skip the immediate interval
505
506        let dialing_fut = self.dial_relay();
507        tokio::pin!(dialing_fut);
508        loop {
509            tokio::select! {
510                biased;
511                _ = self.stop_token.cancelled() => {
512                    debug!("Shutdown.");
513                    break None;
514                }
515                msg = self.prio_inbox.recv() => {
516                    let Some(msg) = msg else {
517                        warn!("Priority inbox closed, shutdown.");
518                        break None;
519                    };
520                    match msg {
521                        ActiveRelayPrioMessage::HasEndpointRoute(_peer, sender) => {
522                            sender.send(false).ok();
523                        }
524                    }
525                }
526                res = &mut dialing_fut => {
527                    match res {
528                        Ok(client) => {
529                            break Some(Ok(client));
530                        }
531                        Err(err) => {
532                            break Some(Err(err));
533                        }
534                    }
535                }
536                msg = self.inbox.recv() => {
537                    let Some(msg) = msg else {
538                        debug!("Inbox closed, shutdown.");
539                        break None;
540                    };
541                    self.handle_msg_while_disconnected(msg);
542                }
543                _ = send_datagram_flush.tick() => {
544                    self.reset_inactive_timeout();
545                    let mut logged = false;
546                    while self.relay_datagrams_send.try_recv().is_ok() {
547                        if !logged {
548                            debug!(?UNDELIVERABLE_DATAGRAM_TIMEOUT, "Dropping datagrams to send.");
549                            logged = true;
550                        }
551                    }
552                }
553                _ = &mut self.inactive_timeout, if !self.is_home_relay => {
554                    debug!(?RELAY_INACTIVE_CLEANUP_TIME, "Inactive, exiting.");
555                    break None;
556                }
557            }
558        }
559    }
560
561    /// Returns a future which will complete once connected to the relay server.
562    ///
563    /// The future only completes once the connection is established and retries
564    /// connections.  It currently does not ever return `Err` as the retries continue
565    /// forever.
566    // This is using `impl Future` to return a future without a reference to self.
567    fn dial_relay(&self) -> impl Future<Output = Result<Client, DialError>> + use<> {
568        let client_builder = self.relay_client_builder.clone();
569        async move {
570            match time::timeout(CONNECT_TIMEOUT, client_builder.connect()).await {
571                Ok(Ok(client)) => Ok(client),
572                Ok(Err(err)) => Err(e!(DialError::Connect, err)),
573                Err(_) => Err(e!(DialError::Timeout {
574                    timeout: CONNECT_TIMEOUT
575                })),
576            }
577        }
578    }
579
580    /// Runs the actor loop when connected to a relay server.
581    ///
582    /// Returns `Ok` if the actor needs to shut down.  `Err` is returned if the connection
583    /// to the relay server is lost.
584    #[allow(clippy::result_large_err)]
585    async fn run_connected(
586        &mut self,
587        client: iroh_relay::client::Client,
588    ) -> Result<(), RelayConnectionError> {
589        trace!("Actor loop: connected to relay");
590        event!(
591            target: "iroh::_events::relay::connected",
592            Level::DEBUG,
593            url = %self.url,
594            home_relay = self.is_home_relay,
595        );
596
597        let (mut client_stream, client_sink) = client.split();
598        let mut client_sink = client_sink.sink_map_err(|e| e!(RunError::ClientStreamWrite, e));
599
600        let mut state = ConnectedRelayState {
601            ping_tracker: PingTracker::default(),
602            endpoints_present: BTreeSet::new(),
603            last_packet_src: None,
604            pong_pending: None,
605            established: false,
606            rate_limited: false,
607            #[cfg(test)]
608            test_pong: None,
609        };
610
611        // A buffer to pass through multiple datagrams at once as an optimisation.
612        let mut send_datagrams_buf = Vec::with_capacity(SEND_DATAGRAM_BATCH_SIZE);
613
614        // Regularly send pings so we know the connection is healthy.
615        // The first ping will be sent immediately.
616        let mut ping_interval = time::interval(PING_INTERVAL);
617        ping_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
618
619        let res = loop {
620            if let Some(data) = state.pong_pending.take() {
621                let fut = client_sink.send(ClientToRelayMsg::Pong(data));
622                self.run_sending(fut, &mut state, &mut client_stream)
623                    .await?;
624            }
625            tokio::select! {
626                biased;
627                _ = self.stop_token.cancelled() => {
628                    debug!("Shutdown.");
629                    break Ok(());
630                }
631                msg = self.prio_inbox.recv() => {
632                    let Some(msg) = msg else {
633                        warn!("Priority inbox closed, shutdown.");
634                        break Ok(());
635                    };
636                    match msg {
637                        ActiveRelayPrioMessage::HasEndpointRoute(peer, sender) => {
638                            let has_peer = state.endpoints_present.contains(&peer);
639                            sender.send(has_peer).ok();
640                        }
641                    }
642                }
643                _ = state.ping_tracker.timeout() => {
644                    break Err(e!(RunError::PingTimeout));
645                }
646                _ = ping_interval.tick() => {
647                    let data = state.ping_tracker.new_ping();
648                    let fut = client_sink.send(ClientToRelayMsg::Ping(data));
649                    self.run_sending(fut, &mut state, &mut client_stream).await?;
650                }
651                msg = self.inbox.recv() => {
652                    let Some(msg) = msg else {
653                        warn!("Inbox closed, shutdown.");
654                        break Ok(());
655                    };
656                    match msg {
657                        ActiveRelayMessage::SetHomeRelay(is_home) => {
658                            self.set_home_relay(is_home);
659                            // We are in `run_connected`, so if we just became the home
660                            // relay, publish `Connected` (the `RelayActor` only sets
661                            // `Connecting` on the URL change since it cannot know our
662                            // actual state).
663                            if is_home {
664                                self.my_relay
665                                    .set_status(&self.url, RelayConnectionState::Connected);
666                            }
667                        }
668                        ActiveRelayMessage::CheckConnection { local_ips } => {
669                            match client_stream.local_addr() {
670                                Some(addr) if local_ips.contains(&addr.ip()) => {
671                                    let data = state.ping_tracker.new_ping();
672                                    let fut = client_sink.send(ClientToRelayMsg::Ping(data));
673                                    self.run_sending(fut, &mut state, &mut client_stream).await?;
674                                }
675                                Some(_) => break Err(e!(RunError::LocalIpInvalid)),
676                                None => break Err(e!(RunError::LocalAddrMissing)),
677                            }
678                        }
679                        #[cfg(test)]
680                        ActiveRelayMessage::GetLocalAddr(sender) => {
681                            let addr = client_stream.local_addr();
682                            sender.send(addr).ok();
683                        }
684                        #[cfg(test)]
685                        ActiveRelayMessage::PingServer(sender) => {
686                            let data = rand::random();
687                            state.test_pong = Some((data, sender));
688                            let fut = client_sink.send(ClientToRelayMsg::Ping(data));
689                            self.run_sending(fut, &mut state, &mut client_stream).await?;
690                        }
691                    }
692                }
693                count = self.relay_datagrams_send.recv_many(
694                    &mut send_datagrams_buf,
695                    SEND_DATAGRAM_BATCH_SIZE,
696                ) => {
697                    if count == 0 {
698                        warn!("Datagram inbox closed, shutdown");
699                        break Ok(());
700                    };
701                    self.reset_inactive_timeout();
702                    // TODO(frando): can we avoid the clone here?
703                    let metrics = self.metrics.clone();
704                    let packet_iter = send_datagrams_buf.drain(..).map(|item| {
705                        metrics.send_relay.inc_by(item.datagrams.contents.len() as _);
706                        Ok(ClientToRelayMsg::Datagrams {
707                            dst_endpoint_id: item.remote_endpoint,
708                            datagrams: item.datagrams,
709                        })
710                    });
711                    let mut packet_stream = n0_future::stream::iter(packet_iter);
712                    let fut = client_sink.send_all(&mut packet_stream);
713                    self.run_sending(fut, &mut state, &mut client_stream).await?;
714                }
715                msg = client_stream.next() => {
716                    let Some(msg) = msg else {
717                        break Err(e!(RunError::StreamClosedServer));
718                    };
719                    match msg {
720                        Ok(msg) => {
721                            self.handle_relay_msg(msg, &mut state);
722                            // reset the ping timer, we have just received a message
723                            ping_interval.reset();
724                        },
725                        Err(err) => break Err(e!(RunError::ClientStreamRead, err)),
726                    }
727                }
728                _ = &mut self.inactive_timeout, if !self.is_home_relay => {
729                    debug!("Inactive for {RELAY_INACTIVE_CLEANUP_TIME:?}, exiting (running).");
730                    break Ok(());
731                }
732            }
733        };
734
735        if res.is_ok() {
736            self.run_closing(client_sink.close()).await;
737        }
738
739        res.map_err(|err| state.map_err(err))
740    }
741
742    /// Closes the relay connection, answering priority messages until it closes or
743    /// [`CLOSE_TIMEOUT`] passes.
744    async fn run_closing(&mut self, close: impl Future<Output = Result<(), RunError>>) {
745        let mut close = pin!(time::timeout(CLOSE_TIMEOUT, close));
746        loop {
747            tokio::select! {
748                biased;
749                res = &mut close => {
750                    match res {
751                        Ok(Ok(())) => {}
752                        Ok(Err(err)) => debug!("Failed to close client sink gracefully: {err:#}"),
753                        Err(_) => debug!("Relay server did not close within {CLOSE_TIMEOUT:?}."),
754                    }
755                    return;
756                }
757                Some(msg) = self.prio_inbox.recv() => {
758                    match msg {
759                        ActiveRelayPrioMessage::HasEndpointRoute(_peer, sender) => {
760                            sender.send(false).ok();
761                        }
762                    }
763                }
764            }
765        }
766    }
767
768    fn handle_relay_msg(&mut self, msg: RelayToClientMsg, state: &mut ConnectedRelayState) {
769        match msg {
770            RelayToClientMsg::Datagrams {
771                remote_endpoint_id,
772                datagrams,
773            } => {
774                trace!(len = datagrams.contents.len(), "received msg");
775                // If this is a new sender, register a route for this peer.
776                if state
777                    .last_packet_src
778                    .as_ref()
779                    .map(|p| *p != remote_endpoint_id)
780                    .unwrap_or(true)
781                {
782                    // Avoid map lookup with high throughput single peer.
783                    state.last_packet_src = Some(remote_endpoint_id);
784                    // Cap `endpoints_present` since the relay controls `remote_endpoint_id`;
785                    // omitting a peer beyond the cap only skips preferring this relay as a
786                    // send-side heuristic.
787                    if state.endpoints_present.len() < MAX_ENDPOINTS_PRESENT {
788                        state.endpoints_present.insert(remote_endpoint_id);
789                    }
790                }
791
792                if let Err(err) = self.relay_datagrams_recv.try_send(RelayRecvDatagram {
793                    url: self.url.clone(),
794                    src: remote_endpoint_id,
795                    datagrams,
796                }) {
797                    warn!("Dropping received relay packet: {err:#}");
798                }
799            }
800            RelayToClientMsg::EndpointGone(endpoint_id) => {
801                state.endpoints_present.remove(&endpoint_id);
802            }
803            RelayToClientMsg::Ping(data) => state.pong_pending = Some(data),
804            RelayToClientMsg::Pong(data) => {
805                #[cfg(test)]
806                {
807                    if let Some((expected_data, sender)) = state.test_pong.take() {
808                        if data == expected_data {
809                            sender.send(()).ok();
810                        } else {
811                            state.test_pong = Some((expected_data, sender));
812                        }
813                    }
814                }
815                state.ping_tracker.pong_received(data);
816                state.established = true;
817            }
818            RelayToClientMsg::Status(status) => match status {
819                Status::Healthy => info!("Relay server reports: {status}"),
820                Status::RateLimited => {
821                    warn!("{status}");
822                    // The relay sends this at most once per connection, but do not rely
823                    // on the remote for the metric to count connections.
824                    if !state.rate_limited {
825                        state.rate_limited = true;
826                        self.metrics.relay_conns_ratelimited.inc();
827                    }
828                }
829                _ => warn!("Relay server reports problem: {status}"),
830            },
831            RelayToClientMsg::Restarting { .. } => {
832                trace!("Ignoring {msg:?}")
833            }
834            // Deprecated variants, kept for backwards compatibility with older relay protocol versions.
835            RelayToClientMsg::Health { problem } => {
836                warn!("Relay server reports problem: {problem}");
837            }
838            _ => unreachable!(
839                "got unknown RelayToClientMsg but iroh is released in sync with iroh-relay"
840            ),
841        }
842    }
843
844    /// Run the actor main loop while sending to the relay server.
845    ///
846    /// While sending the actor should not read any inboxes which will give it more things
847    /// to send to the relay server.
848    ///
849    /// # Returns
850    ///
851    /// On `Err` the relay connection should be disconnected.  An `Ok` return means either
852    /// the actor should shut down, consult the [`ActiveRelayActor::stop_token`] and
853    /// [`ActiveRelayActor::inactive_timeout`] for this, or the send was successful.
854    #[instrument(name = "tx", skip_all)]
855    #[allow(clippy::result_large_err)]
856    async fn run_sending<T>(
857        &mut self,
858        sending_fut: impl Future<Output = Result<T, RunError>>,
859        state: &mut ConnectedRelayState,
860        client_stream: &mut iroh_relay::client::ClientStream,
861    ) -> Result<(), RelayConnectionError> {
862        // we use the same time as for our ping interval
863        let send_timeout = PING_INTERVAL;
864
865        let mut timeout = pin!(time::sleep(send_timeout));
866        let mut sending_fut = pin!(sending_fut);
867        let res = loop {
868            tokio::select! {
869                biased;
870                _ = self.stop_token.cancelled() => {
871                    break Ok(());
872                }
873                _ = &mut timeout => {
874                    break Err(e!(RunError::SendTimeout));
875                }
876                msg = self.prio_inbox.recv() => {
877                    let Some(msg) = msg else {
878                        warn!("Priority inbox closed, shutdown.");
879                        break Ok(());
880                    };
881                    match msg {
882                        ActiveRelayPrioMessage::HasEndpointRoute(peer, sender) => {
883                            let has_peer = state.endpoints_present.contains(&peer);
884                            sender.send(has_peer).ok();
885                        }
886                    }
887                }
888                res = &mut sending_fut => {
889                    match res {
890                        Ok(_) => break Ok(()),
891                        Err(err) => break Err(err),
892                    }
893                }
894                _ = state.ping_tracker.timeout() => {
895                    break Err(e!(RunError::PingTimeout));
896                }
897                // No need to read the inbox or datagrams to send.
898                msg = client_stream.next() => {
899                    let Some(msg) = msg else {
900                        break Err(e!(RunError::StreamClosedServer));
901                    };
902                    match msg {
903                        Ok(msg) => self.handle_relay_msg(msg, state),
904                        Err(err) => break Err(e!(RunError::ClientStreamRead, err)),
905                    }
906                }
907                _ = &mut self.inactive_timeout, if !self.is_home_relay => {
908                    debug!("Inactive for {RELAY_INACTIVE_CLEANUP_TIME:?}, exiting (sending).");
909                    break Ok(());
910                }
911            }
912        };
913        res.map_err(|err| state.map_err(err))
914    }
915}
916
917/// Shared state when the [`ActiveRelayActor`] is connected to a relay server.
918///
919/// Common state between [`ActiveRelayActor::run_connected`] and
920/// [`ActiveRelayActor::run_sending`].
921#[derive(Debug)]
922struct ConnectedRelayState {
923    /// Tracks pings we have sent, awaits pong replies.
924    ping_tracker: PingTracker,
925    /// Endpoints which are reachable via this relay server.
926    endpoints_present: BTreeSet<EndpointId>,
927    /// The [`EndpointId`] from whom we received the last packet.
928    ///
929    /// This is to avoid a slower lookup in the [`ConnectedRelayState::endpoints_present`] map
930    /// when we are only communicating to a single remote endpoint.
931    last_packet_src: Option<EndpointId>,
932    /// A pong we need to send ASAP.
933    pong_pending: Option<[u8; 8]>,
934    /// Whether the connection is to be considered established.
935    ///
936    /// This is set to `true` once a pong was received from the server.
937    established: bool,
938    /// Whether the relay reported that it is rate-limiting this connection.
939    ///
940    /// Used to count each affected connection only once.
941    rate_limited: bool,
942    #[cfg(test)]
943    test_pong: Option<([u8; 8], oneshot::Sender<()>)>,
944}
945
946impl ConnectedRelayState {
947    fn map_err(&self, error: RunError) -> RelayConnectionError {
948        if self.established {
949            e!(RelayConnectionError::Established, error)
950        } else {
951            e!(RelayConnectionError::Handshake, error)
952        }
953    }
954}
955
956pub(super) enum RelayActorMessage {
957    MaybeCloseRelaysOnRebind,
958    NetworkChange {
959        report: Report,
960    },
961    /// Trigger an immediate health check on all relay connections.
962    ///
963    /// Sent after a major network change to detect broken connections faster
964    /// using RTT-based timeouts instead of the default 5s ping timeout.
965    CheckConnectionAfterNetworkChange,
966}
967
968#[derive(Debug, Clone)]
969pub(crate) struct RelaySendItem {
970    /// The destination for the datagrams.
971    pub(crate) remote_endpoint: EndpointId,
972    /// The home relay of the remote endpoint.
973    pub(crate) url: RelayUrl,
974    /// One or more datagrams to send.
975    pub(crate) datagrams: Datagrams,
976}
977
978pub(super) struct RelayActor {
979    config: Config,
980    /// Queue on which to put received datagrams.
981    relay_datagram_recv_queue: mpsc::Sender<RelayRecvDatagram>,
982    /// The actors managing each currently used relay server.
983    ///
984    /// These actors will exit when they have any inactivity.  Otherwise they will keep
985    /// trying to maintain a connection to the relay server as needed.
986    active_relays: BTreeMap<RelayUrl, ActiveRelayHandle>,
987    /// The tasks for the [`ActiveRelayActor`]s in `active_relays` above.
988    active_relay_tasks: JoinSet<()>,
989    cancel_token: CancellationToken,
990}
991
992#[derive(Debug, Clone)]
993pub(crate) struct Config {
994    pub my_relay: HomeRelayWatch,
995    pub secret_key: SecretKey,
996    #[cfg(not(wasm_browser))]
997    pub dns_resolver: DnsResolver,
998    /// Proxy
999    pub proxy_url: Option<Url>,
1000    /// If the last net_report report, reports IPv6 to be available.
1001    pub ipv6_reported: Arc<AtomicBool>,
1002    pub tls_config: rustls::ClientConfig,
1003    pub metrics: Arc<SocketMetrics>,
1004    /// Per-relay configuration. Consulted when starting a connection to
1005    /// look up the auth token and any future per-relay options.
1006    pub relay_map: RelayMap,
1007}
1008
1009/// Connection state of the home relay.
1010///
1011/// Published via [`HomeRelayWatch`] so that [`Endpoint::online`] and the public
1012/// [`Endpoint::home_relay_status`] watcher can observe the connection state.
1013/// This type is `pub(crate)`; the public surface lives on
1014/// [`crate::endpoint::RelayStatus`], and this enum is intentionally free to
1015/// evolve without affecting the public API.
1016///
1017/// [`Endpoint::online`]: crate::Endpoint::online
1018/// [`Endpoint::home_relay_status`]: crate::Endpoint::home_relay_status
1019#[derive(Debug, Clone)]
1020pub(crate) enum RelayConnectionState {
1021    /// Dialing or performing the relay handshake.
1022    Connecting,
1023    /// Connected and handshaked.
1024    Connected,
1025    /// Not connected. Either the connection was lost after having been
1026    /// established, or an attempt to connect failed.
1027    ///
1028    /// `last_failure` carries the most recent connection failure, if any. The
1029    /// initial transition into this state (before any attempt has produced
1030    /// an error) carries `None`.
1031    ///
1032    /// The `Arc` is compared by pointer identity: each new failure produces
1033    /// a fresh allocation, so the watcher fires on every new error.
1034    Disconnected {
1035        last_failure: Option<Arc<RelayConnectionFailure>>,
1036    },
1037}
1038
1039impl RelayConnectionState {
1040    pub(crate) fn is_connected(&self) -> bool {
1041        matches!(self, Self::Connected)
1042    }
1043
1044    pub(crate) fn last_failure(&self) -> Option<&RelayConnectionFailure> {
1045        match self {
1046            Self::Disconnected { last_failure } => last_failure.as_deref(),
1047            _ => None,
1048        }
1049    }
1050}
1051
1052impl PartialEq for RelayConnectionState {
1053    fn eq(&self, other: &Self) -> bool {
1054        match (self, other) {
1055            (Self::Connecting, Self::Connecting) | (Self::Connected, Self::Connected) => true,
1056            (Self::Disconnected { last_failure: a }, Self::Disconnected { last_failure: b }) => {
1057                match (a, b) {
1058                    (None, None) => true,
1059                    (Some(a), Some(b)) => Arc::ptr_eq(a, b),
1060                    _ => false,
1061                }
1062            }
1063            _ => false,
1064        }
1065    }
1066}
1067
1068impl Eq for RelayConnectionState {}
1069
1070/// A failed attempt to connect to a relay server, or a lost connection.
1071///
1072/// Contains the type-erased error, together with whatever we could classify from it
1073/// while the concrete error type was still at hand.
1074#[derive(Debug)]
1075pub(crate) struct RelayConnectionFailure {
1076    error: AnyError,
1077    auth_denied_reason: Option<String>,
1078}
1079
1080impl RelayConnectionFailure {
1081    fn new(error: RelayConnectionError) -> Self {
1082        Self {
1083            auth_denied_reason: auth_denied_reason(&error).map(ToOwned::to_owned),
1084            error: AnyError::from(error),
1085        }
1086    }
1087
1088    /// Returns the type-erased error.
1089    pub(crate) fn error(&self) -> &AnyError {
1090        &self.error
1091    }
1092
1093    /// Returns the reason if the relay server denied our authentication.
1094    pub(crate) fn auth_denied_reason(&self) -> Option<&str> {
1095        self.auth_denied_reason.as_deref()
1096    }
1097}
1098
1099/// Returns the reason if `error` was caused by the relay server denying our authentication.
1100fn auth_denied_reason(error: &RelayConnectionError) -> Option<&str> {
1101    match error {
1102        RelayConnectionError::Dial {
1103            source:
1104                DialError::Connect {
1105                    source:
1106                        ConnectError::Handshake {
1107                            source: handshake::Error::ServerDeniedAuth { reason, .. },
1108                            ..
1109                        },
1110                    ..
1111                },
1112            ..
1113        } => Some(reason),
1114        _ => None,
1115    }
1116}
1117
1118/// Shared watchable for the home relay URL and connection status.
1119///
1120/// Owned by [`RelayActor`] and cloned into each [`ActiveRelayActor`].
1121///
1122/// # Write discipline
1123///
1124/// The [`RelayActor`] writes the URL (via [`Self::set`] and [`Self::clear`]).
1125/// Each [`ActiveRelayActor`] updates only the status (via [`Self::set_status`]),
1126/// which guards against stale writes: if another relay has become home since this actor
1127/// was designated, the write is silently dropped.
1128#[derive(Debug, Clone)]
1129pub(crate) struct HomeRelayWatch {
1130    inner: Watchable<Option<RelayStatus>>,
1131}
1132
1133impl Default for HomeRelayWatch {
1134    fn default() -> Self {
1135        Self {
1136            inner: Watchable::new(None),
1137        }
1138    }
1139}
1140
1141impl HomeRelayWatch {
1142    /// Set the home relay URL and status. Used by [`RelayActor`] on relay changes.
1143    fn set(&self, url: RelayUrl, state: RelayConnectionState) {
1144        let _ = self.inner.set(Some(RelayStatus::new(url, state)));
1145    }
1146
1147    /// Clear the home relay (no preferred relay). Used by [`RelayActor`].
1148    fn clear(&self) {
1149        let _ = self.inner.set(None);
1150    }
1151
1152    /// Update the status, but only if `url` is still the current home relay.
1153    ///
1154    /// This is the only write method [`ActiveRelayActor`] should use. It prevents a
1155    /// demoted actor from overwriting a newer home relay's status: the [`RelayActor`]
1156    /// updates the URL in the watchable *before* sending `SetHomeRelay(false)`, so by
1157    /// the time the old actor tries to write, the URL no longer matches.
1158    fn set_status(&self, url: &RelayUrl, state: RelayConnectionState) {
1159        if self.inner.get().as_ref().map(RelayStatus::url) == Some(url) {
1160            let _ = self.inner.set(Some(RelayStatus::new(url.clone(), state)));
1161        }
1162    }
1163
1164    fn get(&self) -> Option<RelayStatus> {
1165        self.inner.get()
1166    }
1167
1168    pub(crate) fn watch(&self) -> n0_watcher::Direct<Option<RelayStatus>> {
1169        self.inner.watch()
1170    }
1171}
1172
1173impl RelayActor {
1174    pub(super) fn new(
1175        config: Config,
1176        relay_datagram_recv_queue: mpsc::Sender<RelayRecvDatagram>,
1177        cancel_token: CancellationToken,
1178    ) -> Self {
1179        Self {
1180            config,
1181            relay_datagram_recv_queue,
1182            active_relays: Default::default(),
1183            active_relay_tasks: JoinSet::new(),
1184            cancel_token,
1185        }
1186    }
1187
1188    pub(super) async fn run(
1189        mut self,
1190        mut receiver: mpsc::Receiver<RelayActorMessage>,
1191        mut datagram_send_channel: mpsc::Receiver<RelaySendItem>,
1192    ) {
1193        // When this future is present, it is sending pending datagrams to an
1194        // ActiveRelayActor.  We can not process further datagrams during this time.
1195        let mut datagram_send_fut = std::pin::pin!(MaybeFuture::None);
1196
1197        loop {
1198            tokio::select! {
1199                biased;
1200                _ = self.cancel_token.cancelled() => {
1201                    debug!("shutting down");
1202                    break;
1203                }
1204                Some(res) = self.active_relay_tasks.join_next() => {
1205                    log_active_relay_task_result(res);
1206                    self.reap_active_relays();
1207                }
1208                msg = receiver.recv() => {
1209                    let Some(msg) = msg else {
1210                        debug!("Inbox dropped, shutting down.");
1211                        break;
1212                    };
1213                    let cancel_token = self.cancel_token.child_token();
1214                    cancel_token.run_until_cancelled(self.handle_msg(msg)).await;
1215                }
1216                // Only poll for new datagrams if we are not blocked on sending them.
1217                item = datagram_send_channel.recv(), if datagram_send_fut.is_none() => {
1218                    let Some(item) = item else {
1219                        debug!("Datagram send channel dropped, shutting down.");
1220                        break;
1221                    };
1222                    let token = self.cancel_token.child_token();
1223                    if let Some(Some(fut)) = token.run_until_cancelled(
1224                        self.try_send_datagram(item)
1225                    ).await {
1226                        datagram_send_fut.as_mut().set_future(fut);
1227                    }
1228                }
1229                // Only poll this future if it is in use.
1230                _ = &mut datagram_send_fut, if datagram_send_fut.is_some() => {
1231                    datagram_send_fut.as_mut().set_none();
1232                }
1233            }
1234        }
1235
1236        // try shutdown
1237        if time::timeout(Duration::from_secs(3), self.close_all_active_relays())
1238            .await
1239            .is_err()
1240        {
1241            warn!("Failed to shut down all ActiveRelayActors");
1242        }
1243    }
1244
1245    async fn handle_msg(&mut self, msg: RelayActorMessage) {
1246        match msg {
1247            RelayActorMessage::NetworkChange { report } => {
1248                self.on_network_change(report).await;
1249            }
1250            RelayActorMessage::MaybeCloseRelaysOnRebind => {
1251                self.maybe_close_relays_on_rebind().await;
1252            }
1253            RelayActorMessage::CheckConnectionAfterNetworkChange => {
1254                self.check_connection_after_network_change().await;
1255            }
1256        }
1257    }
1258
1259    /// Sends datagrams to the correct [`ActiveRelayActor`], or returns a future.
1260    ///
1261    /// If the datagram can not be sent immediately, because the destination channel is
1262    /// full, a future is returned that will complete once the datagrams have been sent to
1263    /// the [`ActiveRelayActor`].
1264    async fn try_send_datagram(
1265        &mut self,
1266        item: RelaySendItem,
1267    ) -> Option<impl Future<Output = ()> + use<>> {
1268        let url = item.url.clone();
1269        let handle = self
1270            .active_relay_handle_for_endpoint(&item.url, &item.remote_endpoint)
1271            .await;
1272        match handle.datagrams_send_queue.try_send(item) {
1273            Ok(()) => None,
1274            Err(mpsc::error::TrySendError::Closed(_)) => {
1275                warn!(?url, "Dropped datagram(s): ActiveRelayActor closed.");
1276                None
1277            }
1278            Err(mpsc::error::TrySendError::Full(item)) => {
1279                let sender = handle.datagrams_send_queue.clone();
1280                let fut = async move {
1281                    if sender.send(item).await.is_err() {
1282                        warn!(?url, "Dropped datagram(s): ActiveRelayActor closed.");
1283                    }
1284                };
1285                Some(fut)
1286            }
1287        }
1288    }
1289
1290    async fn on_network_change(&mut self, report: Report) {
1291        let prev = self.config.my_relay.get();
1292        let prev_url = prev.as_ref().map(RelayStatus::url);
1293        if report.preferred_relay.as_ref() == prev_url {
1294            // No change.
1295            return;
1296        }
1297
1298        if let Some(relay_url) = report.preferred_relay {
1299            self.config.metrics.relay_home_change.inc();
1300
1301            // On change, notify all currently connected relay servers and
1302            // start connecting to our home relay if we are not already.
1303            info!("home is now relay {}, was {:?}", relay_url, prev_url);
1304            // Publish `Connecting` initially. If an `ActiveRelayActor` already
1305            // exists for this URL it will republish its actual status (e.g.
1306            // `Connected`) when it receives the `SetHomeRelay(true)` message
1307            // sent below.
1308            self.config
1309                .my_relay
1310                .set(relay_url.clone(), RelayConnectionState::Connecting);
1311            self.set_home_relay(Some(relay_url)).await;
1312        } else {
1313            self.config.my_relay.clear();
1314            self.set_home_relay(None).await;
1315        }
1316    }
1317
1318    async fn set_home_relay(&mut self, home_url: Option<RelayUrl>) {
1319        let home_url_ref = home_url.as_ref();
1320        n0_future::join_all(self.active_relays.iter().map(|(url, handle)| async move {
1321            let is_preferred = Some(url) == home_url_ref;
1322            handle
1323                .inbox_addr
1324                .send(ActiveRelayMessage::SetHomeRelay(is_preferred))
1325                .await
1326                .ok()
1327        }))
1328        .await;
1329        // Ensure we have an ActiveRelayActor for the current home relay.
1330        if let Some(home_url) = home_url {
1331            self.active_relay_handle(home_url);
1332        }
1333    }
1334
1335    /// Returns the handle for the [`ActiveRelayActor`] to reach `remote_endpoint`.
1336    ///
1337    /// The endpoint is expected to be reachable on `url`, but if no [`ActiveRelayActor`] for
1338    /// `url` exists but another existing [`ActiveRelayActor`] already knows about the endpoint,
1339    /// that other endpoint is used.
1340    async fn active_relay_handle_for_endpoint(
1341        &mut self,
1342        url: &RelayUrl,
1343        remote_endpoint: &EndpointId,
1344    ) -> ActiveRelayHandle {
1345        if let Some(handle) = self.active_relays.get(url) {
1346            return handle.clone();
1347        }
1348
1349        let mut found_relay: Option<RelayUrl> = None;
1350        // If we don't have an open connection to the remote endpoint's home relay, see if
1351        // we have an open connection to a relay endpoint where we'd heard from that peer
1352        // already.  E.g. maybe they dialed our home relay recently.
1353        {
1354            // Futures which return Some(RelayUrl) if the relay knows about the remote endpoint.
1355            let check_futs = self.active_relays.iter().map(|(url, handle)| async move {
1356                let (tx, rx) = oneshot::channel();
1357                handle
1358                    .prio_inbox_addr
1359                    .send(ActiveRelayPrioMessage::HasEndpointRoute(
1360                        *remote_endpoint,
1361                        tx,
1362                    ))
1363                    .await
1364                    .ok();
1365                match rx.await {
1366                    Ok(true) => Some(url.clone()),
1367                    _ => None,
1368                }
1369            });
1370            let mut futures = FuturesUnorderedBounded::from_iter(check_futs);
1371            while let Some(maybe_url) = futures.next().await {
1372                if maybe_url.is_some() {
1373                    found_relay = maybe_url;
1374                    break;
1375                }
1376            }
1377        }
1378        let url = found_relay.unwrap_or(url.clone());
1379        self.active_relay_handle(url)
1380    }
1381
1382    /// Returns the handle of the [`ActiveRelayActor`].
1383    fn active_relay_handle(&mut self, url: RelayUrl) -> ActiveRelayHandle {
1384        match self.active_relays.get(&url) {
1385            Some(e) => e.clone(),
1386            None => {
1387                let handle = self.start_active_relay(url.clone());
1388                if Some(&url) == self.config.my_relay.get().as_ref().map(RelayStatus::url)
1389                    && let Err(err) = handle
1390                        .inbox_addr
1391                        .try_send(ActiveRelayMessage::SetHomeRelay(true))
1392                {
1393                    error!("Home relay not set, send to new actor failed: {err:#}.");
1394                }
1395                self.active_relays.insert(url, handle.clone());
1396                self.log_active_relay();
1397                handle
1398            }
1399        }
1400    }
1401
1402    fn start_active_relay(&mut self, url: RelayUrl) -> ActiveRelayHandle {
1403        debug!(?url, "Adding relay connection");
1404
1405        let auth_token = self
1406            .config
1407            .relay_map
1408            .get(&url)
1409            .and_then(|cfg| cfg.auth_token.clone());
1410        let connection_opts = RelayConnectionOptions {
1411            secret_key: self.config.secret_key.clone(),
1412            #[cfg(not(wasm_browser))]
1413            dns_resolver: self.config.dns_resolver.clone(),
1414            proxy_url: self.config.proxy_url.clone(),
1415            prefer_ipv6: self.config.ipv6_reported.clone(),
1416            tls_config: self.config.tls_config.clone(),
1417            auth_token,
1418        };
1419
1420        // TODO: Replace 64 with PER_CLIENT_SEND_QUEUE_DEPTH once that's unused
1421        let (send_datagram_tx, send_datagram_rx) = mpsc::channel(64);
1422        let (prio_inbox_tx, prio_inbox_rx) = mpsc::channel(32);
1423        let (inbox_tx, inbox_rx) = mpsc::channel(64);
1424        let span = info_span!("active-relay", %url);
1425        let opts = ActiveRelayActorOptions {
1426            url,
1427            prio_inbox_: prio_inbox_rx,
1428            inbox: inbox_rx,
1429            relay_datagrams_send: send_datagram_rx,
1430            relay_datagrams_recv: self.relay_datagram_recv_queue.clone(),
1431            connection_opts,
1432            stop_token: self.cancel_token.child_token(),
1433            metrics: self.config.metrics.clone(),
1434            my_relay: self.config.my_relay.clone(),
1435        };
1436        let actor = ActiveRelayActor::new(opts);
1437        self.active_relay_tasks.spawn(
1438            async move {
1439                actor.run().await;
1440            }
1441            .instrument(span),
1442        );
1443        let handle = ActiveRelayHandle {
1444            prio_inbox_addr: prio_inbox_tx,
1445            inbox_addr: inbox_tx,
1446            datagrams_send_queue: send_datagram_tx,
1447        };
1448        self.log_active_relay();
1449        handle
1450    }
1451
1452    /// Triggers an immediate health check on all relay connections after a network change.
1453    async fn check_connection_after_network_change(&mut self) {
1454        self.send_check_connection().await;
1455    }
1456
1457    /// Closes the relay connections not originating from a local IP address.
1458    ///
1459    /// Called in response to a rebind, any relay connection originating from an address
1460    /// that's not known to be currently a local IP address should be closed.  All the other
1461    /// relay connections are pinged.
1462    async fn maybe_close_relays_on_rebind(&mut self) {
1463        self.send_check_connection().await;
1464        self.log_active_relay();
1465    }
1466
1467    /// Sends a [`ActiveRelayMessage::CheckConnection`] to all active relays with current
1468    /// local IPs.
1469    async fn send_check_connection(&self) {
1470        #[cfg(not(wasm_browser))]
1471        let ifs = interfaces::State::new().await;
1472        #[cfg(not(wasm_browser))]
1473        let local_ips: Vec<_> = ifs
1474            .interfaces
1475            .values()
1476            .flat_map(|netif| netif.addrs())
1477            .map(|ipnet| ipnet.addr())
1478            .collect();
1479        // In browsers, we don't have this information. This will do the right thing
1480        // in the ActiveRelayActor, though.
1481        #[cfg(wasm_browser)]
1482        let local_ips = Vec::new();
1483        let send_futs = self.active_relays.values().map(|handle| {
1484            let local_ips = local_ips.clone();
1485            async move {
1486                handle
1487                    .inbox_addr
1488                    .send(ActiveRelayMessage::CheckConnection { local_ips })
1489                    .await
1490                    .ok();
1491            }
1492        });
1493        n0_future::join_all(send_futs).await;
1494    }
1495
1496    /// Cleans up [`ActiveRelayActor`]s which have stopped running.
1497    fn reap_active_relays(&mut self) {
1498        self.active_relays
1499            .retain(|_url, handle| !handle.inbox_addr.is_closed());
1500
1501        // Make sure home relay exists
1502        if let Some(status) = self.config.my_relay.get() {
1503            self.active_relay_handle(status.url().clone());
1504        }
1505        self.log_active_relay();
1506    }
1507
1508    /// Stops all [`ActiveRelayActor`]s and awaits for them to finish.
1509    async fn close_all_active_relays(&mut self) {
1510        self.cancel_token.cancel();
1511        let mut tasks = std::mem::take(&mut self.active_relay_tasks);
1512        // Drain instead of `join_all`, which panics on any `JoinError`.
1513        while let Some(res) = tasks.join_next().await {
1514            log_active_relay_task_result(res);
1515        }
1516
1517        self.log_active_relay();
1518    }
1519
1520    fn log_active_relay(&self) {
1521        debug!("{} active relay conns{}", self.active_relays.len(), {
1522            let mut s = String::new();
1523            if !self.active_relays.is_empty() {
1524                s += ":";
1525                for endpoint in self.active_relay_sorted() {
1526                    s += &format!(" relay-{endpoint}");
1527                }
1528            }
1529            s
1530        });
1531    }
1532
1533    fn active_relay_sorted(&self) -> impl Iterator<Item = RelayUrl> + use<> {
1534        let mut ids: Vec<_> = self.active_relays.keys().cloned().collect();
1535        ids.sort();
1536
1537        ids.into_iter()
1538    }
1539}
1540
1541/// Reports how one [`ActiveRelayActor`] task ended, in the run loop and on shutdown.
1542fn log_active_relay_task_result(res: Result<(), JoinError>) {
1543    match res {
1544        Ok(()) => (),
1545        Err(err) if err.is_panic() => error!("ActiveRelayActor task panicked: {err:#?}"),
1546        Err(err) if err.is_cancelled() => error!("ActiveRelayActor cancelled: {err:#?}"),
1547        Err(err) => error!("ActiveRelayActor failed: {err:#?}"),
1548    }
1549}
1550
1551/// Handle to one [`ActiveRelayActor`].
1552#[derive(Debug, Clone)]
1553struct ActiveRelayHandle {
1554    prio_inbox_addr: mpsc::Sender<ActiveRelayPrioMessage>,
1555    inbox_addr: mpsc::Sender<ActiveRelayMessage>,
1556    datagrams_send_queue: mpsc::Sender<RelaySendItem>,
1557}
1558
1559/// A single datagram received from a relay server.
1560///
1561/// This could be either a QUIC or DISCO packet.
1562#[derive(Debug)]
1563pub(crate) struct RelayRecvDatagram {
1564    pub(crate) url: RelayUrl,
1565    pub(crate) src: EndpointId,
1566    pub(crate) datagrams: Datagrams,
1567}
1568
1569#[cfg(test)]
1570mod tests {
1571    use std::{
1572        sync::{Arc, atomic::AtomicBool},
1573        time::Duration,
1574    };
1575
1576    use iroh_base::{EndpointId, RelayUrl, SecretKey};
1577    use iroh_relay::{
1578        PingTracker,
1579        protos::relay::Datagrams,
1580        tls::{CaTlsConfig, default_provider},
1581    };
1582    use n0_error::{AnyError as Error, Result, StackResultExt, StdResultExt};
1583    use n0_tracing_test::traced_test;
1584    use tokio::sync::{mpsc, oneshot};
1585    use tokio_util::{sync::CancellationToken, task::AbortOnDropHandle};
1586    use tracing::{Instrument, info, info_span};
1587
1588    use super::{
1589        ActiveRelayActor, ActiveRelayActorOptions, ActiveRelayHandle, ActiveRelayMessage,
1590        ActiveRelayPrioMessage, Config, RELAY_INACTIVE_CLEANUP_TIME, RelayActor, RelayActorMessage,
1591        RelayConnectionOptions, RelayMap, RelayRecvDatagram, RelaySendItem, Report,
1592        UNDELIVERABLE_DATAGRAM_TIMEOUT,
1593    };
1594    use crate::{dns::DnsResolver, metrics::SocketMetrics, test_utils};
1595
1596    /// Abort stands in for the runtime drop that triggers this in the wild:
1597    /// `join_next` yields a cancelled `JoinError` either way.
1598    #[tokio::test]
1599    #[traced_test]
1600    async fn close_all_active_relays_survives_a_cancelled_task() {
1601        let (relay_datagram_recv_queue, _recv_rx) = mpsc::channel(1);
1602        let config = Config {
1603            my_relay: Default::default(),
1604            secret_key: SecretKey::from_bytes(&[0u8; 32]),
1605            dns_resolver: DnsResolver::new(),
1606            proxy_url: None,
1607            ipv6_reported: Arc::new(AtomicBool::new(false)),
1608            tls_config: CaTlsConfig::insecure_skip_verify()
1609                .client_config(default_provider())
1610                .expect("infallible"),
1611            metrics: Default::default(),
1612            relay_map: RelayMap::empty(),
1613        };
1614        let mut actor =
1615            RelayActor::new(config, relay_datagram_recv_queue, CancellationToken::new());
1616
1617        let handle = actor.active_relay_tasks.spawn(std::future::pending::<()>());
1618        handle.abort();
1619
1620        // Panicked with `join_all`.
1621        actor.close_all_active_relays().await;
1622
1623        assert!(actor.active_relay_tasks.is_empty());
1624        assert!(logs_contain("ActiveRelayActor cancelled"));
1625    }
1626
1627    #[tokio::test]
1628    async fn no_preferred_relay_demotes_home_relay() {
1629        let (relay_datagram_recv_queue, _recv_rx) = mpsc::channel(1);
1630        let config = Config {
1631            my_relay: Default::default(),
1632            secret_key: SecretKey::from_bytes(&[0u8; 32]),
1633            dns_resolver: DnsResolver::new(),
1634            proxy_url: None,
1635            ipv6_reported: Arc::new(AtomicBool::new(false)),
1636            tls_config: CaTlsConfig::insecure_skip_verify()
1637                .client_config(default_provider())
1638                .expect("infallible"),
1639            metrics: Default::default(),
1640            relay_map: RelayMap::empty(),
1641        };
1642        let mut actor =
1643            RelayActor::new(config, relay_datagram_recv_queue, CancellationToken::new());
1644        let url: RelayUrl = "https://relay.invalid".parse().unwrap();
1645        let (prio_inbox_addr, _prio_inbox_rx) = mpsc::channel(1);
1646        let (inbox_addr, mut inbox_rx) = mpsc::channel(1);
1647        let (datagrams_send_queue, _datagrams_send_rx) = mpsc::channel(1);
1648        let handle = ActiveRelayHandle {
1649            prio_inbox_addr,
1650            inbox_addr,
1651            datagrams_send_queue,
1652        };
1653        actor.active_relays.insert(url.clone(), handle);
1654
1655        let report = Report {
1656            preferred_relay: Some(url),
1657            ..Default::default()
1658        };
1659        actor.on_network_change(report).await;
1660        let msg = inbox_rx.try_recv();
1661        assert!(
1662            matches!(msg, Ok(ActiveRelayMessage::SetHomeRelay(true))),
1663            "{msg:?}"
1664        );
1665
1666        actor.on_network_change(Report::default()).await;
1667        assert_eq!(actor.config.my_relay.get(), None);
1668        let msg = inbox_rx.try_recv();
1669        assert!(
1670            matches!(msg, Ok(ActiveRelayMessage::SetHomeRelay(false))),
1671            "{msg:?}"
1672        );
1673    }
1674
1675    /// Starts a new [`ActiveRelayActor`].
1676    #[allow(clippy::too_many_arguments)]
1677    fn start_active_relay_actor(
1678        secret_key: SecretKey,
1679        stop_token: CancellationToken,
1680        url: RelayUrl,
1681        prio_inbox_rx: mpsc::Receiver<ActiveRelayPrioMessage>,
1682        inbox_rx: mpsc::Receiver<ActiveRelayMessage>,
1683        relay_datagrams_send: mpsc::Receiver<RelaySendItem>,
1684        relay_datagrams_recv: mpsc::Sender<RelayRecvDatagram>,
1685        metrics: Arc<SocketMetrics>,
1686        span: tracing::Span,
1687    ) -> AbortOnDropHandle<()> {
1688        let opts = ActiveRelayActorOptions {
1689            url,
1690            prio_inbox_: prio_inbox_rx,
1691            inbox: inbox_rx,
1692            relay_datagrams_send,
1693            relay_datagrams_recv,
1694            connection_opts: RelayConnectionOptions {
1695                secret_key,
1696                dns_resolver: DnsResolver::new(),
1697                proxy_url: None,
1698                prefer_ipv6: Arc::new(AtomicBool::new(true)),
1699                tls_config: CaTlsConfig::insecure_skip_verify()
1700                    .client_config(default_provider())
1701                    .expect("infallible"),
1702                auth_token: None,
1703            },
1704            stop_token,
1705            metrics,
1706            my_relay: Default::default(),
1707        };
1708        let task = tokio::spawn(ActiveRelayActor::new(opts).run().instrument(span));
1709        AbortOnDropHandle::new(task)
1710    }
1711
1712    /// Starts an [`ActiveRelayActor`] as an "iroh echo endpoint".
1713    ///
1714    /// This actor will connect to the relay server, pretending to be an iroh endpoint, and echo
1715    /// back any datagram it receives from the relay.  This is used by the
1716    /// [`ActiveRelayActor`] under test to check connectivity works.
1717    fn start_echo_endpoint(relay_url: RelayUrl) -> (EndpointId, AbortOnDropHandle<()>) {
1718        let secret_key = SecretKey::from_bytes(&[8u8; 32]);
1719        let (recv_datagram_tx, mut recv_datagram_rx) = mpsc::channel(16);
1720        let (send_datagram_tx, send_datagram_rx) = mpsc::channel(16);
1721        let (prio_inbox_tx, prio_inbox_rx) = mpsc::channel(8);
1722        let (inbox_tx, inbox_rx) = mpsc::channel(16);
1723        let cancel_token = CancellationToken::new();
1724        let actor_task = start_active_relay_actor(
1725            secret_key.clone(),
1726            cancel_token.clone(),
1727            relay_url.clone(),
1728            prio_inbox_rx,
1729            inbox_rx,
1730            send_datagram_rx,
1731            recv_datagram_tx,
1732            Default::default(),
1733            info_span!("echo-endpoint"),
1734        );
1735        let echo_task = tokio::spawn({
1736            let relay_url = relay_url.clone();
1737            async move {
1738                loop {
1739                    let datagram = recv_datagram_rx.recv().await;
1740                    if let Some(recv) = datagram {
1741                        let RelayRecvDatagram {
1742                            url: _,
1743                            src,
1744                            datagrams,
1745                        } = recv;
1746                        info!(from = %src.fmt_short(), "Received datagram");
1747                        let send = RelaySendItem {
1748                            remote_endpoint: src,
1749                            url: relay_url.clone(),
1750                            datagrams,
1751                        };
1752                        send_datagram_tx.send(send).await.ok();
1753                    }
1754                }
1755            }
1756            .instrument(info_span!("echo-task"))
1757        });
1758        let echo_task = AbortOnDropHandle::new(echo_task);
1759        let supervisor_task = tokio::spawn(async move {
1760            let _guard = cancel_token.drop_guard();
1761            // move the inboxes here so it is not dropped, as this stops the actor.
1762            let _prio_inbox_tx = prio_inbox_tx;
1763            let _inbox_tx = inbox_tx;
1764            tokio::select! {
1765                biased;
1766                _ = actor_task => (),
1767                _ = echo_task => (),
1768            };
1769        });
1770        let supervisor_task = AbortOnDropHandle::new(supervisor_task);
1771        (secret_key.public(), supervisor_task)
1772    }
1773
1774    /// Sends a message to the echo endpoint, receives the response.
1775    ///
1776    /// This takes care of retry and timeout.  Because we don't know when both the
1777    /// endpoint-under-test and the echo endpoint will be ready and datagrams aren't queued to send
1778    /// forever, we have to retry a few times.
1779    async fn send_recv_echo(
1780        item: RelaySendItem,
1781        tx: &mpsc::Sender<RelaySendItem>,
1782        rx: &mut mpsc::Receiver<RelayRecvDatagram>,
1783    ) -> Result<()> {
1784        tokio::time::timeout(Duration::from_secs(10), async move {
1785            loop {
1786                let res = tokio::time::timeout(UNDELIVERABLE_DATAGRAM_TIMEOUT, async {
1787                    tx.send(item.clone()).await.std_context("send item")?;
1788                    let RelayRecvDatagram {
1789                        url: _,
1790                        src: _,
1791                        datagrams,
1792                    } = rx.recv().await.unwrap();
1793
1794                    assert_eq!(datagrams, item.datagrams);
1795
1796                    Ok::<_, Error>(())
1797                })
1798                .await;
1799                if res.is_ok() {
1800                    break;
1801                }
1802            }
1803        })
1804        .await
1805        .expect("overall timeout exceeded");
1806        Ok(())
1807    }
1808
1809    /// Starts a [`RelayActor`] and returns its inbox, both datagram queues and its task.
1810    fn setup_relay_actor() -> (
1811        mpsc::Sender<RelayActorMessage>,
1812        mpsc::Sender<RelaySendItem>,
1813        mpsc::Receiver<RelayRecvDatagram>,
1814        AbortOnDropHandle<()>,
1815    ) {
1816        let (datagram_recv_tx, datagram_recv_rx) = mpsc::channel(16);
1817        let config = Config {
1818            my_relay: Default::default(),
1819            secret_key: SecretKey::from_bytes(&[1u8; 32]),
1820            dns_resolver: DnsResolver::new(),
1821            proxy_url: None,
1822            ipv6_reported: Arc::new(AtomicBool::new(false)),
1823            tls_config: CaTlsConfig::insecure_skip_verify()
1824                .client_config(default_provider())
1825                .expect("infallible"),
1826            metrics: Default::default(),
1827            relay_map: RelayMap::empty(),
1828        };
1829        let actor = RelayActor::new(config, datagram_recv_tx, CancellationToken::new());
1830        let (msg_tx, msg_rx) = mpsc::channel(128);
1831        let (datagram_send_tx, datagram_send_rx) = mpsc::channel(256);
1832        let task = AbortOnDropHandle::new(tokio::spawn(actor.run(msg_rx, datagram_send_rx)));
1833        (msg_tx, datagram_send_tx, datagram_recv_rx, task)
1834    }
1835
1836    #[tokio::test]
1837    #[traced_test]
1838    async fn test_active_relay_reconnect() -> Result {
1839        let (_relay_map, relay_url, _server) = test_utils::run_relay_server().await?;
1840        let (peer_endpoint, _echo_endpoint_task) = start_echo_endpoint(relay_url.clone());
1841
1842        let secret_key = SecretKey::from_bytes(&[1u8; 32]);
1843        let (datagram_recv_tx, mut datagram_recv_rx) = mpsc::channel(16);
1844        let (send_datagram_tx, send_datagram_rx) = mpsc::channel(16);
1845        let (_prio_inbox_tx, prio_inbox_rx) = mpsc::channel(8);
1846        let (inbox_tx, inbox_rx) = mpsc::channel(16);
1847        let cancel_token = CancellationToken::new();
1848        let metrics = Arc::new(SocketMetrics::default());
1849        let task = start_active_relay_actor(
1850            secret_key,
1851            cancel_token.clone(),
1852            relay_url.clone(),
1853            prio_inbox_rx,
1854            inbox_rx,
1855            send_datagram_rx,
1856            datagram_recv_tx.clone(),
1857            metrics.clone(),
1858            info_span!("actor-under-test"),
1859        );
1860
1861        // Send a datagram to our echo endpoint.
1862        info!("first echo");
1863        let hello_send_item = RelaySendItem {
1864            remote_endpoint: peer_endpoint,
1865            url: relay_url.clone(),
1866            datagrams: Datagrams::from(b"hello"),
1867        };
1868        send_recv_echo(
1869            hello_send_item.clone(),
1870            &send_datagram_tx,
1871            &mut datagram_recv_rx,
1872        )
1873        .await?;
1874
1875        // Now ask to check the connection, triggering a ping but no reconnect.
1876        let (tx, rx) = oneshot::channel();
1877        inbox_tx
1878            .send(ActiveRelayMessage::GetLocalAddr(tx))
1879            .await
1880            .std_context("send get local addr msg")?;
1881
1882        let local_addr = rx
1883            .await
1884            .std_context("wait for local addr msg")?
1885            .context("no local addr")?;
1886        info!(?local_addr, "check connection with addr");
1887        inbox_tx
1888            .send(ActiveRelayMessage::CheckConnection {
1889                local_ips: vec![local_addr.ip()],
1890            })
1891            .await
1892            .std_context("send check connection message")?;
1893
1894        // Sync the ActiveRelayActor. Ping blocks it and we want to be sure it has handled
1895        // another inbox message before continuing.
1896        let (tx, rx) = oneshot::channel();
1897        inbox_tx
1898            .send(ActiveRelayMessage::GetLocalAddr(tx))
1899            .await
1900            .std_context("send get local addr msg")?;
1901        rx.await.std_context("recv send local addr msg")?;
1902
1903        // Echo should still work.
1904        info!("second echo");
1905        send_recv_echo(
1906            hello_send_item.clone(),
1907            &send_datagram_tx,
1908            &mut datagram_recv_rx,
1909        )
1910        .await?;
1911
1912        // Now ask to check the connection, this will reconnect without pinging because we
1913        // do not supply any "valid" local IP addresses.
1914        info!("check connection");
1915        inbox_tx
1916            .send(ActiveRelayMessage::CheckConnection {
1917                local_ips: Vec::new(),
1918            })
1919            .await
1920            .std_context("send check connection msg")?;
1921
1922        // Give some time to reconnect, mostly to sort logs rather than functional.
1923        tokio::time::sleep(Duration::from_millis(10)).await;
1924
1925        // Echo should still work.
1926        info!("third echo");
1927        send_recv_echo(
1928            hello_send_item.clone(),
1929            &send_datagram_tx,
1930            &mut datagram_recv_rx,
1931        )
1932        .await?;
1933
1934        // Shut down the actor.
1935        cancel_token.cancel();
1936        task.await.std_context("wait for task to finish")?;
1937
1938        // The actor connected once at startup and once more after the connection check
1939        // failed.
1940        assert_eq!(metrics.relay_conns_success.get(), 2);
1941        assert_eq!(
1942            metrics.relay_conns_closed.get(),
1943            2,
1944            "the connections are counted as closed once the actor stops"
1945        );
1946
1947        Ok(())
1948    }
1949
1950    #[tokio::test]
1951    #[traced_test]
1952    async fn test_active_relay_inactive() -> Result {
1953        let (_relay_map, relay_url, _server) = test_utils::run_relay_server().await?;
1954
1955        let secret_key = SecretKey::from_bytes(&[1u8; 32]);
1956        let (datagram_recv_tx, _datagram_recv_rx) = mpsc::channel(16);
1957        let (_send_datagram_tx, send_datagram_rx) = mpsc::channel(16);
1958        let (_prio_inbox_tx, prio_inbox_rx) = mpsc::channel(8);
1959        let (inbox_tx, inbox_rx) = mpsc::channel(16);
1960        let cancel_token = CancellationToken::new();
1961        let metrics = Arc::new(SocketMetrics::default());
1962        let mut task = start_active_relay_actor(
1963            secret_key,
1964            cancel_token.clone(),
1965            relay_url,
1966            prio_inbox_rx,
1967            inbox_rx,
1968            send_datagram_rx,
1969            datagram_recv_tx,
1970            metrics.clone(),
1971            info_span!("actor-under-test"),
1972        );
1973
1974        // Wait until the actor is connected to the relay server.
1975        tokio::time::timeout(Duration::from_secs(5), async {
1976            loop {
1977                let (tx, rx) = oneshot::channel();
1978                inbox_tx.send(ActiveRelayMessage::PingServer(tx)).await.ok();
1979                if tokio::time::timeout(Duration::from_millis(200), rx)
1980                    .await
1981                    .map(|resp| resp.is_ok())
1982                    .unwrap_or_default()
1983                {
1984                    break;
1985                }
1986            }
1987        })
1988        .await
1989        .std_context("timeout")?;
1990
1991        assert_eq!(metrics.relay_conns_success.get(), 1);
1992        assert_eq!(
1993            metrics.relay_conns_closed.get(),
1994            0,
1995            "the connection is only counted as closed once it is gone"
1996        );
1997
1998        // We now have an idling ActiveRelayActor.  If we advance time just a little it
1999        // should stay alive.
2000        info!("Stepping time forwards by RELAY_INACTIVE_CLEANUP_TIME / 2");
2001        tokio::time::pause();
2002        tokio::time::advance(RELAY_INACTIVE_CLEANUP_TIME / 2).await;
2003        tokio::time::resume();
2004
2005        assert!(
2006            tokio::time::timeout(Duration::from_millis(100), &mut task)
2007                .await
2008                .is_err(),
2009            "actor task terminated"
2010        );
2011
2012        // If we advance time a lot it should finish.
2013        info!("Stepping time forwards by RELAY_INACTIVE_CLEANUP_TIME");
2014        tokio::time::pause();
2015        tokio::time::advance(RELAY_INACTIVE_CLEANUP_TIME).await;
2016        tokio::time::resume();
2017
2018        // We resume time for these timeouts, as there's actual I/O happening,
2019        // for example closing the TCP stream, so we actually need the tokio
2020        // runtime to idle a bit while the kernel is doing its thing.
2021        assert!(
2022            tokio::time::timeout(Duration::from_secs(1), task)
2023                .await
2024                .is_ok(),
2025            "actor task still running"
2026        );
2027
2028        // The actor may have reconnected while we advanced time, because a ping to the relay
2029        // server can time out while time is frozen, so we do not assert an exact count here.
2030        assert_eq!(
2031            metrics.relay_conns_closed.get(),
2032            metrics.relay_conns_success.get(),
2033            "all connections are counted as closed once the actor stops"
2034        );
2035
2036        cancel_token.cancel();
2037        Ok(())
2038    }
2039
2040    #[tokio::test]
2041    #[traced_test]
2042    async fn undialable_relay_does_not_stall_relay_actor_on_network_changes() -> Result {
2043        let (_relay_map, relay_url, _server) = test_utils::run_relay_server().await?;
2044        let (peer_endpoint, _echo_endpoint_task) = start_echo_endpoint(relay_url.clone());
2045        let (msg_tx, datagram_send_tx, mut datagram_recv_rx, _task) = setup_relay_actor();
2046        let undialable = RelaySendItem {
2047            remote_endpoint: SecretKey::from_bytes(&[2u8; 32]).public(),
2048            url: "x://h/".parse().unwrap(),
2049            datagrams: Datagrams::from(b"lost"),
2050        };
2051        datagram_send_tx
2052            .send(undialable)
2053            .await
2054            .std_context("relay actor alive")?;
2055        let hello = RelaySendItem {
2056            remote_endpoint: peer_endpoint,
2057            url: relay_url,
2058            datagrams: Datagrams::from(b"hello"),
2059        };
2060        send_recv_echo(hello.clone(), &datagram_send_tx, &mut datagram_recv_rx).await?;
2061
2062        for _ in 0..100 {
2063            assert!(
2064                msg_tx
2065                    .send(RelayActorMessage::CheckConnectionAfterNetworkChange)
2066                    .await
2067                    .is_ok(),
2068                "relay actor alive"
2069            );
2070        }
2071
2072        send_recv_echo(hello, &datagram_send_tx, &mut datagram_recv_rx).await
2073    }
2074
2075    #[tokio::test(start_paused = true)]
2076    #[traced_test]
2077    async fn undialable_relay_actor_exits_when_inactive() -> Result {
2078        let (datagram_recv_tx, _datagram_recv_rx) = mpsc::channel(16);
2079        let (_send_datagram_tx, send_datagram_rx) = mpsc::channel(16);
2080        let (_prio_inbox_tx, prio_inbox_rx) = mpsc::channel(8);
2081        let (_inbox_tx, inbox_rx) = mpsc::channel(16);
2082        let task = start_active_relay_actor(
2083            SecretKey::from_bytes(&[1u8; 32]),
2084            CancellationToken::new(),
2085            "x://h/".parse().unwrap(),
2086            prio_inbox_rx,
2087            inbox_rx,
2088            send_datagram_rx,
2089            datagram_recv_tx,
2090            Default::default(),
2091            info_span!("actor-under-test"),
2092        );
2093        tokio::time::timeout(RELAY_INACTIVE_CLEANUP_TIME * 2, task)
2094            .await
2095            .std_context("actor task still running")?
2096            .std_context("actor task failed")?;
2097        Ok(())
2098    }
2099
2100    #[tokio::test]
2101    #[traced_test]
2102    async fn active_relay_answers_routes_and_exits_when_server_ignores_close() -> Result {
2103        let (_relay_map, _relay_url, server) = test_utils::run_relay_server().await?;
2104        let server_addr = server.https_addr().context("no https addr")?;
2105        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
2106        let proxy_url: RelayUrl = format!("https://{}", listener.local_addr()?)
2107            .parse()
2108            .unwrap();
2109        let (freeze_tx, freeze_rx) = oneshot::channel::<()>();
2110        let proxy = tokio::spawn(async move {
2111            let (mut client, _) = listener.accept().await?;
2112            let mut server = tokio::net::TcpStream::connect(server_addr).await?;
2113            tokio::select! {
2114                _ = tokio::io::copy_bidirectional(&mut client, &mut server) => {}
2115                _ = freeze_rx => {}
2116            }
2117            Ok::<_, std::io::Error>((client, server))
2118        });
2119
2120        let (datagram_recv_tx, _datagram_recv_rx) = mpsc::channel(16);
2121        let (_send_datagram_tx, send_datagram_rx) = mpsc::channel(16);
2122        let (prio_inbox_tx, prio_inbox_rx) = mpsc::channel(8);
2123        let (inbox_tx, inbox_rx) = mpsc::channel(16);
2124        let stop = CancellationToken::new();
2125        let task = start_active_relay_actor(
2126            SecretKey::from_bytes(&[1u8; 32]),
2127            stop.clone(),
2128            proxy_url,
2129            prio_inbox_rx,
2130            inbox_rx,
2131            send_datagram_rx,
2132            datagram_recv_tx,
2133            Default::default(),
2134            info_span!("actor-under-test"),
2135        );
2136        tokio::time::timeout(Duration::from_secs(5), async {
2137            loop {
2138                let (tx, rx) = oneshot::channel();
2139                inbox_tx.send(ActiveRelayMessage::PingServer(tx)).await.ok();
2140                if tokio::time::timeout(Duration::from_millis(200), rx)
2141                    .await
2142                    .map(|resp| resp.is_ok())
2143                    .unwrap_or_default()
2144                {
2145                    break;
2146                }
2147            }
2148        })
2149        .await
2150        .std_context("timeout")?;
2151
2152        freeze_tx.send(()).ok();
2153        let _frozen_streams = proxy
2154            .await
2155            .std_context("proxy task failed")?
2156            .std_context("proxy io failed")?;
2157        stop.cancel();
2158
2159        let (tx, rx) = oneshot::channel();
2160        let peer = SecretKey::from_bytes(&[2u8; 32]).public();
2161        prio_inbox_tx
2162            .send(ActiveRelayPrioMessage::HasEndpointRoute(peer, tx))
2163            .await
2164            .std_context("actor gone")?;
2165        let has_route = tokio::time::timeout(Duration::from_secs(5), rx)
2166            .await
2167            .std_context("no route reply while closing")?
2168            .std_context("route query dropped")?;
2169        assert!(!has_route);
2170
2171        tokio::time::timeout(Duration::from_secs(5), task)
2172            .await
2173            .std_context("actor task still running")?
2174            .std_context("actor task failed")?;
2175        Ok(())
2176    }
2177
2178    #[tokio::test]
2179    async fn test_ping_tracker() {
2180        tokio::time::pause();
2181        let mut tracker = PingTracker::default();
2182
2183        let ping0 = tracker.new_ping();
2184
2185        let res = tokio::time::timeout(Duration::from_secs(1), tracker.timeout()).await;
2186        assert!(res.is_err(), "no ping timeout has elapsed yet");
2187
2188        tracker.pong_received(ping0);
2189        let res = tokio::time::timeout(Duration::from_secs(10), tracker.timeout()).await;
2190        assert!(res.is_err(), "ping completed before timeout");
2191
2192        let _ping1 = tracker.new_ping();
2193
2194        let res = tokio::time::timeout(Duration::from_secs(10), tracker.timeout()).await;
2195        assert!(res.is_ok(), "ping timeout should have happened");
2196
2197        let _ping2 = tracker.new_ping();
2198
2199        tokio::time::sleep(Duration::from_secs(10)).await;
2200        let res = tokio::time::timeout(Duration::from_millis(1), tracker.timeout()).await;
2201        assert!(res.is_ok(), "ping timeout happened in the past");
2202
2203        let res = tokio::time::timeout(Duration::from_secs(10), tracker.timeout()).await;
2204        assert!(res.is_err(), "ping timeout should only happen once");
2205    }
2206
2207    #[tokio::test]
2208    #[traced_test]
2209    async fn test_prio_inbox_answered_during_backoff() {
2210        tokio::time::pause();
2211        let secret_key = SecretKey::from_bytes(&[1u8; 32]);
2212        let peer = SecretKey::from_bytes(&[2u8; 32]).public();
2213        let url: RelayUrl = "https://relay.invalid".parse().unwrap();
2214        let (prio_inbox_tx, prio_inbox_rx) = mpsc::channel(8);
2215        let (_inbox_tx, inbox_rx) = mpsc::channel(16);
2216        let (_send_datagram_tx, send_datagram_rx) = mpsc::channel(16);
2217        let (recv_datagram_tx, _recv_datagram_rx) = mpsc::channel(16);
2218        let opts = ActiveRelayActorOptions {
2219            url,
2220            prio_inbox_: prio_inbox_rx,
2221            inbox: inbox_rx,
2222            relay_datagrams_send: send_datagram_rx,
2223            relay_datagrams_recv: recv_datagram_tx,
2224            connection_opts: RelayConnectionOptions {
2225                secret_key,
2226                dns_resolver: DnsResolver::new(),
2227                proxy_url: None,
2228                prefer_ipv6: Arc::new(AtomicBool::new(true)),
2229                tls_config: CaTlsConfig::insecure_skip_verify()
2230                    .client_config(default_provider())
2231                    .expect("infallible"),
2232                auth_token: None,
2233            },
2234            stop_token: CancellationToken::new(),
2235            metrics: Default::default(),
2236            my_relay: Default::default(),
2237        };
2238        let mut actor = ActiveRelayActor::new(opts);
2239
2240        let backoff = tokio::spawn(async move {
2241            let keep_running = actor.sleep_backoff(Duration::from_secs(10)).await;
2242            (actor, keep_running)
2243        });
2244
2245        // Query the actor while it waits out the backoff delay. The reply must
2246        // arrive well before the delay elapses; before the backoff wait
2247        // serviced the priority inbox, this reply only arrived after the
2248        // remaining backoff delay (up to 16s).
2249        let (tx, rx) = oneshot::channel();
2250        prio_inbox_tx
2251            .send(ActiveRelayPrioMessage::HasEndpointRoute(peer, tx))
2252            .await
2253            .expect("actor alive");
2254        let reply = tokio::time::timeout(Duration::from_secs(1), rx)
2255            .await
2256            .expect("no reply within 1s of a 10s backoff")
2257            .expect("sender dropped");
2258        assert!(!reply, "a disconnected relay has no endpoint routes");
2259
2260        // The backoff itself still runs to completion.
2261        let (_actor, keep_running) = backoff.await.expect("backoff task panicked");
2262        assert!(keep_running, "backoff should complete normally");
2263    }
2264
2265    #[test]
2266    fn test_home_relay_watch_url_guard() {
2267        use super::{HomeRelayWatch, RelayConnectionState};
2268        use crate::endpoint::RelayStatus;
2269
2270        let watch = HomeRelayWatch::default();
2271        let a: RelayUrl = "https://a.example.com".parse().unwrap();
2272        let b: RelayUrl = "https://b.example.com".parse().unwrap();
2273
2274        // Actor A becomes home and connects
2275        watch.set(a.clone(), RelayConnectionState::Connecting);
2276        watch.set_status(&a, RelayConnectionState::Connected);
2277        assert_eq!(
2278            watch.get(),
2279            Some(RelayStatus::new(a.clone(), RelayConnectionState::Connected)),
2280        );
2281
2282        // RelayActor migrates home to B
2283        watch.set(b.clone(), RelayConnectionState::Connecting);
2284
2285        // Old actor A tries to write -- rejected because URL changed
2286        watch.set_status(
2287            &a,
2288            RelayConnectionState::Disconnected { last_failure: None },
2289        );
2290        assert_eq!(
2291            watch.get(),
2292            Some(RelayStatus::new(
2293                b.clone(),
2294                RelayConnectionState::Connecting
2295            )),
2296        );
2297
2298        // Actor B writes normally
2299        watch.set_status(&b, RelayConnectionState::Connected);
2300        assert_eq!(
2301            watch.get(),
2302            Some(RelayStatus::new(b, RelayConnectionState::Connected)),
2303        );
2304    }
2305}