vce-engine 0.1.1

The generic state substrate of the Virtual Computing Engine (VCE)
Documentation
//! The event bus.
//!
//! The event system is a first-class Engine primitive: it exists to
//! serve non-OS applications too. Dispatch is synchronous: listeners observe
//! the completed state of a mutation before the mutation's API call returns.
//!
//! Reentrancy: dispatch temporarily takes the listener list out of the bus,
//! so listeners may safely re-enter the Engine, subscribe, or unsubscribe
//! during dispatch. A listener subscribed during dispatch does not receive
//! the event currently being dispatched; a listener unsubscribed during
//! dispatch still receives the event currently being dispatched, and is
//! genuinely removed once the dispatch completes.
//!
//! Listener panics are contained: a listener that panics is removed from the
//! bus (it has demonstrated it cannot be trusted to run again) and the rest
//! of the dispatch round proceeds.

use std::panic::{AssertUnwindSafe, catch_unwind};

use crate::events::event::ObjectEvent;
use crate::events::event_type::EventType;
use crate::events::subscription::SubscriptionId;

pub(crate) struct Listener {
    id: SubscriptionId,
    filter: Option<EventType>,
    callback: Box<dyn FnMut(&ObjectEvent) + Send + Sync>,
}

impl Listener {
    fn matches(&self, event_type: EventType) -> bool {
        self.filter.is_none_or(|filter| filter == event_type)
    }

    /// Invokes the callback if the listener matches the event.
    pub(crate) fn run(&mut self, event: &ObjectEvent) {
        if self.matches(event.event_type) {
            (self.callback)(event);
        }
    }
}

/// Invokes every listener in subscription order.
///
/// A listener that panics is removed from `listeners` (the panic is
/// contained here); the remaining listeners still observe the event.
pub(crate) fn run_listeners(listeners: &mut Vec<Listener>, event: &ObjectEvent) {
    let mut index = 0;
    while index < listeners.len() {
        let result = catch_unwind(AssertUnwindSafe(|| listeners[index].run(event)));
        if result.is_err() {
            listeners.remove(index);
        } else {
            index += 1;
        }
    }
}

/// A synchronous event bus with subscriptions, filtering, and dispatch.
///
/// Subscription IDs are sequential starting at 1.
pub struct EventBus {
    next_id: usize,
    listeners: Vec<Listener>,
    /// Whether the listener list is currently detached for a dispatch round.
    detached: bool,
    /// Unsubscribes requested while the list is detached; applied to the
    /// batch when it returns, so unsubscribing during dispatch takes effect
    /// for every later event.
    pending_removals: Vec<SubscriptionId>,
}

impl Default for EventBus {
    fn default() -> Self {
        Self {
            next_id: 1,
            listeners: Vec::new(),
            detached: false,
            pending_removals: Vec::new(),
        }
    }
}

impl EventBus {
    /// Creates an empty event bus.
    pub fn new() -> Self {
        Self::default()
    }

    /// Subscribes a listener.
    ///
    /// `filter` restricts the listener to a single [`EventType`]; `None`
    /// subscribes to all events. The returned [`SubscriptionId`] unsubscribes
    /// the listener.
    pub fn subscribe(
        &mut self,
        filter: impl Into<Option<EventType>>,
        callback: impl FnMut(&ObjectEvent) + Send + Sync + 'static,
    ) -> SubscriptionId {
        let id = SubscriptionId::new(self.next_id);
        self.next_id = self.next_id.saturating_add(1);
        self.listeners.push(Listener {
            id,
            filter: filter.into(),
            callback: Box::new(callback),
        });
        id
    }

    /// Removes a subscription. Idempotent: unknown IDs are ignored.
    ///
    /// If the listener list is currently detached (a dispatch round in
    /// progress on some thread), the removal is recorded and applied when
    /// the batch is reattached, so the unsubscribe takes effect for every
    /// later event even though the listener still observes the current one.
    pub fn unsubscribe(&mut self, id: SubscriptionId) {
        if self.detached {
            self.pending_removals.push(id);
            return;
        }
        self.listeners.retain(|listener| listener.id != id);
    }

    /// Dispatches an event to all matching listeners, in subscription order.
    ///
    /// See the module documentation for reentrancy semantics.
    pub fn dispatch(&mut self, event: &ObjectEvent) {
        let mut current = std::mem::take(&mut self.listeners);
        run_listeners(&mut current, event);
        self.listeners.extend(current);
    }

    /// Removes every listener from the bus.
    ///
    /// Used by the Engine to dispatch without holding the bus lock. The
    /// listeners must be returned with [`EventBus::reattach_listeners`] after
    /// dispatch; until then, unsubscribes are queued and applied to the
    /// returning batch, and subscriptions added to the bus are ordered after
    /// the detached ones (they subscribed later).
    pub(crate) fn detach_listeners(&mut self) -> Vec<Listener> {
        self.detached = true;
        std::mem::take(&mut self.listeners)
    }

    /// Returns listeners removed by [`EventBus::detach_listeners`],
    /// restoring subscription order: the detached batch predates anything
    /// subscribed while it was away.
    pub(crate) fn reattach_listeners(&mut self, listeners: Vec<Listener>) {
        let mut batch = listeners;
        for id in self.pending_removals.drain(..) {
            batch.retain(|listener| listener.id != id);
        }
        // Anything in self.listeners subscribed while the batch was away,
        // so it runs after the older batch on later events.
        let mut ordered = batch;
        ordered.append(&mut self.listeners);
        self.listeners = ordered;
        self.detached = false;
    }

    /// The number of active subscriptions.
    pub fn listener_count(&self) -> usize {
        self.listeners.len()
    }
}