baichun_framework_core/
context.rs1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3use std::sync::Arc;
4use tokio::sync::RwLock;
5
6#[derive(Debug, Clone, Default, Serialize, Deserialize)]
8pub struct ContextData {
9 pub user_id: Option<String>,
11 pub tenant_id: Option<String>,
13 pub request_id: Option<String>,
15 pub extras: HashMap<String, String>,
17}
18
19#[derive(Debug, Clone)]
21pub struct Context {
22 data: Arc<RwLock<ContextData>>,
23}
24
25impl Context {
26 pub fn new() -> Self {
28 Self {
29 data: Arc::new(RwLock::new(ContextData::default())),
30 }
31 }
32
33 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 pub async fn user_id(&self) -> Option<String> {
41 let data = self.data.read().await;
42 data.user_id.clone()
43 }
44
45 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 pub async fn tenant_id(&self) -> Option<String> {
53 let data = self.data.read().await;
54 data.tenant_id.clone()
55 }
56
57 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 pub async fn request_id(&self) -> Option<String> {
65 let data = self.data.read().await;
66 data.request_id.clone()
67 }
68
69 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 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}