use serde_json::Value;
use std::collections::HashMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SubscriptionId(usize);
type EventHandler = Box<dyn Fn(&Value) -> Result<(), Box<dyn std::error::Error>> + Send + Sync>;
#[allow(dead_code)]
pub struct EventBus {
handlers: HashMap<String, Vec<(SubscriptionId, EventHandler)>>,
next_id: usize,
}
#[allow(dead_code)]
impl EventBus {
pub fn new() -> Self {
Self {
handlers: HashMap::new(),
next_id: 0,
}
}
pub fn subscribe(
&mut self,
event: &str,
handler: impl Fn(&Value) -> Result<(), Box<dyn std::error::Error>> + Send + Sync + 'static,
) -> SubscriptionId {
let id = SubscriptionId(self.next_id);
self.next_id += 1;
self.handlers
.entry(event.to_string())
.or_default()
.push((id, Box::new(handler)));
id
}
pub fn unsubscribe(&mut self, event: &str, id: SubscriptionId) {
if let Some(handlers) = self.handlers.get_mut(event) {
handlers.retain(|(sub_id, _)| *sub_id != id);
}
}
pub fn publish(&self, event: &str, payload: &Value) -> Result<(), Box<dyn std::error::Error>> {
if let Some(handlers) = self.handlers.get(event) {
for (_, handler) in handlers {
handler(payload)?;
}
}
Ok(())
}
}
impl Default for EventBus {
fn default() -> Self {
Self::new()
}
}
#[allow(dead_code)]
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use std::sync::{Arc, Mutex};
fn recording(
log: Arc<Mutex<Vec<String>>>,
) -> impl Fn(&Value) -> Result<(), Box<dyn std::error::Error>> + Send + Sync {
move |payload: &Value| {
if let Some(s) = payload.as_str() {
log.lock().unwrap().push(s.to_string());
}
Ok(())
}
}
#[test]
fn subscribe_publish_delivers_payload() {
let mut bus = EventBus::new();
let log: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
let h = log.clone();
bus.subscribe("e", recording(h));
bus.publish("e", &json!("hello")).unwrap();
assert_eq!(*log.lock().unwrap(), vec!["hello".to_string()]);
}
#[test]
fn unsubscribe_removes_handler() {
let mut bus = EventBus::new();
let log: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
let h = log.clone();
let id = bus.subscribe("e", recording(h));
bus.publish("e", &json!("a")).unwrap();
bus.unsubscribe("e", id);
bus.publish("e", &json!("b")).unwrap();
assert_eq!(*log.lock().unwrap(), vec!["a".to_string()]);
}
#[test]
fn publish_unknown_event_is_noop() {
let bus = EventBus::new();
bus.publish("nope", &json!("x")).unwrap();
}
#[test]
fn handler_error_stops_chain() {
let mut bus = EventBus::new();
let log: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
let h = log.clone();
bus.subscribe("e", |_: &Value| -> Result<(), Box<dyn std::error::Error>> {
Err("boom".into())
});
bus.subscribe("e", recording(h));
assert!(bus.publish("e", &json!("x")).is_err());
assert!(log.lock().unwrap().is_empty());
}
#[test]
fn subscribed_ids_are_unique() {
let mut bus = EventBus::new();
let a = bus.subscribe("e", |_: &Value| Ok(()));
let b = bus.subscribe("e", |_: &Value| Ok(()));
assert_ne!(a, b);
}
}