moonproof_utils/
events.rs1use tokio::sync::broadcast;
11
12pub const DEFAULT_CAPACITY: usize = 256;
17
18#[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 #[must_use]
36 pub fn new() -> Self {
37 Self::with_capacity(DEFAULT_CAPACITY)
38 }
39
40 #[must_use]
42 pub fn with_capacity(capacity: usize) -> Self {
43 let (sender, _) = broadcast::channel(capacity.max(1));
44 Self { sender }
45 }
46
47 pub fn publish(&self, event: E) {
51 let _ = self.sender.send(event);
52 }
53
54 pub fn subscribe(&self) -> broadcast::Receiver<E> {
57 self.sender.subscribe()
58 }
59
60 #[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 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}