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