use crate::error::BaseError;
use crate::table::{TableConfig, TableQuery};
#[cfg(feature = "token")]
use crate::token::TokenManager;
use serde::de::DeserializeOwned;
use std::any::Any;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, OnceLock, RwLock};
use super::Request;
use super::RequestId;
use super::RequestMeta;
static GLOBAL_TOOLS: OnceLock<Arc<GlobalTools>> = OnceLock::new();
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct User {
pub id: i64,
pub username: String,
pub nickname: String,
pub email: String,
pub roles: HashSet<String>,
pub permissions: HashSet<String>,
}
impl User {
pub fn new(id: i64, username: impl Into<String>) -> Self {
Self {
id,
username: username.into(),
nickname: String::new(),
email: String::new(),
roles: HashSet::new(),
permissions: HashSet::new(),
}
}
pub fn with_roles(mut self, roles: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.roles = roles.into_iter().map(Into::into).collect();
self
}
pub fn with_permissions(
mut self,
permissions: impl IntoIterator<Item = impl Into<String>>,
) -> Self {
self.permissions = permissions.into_iter().map(Into::into).collect();
self
}
pub fn has_permission(&self, permission: &str) -> bool {
self.permissions.contains(permission)
}
pub fn has_role(&self, role: &str) -> bool {
self.roles.contains(role)
}
pub fn has_any_role(&self, roles: &[String]) -> bool {
roles.iter().any(|r| self.has_role(r))
}
}
#[derive(Debug)]
pub struct GlobalTools {
#[cfg(feature = "token")]
token_manager: Arc<TokenManager>,
tools: Arc<RwLock<HashMap<String, Arc<dyn Any + Send + Sync>>>>,
}
impl GlobalTools {
#[cfg(feature = "token")]
pub fn new(token_manager: TokenManager) -> Self {
Self {
token_manager: Arc::new(token_manager),
tools: Arc::new(RwLock::new(HashMap::new())),
}
}
#[cfg(not(feature = "token"))]
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self {
tools: Arc::new(RwLock::new(HashMap::new())),
}
}
pub fn register_tool<T: Any + Send + Sync>(
&self,
name: &str,
tool: Arc<T>,
) -> Result<(), BaseError> {
let name = name.trim();
if name.is_empty() {
return Err(BaseError::ConfigError("工具名称不能为空".to_string()));
}
let mut tools = self.tools.write().unwrap_or_else(|p| p.into_inner());
if tools.contains_key(name) {
return Err(BaseError::ConfigError(format!("工具已注册: {}", name)));
}
tools.insert(name.to_string(), tool);
Ok(())
}
pub fn get_tool<T: Any + Send + Sync>(&self, name: &str) -> Option<Arc<T>> {
let name = name.trim();
if name.is_empty() {
return None;
}
let tools = self.tools.read().unwrap_or_else(|p| p.into_inner());
tools
.get(name)
.and_then(|tool| tool.clone().downcast::<T>().ok())
}
#[cfg(feature = "token")]
pub fn token_manager(&self) -> &TokenManager {
&self.token_manager
}
#[cfg(feature = "token")]
pub fn init(token_manager: TokenManager) -> Result<(), BaseError> {
GLOBAL_TOOLS
.set(Arc::new(GlobalTools::new(token_manager)))
.map_err(|_| BaseError::ConfigError("GlobalTools 已初始化".to_string()))
}
#[cfg(not(feature = "token"))]
pub fn init() -> Result<(), BaseError> {
GLOBAL_TOOLS
.set(Arc::new(GlobalTools::new()))
.map_err(|_| BaseError::ConfigError("GlobalTools 已初始化".to_string()))
}
pub fn get() -> Result<&'static GlobalTools, BaseError> {
GLOBAL_TOOLS
.get()
.map(|arc| arc.as_ref())
.ok_or_else(|| BaseError::ConfigError("GlobalTools 未初始化".to_string()))
}
pub(crate) fn get_arc() -> Result<Arc<GlobalTools>, BaseError> {
GLOBAL_TOOLS
.get()
.cloned()
.ok_or_else(|| BaseError::ConfigError("GlobalTools 未初始化".to_string()))
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct ActionContext {
pub request: Request,
pub request_meta: RequestMeta,
pub(crate) user: Option<User>,
pub tools: Arc<GlobalTools>,
pub table_config: Option<Arc<TableConfig>>,
pub request_id: RequestId,
pub module: Option<String>,
#[allow(dead_code)]
cached_roles: Arc<[String]>,
}
impl ActionContext {
pub fn new(request: Request, tools: Arc<GlobalTools>) -> Self {
Self {
request,
request_meta: RequestMeta::default(),
user: None,
tools,
table_config: None,
request_id: RequestId::generate(),
module: None,
cached_roles: Arc::from(Vec::new()),
}
}
pub fn new_with_global_tools(request: Request) -> Result<Self, BaseError> {
let tools = GlobalTools::get_arc()?;
Ok(Self {
request,
request_meta: RequestMeta::default(),
user: None,
tools,
table_config: None,
request_id: RequestId::generate(),
module: None,
cached_roles: Arc::from(Vec::new()),
})
}
#[allow(dead_code)]
pub(crate) fn with_user(mut self, user: User) -> Self {
self.user = Some(user);
self
}
pub fn authenticated_user(&self) -> Option<&User> {
self.user.as_ref()
}
pub fn with_request_id(mut self, request_id: RequestId) -> Self {
self.request_id = request_id;
self
}
pub fn with_request_meta(mut self, request_meta: RequestMeta) -> Self {
self.request_meta = request_meta;
self
}
pub fn with_module(mut self, module: impl Into<String>) -> Self {
self.module = Some(module.into());
self
}
pub fn with_table_config(mut self, config: Arc<TableConfig>) -> Self {
self.table_config = Some(config);
self
}
pub fn extract_input<I: DeserializeOwned>(&self) -> Result<I, BaseError> {
serde_json::from_value(self.request.body.clone())
.map_err(|e| BaseError::ParamInvalid("body".to_string(), e.to_string()))
}
pub(crate) fn extract_input_owned<I: DeserializeOwned>(&mut self) -> Result<I, BaseError> {
let body = std::mem::take(&mut self.request.body);
serde_json::from_value(body)
.map_err(|e| BaseError::ParamInvalid("body".to_string(), e.to_string()))
}
#[deprecated(note = "H-1 重构期间停用,将在 Task 6/7 后移除;请改用 extract_input")]
#[allow(dead_code)]
pub(crate) fn param_optional_strict<T: DeserializeOwned>(
&self,
key: &str,
) -> Result<Option<T>, BaseError> {
if key.trim().is_empty() {
return Err(BaseError::ParamInvalid(
key.to_string(),
"参数名不能为空".to_string(),
));
}
match self.request.body.get(key) {
None => Ok(None),
Some(value) => serde_json::from_value::<T>(value.clone())
.map(Some)
.map_err(|_| {
BaseError::ParamInvalid(
key.to_string(),
format!("参数 '{}' 存在但无法转换为目标类型", key),
)
}),
}
}
pub fn path_param<T: DeserializeOwned>(&self, key: &str) -> Result<T, BaseError> {
let key = key.trim();
if key.is_empty() {
return Err(BaseError::ParamInvalid(
key.to_string(),
"路径参数名不能为空".to_string(),
));
}
let raw = self
.request
.path_params
.get(key)
.ok_or_else(|| BaseError::ParamMissing(key.to_string()))?;
serde_json::from_str::<T>(raw)
.or_else(|_| serde_json::from_value(serde_json::Value::String(raw.clone())))
.map_err(|_| {
BaseError::ParamInvalid(
key.to_string(),
format!("路径参数 '{}' 无法转换为目标类型,原始值: {}", key, raw),
)
})
}
pub fn table_query(&self) -> Result<TableQuery, BaseError> {
let config = self
.table_config
.as_ref()
.ok_or(BaseError::TableConfigNotSet)?;
let roles_set = self.user_roles_set();
let user_roles: Arc<[String]> = Arc::from(
roles_set
.map(|s| s.iter().cloned().collect::<Vec<_>>())
.unwrap_or_default(),
);
#[cfg(feature = "mysql")]
let pool = crate::database::GlobalDatabase::get()
.ok()
.map(|db| Arc::new(db.pool().clone()));
#[cfg(not(feature = "mysql"))]
let pool = None;
let slow_threshold = crate::observability::ObservabilityConfig::get().slow_query_threshold;
Ok(TableQuery::new(config.clone(), user_roles, pool)
.with_slow_threshold(slow_threshold)
.with_request_id(self.request_id))
}
#[cfg(feature = "mysql")]
pub async fn begin_transaction(&self) -> Result<yang_db::Transaction, BaseError> {
crate::database::GlobalDatabase::transaction().await
}
pub fn user_roles(&self) -> Vec<String> {
self.user
.as_ref()
.map(|u| u.roles.iter().cloned().collect())
.unwrap_or_default()
}
pub fn user_roles_set(&self) -> Option<&HashSet<String>> {
self.user.as_ref().map(|u| &u.roles)
}
}