use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use super::{
DomainEvent, DomainEventDispatchError, DomainEventDispatcher, DomainEventError,
DomainEventFailurePolicy, DomainEventHandler, DomainEventName,
};
use crate::result::BoxError;
#[test]
fn event_identifiers_reject_lossy_inputs_in_builders_and_deserialization() {
type Setter = fn(DomainEvent, String) -> Result<DomainEvent, DomainEventError>;
let setters: [(&str, Setter); 4] = [
("subject", DomainEvent::with_subject),
("actor", DomainEvent::with_actor),
("idempotency_key", DomainEvent::with_idempotency_key),
("correlation_id", DomainEvent::with_correlation_id),
];
for (field, set) in setters {
for input in [
"".to_owned(),
" a".to_owned(),
"a ".to_owned(),
"a\nb".to_owned(),
"δΈ".repeat(171),
format!("{}a", "x".repeat(512)),
format!("{}b", "x".repeat(512)),
] {
let error = set(DomainEvent::new("test.event").unwrap(), input.clone()).unwrap_err();
assert!(
matches!(error, DomainEventError::InvalidField { field: actual } if actual == field)
);
let mut wire = serde_json::json!({"name": "test.event"});
wire[field] = input.into();
assert!(serde_json::from_value::<DomainEvent>(wire).is_err());
}
}
}
#[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 events_round_trip_optional_fields_and_json_metadata_in_binary_formats() {
let empty = DomainEvent::new("user.created").unwrap();
let populated = empty
.clone()
.with_subject("usr_01")
.unwrap()
.with_actor("admin")
.unwrap()
.with_idempotency_key("operation_01")
.unwrap()
.with_correlation_id("req_01")
.unwrap()
.with_metadata_value(
"data",
serde_json::json!({
"values": [null, true, 42, 2.5, "δΈζ\n\"\\"],
"nested": {"empty": []}
}),
)
.unwrap();
for event in [empty, populated] {
let bytes = postcard::to_allocvec(&event).unwrap();
assert_eq!(postcard::from_bytes::<DomainEvent>(&bytes).unwrap(), event);
let json = serde_json::to_value(&event).unwrap();
assert!(json["metadata"].is_object());
assert_eq!(serde_json::from_value::<DomainEvent>(json).unwrap(), event);
}
}
#[test]
fn event_identifiers_preserve_identity_at_the_size_boundary() {
for key in [
format!("{}a", "x".repeat(511)),
format!("{}b", "x".repeat(511)),
"π".repeat(128),
] {
let event = DomainEvent::new("user.created")
.unwrap()
.with_idempotency_key(&key)
.unwrap();
assert_eq!(event.idempotency_key(), Some(key.as_str()));
assert_eq!(
serde_json::from_str::<DomainEvent>(&serde_json::to_string(&event).unwrap()).unwrap(),
event
);
}
}
#[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::new("user.created")
.expect("event should build")
.with_subject(subject)
.unwrap()
.with_actor(actor)
.unwrap()
.with_idempotency_key(idempotency_key)
.unwrap()
.with_correlation_id(correlation_id)
.unwrap()
.with_metadata_value("credential", metadata_value)
.unwrap();
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 metadata_rejects_keys_that_would_be_dropped_or_collide() {
let event = DomainEvent::new("user.created").unwrap();
for key in [
"".to_owned(),
" Request-ID ".to_owned(),
"Request-ID".to_owned(),
"bad/key".to_owned(),
format!("{}a", "x".repeat(512)),
format!("{}b", "x".repeat(512)),
] {
let metadata = serde_json::Map::from_iter([(key.clone(), "value".into())]);
assert!(event.clone().with_metadata_value(key, "value").is_err());
assert!(event.clone().with_metadata(metadata.clone()).is_err());
let wire = serde_json::json!({"name": "user.created", "metadata": metadata});
assert!(serde_json::from_value::<DomainEvent>(wire).is_err());
}
let keys = [
format!("{}a", "x".repeat(511)),
format!("{}b", "x".repeat(511)),
];
let metadata = serde_json::Map::from_iter(keys.map(|key| (key, "value".into())));
assert_eq!(
event.with_metadata(metadata.clone()).unwrap().metadata(),
&metadata
);
}
#[test]
fn deserialization_preserves_valid_fields_and_rejects_invalid_names() {
let value = serde_json::json!({
"name": "user.created",
"subject": "usr_01",
"actor": "admin",
"metadata": {
"request-id": "req_01"
}
});
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())
}
}