yang-base 0.1.1

个人使用构建后端服务器
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! Action 执行上下文
//!
//! 提供 Action 执行所需的上下文环境,包含请求信息、用户信息、全局工具和表配置。
//!
//! # 主要组件
//!
//! - `ActionContext`:Action 执行上下文结构
//! - `User`:用户信息(占位符,后续实现)
//! - `GlobalTools`:全局工具集合(占位符,后续实现)

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;
use std::str::FromStr;
use std::sync::{Arc, OnceLock, RwLock};

use super::Request;

/// 全局 GlobalTools 单例
/// 使用 OnceLock 保证线程安全的一次性初始化
/// 内部存储 Arc<GlobalTools> 以支持废弃克隆
/// 注意:返回的是静态引用,不需要克隆
static GLOBAL_TOOLS: OnceLock<Arc<GlobalTools>> = OnceLock::new();

/// 用户信息
#[derive(Debug, Clone)]
pub struct User {
    /// 用户 ID
    pub id: i64,
    /// 用户名
    pub username: String,
    /// 昵称
    pub nickname: String,
    /// 邮箱
    pub email: String,
    /// 角色列表
    pub roles: Vec<String>,
    /// 权限列表
    pub permissions: Vec<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: Vec::new(),
            permissions: Vec::new(),
        }
    }

    /// 检查是否有指定权限
    pub fn has_permission(&self, permission: &str) -> bool {
        self.permissions.contains(&permission.to_string())
    }

    /// 检查是否有指定角色
    pub fn has_role(&self, role: &str) -> bool {
        self.roles.contains(&role.to_string())
    }

    /// 检查是否有任一角色
    pub fn has_any_role(&self, roles: &[String]) -> bool {
        roles.iter().any(|r| self.has_role(r))
    }
}

/// 全局工具集合
#[derive(Debug)]
pub struct GlobalTools {
    /// Token 管理器
    #[cfg(feature = "token")]
    token_manager: Arc<TokenManager>,
    /// 自定义工具注册表
    tools: Arc<RwLock<HashMap<String, Arc<dyn Any + Send + Sync>>>>,
}

impl GlobalTools {
    /// 创建新的全局工具集合(启用 token feature)
    #[cfg(feature = "token")]
    pub fn new(token_manager: TokenManager) -> Self {
        Self {
            token_manager: Arc::new(token_manager),
            tools: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// 创建新的全局工具集合(未启用 token feature)
    #[cfg(not(feature = "token"))]
    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>) {
        // 使用 unwrap_or_else 处理锁中毒:即使锁中毒也能恢复数据并继续注册
        let mut tools = self.tools.write().unwrap_or_else(|p| p.into_inner());
        tools.insert(name.to_string(), tool);
    }

    /// 获取已注册的工具
    pub fn get_tool<T: Any + Send + Sync>(&self, name: &str) -> Option<Arc<T>> {
        // 使用 unwrap_or_else 处理锁中毒:即使锁中毒也能恢复数据并继续读取
        let tools = self.tools.read().unwrap_or_else(|p| p.into_inner());
        tools
            .get(name)
            .and_then(|tool| tool.clone().downcast::<T>().ok())
    }

    /// 获取 Token 管理器
    #[cfg(feature = "token")]
    pub fn token_manager(&self) -> &TokenManager {
        &self.token_manager
    }

    /// 初始化全局 GlobalTools 单例(启用 token feature)
    ///
    /// 使用 `OnceLock` 保证只能初始化一次,线程安全。
    ///
    /// # 参数
    ///
    /// - `token_manager`: JWT 令牌管理器
    ///
    /// # 返回
    ///
    /// - `Ok(())`: 初始化成功
    /// - `Err(BaseError::ConfigError)`: 已经初始化过,重复调用
    ///
    /// # 错误
    ///
    /// - `BaseError::ConfigError("GlobalTools 已初始化")`: 重复初始化时返回
    #[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()))
    }

