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/// 普通租户 capability;构造后始终携带一个不可选的租户主键。
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub struct TenantContext {
113    id: TenantId,
114}
115
116impl TenantContext {
117    /// 创建普通租户 capability。
118    pub const fn new(id: TenantId) -> Self {
119        Self { id }
120    }
121
122    /// 返回不可选的租户主键。
123    pub const fn id(self) -> TenantId {
124        self.id
125    }
126}
127
128/// 显式系统级租户 capability。
129///
130/// 该类型没有公开构造器,只能由可信租户 resolver 在校验已认证 system 角色后签发。
131/// capability 绑定 actor,供系统级数据访问与审计关联;它不能伪装成普通
132/// [`TenantContext`]。
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub struct SystemTenantCapability {
135    actor: ActorContext,
136}
137
138impl SystemTenantCapability {
139    pub(crate) const fn issue(actor: ActorContext) -> Self {
140        Self { actor }
141    }
142
143    /// 返回获授系统级访问的操作者。
144    pub const fn actor(self) -> ActorContext {
145        self.actor
146    }
147}
148
149/// 高频操作者上下文。
150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
151pub struct ActorContext {
152    user_id: i64,
153}
154
155impl ActorContext {
156    /// 创建操作者上下文。
157    pub const fn new(user_id: i64) -> Self {
158        Self { user_id }
159    }
160
161    /// 返回用户主键。
162    pub const fn user_id(self) -> i64 {
163        self.user_id
164    }
165}
166
167/// 创建静态类型化上下文键。
168#[macro_export]
169macro_rules! context_key {
170    ($name:literal) => {
171        $crate::action::ContextKey::new($name)
172    };
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178
179    const TENANT_ID: ContextKey<TenantId> = ContextKey::new("tenant_id");
180
181    #[test]
182    fn request_context_is_type_checked() {
183        let mut context = RequestContext::default();
184        context.insert(TENANT_ID, TenantId::new(7));
185        assert!(matches!(
186            context.require(TENANT_ID).map(|value| value.get()),
187            Ok(7)
188        ));
189        assert!(context
190            .get(ContextKey::<String>::new("tenant_id"))
191            .is_none());
192    }
193
194    #[test]
195    fn tenant_context_always_contains_a_tenant_id() {
196        let tenant = TenantContext::new(TenantId::new(7));
197        assert_eq!(tenant.id(), TenantId::new(7));
198    }
199}