#![allow(dead_code)]
use super::system_events::SystemEvent;
use tokio::sync::broadcast::{self, error::SendError, Receiver, Sender};
use tracing;
const DEFAULT_EVENT_BUS_CAPACITY: usize = 256;
#[derive(Debug, Clone)]
pub struct EventBus {
sender: Sender<SystemEvent>,
}
impl EventBus {
pub fn new() -> Self {
let (sender, _) = broadcast::channel(DEFAULT_EVENT_BUS_CAPACITY);
tracing::debug!(capacity = DEFAULT_EVENT_BUS_CAPACITY, "Created new EventBus");
Self { sender }
}
pub fn with_capacity(capacity: usize) -> Self {
let (sender, _) = broadcast::channel(capacity.max(1)); tracing::debug!(capacity = capacity.max(1), "Created new EventBus with capacity");
Self { sender }
}
pub fn publish(&self, event: SystemEvent) -> Result<usize, SendError<SystemEvent>> {
tracing::trace!(event = ?event, "Publishing event");
self.sender.send(event)
}
pub fn subscribe(&self) -> Receiver<SystemEvent> {
tracing::trace!("Creating new event bus subscription");
self.sender.subscribe()
}
pub fn subscriber_count(&self) -> usize {
self.sender.receiver_count()
}
}
impl Default for EventBus {
fn default() -> Self {
Self::new()
}
}