    /// 初始化全局 GlobalTools 单例(未启用 token feature)
    ///
    /// 使用 `OnceLock` 保证只能初始化一次,线程安全。
    ///
    /// # 返回
    ///
    /// - `Ok(())`: 初始化成功
    /// - `Err(BaseError::ConfigError)`: 已经初始化过,重复调用
    ///
    /// # 错误
    ///
    /// - `BaseError::ConfigError("GlobalTools 已初始化")`: 重复初始化时返回
    #[cfg(not(feature = "token"))]
    pub fn init() -> Result<(), BaseError> {
        // 尝试设置全局单例,若已初始化则返回错误
        GLOBAL_TOOLS
            .set(Arc::new(GlobalTools::new()))
            .map_err(|_| BaseError::ConfigError("GlobalTools 已初始化".to_string()))
    }

    /// 获取全局 GlobalTools 单例引用
    ///
    /// # 返回
    ///
    /// - `Ok(&'static GlobalTools)`: 全局实例的静态引用
    /// - `Err(BaseError::ConfigError)`: 尚未初始化
    ///
    /// # 错误
    ///
    /// - `BaseError::ConfigError("GlobalTools 未初始化")`: 在调用 `init` 之前调用此方法时返回
    pub fn get() -> Result<&'static GlobalTools, BaseError> {
        // 获取全局单例,若未初始化则返回错误
        GLOBAL_TOOLS
            .get()
            .map(|arc| arc.as_ref())
            .ok_or_else(|| BaseError::ConfigError("GlobalTools 未初始化".to_string()))
    }

    /// 获取全局 GlobalTools 的 Arc 引用(内部使用)
    ///
    /// 返回 Arc 克隆,允许将全局单例嵌入到 ActionContext 中
    pub(crate) fn get_arc() -> Result<Arc<GlobalTools>, BaseError> {
        // 获取全局单例的 Arc 克隆(廉价操作)
        GLOBAL_TOOLS
            .get()
            .cloned()
            .ok_or_else(|| BaseError::ConfigError("GlobalTools 未初始化".to_string()))
    }
}

/// Action 执行上下文
///
/// 包含 Action 执行所需的所有信息,包括请求数据、用户信息、全局工具和表配置。
#[derive(Debug)]
pub struct ActionContext {
    /// 请求数据
    pub request: Request,
    /// 当前用户(已认证)
    pub user: Option<User>,
    /// 全局工具
    pub tools: Arc<GlobalTools>,
    /// 表配置(如果 action 关联表)
    pub table_config: Option<Arc<TableConfig>>,
}

impl ActionContext {
    /// 创建新的上下文
    pub fn new(request: Request, tools: Arc<GlobalTools>) -> Self {
        Self {
            request,
            user: None,
            tools,
            table_config: None,
        }
    }

    /// 使用全局单例创建新的上下文
    ///
    /// 自动从全局单例获取 `GlobalTools`,无需手动传入。
    ///
    /// # 参数
    ///
    /// - `request`: 请求数据
    ///
    /// # 返回
    ///
    /// - `Ok(ActionContext)`: 创建成功
    /// - `Err(BaseError::ConfigError)`: 全局单例未初始化
    ///
    /// # 错误
    ///
    /// - `BaseError::ConfigError("GlobalTools 未初始化")`: 在调用 `GlobalTools::init` 之前调用此方法时返回
    pub fn new_with_global_tools(request: Request) -> Result<Self, BaseError> {
        // 从全局单例获取 GlobalTools 的 Arc 克隆(廉价操作)
        let tools = GlobalTools::get_arc()?;
        Ok(Self {
            request,
            user: None,
            tools,
            table_config: None,
        })
    }

    /// 设置用户(链式调用)
    pub fn with_user(mut self, user: User) -> Self {
        self.user = Some(user);
        self
    }

    /// 设置表配置(链式调用)
    pub fn with_table_config(mut self, config: Arc<TableConfig>) -> Self {
        self.table_config = Some(config);
        self
    }

