moonproof-utils 0.2.1

Shared helpers (hex parsing, validation) used across moonproof crates. Mirror of midnight-js/packages/utils.
Documentation
//! Generic event bus over `tokio::sync::broadcast`.
//!
//! Single source of truth for the "subscribe to mutation events"
//! pattern used across moonproof storage wrappers. Each consumer
//! crate wraps its storage trait in a domain-specific type and
//! routes notifications through this primitive — no need to
//! reimplement the `broadcast::channel` + `subscribe()` +
//! `subscriber_count()` boilerplate per domain.

use tokio::sync::broadcast;

/// Default channel capacity. Slow subscribers that fall behind by
/// more than this many events get a `Lagged` error from the
/// receiver; recovery is "fetch the full state via the store's
/// `get_all` and resume listening".
pub const DEFAULT_CAPACITY: usize = 256;

/// Multi-producer multi-consumer event bus. Cheap to clone — the
/// inner `broadcast::Sender` is `Arc`-backed.
#[derive(Debug)]
pub struct EventBus<E: Clone + Send + 'static> {
    sender: broadcast::Sender<E>,
}

impl<E: Clone + Send + 'static> Clone for EventBus<E> {
    fn clone(&self) -> Self {
        Self {
            sender: self.sender.clone(),
        }
    }
}

impl<E: Clone + Send + 'static> EventBus<E> {
    /// New bus with [`DEFAULT_CAPACITY`].
    #[must_use]
    pub fn new() -> Self {
        Self::with_capacity(DEFAULT_CAPACITY)
    }

    /// New bus with explicit capacity. Clamped to at least 1.
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Self {
        let (sender, _) = broadcast::channel(capacity.max(1));
        Self { sender }
    }

    /// Publish `event`. Returns silently when there are zero
    /// receivers — by design, no listeners is not an error from the
    /// publisher's perspective.
    pub fn publish(&self, event: E) {
        let _ = self.sender.send(event);
    }

    /// Subscribe to events. Each receiver sees every event emitted
    /// from the moment of subscription forward.
    pub fn subscribe(&self) -> broadcast::Receiver<E> {
        self.sender.subscribe()
    }

    /// Live subscriber count. Useful for skipping notification work
    /// when nobody is listening (cheap optimisation in mutation paths).
    #[must_use]
    pub fn subscriber_count(&self) -> usize {
        self.sender.receiver_count()
    }
}

impl<E: Clone + Send + 'static> Default for EventBus<E> {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn publish_reaches_every_subscriber() {
        let bus: EventBus<u32> = EventBus::new();
        let mut a = bus.subscribe();
        let mut b = bus.subscribe();
        bus.publish(7);
        assert_eq!(a.recv().await.unwrap(), 7);
        assert_eq!(b.recv().await.unwrap(), 7);
    }

    #[tokio::test]
    async fn publish_with_no_subscribers_is_silent() {
        let bus: EventBus<u32> = EventBus::new();
        bus.publish(7);
        // Subsequent subscribers do NOT see events from before
        // their subscription — verify by checking new receiver
        // gets only post-subscribe events.
        let mut rx = bus.subscribe();
        bus.publish(8);
        assert_eq!(rx.recv().await.unwrap(), 8);
    }

    #[test]
    fn subscriber_count_tracks_receivers() {
        let bus: EventBus<u32> = EventBus::new();
        assert_eq!(bus.subscriber_count(), 0);
        let first = bus.subscribe();
        let _second = bus.subscribe();
        assert_eq!(bus.subscriber_count(), 2);
        drop(first);
        assert_eq!(bus.subscriber_count(), 1);
    }

    #[test]
    fn clone_shares_subscribers() {
        let bus: EventBus<u32> = EventBus::new();
        let bus2 = bus.clone();
        let _rx = bus.subscribe();
        assert_eq!(bus2.subscriber_count(), 1);
    }
}