evx 0.1.0

A type-safe event bus for domain events, CQRS, Redis Pub/Sub, and durable work queues
Documentation
//! CloudEvents 1.0-style wire envelopes.

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;

/// A CloudEvents 1.0-style envelope with an additional routing scope.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CloudEvent {
    /// Unique event identifier.
    pub id: String,
    /// Identifier of the context that produced the event.
    pub source: String,
    /// CloudEvents specification version. Evx emits `1.0`.
    pub specversion: String,
    /// Stable application-defined message type.
    #[serde(rename = "type")]
    pub r#type: String,
    /// Serialized message payload.
    #[serde(default)]
    pub data: Value,
    /// Payload content type.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub datacontenttype: Option<String>,
    /// Optional schema describing the payload.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dataschema: Option<String>,
    /// Optional application-defined subject.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subject: Option<String>,
    /// Time at which the envelope was created.
    pub time: DateTime<Utc>,
    /// Broker routing scope.
    pub scope: EventScope,
    /// CloudEvents extension attributes.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub extensions: HashMap<String, Value>,
    /// In-process tracing span restored when dispatching subscribers.
    ///
    /// This field is not serialized and therefore never crosses a process
    /// boundary.
    #[serde(skip, default = "Option::default")]
    pub span: Option<tracing::Span>,
}

impl CloudEvent {
    /// Creates an envelope from a typed Evx message.
    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,
        })
    }

    /// Deserializes the payload into a typed Evx message.
    pub fn into_message<M: Message>(self) -> Result<M, EventError> {
        serde_json::from_value(self.data).map_err(|e| EventError::Deserialization(e.to_string()))
    }

    /// Creates an envelope from a domain event.
    pub fn from_domain_event<E: DomainEvent>(event: &E) -> Result<Self, EventError> {
        Self::from_message(event)
    }

    /// Deserializes the payload into a typed domain event.
    pub fn into_domain_event<E: DomainEvent>(self) -> Result<E, EventError> {
        self.into_message()
    }

    /// Serializes the envelope for a wire transport such as Redis.
    pub fn to_json(&self) -> Result<String, EventError> {
        serde_json::to_string(self).map_err(|e| EventError::Serialization(e.to_string()))
    }

    /// Deserializes an envelope from JSON.
    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);
    }
}