baichun_framework_core/
context.rs

1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3use std::sync::Arc;
4use tokio::sync::RwLock;
5
6/// 上下文数据
7#[derive(Debug, Clone, Default, Serialize, Deserialize)]
8pub struct ContextData {
9    /// 用户ID
10    pub user_id: Option<String>,
11    /// 租户ID
12    pub tenant_id: Option<String>,
13    /// 请求ID
14    pub request_id: Option<String>,
15    /// 其他数据
16    pub extras: HashMap<String, String>,
17}
18
19/// 上下文
20#[derive(Debug, Clone)]
21pub struct Context {
22    data: Arc<RwLock<ContextData>>,
23}
24
25impl Context {
26    /// 创建新的上下文
27    pub fn new() -> Self {
28        Self {
29            data: Arc::new(RwLock::new(ContextData::default())),
30        }
31    }
32
33    /// 设置用户ID
34    pub async fn set_user_id(&self, user_id: impl Into<String>) {
35        let mut data = self.data.write().await;
36        data.user_id = Some(user_id.into());
37    }
38
39    /// 获取用户ID
40    pub async fn user_id(&self) -> Option<String> {
41        let data = self.data.read().await;
42        data.user_id.clone()
43    }
44
45    /// 设置租户ID
46    pub async fn set_tenant_id(&self, tenant_id: impl Into<String>) {
47        let mut data = self.data.write().await;
48        data.tenant_id = Some(tenant_id.into());
49    }
50
51    /// 获取租户ID
52    pub async fn tenant_id(&self) -> Option<String> {
53        let data = self.data.read().await;
54        data.tenant_id.clone()
55    }
56
57    /// 设置请求ID
58    pub async fn set_request_id(&self, request_id: impl Into<String>) {
59        let mut data = self.data.write().await;
60        data.request_id = Some(request_id.into());
61    }
62
63    /// 获取请求ID
64    pub async fn request_id(&self) -> Option<String> {
65        let data = self.data.read().await;
66        data.request_id.clone()
67    }
68
69    /// 设置额外数据
70    pub async fn set_extra(&self, key: impl Into<String>, value: impl Into<String>) {
71        let mut data = self.data.write().await;
72        data.extras.insert(key.into(), value.into());
73    }
74
75    /// 获取额外数据
76    pub async fn extra(&self, key: &str) -> Option<String> {
77        let data = self.data.read().await;
78        data.extras.get(key).cloned()
79    }
80}
81
82impl Default for Context {
83    fn default() -> Self {
84        Self::new()
85    }
86}