engine/events/event_bus.rs
1//! The event bus.
2//!
3//! The event system is a first-class Engine primitive: it exists to
4//! serve non-OS applications too. Dispatch is synchronous: listeners observe
5//! the completed state of a mutation before the mutation's API call returns.
6//!
7//! Reentrancy: dispatch temporarily takes the listener list out of the bus,
8//! so listeners may safely re-enter the Engine, subscribe, or unsubscribe
9//! during dispatch. A listener subscribed during dispatch does not receive
10//! the event currently being dispatched; a listener unsubscribed during
11//! dispatch still receives the event currently being dispatched, and is
12//! genuinely removed once the dispatch completes.
13//!
14//! Listener panics are contained: a listener that panics is removed from the
15//! bus (it has demonstrated it cannot be trusted to run again) and the rest
16//! of the dispatch round proceeds.
17
18use std::panic::{AssertUnwindSafe, catch_unwind};
19
20use crate::events::event::ObjectEvent;
21use crate::events::event_type::EventType;
22use crate::events::subscription::SubscriptionId;
23
24pub(crate) struct Listener {
25 id: SubscriptionId,
26 filter: Option<EventType>,
27 callback: Box<dyn FnMut(&ObjectEvent) + Send + Sync>,
28}
29
30impl Listener {
31 fn matches(&self, event_type: EventType) -> bool {
32 self.filter.is_none_or(|filter| filter == event_type)
33 }
34
35 /// Invokes the callback if the listener matches the event.
36 pub(crate) fn run(&mut self, event: &ObjectEvent) {
37 if self.matches(event.event_type) {
38 (self.callback)(event);
39 }
40 }
41}
42
43/// Invokes every listener in subscription order.
44///
45/// A listener that panics is removed from `listeners` (the panic is
46/// contained here); the remaining listeners still observe the event.
47pub(crate) fn run_listeners(listeners: &mut Vec<Listener>, event: &ObjectEvent) {
48 let mut index = 0;
49 while index < listeners.len() {
50 let result = catch_unwind(AssertUnwindSafe(|| listeners[index].run(event)));
51 if result.is_err() {
52 listeners.remove(index);
53 } else {
54 index += 1;
55 }
56 }
57}
58
59/// A synchronous event bus with subscriptions, filtering, and dispatch.
60///
61/// Subscription IDs are sequential starting at 1.
62pub struct EventBus {
63 next_id: usize,
64 listeners: Vec<Listener>,
65 /// Whether the listener list is currently detached for a dispatch round.
66 detached: bool,
67 /// Unsubscribes requested while the list is detached; applied to the
68 /// batch when it returns, so unsubscribing during dispatch takes effect
69 /// for every later event.
70 pending_removals: Vec<SubscriptionId>,
71}
72
73impl Default for EventBus {
74 fn default() -> Self {
75 Self {
76 next_id: 1,
77 listeners: Vec::new(),
78 detached: false,
79 pending_removals: Vec::new(),
80 }
81 }
82}
83
84impl EventBus {
85 /// Creates an empty event bus.
86 pub fn new() -> Self {
87 Self::default()
88 }
89
90 /// Subscribes a listener.
91 ///
92 /// `filter` restricts the listener to a single [`EventType`]; `None`
93 /// subscribes to all events. The returned [`SubscriptionId`] unsubscribes
94 /// the listener.
95 pub fn subscribe(
96 &mut self,
97 filter: impl Into<Option<EventType>>,
98 callback: impl FnMut(&ObjectEvent) + Send + Sync + 'static,
99 ) -> SubscriptionId {
100 let id = SubscriptionId::new(self.next_id);
101 self.next_id = self.next_id.saturating_add(1);
102 self.listeners.push(Listener {
103 id,
104 filter: filter.into(),
105 callback: Box::new(callback),
106 });
107 id
108 }
109
110 /// Removes a subscription. Idempotent: unknown IDs are ignored.
111 ///
112 /// If the listener list is currently detached (a dispatch round in
113 /// progress on some thread), the removal is recorded and applied when
114 /// the batch is reattached, so the unsubscribe takes effect for every
115 /// later event even though the listener still observes the current one.
116 pub fn unsubscribe(&mut self, id: SubscriptionId) {
117 if self.detached {
118 self.pending_removals.push(id);
119 return;
120 }
121 self.listeners.retain(|listener| listener.id != id);
122 }
123
124 /// Dispatches an event to all matching listeners, in subscription order.
125 ///
126 /// See the module documentation for reentrancy semantics.
127 pub fn dispatch(&mut self, event: &ObjectEvent) {
128 let mut current = std::mem::take(&mut self.listeners);
129 run_listeners(&mut current, event);
130 self.listeners.extend(current);
131 }
132
133 /// Removes every listener from the bus.
134 ///
135 /// Used by the Engine to dispatch without holding the bus lock. The
136 /// listeners must be returned with [`EventBus::reattach_listeners`] after
137 /// dispatch; until then, unsubscribes are queued and applied to the
138 /// returning batch, and subscriptions added to the bus are ordered after
139 /// the detached ones (they subscribed later).
140 pub(crate) fn detach_listeners(&mut self) -> Vec<Listener> {
141 self.detached = true;
142 std::mem::take(&mut self.listeners)
143 }
144
145 /// Returns listeners removed by [`EventBus::detach_listeners`],
146 /// restoring subscription order: the detached batch predates anything
147 /// subscribed while it was away.
148 pub(crate) fn reattach_listeners(&mut self, listeners: Vec<Listener>) {
149 let mut batch = listeners;
150 for id in self.pending_removals.drain(..) {
151 batch.retain(|listener| listener.id != id);
152 }
153 // Anything in self.listeners subscribed while the batch was away,
154 // so it runs after the older batch on later events.
155 let mut ordered = batch;
156 ordered.append(&mut self.listeners);
157 self.listeners = ordered;
158 self.detached = false;
159 }
160
161 /// The number of active subscriptions.
162 pub fn listener_count(&self) -> usize {
163 self.listeners.len()
164 }
165}