use std::collections::HashMap;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use uuid::Uuid;
use crate::error::EventError;
use crate::event::domain::{DomainEvent, Message};
use crate::event::scope::EventScope;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CloudEvent {
pub id: String,
pub source: String,
pub specversion: String,
#[serde(rename = "type")]
pub r#type: String,
#[serde(default)]
pub data: Value,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub datacontenttype: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub dataschema: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub subject: Option<String>,
pub time: DateTime<Utc>,
pub scope: EventScope,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub extensions: HashMap<String, Value>,
#[serde(skip, default = "Option::default")]
pub span: Option<tracing::Span>,
}
impl CloudEvent {
pub fn from_message<M: Message>(event: &M) -> Result<Self, EventError> {
let data =
serde_json::to_value(event).map_err(|e| EventError::Serialization(e.to_string()))?;
Ok(Self {
id: Uuid::new_v4().to_string(),
source: M::source().to_string(),
specversion: "1.0".to_string(),
r#type: M::message_type().to_string(),
data,
datacontenttype: Some("application/json".to_string()),
dataschema: None,
subject: event.subject(),
time: Utc::now(),
scope: M::scope(),
extensions: HashMap::new(),
span: None,
})
}
pub fn into_message<M: Message>(self) -> Result<M, EventError> {
serde_json::from_value(self.data).map_err(|e| EventError::Deserialization(e.to_string()))
}
pub fn from_domain_event<E: DomainEvent>(event: &E) -> Result<Self, EventError> {
Self::from_message(event)
}
pub fn into_domain_event<E: DomainEvent>(self) -> Result<E, EventError> {
self.into_message()
}
pub fn to_json(&self) -> Result<String, EventError> {
serde_json::to_string(self).map_err(|e| EventError::Serialization(e.to_string()))
}
pub fn from_json(json: &str) -> Result<Self, EventError> {
serde_json::from_str(json).map_err(|e| EventError::Deserialization(e.to_string()))
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde::Deserialize;
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TestEvent {
msg: String,
}
impl Message for TestEvent {
fn message_type() -> &'static str {
"com.test.event"
}
fn source() -> &'static str {
"/test"
}
fn scope() -> EventScope {
EventScope::Process
}
fn subject(&self) -> Option<String> {
Some("test-subject".into())
}
}
impl DomainEvent for TestEvent {}
#[test]
fn roundtrip_domain_event() {
let original = TestEvent {
msg: "hello".into(),
};
let ce = CloudEvent::from_domain_event(&original).unwrap();
assert_eq!(ce.r#type, "com.test.event");
assert_eq!(ce.source, "/test");
assert_eq!(ce.specversion, "1.0");
assert_eq!(ce.datacontenttype.as_deref(), Some("application/json"));
assert_eq!(ce.subject.as_deref(), Some("test-subject"));
assert_eq!(ce.scope, EventScope::Process);
let restored: TestEvent = ce.into_domain_event().unwrap();
assert_eq!(restored.msg, "hello");
}
#[test]
fn json_roundtrip() {
let original = TestEvent {
msg: "world".into(),
};
let ce = CloudEvent::from_domain_event(&original).unwrap();
let json = ce.to_json().unwrap();
let parsed = CloudEvent::from_json(&json).unwrap();
assert_eq!(parsed.r#type, ce.r#type);
assert_eq!(parsed.id, ce.id);
}
}