yang_base/action/
request_context.rs1use crate::error::BaseError;
4use std::any::{Any, TypeId};
5use std::collections::HashMap;
6use std::fmt;
7use std::marker::PhantomData;
8
9pub struct ContextKey<T> {
11 name: &'static str,
12 marker: PhantomData<fn() -> T>,
13}
14
15impl<T> ContextKey<T> {
16 pub const fn new(name: &'static str) -> Self {
18 Self {
19 name,
20 marker: PhantomData,
21 }
22 }
23
24 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#[derive(Default)]
45pub struct RequestContext {
46 values: HashMap<&'static str, ContextValue>,
47}
48
49impl RequestContext {
50 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
96pub struct TenantId(i64);
97
98impl TenantId {
99 pub const fn new(value: i64) -> Self {
101 Self(value)
102 }
103
104 pub const fn get(self) -> i64 {
106 self.0
107 }
108}
109
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub struct TenantContext {
113 id: TenantId,
114}
115
116impl TenantContext {
117 pub const fn new(id: TenantId) -> Self {
119 Self { id }
120 }
121
122 pub const fn id(self) -> TenantId {
124 self.id
125 }
126}
127
128#[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 pub const fn actor(self) -> ActorContext {
145 self.actor
146 }
147}
148
149#[derive(Debug, Clone, Copy, PartialEq, Eq)]
151pub struct ActorContext {
152 user_id: i64,
153}
154
155impl ActorContext {
156 pub const fn new(user_id: i64) -> Self {
158 Self { user_id }
159 }
160
161 pub const fn user_id(self) -> i64 {
163 self.user_id
164 }
165}
166
167#[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}