1use 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#[derive(Debug, Clone, PartialEq, Eq)]
20#[non_exhaustive]
21pub enum Event {
22 Listening(Multiaddr),
24 ListenClosed(Multiaddr),
26 External {
28 addr: Multiaddr,
29 confirmed: bool,
30 },
31 Connected {
33 peer: PeerId,
34 path: Path,
35 },
36 Disconnected {
38 peer: PeerId,
39 path: Path,
40 remaining: u32,
41 },
42 Reserved {
44 relay: PeerId,
45 },
46 ReservationLost {
48 relay: PeerId,
49 },
50 Nat(String),
52 Paused,
53 Resumed,
54 NetworkChanged,
55}
56
57#[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
79pub struct Events {
81 rx: mpsc::UnboundedReceiver<Event>,
82}
83
84impl Events {
85 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 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#[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 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 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}