Skip to main content

weirdnet_net/
events.rs

1//! What a running node reports (W5): an [`Event`] stream and a [`Status`] watch, for apps
2//! that show connectivity, and the lifecycle calls a mobile or desktop app makes
3//! ([`Node::pause`], [`Node::resume`], [`Node::network_changed`]).
4//!
5//! [`Node::pause`]: crate::Node::pause
6//! [`Node::resume`]: crate::Node::resume
7//! [`Node::network_changed`]: crate::Node::network_changed
8use crate::node::Status;
9use crate::stream::Path;
10use futures::StreamExt;
11use futures::channel::mpsc;
12use libp2p::{Multiaddr, PeerId};
13use std::pin::Pin;
14use std::sync::{Arc, Mutex};
15use std::task::{Context, Poll};
16use std::time::{Duration, Instant};
17
18/// Something that changed in the node.
19#[derive(Debug, Clone, PartialEq, Eq)]
20#[non_exhaustive]
21pub enum Event {
22    /// Listening on an address (a circuit through a relay included).
23    Listening(Multiaddr),
24    /// An address stopped being listened on.
25    ListenClosed(Multiaddr),
26    /// Others confirmed they reach us here (`true`), or no longer do (`false`).
27    External {
28        addr: Multiaddr,
29        confirmed: bool,
30    },
31    /// A connection to `peer` came up.
32    Connected {
33        peer: PeerId,
34        path: Path,
35    },
36    /// A connection to `peer` went away; `remaining` are still open.
37    Disconnected {
38        peer: PeerId,
39        path: Path,
40        remaining: u32,
41    },
42    /// A relay holds a reservation for us.
43    Reserved {
44        relay: PeerId,
45    },
46    /// A relay's reservation is gone (the node asks again while it isn't paused).
47    ReservationLost {
48        relay: PeerId,
49    },
50    /// AutoNAT's verdict: `public`, `private` or `unknown`.
51    Nat(String),
52    Paused,
53    Resumed,
54    NetworkChanged,
55}
56
57/// Where the loop sends events: every live [`Events`] gets each one.
58#[derive(Clone, Default)]
59pub(crate) struct Hub {
60    subs: Arc<Mutex<Vec<mpsc::UnboundedSender<Event>>>>,
61}
62
63impl Hub {
64    pub(crate) fn send(&self, e: Event) {
65        if let Ok(mut s) = self.subs.lock() {
66            s.retain(|t| t.unbounded_send(e.clone()).is_ok());
67        }
68    }
69
70    pub(crate) fn subscribe(&self) -> Events {
71        let (tx, rx) = mpsc::unbounded();
72        if let Ok(mut s) = self.subs.lock() {
73            s.push(tx);
74        }
75        Events { rx }
76    }
77}
78
79/// The node's events from when this was made on, as a `futures` stream or by blocking.
80pub struct Events {
81    rx: mpsc::UnboundedReceiver<Event>,
82}
83
84impl Events {
85    /// The next event, waiting at most `d` (`None`: none in time, or the node stopped).
86    pub fn next_timeout(&mut self, d: Duration) -> Option<Event> {
87        let end = Instant::now() + d;
88        loop {
89            match self.rx.try_recv() {
90                Ok(e) => return Some(e),
91                Err(mpsc::TryRecvError::Closed) => return None,
92                Err(mpsc::TryRecvError::Empty) if Instant::now() >= end => return None,
93                Err(mpsc::TryRecvError::Empty) => std::thread::sleep(Duration::from_millis(5)),
94            }
95        }
96    }
97
98    /// Wait (at most `d`) for an event `f` picks.
99    pub fn wait_for(&mut self, d: Duration, mut f: impl FnMut(&Event) -> bool) -> Option<Event> {
100        let end = Instant::now() + d;
101        while let Some(e) = self.next_timeout(end.saturating_duration_since(Instant::now())) {
102            if f(&e) {
103                return Some(e);
104            }
105        }
106        None
107    }
108}
109
110impl futures::Stream for Events {
111    type Item = Event;
112
113    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Event>> {
114        self.rx.poll_next_unpin(cx)
115    }
116}
117
118/// The latest [`Status`], with a way to wait for the next change.
119#[derive(Clone)]
120pub struct StatusWatch {
121    pub(crate) rx: tokio::sync::watch::Receiver<Status>,
122}
123
124impl StatusWatch {
125    pub fn get(&self) -> Status {
126        self.rx.borrow().clone()
127    }
128
129    /// Wait for the status to change (any executor); `None` once the node has stopped.
130    pub async fn changed(&mut self) -> Option<Status> {
131        self.rx.changed().await.ok()?;
132        Some(self.rx.borrow_and_update().clone())
133    }
134
135    /// Block until the status changes, at most `d`.
136    pub fn wait_change(&mut self, d: Duration) -> Option<Status> {
137        let end = Instant::now() + d;
138        loop {
139            if self.rx.has_changed().ok()? {
140                return Some(self.rx.borrow_and_update().clone());
141            }
142            if Instant::now() >= end {
143                return None;
144            }
145            std::thread::sleep(Duration::from_millis(5));
146        }
147    }
148}