    /// 获取请求体参数(必填)
    ///
    /// 从请求体中获取指定参数,如果参数不存在或类型不匹配则返回错误。
    ///
    /// # 参数
    ///
    /// - `key`: 参数名
    ///
    /// # 返回
    ///
    /// - `Ok(T)`: 参数值
    /// - `Err(BaseError::ParamMissing)`: 参数不存在
    /// - `Err(BaseError::ParamInvalid)`: 参数类型不匹配
    pub fn param<T: DeserializeOwned>(&self, key: &str) -> Result<T, BaseError> {
        let value = self
            .request
            .body
            .get(key)
            .ok_or_else(|| BaseError::ParamMissing(key.to_string()))?;

        serde_json::from_value(value.clone()).map_err(|_| {
            BaseError::ParamInvalid(key.to_string(), "无法将参数转换为目标类型".to_string())
        })
    }

    /// 获取请求体参数(可选,宽松模式)
    ///
    /// 从请求体中获取指定参数,如果参数不存在或类型不匹配则返回 None。
    /// 类型不匹配时会记录 warn 日志,但不返回错误。
    ///
    /// 与 [`param_optional_strict`] 的区别:
    /// - `param_optional`:类型不匹配时静默返回 `None`(宽松模式)
    /// - `param_optional_strict`:类型不匹配时返回 `Err`(严格模式)
    ///
    /// # 参数
    ///
    /// - `key`: 参数名
    ///
    /// # 返回
    ///
    /// - `Some(T)`: 参数值
    /// - `None`: 参数不存在或类型不匹配
    pub fn param_optional<T: DeserializeOwned>(&self, key: &str) -> Option<T> {
        let result = self
            .request
            .body
            .get(key)
            .and_then(|v| serde_json::from_value::<T>(v.clone()).ok());
        // 若参数存在但类型不匹配,记录警告日志
        if result.is_none() && self.request.body.get(key).is_some() {
            log::warn!(
                "param_optional: 参数 '{}' 存在但类型不匹配,已静默返回 None",
                key
            );
        }
        result
    }

    /// 获取请求体参数(可选,严格模式)
    ///
    /// 从请求体中获取指定参数:
    /// - 参数不存在:返回 `Ok(None)`
    /// - 参数存在且类型匹配:返回 `Ok(Some(T))`
    /// - 参数存在但类型不匹配:返回 `Err(BaseError::ParamInvalid)`
    ///
    /// 与 [`param_optional`] 的区别:
    /// - `param_optional`:类型不匹配时静默返回 `None`(宽松模式)
    /// - `param_optional_strict`:类型不匹配时返回错误(严格模式),适用于需要明确感知类型错误的场景
    ///
    /// # 参数
    ///
    /// - `key`: 参数名
    ///
    /// # 返回
    ///
    /// - `Ok(Some(T))`: 参数存在且类型匹配
    /// - `Ok(None)`: 参数不存在
    /// - `Err(BaseError::ParamInvalid)`: 参数存在但类型不匹配
    pub fn param_optional_strict<T: DeserializeOwned>(
        &self,
        key: &str,
    ) -> Result<Option<T>, BaseError> {
        match self.request.body.get(key) {
            // 参数不存在,返回 None
            None => Ok(None),
            // 参数存在,尝试反序列化
            Some(value) => serde_json::from_value::<T>(value.clone())
                .map(Some)
                .map_err(|_| {
                    BaseError::ParamInvalid(
                        key.to_string(),
                        format!("参数 '{}' 存在但无法转换为目标类型", key),
                    )
                }),
        }
    }

