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