use std::any::{Any, TypeId};
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::sync::Arc;
use crate::error::JsonApiError;
#[derive(Debug, Clone)]
pub struct Context {
inner: Arc<Fields>,
}
#[derive(Debug, Clone)]
struct Fields {
correlation_id: String,
principal: Option<String>,
tenant: Option<String>,
locale: Option<crate::i18n::Locale>,
metadata: BTreeMap<String, serde_json::Value>,
extensions: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
}
impl Context {
pub fn new(correlation_id: impl Into<String>) -> Self {
Self {
inner: Arc::new(Fields {
correlation_id: correlation_id.into(),
principal: None,
tenant: None,
locale: None,
metadata: BTreeMap::new(),
extensions: HashMap::new(),
}),
}
}
#[must_use]
pub fn with_principal(self, principal: impl Into<String>) -> Self {
self.map(|f| f.principal = Some(principal.into()))
}
#[must_use]
pub fn with_tenant(self, tenant: impl Into<String>) -> Self {
self.map(|f| f.tenant = Some(tenant.into()))
}
#[must_use]
pub fn with_locale(self, locale: crate::i18n::Locale) -> Self {
self.map(|f| f.locale = Some(locale))
}
pub fn locale(&self) -> Option<&crate::i18n::Locale> {
self.inner.locale.as_ref()
}
#[must_use]
pub fn with_metadata(
self,
key: impl Into<String>,
value: impl Into<serde_json::Value>,
) -> Self {
self.map(|f| {
f.metadata.insert(key.into(), value.into());
})
}
pub fn correlation_id(&self) -> &str {
&self.inner.correlation_id
}
pub fn principal(&self) -> Option<&str> {
self.inner.principal.as_deref()
}
pub fn tenant(&self) -> Option<&str> {
self.inner.tenant.as_deref()
}
#[must_use]
pub fn with<T: Any + Send + Sync + 'static>(self, value: T) -> Self {
self.map(|fields| {
fields.extensions.insert(TypeId::of::<T>(), Arc::new(value));
})
}
pub fn get_ext<T: Any + Send + Sync + 'static>(&self) -> Option<&T> {
self.inner
.extensions
.get(&TypeId::of::<T>())
.and_then(|value| value.downcast_ref::<T>())
}
pub fn extract<T: Any + Send + Sync + 'static>(&self) -> Result<&T, JsonApiError> {
self.get_ext::<T>().ok_or_else(|| {
eprintln!(
"[{}] no `{}` in the request context",
self.correlation_id(),
std::any::type_name::<T>()
);
JsonApiError::internal(self)
})
}
pub fn get(&self, key: &str) -> Option<&serde_json::Value> {
self.inner.metadata.get(key)
}
pub fn metadata(&self) -> &BTreeMap<String, serde_json::Value> {
&self.inner.metadata
}
fn map(mut self, edit: impl FnOnce(&mut Fields)) -> Self {
let fields = Arc::make_mut(&mut self.inner);
edit(fields);
self
}
}
#[cfg(feature = "audit")]
#[cfg_attr(docsrs, doc(cfg(feature = "audit")))]
impl Context {
pub fn scope(&self) -> ash_log::ScopeGuard {
let mut scope = ash_log::Scope::new().correlation_id(self.correlation_id());
if let Some(principal) = self.principal() {
scope = scope.principal(principal);
}
if let Some(tenant) = self.tenant() {
scope = scope.with("tenant", tenant);
}
for (key, value) in self.metadata() {
scope = scope.with(key.clone(), value.clone());
}
scope.enter()
}
}