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                state.selected = selected_path_id;
236                selected_path_id.map(|path_id| PathEvent::Selected {
237                    id: path_id,
238                    remote_addr: remote_addr.clone(),
239                    local_addr: local_addr.clone(),
240                })
241            } else {
242                None
243            }
244        };
245        if let Some(event) = event {
246            let _ = self.events.send(event);
247            self.shared.notify.notify_waiters();
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 the current snapshot on the first poll, then a fresh
335    /// snapshot on every state change. Ends when the state is marked
336    /// closed.
337    pub(crate) fn stream<'a>(&'a self, conn: &'a noq::Connection) -> PathListStream<'a> {
338        PathListStream {
339            shared: &self.shared,
340            conn,
341            notified: Box::pin(self.shared.notify.notified()),
342            first_poll: true,
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 the current
502/// snapshot on the first poll and a fresh snapshot whenever the open
503/// paths or the selected path change. Ends when the connection closes.
504///
505/// [`Connection::paths_stream`]: crate::endpoint::Connection::paths_stream
506#[derive(Debug)]
507pub struct PathListStream<'conn> {
508    shared: &'conn Shared,
509    conn: &'conn noq::Connection,
510    notified: Pin<Box<Notified<'conn>>>,
511    first_poll: bool,
512}
513
514impl<'conn> Stream for PathListStream<'conn> {
515    type Item = PathList<'conn>;
516
517    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
518        let this = self.get_mut();
519        if this.first_poll {
520            this.first_poll = false;
521        } else {
522            std::task::ready!(this.notified.as_mut().poll(cx));
523            this.notified.set(this.shared.notify.notified());
524        }
525        this.notified.as_mut().enable();
526        let snapshot = this.shared.state.lock().expect("poisoned").clone();
527        if snapshot.closed {
528            Poll::Ready(None)
529        } else {
530            Poll::Ready(Some(PathList {
531                snapshot,
532                conn: this.conn,
533            }))
534        }
535    }
536}
537
538/// A `'static` stream of [`PathEvent`]s.
539///
540/// Returned by [`Connection::path_events`].
541///
542/// [`Connection::path_events`]: crate::endpoint::Connection::path_events
543#[derive(Debug)]
544pub struct PathEventStream {
545    inner: BroadcastStream<PathEvent>,
546}
547
548impl Stream for PathEventStream {
549    type Item = PathEvent;
550    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
551        self.inner.poll_next(cx).map(|event| match event? {
552            Ok(event) => Some(event),
553            Err(BroadcastStreamRecvError::Lagged(missed)) => Some(PathEvent::Lagged { missed }),
554        })
555    }
556}