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};
pub const MAX_EVENT_NAME_LENGTH: usize = 128;
pub const MAX_EVENT_FIELD_LENGTH: usize = 512;
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
pub struct DomainEventName(String);
impl DomainEventName {
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]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
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")]
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 {
pub fn builder(name: impl Into<String>) -> Result<DomainEventBuilder, DomainEventError> {
DomainEventBuilder::new(name)
}
pub fn new(name: impl Into<String>) -> Result<Self, DomainEventError> {
Ok(Self::builder(name)?.build())
}
#[must_use]
pub fn name(&self) -> &DomainEventName {
&self.name
}
#[must_use]
pub fn subject(&self) -> Option<&str> {
self.subject.as_deref()
}
#[must_use]
pub fn actor(&self) -> Option<&str> {
self.actor.as_deref()
}
#[must_use]
pub fn idempotency_key(&self) -> Option<&str> {
self.idempotency_key.as_deref()
}
#[must_use]
pub fn correlation_id(&self) -> Option<&str> {
self.correlation_id.as_deref()
}
#[must_use]
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)]
pub struct DomainEventBuilder {
event: DomainEvent,
}
impl DomainEventBuilder {
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]
pub fn subject(mut self, subject: impl Into<String>) -> Self {
self.event.subject = normalize_field(subject);
self
}
#[must_use]
pub fn actor(mut self, actor: impl Into<String>) -> Self {
self.event.actor = normalize_field(actor);
self
}
#[must_use]
pub fn idempotency_key(mut self, idempotency_key: impl Into<String>) -> Self {
self.event.idempotency_key = normalize_field(idempotency_key);
self
}
#[must_use]
pub fn correlation_id(mut self, correlation_id: impl Into<String>) -> Self {
self.event.correlation_id = normalize_field(correlation_id);
self
}
#[must_use]
pub fn metadata(mut self, metadata: Map<String, Value>) -> Self {
self.event.metadata = normalize_metadata(metadata);
self
}
#[must_use]
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]
pub fn build(self) -> DomainEvent {
self.event
}
}
#[async_trait]
pub trait DomainEventHandler: Send + Sync + 'static {
fn name(&self) -> &str;
async fn handle(&self, event: &DomainEvent) -> Result<(), BoxError>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum DomainEventFailurePolicy {
#[default]
Continue,
StopOnFirstError,
}
#[derive(Clone, Default)]
pub struct DomainEventDispatcher {
handlers: Arc<[Arc<dyn DomainEventHandler>]>,
failure_policy: DomainEventFailurePolicy,
}
impl DomainEventDispatcher {
#[must_use]
pub fn new() -> Self {
Self {
handlers: Arc::from([]),
failure_policy: DomainEventFailurePolicy::Continue,
}
}
#[must_use]
pub fn with_failure_policy(mut self, failure_policy: DomainEventFailurePolicy) -> Self {
self.failure_policy = failure_policy;
self
}
#[must_use]
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]
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]
pub fn handlers(&self) -> &[Arc<dyn DomainEventHandler>] {
&self.handlers
}
#[must_use]
pub const fn failure_policy(&self) -> DomainEventFailurePolicy {
self.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)
}
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]
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]
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]
pub fn handler(&self) -> &str {
&self.handler
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct DomainEventDispatchSummary {
handlers: usize,
succeeded: usize,
failed: usize,
failures: Vec<DomainEventDispatchFailure>,
}
impl DomainEventDispatchSummary {
#[must_use]
pub fn new(handlers: usize) -> Self {
Self {
handlers,
succeeded: 0,
failed: 0,
failures: Vec::new(),
}
}
#[must_use]
pub const fn handlers(&self) -> usize {
self.handlers
}
#[must_use]
pub const fn succeeded(&self) -> usize {
self.succeeded
}
#[must_use]
pub const fn failed(&self) -> usize {
self.failed
}
#[must_use]
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]
pub enum DomainEventDispatchError {
#[error("domain event handler {handler} failed for {event}")]
HandlerFailed {
event: String,
handler: String,
summary: DomainEventDispatchSummary,
#[source]
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]
pub const fn summary(&self) -> &DomainEventDispatchSummary {
match self {
Self::HandlerFailed { summary, .. } => summary,
}
}
#[must_use]
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]
pub enum DomainEventError {
#[error("domain event name must not be empty")]
EmptyName,
#[error("domain event name must be less than or equal to {max} bytes")]
NameTooLong {
#[doc = "The configured upper bound."]
max: usize,
},
#[error("domain event name contains unsupported characters")]
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())
}
}
}