Skip to main content

clm_rust_core/fiber/
event.rs

1//! Cordis Typed Event Bus and Multi-Agent Event Routing.
2//!
3//! Provides:
4//! - `DispatchMode`: Waterfall (sequential pipeline), Parallel (concurrent fork-join), Bail (speculative short-circuit)
5//! - `EventBus`: Dynamic topic publish-subscribe engine with RAII disposables
6//! - DID authentication filtering for secure multi-agent swarms
7
8use dashmap::DashMap;
9use serde_json::Value;
10use std::sync::atomic::{AtomicUsize, Ordering};
11use std::sync::Arc;
12
13/// Event dispatch execution strategies.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum DispatchMode {
16    /// Sequential pipeline: output of subscriber n becomes input payload to subscriber n+1.
17    Waterfall,
18    /// Concurrent fork-join: executes all subscribers and collects all results.
19    Parallel,
20    /// Speculative execution: executes subscribers sequentially until the first error, short-circuiting immediately.
21    Bail,
22}
23
24pub type EventHandler = Arc<dyn Fn(Value) -> Result<Value, String> + Send + Sync + 'static>;
25
26#[derive(Clone)]
27pub struct Subscription {
28    pub id: usize,
29    pub allowed_did: Option<String>,
30    pub handler: EventHandler,
31}
32
33/// Dynamic Event Bus for Cordis multi-agent messaging and plugin hooks.
34#[derive(Clone)]
35pub struct EventBus {
36    subscribers: Arc<DashMap<String, Vec<Subscription>>>,
37    next_id: Arc<AtomicUsize>,
38}
39
40impl Default for EventBus {
41    fn default() -> Self {
42        Self::new()
43    }
44}
45
46impl EventBus {
47    pub fn new() -> Self {
48        Self {
49            subscribers: Arc::new(DashMap::new()),
50            next_id: Arc::new(AtomicUsize::new(1)),
51        }
52    }
53
54    /// Registers an event handler for a topic.
55    /// Returns a cleanup closure (RAII disposable) that unregisters this subscription.
56    pub fn subscribe<F>(&self, topic: &str, handler: F) -> Box<dyn FnOnce() -> Result<(), String> + Send + 'static>
57    where
58        F: Fn(Value) -> Result<Value, String> + Send + Sync + 'static,
59    {
60        self.subscribe_with_did(topic, None, handler)
61    }
62
63    /// Registers an event handler restricted to a specific DID.
64    /// Returns a cleanup closure (RAII disposable) that unregisters this subscription.
65    pub fn subscribe_with_did<F>(
66        &self,
67        topic: &str,
68        allowed_did: Option<String>,
69        handler: F,
70    ) -> Box<dyn FnOnce() -> Result<(), String> + Send + 'static>
71    where
72        F: Fn(Value) -> Result<Value, String> + Send + Sync + 'static,
73    {
74        let sub_id = self.next_id.fetch_add(1, Ordering::SeqCst);
75        let sub = Subscription {
76            id: sub_id,
77            allowed_did,
78            handler: Arc::new(handler),
79        };
80
81        self.subscribers
82            .entry(topic.to_string())
83            .or_default()
84            .push(sub);
85
86        let subs_map = self.subscribers.clone();
87        let topic_str = topic.to_string();
88
89        Box::new(move || {
90            if let Some(mut entry) = subs_map.get_mut(&topic_str) {
91                entry.retain(|s| s.id != sub_id);
92            }
93            Ok(())
94        })
95    }
96
97    /// Dispatches an event payload across all subscribers for the given topic.
98    pub fn dispatch(
99        &self,
100        topic: &str,
101        payload: Value,
102        mode: DispatchMode,
103    ) -> Result<Vec<Value>, String> {
104        self.dispatch_with_did(topic, None, payload, mode)
105    }
106
107    /// Dispatches an event with caller DID authentication.
108    pub fn dispatch_with_did(
109        &self,
110        topic: &str,
111        caller_did: Option<&str>,
112        payload: Value,
113        mode: DispatchMode,
114    ) -> Result<Vec<Value>, String> {
115        let subs = match self.subscribers.get(topic) {
116            Some(entry) => entry.clone(),
117            None => return Ok(Vec::new()),
118        };
119
120        if subs.is_empty() {
121            return Ok(Vec::new());
122        }
123
124        // Filter subscribers based on DID authentication
125        let mut eligible_handlers = Vec::new();
126        for sub in &subs {
127            if let Some(ref required_did) = sub.allowed_did {
128                match caller_did {
129                    Some(did) if did == required_did => {
130                        eligible_handlers.push(sub.handler.clone());
131                    }
132                    _ => {
133                        return Err(format!(
134                            "DID authorization failed: Topic '{}' requires DID '{}', but caller has '{:?}'",
135                            topic, required_did, caller_did
136                        ));
137                    }
138                }
139            } else {
140                eligible_handlers.push(sub.handler.clone());
141            }
142        }
143
144        match mode {
145            DispatchMode::Waterfall => {
146                let mut current_payload = payload;
147                let mut outputs = Vec::new();
148                for handler in eligible_handlers {
149                    let result = (handler)(current_payload.clone())?;
150                    current_payload = result.clone();
151                    outputs.push(result);
152                }
153                Ok(outputs)
154            }
155            DispatchMode::Parallel => {
156                let handles: Vec<_> = eligible_handlers
157                    .into_iter()
158                    .map(|handler| {
159                        let p = payload.clone();
160                        std::thread::spawn(move || (handler)(p))
161                    })
162                    .collect();
163
164                let mut results = Vec::new();
165                for h in handles {
166                    match h.join() {
167                        Ok(res) => results.push(res?),
168                        Err(_) => return Err("Thread panic during parallel event dispatch".to_string()),
169                    }
170                }
171                Ok(results)
172            }
173            DispatchMode::Bail => {
174                let mut outputs = Vec::new();
175                for handler in eligible_handlers {
176                    match (handler)(payload.clone()) {
177                        Ok(res) => outputs.push(res),
178                        Err(e) => {
179                            return Err(format!("Bail mode triggered by handler failure: {}", e));
180                        }
181                    }
182                }
183                Ok(outputs)
184            }
185        }
186    }
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192    use serde_json::json;
193
194    #[test]
195    fn test_waterfall_dispatch_pipeline() {
196        let bus = EventBus::new();
197
198        // 4 sequential pipeline stages: +1, *2, +10, *3
199        let _s1 = bus.subscribe("calc", |val| {
200            let n = val.as_i64().unwrap_or(0);
201            Ok(json!(n + 1))
202        });
203        let _s2 = bus.subscribe("calc", |val| {
204            let n = val.as_i64().unwrap_or(0);
205            Ok(json!(n * 2))
206        });
207        let _s3 = bus.subscribe("calc", |val| {
208            let n = val.as_i64().unwrap_or(0);
209            Ok(json!(n + 10))
210        });
211        let _s4 = bus.subscribe("calc", |val| {
212            let n = val.as_i64().unwrap_or(0);
213            Ok(json!(n * 3))
214        });
215
216        // Start with 5 -> (5+1)=6 -> (6*2)=12 -> (12+10)=22 -> (22*3)=66
217        let res = bus.dispatch("calc", json!(5), DispatchMode::Waterfall).unwrap();
218        assert_eq!(res.len(), 4);
219        assert_eq!(res.last().unwrap(), &json!(66));
220    }
221
222    #[test]
223    fn test_parallel_dispatch_concurrency() {
224        let bus = EventBus::new();
225        let mut _subs = Vec::new();
226        for i in 0..8 {
227            _subs.push(bus.subscribe("worker", move |_| {
228                Ok(json!({ "worker_id": i, "status": "done" }))
229            }));
230        }
231
232        let res = bus.dispatch("worker", json!({}), DispatchMode::Parallel).unwrap();
233        assert_eq!(res.len(), 8);
234    }
235
236    #[test]
237    fn test_bail_mode_short_circuits_on_error() {
238        let bus = EventBus::new();
239        let _s1 = bus.subscribe("speculative", |_| Ok(json!("ok_1")));
240        let _s2 = bus.subscribe("speculative", |_| Ok(json!("ok_2")));
241        let _s3 = bus.subscribe("speculative", |_| Err("injected_failure".to_string()));
242        let _s4 = bus.subscribe("speculative", |_| Ok(json!("should_not_reach")));
243
244        let res = bus.dispatch("speculative", json!({}), DispatchMode::Bail);
245        assert!(res.is_err());
246        assert!(res.unwrap_err().contains("injected_failure"));
247    }
248
249    #[test]
250    fn test_did_scoped_event_routing() {
251        let bus = EventBus::new();
252        let target_did = "did:pkc:agent:darwin:alpha";
253
254        let _sub = bus.subscribe_with_did("secure_task", Some(target_did.to_string()), |_| {
255            Ok(json!({ "authorized": true }))
256        });
257
258        // Authorized dispatch
259        let ok_res = bus.dispatch_with_did("secure_task", Some(target_did), json!({}), DispatchMode::Waterfall);
260        assert!(ok_res.is_ok());
261
262        // Unauthorized dispatch
263        let unauthorized_did = "did:pkc:agent:darwin:rogue";
264        let bad_res = bus.dispatch_with_did("secure_task", Some(unauthorized_did), json!({}), DispatchMode::Waterfall);
265        assert!(bad_res.is_err());
266        assert!(bad_res.unwrap_err().contains("DID authorization failed"));
267    }
268
269    #[test]
270    fn test_raii_disposable_unregistration() {
271        let bus = EventBus::new();
272        let unsub = bus.subscribe("temp_event", |_| Ok(json!("alive")));
273
274        let res1 = bus.dispatch("temp_event", json!({}), DispatchMode::Waterfall).unwrap();
275        assert_eq!(res1.len(), 1);
276
277        // Execute disposable cleanup
278        unsub().unwrap();
279
280        let res2 = bus.dispatch("temp_event", json!({}), DispatchMode::Waterfall).unwrap();
281        assert_eq!(res2.len(), 0);
282    }
283}