use core::fmt;
use core::pin::Pin;
use core::task::{Context, Poll};
use futures_util::{Stream, StreamExt};
use tokio::sync::broadcast;
use tokio_stream::wrappers::BroadcastStream;
use tokio_stream::wrappers::errors::BroadcastStreamRecvError;
use shep_core::protocol::BusEvent;
#[derive(Debug)]
pub struct EventStream {
inner: BroadcastStream<BusEvent>,
}
impl EventStream {
pub(crate) fn new(receiver: broadcast::Receiver<BusEvent>) -> Self {
Self {
inner: BroadcastStream::new(receiver),
}
}
pub async fn next(&mut self) -> Option<Result<BusEvent, Lagged>> {
StreamExt::next(self).await
}
}
impl Stream for EventStream {
type Item = Result<BusEvent, Lagged>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match Pin::new(&mut self.inner).poll_next(cx) {
Poll::Ready(Some(Ok(event))) => Poll::Ready(Some(Ok(event))),
Poll::Ready(Some(Err(BroadcastStreamRecvError::Lagged(count)))) => {
Poll::Ready(Some(Err(Lagged { count })))
}
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Lagged {
pub count: u64,
}
impl fmt::Display for Lagged {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} events dropped locally (lagged)", self.count)
}
}
impl core::error::Error for Lagged {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lagged_is_printable_and_a_real_error() {
let lagged = Lagged { count: 7 };
assert_eq!(lagged.to_string(), "7 events dropped locally (lagged)");
let _: &dyn core::error::Error = &lagged;
}
}