    /// 获取路径参数(必填)
    ///
    /// 从 `request.path_params` 中获取指定路径参数,并尝试反序列化为目标类型。
    ///
    /// # 参数
    ///
    /// - `key`: 路径参数名
    ///
    /// # 返回
    ///
    /// - `Ok(T)`: 参数值
    /// - `Err(BaseError::ParamMissing)`: 路径参数不存在
    /// - `Err(BaseError::ParamInvalid)`: 参数值无法转换为目标类型
    pub fn path_param<T: DeserializeOwned>(&self, key: &str) -> Result<T, BaseError> {
        // 从路径参数中获取字符串值
        let raw = self
            .request
            .path_params
            .get(key)
            .ok_or_else(|| BaseError::ParamMissing(key.to_string()))?;

        // 将字符串包装为 JSON 字符串后反序列化,支持数字、布尔等类型
        let json_val = serde_json::Value::String(raw.clone());
        serde_json::from_value(json_val).map_err(|_| {
            BaseError::ParamInvalid(
                key.to_string(),
                format!("路径参数 '{}' 无法转换为目标类型,原始值: {}", key, raw),
            )
        })
    }

    /// 获取查询参数(必填)
    ///
    /// 从 `request.query` 中获取指定查询参数,并通过 `FromStr` 解析为目标类型。
    ///
    /// # 参数
    ///
    /// - `key`: 查询参数名
    ///
    /// # 返回
    ///
    /// - `Ok(T)`: 参数值
    /// - `Err(BaseError::ParamMissing)`: 查询参数不存在
    /// - `Err(BaseError::ParamInvalid)`: 参数值无法解析为目标类型
    pub fn query_param<T: FromStr>(&self, key: &str) -> Result<T, BaseError> {
        // 从查询参数中获取字符串值
        let raw = self
            .request
            .query
            .get(key)
            .ok_or_else(|| BaseError::ParamMissing(key.to_string()))?;

        // 通过 FromStr 解析为目标类型
        raw.parse::<T>().map_err(|_| {
            BaseError::ParamInvalid(
                key.to_string(),
                format!("查询参数 '{}' 无法解析为目标类型,原始值: {}", key, raw),
            )
        })
    }

    /// 获取请求体参数,不存在时返回默认值
    ///
    /// 从请求体中获取指定参数,如果参数不存在或类型不匹配则返回提供的默认值。
    ///
    /// # 参数
    ///
    /// - `key`: 参数名
    /// - `default`: 参数不存在或类型不匹配时的默认值
    ///
    /// # 返回
    ///
    /// - `T`: 参数值或默认值
    pub fn param_or<T: DeserializeOwned>(&self, key: &str, default: T) -> T {
        self.request
            .body
            .get(key)
            .and_then(|v| serde_json::from_value(v.clone()).ok())
            .unwrap_or(default)
    }

    /// 创建表查询构建器
    ///
    /// 基于当前上下文的表配置和用户角色创建 TableQuery 实例。
    ///
    /// # 返回
    ///
    /// - `Ok(TableQuery)`: 查询构建器
    /// - `Err(BaseError::TableConfigNotSet)`: 表配置未设置
    pub fn table_query(&self) -> Result<TableQuery, BaseError> {
        let config = self
            .table_config
            .as_ref()
            .ok_or(BaseError::TableConfigNotSet)?;

        // 通过 user_roles_slice 获取借用,再转换为 Arc<[String]>
        let user_roles: Arc<[String]> = Arc::from(self.user_roles_slice().to_vec());

        Ok(TableQuery::new(config.clone(), user_roles, None))
    }

    /// 获取用户角色列表(克隆)
    ///
    /// # 返回
    ///
    /// - 用户角色列表(如果用户未登录则返回空列表)
    pub fn user_roles(&self) -> Vec<String> {
        self.user
            .as_ref()
            .map(|u| u.roles.clone())
            .unwrap_or_default()
    }

    /// 获取用户角色列表(借用切片,避免克隆)
    ///
    /// 返回用户角色的借用切片,避免不必要的内存分配。
    /// 如果用户未登录则返回空切片。
    ///
    /// # 返回
    ///
    /// - `&[String]`: 用户角色切片引用
    pub fn user_roles_slice(&self) -> &[String] {
        self.user
            .as_ref()
            .map(|u| u.roles.as_slice())
            .unwrap_or(&[])
    }
}