iroh/socket/remote_map/remote_state/
path_watcher.rs

1//! Path observation for a [`Connection`].
2//!
3//! [`Connection::paths`] returns a borrowed [`PathList`] with live
4//! statistics. [`Connection::path_events`] returns a `'static` stream
5//! of [`PathEvent`]s. Subscribing to the event stream before reading
6//! the snapshot ensures any change that happens between the read and
7//! the next poll is observed by the subscriber.
8//!
9//! Closed paths are not retained in [`PathList`]; their final
10//! statistics arrive inline on [`PathEvent::Closed`].
11//!
12//! # Internal structure
13//!
14//! [`PathStateSender`] (owned by the [`RemoteStateActor`]) and
15//! [`PathStateReceiver`] (held by the [`Connection`]) share a
16//! [`Mutex`]`<`[`State`]`>`, a [`Notify`], and a [`broadcast`] channel.
17//! The receiver holds a [`WeakSender`]; when the actor drops the
18//! sender, outstanding event streams end.
19//!
20//! [`Connection`]: crate::endpoint::Connection
21//! [`Connection::paths`]: crate::endpoint::Connection::paths
22//! [`Connection::path_events`]: crate::endpoint::Connection::path_events
23//! [`RemoteStateActor`]: super::RemoteStateActor
24//! [`WeakSender`]: broadcast::WeakSender
25
26use std::{
27    pin::Pin,
28    sync::{Arc, Mutex},
29    task::{Context, Poll},
30};
31
32use iroh_base::TransportAddr;
33use n0_future::{StreamExt, time::Duration};
34use noq::WeakPathHandle;
35use noq_proto::PathId;
36use smallvec::SmallVec;
37use tokio::sync::{Notify, broadcast, futures::Notified};
38use tokio_stream::{
39    Stream,
40    wrappers::{BroadcastStream, errors::BroadcastStreamRecvError},
41};
42use tracing::warn;
43
44use crate::{
45    endpoint::PathStats,
46    socket::transports::{self, LocalTransportAddr},
47};
48
49/// Per-connection broadcast channel capacity for path events.
50const BROADCAST_CAPACITY: usize = 8;
51
52/// Lifecycle notifications for a transmission paths in a connection.
53#[derive(Clone, Debug)]
54#[non_exhaustive]
55pub enum PathEvent {
56    /// A new network path was opened.
57    #[non_exhaustive]
58    Opened {
59        /// Path identifier.
60        id: PathId,
61        /// Remote transport address.
62        remote_addr: TransportAddr,
63        /// Local address of the path, if known.
64        local_addr: LocalTransportAddr,
65    },
66    /// A network path was closed.
67    #[non_exhaustive]
68    Closed {
69        /// Path identifier.
70        id: PathId,
71        /// Remote transport address.
72        remote_addr: TransportAddr,
73        /// Local address of the path, if known.
74        local_addr: LocalTransportAddr,
75        /// Path statistics captured at close time.
76        last_stats: Box<PathStats>,
77    },
78    /// This path was selected for transmission of application data.
79    #[non_exhaustive]
80    Selected {
81        /// Path identifier of the newly selected path.
82        id: PathId,
83        /// Remote transport address of the newly selected path.
84        remote_addr: TransportAddr,
85        /// The local address of the newly selected path, if known.
86        local_addr: LocalTransportAddr,
87    },
88    /// Events were dropped before the subscriber received them.
89    ///
90    /// Yielded when the subscriber does not poll the stream fast
91    /// enough to keep up with the writer. The current set of open
92    /// paths and the selected path remain accessible via
93    /// [`Connection::paths`].
94    ///
95    /// [`Connection::paths`]: crate::endpoint::Connection::paths
96    #[non_exhaustive]
97    Lagged {
98        /// Number of events dropped since the last delivered event.
99        missed: u64,
100    },
101}
102
103#[derive(Clone, derive_more::Debug)]
104#[debug("PathData({}, {})", self.handle.id(), self.remote_addr)]
105struct PathData {
106    handle: WeakPathHandle,
107    remote_addr: TransportAddr,
108    local_addr: LocalTransportAddr,
109}
110
111impl PathData {
112    /// Returns a strong [`noq::Path`].
113    ///
114    /// # Panics
115    ///
116    /// This may panic if the passed `noq::Connection` is not the one to which this path belongs.
117    fn upgrade(&self, _conn: &noq::Connection) -> noq::Path {
118        self.handle
119            .upgrade()
120            .expect("Wrong Connection reference passed to PathData::upgrade")
121    }
122}
123
124#[derive(Default, Debug, Clone)]
125struct State {
126    list: SmallVec<[PathData; 4]>,
127    selected: Option<PathId>,
128    closed: bool,
129}
130
131#[derive(Debug)]
132struct Shared {
133    state: Mutex<State>,
134    notify: Notify,
135}
136
137/// The writer-side handle for a connection's path state.
138///
139/// Owned by the [`RemoteStateActor`]; the only handle that mutates
140/// state and emits events. When dropped, every outstanding
141/// [`PathEventStream`] ends.
142///
143/// [`RemoteStateActor`]: super::RemoteStateActor
144#[derive(Debug)]
145pub(super) struct PathStateSender {
146    shared: Arc<Shared>,
147    events: broadcast::Sender<PathEvent>,
148}
149
150impl PathStateSender {
151    /// Creates a sender/receiver pair sharing empty state.
152    ///
153    /// Gets passed a clone of the custom address map, so that we can convert local addresses
154    /// to the public [`LocalTransportAddr`] exposed to users.
155    pub(super) fn new() -> (Self, PathStateReceiver) {
156        let (events, _) = broadcast::channel(BROADCAST_CAPACITY);
157        let shared = Arc::new(Shared {
158            state: Default::default(),
159            notify: Notify::new(),
160        });
161        let receiver = PathStateReceiver {
162            shared: shared.clone(),
163            events: events.downgrade(),
164        };
165        let sender = PathStateSender { shared, events };
166        (sender, receiver)
167    }
168
169    /// Records a newly-opened path and emits [`PathEvent::Opened`].
170    pub(super) fn record_opened(
171        &self,
172        handle: WeakPathHandle,
173        network_path: transports::FourTuple,
174    ) {
175        let id = handle.id();
176        let remote_addr: TransportAddr = network_path.remote().into();
177        let local_addr = network_path.local();
178        {
179            let mut state = self.shared.state.lock().expect("poisoned");
180            let entry = PathData {
181                handle,
182                remote_addr: remote_addr.clone(),
183                local_addr: local_addr.clone(),
184            };
185            match state.list.iter().position(|e| e.handle.id() == id) {
186                Some(idx) => state.list[idx] = entry,
187                None => state.list.push(entry),
188            }
189        }
190        self.shared.notify.notify_waiters();
191        let _ = self.events.send(PathEvent::Opened {
192            id,
193            remote_addr,
194            local_addr,
195        });
196    }
197
198    /// Records that a path was abandoned by `noq`.
199    pub(super) fn record_abandoned(&self, id: PathId, conn: &noq::Connection) {
200        let removed = {
201            let mut state = self.shared.state.lock().expect("poisoned");
202            if state.selected == Some(id) {
203                state.selected = None;
204            }
205            state
206                .list
207                .iter()
208                .position(|e| e.handle.id() == id)
209                .map(|pos| state.list.remove(pos))
210        };
211        if let Some(data) = removed {
212            let stats = data.upgrade(conn).stats();
213            self.shared.notify.notify_waiters();
214            let _ = self.events.send(PathEvent::Closed {
215                id,
216                remote_addr: data.remote_addr.clone(),
217                local_addr: data.local_addr.clone(),
218                last_stats: Box::new(stats),
219            });
220        }
221    }
222
223    /// Updates the selected transmission path.
224    pub(super) fn record_selected(&self, network_path: &transports::FourTuple) {
225        let remote_addr: TransportAddr = network_path.remote().into();
226        let local_addr = network_path.local();
227        let event = {
228            let mut state = self.shared.state.lock().expect("poisoned");
229            let selected_path_id = state
230                .list
231                .iter()
232                .find(|p| p.remote_addr == remote_addr && p.local_addr == local_addr)
233                .map(|p| p.handle.id());
234            if selected_path_id == state.selected {
235                return;
236            }
237            state.selected = selected_path_id;
238            selected_path_id.map(|path_id| PathEvent::Selected {
239                id: path_id,
240                remote_addr: remote_addr.clone(),
241                local_addr: local_addr.clone(),
242            })
243        };
244        // Notify even if the selection was cleared, which emits no event.
245        self.shared.notify.notify_waiters();
246        if let Some(event) = event {
247            let _ = self.events.send(event);
248        }
249    }
250
251    /// Closes the writer side of the path observation.
252    ///
253    /// Emits a final [`PathEvent::Closed`] for every remaining open
254    /// path with its statistics taken from `closed.path_stats`, marks
255    /// the state closed, and drops the sender. No-op if already closed.
256    ///
257    /// [`WeakPathHandle`]: noq::WeakPathHandle
258    pub(super) fn close(self, closed: noq::Closed) {
259        let mut state = self.shared.state.lock().expect("poisoned");
260        if !state.closed {
261            for path in state.list.iter() {
262                if let Some(stats) = closed
263                    .path_stats
264                    .iter()
265                    .find(|(id, _stats)| *id == path.handle.id())
266                    .map(|(_id, stats)| stats)
267                {
268                    let _ = self.events.send(PathEvent::Closed {
269                        id: path.handle.id(),
270                        remote_addr: path.remote_addr.clone(),
271                        local_addr: path.local_addr.clone(),
272                        last_stats: Box::new(*stats),
273                    });
274                } else {
275                    warn!(
276                        "Connection close event is missing path stats for path {}",
277                        path.handle.id()
278                    );
279                }
280            }
281            state.closed = true;
282            self.shared.notify.notify_waiters();
283        }
284    }
285}
286
287impl Drop for PathStateSender {
288    fn drop(&mut self) {
289        let mut state = self.shared.state.lock().expect("poisoned");
290        if !state.closed {
291            state.closed = true;
292            self.shared.notify.notify_waiters();
293        }
294    }
295}
296
297/// The reader-side handle for a connection's path state.
298///
299/// Held by a [`Connection`]. Cheap to clone.
300///
301/// [`Connection`]: crate::endpoint::Connection
302#[derive(Clone, Debug)]
303pub(crate) struct PathStateReceiver {
304    shared: Arc<Shared>,
305    events: broadcast::WeakSender<PathEvent>,
306}
307
308impl PathStateReceiver {
309    /// Returns a snapshot of the currently-open paths, tied to `conn`.
310    pub(crate) fn get<'a>(&self, conn: &'a noq::Connection) -> PathList<'a> {
311        PathList {
312            snapshot: self.shared.state.lock().expect("poisoned").clone(),
313            conn,
314        }
315    }
316
317    /// Returns a stream of [`PathEvent`]s.
318    ///
319    /// Already closed if the sender has been dropped.
320    pub(crate) fn events(&self) -> PathEventStream {
321        let receiver = if let Some(sender) = self.events.upgrade() {
322            sender.subscribe()
323        } else {
324            let (_tx, rx) = broadcast::channel(1);
325            rx
326        };
327        PathEventStream {
328            inner: BroadcastStream::new(receiver),
329        }
330    }
331
332    /// Returns a stream of [`PathList`] snapshots tied to `conn`.
333    ///
334    /// Yields a snapshot taken at creation, then one per state change.
335    /// Ends when the state is marked closed.
336    pub(crate) fn stream<'a>(&'a self, conn: &'a noq::Connection) -> PathListStream<'a> {
337        PathListStream {
338            shared: &self.shared,
339            conn,
340            // Created before the snapshot, so no change is missed.
341            notified: Box::pin(self.shared.notify.notified()),
342            next_value: Some(self.get(conn)),
343        }
344    }
345}
346
347/// A borrowed snapshot of a connection's currently-open paths.
348///
349/// Returned by [`Connection::paths`]. The list is captured at call
350/// time and does not reflect later changes. Closed paths are not
351/// retained; to track per-path totals over the connection's lifetime,
352/// accumulate from [`PathEvent::Closed`].
353///
354/// [`Connection::paths`]: crate::endpoint::Connection::paths
355#[derive(Clone, derive_more::Debug)]
356pub struct PathList<'conn> {
357    snapshot: State,
358    #[debug(skip)]
359    conn: &'conn noq::Connection,
360}
361
362impl<'conn> PathList<'conn> {
363    /// Returns the number of open paths.
364    pub fn len(&self) -> usize {
365        self.snapshot.list.len()
366    }
367
368    /// Returns `true` if no paths are open.
369    pub fn is_empty(&self) -> bool {
370        self.snapshot.list.is_empty()
371    }
372
373    /// Returns an iterator over the open paths.
374    pub fn iter(&self) -> PathListIter<'_> {
375        PathListIter {
376            inner: self.snapshot.list.iter(),
377            selected: self.snapshot.selected,
378            conn: self.conn,
379        }
380    }
381
382    /// Returns the path with the given [`PathId`].
383    ///
384    /// Returns `None` if no open path with that id is present in
385    /// this snapshot.
386    pub fn get(&self, id: PathId) -> Option<Path<'_>> {
387        self.iter().find(|p| p.id() == id)
388    }
389}
390
391impl<'a> IntoIterator for &'a PathList<'a> {
392    type IntoIter = PathListIter<'a>;
393    type Item = Path<'a>;
394    fn into_iter(self) -> Self::IntoIter {
395        self.iter()
396    }
397}
398
399/// An iterator over the open paths in a [`PathList`] snapshot.
400#[derive(Debug)]
401pub struct PathListIter<'a> {
402    inner: std::slice::Iter<'a, PathData>,
403    selected: Option<PathId>,
404    conn: &'a noq::Connection,
405}
406
407impl<'a> PathListIter<'a> {
408    fn item(&self, data: &'a PathData) -> Path<'a> {
409        Path {
410            data,
411            is_selected: self.selected == Some(data.handle.id()),
412            conn: self.conn,
413        }
414    }
415}
416
417impl<'a> Iterator for PathListIter<'a> {
418    type Item = Path<'a>;
419
420    fn next(&mut self) -> Option<Self::Item> {
421        self.inner.next().map(|d| self.item(d))
422    }
423
424    fn size_hint(&self) -> (usize, Option<usize>) {
425        self.inner.size_hint()
426    }
427}
428
429impl<'a> DoubleEndedIterator for PathListIter<'a> {
430    fn next_back(&mut self) -> Option<Self::Item> {
431        self.inner.next_back().map(|d| self.item(d))
432    }
433}
434
435impl ExactSizeIterator for PathListIter<'_> {}
436
437/// A single path within a [`PathList`] snapshot.
438///
439/// Borrows from the enclosing [`PathList`] and from the [`Connection`]
440/// that produced it, so a [`Path`] cannot cross a task boundary. If you need
441/// to send path data to other tasks, you can clone [`Self::remote_addr`] or
442/// [`Self::stats`] into an owned value first.
443///
444/// [`Connection`]: crate::endpoint::Connection
445#[derive(Clone, Debug)]
446pub struct Path<'a> {
447    data: &'a PathData,
448    is_selected: bool,
449    /// Reference to a `noq::Connection` for safe upgrading via [`PathData::upgrade`]
450    conn: &'a noq::Connection,
451}
452
453impl<'conn> Path<'conn> {
454    /// Returns the path's [`PathId`].
455    pub fn id(&self) -> PathId {
456        self.data.handle.id()
457    }
458
459    /// Returns the path's remote transport address.
460    pub fn remote_addr(&self) -> &TransportAddr {
461        &self.data.remote_addr
462    }
463
464    /// Returns the path's local address, if known.
465    pub fn local_addr(&self) -> &LocalTransportAddr {
466        &self.data.local_addr
467    }
468
469    /// Returns `true` if this path is currently selected for application data transmission.
470    pub fn is_selected(&self) -> bool {
471        self.is_selected
472    }
473
474    /// Returns `true` if this is a direct IP path.
475    pub fn is_ip(&self) -> bool {
476        self.data.remote_addr.is_ip()
477    }
478
479    /// Returns `true` if this is a relay path.
480    pub fn is_relay(&self) -> bool {
481        self.data.remote_addr.is_relay()
482    }
483
484    /// Returns the path's statistics.
485    ///
486    /// Returns live statistics from the QUIC state for an open path, or
487    /// the final statistics retained by `noq` for a path that closed
488    /// after this snapshot was taken.
489    pub fn stats(&self) -> PathStats {
490        self.data.upgrade(self.conn).stats()
491    }
492
493    /// Returns the path's round-trip time estimate.
494    pub fn rtt(&self) -> Duration {
495        self.stats().rtt
496    }
497}
498
499/// A stream of [`PathList`] snapshots for a connection.
500///
501/// Returned by [`Connection::paths_stream`]. Yields a snapshot taken at
502/// creation, then one whenever the open paths or the selected path change.
503/// Ends once the connection closes and keeps returning `None` after that.
504///
505/// After a wait method returns, the next poll yields its snapshot again.
506///
507/// # Cancel safety
508///
509/// The wait methods are cancel safe. If one is used in `tokio::select!` and
510/// another branch completes first, no snapshot is lost: the next poll of the
511/// stream yields the last snapshot the method checked, and calling it again
512/// checks the current paths before waiting.
513///
514/// [`Connection::paths_stream`]: crate::endpoint::Connection::paths_stream
515#[derive(Debug)]
516pub struct PathListStream<'conn> {
517    shared: &'conn Shared,
518    conn: &'conn noq::Connection,
519    notified: Pin<Box<Notified<'conn>>>,
520    /// The latest snapshot, if not yet yielded.
521    ///
522    /// Also backs the results of [`Self::wait_any`] and [`Self::wait_none`].
523    next_value: Option<PathList<'conn>>,
524}
525
526impl<'conn> PathListStream<'conn> {
527    /// Waits until an open path matches `predicate` and returns it.
528    ///
529    /// Checks the current paths first. Returns `None` if the stream ends first.
530    ///
531    /// # Cancel safety
532    ///
533    /// This method is cancel safe. See [`PathListStream`](PathListStream#cancel-safety).
534    pub async fn wait_any(
535        &mut self,
536        mut predicate: impl FnMut(&Path<'_>) -> bool,
537    ) -> Option<Path<'_>> {
538        let (id, paths) = self
539            .wait_for(|paths| {
540                paths
541                    .iter()
542                    .find(|path| predicate(path))
543                    .map(|path| path.id())
544            })
545            .await?;
546        paths.get(id)
547    }
548
549    /// Waits until no open path matches `predicate` and returns the snapshot.
550    ///
551    /// Checks the current paths first. Returns `None` if the stream ends first.
552    ///
553    /// # Cancel safety
554    ///
555    /// This method is cancel safe. See [`PathListStream`](PathListStream#cancel-safety).
556    pub async fn wait_none(
557        &mut self,
558        mut predicate: impl FnMut(&Path<'_>) -> bool,
559    ) -> Option<&PathList<'conn>> {
560        let ((), paths) = self
561            .wait_for(|paths| (!paths.iter().any(|path| predicate(&path))).then_some(()))
562            .await?;
563        Some(paths)
564    }
565
566    /// Waits until the path with `id` is closed and returns the snapshot without it.
567    ///
568    /// Checks the current paths first. Returns `None` if the stream ends first.
569    ///
570    /// If the path is already closed, it immediately returns the current snapshot.
571    ///
572    /// # Cancel safety
573    ///
574    /// This method is cancel safe. See [`PathListStream`](PathListStream#cancel-safety).
575    pub async fn wait_closed(&mut self, id: PathId) -> Option<&PathList<'conn>> {
576        self.wait_none(|path| path.id() == id).await
577    }
578
579    /// Waits until `f` returns `Some` for the current or a later snapshot.
580    ///
581    /// Keeps the last checked snapshot in [`Self::next_value`], so cancelling
582    /// does not skip it.
583    async fn wait_for<T>(
584        &mut self,
585        mut f: impl FnMut(&PathList<'conn>) -> Option<T>,
586    ) -> Option<(T, &PathList<'conn>)> {
587        loop {
588            let paths = self.current();
589            if paths.snapshot.closed {
590                self.next_value = Some(paths);
591                return None;
592            }
593            if let Some(value) = f(&paths) {
594                return Some((value, self.next_value.insert(paths)));
595            }
596            self.next_value = Some(paths);
597            std::future::poll_fn(|cx| self.notified.as_mut().poll(cx)).await;
598        }
599    }
600
601    /// Re-arms [`Self::notified`], then returns the current state.
602    fn current(&mut self) -> PathList<'conn> {
603        self.notified.set(self.shared.notify.notified());
604        PathList {
605            snapshot: self.shared.state.lock().expect("poisoned").clone(),
606            conn: self.conn,
607        }
608    }
609}
610
611impl<'conn> Stream for PathListStream<'conn> {
612    type Item = PathList<'conn>;
613
614    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
615        let this = self.get_mut();
616        let paths = match this.next_value.take() {
617            Some(paths) => paths,
618            None => {
619                std::task::ready!(this.notified.as_mut().poll(cx));
620                this.current()
621            }
622        };
623        if paths.snapshot.closed {
624            // Keep it so later polls end too.
625            this.next_value = Some(paths);
626            Poll::Ready(None)
627        } else {
628            Poll::Ready(Some(paths))
629        }
630    }
631}
632
633/// A `'static` stream of [`PathEvent`]s.
634///
635/// Returned by [`Connection::path_events`].
636///
637/// [`Connection::path_events`]: crate::endpoint::Connection::path_events
638#[derive(Debug)]
639pub struct PathEventStream {
640    inner: BroadcastStream<PathEvent>,
641}
642
643impl Stream for PathEventStream {
644    type Item = PathEvent;
645    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
646        self.inner.poll_next(cx).map(|event| match event? {
647            Ok(event) => Some(event),
648            Err(BroadcastStreamRecvError::Lagged(missed)) => Some(PathEvent::Lagged { missed }),
649        })
650    }
651}