larastvel-core 0.2.2

Larastvel framework core - inspired by Laravel
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};

use async_trait::async_trait;
use once_cell::sync::Lazy;
use sea_orm::EntityTrait;

// ---------------------------------------------------------------------------
// Model lifecycle events
// ---------------------------------------------------------------------------

/// Emitted after a model is retrieved from the database via `find()`.
#[derive(Debug, Clone)]
pub struct ModelRetrieved<M: EntityTrait>(pub M::Model);

/// Emitted after a model is inserted for the first time.
#[derive(Debug, Clone)]
pub struct ModelCreated<M: EntityTrait>(pub M::Model);

/// Emitted after a model is updated.
#[derive(Debug, Clone)]
pub struct ModelUpdated<M: EntityTrait>(pub M::Model);

/// Emitted after a model is deleted.
#[derive(Debug, Clone)]
pub struct ModelDeleted<M: EntityTrait>(pub M::Model);

/// Emitted after a model is saved (both created and updated).
#[derive(Debug, Clone)]
pub struct ModelSaved<M: EntityTrait>(pub M::Model);

type EventPayload = Box<dyn Any + Send + Sync>;
type ListenerFnInner =
    dyn Fn(EventPayload) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync;
type ListenerFn = Arc<ListenerFnInner>;

static REGISTRY: Lazy<Mutex<HashMap<TypeId, Vec<ListenerFn>>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

static FAKE_MODE: Lazy<Mutex<bool>> = Lazy::new(|| Mutex::new(false));
static DISPATCHED_EVENTS: Lazy<Mutex<Vec<(TypeId, String)>>> = Lazy::new(|| Mutex::new(Vec::new()));

pub trait Event: Any + Clone + Send + Sync {}
impl<T: Any + Clone + Send + Sync> Event for T {}

#[async_trait]
pub trait Listener<E: Event>: Send + Sync {
    async fn handle(&self, event: E);
}

pub struct EventService;

impl EventService {
    pub fn listen<E: Event, L>(listener: L)
    where
        L: Listener<E> + 'static,
    {
        let type_id = TypeId::of::<E>();
        let listener = Arc::new(listener);
        let fn_box: ListenerFn = Arc::new(move |payload: EventPayload| {
            let event = match payload.downcast::<E>() {
                Ok(e) => *e,
                Err(_) => return Box::pin(async {}),
            };
            let listener = listener.clone();
            Box::pin(async move {
                listener.handle(event).await;
            })
        });

        let mut registry = REGISTRY.lock().unwrap();
        registry.entry(type_id).or_default().push(fn_box);
    }

    pub fn listen_fn<E: Event, F, Fut>(f: F)
    where
        F: Fn(E) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let type_id = TypeId::of::<E>();
        let fn_box: ListenerFn = Arc::new(move |payload: EventPayload| {
            let event = match payload.downcast::<E>() {
                Ok(e) => *e,
                Err(_) => return Box::pin(async {}),
            };
            Box::pin(f(event))
        });

