evx 0.1.0

A type-safe event bus for domain events, CQRS, Redis Pub/Sub, and durable work queues
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
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
//! High-level typed event, request-response, and queued-command dispatch.

use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;

use serde_json::Value;

use crate::broker::{Broker, ErasedHandler, SubscriptionId};
use crate::error::EventError;
use crate::event::cloud::CloudEvent;
use crate::event::domain::{DomainEvent, QueuedCommand, RequestMessage};
use crate::event::scope::EventScope;
use crate::queue::{JobId, QueueBroker};

// ── Type aliases ──────────────────────────────────────────────────────

type TypedCommandFn = Arc<
    dyn Fn(Value) -> Pin<Box<dyn Future<Output = Result<Value, EventError>> + Send>> + Send + Sync,
>;

#[derive(Clone)]
struct TypedHandler {
    subscription_id: SubscriptionId,
    handler: TypedCommandFn,
}

// ── EventBus ──────────────────────────────────────────────────────────

/// Routes typed domain events and request-response messages through two
/// transport scopes.
///
/// [`EventScope::Process`] messages use `process_broker`, while
/// [`EventScope::App`] messages use `app_broker`. Evx creates CloudEvent
/// envelopes and erases handler types internally.
pub struct EventBus {
    process_broker: Arc<dyn Broker>,
    app_broker: Arc<dyn Broker>,
    queue_broker: Option<Arc<dyn QueueBroker>>,
    typed_handlers: Arc<std::sync::RwLock<HashMap<String, TypedHandler>>>,
    subscriptions: Arc<std::sync::RwLock<HashMap<SubscriptionId, EventScope>>>,
}

#[cfg(all(test, feature = "in-process"))]
mod tests {
    use super::*;
    use crate::broker::disruptor::InProcessBroker;
    use crate::{CommandMessage, DomainEvent, Message, QueuePolicy, QueuedCommand, QueuedJob};
    use async_trait::async_trait;
    use serde::{Deserialize, Serialize};
    use std::collections::VecDeque;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use tokio::sync::{Mutex, oneshot};

    #[derive(Debug, Clone, Serialize, Deserialize)]
    struct TestCommand {
        value: String,
    }

    impl Message for TestCommand {
        fn message_type() -> &'static str {
            "com.test.command"
        }

