Skip to main content

kian_plugin/
dispatch.rs

1//! Five-mode typed-event dispatch (DESIGN §6.1; mode semantics follow Cordis).
2//!
3//! Like Cordis, the mode is a property of the *dispatch call*:
4//! - [`Ctx::emit`] — observe: run [`Ctx::on`] observers in registration
5//!   order, no results. (Cordis `emit` does not await; this crate has no
6//!   executor, so observers run to completion instead of being spawned —
7//!   documented deviation.)
8//! - [`Ctx::parallel`] — the same observers, awaited concurrently.
9//! - [`Ctx::serial`] — [`Ctx::on_serial`] handlers awaited in registration
10//!   order; returns every handler's value in order.
11//! - [`Ctx::waterfall`] — a [`WaterfallMiddleware`] chain over a value; any
12//!   middleware may short-circuit with [`Flow::Stop`] (design intent for
13//!   single-decision events).
14//! - [`Ctx::bail`] — [`Ctx::on_bail`] handlers until the first `Some`
15//!   ("bail") value is returned.
16//!
17//! Every registration (`on`, `on_serial`, `on_waterfall`, `on_bail`) returns
18//! a [`Disposer`] removing exactly that handler — registrations are
19//! reversible side effects.
20
21use std::any::{Any, TypeId};
22use std::collections::HashMap;
23use std::sync::atomic::{AtomicU64, Ordering};
24use std::sync::{Arc, RwLock};
25
26use futures::future::{BoxFuture, FutureExt, join_all};
27
28use crate::ctx::{Ctx, Disposer};
29
30/// Observer for event `E`: invoked by both `emit` and `parallel`.
31pub type Observer<E> = Box<dyn for<'a> Fn(&'a E) -> BoxFuture<'a, ()> + Send + Sync>;
32
33/// Serial handler for event `E` producing a value `R`.
34pub type SerialHandler<E, R> = Box<dyn for<'a> Fn(&'a E) -> BoxFuture<'a, R> + Send + Sync>;
35
36/// Bail handler for event `E` producing an optional bail value `T`.
37pub type BailHandler<E, T> = Box<dyn for<'a> Fn(&'a E) -> BoxFuture<'a, Option<T>> + Send + Sync>;
38
39/// The result of one waterfall middleware step: continue into the rest of
40/// the chain, or short-circuit the whole waterfall (both carry the value).
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum Flow<T> {
43    /// Pass the value to the next middleware.
44    Next(T),
45    /// Short-circuit: later middleware must not run.
46    Stop(T),
47}
48
49impl<T> Flow<T> {
50    pub fn value(self) -> T {
51        match self {
52            Flow::Next(v) | Flow::Stop(v) => v,
53        }
54    }
55
56    pub fn is_stop(&self) -> bool {
57        matches!(self, Flow::Stop(_))
58    }
59}
60
61/// The `next()` handle passed to waterfall middleware: invoking `next(value)`
62/// runs the rest of the chain (whose result is a [`Flow`] — an inner
63/// short-circuit propagates outward). Consumed by [`WaterfallMiddleware`]
64/// implementations.
65pub struct WaterfallNext<'a, T> {
66    run: Box<dyn FnOnce(T) -> BoxFuture<'a, Flow<T>> + Send + 'a>,
67}
68
69impl<'a, T> WaterfallNext<'a, T> {
70    /// Runs the remainder of the middleware chain with `value`.
71    pub async fn next(self, value: T) -> Flow<T> {
72        (self.run)(value).await
73    }
74}
75
76/// One step of a waterfall chain over event `E` and value `T`.
77///
78/// The `self: Arc<Self>` receiver lets the continuation own the middleware
79/// across `await` points without borrowing it, keeping the chain composable
80/// for any handler lifetime.
81pub trait WaterfallMiddleware<E, T>: Send + Sync + 'static
82where
83    E: Any + Send + Sync,
84    T: Send + 'static,
85{
86    fn handle<'a>(
87        self: Arc<Self>,
88        event: &'a E,
89        value: T,
90        next: WaterfallNext<'a, T>,
91    ) -> BoxFuture<'a, Flow<T>>;
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
95pub(crate) enum HandlerKind {
96    Observer,
97    Serial,
98    Waterfall,
99    Bail,
100}
101
102struct HandlerSlot {
103    id: u64,
104    erased: Arc<dyn Any + Send + Sync>, // concrete type: Arc<H> for the key's H
105}
106
107/// The typed-event handler registry carried by [`Ctx`]. Handlers are keyed
108/// by (kind, event/value `TypeId` pairs), so serial/bail/waterfall chains
109/// with the same event type but different value types coexist.
110#[derive(Default)]
111pub(crate) struct Events {
112    next_id: AtomicU64,
113    handlers: RwLock<HashMap<(HandlerKind, TypeId), Vec<HandlerSlot>>>,
114}
115
116impl Events {
117    fn insert(&self, key: (HandlerKind, TypeId), erased: Arc<dyn Any + Send + Sync>) -> u64 {
118        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
119        self.handlers
120            .write()
121            .expect("kian-plugin: handlers lock poisoned")
122            .entry(key)
123            .or_default()
124            .push(HandlerSlot { id, erased });
125        id
126    }
127
128    fn remove(&self, key: (HandlerKind, TypeId), id: u64) {
129        let mut handlers = self
130            .handlers
131            .write()
132            .expect("kian-plugin: handlers lock poisoned");
133        if let Some(slots) = handlers.get_mut(&key) {
134            slots.retain(|slot| slot.id != id);
135        }
136    }
137
138    /// Clones the typed handlers registered for `key` (registration order).
139    fn snapshot<H>(&self, key: (HandlerKind, TypeId)) -> Vec<Arc<H>>
140    where
141        H: ?Sized + Send + Sync + 'static,
142    {
143        let handlers = self
144            .handlers
145            .read()
146            .expect("kian-plugin: handlers lock poisoned");
147        handlers
148            .get(&key)
149            .map(|slots| {
150                slots
151                    .iter()
152                    .filter_map(|slot| {
153                        Arc::clone(&slot.erased)
154                            .downcast::<Arc<H>>()
155                            .ok()
156                            .map(|wrapped| (*wrapped).clone())
157                    })
158                    .collect()
159            })
160            .unwrap_or_default()
161    }
162}
163
164impl Ctx {
165    fn register_handler<H>(
166        &self,
167        kind: HandlerKind,
168        event_type: TypeId,
169        handler: Arc<H>,
170    ) -> Disposer
171    where
172        H: ?Sized + Send + Sync + 'static,
173    {
174        let key = (kind, event_type);
175        let erased: Arc<dyn Any + Send + Sync> = Arc::new(handler);
176        let id = self.inner.events.insert(key, erased);
177        let inner = Arc::clone(&self.inner);
178        Disposer::from_fn(move || inner.events.remove(key, id))
179    }
180
181    /// Registers an observer for `E` (used by both `emit` and `parallel`).
182    /// The returned [`Disposer`] unregisters exactly this observer.
183    pub fn on<E, F>(&self, handler: F) -> Disposer
184    where
185        E: Any + Send + Sync,
186        F: for<'a> Fn(&'a E) -> BoxFuture<'a, ()> + Send + Sync + 'static,
187    {
188        let boxed: Observer<E> = Box::new(handler);
189        self.register_handler(HandlerKind::Observer, TypeId::of::<E>(), Arc::new(boxed))
190    }
191
192    /// Registers an ordered handler for `E` producing `R`.
193    pub fn on_serial<E, R, F>(&self, handler: F) -> Disposer
194    where
195        E: Any + Send + Sync,
196        R: Send + 'static,
197        F: for<'a> Fn(&'a E) -> BoxFuture<'a, R> + Send + Sync + 'static,
198    {
199        let boxed: SerialHandler<E, R> = Box::new(handler);
200        self.register_handler(HandlerKind::Serial, TypeId::of::<(E, R)>(), Arc::new(boxed))
201    }
202
203    /// Registers one waterfall middleware step for `(E, T)`.
204    pub fn on_waterfall<E, T, M>(&self, middleware: M) -> Disposer
205    where
206        E: Any + Send + Sync,
207        T: Send + 'static,
208        M: WaterfallMiddleware<E, T>,
209    {
210        let boxed: Arc<dyn WaterfallMiddleware<E, T>> = Arc::new(middleware);
211        self.register_handler(HandlerKind::Waterfall, TypeId::of::<(E, T)>(), boxed)
212    }
213
214    /// Registers a bail handler for `(E, T)`: `Some(value)` bails the
215    /// dispatch, `None` defers to the next handler.
216    pub fn on_bail<E, T, F>(&self, handler: F) -> Disposer
217    where
218        E: Any + Send + Sync,
219        T: Send + 'static,
220        F: for<'a> Fn(&'a E) -> BoxFuture<'a, Option<T>> + Send + Sync + 'static,
221    {
222        let boxed: BailHandler<E, T> = Box::new(handler);
223        self.register_handler(HandlerKind::Bail, TypeId::of::<(E, T)>(), Arc::new(boxed))
224    }
225
226    /// Runs all observers of `E` in registration order; no results.
227    pub async fn emit<E>(&self, event: &E)
228    where
229        E: Any + Send + Sync,
230    {
231        let observers: Vec<Arc<Observer<E>>> = self
232            .inner
233            .events
234            .snapshot((HandlerKind::Observer, TypeId::of::<E>()));
235        for observer in observers {
236            observer(event).await;
237        }
238    }
239
240    /// Runs all observers of `E` concurrently and awaits every one.
241    pub async fn parallel<E>(&self, event: &E)
242    where
243        E: Any + Send + Sync,
244    {
245        let observers: Vec<Arc<Observer<E>>> = self
246            .inner
247            .events
248            .snapshot((HandlerKind::Observer, TypeId::of::<E>()));
249        let pending: Vec<BoxFuture<'_, ()>> = observers
250            .into_iter()
251            .map(|observer| observer(event))
252            .collect();
253        join_all(pending).await;
254    }
255
256    /// Awaits each serial handler of `E` in registration order and returns
257    /// every handler's value, in order.
258    pub async fn serial<E, R>(&self, event: &E) -> Vec<R>
259    where
260        E: Any + Send + Sync,
261        R: Send + 'static,
262    {
263        let handlers: Vec<Arc<SerialHandler<E, R>>> = self
264            .inner
265            .events
266            .snapshot((HandlerKind::Serial, TypeId::of::<(E, R)>()));
267        let mut results = Vec::with_capacity(handlers.len());
268        for handler in handlers {
269            results.push(handler(event).await);
270        }
271        results
272    }
273
274    /// Threads `initial` through the waterfall middleware chain for `(E, T)`
275    /// in registration order; the first [`Flow::Stop`] short-circuits the
276    /// chain (later middleware must not run).
277    pub async fn waterfall<E, T>(&self, event: &E, initial: T) -> T
278    where
279        E: Any + Send + Sync,
280        T: Send + 'static,
281    {
282        let chain: Vec<Arc<dyn WaterfallMiddleware<E, T>>> = self
283            .inner
284            .events
285            .snapshot((HandlerKind::Waterfall, TypeId::of::<(E, T)>()));
286        compose_waterfall(&chain, event, 0, initial).await.value()
287    }
288
289    /// Runs bail handlers of `(E, T)` in registration order until the first
290    /// `Some` value; `None` if every handler deferred.
291    pub async fn bail<E, T>(&self, event: &E) -> Option<T>
292    where
293        E: Any + Send + Sync,
294        T: Send + 'static,
295    {
296        let handlers: Vec<Arc<BailHandler<E, T>>> = self
297            .inner
298            .events
299            .snapshot((HandlerKind::Bail, TypeId::of::<(E, T)>()));
300        for handler in handlers {
301            if let Some(value) = handler(event).await {
302                return Some(value);
303            }
304        }
305        None
306    }
307}
308
309/// Composes the middleware chain index-inside-out: each step receives a
310/// `next` that runs the remainder; a `Flow::Stop` from any level propagates
311/// out without invoking deeper middleware.
312fn compose_waterfall<'a, E, T>(
313    chain: &'a [Arc<dyn WaterfallMiddleware<E, T>>],
314    event: &'a E,
315    index: usize,
316    value: T,
317) -> BoxFuture<'a, Flow<T>>
318where
319    E: Any + Send + Sync,
320    T: Send + 'static,
321{
322    async move {
323        if index == chain.len() {
324            return Flow::Next(value);
325        }
326        let middleware = Arc::clone(&chain[index]);
327        let next = WaterfallNext {
328            run: Box::new(move |v| compose_waterfall(chain, event, index + 1, v)),
329        };
330        middleware.handle(event, value, next).await
331    }
332    .boxed()
333}
334
335#[cfg(test)]
336mod tests {
337    use super::*;
338    use std::sync::Mutex;
339
340    #[derive(Debug, Default, Clone, PartialEq)]
341    struct Ping {
342        seq: u32,
343    }
344
345    #[tokio::test]
346    async fn emit_notifies_all_observers_in_registration_order() {
347        let ctx = Ctx::new();
348        let log = Arc::new(Mutex::new(Vec::new()));
349        let mut keep: Vec<Disposer> = Vec::new();
350        for tag in ["a", "b", "c"] {
351            let log = Arc::clone(&log);
352            keep.push(ctx.on(move |e: &Ping| {
353                let log = Arc::clone(&log);
354                Box::pin(async move {
355                    log.lock().unwrap().push(format!("{tag}:{}", e.seq));
356                })
357            }));
358        }
359        ctx.emit(&Ping { seq: 7 }).await;
360        assert_eq!(*log.lock().unwrap(), ["a:7", "b:7", "c:7"]);
361    }
362
363    #[tokio::test]
364    async fn parallel_awaits_all_observers_concurrently() {
365        let ctx = Ctx::new();
366        let barrier = Arc::new(tokio::sync::Barrier::new(2));
367        let hits = Arc::new(Mutex::new(0u32));
368        let mut keep: Vec<Disposer> = Vec::new();
369        for _ in 0..2 {
370            let barrier = Arc::clone(&barrier);
371            let hits = Arc::clone(&hits);
372            keep.push(ctx.on(move |_e: &Ping| {
373                let barrier = Arc::clone(&barrier);
374                let hits = Arc::clone(&hits);
375                Box::pin(async move {
376                    barrier.wait().await;
377                    *hits.lock().unwrap() += 1;
378                })
379            }));
380        }
381        // If dispatch were serialized, the first barrier waiter would never
382        // release and the timeout would fire.
383        let dispatched = tokio::time::timeout(
384            std::time::Duration::from_secs(5),
385            ctx.parallel(&Ping { seq: 1 }),
386        )
387        .await;
388        assert!(
389            dispatched.is_ok(),
390            "parallel dispatch must not serialize observers"
391        );
392        assert_eq!(*hits.lock().unwrap(), 2);
393    }
394
395    #[tokio::test]
396    async fn serial_awaits_in_order_and_returns_every_value() {
397        let ctx = Ctx::new();
398        let log = Arc::new(Mutex::new(Vec::new()));
399        let mut keep: Vec<Disposer> = Vec::new();
400        for tag in ["first", "second"] {
401            let log = Arc::clone(&log);
402            keep.push(ctx.on_serial(move |_e: &Ping| {
403                let log = Arc::clone(&log);
404                Box::pin(async move {
405                    log.lock().unwrap().push(tag);
406                    format!("done:{tag}")
407                })
408            }));
409        }
410        let results = ctx.serial::<Ping, String>(&Ping { seq: 3 }).await;
411        assert_eq!(results, vec!["done:first", "done:second"]);
412        assert_eq!(*log.lock().unwrap(), ["first", "second"]);
413    }
414
415    struct Add(i32);
416
417    impl WaterfallMiddleware<Ping, i32> for Add {
418        fn handle<'a>(
419            self: Arc<Self>,
420            _event: &'a Ping,
421            value: i32,
422            next: WaterfallNext<'a, i32>,
423        ) -> BoxFuture<'a, Flow<i32>> {
424            Box::pin(async move { next.next(value + self.0).await })
425        }
426    }
427
428    /// Short-circuits the chain once the value exceeds its limit.
429    struct OverLimit(i32);
430
431    impl WaterfallMiddleware<Ping, i32> for OverLimit {
432        fn handle<'a>(
433            self: Arc<Self>,
434            _event: &'a Ping,
435            value: i32,
436            next: WaterfallNext<'a, i32>,
437        ) -> BoxFuture<'a, Flow<i32>> {
438            Box::pin(async move {
439                if value > self.0 {
440                    return Flow::Stop(value);
441                }
442                next.next(value).await
443            })
444        }
445    }
446
447    #[tokio::test]
448    async fn waterfall_threads_value_through_all_middleware() {
449        assert!(!Flow::Next(1).is_stop());
450        assert!(Flow::Stop(1).is_stop());
451
452        let ctx = Ctx::new();
453        let _w1 = ctx.on_waterfall::<Ping, i32, _>(Add(1));
454        let _w2 = ctx.on_waterfall::<Ping, i32, _>(Add(10));
455        let result = ctx.waterfall(&Ping::default(), 5).await;
456        assert_eq!(
457            result, 16,
458            "5 + 1 through the first, + 10 through the second"
459        );
460    }
461
462    #[tokio::test]
463    async fn waterfall_short_circuit_skips_the_rest() {
464        let ctx = Ctx::new();
465        let seen = Arc::new(Mutex::new(Vec::<i32>::new()));
466
467        struct Record(Arc<Mutex<Vec<i32>>>);
468        impl WaterfallMiddleware<Ping, i32> for Record {
469            fn handle<'a>(
470                self: Arc<Self>,
471                _event: &'a Ping,
472                value: i32,
473                next: WaterfallNext<'a, i32>,
474            ) -> BoxFuture<'a, Flow<i32>> {
475                Box::pin(async move {
476                    self.0.lock().unwrap().push(value);
477                    next.next(value).await
478                })
479            }
480        }
481
482        let _w1 = ctx.on_waterfall::<Ping, i32, _>(OverLimit(3));
483        let _w2 = ctx.on_waterfall::<Ping, i32, _>(Record(Arc::clone(&seen)));
484
485        let result = ctx.waterfall(&Ping::default(), 5).await;
486        assert_eq!(result, 5, "OverLimit(3) stops the chain with the raw value");
487        assert!(
488            seen.lock().unwrap().is_empty(),
489            "middleware after the short-circuit must not run"
490        );
491    }
492
493    #[tokio::test]
494    async fn bail_returns_the_first_some_and_skips_the_rest() {
495        let ctx = Ctx::new();
496        let third_called = Arc::new(Mutex::new(false));
497
498        let _b1 = ctx
499            .on_bail::<Ping, String, _>(move |_e: &Ping| Box::pin(async move { None::<String> }));
500        let _b2 = ctx.on_bail::<Ping, String, _>(move |_e: &Ping| {
501            Box::pin(async move { Some("veto".to_string()) })
502        });
503        let flag = Arc::clone(&third_called);
504        let _b3 = ctx.on_bail::<Ping, String, _>(move |_e: &Ping| {
505            let flag = Arc::clone(&flag);
506            Box::pin(async move {
507                *flag.lock().unwrap() = true;
508                Some("late".to_string())
509            })
510        });
511
512        let verdict = ctx.bail::<Ping, String>(&Ping::default()).await;
513        assert_eq!(verdict.as_deref(), Some("veto"));
514        assert!(
515            !*third_called.lock().unwrap(),
516            "handlers after the first bail value must not run"
517        );
518    }
519
520    #[tokio::test]
521    async fn observer_disposer_unregisters_the_handler() {
522        let ctx = Ctx::new();
523        let log = Arc::new(Mutex::new(0u32));
524        let disposer = {
525            let log = Arc::clone(&log);
526            ctx.on(move |_e: &Ping| {
527                let log = Arc::clone(&log);
528                Box::pin(async move {
529                    *log.lock().unwrap() += 1;
530                })
531            })
532        };
533        disposer.dispose();
534        ctx.emit(&Ping::default()).await;
535        assert_eq!(*log.lock().unwrap(), 0, "disposed handler must not fire");
536    }
537}