use std::fmt;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::{Map, Value};
use thiserror::Error;
use crate::result::{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
}
}
#[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) -> crate::result::ErrorCode {
crate::result::ErrorCode::internal(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(())
}
pub(super) 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 truncate_event_field(value: &mut String) {
if value.len() <= MAX_EVENT_FIELD_LENGTH {
return;
}
value.truncate(value.floor_char_boundary(MAX_EVENT_FIELD_LENGTH));
}