angzarr-client 0.2.0

Ergonomic Rust client for Angzarr CQRS/ES framework
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
// tonic::Status is 176 bytes - acceptable for gRPC error handling
#![allow(clippy::result_large_err)]

//! Unified router for aggregates, sagas, process managers, and projectors.
//!
//! # Overview
//!
//! Two router types based on domain cardinality:
//!
//! - `SingleDomainRouter<S, Mode>`: For aggregates and sagas (one domain, set at construction)
//! - `Router<S, Mode>`: For PMs and projectors (multiple domains via fluent `.domain()`)
//!
//! # Example
//!
//! ```rust,ignore
//! // Aggregate (single domain — domain in constructor)
//! let router = SingleDomainRouter::aggregate("player", "player", PlayerHandler::new());
//!
//! // Saga (single domain — domain in constructor)
//! let router = SingleDomainRouter::saga("saga-order-fulfillment", "order", OrderHandler::new());
//!
//! // Process Manager (multi-domain — fluent .domain())
//! let router = Router::process_manager("pmg-hand-flow", "hand-flow", rebuild_pm_state)
//!     .domain("order", OrderPmHandler::new())
//!     .domain("inventory", InventoryPmHandler::new());
//!
//! // Projector (multi-domain — fluent .domain())
//! let router = Router::projector("prj-output")
//!     .domain("player", PlayerProjectorHandler::new())
//!     .domain("hand", HandProjectorHandler::new());
//! ```

mod cloudevents;
mod dispatch;
mod factory;
mod helpers;
mod saga_context;
mod state;
mod traits;
mod upcaster;

use std::collections::HashMap;
use std::marker::PhantomData;
use std::sync::Arc;

use prost_types::Any;
use tonic::Status;

use crate::proto::{
    business_response, event_page, BusinessResponse, ContextualCommand, Cover, EventBook,
    Notification, ProcessManagerHandleResponse, Projection, RejectionNotification,
    RevocationResponse, SagaResponse,
};

// Re-export public types
pub use helpers::{event_book_from, event_page, new_event_book, new_event_book_multi, pack_event};
pub use saga_context::SagaContext;
pub use state::{EventApplier, EventApplierHOF, StateFactory, StateRouter};
pub use traits::{
    CommandHandlerDomainHandler, CommandRejectedError, CommandResult, ProcessManagerDomainHandler,
    ProcessManagerResponse, ProjectorDomainHandler, RejectionHandlerResponse, SagaDomainHandler,
    SagaHandlerResponse, UnpackAny,
};
pub use upcaster::{BoxedUpcasterHandler, UpcasterHandler, UpcasterHandlerHOF, UpcasterMode, UpcasterRouter};

// Factory support for per-request handlers and HOF
pub use factory::{BoxedHandlerFactory, HandlerFactory, HandlerHOF};

// CloudEvents
pub use cloudevents::{CloudEventsHandler, CloudEventsProjector, CloudEventsRouter};

// Re-export macros (defined in dispatch module via #[macro_export])
pub use crate::dispatch_command;
pub use crate::dispatch_event;

// ============================================================================
// Mode Markers
// ============================================================================

/// Mode marker for command handler routers (commands → events).
pub struct CommandHandlerMode;

/// Mode marker for saga routers (events → commands, stateless).
pub struct SagaMode;

/// Mode marker for process manager routers (events → commands + PM events).
pub struct ProcessManagerMode;

/// Mode marker for projector routers (events → external output).
pub struct ProjectorMode;

// ============================================================================
// Handler Storage Types (static or factory)
// ============================================================================

/// Handler storage supporting both static handlers and factories.
enum HandlerStorage<H> {
    /// Static handler - shared across all requests.
    Static(H),
    /// Factory - creates fresh handler per-request.
    Factory(Arc<dyn Fn() -> H + Send + Sync>),
}

impl<H> HandlerStorage<H> {
    /// Get or create handler for this request.
    fn get(&self) -> HandlerRef<'_, H>
    where
        H: Clone,
    {
        match self {
            Self::Static(h) => HandlerRef::Borrowed(h),
            Self::Factory(f) => HandlerRef::Owned(f()),
        }
    }
}

/// Reference to a handler - either borrowed or owned.
enum HandlerRef<'a, H> {
    Borrowed(&'a H),
    Owned(H),
}

impl<'a, H> std::ops::Deref for HandlerRef<'a, H> {
    type Target = H;

    fn deref(&self) -> &Self::Target {
        match self {
            Self::Borrowed(h) => h,
            Self::Owned(h) => h,
        }
    }
}

// ============================================================================
// SingleDomainRouter — CommandHandler Mode
// ============================================================================

