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, 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/// Action 执行上下文
90///
91/// 包含 Action 执行所需的所有信息,包括请求数据、传输元数据、用户信息、应用资源和表配置。
92///
93/// 标注 `#[non_exhaustive]`:未来新增运行期字段(如 trace_id)不构成破坏性变更,
94/// 调用方请用 [`ActionContext::new`] 构造,而非结构体字面量。
95#[derive(Debug)]
96#[non_exhaustive]
97pub struct ActionContext {
98    /// 请求数据
99    pub request: Request,
100    /// 与具体 Web 框架无关的传输元数据。
101    pub request_meta: RequestMeta,
102    /// 当前用户(已认证)
103    // SAFETY: 此字段为 pub(crate),仅 crate 内中间件(如 TokenAuthMiddleware)可注入。
104    // 外部 crate 无法直接设置此字段,防止绕过认证。
105    pub(crate) user: Option<User>,
106    /// 当前应用实例拥有的冻结资源。
107    tools: Arc<Tools>,
108    /// 当前 App 的冻结 Action Registry;仅 BuiltApp 创建的上下文具备。
109    registry: Option<Arc<Registry>>,
110    /// 不可变表定义(如果 Action 关联表)。
111    table_definition: Option<TableDefinition>,
112    /// 本次派发的运行期标识,用于串联日志/span/metrics/审计。
113    ///
114    /// 由 `new` 默认生成;`RequestIdMiddleware` 在洋葱链
115    /// 最外层会按上游 `X-Request-Id` 透传或重新生成并 `span.record`。
116    pub request_id: RequestId,
117    /// 本次派发所属模块名(由 `Registry::dispatch` 注入)。
118    ///
119    /// 仅用于可观测性标注(metrics `module` 标签、日志)。模块数量有界,作为 metrics
120    /// 标签不构成高基数问题。未经路由直接构造的上下文为 `None`。
121    pub module: Option<String>,
122    /// 本次派发的 Action 名(由 `Registry::dispatch` 可信注入)。
123    ///
124    /// 与 `module` 共同标识当前实际执行目标;外部构造的上下文不能伪造此字段。
125    action: Option<String>,
126    /// PERF-13: 缓存用户角色的 Arc 副本,避免 table_query() 每次重新 Arc 化。
127    /// 在 `with_user()` 时一次性构建,后续 `table_query()` 仅需 `Arc::clone`(O(1))。
128    #[allow(dead_code)]
129    cached_roles: Arc<[String]>,
130    /// 当前请求独占的类型化扩展上下文。
131    request_context: RequestContext,
132    /// 高频租户上下文;租户表查询缺少该值时 fail-closed。
133    tenant: Option<TenantContext>,
134}
135
136impl ActionContext {
137    /// 创建新的上下文
138    pub fn new(request: Request, tools: Arc<Tools>) -> Self {
139        Self {
140            request,
141            request_meta: RequestMeta::default(),
142            user: None,
143            tools,
144            registry: None,
145            table_definition: None,
146            request_id: RequestId::generate(),
147            module: None,
148            action: None,
149            cached_roles: Arc::from(Vec::new()),
150            request_context: RequestContext::default(),
151            tenant: None,
152        }
153    }
154
155    /// 返回当前应用实例的冻结资源。
156    pub fn tools(&self) -> &Tools {
157        &self.tools
158    }
159
160    /// 获取当前应用配置的 HTTP 客户端(`http` feature)。
161    ///
162    /// 委托给 [`Tools::http`]:未配置时返回 `BaseError::HttpClientNotInitialized`,
163    /// Tools 生命周期已结束时返回对应错误。
164    #[cfg(feature = "http")]
165    pub fn http(&self) -> Result<&crate::http::HttpClient, BaseError> {
166        self.tools.http()
167    }
168
169    /// 从 Tools 配置槽解析慢查询阈值。
170    ///
171    /// 未注册 [`ObservabilityConfig`](crate::observability::ObservabilityConfig) 时返回
172    /// `None`(关闭慢查询日志),与历史上全局单例未初始化的行为一致。
173    fn slow_query_threshold(&self) -> Option<std::time::Duration> {
174        self.tools
175            .config::<crate::observability::ObservabilityConfig>()
176            .ok()
177            .and_then(|config| config.slow_query_threshold)
178    }
179
180    /// 返回当前请求独占的类型化上下文。
181    pub fn request_context(&mut self) -> &mut RequestContext {
182        &mut self.request_context
183    }
184
185    /// 注入租户上下文。
186    pub fn with_tenant(mut self, tenant: TenantContext) -> Self {
187        self.tenant = Some(tenant);
188        self
189    }
190
191    /// 返回租户上下文。
192    pub fn tenant(&self) -> Result<TenantContext, BaseError> {
193        self.tenant
194            .ok_or_else(|| BaseError::Unauthorized("请求缺少租户上下文".to_string()))
195    }
196
197    /// 返回当前操作者上下文。
198    pub fn actor(&self) -> Result<ActorContext, BaseError> {
199        self.user
200            .as_ref()
201            .map(|user| ActorContext::new(user.id))
202            .ok_or_else(|| BaseError::Unauthorized("请求缺少已认证操作者".to_string()))
203    }
204
205    /// 返回请求标识。
206    pub fn request_id(&self) -> RequestId {
207        self.request_id
208    }
209
210    pub(crate) fn with_registry(mut self, registry: Arc<Registry>) -> Self {
211        self.registry = Some(registry);
212        self
213    }
214
215    /// 消费当前请求上下文并创建强类型内部 Action 调用器。
216    pub fn plugins(self) -> Result<Plugins, BaseError> {
217        let registry = self.registry.as_ref().cloned().ok_or_else(|| {
218            BaseError::ConfigError("ActionContext 未绑定应用 Registry".to_string())
219        })?;
220        Ok(Plugins::new(registry, self))
221    }
222
223    /// 设置用户(链式调用)
224    ///
225    /// 仅供 crate 内中间件/内部使用。调用方有责任确保 user 已经过认证(如 TokenAuthMiddleware),
226    /// 直接注入未验证的 User 将绕过所有鉴权。
227    #[allow(dead_code)]
228    pub(crate) fn with_user(mut self, user: User) -> Self {
229        self.user = Some(user);
230        self
231    }
232
233    /// 获取已认证用户的只读引用。
234    ///
235    /// 外部调用方只能读取认证结果,不能手动注入用户;用户注入仅由 crate 内受信任
236    /// 中间件(如 `TokenAuthMiddleware`)完成。
237    pub fn authenticated_user(&self) -> Option<&User> {
238        self.user.as_ref()
239    }
240
241    /// 按当前请求认证身份返回可访问的版本化 UI 目录。
242    ///
243    /// 目录过滤与真实 Action dispatch 复用同一份构建期授权策略。
244    pub fn ui_catalog(&self) -> Result<crate::definition::UiCatalog, BaseError> {
245        let registry = self.registry.as_ref().ok_or_else(|| {
246            BaseError::ConfigError("ActionContext 未绑定应用 Registry".to_string())
247        })?;
248        registry.ui_catalog(self)
249    }
250
251    /// 设置本次派发的 request_id(链式调用)
252    ///
253    /// 通常由 `RequestIdMiddleware` 在洋葱链最外层调用以透传上游标识;
254    /// 业务侧一般无需手动设置。
255    pub fn with_request_id(mut self, request_id: RequestId) -> Self {
256        self.request_id = request_id;
257        self
258    }
259
260    /// 注入由传输适配器构造的请求元数据(链式调用)。
261    pub fn with_request_meta(mut self, request_meta: RequestMeta) -> Self {
262        self.request_meta = request_meta;
263        self
264    }
265
266    /// 设置所属模块名(链式调用)。
267    ///
268    /// 由 `Registry::dispatch` 注入,用于 metrics `module` 标签等可观测性标注。
269    pub fn with_module(mut self, module: impl Into<String>) -> Self {
270        self.module = Some(module.into());
271        self
272    }
273
274    /// 返回当前实际派发的 `module` 与 `action`。
275    ///
276    /// 该身份由 `Registry` 在进入中间件链前覆盖注入,可供安全中间件绑定目标;
277    /// 未经 Registry 派发而直接构造的上下文返回 `None`。
278    pub fn dispatch_target(&self) -> Option<(&str, &str)> {
279        Some((self.module.as_deref()?, self.action.as_deref()?))
280    }
281
282    /// 覆盖注入当前实际派发目标,防止调用方预置的可观测性字段参与安全判断。
283    pub(crate) fn with_dispatch_target(
284        mut self,
285        module: impl Into<String>,
286        action: impl Into<String>,
287    ) -> Self {
288        self.module = Some(module.into());
289        self.action = Some(action.into());
290        self
291    }
292
293    /// 设置表定义(链式调用)。
294    pub fn with_table_definition(mut self, definition: TableDefinition) -> Self {
295        self.table_definition = Some(definition);
296        self
297    }
298
299    /// 返回当前 Action 绑定的表定义。
300    pub fn table_definition(&self) -> Result<&TableDefinition, BaseError> {
301        self.table_definition
302            .as_ref()
303            .ok_or(BaseError::TableDefinitionNotSet)
304    }
305
306    /// 零拷贝版本:用 `std::mem::take` 替代 clone 请求体。
307    ///
308    /// 调用后 `self.request.body` 变为 `Value::Null`,仅在不再需要 body 时使用。
309    /// 仅限 crate 内部使用(`DynAction::dispatch` blanket impl 中 ctx 仅需传给 handle)。
310    pub(crate) fn extract_input_owned<I: DeserializeOwned>(&mut self) -> Result<I, BaseError> {
311        let body = std::mem::take(&mut self.request.body);
312        serde_json::from_value(body)
313            .map_err(|e| BaseError::ParamInvalid("body".to_string(), e.to_string()))
314    }
315
316    /// 创建表查询构建器
317    ///
318    /// 基于当前上下文的表配置和用户角色创建 TableQuery 实例。启用 `mysql`
319    /// feature 时,从当前上下文的 [`Tools`] 注入共享连接池,使内置 CRUD Action
320    /// 能直接执行数据库操作;若应用未配置数据库,则返回
321    /// `BaseError::DatabaseNotInitialized`。
322    ///
323    /// # 返回
324    ///
325    /// - `Ok(TableQuery)`: 查询构建器
326    /// - `Err(BaseError::TableDefinitionNotSet)`: 表定义未设置
327    pub fn table_query(&self) -> Result<TableQuery, BaseError> {
328        let definition = self
329            .table_definition
330            .as_ref()
331            .ok_or(BaseError::TableDefinitionNotSet)?;
332
333        // 将用户角色 HashSet 转为 Vec 再打包为 Arc(table_query 需要 Vec)
334        let roles_set = self.user_roles_set();
335        let user_roles: Arc<[String]> = Arc::from(
336            roles_set
337                .map(|s| s.iter().cloned().collect::<Vec<_>>())
338                .unwrap_or_default(),
339        );
340
341        // 启用 mysql feature 时,从当前应用资源注入连接池。
342        #[cfg(feature = "mysql")]
343        let pool = self
344            .tools
345            .optional_mysql()?
346            .map(|database| Arc::new(database.pool().clone()));
347        #[cfg(not(feature = "mysql"))]
348        let pool = None;
349
350        // 注入可观测性:慢查询阈值(Tools 配置槽)+ 本次派发 request_id,
351        // 使受保护层执行边界能在超阈值时 warn 并串联 request_id。
352        let slow_threshold = self.slow_query_threshold();
353        let mut query = TableQuery::new(definition.shared_config(), user_roles, pool)
354            .with_slow_threshold(slow_threshold)
355            .with_request_id(self.request_id);
356        if let Some(field) = definition.tenant_key_field() {
357            let tenant = self.tenant()?;
358            if !tenant.is_system() {
359                let tenant_id = tenant.id().ok_or_else(|| {
360                    BaseError::Unauthorized("普通租户上下文缺少 tenant id".to_string())
361                })?;
362                query = query.scope_tenant(field, serde_json::json!(tenant_id.get()))?;
363            }
364        }
365        Ok(query)
366    }
367
368    /// 创建 BR 心智连续的 Tables 入口。
369    pub fn tables(&self) -> Result<Tables, BaseError> {
370        self.table_query().map(Tables::new)
371    }
372
373    /// 开启一个数据库事务(受保护层多步写的原子作用域)
374    ///
375    /// 返回 [`yang_db::Transaction`],可传入 `TableQuery` 的 `*_in_tx` 系列方法
376    /// (`insert_in_tx`/`update_in_tx`/`delete_in_tx`/`select_in_tx` 等),使受
377    /// 权限/校验/软删保护的多步写在同一事务内原子提交或整体回滚。调用方负责
378    /// 显式 `commit()`;若 `Transaction` 在未提交时被 drop,sqlx 会尽力回滚。
379    ///
380    /// 仅在启用 `mysql` feature 时可用。
381    ///
382    /// # 返回
383    ///
384    /// - `Ok(Transaction)`:活动事务
385    /// - `Err(BaseError::DatabaseNotInitialized)`:当前应用未配置数据库
386    /// - `Err(BaseError::DatabaseTransactionFailed)`:开启事务失败
387    ///
388    /// # 示例
389    ///
390    /// ```rust,ignore
391    /// let mut tx = ctx.begin_transaction().await?;
392    /// let id = ctx.table_query()?.insert_returning_id_in_tx(&mut tx, parent).await?.1;
393    /// ctx.table_query()?.insert_in_tx(&mut tx, child_with(id)).await?;
394    /// tx.commit().await?;
395    /// ```
396    #[cfg(feature = "mysql")]
397    pub async fn begin_transaction(&self) -> Result<yang_db::Transaction, BaseError> {
398        self.tools
399            .mysql()?
400            .transaction()
401            .await
402            .map_err(BaseError::DatabaseTransactionFailed)
403    }
404
405    /// 获取用户角色列表(克隆为 Vec)
406    ///
407    /// # 返回
408    ///
409    /// - 用户角色列表(如果用户未登录则返回空列表)
410    pub fn user_roles(&self) -> Vec<String> {
411        self.user
412            .as_ref()
413            .map(|u| u.roles.iter().cloned().collect())
414            .unwrap_or_default()
415    }
416
417    /// 获取用户角色集合引用
418    ///
419    /// 返回用户角色的 HashSet 引用,支持 O(1) 包含检查。
420    /// 如果用户未登录则返回 `None`。
421    ///
422    /// # 返回
423    ///
424    /// - `Some(&HashSet<String>)`: 用户角色集合引用
425    /// - `None`: 用户未登录
426    pub fn user_roles_set(&self) -> Option<&HashSet<String>> {
427        self.user.as_ref().map(|u| &u.roles)
428    }
429}
430
431#[cfg(test)]
432mod tests {
433    use super::*;
434    use crate::observability::ObservabilityConfig;
435    use crate::tools::ToolsBuilder;
436    use std::time::Duration;
437
438    fn empty_context() -> ActionContext {
439        let tools = Arc::new(ToolsBuilder::new().build().expect("空 Tools 应构建成功"));
440        ActionContext::new(Request::new(serde_json::json!({})), tools)
441    }
442
443    #[cfg(feature = "http")]
444    #[test]
445    fn http_shortcut_returns_client_when_configured() {
446        let tools = Arc::new(
447            ToolsBuilder::new()
448                .http(crate::http::HttpClient::new(30).expect("测试 HTTP 客户端应创建成功"))
449                .build()
450                .expect("配置 HTTP 客户端后应构建成功"),
451        );
452        let context = ActionContext::new(Request::new(serde_json::json!({})), tools);
453
454        let client = context.http().expect("已配置时 ctx.http() 应可用");
455        let _builder = client.get("https://api.example.com/test");
456    }
457
458    #[cfg(feature = "http")]
459    #[test]
460    fn http_shortcut_errors_when_not_configured() {
461        let context = empty_context();
462
463        assert!(matches!(
464            context.http(),
465            Err(BaseError::HttpClientNotInitialized)
466        ));
467    }
468
469    #[test]
470    fn slow_query_threshold_is_none_without_registered_config() {
471        let context = empty_context();
472
473        assert_eq!(context.slow_query_threshold(), None);
474    }
475
476    #[test]
477    fn slow_query_threshold_reads_from_tools_config_slot() {
478        let threshold = Duration::from_millis(200);
479        let tools = Arc::new(
480            ToolsBuilder::new()
481                .config(ObservabilityConfig::new().with_slow_query_threshold(threshold))
482                .build()
483                .expect("注册可观测性配置后应构建成功"),
484        );
485        let context = ActionContext::new(Request::new(serde_json::json!({})), tools);
486
487        assert_eq!(context.slow_query_threshold(), Some(threshold));
488    }
489
490    #[test]
491    fn ui_catalog_rejects_context_without_bound_registry() {
492        let context = empty_context();
493
494        assert!(matches!(
495            context.ui_catalog(),
496            Err(BaseError::ConfigError(message))
497                if message == "ActionContext 未绑定应用 Registry"
498        ));
499    }
500}