flare_core_messaging/eventbus/
envelope.rs1use serde::{Deserialize, Serialize};
7use std::fmt;
8use uuid::Uuid;
9
10use flare_core_base::error::{FlareError, Result};
11
12#[derive(Clone, Debug, Serialize, Deserialize)]
14pub struct EventEnvelope {
15 pub event_id: String,
17 pub event_type: String,
19 pub partition_key: String,
21 pub seq: u64,
23 pub payload: Vec<u8>,
25 #[serde(default)]
27 pub timestamp_ms: Option<u64>,
28 #[serde(default)]
30 pub source: Option<String>,
31}
32
33impl EventEnvelope {
34 pub fn new(
36 event_type: impl Into<String>,
37 partition_key: impl Into<String>,
38 seq: u64,
39 payload: Vec<u8>,
40 ) -> Self {
41 Self {
42 event_id: Uuid::new_v4().to_string(),
43 event_type: event_type.into(),
44 partition_key: partition_key.into(),
45 seq,
46 payload,
47 timestamp_ms: None,
48 source: None,
49 }
50 }
51
52 pub fn with_timestamp_ms(mut self, ms: u64) -> Self {
54 self.timestamp_ms = Some(ms);
55 self
56 }
57
58 pub fn with_source(mut self, source: impl Into<String>) -> Self {
60 self.source = Some(source.into());
61 self
62 }
63
64 pub fn partition_key(&self) -> &str {
66 &self.partition_key
67 }
68
69 #[inline]
71 pub fn to_json_bytes(&self) -> Result<Vec<u8>> {
72 serde_json::to_vec(self).map_err(|e| FlareError::serialization_error(e.to_string()))
73 }
74
75 #[cfg(feature = "proto")]
79 #[inline]
80 pub fn to_proto_bytes(&self) -> Result<Vec<u8>> {
81 use prost::Message as _;
82 let msg = flare_proto::common::EventBusEnvelope {
83 event_id: self.event_id.clone(),
84 event_type: self.event_type.clone(),
85 partition_key: self.partition_key.clone(),
86 seq: self.seq,
87 payload: self.payload.clone(),
88 occurred_at: self.timestamp_ms.unwrap_or(0) as i64,
89 source: self.source.clone().unwrap_or_default(),
90 };
91 Ok(msg.encode_to_vec())
92 }
93
94 #[cfg(feature = "proto")]
98 #[inline]
99 pub fn from_proto_bytes(bytes: &[u8]) -> Result<Self> {
100 use prost::Message as _;
101 let msg = flare_proto::common::EventBusEnvelope::decode(bytes)
102 .map_err(|e| FlareError::deserialization_error(e.to_string()))?;
103 Ok(Self {
104 event_id: msg.event_id,
105 event_type: msg.event_type,
106 partition_key: msg.partition_key,
107 seq: msg.seq,
108 payload: msg.payload,
109 timestamp_ms: if msg.occurred_at == 0 {
110 None
111 } else {
112 Some(msg.occurred_at as u64)
113 },
114 source: if msg.source.is_empty() {
115 None
116 } else {
117 Some(msg.source)
118 },
119 })
120 }
121
122 pub fn is_operation(&self) -> bool {
124 self.event_type.starts_with("operation.")
125 }
126}
127
128impl fmt::Display for EventEnvelope {
129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 write!(
131 f,
132 "EventEnvelope({} type={} key={} seq={})",
133 self.event_id, self.event_type, self.partition_key, self.seq
134 )
135 }
136}