footing 0.5.3

Feature-gated foundations for Rust backend services
Documentation
use std::{fmt, sync::Arc};

use async_trait::async_trait;
use thiserror::Error;

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

use super::{DomainEvent, MAX_EVENT_FIELD_LENGTH};

#[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<Vec<Arc<dyn DomainEventHandler>>>,
    failure_policy: DomainEventFailurePolicy,
}

impl DomainEventDispatcher {
    #[must_use]
    /// Creates a new instance.
    pub fn new() -> Self {
        Self::default()
    }

    #[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 {
        Arc::make_mut(&mut self.handlers).push(handler);
        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::new(handlers.into_iter().collect());
        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.failures.push(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.succeeded += 1;
            }
        }
        Ok(summary)
    }

    /// Publishes an event and always returns the resulting dispatch summary.
    ///
    /// The configured failure policy still applies: `StopOnFirstError` skips
    /// later handlers, and the returned summary retains the failure. Failed
    /// handlers are logged by [`Self::publish`].
    pub async fn publish_best_effort(&self, event: &DomainEvent) -> DomainEventDispatchSummary {
        self.publish(event)
            .await
            .unwrap_or_else(DomainEventDispatchError::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,
    failures: Vec<DomainEventDispatchFailure>,
}

impl DomainEventDispatchSummary {
    #[must_use]
    /// Creates a new instance.
    pub fn new(handlers: usize) -> Self {
        Self {
            handlers,
            succeeded: 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.failures.len()
    }

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

#[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) -> 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 {
    crate::text::normalize_message(value, MAX_EVENT_FIELD_LENGTH)
        .unwrap_or_else(|| fallback.to_owned())
}