footing 0.1.0

Feature-gated foundations for Rust backend services
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
//! In-process domain event dispatch.
//!
//! Applications use this module to publish domain events without coupling the
//! domain service to the side effects that may run afterwards. Handlers are
//! explicit, ordered, and local to the process; distributed delivery should use
//! an application outbox.
//!
//! ```rust
//! use footing::event::{DomainEvent, DomainEventDispatcher};
//!
//! # async fn example() -> Result<(), footing::event::DomainEventError> {
//! let dispatcher = DomainEventDispatcher::new();
//! let event = DomainEvent::builder("user.created")?
//!     .subject("usr_01")
//!     .metadata_value("source", "admin")
//!     .build();
//!
//! dispatcher.publish(&event).await.unwrap();
//! # Ok(())
//! # }
//! ```
use std::{borrow::Cow, fmt, sync::Arc};

use async_trait::async_trait;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::{Map, Value};
use thiserror::Error;

use crate::result::{BoxError, ClassifyError, ErrorKind};

/// Maximum supported event name length.
pub const MAX_EVENT_NAME_LENGTH: usize = 128;
/// Maximum supported event field length.
pub const MAX_EVENT_FIELD_LENGTH: usize = 512;

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
/// Represents domain event name.
pub struct DomainEventName(String);

impl DomainEventName {
    /// Creates a new instance.
    pub fn new(value: impl Into<String>) -> Result<Self, DomainEventError> {
        let value = value.into().trim().to_owned();
        validate_event_name(&value)?;
        Ok(Self(value))
    }

    #[must_use]
    /// Returns this value as str.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    #[must_use]
    /// Consumes this value and returns string.
    pub fn into_string(self) -> String {
        self.0
    }
}

impl fmt::Display for DomainEventName {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl TryFrom<String> for DomainEventName {
    type Error = DomainEventError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

impl TryFrom<&str> for DomainEventName {
    type Error = DomainEventError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

impl<'de> Deserialize<'de> for DomainEventName {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Self::new(value).map_err(serde::de::Error::custom)
    }
}

#[derive(Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(try_from = "DomainEventWire")]
/// Represents domain event.
pub struct DomainEvent {
    name: DomainEventName,
    #[serde(skip_serializing_if = "Option::is_none")]
    subject: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    actor: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    idempotency_key: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    correlation_id: Option<String>,
    #[serde(default, skip_serializing_if = "Map::is_empty")]
    metadata: Map<String, Value>,
}

impl fmt::Debug for DomainEvent {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("DomainEvent")
            .field("name", &self.name)
            .field("subject", &self.subject.as_ref().map(|_| "[REDACTED]"))
            .field("actor", &self.actor.as_ref().map(|_| "[REDACTED]"))
            .field(
                "idempotency_key",
                &self.idempotency_key.as_ref().map(|_| "[REDACTED]"),
            )
            .field(
                "correlation_id",
                &self.correlation_id.as_ref().map(|_| "[REDACTED]"),
            )
            .field("metadata", &"[REDACTED]")
            .field("metadata_fields", &self.metadata.len())
            .finish()
    }
}

impl DomainEvent {
    /// Creates builder.
    pub fn builder(name: impl Into<String>) -> Result<DomainEventBuilder, DomainEventError> {
        DomainEventBuilder::new(name)
    }

    /// Creates a new instance.
    pub fn new(name: impl Into<String>) -> Result<Self, DomainEventError> {
        Ok(Self::builder(name)?.build())
    }

    #[must_use]
    /// Returns the name.
    pub fn name(&self) -> &DomainEventName {
        &self.name
    }

    #[must_use]
    /// Returns the subject.
    pub fn subject(&self) -> Option<&str> {
        self.subject.as_deref()
    }

    #[must_use]
    /// Returns the actor.
    pub fn actor(&self) -> Option<&str> {
        self.actor.as_deref()
    }

    #[must_use]
    /// Returns the idempotency key.
    pub fn idempotency_key(&self) -> Option<&str> {
        self.idempotency_key.as_deref()
    }

    #[must_use]
    /// Returns the correlation identifier.
    pub fn correlation_id(&self) -> Option<&str> {
        self.correlation_id.as_deref()
    }

