use std::{fmt, sync::Arc};
use async_trait::async_trait;
use thiserror::Error;
use crate::result::{BoxError, ClassifyError, ErrorKind};
use super::DomainEvent;
use super::model::normalize_field;
#[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<Vec<Arc<dyn DomainEventHandler>>>,
failure_policy: DomainEventFailurePolicy,
}
impl DomainEventDispatcher {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[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 {
Arc::make_mut(&mut self.handlers).push(handler);
self
}
#[must_use]
pub fn with_handlers(
mut self,
handlers: impl IntoIterator<Item = Arc<dyn DomainEventHandler>>,
) -> Self {
self.handlers = Arc::new(handlers.into_iter().collect());
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);
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) -> crate::result::ErrorCode {
crate::result::ErrorCode::internal(match self {
Self::HandlerFailed { .. } => "domain_event_handler_failed",
})
}
}
fn normalize_failure_field(value: impl Into<String>, fallback: &'static str) -> String {
normalize_field(value).unwrap_or_else(|| fallback.to_owned())
}