/// Router for command handler components (commands → events, single domain).
///
/// Domain is set at construction time. No `.domain()` method exists,
/// enforcing single-domain constraint at compile time.
///
/// # Factory Pattern (per-request handlers)
///
/// ```rust,ignore
/// let db_pool = Arc::new(DbPool::new());
/// let router = CommandHandlerRouter::with_factory(
///     "agg-player",
///     "player",
///     move || PlayerHandler::new(db_pool.clone())
/// );
/// ```
pub struct CommandHandlerRouter<S, H>
where
    H: CommandHandlerDomainHandler<State = S>,
{
    name: String,
    domain: String,
    storage: HandlerStorage<H>,
    _state: PhantomData<S>,
}

impl<S: Default + Send + Sync + 'static, H: CommandHandlerDomainHandler<State = S> + Clone>
    CommandHandlerRouter<S, H>
{
    /// Create a new command handler router with a static handler.
    ///
    /// Command handlers accept commands and emit events. Single domain enforced at construction.
    /// The handler is shared across all requests.
    pub fn new(name: impl Into<String>, domain: impl Into<String>, handler: H) -> Self {
        Self {
            name: name.into(),
            domain: domain.into(),
            storage: HandlerStorage::Static(handler),
            _state: PhantomData,
        }
    }

    /// Create a new command handler router with a factory.
    ///
    /// The factory is called per-request to create fresh handler instances.
    /// Use this for dependency injection.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let db_pool = Arc::new(DbPool::new());
    /// let router = CommandHandlerRouter::with_factory(
    ///     "agg-player",
    ///     "player",
    ///     move || PlayerHandler::new(db_pool.clone())
    /// );
    /// ```
    pub fn with_factory<F>(name: impl Into<String>, domain: impl Into<String>, factory: F) -> Self
    where
        F: Fn() -> H + Send + Sync + 'static,
    {
        Self {
            name: name.into(),
            domain: domain.into(),
            storage: HandlerStorage::Factory(Arc::new(factory)),
            _state: PhantomData,
        }
    }

    /// Get the router name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the domain.
    pub fn domain(&self) -> &str {
        &self.domain
    }

    /// Get command types from the handler.
    pub fn command_types(&self) -> Vec<String> {
        self.storage.get().command_types()
    }

    /// Get subscriptions for this command handler.
    pub fn subscriptions(&self) -> Vec<(String, Vec<String>)> {
        vec![(self.domain.clone(), self.command_types())]
    }

    /// Rebuild state from events using the handler's state router.
    pub fn rebuild_state(&self, events: &EventBook) -> S {
        self.storage.get().rebuild(events)
    }

    /// Dispatch a contextual command to the handler.
    pub fn dispatch(&self, cmd: &ContextualCommand) -> Result<BusinessResponse, Status> {
        let command_book = cmd
            .command
            .as_ref()
            .ok_or_else(|| Status::invalid_argument("Missing command book"))?;

        let command_page = command_book
            .pages
            .first()
            .ok_or_else(|| Status::invalid_argument("Missing command page"))?;

        let command_any = match &command_page.payload {
            Some(crate::proto::command_page::Payload::Command(c)) => c,
            _ => return Err(Status::invalid_argument("Missing command")),
        };

        let event_book = cmd
            .events
            .as_ref()
            .ok_or_else(|| Status::invalid_argument("Missing event book"))?;

        // Get handler (static or freshly created via factory)
        let handler = self.storage.get();

        // Rebuild state
        let state = handler.rebuild(event_book);
        let seq = crate::EventBookExt::next_sequence(event_book);

        let type_url = &command_any.type_url;

        // Check for Notification (rejection/compensation)
        if type_url.ends_with("Notification") {
            return dispatch_command_handler_notification(&*handler, command_any, &state);
        }

        // Execute handler
        let result_book = handler.handle(command_book, command_any, &state, seq)?;

        Ok(BusinessResponse {
            result: Some(business_response::Result::Events(result_book)),
        })
    }
}

