Skip to main content

flare_core_base/context/
mod.rs

1//! 上下文模块(极简、0 拷贝)
2//!
3//! 仅保留与 metadata.proto 对齐的四种上下文:CoreContext、ExtendedContext、ActorContext、AuditContext。
4//! 字符串与集合均用 `Arc` 共享,Clone 仅增加引用计数。
5
6use std::collections::HashMap;
7use std::sync::Arc;
8
9// -----------------------------------------------------------------------------
10// 上下文键常量(统一用于 gRPC Metadata 和 MQ Headers)
11// -----------------------------------------------------------------------------
12
13/// 上下文键常量
14pub mod keys {
15    /// 追踪 ID
16    pub const TRACE_ID: &str = "x-trace-id";
17
18    /// 用户 ID
19    pub const USER_ID: &str = "x-user-id";
20
21    /// 租户 ID
22    pub const TENANT_ID: &str = "x-tenant-id";
23
24    /// 设备 ID
25    pub const DEVICE_ID: &str = "x-device-id";
26
27    /// 平台
28    pub const PLATFORM: &str = "x-platform";
29
30    /// 会话 ID
31    pub const SESSION_ID: &str = "x-session-id";
32
33    /// 请求 ID
34    pub const REQUEST_ID: &str = "x-request-id";
35
36    /// Actor ID
37    pub const ACTOR_ID: &str = "x-actor-id";
38
39    /// Actor Type
40    pub const ACTOR_TYPE: &str = "x-actor-type";
41
42    /// 消息来源
43    pub const SOURCE: &str = "x-source";
44
45    /// 消息类型
46    pub const MESSAGE_TYPE: &str = "x-message-type";
47
48    /// 重试次数
49    pub const RETRY_COUNT: &str = "x-retry-count";
50}
51
52// -----------------------------------------------------------------------------
53// ExtendedContext(按需使用,不进主链路)
54// -----------------------------------------------------------------------------
55
56/// 扩展上下文(与 metadata.proto ExtendedContext 对齐)
57///
58/// 使用 `Arc` 共享 attributes,Clone 零拷贝。
59#[derive(Clone, Debug, Default)]
60pub struct ExtendedContext {
61    pub attributes: Arc<HashMap<Arc<str>, Arc<str>>>,
62}
63
64impl ExtendedContext {
65    pub fn new() -> Self {
66        Self::default()
67    }
68
69    pub fn with_attribute(mut self, key: impl AsRef<str>, value: impl AsRef<str>) -> Self {
70        let mut m = HashMap::new();
71        for (k, v) in self.attributes.iter() {
72            m.insert(Arc::clone(k), Arc::clone(v));
73        }
74        m.insert(Arc::from(key.as_ref()), Arc::from(value.as_ref()));
75        self.attributes = Arc::new(m);
76        self
77    }
78
79    #[inline]
80    pub fn get(&self, key: &str) -> Option<&str> {
81        self.attributes.get(key).map(Arc::as_ref)
82    }
83}
84
85impl PartialEq for ExtendedContext {
86    fn eq(&self, other: &Self) -> bool {
87        Arc::ptr_eq(&self.attributes, &other.attributes)
88            || self.attributes.as_ref() == other.attributes.as_ref()
89    }
90}
91impl Eq for ExtendedContext {}
92
93// -----------------------------------------------------------------------------
94// ActorType
95// -----------------------------------------------------------------------------
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
98pub enum ActorType {
99    #[default]
100    Unspecified = 0,
101    User = 1,
102    Service = 2,
103    TenantAdmin = 3,
104    System = 4,
105    Guest = 5,
106}
107
108impl From<i32> for ActorType {
109    fn from(v: i32) -> Self {
110        match v {
111            1 => ActorType::User,
112            2 => ActorType::Service,
113            3 => ActorType::TenantAdmin,
114            4 => ActorType::System,
115            5 => ActorType::Guest,
116            _ => ActorType::Unspecified,
117        }
118    }
119}
120
121impl From<ActorType> for i32 {
122    fn from(v: ActorType) -> i32 {
123        v as i32
124    }
125}
126
127// -----------------------------------------------------------------------------
128// ActorContext(鉴权与审计)
129// -----------------------------------------------------------------------------
130
131/// 操作者上下文(与 metadata.proto ActorContext 对齐)
132///
133/// 字段均用 Arc 共享,Clone 零拷贝。
134#[derive(Clone, Debug)]
135pub struct ActorContext {
136    pub actor_id: Arc<str>,
137    pub actor_type: ActorType,
138    pub roles: Arc<[Arc<str>]>,
139    pub attributes: Arc<HashMap<Arc<str>, Arc<str>>>,
140}
141
142impl Default for ActorContext {
143    fn default() -> Self {
144        Self {
145            actor_id: Arc::from(""),
146            actor_type: ActorType::Unspecified,
147            roles: Arc::from([]),
148            attributes: Arc::new(HashMap::new()),
149        }
150    }
151}
152
153impl ActorContext {
154    pub fn new(actor_id: impl AsRef<str>) -> Self {
155        Self {
156            actor_id: Arc::from(actor_id.as_ref()),
157            actor_type: ActorType::User,
158            roles: Arc::from([]),
159            attributes: Arc::new(HashMap::new()),
160        }
161    }
162
163    pub fn with_type(mut self, actor_type: ActorType) -> Self {
164        self.actor_type = actor_type;
165        self
166    }
167
168    pub fn with_role(mut self, role: impl AsRef<str>) -> Self {
169        let mut v: Vec<Arc<str>> = self.roles.iter().map(Arc::clone).collect();
170        v.push(Arc::from(role.as_ref()));
171        self.roles = Arc::from(v);
172        self
173    }
174
175    pub fn with_attribute(mut self, key: impl AsRef<str>, value: impl AsRef<str>) -> Self {
176        let mut m = HashMap::new();
177        for (k, v) in self.attributes.iter() {
178            m.insert(Arc::clone(k), Arc::clone(v));
179        }
180        m.insert(Arc::from(key.as_ref()), Arc::from(value.as_ref()));
181        self.attributes = Arc::new(m);
182        self
183    }
184
185    #[inline]
186    pub fn actor_id(&self) -> &str {
187        self.actor_id.as_ref()
188    }
189
190    #[inline]
191    pub fn roles(&self) -> &[Arc<str>] {
192        &self.roles
193    }
194
195    #[inline]
196    pub fn attributes(&self) -> &HashMap<Arc<str>, Arc<str>> {
197        &self.attributes
198    }
199}
200
201impl PartialEq for ActorContext {
202    fn eq(&self, other: &Self) -> bool {
203        self.actor_id == other.actor_id
204            && self.actor_type == other.actor_type
205            && self.roles == other.roles
206            && self.attributes.as_ref() == other.attributes.as_ref()
207    }
208}
209impl Eq for ActorContext {}
210
211// -----------------------------------------------------------------------------
212// AuditContext(敏感操作记录)
213// -----------------------------------------------------------------------------
214
215/// 审计上下文(与 metadata.proto AuditContext 对齐)
216///
217/// actor 与 metadata 用 Arc 共享,Clone 零拷贝。
218#[derive(Clone, Debug)]
219pub struct AuditContext {
220    pub actor: Arc<ActorContext>,
221    pub operated_at: i64,
222    pub reason: Arc<str>,
223    pub metadata: Arc<HashMap<Arc<str>, Arc<str>>>,
224}
225
226impl Default for AuditContext {
227    fn default() -> Self {
228        Self {
229            actor: Arc::new(ActorContext::default()),
230            operated_at: 0,
231            reason: Arc::from(""),
232            metadata: Arc::new(HashMap::new()),
233        }
234    }
235}
236
237impl AuditContext {
238    pub fn new(actor: ActorContext) -> Self {
239        Self {
240            actor: Arc::new(actor),
241            operated_at: chrono::Utc::now().timestamp_millis(),
242            reason: Arc::from(""),
243            metadata: Arc::new(HashMap::new()),
244        }
245    }
246
247    pub fn with_operated_at(mut self, ts: i64) -> Self {
248        self.operated_at = ts;
249        self
250    }
251
252    pub fn with_reason(mut self, reason: impl AsRef<str>) -> Self {
253        self.reason = Arc::from(reason.as_ref());
254        self
255    }
256
257    pub fn with_metadata_entry(mut self, key: impl AsRef<str>, value: impl AsRef<str>) -> Self {
258        let mut m = HashMap::new();
259        for (k, v) in self.metadata.iter() {
260            m.insert(Arc::clone(k), Arc::clone(v));
261        }
262        m.insert(Arc::from(key.as_ref()), Arc::from(value.as_ref()));
263        self.metadata = Arc::new(m);
264        self
265    }
266}
267
268impl PartialEq for AuditContext {
269    fn eq(&self, other: &Self) -> bool {
270        Arc::ptr_eq(&self.actor, &other.actor)
271            && self.operated_at == other.operated_at
272            && self.reason == other.reason
273            && self.metadata.as_ref() == other.metadata.as_ref()
274    }
275}
276impl Eq for AuditContext {}
277
278// -----------------------------------------------------------------------------
279// 核心 Context 系统(core.rs)
280// -----------------------------------------------------------------------------
281
282pub mod core;
283pub mod typemap;
284
285pub use core::{Context, ContextError, ContextExt, Ctx, TaskControl};
286pub use typemap::TypeMap;
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291
292    #[test]
293    fn test_extended_context() {
294        let ext = ExtendedContext::new().with_attribute("k", "v");
295        assert_eq!(ext.get("k"), Some("v"));
296    }
297
298    #[test]
299    fn test_actor_context() {
300        let actor = ActorContext::new("user-1")
301            .with_type(ActorType::User)
302            .with_role("admin");
303        assert_eq!(actor.actor_id(), "user-1");
304        assert_eq!(actor.roles.len(), 1);
305    }
306
307    #[test]
308    fn test_audit_context() {
309        let actor = ActorContext::new("user-1");
310        let audit = AuditContext::new(actor).with_reason("test");
311        assert_eq!(audit.reason.as_ref(), "test");
312    }
313}