Skip to main content

moonproof_utils/
events.rs

1//! Generic event bus over `tokio::sync::broadcast`.
2//!
3//! Single source of truth for the "subscribe to mutation events"
4//! pattern used across moonproof storage wrappers. Each consumer
5//! crate wraps its storage trait in a domain-specific type and
6//! routes notifications through this primitive — no need to
7//! reimplement the `broadcast::channel` + `subscribe()` +
8//! `subscriber_count()` boilerplate per domain.
9
10use tokio::sync::broadcast;
11
12/// Default channel capacity. Slow subscribers that fall behind by
13/// more than this many events get a `Lagged` error from the
14/// receiver; recovery is "fetch the full state via the store's
15/// `get_all` and resume listening".
16pub const DEFAULT_CAPACITY: usize = 256;
17
18/// Multi-producer multi-consumer event bus. Cheap to clone — the
19/// inner `broadcast::Sender` is `Arc`-backed.
20#[derive(Debug)]
21pub struct EventBus<E: Clone + Send + 'static> {
22    sender: broadcast::Sender<E>,
23}
24
25impl<E: Clone + Send + 'static> Clone for EventBus<E> {
26    fn clone(&self) -> Self {
27        Self {
28            sender: self.sender.clone(),
29        }
30    }
31}
32
33impl<E: Clone + Send + 'static> EventBus<E> {
34    /// New bus with [`DEFAULT_CAPACITY`].
35    #[must_use]
36    pub fn new() -> Self {
37        Self::with_capacity(DEFAULT_CAPACITY)
38    }
39
40    /// New bus with explicit capacity. Clamped to at least 1.
41    #[must_use]
42    pub fn with_capacity(capacity: usize) -> Self {
43        let (sender, _) = broadcast::channel(capacity.max(1));
44        Self { sender }
45    }
46
47    /// Publish `event`. Returns silently when there are zero
48    /// receivers — by design, no listeners is not an error from the
49    /// publisher's perspective.
50    pub fn publish(&self, event: E) {
51        let _ = self.sender.send(event);
52    }
53
54    /// Subscribe to events. Each receiver sees every event emitted
55    /// from the moment of subscription forward.
56    pub fn subscribe(&self) -> broadcast::Receiver<E> {
57        self.sender.subscribe()
58    }
59
60    /// Live subscriber count. Useful for skipping notification work
61    /// when nobody is listening (cheap optimisation in mutation paths).
62    #[must_use]
63    pub fn subscriber_count(&self) -> usize {
64        self.sender.receiver_count()
65    }
66}
67
68impl<E: Clone + Send + 'static> Default for EventBus<E> {
69    fn default() -> Self {
70        Self::new()
71    }
72}
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77
78    #[tokio::test]
79    async fn publish_reaches_every_subscriber() {
80        let bus: EventBus<u32> = EventBus::new();
81        let mut a = bus.subscribe();
82        let mut b = bus.subscribe();
83        bus.publish(7);
84        assert_eq!(a.recv().await.unwrap(), 7);
85        assert_eq!(b.recv().await.unwrap(), 7);
86    }
87
88    #[tokio::test]
89    async fn publish_with_no_subscribers_is_silent() {
90        let bus: EventBus<u32> = EventBus::new();
91        bus.publish(7);
92        // Subsequent subscribers do NOT see events from before
93        // their subscription — verify by checking new receiver
94        // gets only post-subscribe events.
95        let mut rx = bus.subscribe();
96        bus.publish(8);
97        assert_eq!(rx.recv().await.unwrap(), 8);
98    }
99
100    #[test]
101    fn subscriber_count_tracks_receivers() {
102        let bus: EventBus<u32> = EventBus::new();
103        assert_eq!(bus.subscriber_count(), 0);
104        let first = bus.subscribe();
105        let _second = bus.subscribe();
106        assert_eq!(bus.subscriber_count(), 2);
107        drop(first);
108        assert_eq!(bus.subscriber_count(), 1);
109    }
110
111    #[test]
112    fn clone_shares_subscribers() {
113        let bus: EventBus<u32> = EventBus::new();
114        let bus2 = bus.clone();
115        let _rx = bus.subscribe();
116        assert_eq!(bus2.subscriber_count(), 1);
117    }
118}