use crate::agent::AgentEvent;
use std::sync::Arc;
use tokio::sync::broadcast;
#[derive(Debug, Clone)]
pub struct BusEvent {
pub event: Arc<AgentEvent>,
pub run_id: Option<String>,
pub agent_id: Option<String>,
}
pub struct EventBus {
sender: broadcast::Sender<Arc<BusEvent>>,
}
impl EventBus {
pub fn new(capacity: usize) -> Self {
let (sender, _) = broadcast::channel(capacity);
Self { sender }
}
pub fn subscribe(&self) -> broadcast::Receiver<Arc<BusEvent>> {
self.sender.subscribe()
}
pub fn send_with(&self, event: AgentEvent, run_id: Option<String>, agent_id: Option<String>) {
let _ = self.sender.send(Arc::new(BusEvent {
event: Arc::new(event),
run_id,
agent_id,
}));
}
pub fn send(&self, event: AgentEvent) {
self.send_with(event, None, None);
}
pub fn send_for_run(&self, event: AgentEvent, run_id: &str) {
self.send_with(event, Some(run_id.to_string()), None);
}
pub fn subscriber_count(&self) -> usize {
self.sender.receiver_count()
}
}
impl Default for EventBus {
fn default() -> Self {
Self::new(1024)
}
}
pub static GLOBAL_EVENT_BUS: std::sync::LazyLock<Arc<EventBus>> =
std::sync::LazyLock::new(|| Arc::new(EventBus::new(1024)));