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: Option<TenantId>,
114 system: bool,
115}
116
117impl TenantContext {
118 pub const fn new(id: TenantId) -> Self {
120 Self {
121 id: Some(id),
122 system: false,
123 }
124 }
125
126 pub const fn system() -> Self {
128 Self {
129 id: None,
130 system: true,
131 }
132 }
133
134 pub const fn id(self) -> Option<TenantId> {
136 self.id
137 }
138
139 pub const fn is_system(self) -> bool {
141 self.system
142 }
143}
144
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub struct ActorContext {
148 user_id: i64,
149}
150
151impl ActorContext {
152 pub const fn new(user_id: i64) -> Self {
154 Self { user_id }
155 }
156
157 pub const fn user_id(self) -> i64 {
159 self.user_id
160 }
161}
162
163#[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}