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