/// Dispatch a Notification to the command handler's rejection handler.
fn dispatch_command_handler_notification<S: Default + 'static>(
    handler: &dyn CommandHandlerDomainHandler<State = S>,
    command_any: &Any,
    state: &S,
) -> Result<BusinessResponse, Status> {
    use prost::Message;

    let notification = Notification::decode(command_any.value.as_slice())
        .map_err(|e| Status::invalid_argument(format!("Failed to decode Notification: {}", e)))?;

    let rejection = notification
        .payload
        .as_ref()
        .map(|p| RejectionNotification::decode(p.value.as_slice()))
        .transpose()
        .map_err(|e| {
            Status::invalid_argument(format!("Failed to decode RejectionNotification: {}", e))
        })?
        .unwrap_or_default();

    let (domain, cmd_suffix) = extract_rejection_key(&rejection);

    let response = handler.on_rejected(&notification, state, &domain, &cmd_suffix)?;

    match (response.events, response.notification) {
        (Some(events), _) => Ok(BusinessResponse {
            result: Some(business_response::Result::Events(events)),
        }),
        (None, Some(notif)) => Ok(BusinessResponse {
            result: Some(business_response::Result::Notification(notif)),
        }),
        (None, None) => Ok(BusinessResponse {
            result: Some(business_response::Result::Revocation(RevocationResponse {
                emit_system_revocation: true,
                send_to_dead_letter_queue: false,
                escalate: false,
                abort: false,
                reason: format!(
                    "Handler returned empty response for {}/{}",
                    domain, cmd_suffix
                ),
            })),
        }),
    }
}

// ============================================================================
// SagaRouter — Saga Mode
// ============================================================================

/// Router for saga components (events → commands, single domain, stateless).
///
/// Domain is set at construction time. No `.domain()` method exists,
/// enforcing single-domain constraint at compile time.
///
/// # Factory Pattern (per-request handlers)
///
/// ```rust,ignore
/// let message_bus = Arc::new(MessageBus::new());
/// let router = SagaRouter::with_factory(
///     "saga-order-fulfillment",
///     "order",
///     move || OrderFulfillmentHandler::new(message_bus.clone())
/// );
/// ```
pub struct SagaRouter<H>
where
    H: SagaDomainHandler,
{
    name: String,
    domain: String,
    storage: HandlerStorage<H>,
}

impl<H: SagaDomainHandler + Clone> SagaRouter<H> {
    /// Create a new saga router with a static handler.
    ///
    /// Sagas translate events from one domain to commands for another.
    /// Single domain enforced at construction.
    pub fn new(name: impl Into<String>, domain: impl Into<String>, handler: H) -> Self {
        Self {
            name: name.into(),
            domain: domain.into(),
            storage: HandlerStorage::Static(handler),
        }
    }

    /// Create a new saga router with a factory.
    ///
    /// The factory is called per-request to create fresh handler instances.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let message_bus = Arc::new(MessageBus::new());
    /// let router = SagaRouter::with_factory(
    ///     "saga-order-fulfillment",
    ///     "order",
    ///     move || OrderFulfillmentHandler::new(message_bus.clone())
    /// );
    /// ```
    pub fn with_factory<F>(name: impl Into<String>, domain: impl Into<String>, factory: F) -> Self
    where
        F: Fn() -> H + Send + Sync + 'static,
    {
        Self {
            name: name.into(),
            domain: domain.into(),
            storage: HandlerStorage::Factory(Arc::new(factory)),
        }
    }

    /// Get the router name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the input domain.
    pub fn input_domain(&self) -> &str {
        &self.domain
    }

    /// Get event types from the handler.
    pub fn event_types(&self) -> Vec<String> {
        self.storage.get().event_types()
    }

    /// Get subscriptions for this saga.
    pub fn subscriptions(&self) -> Vec<(String, Vec<String>)> {
        vec![(self.domain.clone(), self.event_types())]
    }

    /// Dispatch an event to the saga handler.
    ///
    /// Sagas receive only source events — the framework handles sequence
    /// stamping and delivery retries.
    pub fn dispatch(&self, source: &EventBook) -> Result<SagaResponse, Status> {
        let event_page = source
            .pages
            .last()
            .ok_or_else(|| Status::invalid_argument("Source event book has no events"))?;

        let event_any = match &event_page.payload {
            Some(event_page::Payload::Event(e)) => e,
            _ => return Err(Status::invalid_argument("Missing event payload")),
        };

        // Get handler (static or freshly created via factory)
        let handler = self.storage.get();

        // Check for Notification (rejection/compensation)
        if event_any.type_url.ends_with("Notification") {
            return dispatch_saga_notification(&*handler, event_any);
        }

        let response = handler.handle(source, event_any)?;

        Ok(SagaResponse {
            commands: response.commands,
            events: response.events,
        })
    }
}

