use crate::error::BaseError;
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::fmt;
use std::marker::PhantomData;
pub struct ContextKey<T> {
name: &'static str,
marker: PhantomData<fn() -> T>,
}
impl<T> ContextKey<T> {
pub const fn new(name: &'static str) -> Self {
Self {
name,
marker: PhantomData,
}
}
pub const fn name(self) -> &'static str {
self.name
}
}
impl<T> Copy for ContextKey<T> {}
impl<T> Clone for ContextKey<T> {
fn clone(&self) -> Self {
*self
}
}
struct ContextValue {
type_id: TypeId,
value: Box<dyn Any + Send + Sync>,
}
#[derive(Default)]
pub struct RequestContext {
values: HashMap<&'static str, ContextValue>,
}
impl RequestContext {
pub fn insert<T>(&mut self, key: ContextKey<T>, value: T)
where
T: Send + Sync + 'static,
{
self.values.insert(
key.name,
ContextValue {
type_id: TypeId::of::<T>(),
value: Box::new(value),
},
);
}
pub fn get<T>(&self, key: ContextKey<T>) -> Option<&T>
where
T: Send + Sync + 'static,
{
let value = self.values.get(key.name)?;
(value.type_id == TypeId::of::<T>())
.then(|| value.value.downcast_ref::<T>())
.flatten()
}
pub fn require<T>(&self, key: ContextKey<T>) -> Result<&T, BaseError>
where
T: Send + Sync + 'static,
{
self.get(key)
.ok_or_else(|| BaseError::ConfigError(format!("请求上下文缺少类型化值: {}", key.name)))
}
}
impl fmt::Debug for RequestContext {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("RequestContext")
.field("keys", &self.values.keys().collect::<Vec<_>>())
.finish()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TenantId(i64);
impl TenantId {
pub const fn new(value: i64) -> Self {
Self(value)
}
pub const fn get(self) -> i64 {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TenantContext {
id: TenantId,
}
impl TenantContext {
pub const fn new(id: TenantId) -> Self {
Self { id }
}
pub const fn id(self) -> TenantId {
self.id
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SystemTenantCapability {
actor: ActorContext,
}
impl SystemTenantCapability {
pub(crate) const fn issue(actor: ActorContext) -> Self {
Self { actor }
}
pub const fn actor(self) -> ActorContext {
self.actor
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ActorContext {
user_id: i64,
}
impl ActorContext {
pub const fn new(user_id: i64) -> Self {
Self { user_id }
}
pub const fn user_id(self) -> i64 {
self.user_id
}
}
#[macro_export]
macro_rules! context_key {
($name:literal) => {
$crate::action::ContextKey::new($name)
};
}
#[cfg(test)]
mod tests {
use super::*;
const TENANT_ID: ContextKey<TenantId> = ContextKey::new("tenant_id");
#[test]
fn request_context_is_type_checked() {
let mut context = RequestContext::default();
context.insert(TENANT_ID, TenantId::new(7));
assert!(matches!(
context.require(TENANT_ID).map(|value| value.get()),
Ok(7)
));
assert!(context
.get(ContextKey::<String>::new("tenant_id"))
.is_none());
}
#[test]
fn tenant_context_always_contains_a_tenant_id() {
let tenant = TenantContext::new(TenantId::new(7));
assert_eq!(tenant.id(), TenantId::new(7));
}
}