use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EventEnvelope<T> {
pub event_id: Uuid,
pub aggregate_id: Uuid,
pub aggregate_type: String,
pub sequence: i64,
pub event_type: String,
pub event_version: i32,
pub payload: T,
pub metadata: EventMetadata,
pub occurred_at: DateTime<Utc>,
pub stored_at: Option<DateTime<Utc>>,
}
impl<T> EventEnvelope<T> {
pub fn new(
aggregate_id: Uuid,
aggregate_type: impl Into<String>,
sequence: i64,
event_type: impl Into<String>,
payload: T,
) -> Self {
Self {
event_id: Uuid::new_v4(),
aggregate_id,
aggregate_type: aggregate_type.into(),
sequence,
event_type: event_type.into(),
event_version: 1,
payload,
metadata: EventMetadata::default(),
occurred_at: Utc::now(),
stored_at: None,
}
}
pub fn with_correlation_id(mut self, id: Uuid) -> Self {
self.metadata.correlation_id = Some(id);
self
}
pub fn with_causation_id(mut self, id: Uuid) -> Self {
self.metadata.causation_id = Some(id);
self
}
pub fn with_user_id(mut self, id: Uuid) -> Self {
self.metadata.user_id = Some(id);
self
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct EventMetadata {
pub correlation_id: Option<Uuid>,
pub causation_id: Option<Uuid>,
pub user_id: Option<Uuid>,
#[serde(default)]
pub custom: std::collections::HashMap<String, serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct StoredEvent {
pub event_id: Uuid,
pub aggregate_id: Uuid,
pub aggregate_type: String,
pub sequence: i64,
pub event_type: String,
pub event_version: i32,
pub payload: serde_json::Value,
pub metadata: serde_json::Value,
pub occurred_at: DateTime<Utc>,
pub stored_at: DateTime<Utc>,
}