/// Dispatch a Notification to the saga's rejection handler.
fn dispatch_saga_notification<H: SagaDomainHandler>(
    handler: &H,
    event_any: &Any,
) -> Result<SagaResponse, Status> {
    use prost::Message;

    let notification = Notification::decode(event_any.value.as_slice())
        .map_err(|e| Status::invalid_argument(format!("Failed to decode Notification: {}", e)))?;

    let rejection = notification
        .payload
        .as_ref()
        .map(|p| RejectionNotification::decode(p.value.as_slice()))
        .transpose()
        .map_err(|e| {
            Status::invalid_argument(format!("Failed to decode RejectionNotification: {}", e))
        })?
        .unwrap_or_default();

    let (domain, cmd_suffix) = extract_rejection_key(&rejection);

    let response = handler.on_rejected(&notification, &domain, &cmd_suffix)?;

    // Sagas can only return events for compensation (no commands on rejection)
    Ok(SagaResponse {
        commands: vec![],
        events: response.events.into_iter().collect(),
    })
}

/// Extract domain and command suffix from a RejectionNotification.
fn extract_rejection_key(rejection: &RejectionNotification) -> (String, String) {
    if let Some(rejected) = &rejection.rejected_command {
        let domain = rejected
            .cover
            .as_ref()
            .map(|c| c.domain.clone())
            .unwrap_or_default();

        let cmd_suffix = rejected
            .pages
            .first()
            .and_then(|p| match &p.payload {
                Some(crate::proto::command_page::Payload::Command(c)) => Some(c),
                _ => None,
            })
            .map(|c| {
                c.type_url
                    .rsplit('/')
                    .next()
                    .unwrap_or(&c.type_url)
                    .to_string()
            })
            .unwrap_or_default();

        (domain, cmd_suffix)
    } else {
        (String::new(), String::new())
    }
}

// ============================================================================
// ProcessManagerRouter — Process Manager Mode
// ============================================================================

/// Router for process manager components (events → commands + PM events, multi-domain).
///
/// Domains are registered via fluent `.domain()` calls.
pub struct ProcessManagerRouter<S: Default + Send + Sync + 'static> {
    name: String,
    pm_domain: String,
    rebuild: Arc<dyn Fn(&EventBook) -> S + Send + Sync>,
    domains: HashMap<String, Arc<dyn ProcessManagerDomainHandler<S>>>,
}

impl<S: Default + Send + Sync + 'static> ProcessManagerRouter<S> {
    /// Create a new process manager router.
    ///
    /// Process managers correlate events across multiple domains and maintain
    /// their own state. The `pm_domain` is used for storing PM state.
    pub fn new<R>(name: impl Into<String>, pm_domain: impl Into<String>, rebuild: R) -> Self
    where
        R: Fn(&EventBook) -> S + Send + Sync + 'static,
    {
        Self {
            name: name.into(),
            pm_domain: pm_domain.into(),
            rebuild: Arc::new(rebuild),
            domains: HashMap::new(),
        }
    }

    /// Register a domain handler.
    ///
    /// Process managers can have multiple input domains.
    pub fn domain<H>(mut self, name: impl Into<String>, handler: H) -> Self
    where
        H: ProcessManagerDomainHandler<S> + 'static,
    {
        self.domains.insert(name.into(), Arc::new(handler));
        self
    }

    /// Get the router name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the PM's own domain (for state storage).
    pub fn pm_domain(&self) -> &str {
        &self.pm_domain
    }

    /// Get subscriptions (domain + event types) for this PM.
    pub fn subscriptions(&self) -> Vec<(String, Vec<String>)> {
        self.domains
            .iter()
            .map(|(domain, handler)| (domain.clone(), handler.event_types()))
            .collect()
    }

    /// Rebuild PM state from events.
    pub fn rebuild_state(&self, events: &EventBook) -> S {
        (self.rebuild)(events)
    }

    /// Get destinations needed for the given trigger and process state.
    pub fn prepare_destinations(
        &self,
        trigger: &Option<EventBook>,
        process_state: &Option<EventBook>,
    ) -> Vec<Cover> {
        let trigger = match trigger {
            Some(t) => t,
            None => return vec![],
        };

        let trigger_domain = trigger
            .cover
            .as_ref()
            .map(|c| c.domain.as_str())
            .unwrap_or("");

        let event_page = match trigger.pages.last() {
            Some(p) => p,
            None => return vec![],
        };

        let event_any = match &event_page.payload {
            Some(event_page::Payload::Event(e)) => e,
            _ => return vec![],
        };

        let state = match process_state {
            Some(ps) => self.rebuild_state(ps),
            None => S::default(),
        };

        self.domains
            .get(trigger_domain)
            .map(|handler| handler.prepare(trigger, &state, event_any))
            .unwrap_or_default()
    }

    /// Dispatch a trigger event to the appropriate handler.
    pub fn dispatch(
        &self,
        trigger: &EventBook,
        process_state: &EventBook,
        destinations: &[EventBook],
    ) -> Result<ProcessManagerHandleResponse, Status> {
        let trigger_domain = trigger
            .cover
            .as_ref()
            .map(|c| c.domain.as_str())
            .unwrap_or("");

        let handler = self.domains.get(trigger_domain).ok_or_else(|| {
            Status::unimplemented(format!("No handler for domain: {}", trigger_domain))
        })?;

        let event_page = trigger
            .pages
            .last()
            .ok_or_else(|| Status::invalid_argument("Trigger event book has no events"))?;

        let event_any = match &event_page.payload {
            Some(event_page::Payload::Event(e)) => e,
            _ => return Err(Status::invalid_argument("Missing event payload")),
        };

        let state = self.rebuild_state(process_state);

        // Check for Notification
        if event_any.type_url.ends_with("Notification") {
            return dispatch_pm_notification(handler.as_ref(), event_any, &state);
        }

        let response = handler.handle(trigger, &state, event_any, destinations)?;

        Ok(ProcessManagerHandleResponse {
            commands: response.commands,
            process_events: response.process_events,
            facts: response.facts,
        })
    }
}