    #[must_use]
    /// Returns the metadata.
    pub const fn metadata(&self) -> &Map<String, Value> {
        &self.metadata
    }
}

#[derive(Deserialize)]
struct DomainEventWire {
    name: DomainEventName,
    #[serde(default)]
    subject: Option<String>,
    #[serde(default)]
    actor: Option<String>,
    #[serde(default)]
    idempotency_key: Option<String>,
    #[serde(default)]
    correlation_id: Option<String>,
    #[serde(default)]
    metadata: Map<String, Value>,
}

impl TryFrom<DomainEventWire> for DomainEvent {
    type Error = DomainEventError;

    fn try_from(value: DomainEventWire) -> Result<Self, Self::Error> {
        Ok(Self {
            name: value.name,
            subject: value.subject.and_then(normalize_field),
            actor: value.actor.and_then(normalize_field),
            idempotency_key: value.idempotency_key.and_then(normalize_field),
            correlation_id: value.correlation_id.and_then(normalize_field),
            metadata: normalize_metadata(value.metadata),
        })
    }
}

#[derive(Debug, Clone)]
/// Builder for constructing domain event.
pub struct DomainEventBuilder {
    event: DomainEvent,
}

impl DomainEventBuilder {
    /// Creates a new instance.
    pub fn new(name: impl Into<String>) -> Result<Self, DomainEventError> {
        Ok(Self {
            event: DomainEvent {
                name: DomainEventName::new(name)?,
                subject: None,
                actor: None,
                idempotency_key: None,
                correlation_id: None,
                metadata: Map::new(),
            },
        })
    }

    #[must_use]
    /// Returns the subject.
    pub fn subject(mut self, subject: impl Into<String>) -> Self {
        self.event.subject = normalize_field(subject);
        self
    }

    #[must_use]
    /// Returns the actor.
    pub fn actor(mut self, actor: impl Into<String>) -> Self {
        self.event.actor = normalize_field(actor);
        self
    }

    #[must_use]
    /// Returns the idempotency key.
    pub fn idempotency_key(mut self, idempotency_key: impl Into<String>) -> Self {
        self.event.idempotency_key = normalize_field(idempotency_key);
        self
    }

    #[must_use]
    /// Returns the correlation identifier.
    pub fn correlation_id(mut self, correlation_id: impl Into<String>) -> Self {
        self.event.correlation_id = normalize_field(correlation_id);
        self
    }

    #[must_use]
    /// Returns the metadata.
    pub fn metadata(mut self, metadata: Map<String, Value>) -> Self {
        self.event.metadata = normalize_metadata(metadata);
        self
    }

    #[must_use]
    /// Returns the metadata value.
    pub fn metadata_value(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
        let key = normalize_metadata_key(key);
        if !key.is_empty() {
            self.event.metadata.insert(key, value.into());
        }
        self
    }

    #[must_use]
    /// Builds the configured value.
    pub fn build(self) -> DomainEvent {
        self.event
    }
}

#[async_trait]
/// Defines the contract for domain event handler.
pub trait DomainEventHandler: Send + Sync + 'static {
    /// Returns the name.
    fn name(&self) -> &str;

    /// Handles one event.
    async fn handle(&self, event: &DomainEvent) -> Result<(), BoxError>;
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
/// Policy controlling domain event failure.
pub enum DomainEventFailurePolicy {
    #[default]
    /// Indicates continue.
    Continue,
    /// Indicates stop on first error.
    StopOnFirstError,
}

#[derive(Clone, Default)]
/// Represents domain event dispatcher.
pub struct DomainEventDispatcher {
    handlers: Arc<[Arc<dyn DomainEventHandler>]>,
    failure_policy: DomainEventFailurePolicy,
}

impl DomainEventDispatcher {
    #[must_use]
    /// Creates a new instance.
    pub fn new() -> Self {
        Self {
            handlers: Arc::from([]),
            failure_policy: DomainEventFailurePolicy::Continue,
        }
    }

    #[must_use]
    /// Configures failure policy and returns the updated value.
    pub fn with_failure_policy(mut self, failure_policy: DomainEventFailurePolicy) -> Self {
        self.failure_policy = failure_policy;
        self
    }

