Skip to main content

yang_base/action/
request_context.rs

1//! 请求拥有的类型化上下文;异步切换线程时随 `ActionContext` 一起移动。
2
3use crate::error::BaseError;
4use std::any::{Any, TypeId};
5use std::collections::HashMap;
6use std::fmt;
7use std::marker::PhantomData;
8
9/// 类型化请求上下文键。
10pub struct ContextKey<T> {
11    name: &'static str,
12    marker: PhantomData<fn() -> T>,
13}
14
15impl<T> ContextKey<T> {
16    /// 创建静态上下文键。
17    pub const fn new(name: &'static str) -> Self {
18        Self {
19            name,
20            marker: PhantomData,
21        }
22    }
23
24    /// 返回诊断名称。
25    pub const fn name(self) -> &'static str {
26        self.name
27    }
28}
29
30impl<T> Copy for ContextKey<T> {}
31
32impl<T> Clone for ContextKey<T> {
33    fn clone(&self) -> Self {
34        *self
35    }
36}
37
38struct ContextValue {
39    type_id: TypeId,
40    value: Box<dyn Any + Send + Sync>,
41}
42
43/// 当前请求独占的类型化扩展值集合。
44#[derive(Default)]
45pub struct RequestContext {
46    values: HashMap<&'static str, ContextValue>,
47}
48
49impl RequestContext {
50    /// 插入或替换一个类型化值。
51    pub fn insert<T>(&mut self, key: ContextKey<T>, value: T)
52    where
53        T: Send + Sync + 'static,
54    {
55        self.values.insert(
56            key.name,
57            ContextValue {
58                type_id: TypeId::of::<T>(),
59                value: Box::new(value),
60            },
61        );
62    }
63
64    /// 读取一个类型化值;名称相同但类型不同时返回 `None`。
65    pub fn get<T>(&self, key: ContextKey<T>) -> Option<&T>
66    where
67        T: Send + Sync + 'static,
68    {
69        let value = self.values.get(key.name)?;
70        (value.type_id == TypeId::of::<T>())
71            .then(|| value.value.downcast_ref::<T>())
72            .flatten()
73    }
74
75    /// 读取必需值,并把缺失或类型冲突转换成结构化错误。
76    pub fn require<T>(&self, key: ContextKey<T>) -> Result<&T, BaseError>
77    where
78        T: Send + Sync + 'static,
79    {
80        self.get(key)
81            .ok_or_else(|| BaseError::ConfigError(format!("请求上下文缺少类型化值: {}", key.name)))
82    }
83}
84
85impl fmt::Debug for RequestContext {
86    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
87        formatter
88            .debug_struct("RequestContext")
89            .field("keys", &self.values.keys().collect::<Vec<_>>())
90            .finish()
91    }
92}
93
94/// 租户主键。
95#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
96pub struct TenantId(i64);
97
98impl TenantId {
99    /// 创建租户主键。
100    pub const fn new(value: i64) -> Self {
101        Self(value)
102    }
103
104    /// 返回数据库整数值。
105    pub const fn get(self) -> i64 {
106        self.0
107    }
108}
109
110/// 高频租户上下文;system 模式是唯一允许绕过租户条件的显式入口。
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub struct TenantContext {
113    id: Option<TenantId>,
114    system: bool,
115}
116
117impl TenantContext {
118    /// 创建普通租户上下文。
119    pub const fn new(id: TenantId) -> Self {
120        Self {
121            id: Some(id),
122            system: false,
123        }
124    }
125
126    /// 创建显式系统上下文。
127    pub const fn system() -> Self {
128        Self {
129            id: None,
130            system: true,
131        }
132    }
133
134    /// 返回租户主键;system 上下文返回 `None`。
135    pub const fn id(self) -> Option<TenantId> {
136        self.id
137    }
138
139    /// 返回是否允许绕过租户隔离。
140    pub const fn is_system(self) -> bool {
141        self.system
142    }
143}
144
145/// 高频操作者上下文。
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub struct ActorContext {
148    user_id: i64,
149}
150
151impl ActorContext {
152    /// 创建操作者上下文。
153    pub const fn new(user_id: i64) -> Self {
154        Self { user_id }
155    }
156
157    /// 返回用户主键。
158    pub const fn user_id(self) -> i64 {
159        self.user_id
160    }
161}
162
163/// 创建静态类型化上下文键。
164#[macro_export]
165macro_rules! context_key {
166    ($name:literal) => {
167        $crate::action::ContextKey::new($name)
168    };
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    const TENANT_ID: ContextKey<TenantId> = ContextKey::new("tenant_id");
176
177    #[test]
178    fn request_context_is_type_checked() {
179        let mut context = RequestContext::default();
180        context.insert(TENANT_ID, TenantId::new(7));
181        assert!(matches!(
182            context.require(TENANT_ID).map(|value| value.get()),
183            Ok(7)
184        ));
185        assert!(context
186            .get(ContextKey::<String>::new("tenant_id"))
187            .is_none());
188    }
189}