Skip to main content

kardia_core/
events.rs

1use std::any::{Any, TypeId, type_name};
2use std::future::Future;
3use std::panic::{AssertUnwindSafe, catch_unwind};
4use std::sync::Arc;
5use std::sync::atomic::{AtomicBool, Ordering};
6
7use futures::FutureExt;
8use futures::future::{BoxFuture, join_all};
9use parking_lot::Mutex;
10use serde_json::Value;
11
12use crate::config::ErasedConfig;
13use crate::context::Context;
14use crate::effect::EffectHandle;
15use crate::error::{AggregateError, Error, Result};
16use crate::fiber::{Fiber, FiberState};
17use crate::key::{FiberId, Key, RealmId};
18use crate::root::RootInner;
19use crate::scope::Scope;
20
21/// A typed event. Listeners are registered per event type.
22pub trait Event: Any + Send + Sync {
23    type Output: Bailable;
24
25    /// Whether a listener registered in `listener` receives this event.
26    fn filter(&self, _listener: &Context) -> bool {
27        true
28    }
29}
30
31/// Listener results that can stop a `bail` / `serial` dispatch.
32pub trait Bailable: Send + 'static {
33    fn is_bailed(&self) -> bool {
34        false
35    }
36
37    /// A failure reported by a `parallel` dispatch.
38    fn into_error(self) -> Option<Error>
39    where
40        Self: Sized,
41    {
42        None
43    }
44}
45
46impl Bailable for () {}
47
48impl Bailable for bool {
49    fn is_bailed(&self) -> bool {
50        *self
51    }
52}
53
54impl<T: Send + 'static> Bailable for Option<T> {
55    fn is_bailed(&self) -> bool {
56        self.is_some()
57    }
58}
59
60impl<T: Bailable> Bailable for Result<T, Error> {
61    fn is_bailed(&self) -> bool {
62        self.as_ref().map_or(true, Bailable::is_bailed)
63    }
64
65    fn into_error(self) -> Option<Error> {
66        self.err()
67    }
68}
69
70type SyncListener<E> = Box<dyn Fn(&E) -> <E as Event>::Output + Send + Sync>;
71type AsyncListener<E> = Box<dyn Fn(&E) -> BoxFuture<'static, <E as Event>::Output> + Send + Sync>;
72
73enum Callback<E: Event> {
74    Sync(SyncListener<E>),
75    Async(AsyncListener<E>),
76}
77
78pub(crate) struct ListenerEntry {
79    id: u64,
80    fiber: FiberId,
81    scope: Arc<Scope>,
82    removed: AtomicBool,
83    callback: Box<dyn Any + Send + Sync>,
84}
85
86impl ListenerEntry {
87    fn callback<E: Event>(&self) -> &Callback<E> {
88        self.callback.downcast_ref().expect("listener registered for this event type")
89    }
90}
91
92/// A deferred dispatch of an internal event, built after the critical section.
93type Dispatch = Box<dyn FnOnce(&Arc<RootInner>) + Send>;
94
95pub(crate) struct Emit(Dispatch);
96
97impl Emit {
98    pub(crate) fn new<E: Event>(make: impl FnOnce(&Arc<RootInner>) -> E + Send + 'static) -> Self {
99        Self(Box::new(move |root| {
100            let event = make(root);
101            Context::of_root(root).emit(&event);
102        }))
103    }
104
105    pub(crate) fn run(self, root: &Arc<RootInner>) {
106        (self.0)(root)
107    }
108}
109
110impl Context {
111    /// Registers a listener as an effect of the current fiber.
112    pub fn on<E: Event>(&self, listener: impl Fn(&E) -> E::Output + Send + Sync + 'static) -> Result<EffectHandle> {
113        self.listen(Callback::Sync(Box::new(listener)), false)
114    }
115
116    /// Registers a listener that runs before the ones registered so far.
117    pub fn on_prepend<E: Event>(
118        &self,
119        listener: impl Fn(&E) -> E::Output + Send + Sync + 'static,
120    ) -> Result<EffectHandle> {
121        self.listen(Callback::Sync(Box::new(listener)), true)
122    }
123
124    /// Registers an asynchronous listener. `emit` and `bail` start it
125    /// without waiting (a panic is logged); `serial` and `parallel` await it.
126    pub fn on_async<E, F, Fut>(&self, listener: F) -> Result<EffectHandle>
127    where
128        E: Event,
129        F: Fn(&E) -> Fut + Send + Sync + 'static,
130        Fut: Future<Output = E::Output> + Send + 'static,
131    {
132        self.listen(Callback::Async(Box::new(move |event: &E| listener(event).boxed())), false)
133    }
134
135    /// Registers a listener that runs at most once.
136    pub fn once<E: Event>(&self, listener: impl FnOnce(&E) -> E::Output + Send + 'static) -> Result<EffectHandle>
137    where
138        E::Output: Default,
139    {
140        let listener = Mutex::new(Some(listener));
141        let handle: Arc<Mutex<Option<EffectHandle>>> = Default::default();
142        let own = handle.clone();
143        let registered = self.on(move |event: &E| {
144            let Some(listener) = listener.lock().take() else { return Default::default() };
145            if let Some(handle) = own.lock().take() {
146                drop(handle.dispose());
147            }
148            listener(event)
149        })?;
150        *handle.lock() = Some(registered.clone());
151        Ok(registered)
152    }
153
154    /// Calls every listener; asynchronous ones are started, not awaited.
155    /// A panicking listener is logged and the rest still run.
156    pub fn emit<E: Event>(&self, event: &E) {
157        for entry in self.listeners_for(event) {
158            if entry.removed.load(Ordering::Acquire) {
159                continue;
160            }
161            match entry.callback::<E>() {
162                Callback::Sync(listener) => {
163                    if let Err(panic) = catch_unwind(AssertUnwindSafe(|| listener(event))) {
164                        self.logger().log_error(&Error::from_panic(panic));
165                    }
166                }
167                Callback::Async(listener) => self.spawn_logged(listener(event)),
168            }
169        }
170    }
171
172    /// Calls synchronous listeners until one returns a bailing result;
173    /// asynchronous ones are started, not awaited. A panicking listener is
174    /// logged and counts as not bailing.
175    pub fn bail<E: Event>(&self, event: &E) -> Option<E::Output> {
176        for entry in self.listeners_for(event) {
177            if entry.removed.load(Ordering::Acquire) {
178                continue;
179            }
180            match entry.callback::<E>() {
181                Callback::Sync(listener) => match catch_unwind(AssertUnwindSafe(|| listener(event))) {
182                    Ok(result) if result.is_bailed() => return Some(result),
183                    Ok(_) => {}
184                    Err(panic) => self.logger().log_error(&Error::from_panic(panic)),
185                },
186                Callback::Async(listener) => self.spawn_logged(listener(event)),
187            }
188        }
189        None
190    }
191
192    /// Calls listeners one after another, awaiting each, until one bails.
193    /// A panicking listener stops the dispatch with its panic as the error.
194    pub async fn serial<E: Event>(&self, event: &E) -> Result<Option<E::Output>> {
195        for entry in self.listeners_for(event) {
196            if entry.removed.load(Ordering::Acquire) {
197                continue;
198            }
199            let result = match entry.callback::<E>() {
200                Callback::Sync(listener) => catch_unwind(AssertUnwindSafe(|| listener(event))),
201                Callback::Async(listener) => AssertUnwindSafe(listener(event)).catch_unwind().await,
202            };
203            let result = result.map_err(Error::from_panic)?;
204            if result.is_bailed() {
205                return Ok(Some(result));
206            }
207        }
208        Ok(None)
209    }
210
211    /// Calls all listeners concurrently and collects their failures.
212    pub async fn parallel<E: Event>(&self, event: &E) -> Result<(), AggregateError> {
213        let mut tasks = Vec::new();
214        for entry in self.listeners_for(event) {
215            if entry.removed.load(Ordering::Acquire) {
216                continue;
217            }
218            let task = match entry.callback::<E>() {
219                Callback::Sync(listener) => {
220                    let result = catch_unwind(AssertUnwindSafe(|| listener(event)));
221                    futures::future::ready(result.map_err(Error::from_panic)).boxed()
222                }
223                Callback::Async(listener) => {
224                    AssertUnwindSafe(listener(event)).catch_unwind().map(|r| r.map_err(Error::from_panic)).boxed()
225                }
226            };
227            tasks.push(task);
228        }
229        let errors: Vec<Error> = join_all(tasks)
230            .await
231            .into_iter()
232            .filter_map(|result| match result {
233                Ok(output) => output.into_error(),
234                Err(error) => Some(error),
235            })
236            .collect();
237        if errors.is_empty() {
238            return Ok(());
239        }
240        let message = format!("one or more listeners of event {} failed", short_name::<E>());
241        Err(AggregateError { message, errors })
242    }
243
244    /// Number of listeners currently registered for `E`.
245    pub fn listener_count<E: Event>(&self) -> usize {
246        self.root.with(|st| st.listeners.get(&TypeId::of::<E>()).map_or(0, Vec::len))
247    }
248
249    fn listen<E: Event>(&self, callback: Callback<E>, prepend: bool) -> Result<EffectHandle> {
250        let label = format!("ctx.on({})", short_name::<E>());
251        let root = Arc::downgrade(&self.root);
252        self.effect_sync(label, |scope| {
253            let entry = self.root.run(|st| {
254                st.next_listener += 1;
255                let entry = Arc::new(ListenerEntry {
256                    id: st.next_listener,
257                    fiber: self.fiber,
258                    scope: self.scope.clone(),
259                    removed: AtomicBool::new(false),
260                    callback: Box::new(callback),
261                });
262                let list = st.listeners.entry(TypeId::of::<E>()).or_default();
263                if prepend {
264                    list.insert(0, entry.clone());
265                } else {
266                    list.push(entry.clone());
267                }
268                entry
269            });
270            scope.defer_fn(move || {
271                entry.removed.store(true, Ordering::Release);
272                let Some(root) = root.upgrade() else { return };
273                root.run(|st| {
274                    let type_id = TypeId::of::<E>();
275                    if let Some(list) = st.listeners.get_mut(&type_id) {
276                        list.retain(|other| other.id != entry.id);
277                        if list.is_empty() {
278                            st.listeners.remove(&type_id);
279                        }
280                    }
281                    st.drop_later(entry);
282                });
283            });
284            Ok(())
285        })
286    }
287
288    fn spawn_logged<T: Send + 'static>(&self, listener: BoxFuture<'static, T>) {
289        let logger = self.logger();
290        tokio::spawn(async move {
291            if let Err(panic) = AssertUnwindSafe(listener).catch_unwind().await {
292                logger.log_error(&Error::from_panic(panic));
293            }
294        });
295    }
296
297    fn listeners_for<E: Event>(&self, event: &E) -> Vec<Arc<ListenerEntry>> {
298        let entries = self.root.with(|st| st.listeners.get(&TypeId::of::<E>()).cloned().unwrap_or_default());
299        entries
300            .into_iter()
301            .filter(|entry| {
302                let listener = Context { root: self.root.clone(), fiber: entry.fiber, scope: entry.scope.clone() };
303                event.filter(&listener)
304            })
305            .collect()
306    }
307}
308
309fn short_name<E>() -> &'static str {
310    let name = type_name::<E>();
311    name.rsplit("::").next().unwrap_or(name)
312}
313
314/// A fiber was created (`internal/plugin` on insertion).
315pub struct PluginInserted {
316    pub fiber: Fiber,
317}
318
319/// A fiber was retired (`internal/plugin` on removal).
320pub struct PluginRemoved {
321    pub fiber: Fiber,
322}
323
324pub struct StatusChanged {
325    pub fiber: Fiber,
326    pub old: FiberState,
327    pub new: FiberState,
328}
329
330/// A binding of `key` in `realm` appeared or disappeared. Delivered only to
331/// listeners whose context resolves `key` to the same realm.
332pub struct ServiceChanged {
333    pub key: Key,
334    pub realm: RealmId,
335}
336
337/// A fiber's configuration was replaced through `update` (write-back point).
338pub struct ConfigCommitted {
339    pub fiber: Fiber,
340    pub config: Value,
341}
342
343/// A fiber was moved to another plugin implementation by `registry.replace`.
344pub struct Replaced {
345    pub fiber: Fiber,
346}
347
348impl Event for PluginInserted {
349    type Output = ();
350}
351
352impl Event for PluginRemoved {
353    type Output = ();
354}
355
356impl Event for StatusChanged {
357    type Output = ();
358}
359
360impl Event for ConfigCommitted {
361    type Output = ();
362}
363
364impl Event for Replaced {
365    type Output = ();
366}
367
368impl Event for ServiceChanged {
369    type Output = ();
370
371    fn filter(&self, listener: &Context) -> bool {
372        listener.realm(&self.key) == Some(self.realm)
373    }
374}
375
376type AcceptFn = Box<dyn Fn(&ErasedConfig) -> Option<BoxFuture<'static, Result<()>>> + Send + Sync>;
377
378pub(crate) struct UpdateHook {
379    removed: AtomicBool,
380    accept: AcceptFn,
381}
382
383impl UpdateHook {
384    /// `Some` if the hook takes the update over, with its completion.
385    pub(crate) fn offer(&self, config: &ErasedConfig) -> Option<BoxFuture<'static, Result<()>>> {
386        if self.removed.load(Ordering::Acquire) { None } else { (self.accept)(config) }
387    }
388}
389
390/// A configuration resolution hook: receives the source configuration and
391/// the next stage (ultimately the plugin's own decoding).
392pub type ConfigHook =
393    Arc<dyn Fn(&Fiber, Value, &dyn Fn(Value) -> Result<ErasedConfig>) -> Result<ErasedConfig> + Send + Sync>;
394
395impl Context {
396    /// Offers configuration updates of the current fiber to `accept` before
397    /// restarting it. Returning `true` takes the update over (no restart).
398    /// The hook sees the decoded configuration; it is skipped if `C` does
399    /// not match the plugin's configuration type.
400    pub fn on_update<C: Any>(&self, accept: impl Fn(&C) -> bool + Send + Sync + 'static) -> Result<EffectHandle> {
401        self.on_update_with(move |config: &C| accept(config).then(|| futures::future::ready(Ok(())).boxed()))
402    }
403
404    /// Like [`Context::on_update`]; a hook taking the update over returns
405    /// the future that `update` resolves with.
406    pub fn on_update_with<C: Any>(
407        &self,
408        accept: impl Fn(&C) -> Option<BoxFuture<'static, Result<()>>> + Send + Sync + 'static,
409    ) -> Result<EffectHandle> {
410        let hook = Arc::new(UpdateHook {
411            removed: AtomicBool::new(false),
412            accept: Box::new(move |config| config.downcast_ref::<C>().and_then(&accept)),
413        });
414        let root = Arc::downgrade(&self.root);
415        let fiber = self.fiber;
416        self.effect_sync("ctx.on_update()", |scope| {
417            let id = self.root.run(|st| st.fiber_mut(fiber).map(|f| f.update_hooks.insert(hook.clone())));
418            scope.defer_fn(move || {
419                hook.removed.store(true, Ordering::Release);
420                if let (Some(root), Some(id)) = (root.upgrade(), id) {
421                    let removed = root.run(|st| st.fiber_mut(fiber).and_then(|f| f.update_hooks.remove(id)));
422                    drop(removed);
423                }
424            });
425            Ok(())
426        })
427    }
428
429    /// Registers a configuration resolution hook for every fiber of the root.
430    pub fn on_config(&self, hook: ConfigHook) -> Result<EffectHandle> {
431        let root = Arc::downgrade(&self.root);
432        self.effect_sync("ctx.on_config()", |scope| {
433            let id = self.root.run(|st| st.config_hooks.insert(hook));
434            scope.defer_fn(move || {
435                if let Some(root) = root.upgrade() {
436                    let removed = root.run(|st| st.config_hooks.remove(id));
437                    drop(removed);
438                }
439            });
440            Ok(())
441        })
442    }
443}