iroh/socket/
remote_map.rs

1use std::{
2    collections::BTreeSet,
3    future::poll_fn,
4    hash::Hash,
5    net::SocketAddr,
6    sync::Arc,
7    task::{Context, Poll, Waker, ready},
8};
9
10use iroh_base::{CustomAddr, EndpointAddr, EndpointId};
11use n0_future::task::JoinSet;
12use serde::{Deserialize, Serialize};
13use tokio::sync::{mpsc, oneshot};
14use tokio_util::sync::CancellationToken;
15use tracing::{Span, debug, error, trace};
16
17pub(crate) use self::remote_state::PathStateReceiver;
18use self::remote_state::RemoteStateActor;
19pub(super) use self::remote_state::RemoteStateMessage;
20pub use self::remote_state::{
21    Path, PathEvent, PathEventStream, PathList, PathListIter, PathListStream, RemoteInfo,
22    TransportAddrInfo, TransportAddrUsage,
23};
24#[cfg(feature = "unstable-custom-transports")]
25pub use self::remote_state::{
26    PathSelection, PathSelectionContext, PathSelectionData, PathSelector,
27};
28#[cfg(not(feature = "unstable-custom-transports"))]
29pub(crate) use self::remote_state::{
30    PathSelection, PathSelectionContext, PathSelectionData, PathSelector,
31};
32use super::{
33    DirectAddr, Metrics as SocketMetrics,
34    mapped_addrs::{
35        AddrMap, CustomMappedAddr, EndpointIdMappedAddr, MappedAddr, MultipathMappedAddr,
36        RelayAddrMap,
37    },
38    transports,
39};
40use crate::{
41    address_lookup::{self, AddressLookupFailed},
42    endpoint::LocalTransportAddr,
43    socket::concurrent_read_map::{ConcurrentReadMap, ReadOnlyMap},
44};
45
46mod remote_state;
47
48// TODO: use this
49// /// Number of endpoints that are inactive for which we keep info about. This limit is enforced
50// /// periodically via [`NodeMap::prune_inactive`].
51// const MAX_INACTIVE_NODES: usize = 30;
52
53/// Map containing all the state for endpoints.
54///
55/// - Has actors which each manage all the connection state for a remote endpoint.
56///
57/// - Has the mapped addresses we use to refer to non-IP transports destinations into IPv6
58///   addressing space that is used by Noq.
59#[derive(Debug)]
60pub(crate) struct RemoteMap {
61    /// Maps for converting between mapped and IP/relay addrs.
62    pub(super) mapped_addrs: MappedAddrs,
63
64    /// The senders for the inbox of each `RemoteStateActor` that runs.
65    ///
66    /// This is separated out of `Tasks` to make keeping a mutable borrow of the senders possible
67    /// while we're spawning a task using another mutable borrow of `Tasks`.
68    senders: ConcurrentReadMap<EndpointId, mpsc::Sender<RemoteStateMessage>>,
69
70    /// The state kept for spawning new actors and cleaning them up.
71    tasks: Tasks,
72}
73
74#[derive(Clone, Debug, Default)]
75pub(crate) struct MappedAddrs {
76    /// The mapping between [`EndpointId`]s and [`EndpointIdMappedAddr`]s.
77    ///
78    /// Entries are inserted when the endpoint's `RemoteStateActor` starts and removed when
79    /// it stops.
80    pub(super) endpoint_addrs: AddrMap<EndpointId, EndpointIdMappedAddr>,
81    /// The mapping between endpoints via a relay and their [`RelayMappedAddr`](super::mapped_addrs::RelayMappedAddr)s.
82    ///
83    /// A relay chooses the source [`EndpointId`] of incoming datagrams, so entries created
84    /// on receive are bounded per relay, see [`RelayAddrMap`].
85    pub(super) relay_addrs: RelayAddrMap,
86    /// The mapping between custom transport addresses and their [`CustomMappedAddr`]s.
87    ///
88    /// Custom transports are supplied by the local application, so entries are never
89    /// removed.
90    pub(super) custom_addrs: AddrMap<CustomAddr, CustomMappedAddr>,
91}
92
93impl MappedAddrs {
94    /// Releases the mapped addresses of `endpoint_id` after its `RemoteStateActor` stopped.
95    fn release_endpoint(&self, endpoint_id: &EndpointId) {
96        // Without an actor, transmits to this address are dropped anyway.
97        self.endpoint_addrs.remove(endpoint_id);
98        self.relay_addrs.unpin_endpoint(endpoint_id);
99    }
100
101    /// Converts a possibly mapped-IP address into a [`transports::Addr`].
102    pub(crate) fn to_transport_addr(&self, addr: SocketAddr) -> Option<transports::Addr> {
103        to_transport_addr(addr, &self.relay_addrs, &self.custom_addrs)
104    }
105
106    /// Converts a mapped-IP 4-tuple to a [`transports::FourTuple`], pinning relay addresses.
107    ///
108    /// `endpoint_id` is the remote of the connection using the path. Returns `None` for relay
109    /// paths that name another endpoint: a relay chooses the source [`EndpointId`] of the
110    /// datagrams it forwards, so it could otherwise make the actor of `endpoint_id` use, and
111    /// later pin, entries for arbitrary endpoints.
112    pub(crate) fn to_pinned_transport_tuple(
113        &self,
114        four_tuple: &noq::FourTuple,
115        endpoint_id: &EndpointId,
116    ) -> Option<transports::FourTuple> {
117        let remote = match MultipathMappedAddr::from(four_tuple.remote()) {
118            MultipathMappedAddr::Relay(addr) => {
119                let Some(key) = self.relay_addrs.pin_addr(&addr, endpoint_id) else {
120                    debug!(
121                        ?addr,
122                        "unknown relay mapped addr or path names another endpoint"
123                    );
124                    return None;
125                };
126                transports::Addr::from(key)
127            }
128            addr => to_transport_addr(addr, &self.relay_addrs, &self.custom_addrs)?,
129        };
130        let local = LocalTransportAddr::from_noq_local_ip(
131            four_tuple.local_ip(),
132            &remote,
133            &self.custom_addrs,
134        );
135        Some(transports::FourTuple::new(remote, local))
136    }
137
138    /// Converts a [`transports::FourTuple`] to a mapped-IP 4-tuple, pinning relay addresses.
139    ///
140    /// Relay addresses are pinned for `owner`, the remote of the connection using the path,
141    /// so they are unpinned again when the actor of `owner` stops.
142    pub(crate) fn to_mapped_tuple(
143        &self,
144        four_tuple: &transports::FourTuple,
145        owner: &EndpointId,
146    ) -> noq::FourTuple {
147        let (remote, local) = match four_tuple {
148            transports::FourTuple::Ip { remote, local } => (*remote, *local),
149            transports::FourTuple::Relay { url, endpoint_id } => {
150                debug_assert_eq!(endpoint_id, owner, "relay path names another endpoint");
151                let addr = self.relay_addrs.get_pinned(&(url.clone(), *owner));
152                (addr.private_socket_addr(), None)
153            }
154            transports::FourTuple::Custom { remote, local } => {
155                let remote = self.custom_addrs.get(remote).private_socket_addr();
156                let local = local.as_ref().map(|custom_addr| {
157                    self.custom_addrs
158                        .get(custom_addr)
159                        .private_socket_addr()
160                        .ip()
161                });
162                (remote, local)
163            }
164        };
165        noq::FourTuple::new(remote, local)
166    }
167}
168
169/// Converts a mapped socket address to a transport address.
170///
171/// This takes a socket address, converts it into a [`MultipathMappedAddr`] and then tries
172/// to convert the mapped address into a [`transports::Addr`].
173///
174/// Returns `Some` with the transport address for IP, relay, or custom mapped addresses
175/// if an entry exists in the corresponding map.
176///
177/// Returns `None` for [`MultipathMappedAddr::Mixed`] addresses or unknown mapped addresses.
178fn to_transport_addr(
179    addr: impl Into<MultipathMappedAddr>,
180    relay_addrs: &RelayAddrMap,
181    custom_addrs: &AddrMap<CustomAddr, CustomMappedAddr>,
182) -> Option<transports::Addr> {
183    match addr.into() {
184        MultipathMappedAddr::Mixed(_) => {
185            error!(
186                "Failed to convert addr to transport addr: Mixed mapped addr has no transport address"
187            );
188            None
189        }
190        MultipathMappedAddr::Relay(relay_mapped_addr) => {
191            match relay_addrs.lookup(&relay_mapped_addr) {
192                Some(parts) => Some(transports::Addr::from(parts)),
193                None => {
194                    error!("Failed to convert addr to transport addr: Unknown relay mapped addr");
195                    None
196                }
197            }
198        }
199        MultipathMappedAddr::Custom(custom_mapped_addr) => {
200            match custom_addrs.lookup(&custom_mapped_addr) {
201                Some(custom_addr) => Some(transports::Addr::Custom(custom_addr)),
202                None => {
203                    error!("Failed to convert addr to transport addr: Unknown custom mapped addr");
204                    None
205                }
206            }
207        }
208        MultipathMappedAddr::Ip(addr) => Some(transports::Addr::from(addr)),
209    }
210}
211
212/// Stores the state required for starting and cleaning up the `RemoteStateActor`s.
213///
214/// When this is dropped, this will abort all tasks.
215#[derive(Debug)]
216struct Tasks {
217    //
218    // State required for spawning new actors.
219    //
220    metrics: Arc<SocketMetrics>,
221    /// The "direct" addresses known for our local endpoint
222    local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>,
223    address_lookup: address_lookup::AddressLookupServices,
224    shutdown_token: CancellationToken,
225
226    //
227    // State for task-tracking spawned actors.
228    //
229    /// All the `RemoteStateActor` tasks, stored inside a `JoinSet`.
230    ///
231    /// These tasks return their endpoint ID and the list of messages they didn't get to handle
232    /// when they shut down.
233    tasks: JoinSet<(EndpointId, Vec<RemoteStateMessage>)>,
234    /// The waker that notifies `poll_cleanup` when the join set is populated with another task.
235    poll_cleanup_waker: Option<Waker>,
236    /// The path selector used by all [`RemoteStateActor`]s spawned by this map.
237    path_selector: Arc<dyn PathSelector>,
238    /// The tracing span for this endpoint, to be used as parent span for `RemoteStateActor` tasks.
239    span: Span,
240}
241
242impl RemoteMap {
243    /// Creates a new [`RemoteMap`].
244    pub(super) fn new(
245        metrics: Arc<SocketMetrics>,
246        local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>,
247        address_lookup: address_lookup::AddressLookupServices,
248        shutdown_token: CancellationToken,
249        path_selector: Arc<dyn PathSelector>,
250        span: Span,
251    ) -> Self {
252        Self {
253            mapped_addrs: Default::default(),
254            senders: Default::default(),
255            tasks: Tasks {
256                metrics,
257                local_direct_addrs,
258                address_lookup,
259                shutdown_token,
260                tasks: Default::default(),
261                poll_cleanup_waker: None,
262                path_selector,
263                span,
264            },
265        }
266    }
267
268    /// Cleans up terminated `RemoteStateActor` tasks.
269    ///
270    /// This polls for terminated actor tasks, and removes the corresponding actor sender
271    /// from our sender map, or restarts the actor if it has pending messages.
272    ///
273    /// Resolves to the actor's remote endpoint ID whenever a `RemoteStateActor` task joined,
274    /// independent of whether the task was restarted or not.
275    ///
276    /// Returns pending if there was no actor to be cleaned up right now, and registers
277    /// for moments where this could become the case.
278    ///
279    /// This function should be called in a loop to clean up expired tasks.
280    /// Only one task is allowed to poll this function concurrently.
281    pub(super) async fn cleanup(&mut self) -> EndpointId {
282        loop {
283            let (remote_id, leftover_messages) = poll_fn(|cx| self.poll_join_next(cx)).await;
284            if self.remove_or_restart_actor(remote_id, leftover_messages) {
285                return remote_id;
286            }
287        }
288    }
289
290    /// Polls for the next joined actor task.
291    ///
292    /// Returns [`Poll::Pending`] if no tasks are running, and is woken when the task set changes.
293    fn poll_join_next(
294        &mut self,
295        cx: &mut Context<'_>,
296    ) -> Poll<(EndpointId, Vec<RemoteStateMessage>)> {
297        while let Some(result) = ready!(self.tasks.tasks.poll_join_next(cx)) {
298            match result {
299                Ok((remote_id, leftover_msgs)) => {
300                    return Poll::Ready((remote_id, leftover_msgs));
301                }
302                Err(err) => {
303                    if let Ok(panic) = err.try_into_panic() {
304                        error!("RemoteStateActor panicked.");
305                        std::panic::resume_unwind(panic);
306                    }
307                }
308            }
309        }
310        // There's nothing to clean up.
311        // Let's get woken when there's another task.
312        // If we're called after that, then we'll fall into `poll_join_next` and
313        // properly wait for a task to finish.
314        self.tasks.poll_cleanup_waker.replace(cx.waker().clone());
315        Poll::Pending
316    }
317
318    /// Removes an actor sender if `leftover_msgs` is empty, or restarts the actor otherwise.
319    fn remove_or_restart_actor(
320        &mut self,
321        remote_id: iroh_base::PublicKey,
322        leftover_msgs: Vec<RemoteStateMessage>,
323    ) -> bool {
324        if leftover_msgs.is_empty() {
325            // the actor shut down cleanly
326            self.senders.remove(&remote_id);
327            self.mapped_addrs.release_endpoint(&remote_id);
328            trace!(%remote_id, "cleaned up RemoteStateActor");
329            true
330        } else {
331            // The remote actor got messages while it was closing, so we're restarting
332            trace!(%remote_id, "restarting terminated RemoteStateActor: messages received during shutdown");
333            let sender =
334                self.tasks
335                    .start_remote_state_actor(remote_id, leftover_msgs, &self.mapped_addrs);
336            // We don't have to be careful about guards - only one thread is modifying this hashmap at a time.
337            self.senders.insert(remote_id, sender);
338            false
339        }
340    }
341
342    pub(super) fn on_network_change(&mut self, is_major: bool) {
343        let read = self.senders.read_only();
344        let guard = read.guard();
345        for sender in read.values(&guard) {
346            sender
347                .try_send(RemoteStateMessage::NetworkChange { is_major })
348                .ok();
349        }
350    }
351
352    pub(super) async fn resolve_remote(
353        &mut self,
354        addr: EndpointAddr,
355        tx: oneshot::Sender<Result<(), AddressLookupFailed>>,
356    ) {
357        let EndpointAddr { id, addrs } = addr;
358        self.send_to_actor(id, RemoteStateMessage::ResolveRemote(addrs, tx))
359            .await
360    }
361
362    pub(super) async fn add_connection(
363        &mut self,
364        remote: EndpointId,
365        conn: noq::Connection,
366        tx: oneshot::Sender<PathStateReceiver>,
367    ) {
368        self.send_to_actor(remote, RemoteStateMessage::AddConnection(conn, tx))
369            .await
370    }
371
372    /// Sends a message to a `RemoteStateActor`, starting it if not running already.
373    ///
374    /// When sending fails, the actor must be terminating, in which case we wait for its task to
375    /// join and then restart the sender.
376    async fn send_to_actor(&mut self, remote_id: EndpointId, message: RemoteStateMessage) {
377        let sender = self.senders.get_or_insert_with(remote_id, || {
378            self.tasks
379                .start_remote_state_actor(remote_id, vec![], &self.mapped_addrs)
380        });
381
382        if let Err(mpsc::error::SendError(message)) = sender.send(message).await {
383            // The send failed, which means the RemoteStateActor is terminating. We call the cleanup
384            // function so that its task is processed. This ensures that the leftover messages are
385            // properly enqueued into a new actor, and that a later cleanup does not reap a newly
386            // created sender again.  We can be sure that the task has not been cleaned up yet
387            // because we take a `&mut self` reference.
388            loop {
389                let (id, leftover_messages) = poll_fn(|cx| self.poll_join_next(cx)).await;
390                if id != remote_id {
391                    self.remove_or_restart_actor(id, leftover_messages);
392                } else {
393                    let mut messages = leftover_messages;
394                    messages.push(message);
395                    self.remove_or_restart_actor(id, messages);
396                    break;
397                }
398            }
399        }
400    }
401
402    pub(super) fn senders(&self) -> ReadOnlyMap<EndpointId, mpsc::Sender<RemoteStateMessage>> {
403        self.senders.read_only()
404    }
405}
406
407impl Tasks {
408    /// Starts a new remote state actor and returns a handle and a sender.
409    ///
410    /// The handle is not inserted into the endpoint map, this must be done by the caller of this function.
411    fn start_remote_state_actor(
412        &mut self,
413        eid: EndpointId,
414        initial_msgs: Vec<RemoteStateMessage>,
415        mapped_addrs: &MappedAddrs,
416    ) -> mpsc::Sender<RemoteStateMessage> {
417        // Ensure there is a RemoteMappedAddr for this EndpointId.
418        mapped_addrs.endpoint_addrs.get(&eid);
419        let sender = RemoteStateActor::new(
420            eid,
421            self.local_direct_addrs.clone(),
422            mapped_addrs.clone(),
423            self.metrics.clone(),
424            self.address_lookup.clone(),
425            self.path_selector.clone(),
426        )
427        .start(
428            initial_msgs,
429            &mut self.tasks,
430            self.shutdown_token.clone(),
431            self.span.clone(),
432        );
433        if let Some(waker) = self.poll_cleanup_waker.take() {
434            // Notify something waiting for changes to tasks when there's a new task.
435            waker.wake();
436        }
437        sender
438    }
439}
440
441/// The origin or *source* through which an address associated with a remote endpoint
442/// was discovered.
443///
444/// An aggregate of the [`Source`]s of all the addresses of an endpoint describe the
445/// [`Source`]s of the endpoint itself.
446///
447/// A [`Source`] helps track how and where an address was learned. Multiple
448/// sources can be associated with a single address, if we have discovered this
449/// address through multiple means.
450#[derive(Serialize, Deserialize, strum::Display, Debug, Clone, Eq, PartialEq, Hash)]
451#[strum(serialize_all = "kebab-case")]
452#[allow(private_interfaces)]
453#[non_exhaustive]
454pub(crate) enum Source {
455    /// Application layer added the address directly.
456    App,
457    /// The address was discovered by an Address Lookup system
458    #[strum(serialize = "{name}")]
459    AddressLookup {
460        /// The name of the Address Lookup that discovered the address.
461        name: String,
462    },
463    /// The address was added as a path within a connection.
464    Connection,
465}
466
467#[cfg(test)]
468mod tests {
469    use std::{net::SocketAddr, pin::Pin, time::Duration};
470
471    use bytes::Bytes;
472    use futures_util::StreamExt;
473    use iroh_base::{RelayUrl, SecretKey, TransportAddr};
474    use n0_future::future::now_or_never;
475    use n0_tracing_test::traced_test;
476    use n0_watcher::Watchable;
477    use tokio::sync::oneshot;
478    use tracing::Span;
479
480    use super::*;
481    use crate::socket::{
482        biased_rtt_path_selector::BiasedRttPathSelector,
483        transports::{OwnedTransmit, Transmit},
484    };
485
486    #[tokio::test(start_paused = true)]
487    async fn pending_initial_send_does_not_block_remote_actor_inbox() {
488        check_initial_send_inbox(256).await;
489    }
490
491    #[tokio::test(start_paused = true)]
492    async fn uncongested_initial_send_keeps_remote_actor_responsive() {
493        check_initial_send_inbox(0).await;
494    }
495
496    async fn check_initial_send_inbox(queued: usize) {
497        let (mut remote_map, _shutdown_token, _guards) = make_remote_map();
498        let (endpoint_id, mut receiver) = enqueue_initials(&mut remote_map, queued, 1).await;
499        let (info_tx, info_rx) = oneshot::channel();
500        remote_map
501            .send_to_actor(endpoint_id, RemoteStateMessage::RemoteInfo(info_tx))
502            .await;
503        // The inbox must respond before the blocked send's three-second deadline.
504        tokio::time::timeout(Duration::from_secs(1), info_rx)
505            .await
506            .expect("pending Initial send blocked the RemoteStateActor inbox")
507            .expect("remote actor dropped the response");
508        assert!(
509            tokio::time::timeout(Duration::from_secs(1), receiver.next())
510                .await
511                .expect("Initial was not sent on an uncongested queue")
512                .is_some()
513        );
514    }
515
516    #[tokio::test]
517    async fn pending_initial_sends_are_cancelled_on_shutdown() {
518        let (mut remote_map, shutdown_token, _guards) = make_remote_map();
519        let (endpoint_id, receiver) = enqueue_initials(&mut remote_map, 256, 1).await;
520        wait_for_inbox(&mut remote_map, endpoint_id).await;
521        shutdown_token.cancel();
522        tokio::time::timeout(Duration::from_secs(1), remote_map.cleanup())
523            .await
524            .expect("actor shutdown blocked by Initial send");
525        let remaining = tokio::time::timeout(Duration::from_secs(1), receiver.count())
526            .await
527            .expect("send task retained the RelaySender after shutdown");
528        assert_eq!(remaining, 256);
529    }
530
531    #[tokio::test(start_paused = true)]
532    async fn pending_initial_sends_expire_without_sending_late_packets() {
533        let (mut remote_map, _shutdown_token, _guards) = make_remote_map();
534        let (endpoint_id, receiver) = enqueue_initials(&mut remote_map, 256, 1).await;
535        wait_for_inbox(&mut remote_map, endpoint_id).await;
536        tokio::time::sleep(Duration::from_secs(4)).await;
537        let remaining = tokio::time::timeout(Duration::from_secs(1), receiver.count())
538            .await
539            .expect("expired Initial still holds the sender");
540        assert_eq!(remaining, 256);
541    }
542
543    #[tokio::test(start_paused = true)]
544    async fn congested_initial_sends_have_bounded_pending_work() {
545        let (mut remote_map, _shutdown_token, _guards) = make_remote_map();
546        let (endpoint_id, receiver) = enqueue_initials(&mut remote_map, 256, 32).await;
547        wait_for_inbox(&mut remote_map, endpoint_id).await;
548        let remaining = tokio::time::timeout(Duration::from_secs(1), receiver.count())
549            .await
550            .expect("Initial sends did not finish after draining the queue");
551        assert_eq!(remaining, 256 + 16);
552    }
553
554    async fn enqueue_initials(
555        remote_map: &mut RemoteMap,
556        queued: usize,
557        count: usize,
558    ) -> (
559        EndpointId,
560        impl futures_util::Stream<Item = ()> + Unpin + use<>,
561    ) {
562        let endpoint_id = SecretKey::from_bytes(&[1u8; 32]).public();
563        let relay_url: RelayUrl = "https://relay.example.invalid".parse().unwrap();
564        let (resolve_tx, resolve_rx) = oneshot::channel();
565        remote_map
566            .resolve_remote(
567                EndpointAddr::from_parts(endpoint_id, [TransportAddr::Relay(relay_url.clone())]),
568                resolve_tx,
569            )
570            .await;
571        assert!(resolve_rx.await.expect("resolve response").is_ok());
572
573        // Hold the receiver to apply backpressure without changing poll_send.
574        let (mut sender, receiver) = transports::TransportsSender::with_bounded_relay(
575            256,
576            #[cfg(not(wasm_browser))]
577            std::iter::empty(),
578        );
579        let transmit = Transmit {
580            ecn: None,
581            contents: b"queued",
582            segment_size: None,
583        };
584        let path = transports::FourTuple::Relay {
585            url: relay_url,
586            endpoint_id,
587        };
588        for _ in 0..queued {
589            poll_fn(|cx| Pin::new(&mut sender).poll_send(cx, &path, &transmit))
590                .await
591                .expect("fill relay queue");
592        }
593        for _ in 0..count {
594            remote_map
595                .send_to_actor(
596                    endpoint_id,
597                    RemoteStateMessage::SendDatagram(
598                        Box::new(sender.clone()),
599                        OwnedTransmit {
600                            ecn: None,
601                            contents: Bytes::from_static(b"initial"),
602                            segment_size: None,
603                        },
604                    ),
605                )
606                .await;
607        }
608        (endpoint_id, receiver)
609    }
610
611    async fn wait_for_inbox(remote_map: &mut RemoteMap, endpoint_id: EndpointId) {
612        // Resolve is queued after the sends, so its reply marks them as handled.
613        let (ack_tx, ack_rx) = oneshot::channel();
614        remote_map
615            .send_to_actor(
616                endpoint_id,
617                RemoteStateMessage::ResolveRemote(BTreeSet::new(), ack_tx),
618            )
619            .await;
620        tokio::time::timeout(Duration::from_secs(1), ack_rx)
621            .await
622            .expect("inbox stalled")
623            .expect("actor dropped acknowledgement")
624            .expect("resolve acknowledgement");
625    }
626
627    fn make_remote_map() -> (RemoteMap, CancellationToken, impl Sized) {
628        let metrics = Arc::new(SocketMetrics::default());
629        let watchable: Watchable<BTreeSet<DirectAddr>> = Watchable::new(BTreeSet::new());
630        let local_direct_addrs = watchable.watch();
631        let shutdown_token = CancellationToken::new();
632        let remote_map = RemoteMap::new(
633            metrics,
634            local_direct_addrs,
635            address_lookup::AddressLookupServices::default(),
636            shutdown_token.clone(),
637            Arc::new(BiasedRttPathSelector::default()),
638            Span::none(),
639        );
640        let guards = (watchable, shutdown_token.clone().drop_guard());
641        (remote_map, shutdown_token, guards)
642    }
643
644    /// Regression test: No new RemoteStateActors may be started before
645    /// the task of its previous incarnation was processed.
646    #[tokio::test(flavor = "current_thread", start_paused = true)]
647    #[traced_test]
648    async fn poll_cleanup_preserves_restarted_sender() {
649        let (mut remote_map, _shutdown_token, _guards) = make_remote_map();
650        let eid = SecretKey::from_bytes(&[0u8; 32]).public();
651
652        // Non-empty addrs so each `resolve_remote` resolves its tx
653        // immediately and does not park in `paths.pending_resolve_requests`;
654        // the actor would never idle out otherwise.
655        let addr_with_ip = |port: u16| {
656            EndpointAddr::from_parts(
657                eid,
658                [TransportAddr::Ip(SocketAddr::from(([127, 0, 0, 1], port)))],
659            )
660        };
661
662        // 1. Spawn A1 and let it process a real `ResolveRemote`.
663        let (tx1, rx1) = oneshot::channel();
664        remote_map.resolve_remote(addr_with_ip(1234), tx1).await;
665        assert!(
666            matches!(rx1.await, Ok(Ok(()))),
667            "First resolve completes Ok"
668        );
669
670        // 2. Advance past idle timeout.
671        tokio::time::sleep(Duration::from_secs(65)).await;
672
673        // 3. Call `resolve_remote` again. The actor A1 has terminated but its task
674        //    has not yet been cleaned up. A1's sender is still in the sender map
675        //    but is closed. This will spawn a new actor A2.
676        //    Before our fixes, `resolve_remote` would spawn a new actor, and when
677        //    `cleanup` was then called, the sender to this new actor would be
678        //    removed again. We fixed this by first processing the joined task for the
679        //    terminated actor, so that it is removed from our task list *before*
680        //    starting a new actor.
681        //    We also resume time here so that we don't immediately idle-out again.
682        tokio::time::resume();
683        let (tx2, rx2) = oneshot::channel();
684        remote_map.resolve_remote(addr_with_ip(5678), tx2).await;
685
686        // 4. Drive `cleanup`, like the socket actor does.
687        //    Before our fixes, this would remove the sender to the just-started A2 from the sender map.
688        now_or_never(remote_map.cleanup());
689
690        // 5. A third `resolve_remote`, this time with no addrs.
691        //    With our fix, this reaches the actor spawned above (A2); without
692        //    the fix this would start a new actor because A2 was falsely removed from
693        //    the senders map.
694        let (tx3, rx3) = oneshot::channel();
695        remote_map.resolve_remote(EndpointAddr::new(eid), tx3).await;
696
697        let outcome2 = rx2.await.expect("the resolve tx must be sent");
698        let outcome3 = rx3.await.expect("the resolve tx must be sent");
699        assert!(outcome2.is_ok(), "expected Ok, but got {outcome2:?}");
700        assert!(outcome3.is_ok(), "expected Ok, but got {outcome3:?}");
701    }
702
703    /// A relay can label a path of one endpoint with another [`EndpointId`]. Such paths
704    /// must not be registered by the actor, or their entries would stay pinned.
705    #[test]
706    fn relay_paths_naming_another_endpoint_are_not_pinned() {
707        let mapped_addrs = MappedAddrs::default();
708        let real = SecretKey::from_bytes(&[1u8; 32]).public();
709        let forged = SecretKey::from_bytes(&[2u8; 32]).public();
710        let url: RelayUrl = "https://relay.example".parse().unwrap();
711
712        // Received over the relay, labelled with `forged`.
713        let addr = mapped_addrs
714            .relay_addrs
715            .get_unpinned(&(url.clone(), forged));
716        let path = noq::FourTuple::new(addr.private_socket_addr(), None);
717        assert_eq!(mapped_addrs.to_pinned_transport_tuple(&path, &real), None);
718        assert!(!mapped_addrs.relay_addrs.is_pinned(&addr));
719        assert_eq!(mapped_addrs.relay_addrs.len(), 1);
720
721        // The actor of `forged` itself may pin it.
722        let forged_path = transports::FourTuple::Relay {
723            url: url.clone(),
724            endpoint_id: forged,
725        };
726        assert_eq!(
727            mapped_addrs.to_pinned_transport_tuple(&path, &forged),
728            Some(forged_path)
729        );
730        assert!(mapped_addrs.relay_addrs.is_pinned(&addr));
731    }
732
733    /// When an actor stops cleanly, its endpoint mapped address is removed and its relay
734    /// mapped addresses are unpinned but kept for in-flight handshakes.
735    #[tokio::test(flavor = "current_thread", start_paused = true)]
736    #[traced_test]
737    async fn cleanup_releases_mapped_addrs() {
738        let (mut remote_map, _shutdown_token, _guards) = make_remote_map();
739        let eid = SecretKey::from_bytes(&[0u8; 32]).public();
740        let url: RelayUrl = "https://relay.example".parse().unwrap();
741
742        // Non-empty addrs so the actor replies right away and can idle out afterwards.
743        let addr = EndpointAddr::from_parts(
744            eid,
745            [TransportAddr::Ip(SocketAddr::from(([127, 0, 0, 1], 1234)))],
746        );
747        let (tx, rx) = oneshot::channel();
748        remote_map.resolve_remote(addr, tx).await;
749        assert!(matches!(rx.await, Ok(Ok(()))));
750
751        let mapped_addrs = remote_map.mapped_addrs.clone();
752        let endpoint_addr = mapped_addrs.endpoint_addrs.get(&eid);
753        let relay_addr = mapped_addrs.relay_addrs.get_pinned(&(url, eid));
754        assert!(mapped_addrs.relay_addrs.is_pinned(&relay_addr));
755
756        // Let the actor idle out and clean up its task.
757        tokio::time::sleep(Duration::from_secs(65)).await;
758        assert_eq!(remote_map.cleanup().await, eid);
759
760        assert_eq!(mapped_addrs.endpoint_addrs.lookup(&endpoint_addr), None);
761        assert!(mapped_addrs.relay_addrs.lookup(&relay_addr).is_some());
762        assert!(!mapped_addrs.relay_addrs.is_pinned(&relay_addr));
763    }
764}