    #[must_use]
    /// Configures handler and returns the updated value.
    pub fn with_handler(mut self, handler: Arc<dyn DomainEventHandler>) -> Self {
        let mut handlers = self.handlers.iter().cloned().collect::<Vec<_>>();
        handlers.push(handler);
        self.handlers = Arc::from(handlers);
        self
    }

    #[must_use]
    /// Configures handlers and returns the updated value.
    pub fn with_handlers(
        mut self,
        handlers: impl IntoIterator<Item = Arc<dyn DomainEventHandler>>,
    ) -> Self {
        self.handlers = Arc::from(handlers.into_iter().collect::<Vec<_>>());
        self
    }

    #[must_use]
    /// Returns the handlers.
    pub fn handlers(&self) -> &[Arc<dyn DomainEventHandler>] {
        &self.handlers
    }

    #[must_use]
    /// Returns the failure policy.
    pub const fn failure_policy(&self) -> DomainEventFailurePolicy {
        self.failure_policy
    }

    /// Publishes an event to the registered handlers according to the failure policy.
    pub async fn publish(
        &self,
        event: &DomainEvent,
    ) -> Result<DomainEventDispatchSummary, DomainEventDispatchError> {
        let mut summary = DomainEventDispatchSummary::new(self.handlers.len());
        for handler in self.handlers.iter() {
            if let Err(error) = handler.handle(event).await {
                let failure = DomainEventDispatchFailure::new(handler.name(), error.to_string());
                summary.record_failure(failure.clone());
                tracing::warn!(
                    event = %event.name(),
                    handler = handler.name(),
                    "domain event handler failed"
                );
                if self.failure_policy == DomainEventFailurePolicy::StopOnFirstError {
                    return Err(DomainEventDispatchError::HandlerFailed {
                        event: event.name().to_string(),
                        handler: handler.name().to_owned(),
                        summary,
                        source: error,
                    });
                }
            } else {
                summary.record_success();
            }
        }
        Ok(summary)
    }

    /// Publishes an event and always returns the resulting dispatch summary.
    pub async fn publish_best_effort(&self, event: &DomainEvent) -> DomainEventDispatchSummary {
        match self.publish(event).await {
            Ok(summary) => summary,
            Err(error) => {
                tracing::warn!(%error, event = %event.name(), "domain event dispatch failed");
                error.into_summary()
            }
        }
    }
}

impl fmt::Debug for DomainEventDispatcher {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("DomainEventDispatcher")
            .field("handlers", &self.handlers.len())
            .field("failure_policy", &self.failure_policy)
            .finish()
    }
}

#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Represents domain event dispatch failure.
pub struct DomainEventDispatchFailure {
    handler: String,
    message: String,
}

impl fmt::Debug for DomainEventDispatchFailure {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("DomainEventDispatchFailure")
            .field("handler", &self.handler)
            .field("message", &"[REDACTED]")
            .finish()
    }
}

