Skip to main content

yang_base/action/
context.rs

1//! Action 执行上下文
2//!
3//! 提供 Action 执行所需的上下文环境,包含请求信息、用户信息、应用资源和表配置。
4//!
5//! # 主要组件
6//!
7//! - `ActionContext`:Action 执行上下文结构
8//! - `User`:用户信息(占位符,后续实现)
9//! - [`Tools`](crate::tools::Tools):由当前应用实例显式拥有的冻结资源
10
11use crate::definition::{Plugins, Registry};
12use crate::error::BaseError;
13use crate::table::{TableDefinition, TableQuery, Tables};
14use crate::tools::Tools;
15use serde::de::DeserializeOwned;
16use std::collections::HashSet;
17use std::sync::Arc;
18
19use super::Request;
20use super::RequestId;
21use super::RequestMeta;
22use super::{ActorContext, RequestContext, SystemTenantCapability, TenantContext};
23
24/// 用户信息
25///
26/// 标注 `#[non_exhaustive]`:未来新增字段不构成破坏性变更。
27/// 请使用 [`User::new`] 构造,再通过字段赋值设置可选属性。
28#[derive(Debug, Clone)]
29#[non_exhaustive]
30pub struct User {
31    /// 用户 ID
32    pub id: i64,
33    /// 用户名
34    pub username: String,
35    /// 昵称
36    pub nickname: String,
37    /// 邮箱
38    pub email: String,
39    /// 角色集合(HashSet 保证 O(1) 查找)
40    pub roles: HashSet<String>,
41    /// 权限集合(HashSet 保证 O(1) 查找)
42    pub permissions: HashSet<String>,
43}
44
45impl User {
46    /// 创建新用户(空角色/权限)
47    pub fn new(id: i64, username: impl Into<String>) -> Self {
48        Self {
49            id,
50            username: username.into(),
51            nickname: String::new(),
52            email: String::new(),
53            roles: HashSet::new(),
54            permissions: HashSet::new(),
55        }
56    }
57
58    /// 设置角色集合(替换现有角色)
59    pub fn with_roles(mut self, roles: impl IntoIterator<Item = impl Into<String>>) -> Self {
60        self.roles = roles.into_iter().map(Into::into).collect();
61        self
62    }
63
64    /// 设置权限集合(替换现有权限)
65    pub fn with_permissions(
66        mut self,
67        permissions: impl IntoIterator<Item = impl Into<String>>,
68    ) -> Self {
69        self.permissions = permissions.into_iter().map(Into::into).collect();
70        self
71    }
72
73    /// 检查是否有指定权限(O(1) HashSet 查找)
74    pub fn has_permission(&self, permission: &str) -> bool {
75        self.permissions.contains(permission)
76    }
77
78    /// 检查是否有指定角色(O(1) HashSet 查找)
79    pub fn has_role(&self, role: &str) -> bool {
80        self.roles.contains(role)
81    }
82
83    /// 检查是否有任一角色(O(1) 每角色)
84    pub fn has_any_role(&self, roles: &[String]) -> bool {
85        roles.iter().any(|r| self.has_role(r))
86    }
87}
88
89/// 当前请求的互斥租户访问状态。
90///
91/// 单一代数和类型确保普通租户与系统 capability 不会同时存在,也避免用
92/// `Option<TenantContext>` 表达系统绕过。
93#[derive(Debug, Clone, Copy, Default)]
94enum TenantAccess {
95    #[default]
96    Missing,
97    Tenant(TenantContext),
98    System(SystemTenantCapability),
99}
100
101/// Action 执行上下文
102///
103/// 包含 Action 执行所需的所有信息,包括请求数据、传输元数据、用户信息、应用资源和表配置。
104///
105/// 标注 `#[non_exhaustive]`:未来新增运行期字段(如 trace_id)不构成破坏性变更,
106/// 调用方请用 [`ActionContext::new`] 构造,而非结构体字面量。
107#[derive(Debug)]
108#[non_exhaustive]
109pub struct ActionContext {
110    /// 请求数据
111    pub request: Request,
112    /// 与具体 Web 框架无关的传输元数据。
113    pub request_meta: RequestMeta,
114    /// 当前用户(已认证)
115    // SAFETY: 此字段为 pub(crate),仅 crate 内中间件(如 TokenAuthMiddleware)可注入。
116    // 外部 crate 无法直接设置此字段,防止绕过认证。
117    pub(crate) user: Option<User>,
118    /// 当前应用实例拥有的冻结资源。
119    tools: Arc<Tools>,
120    /// 当前 App 的冻结 Action Registry;仅 BuiltApp 创建的上下文具备。
121    registry: Option<Arc<Registry>>,
122    /// 不可变表定义(如果 Action 关联表)。
123    table_definition: Option<TableDefinition>,
124    /// 本次派发的运行期标识,用于串联日志/span/metrics/审计。
125    ///
126    /// 由 `new` 默认生成;`RequestIdMiddleware` 在洋葱链
127    /// 最外层会按上游 `X-Request-Id` 透传或重新生成并 `span.record`。
128    pub request_id: RequestId,
129    /// 本次派发所属模块名(由 `Registry::dispatch` 注入)。
130    ///
131    /// 仅用于可观测性标注(metrics `module` 标签、日志)。模块数量有界,作为 metrics
132    /// 标签不构成高基数问题。未经路由直接构造的上下文为 `None`。
133    pub module: Option<String>,
134    /// 本次派发的 Action 名(由 `Registry::dispatch` 可信注入)。
135    ///
136    /// 与 `module` 共同标识当前实际执行目标;外部构造的上下文不能伪造此字段。
137    action: Option<String>,
138    /// PERF-13: 缓存用户角色的 Arc 副本,避免 table_query() 每次重新 Arc 化。
139    /// 在 `with_user()` 时一次性构建,后续 `table_query()` 仅需 `Arc::clone`(O(1))。
140    cached_roles: Arc<[String]>,
141    /// 当前请求独占的类型化扩展上下文。
142    request_context: RequestContext,
143    /// 普通租户、系统 capability 或缺失三者互斥的访问状态。
144    tenant_access: TenantAccess,
145}
146
147impl Clone for ActionContext {
148    fn clone(&self) -> Self {
149        // RequestContext 含 `Box<dyn Any>` 不可 Clone;克隆副本重建空的
150        // 请求扩展集合——扩展值只属于原始请求生命周期,副本按无扩展降级。
151        Self {
152            request: self.request.clone(),
153            request_meta: self.request_meta.clone(),
154            user: self.user.clone(),
155            tools: Arc::clone(&self.tools),
156            registry: self.registry.clone(),
157            table_definition: self.table_definition.clone(),
158            request_id: self.request_id,
159            module: self.module.clone(),
160            action: self.action.clone(),
161            cached_roles: Arc::clone(&self.cached_roles),
162            request_context: RequestContext::default(),
163            tenant_access: self.tenant_access,
164        }
165    }
166}
167
168impl ActionContext {
169    /// 创建新的上下文
170    pub fn new(request: Request, tools: Arc<Tools>) -> Self {
171        Self {
172            request,
173            request_meta: RequestMeta::default(),
174            user: None,
175            tools,
176            registry: None,
177            table_definition: None,
178            request_id: RequestId::generate(),
179            module: None,
180            action: None,
181            cached_roles: Arc::from(Vec::new()),
182            request_context: RequestContext::default(),
183            tenant_access: TenantAccess::Missing,
184        }
185    }
186
187    /// 返回当前应用实例的冻结资源。
188    pub fn tools(&self) -> &Tools {
189        &self.tools
190    }
191
192    /// 获取当前应用配置的 HTTP 客户端(`http` feature)。
193    ///
194    /// 委托给 [`Tools::http`]:未配置时返回 `BaseError::HttpClientNotInitialized`,
195    /// Tools 生命周期已结束时返回对应错误。
196    #[cfg(feature = "http")]
197    pub fn http(&self) -> Result<&crate::http::HttpClient, BaseError> {
198        self.tools.http()
199    }
200
201    /// 从 Tools 配置槽解析慢查询阈值。
202    ///
203    /// 未注册 [`ObservabilityConfig`](crate::observability::ObservabilityConfig) 时返回
204    /// `None`(关闭慢查询日志),与历史上全局单例未初始化的行为一致。
205    fn slow_query_threshold(&self) -> Option<std::time::Duration> {
206        self.tools
207            .config::<crate::observability::ObservabilityConfig>()
208            .ok()
209            .and_then(|config| config.slow_query_threshold)
210    }
211
212    /// 返回当前请求独占的类型化上下文。
213    pub fn request_context(&mut self) -> &mut RequestContext {
214        &mut self.request_context
215    }
216
217    /// 注入普通租户 capability。
218    pub fn with_tenant(mut self, tenant: TenantContext) -> Self {
219        self.tenant_access = TenantAccess::Tenant(tenant);
220        self
221    }
222
223    pub(crate) fn with_system_tenant(mut self, capability: SystemTenantCapability) -> Self {
224        self.tenant_access = TenantAccess::System(capability);
225        self
226    }
227
228    /// 返回不可选的普通租户 capability。
229    pub fn tenant(&self) -> Result<TenantContext, BaseError> {
230        match self.tenant_access {
231            TenantAccess::Tenant(tenant) => Ok(tenant),
232            TenantAccess::Missing | TenantAccess::System(_) => Err(BaseError::Unauthorized(
233                "请求缺少普通租户 capability".to_string(),
234            )),
235        }
236    }
237
238    /// 返回当前请求已获授的系统级租户 capability。
239    pub fn system_tenant(&self) -> Result<SystemTenantCapability, BaseError> {
240        match self.tenant_access {
241            TenantAccess::System(capability) => Ok(capability),
242            TenantAccess::Missing | TenantAccess::Tenant(_) => Err(BaseError::PermissionDenied(
243                "请求缺少系统租户 capability".to_string(),
244            )),
245        }
246    }
247
248    /// 返回当前操作者上下文。
249    pub fn actor(&self) -> Result<ActorContext, BaseError> {
250        self.user
251            .as_ref()
252            .map(|user| ActorContext::new(user.id))
253            .ok_or_else(|| BaseError::Unauthorized("请求缺少已认证操作者".to_string()))
254    }
255
256    /// 返回请求标识。
257    pub fn request_id(&self) -> RequestId {
258        self.request_id
259    }
260
261    pub(crate) fn with_registry(mut self, registry: Arc<Registry>) -> Self {
262        self.registry = Some(registry);
263        self
264    }
265
266    /// 消费当前请求上下文并创建强类型内部 Action 调用器。
267    pub fn plugins(self) -> Result<Plugins, BaseError> {
268        let registry = self.registry.as_ref().cloned().ok_or_else(|| {
269            BaseError::ConfigError("ActionContext 未绑定应用 Registry".to_string())
270        })?;
271        Ok(Plugins::new(registry, self))
272    }
273
274    /// 设置用户(链式调用)
275    ///
276    /// 仅供 crate 内中间件/内部使用。调用方有责任确保 user 已经过认证(如 TokenAuthMiddleware),
277    /// 直接注入未验证的 User 将绕过所有鉴权。
278    #[allow(dead_code)]
279    pub(crate) fn with_user(mut self, user: User) -> Self {
280        let mut roles = user.roles.iter().cloned().collect::<Vec<_>>();
281        roles.sort_unstable();
282        self.cached_roles = Arc::from(roles);
283        self.user = Some(user);
284        self
285    }
286
287    /// 获取已认证用户的只读引用。
288    ///
289    /// 外部调用方只能读取认证结果,不能手动注入用户;用户注入仅由 crate 内受信任
290    /// 中间件(如 `TokenAuthMiddleware`)完成。
291    pub fn authenticated_user(&self) -> Option<&User> {
292        self.user.as_ref()
293    }
294
295    /// 按当前请求认证身份返回可访问的版本化 UI 目录。
296    ///
297    /// 目录过滤与真实 Action dispatch 复用同一份构建期授权策略。
298    pub fn ui_catalog(&self) -> Result<crate::definition::UiCatalog, BaseError> {
299        let registry = self.registry.as_ref().ok_or_else(|| {
300            BaseError::ConfigError("ActionContext 未绑定应用 Registry".to_string())
301        })?;
302        registry.ui_catalog(self)
303    }
304
305    /// 设置本次派发的 request_id(链式调用)
306    ///
307    /// 通常由 `RequestIdMiddleware` 在洋葱链最外层调用以透传上游标识;
308    /// 业务侧一般无需手动设置。
309    pub fn with_request_id(mut self, request_id: RequestId) -> Self {
310        self.request_id = request_id;
311        self
312    }
313
314    /// 注入由传输适配器构造的请求元数据(链式调用)。
315    pub fn with_request_meta(mut self, request_meta: RequestMeta) -> Self {
316        self.request_meta = request_meta;
317        self
318    }
319
320    /// 设置所属模块名(链式调用)。
321    ///
322    /// 由 `Registry::dispatch` 注入,用于 metrics `module` 标签等可观测性标注。
323    pub fn with_module(mut self, module: impl Into<String>) -> Self {
324        self.module = Some(module.into());
325        self
326    }
327
328    /// 返回当前实际派发的 `module` 与 `action`。
329    ///
330    /// 该身份由 `Registry` 在进入中间件链前覆盖注入,可供安全中间件绑定目标;
331    /// 未经 Registry 派发而直接构造的上下文返回 `None`。
332    pub fn dispatch_target(&self) -> Option<(&str, &str)> {
333        Some((self.module.as_deref()?, self.action.as_deref()?))
334    }
335
336    /// 覆盖注入当前实际派发目标,防止调用方预置的可观测性字段参与安全判断。
337    pub(crate) fn with_dispatch_target(
338        mut self,
339        module: impl Into<String>,
340        action: impl Into<String>,
341    ) -> Self {
342        self.module = Some(module.into());
343        self.action = Some(action.into());
344        self
345    }
346
347    /// 设置表定义(链式调用)。
348    pub fn with_table_definition(mut self, definition: TableDefinition) -> Self {
349        self.table_definition = Some(definition);
350        self
351    }
352
353    /// 返回当前 Action 绑定的表定义。
354    pub fn table_definition(&self) -> Result<&TableDefinition, BaseError> {
355        self.table_definition
356            .as_ref()
357            .ok_or(BaseError::TableDefinitionNotSet)
358    }
359
360    /// 零拷贝版本:用 `std::mem::take` 替代 clone 请求体。
361    ///
362    /// 调用后 `self.request.body` 变为 `Value::Null`,仅在不再需要 body 时使用。
363    /// 仅限 crate 内部使用(`DynAction::dispatch` blanket impl 中 ctx 仅需传给 handle)。
364    pub(crate) fn extract_input_owned<I: DeserializeOwned>(&mut self) -> Result<I, BaseError> {
365        let body = std::mem::take(&mut self.request.body);
366        serde_json::from_value(body)
367            .map_err(|e| BaseError::ParamInvalid("body".to_string(), e.to_string()))
368    }
369
370    /// 创建表查询构建器
371    ///
372    /// 基于当前上下文的表配置和用户角色创建 TableQuery 实例。启用 `mysql`
373    /// feature 时,从当前上下文的 [`Tools`] 注入共享连接池,使内置 CRUD Action
374    /// 能直接执行数据库操作;若应用未配置数据库,则返回
375    /// `BaseError::DatabaseNotInitialized`。
376    ///
377    /// # 返回
378    ///
379    /// - `Ok(TableQuery)`: 查询构建器
380    /// - `Err(BaseError::TableDefinitionNotSet)`: 表定义未设置
381    fn base_table_query(&self, definition: &TableDefinition) -> Result<TableQuery, BaseError> {
382        // 启用 mysql feature 时,从当前应用资源注入连接池。
383        #[cfg(feature = "mysql")]
384        let pool = self
385            .tools
386            .optional_mysql()?
387            .map(|database| Arc::new(database.pool().clone()));
388        #[cfg(not(feature = "mysql"))]
389        let pool = None;
390
391        // 注入可观测性:慢查询阈值(Tools 配置槽)+ 本次派发 request_id,
392        // 使受保护层执行边界能在超阈值时 warn 并串联 request_id。
393        let slow_threshold = self.slow_query_threshold();
394        Ok(TableQuery::new(
395            definition.shared_config(),
396            Arc::clone(&self.cached_roles),
397            pool,
398        )
399        .with_slow_threshold(slow_threshold)
400        .with_request_id(self.request_id)
401        .with_regex_cache(self.tools.regex_cache().clone()))
402    }
403
404    /// 创建默认失败关闭的表查询构建器。
405    ///
406    /// 带 tenant key 的表必须存在普通 [`TenantContext`],并始终自动施加租户条件。
407    /// 系统身份不会隐式绕过;全域访问必须显式调用
408    /// [`ActionContext::system_table_query`]。
409    pub fn table_query(&self) -> Result<TableQuery, BaseError> {
410        let definition = self.table_definition()?;
411        let mut query = self.base_table_query(definition)?;
412        if let Some(field) = definition.tenant_key_field() {
413            query = query.scope_tenant(field, serde_json::json!(self.tenant()?.id().get()))?;
414        }
415        Ok(query)
416    }
417
418    /// 使用显式、已绑定当前请求 actor 的系统 capability 创建全域表查询。
419    ///
420    /// 调用方必须先通过 [`ActionContext::system_tenant`] 取得 capability,再在具体
421    /// repository 旁路中显式传回;普通 CRUD 只调用 [`ActionContext::table_query`],
422    /// 因而不会自动获得全租户访问。
423    pub fn system_table_query(
424        &self,
425        capability: SystemTenantCapability,
426    ) -> Result<TableQuery, BaseError> {
427        if self.system_tenant()? != capability {
428            return Err(BaseError::PermissionDenied(
429                "系统租户 capability 与当前请求不匹配".to_string(),
430            ));
431        }
432        let definition = self.table_definition()?;
433        self.base_table_query(definition)
434    }
435
436    /// 创建 BR 心智连续的 Tables 入口。
437    pub fn tables(&self) -> Result<Tables, BaseError> {
438        self.table_query().map(Tables::new)
439    }
440
441    /// 使用显式系统 capability 创建全域 Tables 入口。
442    pub fn system_tables(&self, capability: SystemTenantCapability) -> Result<Tables, BaseError> {
443        self.system_table_query(capability).map(Tables::new)
444    }
445
446    /// 开启一个数据库事务(受保护层多步写的原子作用域)
447    ///
448    /// 返回 [`yang_db::Transaction`],可传入 `TableQuery` 的 `*_in_tx` 系列方法
449    /// (`insert_in_tx`/`update_in_tx`/`delete_in_tx`/`select_in_tx` 等),使受
450    /// 权限/校验/软删保护的多步写在同一事务内原子提交或整体回滚。调用方负责
451    /// 显式 `commit()`;若 `Transaction` 在未提交时被 drop,sqlx 会尽力回滚。
452    ///
453    /// 仅在启用 `mysql` feature 时可用。
454    ///
455    /// # 返回
456    ///
457    /// - `Ok(Transaction)`:活动事务
458    /// - `Err(BaseError::DatabaseNotInitialized)`:当前应用未配置数据库
459    /// - `Err(BaseError::DatabaseTransactionFailed)`:开启事务失败
460    ///
461    /// # 示例
462    ///
463    /// ```rust,ignore
464    /// let mut tx = ctx.begin_transaction().await?;
465    /// let id = ctx.table_query()?.insert_returning_id_in_tx(&mut tx, parent).await?.1;
466    /// ctx.table_query()?.insert_in_tx(&mut tx, child_with(id)).await?;
467    /// tx.commit().await?;
468    /// ```
469    #[cfg(feature = "mysql")]
470    pub async fn begin_transaction(&self) -> Result<yang_db::Transaction, BaseError> {
471        self.tools
472            .mysql()?
473            .transaction()
474            .await
475            .map_err(BaseError::DatabaseTransactionFailed)
476    }
477
478    /// 获取用户角色列表(克隆为 Vec)
479    ///
480    /// # 返回
481    ///
482    /// - 用户角色列表(如果用户未登录则返回空列表)
483    pub fn user_roles(&self) -> Vec<String> {
484        self.user
485            .as_ref()
486            .map(|u| u.roles.iter().cloned().collect())
487            .unwrap_or_default()
488    }
489
490    /// 获取用户角色集合引用
491    ///
492    /// 返回用户角色的 HashSet 引用,支持 O(1) 包含检查。
493    /// 如果用户未登录则返回 `None`。
494    ///
495    /// # 返回
496    ///
497    /// - `Some(&HashSet<String>)`: 用户角色集合引用
498    /// - `None`: 用户未登录
499    pub fn user_roles_set(&self) -> Option<&HashSet<String>> {
500        self.user.as_ref().map(|u| &u.roles)
501    }
502}
503
504#[cfg(test)]
505mod tests {
506    use super::*;
507    use crate::observability::ObservabilityConfig;
508    use crate::tools::ToolsBuilder;
509    use std::time::Duration;
510
511    fn empty_context() -> ActionContext {
512        let tools = Arc::new(ToolsBuilder::new().build().expect("空 Tools 应构建成功"));
513        ActionContext::new(Request::new(serde_json::json!({})), tools)
514    }
515
516    #[cfg(feature = "http")]
517    #[test]
518    fn http_shortcut_returns_client_when_configured() {
519        let tools = Arc::new(
520            ToolsBuilder::new()
521                .http(crate::http::HttpClient::new(30).expect("测试 HTTP 客户端应创建成功"))
522                .build()
523                .expect("配置 HTTP 客户端后应构建成功"),
524        );
525        let context = ActionContext::new(Request::new(serde_json::json!({})), tools);
526
527        let client = context.http().expect("已配置时 ctx.http() 应可用");
528        let _builder = client.get("https://api.example.com/test");
529    }
530
531    #[cfg(feature = "http")]
532    #[test]
533    fn http_shortcut_errors_when_not_configured() {
534        let context = empty_context();
535
536        assert!(matches!(
537            context.http(),
538            Err(BaseError::HttpClientNotInitialized)
539        ));
540    }
541
542    #[test]
543    fn slow_query_threshold_is_none_without_registered_config() {
544        let context = empty_context();
545
546        assert_eq!(context.slow_query_threshold(), None);
547    }
548
549    #[test]
550    fn slow_query_threshold_reads_from_tools_config_slot() {
551        let threshold = Duration::from_millis(200);
552        let tools = Arc::new(
553            ToolsBuilder::new()
554                .config(ObservabilityConfig::new().with_slow_query_threshold(threshold))
555                .build()
556                .expect("注册可观测性配置后应构建成功"),
557        );
558        let context = ActionContext::new(Request::new(serde_json::json!({})), tools);
559
560        assert_eq!(context.slow_query_threshold(), Some(threshold));
561    }
562
563    #[test]
564    fn authenticated_roles_are_cached_once_in_stable_order() {
565        let context = empty_context()
566            .with_user(User::new(1, "alice").with_roles(["operator", "admin", "operator"]));
567
568        assert_eq!(
569            context.cached_roles.as_ref(),
570            ["admin".to_string(), "operator".to_string()]
571        );
572        assert_eq!(
573            context.user_roles_set(),
574            Some(&HashSet::from([
575                "admin".to_string(),
576                "operator".to_string()
577            ]))
578        );
579    }
580
581    #[test]
582    fn ui_catalog_rejects_context_without_bound_registry() {
583        let context = empty_context();
584
585        assert!(matches!(
586            context.ui_catalog(),
587            Err(BaseError::ConfigError(message))
588                if message == "ActionContext 未绑定应用 Registry"
589        ));
590    }
591}