Skip to main content

shep_client/
events.rs

1//! [`EventStream`], the public subscription surface handed back by
2//! [`crate::Client::subscribe`], and [`Lagged`], the local-only drop notice
3//! it can yield.
4//!
5//! Wraps [`tokio_stream::wrappers::BroadcastStream`] rather than polling a
6//! raw [`broadcast::Receiver`] by hand: that receiver exposes no poll API at
7//! all (`recv` is `async`, and `try_recv` registers no waker, so a
8//! hand-rolled `poll_next` over it either does not compile or busy-spins).
9//! `BroadcastStream` is upstream's answer, built on tokio-util's
10//! `ReusableBoxFuture`, which owns the receiver between polls.
11
12use core::fmt;
13use core::pin::Pin;
14use core::task::{Context, Poll};
15
16use futures_util::{Stream, StreamExt};
17use tokio::sync::broadcast;
18use tokio_stream::wrappers::BroadcastStream;
19use tokio_stream::wrappers::errors::BroadcastStreamRecvError;
20
21use shep_core::protocol::BusEvent;
22
23/// Live bus events for one [`crate::Client::subscribe`] call.
24///
25/// Named rather than `impl Stream`: an anonymous return type cannot be
26/// spelled in a struct field, which a caller holding a subscription needs.
27/// Each item is `Ok(`[`BusEvent`]`)`, or `Err(`[`Lagged`]`)` when this
28/// stream's own local buffer fell behind. The stream ends once the
29/// connection closes; a `Lagged` item does not end it.
30#[derive(Debug)]
31pub struct EventStream {
32    inner: BroadcastStream<BusEvent>,
33}
34
35impl EventStream {
36    /// Wraps `receiver` in the named public stream type.
37    pub(crate) fn new(receiver: broadcast::Receiver<BusEvent>) -> Self {
38        Self {
39            inner: BroadcastStream::new(receiver),
40        }
41    }
42
43    /// Returns the next event, or `None` once the subscription ends.
44    ///
45    /// Inherent so a caller needs no `StreamExt` import: an inherent
46    /// method wins name resolution over a trait method of the same name.
47    pub async fn next(&mut self) -> Option<Result<BusEvent, Lagged>> {
48        StreamExt::next(self).await
49    }
50}
51
52impl Stream for EventStream {
53    type Item = Result<BusEvent, Lagged>;
54
55    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
56        // `BroadcastStreamRecvError` has exactly one variant and is not
57        // `#[non_exhaustive]`; no wildcard arm, so a new variant fails this build.
58        match Pin::new(&mut self.inner).poll_next(cx) {
59            Poll::Ready(Some(Ok(event))) => Poll::Ready(Some(Ok(event))),
60            Poll::Ready(Some(Err(BroadcastStreamRecvError::Lagged(count)))) => {
61                Poll::Ready(Some(Err(Lagged { count })))
62            }
63            Poll::Ready(None) => Poll::Ready(None),
64            Poll::Pending => Poll::Pending,
65        }
66    }
67}
68
69/// The local [`broadcast::Receiver`] behind an [`EventStream`] fell behind
70/// and discarded events before this stream could read them.
71///
72/// Distinct from [`BusEvent::Dropped`]: the daemon's own queue
73/// overflowing. That arrives as an ordinary `Ok(BusEvent::Dropped { .. })`
74/// item on this same stream.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub struct Lagged {
77    /// How many events were discarded since this stream's last successful
78    /// read.
79    pub count: u64,
80}
81
82impl fmt::Display for Lagged {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        write!(f, "{} events dropped locally (lagged)", self.count)
85    }
86}
87
88impl core::error::Error for Lagged {}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93
94    /// `Lagged` implements `Display` and `core::error::Error` like this
95    /// crate's other error types, so a consumer can print it or `?` it
96    /// into `anyhow`.
97    #[test]
98    fn lagged_is_printable_and_a_real_error() {
99        let lagged = Lagged { count: 7 };
100        assert_eq!(lagged.to_string(), "7 events dropped locally (lagged)");
101
102        // compiles only if `Lagged: core::error::Error`; `to_string()` alone needs only `Display`
103        let _: &dyn core::error::Error = &lagged;
104    }
105}