2019-08-26 11:44:00 +00:00
|
|
|
use std::future::Future;
|
|
|
|
use std::pin::Pin;
|
|
|
|
use std::sync::{Arc, Mutex};
|
2019-04-26 15:56:41 +00:00
|
|
|
|
2020-04-17 12:11:25 +00:00
|
|
|
use anyhow::{format_err, Error};
|
2019-08-26 11:44:00 +00:00
|
|
|
use futures::future::{FutureExt, TryFutureExt};
|
2019-04-26 15:56:41 +00:00
|
|
|
use tokio::sync::oneshot;
|
|
|
|
|
2019-04-30 06:40:13 +00:00
|
|
|
/// Broadcast results to registered listeners using asnyc oneshot channels
|
2019-10-26 09:36:01 +00:00
|
|
|
#[derive(Default)]
|
2019-04-30 06:40:13 +00:00
|
|
|
pub struct BroadcastData<T> {
|
2019-04-26 15:56:41 +00:00
|
|
|
result: Option<Result<T, String>>,
|
|
|
|
listeners: Vec<oneshot::Sender<Result<T, Error>>>,
|
|
|
|
}
|
|
|
|
|
2019-04-30 06:40:13 +00:00
|
|
|
impl <T: Clone> BroadcastData<T> {
|
2019-04-26 15:56:41 +00:00
|
|
|
|
2019-04-30 06:40:13 +00:00
|
|
|
pub fn new() -> Self {
|
|
|
|
Self {
|
2019-04-26 15:56:41 +00:00
|
|
|
result: None,
|
|
|
|
listeners: vec![],
|
2019-04-30 06:40:13 +00:00
|
|
|
}
|
2019-04-27 08:56:49 +00:00
|
|
|
}
|
|
|
|
|
2019-04-30 06:40:13 +00:00
|
|
|
pub fn notify_listeners(&mut self, result: Result<T, String>) {
|
2019-04-26 15:56:41 +00:00
|
|
|
|
2019-04-30 06:40:13 +00:00
|
|
|
self.result = Some(result.clone());
|
2019-04-26 15:56:41 +00:00
|
|
|
|
|
|
|
loop {
|
2019-04-30 06:40:13 +00:00
|
|
|
match self.listeners.pop() {
|
2019-04-26 15:56:41 +00:00
|
|
|
None => { break; },
|
|
|
|
Some(ch) => {
|
|
|
|
match &result {
|
|
|
|
Ok(result) => { let _ = ch.send(Ok(result.clone())); },
|
|
|
|
Err(err) => { let _ = ch.send(Err(format_err!("{}", err))); },
|
|
|
|
}
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-26 11:44:00 +00:00
|
|
|
pub fn listen(&mut self) -> impl Future<Output = Result<T, Error>> {
|
|
|
|
use futures::future::{ok, Either};
|
2019-04-26 15:56:41 +00:00
|
|
|
|
2019-04-30 06:40:13 +00:00
|
|
|
match &self.result {
|
2019-04-26 15:56:41 +00:00
|
|
|
None => {},
|
2019-08-26 11:44:00 +00:00
|
|
|
Some(Ok(result)) => return Either::Left(ok(result.clone())),
|
|
|
|
Some(Err(err)) => return Either::Left(futures::future::err(format_err!("{}", err))),
|
2019-04-26 15:56:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
let (tx, rx) = oneshot::channel::<Result<T, Error>>();
|
|
|
|
|
2019-04-30 06:40:13 +00:00
|
|
|
self.listeners.push(tx);
|
|
|
|
|
2019-08-26 11:44:00 +00:00
|
|
|
Either::Right(rx
|
|
|
|
.map(|res| match res {
|
|
|
|
Ok(Ok(t)) => Ok(t),
|
|
|
|
Ok(Err(e)) => Err(e),
|
|
|
|
Err(e) => Err(Error::from(e)),
|
|
|
|
})
|
|
|
|
)
|
2019-04-30 06:40:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-25 13:42:47 +00:00
|
|
|
type SourceFuture<T> = Pin<Box<dyn Future<Output = Result<T, Error>> + Send>>;
|
|
|
|
|
|
|
|
struct BroadCastFutureBinding<T> {
|
|
|
|
broadcast: BroadcastData<T>,
|
|
|
|
future: Option<SourceFuture<T>>,
|
|
|
|
}
|
|
|
|
|
2019-04-30 06:40:13 +00:00
|
|
|
/// Broadcast future results to registered listeners
|
|
|
|
pub struct BroadcastFuture<T> {
|
2021-01-25 13:42:47 +00:00
|
|
|
inner: Arc<Mutex<BroadCastFutureBinding<T>>>,
|
2019-04-30 06:40:13 +00:00
|
|
|
}
|
|
|
|
|
2019-08-26 11:44:00 +00:00
|
|
|
impl<T: Clone + Send + 'static> BroadcastFuture<T> {
|
2019-04-30 06:40:13 +00:00
|
|
|
/// Create instance for specified source future.
|
|
|
|
///
|
|
|
|
/// The result of the future is sent to all registered listeners.
|
2019-08-26 11:44:00 +00:00
|
|
|
pub fn new(source: Box<dyn Future<Output = Result<T, Error>> + Send>) -> Self {
|
2021-01-25 13:42:47 +00:00
|
|
|
let inner = BroadCastFutureBinding {
|
|
|
|
broadcast: BroadcastData::new(),
|
|
|
|
future: Some(Pin::from(source)),
|
|
|
|
};
|
|
|
|
Self { inner: Arc::new(Mutex::new(inner)) }
|
2019-04-30 06:40:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Creates a new instance with a oneshot channel as trigger
|
|
|
|
pub fn new_oneshot() -> (Self, oneshot::Sender<Result<T, Error>>) {
|
|
|
|
|
|
|
|
let (tx, rx) = oneshot::channel::<Result<T, Error>>();
|
2019-08-26 11:44:00 +00:00
|
|
|
let rx = rx
|
|
|
|
.map_err(Error::from)
|
2019-10-26 09:36:01 +00:00
|
|
|
.and_then(futures::future::ready);
|
2019-04-30 06:40:13 +00:00
|
|
|
|
2019-08-26 11:44:00 +00:00
|
|
|
(Self::new(Box::new(rx)), tx)
|
2019-04-30 06:40:13 +00:00
|
|
|
}
|
|
|
|
|
2019-08-26 11:44:00 +00:00
|
|
|
fn notify_listeners(
|
2021-01-25 13:42:47 +00:00
|
|
|
inner: Arc<Mutex<BroadCastFutureBinding<T>>>,
|
2019-08-26 11:44:00 +00:00
|
|
|
result: Result<T, String>,
|
|
|
|
) {
|
2019-04-30 06:40:13 +00:00
|
|
|
let mut data = inner.lock().unwrap();
|
2021-01-25 13:42:47 +00:00
|
|
|
data.broadcast.notify_listeners(result);
|
2019-04-30 06:40:13 +00:00
|
|
|
}
|
|
|
|
|
2021-01-25 13:42:47 +00:00
|
|
|
fn spawn(inner: Arc<Mutex<BroadCastFutureBinding<T>>>) -> impl Future<Output = Result<T, Error>> {
|
2019-04-30 06:40:13 +00:00
|
|
|
let mut data = inner.lock().unwrap();
|
2019-04-26 15:56:41 +00:00
|
|
|
|
2021-01-25 13:42:47 +00:00
|
|
|
if let Some(source) = data.future.take() {
|
2019-04-26 15:56:41 +00:00
|
|
|
|
|
|
|
let inner1 = inner.clone();
|
|
|
|
|
2019-08-26 11:44:00 +00:00
|
|
|
let task = source.map(move |value| {
|
2019-04-26 15:56:41 +00:00
|
|
|
match value {
|
2021-01-15 13:38:27 +00:00
|
|
|
Ok(value) => Self::notify_listeners(inner1, Ok(value)),
|
2019-04-30 06:40:13 +00:00
|
|
|
Err(err) => Self::notify_listeners(inner1, Err(err.to_string())),
|
2019-04-26 15:56:41 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
tokio::spawn(task);
|
|
|
|
}
|
|
|
|
|
2021-01-25 13:42:47 +00:00
|
|
|
data.broadcast.listen()
|
2019-04-26 15:56:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Register a listener
|
2019-08-26 11:44:00 +00:00
|
|
|
pub fn listen(&self) -> impl Future<Output = Result<T, Error>> {
|
2019-04-26 15:56:41 +00:00
|
|
|
let inner2 = self.inner.clone();
|
2019-08-26 11:44:00 +00:00
|
|
|
async move { Self::spawn(inner2).await }
|
2019-04-26 15:56:41 +00:00
|
|
|
}
|
|
|
|
}
|
2019-04-27 08:56:49 +00:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_broadcast_future() {
|
|
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
|
|
|
|
|
|
static CHECKSUM: AtomicUsize = AtomicUsize::new(0);
|
|
|
|
|
|
|
|
let (sender, trigger) = BroadcastFuture::new_oneshot();
|
|
|
|
|
|
|
|
let receiver1 = sender.listen()
|
2019-08-26 11:44:00 +00:00
|
|
|
.map_ok(|res| {
|
2019-04-27 08:56:49 +00:00
|
|
|
CHECKSUM.fetch_add(res, Ordering::SeqCst);
|
|
|
|
})
|
2020-05-30 14:37:33 +00:00
|
|
|
.map_err(|err| { panic!("got error {}", err); })
|
2019-08-26 11:44:00 +00:00
|
|
|
.map(|_| ());
|
2019-04-27 08:56:49 +00:00
|
|
|
|
|
|
|
let receiver2 = sender.listen()
|
2019-08-26 11:44:00 +00:00
|
|
|
.map_ok(|res| {
|
2019-04-27 08:56:49 +00:00
|
|
|
CHECKSUM.fetch_add(res*2, Ordering::SeqCst);
|
|
|
|
})
|
2020-05-30 14:37:33 +00:00
|
|
|
.map_err(|err| { panic!("got error {}", err); })
|
2019-08-26 11:44:00 +00:00
|
|
|
.map(|_| ());
|
2019-04-27 08:56:49 +00:00
|
|
|
|
2020-12-04 10:53:34 +00:00
|
|
|
let rt = tokio::runtime::Runtime::new().unwrap();
|
2019-08-26 11:44:00 +00:00
|
|
|
rt.block_on(async move {
|
2019-12-17 09:47:11 +00:00
|
|
|
let r1 = tokio::spawn(receiver1);
|
|
|
|
let r2 = tokio::spawn(receiver2);
|
2019-04-27 08:56:49 +00:00
|
|
|
|
|
|
|
trigger.send(Ok(1)).unwrap();
|
2019-12-17 09:47:11 +00:00
|
|
|
let _ = r1.await;
|
|
|
|
let _ = r2.await;
|
2019-08-26 11:44:00 +00:00
|
|
|
});
|
2019-04-27 08:56:49 +00:00
|
|
|
|
|
|
|
let result = CHECKSUM.load(Ordering::SeqCst);
|
|
|
|
|
2019-12-13 11:33:49 +00:00
|
|
|
assert_eq!(result, 3);
|
2021-06-07 15:35:24 +00:00
|
|
|
|
|
|
|
// the result stays available until the BroadcastFuture is dropped
|
|
|
|
rt.block_on(sender.listen()
|
|
|
|
.map_ok(|res| {
|
|
|
|
CHECKSUM.fetch_add(res*4, Ordering::SeqCst);
|
|
|
|
})
|
|
|
|
.map_err(|err| { panic!("got error {}", err); })
|
|
|
|
.map(|_| ()));
|
|
|
|
|
|
|
|
let result = CHECKSUM.load(Ordering::SeqCst);
|
|
|
|
assert_eq!(result, 7);
|
2019-04-27 08:56:49 +00:00
|
|
|
}
|