impl DomainEventDispatchFailure {
    #[must_use]
    /// Creates a new instance.
    pub fn new(handler: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            handler: normalize_failure_field(handler, "unknown"),
            message: normalize_failure_field(message, "handler failed"),
        }
    }

    #[must_use]
    /// Returns the handler.
    pub fn handler(&self) -> &str {
        &self.handler
    }

    #[must_use]
    /// Returns the message.
    pub fn message(&self) -> &str {
        &self.message
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
/// Summary of domain event dispatch.
pub struct DomainEventDispatchSummary {
    handlers: usize,
    succeeded: usize,
    failed: usize,
    failures: Vec<DomainEventDispatchFailure>,
}

impl DomainEventDispatchSummary {
    #[must_use]
    /// Creates a new instance.
    pub fn new(handlers: usize) -> Self {
        Self {
            handlers,
            succeeded: 0,
            failed: 0,
            failures: Vec::new(),
        }
    }

    #[must_use]
    /// Returns the handlers.
    pub const fn handlers(&self) -> usize {
        self.handlers
    }

    #[must_use]
    /// Returns the succeeded.
    pub const fn succeeded(&self) -> usize {
        self.succeeded
    }

    #[must_use]
    /// Returns the failed.
    pub const fn failed(&self) -> usize {
        self.failed
    }

    #[must_use]
    /// Returns the failures.
    pub fn failures(&self) -> &[DomainEventDispatchFailure] {
        &self.failures
    }

    fn record_success(&mut self) {
        self.succeeded = self.succeeded.saturating_add(1);
    }

    fn record_failure(&mut self, failure: DomainEventDispatchFailure) {
        self.failed = self.failed.saturating_add(1);
        self.failures.push(failure);
    }
}

#[derive(Error)]
#[non_exhaustive]
/// Errors that can occur while handling domain event dispatch.
pub enum DomainEventDispatchError {
    #[error("domain event handler {handler} failed for {event}")]
    /// Indicates handler failed.
    HandlerFailed {
        /// The event value.
        event: String,
        /// The handler value.
        handler: String,
        /// The summary value.
        summary: DomainEventDispatchSummary,
        #[source]
        /// The source value.
        source: BoxError,
    },
}

impl fmt::Debug for DomainEventDispatchError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::HandlerFailed {
                event,
                handler,
                summary,
                source: _,
            } => formatter
                .debug_struct("DomainEventDispatchError::HandlerFailed")
                .field("event", event)
                .field("handler", handler)
                .field("summary", summary)
                .field("source", &"[REDACTED]")
                .finish(),
        }
    }
}

impl DomainEventDispatchError {
    #[must_use]
    /// Returns the summary.
    pub const fn summary(&self) -> &DomainEventDispatchSummary {
        match self {
            Self::HandlerFailed { summary, .. } => summary,
        }
    }

    #[must_use]
    /// Consumes this value and returns summary.
    pub fn into_summary(self) -> DomainEventDispatchSummary {
        match self {
            Self::HandlerFailed { summary, .. } => summary,
        }
    }
}

impl ClassifyError for DomainEventDispatchError {
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::HandlerFailed { .. } => ErrorKind::Internal,
        }
    }

    fn error_code(&self) -> Cow<'static, str> {
        Cow::Borrowed(match self {
            Self::HandlerFailed { .. } => "domain_event_handler_failed",
        })
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
/// Errors that can occur while handling domain event.
pub enum DomainEventError {
    #[error("domain event name must not be empty")]
    /// The name is empty.
    EmptyName,
    #[error("domain event name must be less than or equal to {max} bytes")]
    /// The name exceeds the supported length.
    NameTooLong {
        #[doc = "The configured upper bound."]
        max: usize,
    },
    #[error("domain event name contains unsupported characters")]
    /// The name is invalid.
    InvalidName,
}

impl ClassifyError for DomainEventError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Validation
    }

    fn error_code(&self) -> Cow<'static, str> {
        Cow::Borrowed(match self {
            Self::EmptyName => "domain_event_empty_name",
            Self::NameTooLong { .. } => "domain_event_name_too_long",
            Self::InvalidName => "domain_event_invalid_name",
        })
    }
}

fn validate_event_name(value: &str) -> Result<(), DomainEventError> {
    if value.is_empty() {
        return Err(DomainEventError::EmptyName);
    }
    if value.len() > MAX_EVENT_NAME_LENGTH {
        return Err(DomainEventError::NameTooLong {
            max: MAX_EVENT_NAME_LENGTH,
        });
    }
    if !value
        .bytes()
        .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'.')
    {
        return Err(DomainEventError::InvalidName);
    }
    Ok(())
}

fn normalize_field(value: impl Into<String>) -> Option<String> {
    let mut value = value
        .into()
        .trim()
        .chars()
        .filter(|character| !character.is_control())
        .collect::<String>();
    if value.is_empty() {
        return None;
    }
    truncate_event_field(&mut value);
    Some(value)
}

fn normalize_metadata(metadata: Map<String, Value>) -> Map<String, Value> {
    metadata
        .into_iter()
        .filter_map(|(key, value)| {
            let key = normalize_metadata_key(key);
            (!key.is_empty()).then_some((key, value))
        })
        .collect()
}

