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 ActionContext {
148    /// 创建新的上下文
149    pub fn new(request: Request, tools: Arc<Tools>) -> Self {
150        Self {
151            request,
152            request_meta: RequestMeta::default(),
153            user: None,
154            tools,
155            registry: None,
156            table_definition: None,
157            request_id: RequestId::generate(),
158            module: None,
159            action: None,
160            cached_roles: Arc::from(Vec::new()),
161            request_context: RequestContext::default(),
162            tenant_access: TenantAccess::Missing,
163        }
164    }
165
166    /// 返回当前应用实例的冻结资源。
167    pub fn tools(&self) -> &Tools {
168        &self.tools
169    }
170
171    /// 获取当前应用配置的 HTTP 客户端(`http` feature)。
172    ///
173    /// 委托给 [`Tools::http`]:未配置时返回 `BaseError::HttpClientNotInitialized`,
174    /// Tools 生命周期已结束时返回对应错误。
175    #[cfg(feature = "http")]
176    pub fn http(&self) -> Result<&crate::http::HttpClient, BaseError> {
177        self.tools.http()
178    }
179
180    /// 从 Tools 配置槽解析慢查询阈值。
181    ///
182    /// 未注册 [`ObservabilityConfig`](crate::observability::ObservabilityConfig) 时返回
183    /// `None`(关闭慢查询日志),与历史上全局单例未初始化的行为一致。
184    fn slow_query_threshold(&self) -> Option<std::time::Duration> {
185        self.tools
186            .config::<crate::observability::ObservabilityConfig>()
187            .ok()
188            .and_then(|config| config.slow_query_threshold)
189    }
190
191    /// 返回当前请求独占的类型化上下文。
192    pub fn request_context(&mut self) -> &mut RequestContext {
193        &mut self.request_context
194    }
195
196    /// 注入普通租户 capability。
197    pub fn with_tenant(mut self, tenant: TenantContext) -> Self {
198        self.tenant_access = TenantAccess::Tenant(tenant);
199        self
200    }
201
202    pub(crate) fn with_system_tenant(mut self, capability: SystemTenantCapability) -> Self {
203        self.tenant_access = TenantAccess::System(capability);
204        self
205    }
206
207    /// 返回不可选的普通租户 capability。
208    pub fn tenant(&self) -> Result<TenantContext, BaseError> {
209        match self.tenant_access {
210            TenantAccess::Tenant(tenant) => Ok(tenant),
211            TenantAccess::Missing | TenantAccess::System(_) => Err(BaseError::Unauthorized(
212                "请求缺少普通租户 capability".to_string(),
213            )),
214        }
215    }
216
217    /// 返回当前请求已获授的系统级租户 capability。
218    pub fn system_tenant(&self) -> Result<SystemTenantCapability, BaseError> {
219        match self.tenant_access {
220            TenantAccess::System(capability) => Ok(capability),
221            TenantAccess::Missing | TenantAccess::Tenant(_) => Err(BaseError::PermissionDenied(
222                "请求缺少系统租户 capability".to_string(),
223            )),
224        }
225    }
226
227    /// 返回当前操作者上下文。
228    pub fn actor(&self) -> Result<ActorContext, BaseError> {
229        self.user
230            .as_ref()
231            .map(|user| ActorContext::new(user.id))
232            .ok_or_else(|| BaseError::Unauthorized("请求缺少已认证操作者".to_string()))
233    }
234
235    /// 返回请求标识。
236    pub fn request_id(&self) -> RequestId {
237        self.request_id
238    }
239
240    pub(crate) fn with_registry(mut self, registry: Arc<Registry>) -> Self {
241        self.registry = Some(registry);
242        self
243    }
244
245    /// 消费当前请求上下文并创建强类型内部 Action 调用器。
246    pub fn plugins(self) -> Result<Plugins, BaseError> {
247        let registry = self.registry.as_ref().cloned().ok_or_else(|| {
248            BaseError::ConfigError("ActionContext 未绑定应用 Registry".to_string())
249        })?;
250        Ok(Plugins::new(registry, self))
251    }
252
253    /// 设置用户(链式调用)
254    ///
255    /// 仅供 crate 内中间件/内部使用。调用方有责任确保 user 已经过认证(如 TokenAuthMiddleware),
256    /// 直接注入未验证的 User 将绕过所有鉴权。
257    #[allow(dead_code)]
258    pub(crate) fn with_user(mut self, user: User) -> Self {
259        let mut roles = user.roles.iter().cloned().collect::<Vec<_>>();
260        roles.sort_unstable();
261        self.cached_roles = Arc::from(roles);
262        self.user = Some(user);
263        self
264    }
265
266    /// 获取已认证用户的只读引用。
267    ///
268    /// 外部调用方只能读取认证结果,不能手动注入用户;用户注入仅由 crate 内受信任
269    /// 中间件(如 `TokenAuthMiddleware`)完成。
270    pub fn authenticated_user(&self) -> Option<&User> {
271        self.user.as_ref()
272    }
273
274    /// 按当前请求认证身份返回可访问的版本化 UI 目录。
275    ///
276    /// 目录过滤与真实 Action dispatch 复用同一份构建期授权策略。
277    pub fn ui_catalog(&self) -> Result<crate::definition::UiCatalog, BaseError> {
278        let registry = self.registry.as_ref().ok_or_else(|| {
279            BaseError::ConfigError("ActionContext 未绑定应用 Registry".to_string())
280        })?;
281        registry.ui_catalog(self)
282    }
283
284    /// 设置本次派发的 request_id(链式调用)
285    ///
286    /// 通常由 `RequestIdMiddleware` 在洋葱链最外层调用以透传上游标识;
287    /// 业务侧一般无需手动设置。
288    pub fn with_request_id(mut self, request_id: RequestId) -> Self {
289        self.request_id = request_id;
290        self
291    }
292
293    /// 注入由传输适配器构造的请求元数据(链式调用)。
294    pub fn with_request_meta(mut self, request_meta: RequestMeta) -> Self {
295        self.request_meta = request_meta;
296        self
297    }
298
299    /// 设置所属模块名(链式调用)。
300    ///
301    /// 由 `Registry::dispatch` 注入,用于 metrics `module` 标签等可观测性标注。
302    pub fn with_module(mut self, module: impl Into<String>) -> Self {
303        self.module = Some(module.into());
304        self
305    }
306
307    /// 返回当前实际派发的 `module` 与 `action`。
308    ///
309    /// 该身份由 `Registry` 在进入中间件链前覆盖注入,可供安全中间件绑定目标;
310    /// 未经 Registry 派发而直接构造的上下文返回 `None`。
311    pub fn dispatch_target(&self) -> Option<(&str, &str)> {
312        Some((self.module.as_deref()?, self.action.as_deref()?))
313    }
314
315    /// 覆盖注入当前实际派发目标,防止调用方预置的可观测性字段参与安全判断。
316    pub(crate) fn with_dispatch_target(
317        mut self,
318        module: impl Into<String>,
319        action: impl Into<String>,
320    ) -> Self {
321        self.module = Some(module.into());
322        self.action = Some(action.into());
323        self
324    }
325
326    /// 设置表定义(链式调用)。
327    pub fn with_table_definition(mut self, definition: TableDefinition) -> Self {
328        self.table_definition = Some(definition);
329        self
330    }
331
332    /// 返回当前 Action 绑定的表定义。
333    pub fn table_definition(&self) -> Result<&TableDefinition, BaseError> {
334        self.table_definition
335            .as_ref()
336            .ok_or(BaseError::TableDefinitionNotSet)
337    }
338
339    /// 零拷贝版本:用 `std::mem::take` 替代 clone 请求体。
340    ///
341    /// 调用后 `self.request.body` 变为 `Value::Null`,仅在不再需要 body 时使用。
342    /// 仅限 crate 内部使用(`DynAction::dispatch` blanket impl 中 ctx 仅需传给 handle)。
343    pub(crate) fn extract_input_owned<I: DeserializeOwned>(&mut self) -> Result<I, BaseError> {
344        let body = std::mem::take(&mut self.request.body);
345        serde_json::from_value(body)
346            .map_err(|e| BaseError::ParamInvalid("body".to_string(), e.to_string()))
347    }
348
349    /// 创建表查询构建器
350    ///
351    /// 基于当前上下文的表配置和用户角色创建 TableQuery 实例。启用 `mysql`
352    /// feature 时,从当前上下文的 [`Tools`] 注入共享连接池,使内置 CRUD Action
353    /// 能直接执行数据库操作;若应用未配置数据库,则返回
354    /// `BaseError::DatabaseNotInitialized`。
355    ///
356    /// # 返回
357    ///
358    /// - `Ok(TableQuery)`: 查询构建器
359    /// - `Err(BaseError::TableDefinitionNotSet)`: 表定义未设置
360    fn base_table_query(&self, definition: &TableDefinition) -> Result<TableQuery, BaseError> {
361        // 启用 mysql feature 时,从当前应用资源注入连接池。
362        #[cfg(feature = "mysql")]
363        let pool = self
364            .tools
365            .optional_mysql()?
366            .map(|database| Arc::new(database.pool().clone()));
367        #[cfg(not(feature = "mysql"))]
368        let pool = None;
369
370        // 注入可观测性:慢查询阈值(Tools 配置槽)+ 本次派发 request_id,
371        // 使受保护层执行边界能在超阈值时 warn 并串联 request_id。
372        let slow_threshold = self.slow_query_threshold();
373        Ok(TableQuery::new(
374            definition.shared_config(),
375            Arc::clone(&self.cached_roles),
376            pool,
377        )
378        .with_slow_threshold(slow_threshold)
379        .with_request_id(self.request_id))
380    }
381
382    /// 创建默认失败关闭的表查询构建器。
383    ///
384    /// 带 tenant key 的表必须存在普通 [`TenantContext`],并始终自动施加租户条件。
385    /// 系统身份不会隐式绕过;全域访问必须显式调用
386    /// [`ActionContext::system_table_query`]。
387    pub fn table_query(&self) -> Result<TableQuery, BaseError> {
388        let definition = self.table_definition()?;
389        let mut query = self.base_table_query(definition)?;
390        if let Some(field) = definition.tenant_key_field() {
391            query = query.scope_tenant(field, serde_json::json!(self.tenant()?.id().get()))?;
392        }
393        Ok(query)
394    }
395
396    /// 使用显式、已绑定当前请求 actor 的系统 capability 创建全域表查询。
397    ///
398    /// 调用方必须先通过 [`ActionContext::system_tenant`] 取得 capability,再在具体
399    /// repository 旁路中显式传回;普通 CRUD 只调用 [`ActionContext::table_query`],
400    /// 因而不会自动获得全租户访问。
401    pub fn system_table_query(
402        &self,
403        capability: SystemTenantCapability,
404    ) -> Result<TableQuery, BaseError> {
405        if self.system_tenant()? != capability {
406            return Err(BaseError::PermissionDenied(
407                "系统租户 capability 与当前请求不匹配".to_string(),
408            ));
409        }
410        let definition = self.table_definition()?;
411        self.base_table_query(definition)
412    }
413
414    /// 创建 BR 心智连续的 Tables 入口。
415    pub fn tables(&self) -> Result<Tables, BaseError> {
416        self.table_query().map(Tables::new)
417    }
418
419    /// 使用显式系统 capability 创建全域 Tables 入口。
420    pub fn system_tables(&self, capability: SystemTenantCapability) -> Result<Tables, BaseError> {
421        self.system_table_query(capability).map(Tables::new)
422    }
423
424    /// 开启一个数据库事务(受保护层多步写的原子作用域)
425    ///
426    /// 返回 [`yang_db::Transaction`],可传入 `TableQuery` 的 `*_in_tx` 系列方法
427    /// (`insert_in_tx`/`update_in_tx`/`delete_in_tx`/`select_in_tx` 等),使受
428    /// 权限/校验/软删保护的多步写在同一事务内原子提交或整体回滚。调用方负责
429    /// 显式 `commit()`;若 `Transaction` 在未提交时被 drop,sqlx 会尽力回滚。
430    ///
431    /// 仅在启用 `mysql` feature 时可用。
432    ///
433    /// # 返回
434    ///
435    /// - `Ok(Transaction)`:活动事务
436    /// - `Err(BaseError::DatabaseNotInitialized)`:当前应用未配置数据库
437    /// - `Err(BaseError::DatabaseTransactionFailed)`:开启事务失败
438    ///
439    /// # 示例
440    ///
441    /// ```rust,ignore
442    /// let mut tx = ctx.begin_transaction().await?;
443    /// let id = ctx.table_query()?.insert_returning_id_in_tx(&mut tx, parent).await?.1;
444    /// ctx.table_query()?.insert_in_tx(&mut tx, child_with(id)).await?;
445    /// tx.commit().await?;
446    /// ```
447    #[cfg(feature = "mysql")]
448    pub async fn begin_transaction(&self) -> Result<yang_db::Transaction, BaseError> {
449        self.tools
450            .mysql()?
451            .transaction()
452            .await
453            .map_err(BaseError::DatabaseTransactionFailed)
454    }
455
456    /// 获取用户角色列表(克隆为 Vec)
457    ///
458    /// # 返回
459    ///
460    /// - 用户角色列表(如果用户未登录则返回空列表)
461    pub fn user_roles(&self) -> Vec<String> {
462        self.user
463            .as_ref()
464            .map(|u| u.roles.iter().cloned().collect())
465            .unwrap_or_default()
466    }
467
468    /// 获取用户角色集合引用
469    ///
470    /// 返回用户角色的 HashSet 引用,支持 O(1) 包含检查。
471    /// 如果用户未登录则返回 `None`。
472    ///
473    /// # 返回
474    ///
475    /// - `Some(&HashSet<String>)`: 用户角色集合引用
476    /// - `None`: 用户未登录
477    pub fn user_roles_set(&self) -> Option<&HashSet<String>> {
478        self.user.as_ref().map(|u| &u.roles)
479    }
480}
481
482#[cfg(test)]
483mod tests {
484    use super::*;
485    use crate::observability::ObservabilityConfig;
486    use crate::tools::ToolsBuilder;
487    use std::time::Duration;
488
489    fn empty_context() -> ActionContext {
490        let tools = Arc::new(ToolsBuilder::new().build().expect("空 Tools 应构建成功"));
491        ActionContext::new(Request::new(serde_json::json!({})), tools)
492    }
493
494    #[cfg(feature = "http")]
495    #[test]
496    fn http_shortcut_returns_client_when_configured() {
497        let tools = Arc::new(
498            ToolsBuilder::new()
499                .http(crate::http::HttpClient::new(30).expect("测试 HTTP 客户端应创建成功"))
500                .build()
501                .expect("配置 HTTP 客户端后应构建成功"),
502        );
503        let context = ActionContext::new(Request::new(serde_json::json!({})), tools);
504
505        let client = context.http().expect("已配置时 ctx.http() 应可用");
506        let _builder = client.get("https://api.example.com/test");
507    }
508
509    #[cfg(feature = "http")]
510    #[test]
511    fn http_shortcut_errors_when_not_configured() {
512        let context = empty_context();
513
514        assert!(matches!(
515            context.http(),
516            Err(BaseError::HttpClientNotInitialized)
517        ));
518    }
519
520    #[test]
521    fn slow_query_threshold_is_none_without_registered_config() {
522        let context = empty_context();
523
524        assert_eq!(context.slow_query_threshold(), None);
525    }
526
527    #[test]
528    fn slow_query_threshold_reads_from_tools_config_slot() {
529        let threshold = Duration::from_millis(200);
530        let tools = Arc::new(
531            ToolsBuilder::new()
532                .config(ObservabilityConfig::new().with_slow_query_threshold(threshold))
533                .build()
534                .expect("注册可观测性配置后应构建成功"),
535        );
536        let context = ActionContext::new(Request::new(serde_json::json!({})), tools);
537
538        assert_eq!(context.slow_query_threshold(), Some(threshold));
539    }
540
541    #[test]
542    fn authenticated_roles_are_cached_once_in_stable_order() {
543        let context = empty_context()
544            .with_user(User::new(1, "alice").with_roles(["operator", "admin", "operator"]));
545
546        assert_eq!(
547            context.cached_roles.as_ref(),
548            ["admin".to_string(), "operator".to_string()]
549        );
550        assert_eq!(
551            context.user_roles_set(),
552            Some(&HashSet::from([
553                "admin".to_string(),
554                "operator".to_string()
555            ]))
556        );
557    }
558
559    #[test]
560    fn ui_catalog_rejects_context_without_bound_registry() {
561        let context = empty_context();
562
563        assert!(matches!(
564            context.ui_catalog(),
565            Err(BaseError::ConfigError(message))
566                if message == "ActionContext 未绑定应用 Registry"
567        ));
568    }
569}