Skip to main content

flare_core_messaging/eventbus/
envelope.rs

1//! 统一事件信封(分布式事件总线标准载荷)
2//!
3//! 用于跨服务、基于 Topic 的事件总线(Kafka / NATS 等):按 `partition_key` 分区保证同流有序,
4//! 适用于 IM(conversation_id)、订单(order_id)、审计(tenant_id)等任意业务流。
5
6use serde::{Deserialize, Serialize};
7use std::fmt;
8use uuid::Uuid;
9
10use flare_core_base::error::{FlareError, Result};
11
12/// 统一事件信封:事件总线上的标准载荷(与具体业务解耦)
13#[derive(Clone, Debug, Serialize, Deserialize)]
14pub struct EventEnvelope {
15    /// 全局唯一事件 ID
16    pub event_id: String,
17    /// 事件类型(业务自定义,如 "message.created"、"order.shipped")
18    pub event_type: String,
19    /// 分区键:用于 Kafka 等按 key 分区与过滤,同 key 内有序(IM 可为 conversation_id,订单可为 order_id)
20    pub partition_key: String,
21    /// 流内序号:用于同分区内的顺序与去重
22    pub seq: u64,
23    /// 业务载荷(protobuf / JSON 等,由业务解析)
24    pub payload: Vec<u8>,
25    /// 可选:事件发生时间戳(毫秒)
26    #[serde(default)]
27    pub timestamp_ms: Option<u64>,
28    /// 可选:来源服务标识
29    #[serde(default)]
30    pub source: Option<String>,
31}
32
33impl EventEnvelope {
34    /// 构造信封。`partition_key` 由业务定义(如会话 ID、订单 ID、租户 ID)。
35    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    /// 设置时间戳(毫秒)
53    pub fn with_timestamp_ms(mut self, ms: u64) -> Self {
54        self.timestamp_ms = Some(ms);
55        self
56    }
57
58    /// 设置来源服务
59    pub fn with_source(mut self, source: impl Into<String>) -> Self {
60        self.source = Some(source.into());
61        self
62    }
63
64    /// 分区键引用(Kafka 等后端用于分区与顺序)
65    pub fn partition_key(&self) -> &str {
66        &self.partition_key
67    }
68
69    /// JSON 编码整封信封(历史兼容;不建议用于 MQ 热路径)。
70    #[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    /// protobuf 编码整封信封(推荐:低开销、体积小)。
76    ///
77    /// 需要启用 `flare-server-core` 的 `proto` feature。
78    #[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    /// 从 protobuf bytes 解码信封。
95    ///
96    /// 需要启用 `flare-server-core` 的 `proto` feature。
97    #[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    /// 可选约定:event_type 以 "operation." 开头时视为操作类(可由业务自行约定或忽略)
123    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}