Skip to main content

larastvel_core/events/
mod.rs

1use std::any::{Any, TypeId};
2use std::collections::HashMap;
3use std::future::Future;
4use std::pin::Pin;
5use std::sync::{Arc, Mutex};
6
7use async_trait::async_trait;
8use once_cell::sync::Lazy;
9use sea_orm::EntityTrait;
10
11// ---------------------------------------------------------------------------
12// Model lifecycle events
13// ---------------------------------------------------------------------------
14
15/// Emitted after a model is retrieved from the database via `find()`.
16#[derive(Debug, Clone)]
17pub struct ModelRetrieved<M: EntityTrait>(pub M::Model);
18
19/// Emitted after a model is inserted for the first time.
20#[derive(Debug, Clone)]
21pub struct ModelCreated<M: EntityTrait>(pub M::Model);
22
23/// Emitted after a model is updated.
24#[derive(Debug, Clone)]
25pub struct ModelUpdated<M: EntityTrait>(pub M::Model);
26
27/// Emitted after a model is deleted.
28#[derive(Debug, Clone)]
29pub struct ModelDeleted<M: EntityTrait>(pub M::Model);
30
31/// Emitted after a model is saved (both created and updated).
32#[derive(Debug, Clone)]
33pub struct ModelSaved<M: EntityTrait>(pub M::Model);
34
35type EventPayload = Box<dyn Any + Send + Sync>;
36type ListenerFnInner =
37    dyn Fn(EventPayload) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync;
38type ListenerFn = Arc<ListenerFnInner>;
39
40static REGISTRY: Lazy<Mutex<HashMap<TypeId, Vec<ListenerFn>>>> =
41    Lazy::new(|| Mutex::new(HashMap::new()));
42
43static FAKE_MODE: Lazy<Mutex<bool>> = Lazy::new(|| Mutex::new(false));
44static DISPATCHED_EVENTS: Lazy<Mutex<Vec<(TypeId, String)>>> = Lazy::new(|| Mutex::new(Vec::new()));
45
46pub trait Event: Any + Clone + Send + Sync {}
47impl<T: Any + Clone + Send + Sync> Event for T {}
48
49#[async_trait]
50pub trait Listener<E: Event>: Send + Sync {
51    async fn handle(&self, event: E);
52}
53
54pub struct EventService;
55
56impl EventService {
57    pub fn listen<E: Event, L>(listener: L)
58    where
59        L: Listener<E> + 'static,
60    {
61        let type_id = TypeId::of::<E>();
62        let listener = Arc::new(listener);
63        let fn_box: ListenerFn = Arc::new(move |payload: EventPayload| {
64            let event = match payload.downcast::<E>() {
65                Ok(e) => *e,
66                Err(_) => return Box::pin(async {}),
67            };
68            let listener = listener.clone();
69            Box::pin(async move {
70                listener.handle(event).await;
71            })
72        });
73
74        let mut registry = REGISTRY.lock().unwrap();
75        registry.entry(type_id).or_default().push(fn_box);
76    }
77
78    pub fn listen_fn<E: Event, F, Fut>(f: F)
79    where
80        F: Fn(E) -> Fut + Send + Sync + 'static,
81        Fut: Future<Output = ()> + Send + 'static,
82    {
83        let type_id = TypeId::of::<E>();
84        let fn_box: ListenerFn = Arc::new(move |payload: EventPayload| {
85            let event = match payload.downcast::<E>() {
86                Ok(e) => *e,
87                Err(_) => return Box::pin(async {}),
88            };
89            Box::pin(f(event))
90        });
91
92        let mut registry = REGISTRY.lock().unwrap();
93        registry.entry(type_id).or_default().push(fn_box);
94    }
95
96    pub async fn dispatch<E: Event>(event: E) {
97        {
98            let fake = FAKE_MODE.lock().unwrap();
99            if *fake {
100                let mut dispatched = DISPATCHED_EVENTS.lock().unwrap();
101                dispatched.push((TypeId::of::<E>(), std::any::type_name::<E>().to_string()));
102                return;
103            }
104        }
105
106        let type_id = TypeId::of::<E>();
107        let listeners = {
108            let registry = REGISTRY.lock().unwrap();
109            registry.get(&type_id).cloned().unwrap_or_default()
110        };
111
112        for listener in &listeners {
113            (listener.as_ref())(Box::new(event.clone())).await;
114        }
115    }
116
117    pub fn fake() {
118        let mut fake = FAKE_MODE.lock().unwrap();
119        *fake = true;
120        let mut dispatched = DISPATCHED_EVENTS.lock().unwrap();
121        dispatched.clear();
122    }
123
124    pub fn assert_dispatched<E: Event>() -> bool {
125        let dispatched = DISPATCHED_EVENTS.lock().unwrap();
126        dispatched.iter().any(|(id, _)| *id == TypeId::of::<E>())
127    }
128
129    pub fn assert_not_dispatched<E: Event>() -> bool {
130        !Self::assert_dispatched::<E>()
131    }
132
133    pub fn assert_dispatched_times<E: Event>(expected: usize) -> bool {
134        let dispatched = DISPATCHED_EVENTS.lock().unwrap();
135        let count = dispatched
136            .iter()
137            .filter(|(id, _)| *id == TypeId::of::<E>())
138            .count();
139        count == expected
140    }
141
142    pub fn clear_listeners<E: Event>() {
143        let mut registry = REGISTRY.lock().unwrap();
144        registry.remove(&TypeId::of::<E>());
145    }
146
147    pub fn clear_all_listeners() {
148        let mut registry = REGISTRY.lock().unwrap();
149        registry.clear();
150    }
151
152    pub fn reset() {
153        Self::clear_all_listeners();
154        let mut fake = FAKE_MODE.lock().unwrap();
155        *fake = false;
156        let mut dispatched = DISPATCHED_EVENTS.lock().unwrap();
157        dispatched.clear();
158    }
159
160    pub fn has_listeners<E: Event>() -> bool {
161        let registry = REGISTRY.lock().unwrap();
162        registry.contains_key(&TypeId::of::<E>())
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
170
171    #[tokio::test]
172    #[serial_test::serial]
173    async fn test_all_events() {
174        test_minimal_arc_fn_call().await;
175        test_listen_and_dispatch_with_struct().await;
176        test_listen_fn_and_dispatch().await;
177        test_multiple_listeners().await;
178        test_no_listeners_does_not_panic().await;
179        test_clear_listeners().await;
180        test_has_listeners().await;
181        test_fake_mode_integration().await;
182        test_clear_all_listeners().await;
183        test_multiple_event_types().await;
184        test_listener_receives_correct_data().await;
185    }
186
187    async fn test_minimal_arc_fn_call() {
188        let called = Arc::new(AtomicBool::new(false));
189        let c = called.clone();
190
191        let f: ListenerFn = Arc::new(move |payload: EventPayload| {
192            let _event = *payload.downcast::<String>().unwrap();
193            let c = c.clone();
194            Box::pin(async move {
195                c.store(true, Ordering::SeqCst);
196            })
197        });
198
199        f(Box::new("hello".to_string())).await;
200        assert!(called.load(Ordering::SeqCst));
201    }
202
203    #[derive(Debug, Clone, PartialEq)]
204    struct OrderShipped {
205        order_id: String,
206    }
207
208    struct SendNotification;
209
210    #[async_trait]
211    impl Listener<OrderShipped> for SendNotification {
212        async fn handle(&self, _event: OrderShipped) {}
213    }
214
215    async fn test_listen_and_dispatch_with_struct() {
216        EventService::clear_all_listeners();
217        let handled = Arc::new(AtomicBool::new(false));
218        let h = handled.clone();
219
220        struct TestListener(Arc<AtomicBool>);
221        #[async_trait]
222        impl Listener<OrderShipped> for TestListener {
223            async fn handle(&self, _event: OrderShipped) {
224                self.0.store(true, Ordering::SeqCst);
225            }
226        }
227
228        EventService::listen::<OrderShipped, TestListener>(TestListener(h));
229        EventService::dispatch(OrderShipped {
230            order_id: "123".into(),
231        })
232        .await;
233
234        assert!(handled.load(Ordering::SeqCst));
235        EventService::clear_listeners::<OrderShipped>();
236    }
237
238    async fn test_listen_fn_and_dispatch() {
239        EventService::clear_all_listeners();
240        let handled = Arc::new(AtomicBool::new(false));
241        let h = handled.clone();
242
243        EventService::listen_fn::<OrderShipped, _, _>(move |_event| {
244            let h = h.clone();
245            async move {
246                h.store(true, Ordering::SeqCst);
247            }
248        });
249
250        EventService::dispatch(OrderShipped {
251            order_id: "456".into(),
252        })
253        .await;
254
255        assert!(handled.load(Ordering::SeqCst));
256        EventService::clear_listeners::<OrderShipped>();
257    }
258
259    async fn test_multiple_listeners() {
260        EventService::clear_all_listeners();
261        let call_count = Arc::new(AtomicUsize::new(0));
262        let c1 = call_count.clone();
263        let c2 = call_count.clone();
264
265        EventService::listen_fn::<OrderShipped, _, _>(move |_| {
266            let c = c1.clone();
267            async move {
268                c.fetch_add(1, Ordering::SeqCst);
269            }
270        });
271
272        EventService::listen_fn::<OrderShipped, _, _>(move |_| {
273            let c = c2.clone();
274            async move {
275                c.fetch_add(1, Ordering::SeqCst);
276            }
277        });
278
279        EventService::dispatch(OrderShipped {
280            order_id: "789".into(),
281        })
282        .await;
283
284        assert_eq!(call_count.load(Ordering::SeqCst), 2);
285        EventService::clear_listeners::<OrderShipped>();
286    }
287
288    async fn test_no_listeners_does_not_panic() {
289        EventService::clear_all_listeners();
290        EventService::dispatch(OrderShipped {
291            order_id: "no-listeners".into(),
292        })
293        .await;
294    }
295
296    async fn test_clear_listeners() {
297        EventService::clear_all_listeners();
298        let handled = Arc::new(AtomicBool::new(false));
299        let h = handled.clone();
300
301        EventService::listen_fn::<OrderShipped, _, _>(move |_| {
302            let h = h.clone();
303            async move {
304                h.store(true, Ordering::SeqCst);
305            }
306        });
307
308        EventService::clear_listeners::<OrderShipped>();
309        assert!(!EventService::has_listeners::<OrderShipped>());
310
311        EventService::dispatch(OrderShipped {
312            order_id: "cleared".into(),
313        })
314        .await;
315
316        assert!(!handled.load(Ordering::SeqCst));
317    }
318
319    async fn test_has_listeners() {
320        EventService::clear_all_listeners();
321        assert!(!EventService::has_listeners::<OrderShipped>());
322
323        EventService::listen::<OrderShipped, SendNotification>(SendNotification);
324        assert!(EventService::has_listeners::<OrderShipped>());
325
326        EventService::clear_all_listeners();
327    }
328
329    async fn test_fake_mode_integration() {
330        EventService::clear_all_listeners();
331
332        assert!(EventService::assert_not_dispatched::<OrderShipped>());
333
334        EventService::fake();
335
336        let handled = Arc::new(AtomicBool::new(false));
337        let h = handled.clone();
338        EventService::listen_fn::<OrderShipped, _, _>(move |_| {
339            let h = h.clone();
340            async move {
341                h.store(true, Ordering::SeqCst);
342            }
343        });
344
345        EventService::dispatch(OrderShipped {
346            order_id: "fake-test".into(),
347        })
348        .await;
349        assert!(
350            !handled.load(Ordering::SeqCst),
351            "listener should not be called in fake mode"
352        );
353
354        assert!(EventService::assert_dispatched::<OrderShipped>());
355
356        EventService::dispatch(OrderShipped {
357            order_id: "another".into(),
358        })
359        .await;
360        assert!(EventService::assert_dispatched_times::<OrderShipped>(2));
361
362        EventService::reset();
363        assert!(EventService::assert_not_dispatched::<OrderShipped>());
364    }
365
366    async fn test_clear_all_listeners() {
367        EventService::clear_all_listeners();
368        EventService::listen::<OrderShipped, SendNotification>(SendNotification);
369        assert!(EventService::has_listeners::<OrderShipped>());
370        EventService::clear_all_listeners();
371        assert!(!EventService::has_listeners::<OrderShipped>());
372    }
373
374    #[derive(Debug, Clone, PartialEq)]
375    struct UserRegistered {
376        email: String,
377    }
378
379    async fn test_multiple_event_types() {
380        EventService::clear_all_listeners();
381        let order_handled = Arc::new(AtomicBool::new(false));
382        let user_handled = Arc::new(AtomicBool::new(false));
383        let oh = order_handled.clone();
384        let uh = user_handled.clone();
385
386        EventService::listen_fn::<OrderShipped, _, _>(move |_| {
387            let oh = oh.clone();
388            async move {
389                oh.store(true, Ordering::SeqCst);
390            }
391        });
392
393        EventService::listen_fn::<UserRegistered, _, _>(move |_| {
394            let uh = uh.clone();
395            async move {
396                uh.store(true, Ordering::SeqCst);
397            }
398        });
399
400        EventService::dispatch(OrderShipped {
401            order_id: "multi".into(),
402        })
403        .await;
404
405        assert!(order_handled.load(Ordering::SeqCst));
406        assert!(!user_handled.load(Ordering::SeqCst));
407
408        EventService::dispatch(UserRegistered {
409            email: "test@test.com".into(),
410        })
411        .await;
412
413        assert!(user_handled.load(Ordering::SeqCst));
414        EventService::clear_all_listeners();
415    }
416
417    async fn test_listener_receives_correct_data() {
418        EventService::clear_all_listeners();
419        let received = Arc::new(Mutex::new(None));
420        let r = received.clone();
421
422        EventService::listen_fn::<OrderShipped, _, _>(move |event| {
423            let r = r.clone();
424            async move {
425                let mut recv = r.lock().unwrap();
426                *recv = Some(event.order_id);
427            }
428        });
429
430        EventService::dispatch(OrderShipped {
431            order_id: "data-check".into(),
432        })
433        .await;
434
435        let recv = received.lock().unwrap();
436        assert_eq!(recv.as_deref(), Some("data-check"));
437        EventService::clear_all_listeners();
438    }
439
440    // --- #[listener] attribute macro tests ---
441
442    use crate::listener;
443
444    #[derive(Debug, Clone, PartialEq)]
445    struct InvoicePaid {
446        invoice_id: String,
447        amount: f64,
448    }
449
450    static LISTENER_HANDLED: AtomicBool = AtomicBool::new(false);
451    static LISTENER_INVOICE_ID: Mutex<String> = Mutex::new(String::new());
452
453    #[listener(InvoicePaid)]
454    async fn send_invoice_receipt(event: InvoicePaid) {
455        let _ = event;
456    }
457
458    #[tokio::test]
459    #[serial_test::serial]
460    async fn test_listener_macro_generates_struct_and_registers() {
461        EventService::clear_all_listeners();
462        LISTENER_HANDLED.store(false, Ordering::SeqCst);
463
464        #[listener(InvoicePaid)]
465        async fn record_payment(_event: InvoicePaid) {
466            LISTENER_HANDLED.store(true, Ordering::SeqCst);
467        }
468
469        RecordPaymentListener::listen();
470
471        assert!(EventService::has_listeners::<InvoicePaid>());
472
473        EventService::dispatch(InvoicePaid {
474            invoice_id: "INV-001".into(),
475            amount: 99.99,
476        })
477        .await;
478
479        assert!(LISTENER_HANDLED.load(Ordering::SeqCst));
480        EventService::clear_listeners::<InvoicePaid>();
481    }
482
483    #[tokio::test]
484    #[serial_test::serial]
485    async fn test_listener_macro_receives_event_data() {
486        EventService::clear_all_listeners();
487        *LISTENER_INVOICE_ID.lock().unwrap() = String::new();
488
489        #[listener(InvoicePaid)]
490        async fn log_invoice(event: InvoicePaid) {
491            let mut recv = LISTENER_INVOICE_ID.lock().unwrap();
492            *recv = event.invoice_id;
493        }
494
495        LogInvoiceListener::listen();
496
497        EventService::dispatch(InvoicePaid {
498            invoice_id: "INV-002".into(),
499            amount: 49.50,
500        })
501        .await;
502
503        {
504            let recv = LISTENER_INVOICE_ID.lock().unwrap();
505            assert_eq!(*recv, "INV-002");
506        }
507        EventService::clear_listeners::<InvoicePaid>();
508    }
509
510    #[tokio::test]
511    #[serial_test::serial]
512    async fn test_listener_macro_top_level() {
513        EventService::clear_all_listeners();
514
515        SendInvoiceReceiptListener::listen();
516        assert!(EventService::has_listeners::<InvoicePaid>());
517
518        EventService::dispatch(InvoicePaid {
519            invoice_id: "INV-003".into(),
520            amount: 10.00,
521        })
522        .await;
523
524        EventService::clear_listeners::<InvoicePaid>();
525    }
526
527    // --- #[queued_listener] attribute macro tests ---
528
529    use crate::queued_listener;
530
531    #[tokio::test]
532    #[serial_test::serial]
533    async fn test_queued_listener_dispatches_job() {
534        EventService::clear_all_listeners();
535        static QUEUED_FLAG: AtomicBool = AtomicBool::new(false);
536
537        #[derive(Debug, Clone, PartialEq)]
538        struct UserRegistered {
539            user_id: u64,
540        }
541
542        #[queued_listener(UserRegistered)]
543        async fn send_welcome_email(event: UserRegistered) -> Result<(), crate::queue::JobError> {
544            let _ = event;
545            QUEUED_FLAG.store(true, Ordering::SeqCst);
546            Ok(())
547        }
548
549        SendWelcomeEmailListener::listen();
550        assert!(EventService::has_listeners::<UserRegistered>());
551
552        EventService::dispatch(UserRegistered { user_id: 42 }).await;
553
554        // The queued listener dispatches a job synchronously (SyncQueue),
555        // so the flag should be set after dispatch.
556        assert!(QUEUED_FLAG.load(Ordering::SeqCst));
557        EventService::clear_listeners::<UserRegistered>();
558    }
559
560    #[tokio::test]
561    #[serial_test::serial]
562    async fn test_queued_listener_job_name() {
563        EventService::clear_all_listeners();
564
565        #[derive(Debug, Clone, PartialEq)]
566        struct OrderPlaced {
567            id: u64,
568        }
569
570        #[queued_listener(OrderPlaced)]
571        async fn on_order_placed(event: OrderPlaced) -> Result<(), crate::queue::JobError> {
572            let _ = event;
573            Ok(())
574        }
575
576        let job = OnOrderPlacedJob {
577            event: OrderPlaced { id: 1 },
578        };
579        assert_eq!(
580            <OnOrderPlacedJob as crate::queue::ShouldQueue>::name(&job),
581            "on_order_placed"
582        );
583    }
584
585    // --- #[observer] attribute macro tests ---
586
587    use crate::models::DbModel;
588    use crate::observer;
589
590    // A minimal SeaORM entity for use in observer tests
591    mod obs_user {
592        use sea_orm::entity::prelude::*;
593
594        #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
595        #[sea_orm(table_name = "obs_users")]
596        pub struct Model {
597            #[sea_orm(primary_key)]
598            pub id: i32,
599            pub name: String,
600        }
601
602        #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
603        pub enum Relation {}
604
605        impl ActiveModelBehavior for ActiveModel {}
606    }
607
608    struct ObsUser;
609
610    impl DbModel for ObsUser {
611        type Entity = obs_user::Entity;
612    }
613
614    #[test]
615    fn test_observer_macro_compiles() {
616        use super::*;
617
618        struct TestObserver;
619
620        #[observer(ObsUser)]
621        impl TestObserver {
622            async fn created(&self, _model: obs_user::Model) {}
623
624            async fn deleted(&self, _model: obs_user::Model) {}
625        }
626
627        // Verify the listener impls exist by requiring the trait bounds
628        fn _assert_listener<E, L>()
629        where
630            E: Event,
631            L: Listener<E>,
632        {
633        }
634        _assert_listener::<ModelCreated<obs_user::Entity>, TestObserver>();
635        _assert_listener::<ModelDeleted<obs_user::Entity>, TestObserver>();
636    }
637
638    #[test]
639    #[serial_test::serial]
640    fn test_observer_observe_method_registers_listeners() {
641        EventService::clear_all_listeners();
642
643        struct TestObserver2;
644
645        #[observer(ObsUser)]
646        impl TestObserver2 {
647            async fn created(&self, _model: obs_user::Model) {}
648
649            async fn updated(&self, _model: obs_user::Model) {}
650        }
651
652        TestObserver2::observe();
653
654        assert!(EventService::has_listeners::<ModelCreated<obs_user::Entity>>());
655        assert!(EventService::has_listeners::<ModelUpdated<obs_user::Entity>>());
656
657        // Should NOT have listener for deleted (no deleted method defined)
658        assert!(!EventService::has_listeners::<ModelDeleted<obs_user::Entity>>());
659
660        EventService::clear_all_listeners();
661    }
662
663    #[tokio::test]
664    #[serial_test::serial]
665    async fn test_observer_receives_created_event() {
666        EventService::clear_all_listeners();
667        static CALLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
668
669        struct CreatedObserver;
670
671        #[observer(ObsUser)]
672        impl CreatedObserver {
673            async fn created(&self, _model: obs_user::Model) {
674                CALLED.store(true, std::sync::atomic::Ordering::SeqCst);
675            }
676        }
677
678        CreatedObserver::observe();
679        assert!(EventService::has_listeners::<ModelCreated<obs_user::Entity>>());
680
681        EventService::dispatch(ModelCreated::<obs_user::Entity>(obs_user::Model {
682            id: 1,
683            name: "test".into(),
684        }))
685        .await;
686
687        assert!(CALLED.load(std::sync::atomic::Ordering::SeqCst));
688        EventService::clear_listeners::<ModelCreated<obs_user::Entity>>();
689    }
690
691    #[tokio::test]
692    #[serial_test::serial]
693    async fn test_observer_receives_deleted_event() {
694        EventService::clear_all_listeners();
695        static HANDLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
696
697        struct DeletedObserver;
698
699        #[observer(ObsUser)]
700        impl DeletedObserver {
701            async fn deleted(&self, _model: obs_user::Model) {
702                HANDLED.store(true, std::sync::atomic::Ordering::SeqCst);
703            }
704        }
705
706        DeletedObserver::observe();
707        assert!(EventService::has_listeners::<ModelDeleted<obs_user::Entity>>());
708
709        EventService::dispatch(ModelDeleted::<obs_user::Entity>(obs_user::Model {
710            id: 42,
711            name: "deleted-user".into(),
712        }))
713        .await;
714
715        assert!(HANDLED.load(std::sync::atomic::Ordering::SeqCst));
716        EventService::clear_listeners::<ModelDeleted<obs_user::Entity>>();
717    }
718
719    #[test]
720    fn test_observer_macro_handles_all_hook_methods() {
721        #[allow(dead_code)]
722        struct FullObserver;
723
724        // All five hooks — should compile and generate all five listener impls
725        #[observer(ObsUser)]
726        #[allow(dead_code)]
727        impl FullObserver {
728            async fn created(&self, _model: obs_user::Model) {}
729            async fn updated(&self, _model: obs_user::Model) {}
730            async fn deleted(&self, _model: obs_user::Model) {}
731            async fn saved(&self, _model: obs_user::Model) {}
732            async fn retrieved(&self, _model: obs_user::Model) {}
733        }
734
735        fn _assert_created()
736        where
737            FullObserver: Listener<ModelCreated<obs_user::Entity>>,
738        {
739        }
740        fn _assert_updated()
741        where
742            FullObserver: Listener<ModelUpdated<obs_user::Entity>>,
743        {
744        }
745        fn _assert_deleted()
746        where
747            FullObserver: Listener<ModelDeleted<obs_user::Entity>>,
748        {
749        }
750        fn _assert_saved()
751        where
752            FullObserver: Listener<ModelSaved<obs_user::Entity>>,
753        {
754        }
755        fn _assert_retrieved()
756        where
757            FullObserver: Listener<ModelRetrieved<obs_user::Entity>>,
758        {
759        }
760    }
761}