larust_events/lib.rs
1//! A lightweight, explicit, in-process pub/sub - Laravel's `Event::dispatch`/
2//! listeners, deliberately scaled down. No persistence, no queue
3//! involvement, no derive macro, no DI-container resolution: listeners are
4//! registered explicitly (`listeners().on::<E>(...)`, same "build a
5//! registry, then publish it" shape as
6//! `larust_http::route`'s named-route registry), and every listener for an
7//! event runs synchronously, in registration order, in-process - the same
8//! default Laravel itself uses (only a `ShouldQueue` listener defers
9//! there). A listener that needs to defer real work should enqueue a
10//! `larust_queue::Job` instead of doing it inline.
11
12use std::any::{Any, TypeId};
13use std::collections::HashMap;
14use std::future::Future;
15use std::pin::Pin;
16use std::sync::OnceLock;
17
18/// Any plain `Clone + Send + Sync + 'static` value can be an event - a
19/// blanket impl, no derive, no required methods. `Clone` is required
20/// because each of possibly-several listeners for one dispatch gets its
21/// own owned copy to move into its independently-`'static` future.
22pub trait Event: Clone + Send + Sync + 'static {}
23impl<T: Clone + Send + Sync + 'static> Event for T {}
24
25type BoxedFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
26type BoxedListener = Box<dyn Fn(Box<dyn Any + Send + Sync>) -> BoxedFuture + Send + Sync>;
27
28static LISTENERS: OnceLock<HashMap<TypeId, Vec<BoxedListener>>> = OnceLock::new();
29
30/// Starts building the process-wide listener registry. Call `.on::<E>(...)`
31/// for each listener, then `.publish()` once, typically right before
32/// `Application::serve()`.
33pub fn listeners() -> ListenerRegistry {
34 ListenerRegistry {
35 map: HashMap::new(),
36 }
37}
38
39#[must_use]
40pub struct ListenerRegistry {
41 map: HashMap<TypeId, Vec<BoxedListener>>,
42}
43
44impl ListenerRegistry {
45 /// Registers `listener` to run whenever an `E` is dispatched. Multiple
46 /// listeners for the same `E` (including across separate `.on::<E>()`
47 /// calls) all run, in the order they were registered.
48 pub fn on<E, F, Fut>(mut self, listener: F) -> Self
49 where
50 E: Event,
51 F: Fn(E) -> Fut + Send + Sync + 'static,
52 Fut: Future<Output = ()> + Send + 'static,
53 {
54 let boxed: BoxedListener = Box::new(move |event: Box<dyn Any + Send + Sync>| {
55 let event = *event
56 .downcast::<E>()
57 .expect("dispatch() only ever boxes an E under its own TypeId key");
58 Box::pin(listener(event))
59 });
60 self.map.entry(TypeId::of::<E>()).or_default().push(boxed);
61 self
62 }
63
64 /// Publishes this registry process-wide - `dispatch()` reads from it
65 /// afterward. Same "second call warns, doesn't panic, first writer
66 /// wins" shape as `larust_http::route::publish_route_names`: a second
67 /// `.publish()` in the same process (e.g. `Application::new()`-style
68 /// re-entry in tests) doesn't overwrite the first registry, and every
69 /// `dispatch()` afterward keeps using it.
70 pub fn publish(self) {
71 if LISTENERS.set(self.map).is_err() {
72 tracing::warn!(
73 "event listener registry published more than once in this process; \
74 dispatch() still uses the first registry's listeners"
75 );
76 }
77 }
78}
79
80/// Runs every listener registered for `E`, sequentially, awaiting each in
81/// turn before moving to the next. A silent no-op if `listeners()...
82/// publish()` was never called, or if nothing is registered for this
83/// specific `E` - there's no failure mode here worth an `AppError`; a
84/// listener that can fail should log its own error internally rather than
85/// short-circuit the others.
86pub async fn dispatch<E: Event>(event: E) {
87 let Some(map) = LISTENERS.get() else {
88 return;
89 };
90 let Some(list) = map.get(&TypeId::of::<E>()) else {
91 return;
92 };
93 for listener in list {
94 listener(Box::new(event.clone())).await;
95 }
96}