use crate::node::Status;
use crate::stream::Path;
use futures::StreamExt;
use futures::channel::mpsc;
use libp2p::{Multiaddr, PeerId};
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Event {
Listening(Multiaddr),
ListenClosed(Multiaddr),
External {
addr: Multiaddr,
confirmed: bool,
},
Connected {
peer: PeerId,
path: Path,
},
Disconnected {
peer: PeerId,
path: Path,
remaining: u32,
},
Reserved {
relay: PeerId,
},
ReservationLost {
relay: PeerId,
},
Nat(String),
Paused,
Resumed,
NetworkChanged,
}
#[derive(Clone, Default)]
pub(crate) struct Hub {
subs: Arc<Mutex<Vec<mpsc::UnboundedSender<Event>>>>,
}
impl Hub {
pub(crate) fn send(&self, e: Event) {
if let Ok(mut s) = self.subs.lock() {
s.retain(|t| t.unbounded_send(e.clone()).is_ok());
}
}
pub(crate) fn subscribe(&self) -> Events {
let (tx, rx) = mpsc::unbounded();
if let Ok(mut s) = self.subs.lock() {
s.push(tx);
}
Events { rx }
}
}
pub struct Events {
rx: mpsc::UnboundedReceiver<Event>,
}
impl Events {
pub fn next_timeout(&mut self, d: Duration) -> Option<Event> {
let end = Instant::now() + d;
loop {
match self.rx.try_recv() {
Ok(e) => return Some(e),
Err(mpsc::TryRecvError::Closed) => return None,
Err(mpsc::TryRecvError::Empty) if Instant::now() >= end => return None,
Err(mpsc::TryRecvError::Empty) => std::thread::sleep(Duration::from_millis(5)),
}
}
}
pub fn wait_for(&mut self, d: Duration, mut f: impl FnMut(&Event) -> bool) -> Option<Event> {
let end = Instant::now() + d;
while let Some(e) = self.next_timeout(end.saturating_duration_since(Instant::now())) {
if f(&e) {
return Some(e);
}
}
None
}
}
impl futures::Stream for Events {
type Item = Event;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Event>> {
self.rx.poll_next_unpin(cx)
}
}
#[derive(Clone)]
pub struct StatusWatch {
pub(crate) rx: tokio::sync::watch::Receiver<Status>,
}
impl StatusWatch {
pub fn get(&self) -> Status {
self.rx.borrow().clone()
}
pub async fn changed(&mut self) -> Option<Status> {
self.rx.changed().await.ok()?;
Some(self.rx.borrow_and_update().clone())
}
pub fn wait_change(&mut self, d: Duration) -> Option<Status> {
let end = Instant::now() + d;
loop {
if self.rx.has_changed().ok()? {
return Some(self.rx.borrow_and_update().clone());
}
if Instant::now() >= end {
return None;
}
std::thread::sleep(Duration::from_millis(5));
}
}
}