/// Dispatch a Notification to the PM's rejection handler.
fn dispatch_pm_notification<S: Default>(
    handler: &dyn ProcessManagerDomainHandler<S>,
    event_any: &Any,
    state: &S,
) -> Result<ProcessManagerHandleResponse, Status> {
    use prost::Message;

    let notification = Notification::decode(event_any.value.as_slice())
        .map_err(|e| Status::invalid_argument(format!("Failed to decode Notification: {}", e)))?;

    let rejection = notification
        .payload
        .as_ref()
        .map(|p| RejectionNotification::decode(p.value.as_slice()))
        .transpose()
        .map_err(|e| {
            Status::invalid_argument(format!("Failed to decode RejectionNotification: {}", e))
        })?
        .unwrap_or_default();

    let (domain, cmd_suffix) = extract_rejection_key(&rejection);

    let response = handler.on_rejected(&notification, state, &domain, &cmd_suffix)?;

    Ok(ProcessManagerHandleResponse {
        commands: vec![],
        process_events: response.events,
        facts: vec![],
    })
}

// ============================================================================
// ProjectorRouter — Projector Mode
// ============================================================================

/// Router for projector components (events → external output, multi-domain).
///
/// Domains are registered via fluent `.domain()` calls.
pub struct ProjectorRouter {
    name: String,
    domains: HashMap<String, Arc<dyn ProjectorDomainHandler>>,
}

impl ProjectorRouter {
    /// Create a new projector router.
    ///
    /// Projectors consume events from multiple domains and produce external output.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            domains: HashMap::new(),
        }
    }

    /// Register a domain handler.
    ///
    /// Projectors can have multiple input domains.
    pub fn domain<H>(mut self, name: impl Into<String>, handler: H) -> Self
    where
        H: ProjectorDomainHandler + 'static,
    {
        self.domains.insert(name.into(), Arc::new(handler));
        self
    }

    /// Get the router name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get subscriptions (domain + event types) for this projector.
    pub fn subscriptions(&self) -> Vec<(String, Vec<String>)> {
        self.domains
            .iter()
            .map(|(domain, handler)| (domain.clone(), handler.event_types()))
            .collect()
    }

    /// Dispatch events to the appropriate handler.
    pub fn dispatch(&self, events: &EventBook) -> Result<Projection, Status> {
        let domain = events
            .cover
            .as_ref()
            .map(|c| c.domain.as_str())
            .unwrap_or("");

        let handler = self
            .domains
            .get(domain)
            .ok_or_else(|| Status::unimplemented(format!("No handler for domain: {}", domain)))?;

        handler
            .project(events)
            .map_err(|e| Status::internal(e.to_string()))
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    // Test mode markers exist
    #[test]
    fn mode_markers_are_zero_sized() {
        assert_eq!(std::mem::size_of::<CommandHandlerMode>(), 0);
        assert_eq!(std::mem::size_of::<SagaMode>(), 0);
        assert_eq!(std::mem::size_of::<ProcessManagerMode>(), 0);
        assert_eq!(std::mem::size_of::<ProjectorMode>(), 0);
    }

    // Test PM router creation
    #[test]
    fn pm_router_creation() {
        let router: ProcessManagerRouter<()> =
            ProcessManagerRouter::new("test-pm", "pm-domain", |_| ());
        assert_eq!(router.name(), "test-pm");
        assert_eq!(router.pm_domain(), "pm-domain");
    }

    // Test projector router creation
    #[test]
    fn projector_router_creation() {
        let router = ProjectorRouter::new("test-prj");
        assert_eq!(router.name(), "test-prj");
    }
}