        fn source() -> &'static str {
            "/test"
        }

        fn scope() -> EventScope {
            EventScope::Process
        }
    }

    impl RequestMessage for TestCommand {
        type Response = TestResponse;
    }

    impl CommandMessage for TestCommand {}

    #[derive(Debug, Clone, Serialize, Deserialize)]
    struct TestEvent {
        value: String,
    }

    impl Message for TestEvent {
        fn message_type() -> &'static str {
            "com.test.event"
        }

        fn source() -> &'static str {
            "/test"
        }

        fn scope() -> EventScope {
            EventScope::Process
        }
    }

    impl DomainEvent for TestEvent {}

    #[derive(Debug, Clone, Serialize, Deserialize)]
    struct TestResponse {
        value: String,
    }

    impl Message for TestResponse {
        fn message_type() -> &'static str {
            "com.test.response"
        }

        fn source() -> &'static str {
            "/test"
        }

        fn scope() -> EventScope {
            EventScope::Process
        }
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    struct AppCommand {
        value: String,
    }

    impl Message for AppCommand {
        fn message_type() -> &'static str {
            "com.test.app-command"
        }

        fn source() -> &'static str {
            "/test"
        }

        fn scope() -> EventScope {
            EventScope::App
        }
    }

    impl RequestMessage for AppCommand {
        type Response = AppResponse;
    }

    impl CommandMessage for AppCommand {}

    #[derive(Debug, Clone, Serialize, Deserialize)]
    struct AppResponse {
        value: String,
    }

    impl Message for AppResponse {
        fn message_type() -> &'static str {
            "com.test.app-response"
        }

        fn source() -> &'static str {
            "/test"
        }

        fn scope() -> EventScope {
            EventScope::App
        }
    }

    #[derive(Default)]
    struct RecordingBroker {
        published: Mutex<Vec<CloudEvent>>,
    }

    #[async_trait]
    impl Broker for RecordingBroker {
        async fn publish(&self, event: CloudEvent) -> Result<(), EventError> {
            self.published.lock().await.push(event);
            Ok(())
        }

        async fn subscribe(
            &self,
            _event_type: &str,
            _handler: ErasedHandler,
        ) -> Result<SubscriptionId, EventError> {
            Ok(SubscriptionId::new())
        }

        async fn unsubscribe(&self, _id: SubscriptionId) -> Result<(), EventError> {
            Ok(())
        }

        async fn call(
            &self,
            _event: CloudEvent,
            _timeout: Duration,
        ) -> Result<CloudEvent, EventError> {
            Err(EventError::Publish("recording broker cannot call".into()))
        }

        async fn shutdown(&self) -> Result<(), EventError> {
            Ok(())
        }
    }

    fn test_bus() -> Arc<EventBus> {
        let runtime = tokio::runtime::Handle::current();
        Arc::new(EventBus::new(
            Arc::new(InProcessBroker::new(256, runtime.clone())),
            Arc::new(InProcessBroker::new(256, runtime)),
        ))
    }

    #[derive(Default)]
    struct TestQueueBroker {
        next_id: AtomicUsize,
        jobs: Mutex<VecDeque<QueuedJob>>,
        acked: Mutex<Vec<JobId>>,
        dead_lettered: AtomicUsize,
    }

    #[async_trait]
    impl QueueBroker for TestQueueBroker {
        async fn enqueue(
            &self,
            _queue: &str,
            event: CloudEvent,
            attempts: u32,
        ) -> Result<JobId, EventError> {
            let id = JobId(
                self.next_id
                    .fetch_add(1, Ordering::Relaxed)
                    .saturating_add(1)
                    .to_string(),
            );
            self.jobs.lock().await.push_back(QueuedJob {
                id: id.clone(),
                event,
                attempts,
            });
            Ok(id)
        }

        async fn read(
            &self,
            _queue: &str,
            _group: &str,
            _consumer: &str,
            count: usize,
            block_ms: u64,
        ) -> Result<Vec<QueuedJob>, EventError> {
            let mut jobs = self.jobs.lock().await;
            if jobs.is_empty() {
                drop(jobs);
                tokio::time::sleep(Duration::from_millis(block_ms.min(10))).await;
                return Ok(Vec::new());
            }

            Ok((0..count).filter_map(|_| jobs.pop_front()).collect())
        }

        async fn claim_stale(
            &self,
            _queue: &str,
            _group: &str,
            _consumer: &str,
            _count: usize,
            _min_idle_ms: u64,
        ) -> Result<Vec<QueuedJob>, EventError> {
            Ok(Vec::new())
        }

        async fn ack(&self, _queue: &str, _group: &str, id: &JobId) -> Result<(), EventError> {
            self.acked.lock().await.push(id.clone());
            Ok(())
        }

        async fn dead_letter(
            &self,
            _queue: &str,
            _event: CloudEvent,
            _attempts: u32,
            _error: String,
        ) -> Result<JobId, EventError> {
            self.dead_lettered.fetch_add(1, Ordering::Relaxed);
            Ok(JobId("dlq".to_string()))
        }
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    struct QueuedTestCommand {
        value: String,
    }

    impl Message for QueuedTestCommand {
        fn message_type() -> &'static str {
            "com.test.queued-command"
        }

        fn source() -> &'static str {
            "/test"
        }

        fn scope() -> EventScope {
            EventScope::App
        }
    }

    impl RequestMessage for QueuedTestCommand {
        type Response = TestResponse;
    }

    impl CommandMessage for QueuedTestCommand {}

    impl QueuedCommand for QueuedTestCommand {
        fn queue_policy() -> QueuePolicy {
            QueuePolicy {
                queue: "test.queue",
                consumer_group: "test-group",
                max_attempts: 2,
                max_in_flight: 1,
                block_ms: 10,
                claim_idle_ms: 100,
            }
        }
    }

    #[tokio::test]
    async fn duplicate_process_command_handler_registration_returns_error() {
        let bus = test_bus();
        bus.handle::<TestCommand, _, _>(|cmd| async move { Ok(TestResponse { value: cmd.value }) })
            .await
            .unwrap();

        let result = bus
            .handle::<TestCommand, _, _>(|cmd| async move { Ok(TestResponse { value: cmd.value }) })
            .await;

        assert!(matches!(result, Err(EventError::Subscription(_))));
    }

    #[tokio::test]
    async fn typed_process_call_obeys_timeout() {
        let bus = test_bus();
        bus.handle::<TestCommand, _, _>(|cmd| async move {
            tokio::time::sleep(Duration::from_millis(50)).await;
            Ok(TestResponse { value: cmd.value })
        })
        .await
        .unwrap();

        let result: Result<TestResponse, EventError> = bus
            .call(
                &TestCommand {
                    value: "slow".to_string(),
                },
                Duration::from_millis(5),
            )
            .await;

        assert!(matches!(result, Err(EventError::Timeout(_))));
    }

    #[tokio::test]
    async fn unsubscribe_stops_event_delivery() {
        let bus = test_bus();
        let calls = Arc::new(AtomicUsize::new(0));
        let subscription_id = bus
            .subscribe::<TestEvent, _, _>({
                let calls = Arc::clone(&calls);
                move |_event| {
                    let calls = Arc::clone(&calls);
                    async move {
                        calls.fetch_add(1, Ordering::SeqCst);
                        Ok(())
                    }
                }
            })
            .await
            .unwrap();

        bus.publish(&TestEvent {
            value: "before".to_string(),
        })
        .await
        .unwrap();
        tokio::time::sleep(Duration::from_millis(20)).await;
        assert_eq!(calls.load(Ordering::SeqCst), 1);

        bus.unsubscribe(subscription_id).await.unwrap();
        bus.publish(&TestEvent {
            value: "after".to_string(),
        })
        .await
        .unwrap();
        tokio::time::sleep(Duration::from_millis(20)).await;
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn unsubscribed_typed_handler_can_be_registered_again() {
        let bus = test_bus();
        let subscription_id = bus
            .handle::<TestCommand, _, _>(|command| async move {
                Ok(TestResponse {
                    value: command.value,
                })
            })
            .await
            .unwrap();
        bus.unsubscribe(subscription_id).await.unwrap();

        bus.handle::<TestCommand, _, _>(|command| async move {
            Ok(TestResponse {
                value: format!("{}-new", command.value),
            })
        })
        .await
        .unwrap();
        let response = bus
            .call(
                &TestCommand {
                    value: "handler".to_string(),
                },
                Duration::from_secs(1),
            )
            .await
            .unwrap();

        assert_eq!(response.value, "handler-new");
    }

    #[tokio::test]
    async fn app_command_response_is_published_to_app_scope() {
        let app_broker = Arc::new(RecordingBroker::default());
        let runtime = tokio::runtime::Handle::current();
        let bus = Arc::new(EventBus::new(
            Arc::new(InProcessBroker::new(256, runtime)),
            app_broker.clone(),
        ));
        let handler = EventBus::make_command_handler::<AppCommand, _, _>(
            Arc::clone(&bus),
            |command| async move {
                Ok(AppResponse {
                    value: command.value,
                })
            },
        );
        let mut request = CloudEvent::from_message(&AppCommand {
            value: "app".to_string(),
        })
        .unwrap();
        request
            .extensions
            .insert("reply_to".into(), Value::String("_reply.test".to_string()));
        request.extensions.insert(
            "correlationid".into(),
            Value::String("test-correlation".to_string()),
        );

        handler(request).await.unwrap();

        let published = app_broker.published.lock().await;
        assert_eq!(published.len(), 1);
        assert_eq!(published[0].scope, EventScope::App);
        assert_eq!(published[0].r#type, "_reply.test");
    }

    #[tokio::test]
    async fn queued_command_worker_consumes_and_acks_job() {
        let runtime = tokio::runtime::Handle::current();
        let queue = Arc::new(TestQueueBroker::default());
        let bus = Arc::new(EventBus::new_with_queue(
            Arc::new(InProcessBroker::new(256, runtime.clone())),
            Arc::new(InProcessBroker::new(256, runtime)),
            queue.clone(),
        ));

        bus.enqueue(&QueuedTestCommand {
            value: "queued".to_string(),
        })
        .await
        .unwrap();

        let (tx, rx) = oneshot::channel();
        let tx = Arc::new(Mutex::new(Some(tx)));
        let worker = bus
            .work::<QueuedTestCommand, _, _>("test-consumer", {
                let tx = Arc::clone(&tx);
                move |cmd| {
                    let tx = Arc::clone(&tx);
                    async move {
                        if let Some(tx) = tx.lock().await.take() {
                            let _ = tx.send(cmd.value.clone());
                        }
                        Ok(TestResponse { value: cmd.value })
                    }
                }
            })
            .await
            .unwrap();

        let received = tokio::time::timeout(Duration::from_millis(100), rx)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(received, "queued");

        for _ in 0..10 {
            if queue.acked.lock().await.len() == 1 {
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        assert_eq!(queue.acked.lock().await.len(), 1);
        worker.abort();
    }

    #[tokio::test]
    async fn queued_command_retries_then_dead_letters() {
        let runtime = tokio::runtime::Handle::current();
        let queue = Arc::new(TestQueueBroker::default());
        let bus = Arc::new(EventBus::new_with_queue(
            Arc::new(InProcessBroker::new(256, runtime.clone())),
            Arc::new(InProcessBroker::new(256, runtime)),
            queue.clone(),
        ));
        bus.enqueue(&QueuedTestCommand {
            value: "fails".to_string(),
        })
        .await
        .unwrap();

        let worker = bus
            .work::<QueuedTestCommand, _, _>("test-consumer", |_command| async move {
                Err(EventError::Publish("handler failed".to_string()))
            })
            .await
            .unwrap();

        for _ in 0..20 {
            if queue.dead_lettered.load(Ordering::Relaxed) == 1 {
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }

        assert_eq!(queue.dead_lettered.load(Ordering::Relaxed), 1);
        assert_eq!(queue.acked.lock().await.len(), 2);
        worker.abort();
    }
}

impl EventBus {
    /// Creates an event bus with process and application brokers.
    ///
    /// With the default features, [`crate::InProcessBroker`] is available for
    /// the process broker. Enable `redis` to use `RedisBroker` as the
    /// application broker.
    pub fn new(process_broker: Arc<dyn Broker>, app_broker: Arc<dyn Broker>) -> Self {
        Self {
            process_broker,
            app_broker,
            queue_broker: None,
            typed_handlers: Arc::new(std::sync::RwLock::new(HashMap::new())),
            subscriptions: Arc::new(std::sync::RwLock::new(HashMap::new())),
        }
    }

    /// Creates an event bus with an additional durable queue backend.
    pub fn new_with_queue(
        process_broker: Arc<dyn Broker>,
        app_broker: Arc<dyn Broker>,
        queue_broker: Arc<dyn QueueBroker>,
    ) -> Self {
        Self {
            process_broker,
            app_broker,
            queue_broker: Some(queue_broker),
            typed_handlers: Arc::new(std::sync::RwLock::new(HashMap::new())),
            subscriptions: Arc::new(std::sync::RwLock::new(HashMap::new())),
        }
    }

    // ── Public API ────────────────────────────────────────────────────

    /// Publishes a domain event without waiting for its subscribers.
    ///
    /// The message's [`EventScope`] selects the destination broker. A
    /// successful result means the broker accepted the event, not that every
    /// subscriber completed successfully.
    pub async fn publish<E: DomainEvent>(&self, event: &E) -> Result<(), EventError> {
        let mut cloud_event = CloudEvent::from_domain_event(event)?;
        cloud_event.span = Some(tracing::Span::current());
        self.publish_ce(cloud_event).await
    }

    /// Sends a request and waits for its typed response.
    ///
    /// Process-scoped requests use a direct typed handler when one is
    /// registered, avoiding a CloudEvent serialization round trip. Other
    /// requests use broker RPC with correlation metadata. Returns
    /// [`EventError::Timeout`] when `timeout` elapses.
    pub async fn call<Req: RequestMessage>(
        &self,
        cmd: &Req,
        timeout: Duration,
    ) -> Result<Req::Response, EventError> {
        // Process scope: try typed dispatch first (short-circuit)
        if Req::scope() == EventScope::Process {
            let cmd_data =
                serde_json::to_value(cmd).map_err(|e| EventError::Serialization(e.to_string()))?;
            if let Some(handler) = self.typed_handler(Req::message_type()) {
                let value = tokio::time::timeout(timeout, handler(cmd_data))
                    .await
                    .map_err(|_| EventError::Timeout("typed call timed out".into()))??;
                return serde_json::from_value(value)
                    .map_err(|e| EventError::Deserialization(e.to_string()));
            }
        }

        // Fallback: full CloudEvent RPC path
        let cloud_cmd = CloudEvent::from_message(cmd)?;
        let response_ce = self.call_ce(cloud_cmd, timeout).await?;
        response_ce.into_message::<Req::Response>()
    }

    /// Subscribes a fire-and-forget handler to a domain event type.
    ///
    /// The handler is registered only with the broker selected by `E::scope()`.
    /// Handler errors are logged by the broker and are not returned to the
    /// publisher. Use the returned [`SubscriptionId`] with
    /// [`Self::unsubscribe`].
    pub async fn subscribe<E, H, Fut>(&self, handler: H) -> Result<SubscriptionId, EventError>
    where
        E: DomainEvent,
        H: Fn(E) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<(), EventError>> + Send + 'static,
    {
        let event_type = E::message_type();
        let erased = Self::make_erased_handler(handler);
        self.subscribe_ce(event_type, E::scope(), erased).await
    }

    /// Registers the request handler used by [`Self::call`].
    ///
    /// Responses are correlated and routed through the same scope as the
    /// request. Process-scoped handlers also receive a direct typed-dispatch
    /// registration. Only one process-scoped handler may be active for a
    /// message type.
    pub async fn handle<Req, H, Fut>(
        self: &Arc<Self>,
        handler: H,
    ) -> Result<SubscriptionId, EventError>
    where
        Req: RequestMessage,
        H: Fn(Req) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Req::Response, EventError>> + Send + 'static,
    {
        let event_type = Req::message_type();
        let handler = Arc::new(handler);

        // Register typed handler for direct Process-scope dispatch
        let typed = if Req::scope() == EventScope::Process {
            let h = Arc::clone(&handler);
            let typed: TypedCommandFn = Arc::new(move |data: Value| {
                let h = Arc::clone(&h);
                Box::pin(async move {
                    let cmd: Req = serde_json::from_value(data)
                        .map_err(|e| EventError::Deserialization(e.to_string()))?;
                    let res = h(cmd).await?;
                    serde_json::to_value(res).map_err(|e| EventError::Serialization(e.to_string()))
                })
            });
            Some(typed)
        } else {
            None
        };

        let erased = Self::make_command_handler(self.clone(), move |cmd| {
            let handler = Arc::clone(&handler);
            async move { handler(cmd).await }
        });
        let subscription_id = self.subscribe_ce(event_type, Req::scope(), erased).await?;

        if let Some(typed) = typed
            && let Err(error) = self.register_typed_handler(event_type, subscription_id, typed)
        {
            let _ = self.unsubscribe(subscription_id).await;
            return Err(error);
        }

        Ok(subscription_id)
    }

    /// Shuts down both brokers and reports any shutdown failures.
    pub async fn shutdown(&self) -> Result<(), EventError> {
        let mut errors = Vec::new();
        if let Err(e) = self.process_broker.shutdown().await {
            errors.push(format!("process broker: {e}"));
        }
        if let Err(e) = self.app_broker.shutdown().await {
            errors.push(format!("app broker: {e}"));
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(EventError::Shutdown(errors.join("; ")))
        }
    }

    /// Enqueues a durable command according to its [`crate::QueuePolicy`].
    ///
    /// Returns an error if this bus was not created with [`Self::new_with_queue`].
    pub async fn enqueue<C: QueuedCommand>(&self, cmd: &C) -> Result<JobId, EventError> {
        let queue = self
            .queue_broker
            .as_ref()
            .ok_or_else(|| EventError::Publish("queue broker not configured".to_string()))?;
        let event = CloudEvent::from_message(cmd)?;
        queue.enqueue(C::queue_policy().queue, event, 0).await
    }

    /// Starts a background worker for a durable command type.
    ///
    /// The worker claims stale pending jobs before reading new jobs, retries
    /// handler failures according to the command's queue policy, and moves
    /// exhausted jobs to the dead-letter stream. Abort the returned task
    /// during application shutdown.
    pub async fn work<C, H, Fut>(
        &self,
        consumer_name: impl Into<String>,
        handler: H,
    ) -> Result<tokio::task::JoinHandle<()>, EventError>
    where
        C: QueuedCommand,
        H: Fn(C) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<C::Response, EventError>> + Send + 'static,
    {
        let queue =
            self.queue_broker.as_ref().cloned().ok_or_else(|| {
                EventError::Subscription("queue broker not configured".to_string())
            })?;
        let policy = C::queue_policy();
        let consumer_name = consumer_name.into();
        let handler = Arc::new(handler);

        Ok(tokio::spawn(async move {
            let semaphore = Arc::new(tokio::sync::Semaphore::new(policy.max_in_flight.max(1)));
            loop {
                let mut permits = Vec::with_capacity(policy.max_in_flight.max(1));
                let Ok(first_permit) = semaphore.clone().acquire_owned().await else {
                    return;
                };
                permits.push(first_permit);
                while permits.len() < policy.max_in_flight.max(1) {
                    let Ok(permit) = semaphore.clone().try_acquire_owned() else {
                        break;
                    };
                    permits.push(permit);
                }

                let jobs = match queue
                    .claim_stale(
                        policy.queue,
                        policy.consumer_group,
                        &consumer_name,
                        permits.len(),
                        policy.claim_idle_ms,
                    )
                    .await
                {
                    Ok(jobs) if !jobs.is_empty() => jobs,
                    Ok(_) => match queue
                        .read(
                            policy.queue,
                            policy.consumer_group,
                            &consumer_name,
                            permits.len(),
                            policy.block_ms,
                        )
                        .await
                    {
                        Ok(jobs) => jobs,
                        Err(error) => {
                            tracing::error!(error = %error, queue = policy.queue, "queue read failed");
                            tokio::time::sleep(Duration::from_secs(1)).await;
                            continue;
                        }
                    },
                    Err(error) => {
                        tracing::error!(error = %error, queue = policy.queue, "queue stale-claim failed");
                        tokio::time::sleep(Duration::from_secs(1)).await;
                        continue;
                    }
                };

                for (job, permit) in jobs.into_iter().zip(permits.drain(..)) {
                    let queue = Arc::clone(&queue);
                    let handler = Arc::clone(&handler);
                    let policy = policy.clone();
                    tokio::spawn(async move {
                        let _permit = permit;
                        let event_for_retry = job.event.clone();
                        let handler_result = async {
                            let cmd: C = job.event.into_message::<C>()?;
                            handler(cmd).await?;
                            Ok::<(), EventError>(())
                        }
                        .await;

                        match handler_result {
                            Ok(()) => {
                                if let Err(error) = queue
                                    .ack(policy.queue, policy.consumer_group, &job.id)
                                    .await
                                {
                                    tracing::error!(
                                        error = %error,
                                        queue = policy.queue,
                                        job_id = %job.id.0,
                                        "queue acknowledgement failed; job remains pending"
                                    );
                                }
                            }
                            Err(error) => {
                                let next_attempt = job.attempts.saturating_add(1);
                                let persisted = if next_attempt >= policy.max_attempts.max(1) {
                                    queue
                                        .dead_letter(
                                            policy.queue,
                                            event_for_retry,
                                            next_attempt,
                                            error.to_string(),
                                        )
                                        .await
                                        .map(|_| ())
                                } else {
                                    queue
                                        .enqueue(policy.queue, event_for_retry, next_attempt)
                                        .await
                                        .map(|_| ())
                                };

                                match persisted {
                                    Ok(()) => {
                                        if let Err(ack_error) = queue
                                            .ack(policy.queue, policy.consumer_group, &job.id)
                                            .await
                                        {
                                            tracing::error!(
                                                error = %ack_error,
                                                queue = policy.queue,
                                                job_id = %job.id.0,
                                                "failed to acknowledge replaced queue job"
                                            );
                                        }
                                    }
                                    Err(persist_error) => {
                                        tracing::error!(
                                            error = %persist_error,
                                            handler_error = %error,
                                            queue = policy.queue,
                                            job_id = %job.id.0,
                                            "failed to persist retry or dead letter; job remains pending"
                                        );
                                    }
                                }
                            }
                        }
                    });
                }
            }
        }))
    }

    // ── Private: CloudEvent-level dispatch ─────────────────────────────

    /// 按 scope 路由 CloudEvent 到对应 broker 发布。
    async fn publish_ce(&self, event: CloudEvent) -> Result<(), EventError> {
        match event.scope {
            EventScope::Process => self.process_broker.publish(event).await,
            EventScope::App => self.app_broker.publish(event).await,
        }
    }

    /// 订阅类型擦除 handler(同时注册到 process + app broker)。
    async fn subscribe_ce(
        &self,
        event_type: &str,
        scope: EventScope,
        handler: ErasedHandler,
    ) -> Result<SubscriptionId, EventError> {
        let id = match scope {
            EventScope::Process => self.process_broker.subscribe(event_type, handler).await?,
            EventScope::App => self.app_broker.subscribe(event_type, handler).await?,
        };
        self.subscriptions.write().unwrap().insert(id, scope);
        Ok(id)
    }

    /// Cancels an EventBus subscription and removes any associated typed
    /// command handler.
    pub async fn unsubscribe(&self, id: SubscriptionId) -> Result<(), EventError> {
        let scope = *self.subscriptions.read().unwrap().get(&id).ok_or_else(|| {
            EventError::Subscription(format!("unknown subscription id: {}", id.0))
        })?;

        match scope {
            EventScope::Process => self.process_broker.unsubscribe(id).await?,
            EventScope::App => self.app_broker.unsubscribe(id).await?,
        }

        self.subscriptions.write().unwrap().remove(&id);
        self.typed_handlers
            .write()
            .unwrap()
            .retain(|_, handler| handler.subscription_id != id);
        Ok(())
    }

    /// CloudEvent 级 RPC:按 scope 路由,返回响应 CloudEvent。
    async fn call_ce(
        &self,
        event: CloudEvent,
        timeout: Duration,
    ) -> Result<CloudEvent, EventError> {
        match event.scope {
            EventScope::Process => self.process_broker.call(event, timeout).await,
            EventScope::App => self.app_broker.call(event, timeout).await,
        }
    }

    // ── Private: typed dispatch ────────────────────────────────────────

    /// 直接 dispatch 到 typed handler(绕过 CloudEvent)。
    /// 返回 `None` 表示该事件类型无 typed handler 注册。
    fn typed_handler(&self, event_type: &str) -> Option<TypedCommandFn> {
        let handlers = self.typed_handlers.read().unwrap();
        handlers.get(event_type).map(|typed| typed.handler.clone())
    }

    /// 注册 typed command handler。
    fn register_typed_handler(
        &self,
        event_type: &str,
        subscription_id: SubscriptionId,
        handler: TypedCommandFn,
    ) -> Result<(), EventError> {
        let mut handlers = self.typed_handlers.write().unwrap();
        if handlers.contains_key(event_type) {
            return Err(EventError::Subscription(format!(
                "handler already registered for {event_type}"
            )));
        }
        handlers.insert(
            event_type.to_string(),
            TypedHandler {
                subscription_id,
                handler,
            },
        );
        Ok(())
    }

    // ── Private: handler constructors ──────────────────────────────────

    /// 从类型化 handler 构造类型擦除的 [`ErasedHandler`]。
    fn make_erased_handler<E, H, Fut>(handler: H) -> ErasedHandler
    where
        E: DomainEvent,
        H: Fn(E) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<(), EventError>> + Send + 'static,
    {
        let handler = Arc::new(handler);
        Arc::new(move |cloud_event: CloudEvent| {
            let handler = Arc::clone(&handler);
            Box::pin(async move {
                let typed: E = cloud_event.into_message::<E>()?;
                handler(typed).await
            })
        })
    }

    /// 从类型化命令 handler 构造类型擦除的 [`ErasedHandler`](含 RPC 响应路由)。
    fn make_command_handler<Req, H, Fut>(eventbus: Arc<EventBus>, handler: H) -> ErasedHandler
    where
        Req: RequestMessage,
        H: Fn(Req) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Req::Response, EventError>> + Send + 'static,
    {
        let handler = Arc::new(handler);
        Arc::new(move |request: CloudEvent| {
            let eventbus = Arc::clone(&eventbus);
            let handler = Arc::clone(&handler);
            Box::pin(async move {
                let request_scope = request.scope;
                let reply_to = request
                    .extensions
                    .get("reply_to")
                    .and_then(|v| v.as_str())
                    .map(String::from);
                let correlation_id = request
                    .extensions
                    .get("correlationid")
                    .and_then(|v| v.as_str())
                    .map(String::from);

                let cmd: Req = request.into_message::<Req>()?;
                let result = handler(cmd).await?;

                if let (Some(reply_to), Some(corr)) = (reply_to, correlation_id) {
                    let mut response = CloudEvent::from_message(&result)?;
                    response.r#type = reply_to;
                    response.scope = request_scope;
                    response
                        .extensions
                        .insert("correlationid".into(), Value::String(corr));
                    eventbus.publish_ce(response).await?;
                }
                Ok(())
            })
        })
    }
}