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    /// 本次派发所属模块绑定的逻辑数据源;由 Registry 注入。
125    datasource: Option<crate::datasource::DatasourceId>,
126    /// 本次派发的运行期标识,用于串联日志/span/metrics/审计。
127    ///
128    /// 由 `new` 默认生成;`RequestIdMiddleware` 在洋葱链
129    /// 最外层会按上游 `X-Request-Id` 透传或重新生成并 `span.record`。
130    pub request_id: RequestId,
131    /// 本次派发所属模块名(由 `Registry::dispatch` 注入)。
132    ///
133    /// 仅用于可观测性标注(metrics `module` 标签、日志)。模块数量有界,作为 metrics
134    /// 标签不构成高基数问题。未经路由直接构造的上下文为 `None`。
135    pub module: Option<String>,
136    /// 本次派发的 Action 名(由 `Registry::dispatch` 可信注入)。
137    ///
138    /// 与 `module` 共同标识当前实际执行目标;外部构造的上下文不能伪造此字段。
139    action: Option<String>,
140    /// PERF-13: 缓存用户角色的 Arc 副本,避免 table_query() 每次重新 Arc 化。
141    /// 在 `with_user()` 时一次性构建,后续 `table_query()` 仅需 `Arc::clone`(O(1))。
142    cached_roles: Arc<[String]>,
143    /// 当前请求独占的类型化扩展上下文。
144    request_context: RequestContext,
145    /// 普通租户、系统 capability 或缺失三者互斥的访问状态。
146    tenant_access: TenantAccess,
147}
148
149impl Clone for ActionContext {
150    fn clone(&self) -> Self {
151        // RequestContext 含 `Box<dyn Any>` 不可 Clone;克隆副本重建空的
152        // 请求扩展集合——扩展值只属于原始请求生命周期,副本按无扩展降级。
153        Self {
154            request: self.request.clone(),
155            request_meta: self.request_meta.clone(),
156            user: self.user.clone(),
157            tools: Arc::clone(&self.tools),
158            registry: self.registry.clone(),
159            table_definition: self.table_definition.clone(),
160            datasource: self.datasource.clone(),
161            request_id: self.request_id,
162            module: self.module.clone(),
163            action: self.action.clone(),
164            cached_roles: Arc::clone(&self.cached_roles),
165            request_context: RequestContext::default(),
166            tenant_access: self.tenant_access,
167        }
168    }
169}
170
171impl ActionContext {
172    /// 创建新的上下文
173    pub fn new(request: Request, tools: Arc<Tools>) -> Self {
174        Self {
175            request,
176            request_meta: RequestMeta::default(),
177            user: None,
178            tools,
179            registry: None,
180            table_definition: None,
181            datasource: None,
182            request_id: RequestId::generate(),
183            module: None,
184            action: None,
185            cached_roles: Arc::from(Vec::new()),
186            request_context: RequestContext::default(),
187            tenant_access: TenantAccess::Missing,
188        }
189    }
190
191    /// 返回当前应用实例的冻结资源。
192    pub fn tools(&self) -> &Tools {
193        &self.tools
194    }
195
196    /// 获取当前应用配置的 HTTP 客户端(`http` feature)。
197    ///
198    /// 委托给 [`Tools::http`]:未配置时返回 `BaseError::HttpClientNotInitialized`,
199    /// Tools 生命周期已结束时返回对应错误。
200    #[cfg(feature = "http")]
201    pub fn http(&self) -> Result<&crate::http::HttpClient, BaseError> {
202        self.tools.http()
203    }
204
205    /// 从 Tools 配置槽解析慢查询阈值。
206    ///
207    /// 未注册 [`ObservabilityConfig`](crate::observability::ObservabilityConfig) 时返回
208    /// `None`(关闭慢查询日志),与历史上全局单例未初始化的行为一致。
209    fn slow_query_threshold(&self) -> Option<std::time::Duration> {
210        self.tools
211            .config::<crate::observability::ObservabilityConfig>()
212            .ok()
213            .and_then(|config| config.slow_query_threshold)
214    }
215
216    /// 返回当前请求独占的类型化上下文。
217    pub fn request_context(&mut self) -> &mut RequestContext {
218        &mut self.request_context
219    }
220
221    /// 注入普通租户 capability。
222    pub fn with_tenant(mut self, tenant: TenantContext) -> Self {
223        self.tenant_access = TenantAccess::Tenant(tenant);
224        self
225    }
226
227    pub(crate) fn with_system_tenant(mut self, capability: SystemTenantCapability) -> Self {
228        self.tenant_access = TenantAccess::System(capability);
229        self
230    }
231
232    /// 返回不可选的普通租户 capability。
233    pub fn tenant(&self) -> Result<TenantContext, BaseError> {
234        match self.tenant_access {
235            TenantAccess::Tenant(tenant) => Ok(tenant),
236            TenantAccess::Missing | TenantAccess::System(_) => Err(BaseError::Unauthorized(
237                "请求缺少普通租户 capability".to_string(),
238            )),
239        }
240    }
241
242    /// 返回当前请求已获授的系统级租户 capability。
243    pub fn system_tenant(&self) -> Result<SystemTenantCapability, BaseError> {
244        match self.tenant_access {
245            TenantAccess::System(capability) => Ok(capability),
246            TenantAccess::Missing | TenantAccess::Tenant(_) => Err(BaseError::PermissionDenied(
247                "请求缺少系统租户 capability".to_string(),
248            )),
249        }
250    }
251
252    /// 返回当前操作者上下文。
253    pub fn actor(&self) -> Result<ActorContext, BaseError> {
254        self.user
255            .as_ref()
256            .map(|user| ActorContext::new(user.id))
257            .ok_or_else(|| BaseError::Unauthorized("请求缺少已认证操作者".to_string()))
258    }
259
260    /// 返回请求标识。
261    pub fn request_id(&self) -> RequestId {
262        self.request_id
263    }
264
265    pub(crate) fn with_registry(mut self, registry: Arc<Registry>) -> Self {
266        self.registry = Some(registry);
267        self
268    }
269
270    /// 消费当前请求上下文并创建强类型内部 Action 调用器。
271    pub fn plugins(self) -> Result<Plugins, BaseError> {
272        let registry = self.registry.as_ref().cloned().ok_or_else(|| {
273            BaseError::ConfigError("ActionContext 未绑定应用 Registry".to_string())
274        })?;
275        Ok(Plugins::new(registry, self))
276    }
277
278    /// 设置用户(链式调用)
279    ///
280    /// 仅供 crate 内中间件/内部使用。调用方有责任确保 user 已经过认证(如 TokenAuthMiddleware),
281    /// 直接注入未验证的 User 将绕过所有鉴权。
282    #[allow(dead_code)]
283    pub(crate) fn with_user(mut self, user: User) -> Self {
284        let mut roles = user.roles.iter().cloned().collect::<Vec<_>>();
285        roles.sort_unstable();
286        self.cached_roles = Arc::from(roles);
287        self.user = Some(user);
288        self
289    }
290
291    /// 获取已认证用户的只读引用。
292    ///
293    /// 外部调用方只能读取认证结果,不能手动注入用户;用户注入仅由 crate 内受信任
294    /// 中间件(如 `TokenAuthMiddleware`)完成。
295    pub fn authenticated_user(&self) -> Option<&User> {
296        self.user.as_ref()
297    }
298
299    /// 按当前请求认证身份返回可访问的版本化 UI 目录。
300    ///
301    /// 目录过滤与真实 Action dispatch 复用同一份构建期授权策略。
302    pub fn ui_catalog(&self) -> Result<crate::definition::UiCatalog, BaseError> {
303        let registry = self.registry.as_ref().ok_or_else(|| {
304            BaseError::ConfigError("ActionContext 未绑定应用 Registry".to_string())
305        })?;
306        registry.ui_catalog(self)
307    }
308
309    /// 设置本次派发的 request_id(链式调用)
310    ///
311    /// 通常由 `RequestIdMiddleware` 在洋葱链最外层调用以透传上游标识;
312    /// 业务侧一般无需手动设置。
313    pub fn with_request_id(mut self, request_id: RequestId) -> Self {
314        self.request_id = request_id;
315        self
316    }
317
318    /// 注入由传输适配器构造的请求元数据(链式调用)。
319    pub fn with_request_meta(mut self, request_meta: RequestMeta) -> Self {
320        self.request_meta = request_meta;
321        self
322    }
323
324    /// 设置所属模块名(链式调用)。
325    ///
326    /// 由 `Registry::dispatch` 注入,用于 metrics `module` 标签等可观测性标注。
327    pub fn with_module(mut self, module: impl Into<String>) -> Self {
328        self.module = Some(module.into());
329        self
330    }
331
332    /// 返回当前实际派发的 `module` 与 `action`。
333    ///
334    /// 该身份由 `Registry` 在进入中间件链前覆盖注入,可供安全中间件绑定目标;
335    /// 未经 Registry 派发而直接构造的上下文返回 `None`。
336    pub fn dispatch_target(&self) -> Option<(&str, &str)> {
337        Some((self.module.as_deref()?, self.action.as_deref()?))
338    }
339
340    /// 覆盖注入当前实际派发目标,防止调用方预置的可观测性字段参与安全判断。
341    pub(crate) fn with_dispatch_target(
342        mut self,
343        module: impl Into<String>,
344        action: impl Into<String>,
345    ) -> Self {
346        self.module = Some(module.into());
347        self.action = Some(action.into());
348        self
349    }
350
351    /// 设置表定义(链式调用)。
352    pub fn with_table_definition(mut self, definition: TableDefinition) -> Self {
353        self.table_definition = Some(definition);
354        self
355    }
356
357    /// 返回当前 Action 绑定的表定义。
358    pub fn table_definition(&self) -> Result<&TableDefinition, BaseError> {
359        self.table_definition
360            .as_ref()
361            .ok_or(BaseError::TableDefinitionNotSet)
362    }
363
364    /// 注入本次派发所属模块的数据源(仅 crate 内 Registry 使用)。
365    pub(crate) fn with_datasource(
366        mut self,
367        datasource: Option<crate::datasource::DatasourceId>,
368    ) -> Self {
369        self.datasource = datasource;
370        self
371    }
372
373    /// 返回本次派发所属逻辑数据源。
374    pub fn datasource(&self) -> Option<&crate::datasource::DatasourceId> {
375        self.datasource.as_ref()
376    }
377
378    /// 解析本请求使用的数据源:模块注入源 → 表定义源 → 默认源。
379    #[cfg(any(feature = "mysql", feature = "postgres"))]
380    fn resolved_datasource(&self) -> crate::datasource::DatasourceId {
381        self.datasource
382            .clone()
383            .or_else(|| {
384                self.table_definition
385                    .as_ref()
386                    .map(|definition| definition.datasource().clone())
387            })
388            .unwrap_or_default()
389    }
390
391    /// 零拷贝版本:用 `std::mem::take` 替代 clone 请求体。
392    ///
393    /// 调用后 `self.request.body` 变为 `Value::Null`,仅在不再需要 body 时使用。
394    /// 仅限 crate 内部使用(`DynAction::dispatch` blanket impl 中 ctx 仅需传给 handle)。
395    pub(crate) fn extract_input_owned<I: DeserializeOwned>(&mut self) -> Result<I, BaseError> {
396        let body = std::mem::take(&mut self.request.body);
397        serde_json::from_value(body)
398            .map_err(|e| BaseError::ParamInvalid("body".to_string(), e.to_string()))
399    }
400
401    /// 创建表查询构建器
402    ///
403    /// 基于当前上下文的表配置和用户角色创建 TableQuery 实例。启用 `mysql` 或
404    /// `postgres` feature 时,从当前上下文的 [`Tools`] 注入共享连接池(按运行时
405    /// 后端分派),使内置 CRUD Action 能直接执行数据库操作;若应用未配置数据库,
406    /// 查询对象仍可构建,但执行时返回 `BaseError::DatabaseNotInitialized`。
407    ///
408    /// # 返回
409    ///
410    /// - `Ok(TableQuery)`: 查询构建器
411    /// - `Err(BaseError::TableDefinitionNotSet)`: 表定义未设置
412    fn base_table_query(&self, definition: &TableDefinition) -> Result<TableQuery, BaseError> {
413        #[cfg(any(feature = "mysql", feature = "postgres"))]
414        let (pool, pool_source) = {
415            let source = definition.datasource().clone();
416            match self.tools.database_named(&source) {
417                Ok(database) => (Some(database.pool()), database.id().clone()),
418                Err(BaseError::DatabaseNotInitialized) => (None, source),
419                Err(error) => return Err(error),
420            }
421        };
422        #[cfg(not(any(feature = "mysql", feature = "postgres")))]
423        let (pool, pool_source) = (None, crate::datasource::DatasourceId::default_source());
424
425        // 注入可观测性:慢查询阈值(Tools 配置槽)+ 本次派发 request_id,
426        // 使受保护层执行边界能在超阈值时 warn 并串联 request_id。
427        let slow_threshold = self.slow_query_threshold();
428        #[cfg(any(feature = "mysql", feature = "postgres"))]
429        let query = TableQuery::new_sourced(
430            definition.shared_config(),
431            Arc::clone(&self.cached_roles),
432            pool,
433            pool_source,
434        )
435        .require_sourced_tx(
436            self.tools
437                .datasources()
438                .map(|datasources| {
439                    let backends: Vec<_> = datasources
440                        .iter()
441                        .map(|datasource| datasource.database().backend())
442                        .collect();
443                    backends
444                        .iter()
445                        .enumerate()
446                        .any(|(index, backend)| backends[..index].contains(backend))
447                })
448                .unwrap_or(false),
449        );
450        #[cfg(not(any(feature = "mysql", feature = "postgres")))]
451        let query = {
452            let _ = pool_source;
453            TableQuery::new(
454                definition.shared_config(),
455                Arc::clone(&self.cached_roles),
456                pool,
457            )
458        };
459        Ok(query
460            .with_slow_threshold(slow_threshold)
461            .with_request_id(self.request_id)
462            .with_regex_cache(self.tools.regex_cache().clone()))
463    }
464
465    /// 创建默认失败关闭的表查询构建器。
466    ///
467    /// 带 tenant key 的表必须存在普通 [`TenantContext`],并始终自动施加租户条件。
468    /// 系统身份不会隐式绕过;全域访问必须显式调用
469    /// [`ActionContext::system_table_query`]。
470    pub fn table_query(&self) -> Result<TableQuery, BaseError> {
471        let definition = self.table_definition()?;
472        let mut query = self.base_table_query(definition)?;
473        if let Some(field) = definition.tenant_key_field() {
474            query = query.scope_tenant(field, serde_json::json!(self.tenant()?.id().get()))?;
475        }
476        Ok(query)
477    }
478
479    /// 使用显式、已绑定当前请求 actor 的系统 capability 创建全域表查询。
480    ///
481    /// 调用方必须先通过 [`ActionContext::system_tenant`] 取得 capability,再在具体
482    /// repository 旁路中显式传回;普通 CRUD 只调用 [`ActionContext::table_query`],
483    /// 因而不会自动获得全租户访问。
484    pub fn system_table_query(
485        &self,
486        capability: SystemTenantCapability,
487    ) -> Result<TableQuery, BaseError> {
488        if self.system_tenant()? != capability {
489            return Err(BaseError::PermissionDenied(
490                "系统租户 capability 与当前请求不匹配".to_string(),
491            ));
492        }
493        let definition = self.table_definition()?;
494        self.base_table_query(definition)
495    }
496
497    /// 创建 BR 心智连续的 Tables 入口。
498    pub fn tables(&self) -> Result<Tables, BaseError> {
499        self.table_query().map(Tables::new)
500    }
501
502    /// 使用显式系统 capability 创建全域 Tables 入口。
503    pub fn system_tables(&self, capability: SystemTenantCapability) -> Result<Tables, BaseError> {
504        self.system_table_query(capability).map(Tables::new)
505    }
506
507    /// 开启一个数据库事务(受保护层多步写的原子作用域)
508    ///
509    /// 返回 [`AnyTransaction`](crate::database::AnyTransaction),可传入 `TableQuery`
510    /// 的 `*_in_tx` 系列方法(`insert_in_tx`/`update_in_tx`/`delete_in_tx`/
511    /// `select_in_tx` 等),使受权限/校验/软删保护的多步写在同一事务内原子提交或
512    /// 整体回滚。调用方负责显式 `commit()`;若 `AnyTransaction` 在未提交时被 drop,
513    /// sqlx 会尽力回滚。
514    ///
515    /// 仅在启用 `mysql` 或 `postgres` feature 时可用。
516    ///
517    /// # 返回
518    ///
519    /// - `Ok(AnyTransaction)`:活动事务(按运行时后端分派)
520    /// - `Err(BaseError::DatabaseNotInitialized)`:当前应用未配置数据库
521    /// - `Err(BaseError::DatabaseTransactionFailed)`:开启事务失败
522    ///
523    /// # 示例
524    ///
525    /// ```rust,ignore
526    /// let mut tx = ctx.begin_transaction().await?;
527    /// let id = ctx.table_query()?.insert_returning_id_in_tx(&mut tx, parent).await?.1;
528    /// ctx.table_query()?.insert_in_tx(&mut tx, child_with(id)).await?;
529    /// tx.commit().await?;
530    /// ```
531    #[cfg(any(feature = "mysql", feature = "postgres"))]
532    pub async fn begin_transaction(&self) -> Result<crate::database::AnyTransaction, BaseError> {
533        let source = self.resolved_datasource();
534        self.begin_transaction_on(&source).await
535    }
536
537    /// 在指定逻辑数据源上开启事务。
538    #[cfg(any(feature = "mysql", feature = "postgres"))]
539    pub async fn begin_transaction_on(
540        &self,
541        source: &crate::datasource::DatasourceId,
542    ) -> Result<crate::database::AnyTransaction, BaseError> {
543        self.tools
544            .database_named(source)?
545            .begin()
546            .await
547            .map_err(BaseError::DatabaseTransactionFailed)
548    }
549
550    /// 返回本请求使用的数据库容器(模块源 → 表定义源 → 默认源)。
551    #[cfg(any(feature = "mysql", feature = "postgres"))]
552    pub fn database(&self) -> Result<&crate::database::AnyDatabase, BaseError> {
553        let source = self.resolved_datasource();
554        self.database_on(&source)
555    }
556
557    /// 返回指定数据源的数据库容器。
558    #[cfg(any(feature = "mysql", feature = "postgres"))]
559    pub fn database_on(
560        &self,
561        source: &crate::datasource::DatasourceId,
562    ) -> Result<&crate::database::AnyDatabase, BaseError> {
563        self.tools.database_named(source)
564    }
565
566    /// 事务局部会话配置的默认键:当前租户 ID。
567    ///
568    /// PostgreSQL RLS 策略可用 `current_setting('app.tenant_id')` 读取该值;
569    /// 调用方也可用自定义键直接调 [`ActionContext::set_local`],本常量只是默认约定。
570    #[cfg(any(feature = "mysql", feature = "postgres"))]
571    pub const TENANT_LOCAL_KEY: &'static str = "app.tenant_id";
572
573    /// 把键值写入当前事务的局部会话配置(PostgreSQL `SET LOCAL` 语义)。
574    ///
575    /// 委托 `yang_db` 的 `Transaction::set_local`:键名经严格标识符校验后作为字符串
576    /// 常量进入 SQL,值走绑定参数;作用域限于当前事务,提交或回滚后由 PostgreSQL
577    /// 自动还原。使用连接池时会话级配置可能被后续请求复用,因此这里固定用事务局部
578    /// (`is_local = true`),不提供会话级写入。
579    ///
580    /// 仅 PostgreSQL 支持;MySQL 事务返回 [`BaseError::ConfigError`](MySQL 没有
581    /// 等价的事务级 `SET LOCAL`,会话变量会跨池化连接泄漏)。
582    ///
583    /// # 示例
584    ///
585    /// ```rust,ignore
586    /// let mut tx = ctx.begin_transaction().await?;
587    /// ctx.set_local(&mut tx, "app.tenant_id", "42").await?;
588    /// // 事务内 RLS 策略可读取 current_setting('app.tenant_id')
589    /// tx.commit().await?;
590    /// ```
591    #[cfg(any(feature = "mysql", feature = "postgres"))]
592    pub async fn set_local(
593        &self,
594        tx: &mut crate::database::AnyTransaction,
595        key: &str,
596        value: &str,
597    ) -> Result<(), BaseError> {
598        // 仅 MySQL 时 PostgreSQL 分支不参与编译,键值参数保持未使用。
599        #[cfg(not(feature = "postgres"))]
600        let _ = (key, value);
601        match tx.kind_mut() {
602            #[cfg(feature = "postgres")]
603            crate::database::AnyTransactionKind::Postgres(tx) => tx
604                .set_local(key, value)
605                .await
606                .map_err(BaseError::DatabaseExecuteFailed),
607            #[cfg(feature = "mysql")]
608            crate::database::AnyTransactionKind::MySql(_) => Err(BaseError::ConfigError(
609                "MySQL 不支持事务级 SET LOCAL;该能力仅在 PostgreSQL 下可用".to_string(),
610            )),
611        }
612    }
613
614    /// 把当前 [`TenantContext`] 的租户 ID 写入事务局部配置
615    /// [`ActionContext::TENANT_LOCAL_KEY`](默认 `app.tenant_id`)。
616    ///
617    /// 供 PostgreSQL RLS 策略读取;缺少普通租户 capability 时返回
618    /// [`BaseError::Unauthorized`]。
619    #[cfg(any(feature = "mysql", feature = "postgres"))]
620    pub async fn set_tenant_local(
621        &self,
622        tx: &mut crate::database::AnyTransaction,
623    ) -> Result<(), BaseError> {
624        let tenant_id = self.tenant()?.id().get();
625        self.set_local(tx, Self::TENANT_LOCAL_KEY, &tenant_id.to_string())
626            .await
627    }
628
629    /// 获取用户角色列表(克隆为 Vec)
630    ///
631    /// # 返回
632    ///
633    /// - 用户角色列表(如果用户未登录则返回空列表)
634    pub fn user_roles(&self) -> Vec<String> {
635        self.user
636            .as_ref()
637            .map(|u| u.roles.iter().cloned().collect())
638            .unwrap_or_default()
639    }
640
641    /// 获取用户角色集合引用
642    ///
643    /// 返回用户角色的 HashSet 引用,支持 O(1) 包含检查。
644    /// 如果用户未登录则返回 `None`。
645    ///
646    /// # 返回
647    ///
648    /// - `Some(&HashSet<String>)`: 用户角色集合引用
649    /// - `None`: 用户未登录
650    pub fn user_roles_set(&self) -> Option<&HashSet<String>> {
651        self.user.as_ref().map(|u| &u.roles)
652    }
653}
654
655#[cfg(test)]
656mod tests {
657    use super::*;
658    use crate::observability::ObservabilityConfig;
659    use crate::tools::ToolsBuilder;
660    use std::time::Duration;
661
662    fn empty_context() -> ActionContext {
663        let tools = Arc::new(ToolsBuilder::new().build().expect("空 Tools 应构建成功"));
664        ActionContext::new(Request::new(serde_json::json!({})), tools)
665    }
666
667    #[cfg(feature = "http")]
668    #[test]
669    fn http_shortcut_returns_client_when_configured() {
670        let tools = Arc::new(
671            ToolsBuilder::new()
672                .http(crate::http::HttpClient::new(30).expect("测试 HTTP 客户端应创建成功"))
673                .build()
674                .expect("配置 HTTP 客户端后应构建成功"),
675        );
676        let context = ActionContext::new(Request::new(serde_json::json!({})), tools);
677
678        let client = context.http().expect("已配置时 ctx.http() 应可用");
679        let _builder = client.get("https://api.example.com/test");
680    }
681
682    #[cfg(feature = "http")]
683    #[test]
684    fn http_shortcut_errors_when_not_configured() {
685        let context = empty_context();
686
687        assert!(matches!(
688            context.http(),
689            Err(BaseError::HttpClientNotInitialized)
690        ));
691    }
692
693    #[test]
694    fn slow_query_threshold_is_none_without_registered_config() {
695        let context = empty_context();
696
697        assert_eq!(context.slow_query_threshold(), None);
698    }
699
700    #[test]
701    fn slow_query_threshold_reads_from_tools_config_slot() {
702        let threshold = Duration::from_millis(200);
703        let tools = Arc::new(
704            ToolsBuilder::new()
705                .config(ObservabilityConfig::new().with_slow_query_threshold(threshold))
706                .build()
707                .expect("注册可观测性配置后应构建成功"),
708        );
709        let context = ActionContext::new(Request::new(serde_json::json!({})), tools);
710
711        assert_eq!(context.slow_query_threshold(), Some(threshold));
712    }
713
714    #[test]
715    fn authenticated_roles_are_cached_once_in_stable_order() {
716        let context = empty_context()
717            .with_user(User::new(1, "alice").with_roles(["operator", "admin", "operator"]));
718
719        assert_eq!(
720            context.cached_roles.as_ref(),
721            ["admin".to_string(), "operator".to_string()]
722        );
723        assert_eq!(
724            context.user_roles_set(),
725            Some(&HashSet::from([
726                "admin".to_string(),
727                "operator".to_string()
728            ]))
729        );
730    }
731
732    #[test]
733    fn ui_catalog_rejects_context_without_bound_registry() {
734        let context = empty_context();
735
736        assert!(matches!(
737            context.ui_catalog(),
738            Err(BaseError::ConfigError(message))
739                if message == "ActionContext 未绑定应用 Registry"
740        ));
741    }
742}