paperos 0.2.0

A programmable editor built on the Runact actor runtime
Documentation
use serde_json::Value;
use std::collections::HashMap;

/// Opaque handle identifying a subscription, used for unsubscribe.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SubscriptionId(usize);

/// A handler receives the event payload and returns an error to stop delivery.
type EventHandler = Box<dyn Fn(&Value) -> Result<(), Box<dyn std::error::Error>> + Send + Sync>;

/// EventBus: minimal pub/sub for cross-extension state change notification.
///
/// Core infrastructure only — no file I/O, no UI, no scripting.
/// Extensions subscribe to named events in `init()`, publish when their own
/// state changes, and receive payloads as `serde_json::Value` — language-
/// neutral, so Rust extensions and Lua handlers consume the same events.
/// Handler errors propagate to the publisher and stop further delivery.
#[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,
        }
    }

    /// Subscribe to an event. Returns a handle that can be passed to
    /// [`EventBus::unsubscribe`] to stop delivery.
    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
    }

    /// Remove a subscription. No-op if the event or id does not exist.
    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);
        }
    }

    /// Deliver a payload to every subscriber of `event`.
    ///
    /// Stops at the first handler error and returns it; the payload is
    /// borrowed, so handlers cannot mutate it.
    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);
    }
}