fn normalize_metadata_key(value: impl Into<String>) -> String {
    let mut value = value.into().trim().to_ascii_lowercase();
    if value.is_empty()
        || !value.chars().all(|character| {
            character.is_ascii_lowercase()
                || character.is_ascii_digit()
                || matches!(character, '_' | '.' | '-')
        })
    {
        return String::new();
    }
    truncate_event_field(&mut value);
    value
}

fn normalize_failure_field(value: impl Into<String>, fallback: &'static str) -> String {
    let value = normalize_field(value).unwrap_or_else(|| fallback.to_owned());
    if value.is_empty() {
        fallback.to_owned()
    } else {
        value
    }
}

fn truncate_event_field(value: &mut String) {
    if value.len() <= MAX_EVENT_FIELD_LENGTH {
        return;
    }

    value.truncate(MAX_EVENT_FIELD_LENGTH);
    while !value.is_char_boundary(value.len()) {
        value.pop();
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{Arc, Mutex};

    use async_trait::async_trait;

    use super::{
        DomainEvent, DomainEventDispatchError, DomainEventDispatcher, DomainEventFailurePolicy,
        DomainEventHandler, DomainEventName,
    };
    use crate::result::BoxError;

    #[test]
    fn validates_event_names() {
        assert!(DomainEventName::new("user.created").is_ok());
        assert!(DomainEventName::new("UserCreated").is_err());
        assert!(DomainEventName::new("user-created").is_err());
    }

    #[test]
    fn builder_normalizes_optional_fields_and_metadata() {
        let event = DomainEvent::builder("user.created")
            .expect("event should build")
            .subject(" usr_\n01 ")
            .actor(" admin ")
            .metadata_value(" source ", "console")
            .metadata_value("Request-ID", "req_01")
            .metadata_value("bad/key", "ignored")
            .build();

        assert_eq!(event.name().as_str(), "user.created");
        assert_eq!(event.subject(), Some("usr_01"));
        assert_eq!(event.actor(), Some("admin"));
        assert_eq!(event.metadata()["source"], "console");
        assert_eq!(event.metadata()["request-id"], "req_01");
        assert!(!event.metadata().contains_key("bad/key"));
    }

    #[test]
    fn domain_event_debug_redacts_identifiers_and_metadata_without_changing_wire_data() {
        let subject = "private-subject";
        let actor = "private-actor";
        let idempotency_key = "private-idempotency-key";
        let correlation_id = "private-correlation-id";
        let metadata_value = "private-metadata-value";
        let event = DomainEvent::builder("user.created")
            .expect("event should build")
            .subject(subject)
            .actor(actor)
            .idempotency_key(idempotency_key)
            .correlation_id(correlation_id)
            .metadata_value("credential", metadata_value)
            .build();

        let debug = format!("{event:?}");
        assert!(debug.contains("[REDACTED]"));
        for sensitive in [
            subject,
            actor,
            idempotency_key,
            correlation_id,
            metadata_value,
        ] {
            assert!(!debug.contains(sensitive));
        }

        let wire = serde_json::to_value(event).expect("event should serialize");
        assert_eq!(wire["subject"], subject);
        assert_eq!(wire["actor"], actor);
        assert_eq!(wire["idempotency_key"], idempotency_key);
        assert_eq!(wire["correlation_id"], correlation_id);
        assert_eq!(wire["metadata"]["credential"], metadata_value);
    }

    #[test]
    fn builder_normalizes_bulk_metadata_like_single_metadata_values() {
        let mut metadata = serde_json::Map::new();
        metadata.insert(" Request-ID ".to_owned(), "req_01".into());
        metadata.insert("bad/key".to_owned(), "ignored".into());
        metadata.insert("".to_owned(), "ignored".into());

        let event = DomainEvent::builder("user.created")
            .expect("event should build")
            .metadata(metadata)
            .build();

        assert_eq!(event.metadata()["request-id"], "req_01");
        assert_eq!(event.metadata().len(), 1);
    }

    #[test]
    fn deserialization_validates_name_and_normalizes_fields() {
        let value = serde_json::json!({
            "name": "user.created",
            "subject": " usr_\n01 ",
            "actor": " admin ",
            "metadata": {
                " Request-ID ": "req_01",
                "bad/key": "ignored"
            }
        });
        let event: DomainEvent =
            serde_json::from_value(value).expect("valid event JSON should deserialize");

        assert_eq!(event.name().as_str(), "user.created");
        assert_eq!(event.subject(), Some("usr_01"));
        assert_eq!(event.actor(), Some("admin"));
        assert_eq!(event.metadata()["request-id"], "req_01");
        assert_eq!(event.metadata().len(), 1);

        assert!(
            serde_json::from_value::<DomainEventName>(serde_json::json!("UserCreated")).is_err()
        );
        assert!(
            serde_json::from_value::<DomainEvent>(serde_json::json!({ "name": "UserCreated" }))
                .is_err()
        );
    }

    #[tokio::test]
    async fn dispatcher_invokes_handlers_in_order() {
        let seen = Arc::new(Mutex::new(Vec::new()));
        let dispatcher = DomainEventDispatcher::new()
            .with_handler(Arc::new(RecordingHandler::new("first", Arc::clone(&seen))))
            .with_handler(Arc::new(RecordingHandler::new("second", Arc::clone(&seen))));
        let event = DomainEvent::new("user.created").expect("event should build");

        let summary = dispatcher
            .publish(&event)
            .await
            .expect("dispatch should succeed");

        assert_eq!(summary.handlers(), 2);
        assert_eq!(summary.succeeded(), 2);
        assert_eq!(
            &*seen.lock().expect("seen lock should not poison"),
            &["first", "second"]
        );
    }

    #[tokio::test]
    async fn dispatcher_can_stop_on_first_error() {
        let dispatcher = DomainEventDispatcher::new()
            .with_failure_policy(DomainEventFailurePolicy::StopOnFirstError)
            .with_handler(Arc::new(FailingHandler));
        let event = DomainEvent::new("user.created").expect("event should build");

        let error = dispatcher
            .publish(&event)
            .await
            .expect_err("dispatch should fail");

        assert!(matches!(
            error,
            DomainEventDispatchError::HandlerFailed { .. }
        ));
        assert_eq!(error.summary().failed(), 1);
        assert_eq!(error.summary().failures()[0].handler(), "failing");
        let debug = format!("{error:?}");
        assert!(debug.contains("[REDACTED]"));
        assert!(!debug.contains("handler failed"));
    }

    #[tokio::test]
    async fn dispatcher_records_failure_details_when_continuing() {
        let seen = Arc::new(Mutex::new(Vec::new()));
        let dispatcher = DomainEventDispatcher::new()
            .with_handler(Arc::new(FailingHandler))
            .with_handler(Arc::new(RecordingHandler::new("second", Arc::clone(&seen))));
        let event = DomainEvent::new("user.created").expect("event should build");

        let summary = dispatcher
            .publish(&event)
            .await
            .expect("dispatch should continue");

        assert_eq!(summary.handlers(), 2);
        assert_eq!(summary.succeeded(), 1);
        assert_eq!(summary.failed(), 1);
        assert_eq!(summary.failures()[0].handler(), "failing");
        assert!(summary.failures()[0].message().contains("handler failed"));
        assert!(!format!("{summary:?}").contains("handler failed"));
        assert_eq!(
            &*seen.lock().expect("seen lock should not poison"),
            &["second"]
        );
    }

    struct RecordingHandler {
        name: &'static str,
        seen: Arc<Mutex<Vec<&'static str>>>,
    }

    impl RecordingHandler {
        fn new(name: &'static str, seen: Arc<Mutex<Vec<&'static str>>>) -> Self {
            Self { name, seen }
        }
    }

    #[async_trait]
    impl DomainEventHandler for RecordingHandler {
        fn name(&self) -> &str {
            self.name
        }

        async fn handle(&self, _event: &DomainEvent) -> Result<(), BoxError> {
            self.seen
                .lock()
                .expect("seen lock should not poison")
                .push(self.name);
            Ok(())
        }
    }

    struct FailingHandler;

    #[async_trait]
    impl DomainEventHandler for FailingHandler {
        fn name(&self) -> &str {
            "failing"
        }

        async fn handle(&self, _event: &DomainEvent) -> Result<(), BoxError> {
            Err("handler failed".into())
        }
    }
}