        let mut registry = REGISTRY.lock().unwrap();
        registry.entry(type_id).or_default().push(fn_box);
    }

    pub async fn dispatch<E: Event>(event: E) {
        {
            let fake = FAKE_MODE.lock().unwrap();
            if *fake {
                let mut dispatched = DISPATCHED_EVENTS.lock().unwrap();
                dispatched.push((TypeId::of::<E>(), std::any::type_name::<E>().to_string()));
                return;
            }
        }

        let type_id = TypeId::of::<E>();
        let listeners = {
            let registry = REGISTRY.lock().unwrap();
            registry.get(&type_id).cloned().unwrap_or_default()
        };

        for listener in &listeners {
            (listener.as_ref())(Box::new(event.clone())).await;
        }
    }

    pub fn fake() {
        let mut fake = FAKE_MODE.lock().unwrap();
        *fake = true;
        let mut dispatched = DISPATCHED_EVENTS.lock().unwrap();
        dispatched.clear();
    }

    pub fn assert_dispatched<E: Event>() -> bool {
        let dispatched = DISPATCHED_EVENTS.lock().unwrap();
        dispatched.iter().any(|(id, _)| *id == TypeId::of::<E>())
    }

    pub fn assert_not_dispatched<E: Event>() -> bool {
        !Self::assert_dispatched::<E>()
    }

    pub fn assert_dispatched_times<E: Event>(expected: usize) -> bool {
        let dispatched = DISPATCHED_EVENTS.lock().unwrap();
        let count = dispatched
            .iter()
            .filter(|(id, _)| *id == TypeId::of::<E>())
            .count();
        count == expected
    }

    pub fn clear_listeners<E: Event>() {
        let mut registry = REGISTRY.lock().unwrap();
        registry.remove(&TypeId::of::<E>());
    }

    pub fn clear_all_listeners() {
        let mut registry = REGISTRY.lock().unwrap();
        registry.clear();
    }

    pub fn reset() {
        Self::clear_all_listeners();
        let mut fake = FAKE_MODE.lock().unwrap();
        *fake = false;
        let mut dispatched = DISPATCHED_EVENTS.lock().unwrap();
        dispatched.clear();
    }

    pub fn has_listeners<E: Event>() -> bool {
        let registry = REGISTRY.lock().unwrap();
        registry.contains_key(&TypeId::of::<E>())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

    #[tokio::test]
    #[serial_test::serial]
    async fn test_all_events() {
        test_minimal_arc_fn_call().await;
        test_listen_and_dispatch_with_struct().await;
        test_listen_fn_and_dispatch().await;
        test_multiple_listeners().await;
        test_no_listeners_does_not_panic().await;
        test_clear_listeners().await;
        test_has_listeners().await;
        test_fake_mode_integration().await;
        test_clear_all_listeners().await;
        test_multiple_event_types().await;
        test_listener_receives_correct_data().await;
    }

    async fn test_minimal_arc_fn_call() {
        let called = Arc::new(AtomicBool::new(false));
        let c = called.clone();

        let f: ListenerFn = Arc::new(move |payload: EventPayload| {
            let _event = *payload.downcast::<String>().unwrap();
            let c = c.clone();
            Box::pin(async move {
                c.store(true, Ordering::SeqCst);
            })
        });

        f(Box::new("hello".to_string())).await;
        assert!(called.load(Ordering::SeqCst));
    }

    #[derive(Debug, Clone, PartialEq)]
    struct OrderShipped {
        order_id: String,
    }

    struct SendNotification;

    #[async_trait]
    impl Listener<OrderShipped> for SendNotification {
        async fn handle(&self, _event: OrderShipped) {}
    }

    async fn test_listen_and_dispatch_with_struct() {
        EventService::clear_all_listeners();
        let handled = Arc::new(AtomicBool::new(false));
        let h = handled.clone();

        struct TestListener(Arc<AtomicBool>);
        #[async_trait]
        impl Listener<OrderShipped> for TestListener {
            async fn handle(&self, _event: OrderShipped) {
                self.0.store(true, Ordering::SeqCst);
            }
        }

        EventService::listen::<OrderShipped, TestListener>(TestListener(h));
        EventService::dispatch(OrderShipped {
            order_id: "123".into(),
        })
        .await;

        assert!(handled.load(Ordering::SeqCst));
        EventService::clear_listeners::<OrderShipped>();
    }

    async fn test_listen_fn_and_dispatch() {
        EventService::clear_all_listeners();
        let handled = Arc::new(AtomicBool::new(false));
        let h = handled.clone();

        EventService::listen_fn::<OrderShipped, _, _>(move |_event| {
            let h = h.clone();
            async move {
                h.store(true, Ordering::SeqCst);
            }
        });

        EventService::dispatch(OrderShipped {
            order_id: "456".into(),
        })
        .await;

        assert!(handled.load(Ordering::SeqCst));
        EventService::clear_listeners::<OrderShipped>();
    }

    async fn test_multiple_listeners() {
        EventService::clear_all_listeners();
        let call_count = Arc::new(AtomicUsize::new(0));
        let c1 = call_count.clone();
        let c2 = call_count.clone();

        EventService::listen_fn::<OrderShipped, _, _>(move |_| {
            let c = c1.clone();
            async move {
                c.fetch_add(1, Ordering::SeqCst);
            }
        });

        EventService::listen_fn::<OrderShipped, _, _>(move |_| {
            let c = c2.clone();
            async move {
                c.fetch_add(1, Ordering::SeqCst);
            }
        });

        EventService::dispatch(OrderShipped {
            order_id: "789".into(),
        })
        .await;

        assert_eq!(call_count.load(Ordering::SeqCst), 2);
        EventService::clear_listeners::<OrderShipped>();
    }

    async fn test_no_listeners_does_not_panic() {
        EventService::clear_all_listeners();
        EventService::dispatch(OrderShipped {
            order_id: "no-listeners".into(),
        })
        .await;
    }

    async fn test_clear_listeners() {
        EventService::clear_all_listeners();
        let handled = Arc::new(AtomicBool::new(false));
        let h = handled.clone();

        EventService::listen_fn::<OrderShipped, _, _>(move |_| {
            let h = h.clone();
            async move {
                h.store(true, Ordering::SeqCst);
            }
        });

        EventService::clear_listeners::<OrderShipped>();
        assert!(!EventService::has_listeners::<OrderShipped>());

        EventService::dispatch(OrderShipped {
            order_id: "cleared".into(),
        })
        .await;

        assert!(!handled.load(Ordering::SeqCst));
    }

    async fn test_has_listeners() {
        EventService::clear_all_listeners();
        assert!(!EventService::has_listeners::<OrderShipped>());

        EventService::listen::<OrderShipped, SendNotification>(SendNotification);
        assert!(EventService::has_listeners::<OrderShipped>());

        EventService::clear_all_listeners();
    }

    async fn test_fake_mode_integration() {
        EventService::clear_all_listeners();

        assert!(EventService::assert_not_dispatched::<OrderShipped>());

        EventService::fake();

        let handled = Arc::new(AtomicBool::new(false));
        let h = handled.clone();
        EventService::listen_fn::<OrderShipped, _, _>(move |_| {
            let h = h.clone();
            async move {
                h.store(true, Ordering::SeqCst);
            }
        });

        EventService::dispatch(OrderShipped {
            order_id: "fake-test".into(),
        })
        .await;
        assert!(
            !handled.load(Ordering::SeqCst),
            "listener should not be called in fake mode"
        );

        assert!(EventService::assert_dispatched::<OrderShipped>());

        EventService::dispatch(OrderShipped {
            order_id: "another".into(),
        })
        .await;
        assert!(EventService::assert_dispatched_times::<OrderShipped>(2));

        EventService::reset();
        assert!(EventService::assert_not_dispatched::<OrderShipped>());
    }

    async fn test_clear_all_listeners() {
        EventService::clear_all_listeners();
        EventService::listen::<OrderShipped, SendNotification>(SendNotification);
        assert!(EventService::has_listeners::<OrderShipped>());
        EventService::clear_all_listeners();
        assert!(!EventService::has_listeners::<OrderShipped>());
    }

    #[derive(Debug, Clone, PartialEq)]
    struct UserRegistered {
        email: String,
    }

    async fn test_multiple_event_types() {
        EventService::clear_all_listeners();
        let order_handled = Arc::new(AtomicBool::new(false));
        let user_handled = Arc::new(AtomicBool::new(false));
        let oh = order_handled.clone();
        let uh = user_handled.clone();

        EventService::listen_fn::<OrderShipped, _, _>(move |_| {
            let oh = oh.clone();
            async move {
                oh.store(true, Ordering::SeqCst);
            }
        });

        EventService::listen_fn::<UserRegistered, _, _>(move |_| {
            let uh = uh.clone();
            async move {
                uh.store(true, Ordering::SeqCst);
            }
        });

        EventService::dispatch(OrderShipped {
            order_id: "multi".into(),
        })
        .await;

        assert!(order_handled.load(Ordering::SeqCst));
        assert!(!user_handled.load(Ordering::SeqCst));

        EventService::dispatch(UserRegistered {
            email: "test@test.com".into(),
        })
        .await;

        assert!(user_handled.load(Ordering::SeqCst));
        EventService::clear_all_listeners();
    }

    async fn test_listener_receives_correct_data() {
        EventService::clear_all_listeners();
        let received = Arc::new(Mutex::new(None));
        let r = received.clone();

        EventService::listen_fn::<OrderShipped, _, _>(move |event| {
            let r = r.clone();
            async move {
                let mut recv = r.lock().unwrap();
                *recv = Some(event.order_id);
            }
        });

        EventService::dispatch(OrderShipped {
            order_id: "data-check".into(),
        })
        .await;

        let recv = received.lock().unwrap();
        assert_eq!(recv.as_deref(), Some("data-check"));
        EventService::clear_all_listeners();
    }

    // --- #[listener] attribute macro tests ---

    use crate::listener;

    #[derive(Debug, Clone, PartialEq)]
    struct InvoicePaid {
        invoice_id: String,
        amount: f64,
    }

    static LISTENER_HANDLED: AtomicBool = AtomicBool::new(false);
    static LISTENER_INVOICE_ID: Mutex<String> = Mutex::new(String::new());

    #[listener(InvoicePaid)]
    async fn send_invoice_receipt(event: InvoicePaid) {
        let _ = event;
    }

    #[tokio::test]
    #[serial_test::serial]
    async fn test_listener_macro_generates_struct_and_registers() {
        EventService::clear_all_listeners();
        LISTENER_HANDLED.store(false, Ordering::SeqCst);

        #[listener(InvoicePaid)]
        async fn record_payment(_event: InvoicePaid) {
            LISTENER_HANDLED.store(true, Ordering::SeqCst);
        }

        RecordPaymentListener::listen();

        assert!(EventService::has_listeners::<InvoicePaid>());

        EventService::dispatch(InvoicePaid {
            invoice_id: "INV-001".into(),
            amount: 99.99,
        })
        .await;

        assert!(LISTENER_HANDLED.load(Ordering::SeqCst));
        EventService::clear_listeners::<InvoicePaid>();
    }

    #[tokio::test]
    #[serial_test::serial]
    async fn test_listener_macro_receives_event_data() {
        EventService::clear_all_listeners();
        *LISTENER_INVOICE_ID.lock().unwrap() = String::new();

        #[listener(InvoicePaid)]
        async fn log_invoice(event: InvoicePaid) {
            let mut recv = LISTENER_INVOICE_ID.lock().unwrap();
            *recv = event.invoice_id;
        }

        LogInvoiceListener::listen();

        EventService::dispatch(InvoicePaid {
            invoice_id: "INV-002".into(),
            amount: 49.50,
        })
        .await;

        {
            let recv = LISTENER_INVOICE_ID.lock().unwrap();
            assert_eq!(*recv, "INV-002");
        }
        EventService::clear_listeners::<InvoicePaid>();
    }

    #[tokio::test]
    #[serial_test::serial]
    async fn test_listener_macro_top_level() {
        EventService::clear_all_listeners();

        SendInvoiceReceiptListener::listen();
        assert!(EventService::has_listeners::<InvoicePaid>());

        EventService::dispatch(InvoicePaid {
            invoice_id: "INV-003".into(),
            amount: 10.00,
        })
        .await;

        EventService::clear_listeners::<InvoicePaid>();
    }

    // --- #[queued_listener] attribute macro tests ---

    use crate::queued_listener;

    #[tokio::test]
    #[serial_test::serial]
    async fn test_queued_listener_dispatches_job() {
        EventService::clear_all_listeners();
        static QUEUED_FLAG: AtomicBool = AtomicBool::new(false);

        #[derive(Debug, Clone, PartialEq)]
        struct UserRegistered {
            user_id: u64,
        }

        #[queued_listener(UserRegistered)]
        async fn send_welcome_email(event: UserRegistered) -> Result<(), crate::queue::JobError> {
            let _ = event;
            QUEUED_FLAG.store(true, Ordering::SeqCst);
            Ok(())
        }

        SendWelcomeEmailListener::listen();
        assert!(EventService::has_listeners::<UserRegistered>());

        EventService::dispatch(UserRegistered { user_id: 42 }).await;

        // The queued listener dispatches a job synchronously (SyncQueue),
        // so the flag should be set after dispatch.
        assert!(QUEUED_FLAG.load(Ordering::SeqCst));
        EventService::clear_listeners::<UserRegistered>();
    }

    #[tokio::test]
    #[serial_test::serial]
    async fn test_queued_listener_job_name() {
        EventService::clear_all_listeners();

        #[derive(Debug, Clone, PartialEq)]
        struct OrderPlaced {
            id: u64,
        }

        #[queued_listener(OrderPlaced)]
        async fn on_order_placed(event: OrderPlaced) -> Result<(), crate::queue::JobError> {
            let _ = event;
            Ok(())
        }

        let job = OnOrderPlacedJob {
            event: OrderPlaced { id: 1 },
        };
        assert_eq!(
            <OnOrderPlacedJob as crate::queue::ShouldQueue>::name(&job),
            "on_order_placed"
        );
    }

    // --- #[observer] attribute macro tests ---

    use crate::models::DbModel;
    use crate::observer;

    // A minimal SeaORM entity for use in observer tests
    mod obs_user {
        use sea_orm::entity::prelude::*;

        #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
        #[sea_orm(table_name = "obs_users")]
        pub struct Model {
            #[sea_orm(primary_key)]
            pub id: i32,
            pub name: String,
        }

        #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
        pub enum Relation {}

        impl ActiveModelBehavior for ActiveModel {}
    }

    struct ObsUser;

    impl DbModel for ObsUser {
        type Entity = obs_user::Entity;
    }

    #[test]
    fn test_observer_macro_compiles() {
        use super::*;

        struct TestObserver;

        #[observer(ObsUser)]
        impl TestObserver {
            async fn created(&self, _model: obs_user::Model) {}

            async fn deleted(&self, _model: obs_user::Model) {}
        }

        // Verify the listener impls exist by requiring the trait bounds
        fn _assert_listener<E, L>()
        where
            E: Event,
            L: Listener<E>,
        {
        }
        _assert_listener::<ModelCreated<obs_user::Entity>, TestObserver>();
        _assert_listener::<ModelDeleted<obs_user::Entity>, TestObserver>();
    }

    #[test]
    #[serial_test::serial]
    fn test_observer_observe_method_registers_listeners() {
        EventService::clear_all_listeners();

        struct TestObserver2;

        #[observer(ObsUser)]
        impl TestObserver2 {
            async fn created(&self, _model: obs_user::Model) {}

            async fn updated(&self, _model: obs_user::Model) {}
        }

        TestObserver2::observe();

        assert!(EventService::has_listeners::<ModelCreated<obs_user::Entity>>());
        assert!(EventService::has_listeners::<ModelUpdated<obs_user::Entity>>());

        // Should NOT have listener for deleted (no deleted method defined)
        assert!(!EventService::has_listeners::<ModelDeleted<obs_user::Entity>>());

        EventService::clear_all_listeners();
    }

    #[tokio::test]
    #[serial_test::serial]
    async fn test_observer_receives_created_event() {
        EventService::clear_all_listeners();
        static CALLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

        struct CreatedObserver;

        #[observer(ObsUser)]
        impl CreatedObserver {
            async fn created(&self, _model: obs_user::Model) {
                CALLED.store(true, std::sync::atomic::Ordering::SeqCst);
            }
        }

        CreatedObserver::observe();
        assert!(EventService::has_listeners::<ModelCreated<obs_user::Entity>>());

        EventService::dispatch(ModelCreated::<obs_user::Entity>(obs_user::Model {
            id: 1,
            name: "test".into(),
        }))
        .await;

        assert!(CALLED.load(std::sync::atomic::Ordering::SeqCst));
        EventService::clear_listeners::<ModelCreated<obs_user::Entity>>();
    }

    #[tokio::test]
    #[serial_test::serial]
    async fn test_observer_receives_deleted_event() {
        EventService::clear_all_listeners();
        static HANDLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

        struct DeletedObserver;

        #[observer(ObsUser)]
        impl DeletedObserver {
            async fn deleted(&self, _model: obs_user::Model) {
                HANDLED.store(true, std::sync::atomic::Ordering::SeqCst);
            }
        }

        DeletedObserver::observe();
        assert!(EventService::has_listeners::<ModelDeleted<obs_user::Entity>>());

        EventService::dispatch(ModelDeleted::<obs_user::Entity>(obs_user::Model {
            id: 42,
            name: "deleted-user".into(),
        }))
        .await;

        assert!(HANDLED.load(std::sync::atomic::Ordering::SeqCst));
        EventService::clear_listeners::<ModelDeleted<obs_user::Entity>>();
    }

    #[test]
    fn test_observer_macro_handles_all_hook_methods() {
        #[allow(dead_code)]
        struct FullObserver;

        // All five hooks — should compile and generate all five listener impls
        #[observer(ObsUser)]
        #[allow(dead_code)]
        impl FullObserver {
            async fn created(&self, _model: obs_user::Model) {}
            async fn updated(&self, _model: obs_user::Model) {}
            async fn deleted(&self, _model: obs_user::Model) {}
            async fn saved(&self, _model: obs_user::Model) {}
            async fn retrieved(&self, _model: obs_user::Model) {}
        }

        fn _assert_created()
        where
            FullObserver: Listener<ModelCreated<obs_user::Entity>>,
        {
        }
        fn _assert_updated()
        where
            FullObserver: Listener<ModelUpdated<obs_user::Entity>>,
        {
        }
        fn _assert_deleted()
        where
            FullObserver: Listener<ModelDeleted<obs_user::Entity>>,
        {
        }
        fn _assert_saved()
        where
            FullObserver: Listener<ModelSaved<obs_user::Entity>>,
        {
        }
        fn _assert_retrieved()
        where
            FullObserver: Listener<ModelRetrieved<obs_user::Entity>>,
        {
        }
    }
}