clm-kernel 0.0.15

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Cordis Typed Event Bus and Multi-Agent Event Routing.
//!
//! Provides:
//! - `DispatchMode`: Waterfall (sequential pipeline), Parallel (concurrent fork-join), Bail (speculative short-circuit)
//! - `EventBus`: Dynamic topic publish-subscribe engine with RAII disposables
//! - DID authentication filtering for secure multi-agent swarms

use dashmap::DashMap;
use serde_json::Value;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

/// Event dispatch execution strategies.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DispatchMode {
    /// Sequential pipeline: output of subscriber n becomes input payload to subscriber n+1.
    Waterfall,
    /// Concurrent fork-join: executes all subscribers and collects all results.
    Parallel,
    /// Speculative execution: executes subscribers sequentially until the first error, short-circuiting immediately.
    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,
}

/// Dynamic Event Bus for Cordis multi-agent messaging and plugin hooks.
#[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)),
        }
    }

    /// Registers an event handler for a topic.
    /// Returns a cleanup closure (RAII disposable) that unregisters this subscription.
    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)
    }

    /// Registers an event handler restricted to a specific DID.
    /// Returns a cleanup closure (RAII disposable) that unregisters this subscription.
    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(())
        })
    }

    /// Dispatches an event payload across all subscribers for the given topic.
    pub fn dispatch(
        &self,
        topic: &str,
        payload: Value,
        mode: DispatchMode,
    ) -> Result<Vec<Value>, String> {
        self.dispatch_with_did(topic, None, payload, mode)
    }

    /// Dispatches an event with caller DID authentication.
    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());
        }

        // Filter subscribers based on DID authentication
        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();

        // 4 sequential pipeline stages: +1, *2, +10, *3
        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))
        });

        // Start with 5 -> (5+1)=6 -> (6*2)=12 -> (12+10)=22 -> (22*3)=66
        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 }))
        });

        // Authorized dispatch
        let ok_res = bus.dispatch_with_did("secure_task", Some(target_did), json!({}), DispatchMode::Waterfall);
        assert!(ok_res.is_ok());

        // Unauthorized dispatch
        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);

        // Execute disposable cleanup
        unsub().unwrap();

        let res2 = bus.dispatch("temp_event", json!({}), DispatchMode::Waterfall).unwrap();
        assert_eq!(res2.len(), 0);
    }
}