use dashmap::DashMap;
use serde_json::Value;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DispatchMode {
Waterfall,
Parallel,
Bail,
}
pub type EventHandler = Arc<dyn Fn(Value) -> Result<Value, String> + Send + Sync + 'static>;
#[derive(Clone)]
pub struct Subscription {
pub id: usize,
pub allowed_did: Option<String>,
pub handler: EventHandler,
}
#[derive(Clone)]
pub struct EventBus {
subscribers: Arc<DashMap<String, Vec<Subscription>>>,
next_id: Arc<AtomicUsize>,
}
impl Default for EventBus {
fn default() -> Self {
Self::new()
}
}
impl EventBus {
pub fn new() -> Self {
Self {
subscribers: Arc::new(DashMap::new()),
next_id: Arc::new(AtomicUsize::new(1)),
}
}
pub fn subscribe<F>(&self, topic: &str, handler: F) -> Box<dyn FnOnce() -> Result<(), String> + Send + 'static>
where
F: Fn(Value) -> Result<Value, String> + Send + Sync + 'static,
{
self.subscribe_with_did(topic, None, handler)
}
pub fn subscribe_with_did<F>(
&self,
topic: &str,
allowed_did: Option<String>,
handler: F,
) -> Box<dyn FnOnce() -> Result<(), String> + Send + 'static>
where
F: Fn(Value) -> Result<Value, String> + Send + Sync + 'static,
{
let sub_id = self.next_id.fetch_add(1, Ordering::SeqCst);
let sub = Subscription {
id: sub_id,
allowed_did,
handler: Arc::new(handler),
};
self.subscribers
.entry(topic.to_string())
.or_default()
.push(sub);
let subs_map = self.subscribers.clone();
let topic_str = topic.to_string();
Box::new(move || {
if let Some(mut entry) = subs_map.get_mut(&topic_str) {
entry.retain(|s| s.id != sub_id);
}
Ok(())
})
}
pub fn dispatch(
&self,
topic: &str,
payload: Value,
mode: DispatchMode,
) -> Result<Vec<Value>, String> {
self.dispatch_with_did(topic, None, payload, mode)
}
pub fn dispatch_with_did(
&self,
topic: &str,
caller_did: Option<&str>,
payload: Value,
mode: DispatchMode,
) -> Result<Vec<Value>, String> {
let subs = match self.subscribers.get(topic) {
Some(entry) => entry.clone(),
None => return Ok(Vec::new()),
};
if subs.is_empty() {
return Ok(Vec::new());
}
let mut eligible_handlers = Vec::new();
for sub in &subs {
if let Some(ref required_did) = sub.allowed_did {
match caller_did {
Some(did) if did == required_did => {
eligible_handlers.push(sub.handler.clone());
}
_ => {
return Err(format!(
"DID authorization failed: Topic '{}' requires DID '{}', but caller has '{:?}'",
topic, required_did, caller_did
));
}
}
} else {
eligible_handlers.push(sub.handler.clone());
}
}
match mode {
DispatchMode::Waterfall => {
let mut current_payload = payload;
let mut outputs = Vec::new();
for handler in eligible_handlers {
let result = (handler)(current_payload.clone())?;
current_payload = result.clone();
outputs.push(result);
}
Ok(outputs)
}
DispatchMode::Parallel => {
let handles: Vec<_> = eligible_handlers
.into_iter()
.map(|handler| {
let p = payload.clone();
std::thread::spawn(move || (handler)(p))
})
.collect();
let mut results = Vec::new();
for h in handles {
match h.join() {
Ok(res) => results.push(res?),
Err(_) => return Err("Thread panic during parallel event dispatch".to_string()),
}
}
Ok(results)
}
DispatchMode::Bail => {
let mut outputs = Vec::new();
for handler in eligible_handlers {
match (handler)(payload.clone()) {
Ok(res) => outputs.push(res),
Err(e) => {
return Err(format!("Bail mode triggered by handler failure: {}", e));
}
}
}
Ok(outputs)
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn test_waterfall_dispatch_pipeline() {
let bus = EventBus::new();
let _s1 = bus.subscribe("calc", |val| {
let n = val.as_i64().unwrap_or(0);
Ok(json!(n + 1))
});
let _s2 = bus.subscribe("calc", |val| {
let n = val.as_i64().unwrap_or(0);
Ok(json!(n * 2))
});
let _s3 = bus.subscribe("calc", |val| {
let n = val.as_i64().unwrap_or(0);
Ok(json!(n + 10))
});
let _s4 = bus.subscribe("calc", |val| {
let n = val.as_i64().unwrap_or(0);
Ok(json!(n * 3))
});
let res = bus.dispatch("calc", json!(5), DispatchMode::Waterfall).unwrap();
assert_eq!(res.len(), 4);
assert_eq!(res.last().unwrap(), &json!(66));
}
#[test]
fn test_parallel_dispatch_concurrency() {
let bus = EventBus::new();
let mut _subs = Vec::new();
for i in 0..8 {
_subs.push(bus.subscribe("worker", move |_| {
Ok(json!({ "worker_id": i, "status": "done" }))
}));
}
let res = bus.dispatch("worker", json!({}), DispatchMode::Parallel).unwrap();
assert_eq!(res.len(), 8);
}
#[test]
fn test_bail_mode_short_circuits_on_error() {
let bus = EventBus::new();
let _s1 = bus.subscribe("speculative", |_| Ok(json!("ok_1")));
let _s2 = bus.subscribe("speculative", |_| Ok(json!("ok_2")));
let _s3 = bus.subscribe("speculative", |_| Err("injected_failure".to_string()));
let _s4 = bus.subscribe("speculative", |_| Ok(json!("should_not_reach")));
let res = bus.dispatch("speculative", json!({}), DispatchMode::Bail);
assert!(res.is_err());
assert!(res.unwrap_err().contains("injected_failure"));
}
#[test]
fn test_did_scoped_event_routing() {
let bus = EventBus::new();
let target_did = "did:pkc:agent:darwin:alpha";
let _sub = bus.subscribe_with_did("secure_task", Some(target_did.to_string()), |_| {
Ok(json!({ "authorized": true }))
});
let ok_res = bus.dispatch_with_did("secure_task", Some(target_did), json!({}), DispatchMode::Waterfall);
assert!(ok_res.is_ok());
let unauthorized_did = "did:pkc:agent:darwin:rogue";
let bad_res = bus.dispatch_with_did("secure_task", Some(unauthorized_did), json!({}), DispatchMode::Waterfall);
assert!(bad_res.is_err());
assert!(bad_res.unwrap_err().contains("DID authorization failed"));
}
#[test]
fn test_raii_disposable_unregistration() {
let bus = EventBus::new();
let unsub = bus.subscribe("temp_event", |_| Ok(json!("alive")));
let res1 = bus.dispatch("temp_event", json!({}), DispatchMode::Waterfall).unwrap();
assert_eq!(res1.len(), 1);
unsub().unwrap();
let res2 = bus.dispatch("temp_event", json!({}), DispatchMode::Waterfall).unwrap();
assert_eq!(res2.len(), 0);
}
}