Skip to main content

ActionContext

Struct ActionContext 

Source
#[non_exhaustive]
pub struct ActionContext { pub request: Request, pub request_meta: RequestMeta, pub request_id: RequestId, pub module: Option<String>, /* private fields */ }
Expand description

Action 执行上下文

包含 Action 执行所需的所有信息,包括请求数据、传输元数据、用户信息、应用资源和表配置。

标注 #[non_exhaustive]:未来新增运行期字段(如 trace_id)不构成破坏性变更, 调用方请用 ActionContext::new 构造,而非结构体字面量。

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§request: Request

请求数据

§request_meta: RequestMeta

与具体 Web 框架无关的传输元数据。

§request_id: RequestId

本次派发的运行期标识,用于串联日志/span/metrics/审计。

由 new 默认生成;RequestIdMiddleware 在洋葱链 最外层会按上游 X-Request-Id 透传或重新生成并 span.record。

§module: Option<String>

本次派发所属模块名(由 Registry::dispatch 注入)。

仅用于可观测性标注(metrics module 标签、日志)。模块数量有界,作为 metrics 标签不构成高基数问题。未经路由直接构造的上下文为 None。

Implementations§

Source§

impl ActionContext

Source

pub const TENANT_LOCAL_KEY: &'static str = "app.tenant_id"

事务局部会话配置的默认键:当前租户 ID。

PostgreSQL RLS 策略可用 current_setting('app.tenant_id') 读取该值; 调用方也可用自定义键直接调 ActionContext::set_local,本常量只是默认约定。

Source

pub fn new(request: Request, tools: Arc<Tools>) -> Self

创建新的上下文

Source

pub fn tools(&self) -> &Tools

返回当前应用实例的冻结资源。

Source

pub fn http(&self) -> Result<&HttpClient, BaseError>

获取当前应用配置的 HTTP 客户端(http feature)。

委托给 Tools::http:未配置时返回 BaseError::HttpClientNotInitialized, Tools 生命周期已结束时返回对应错误。

Source

pub fn request_context(&mut self) -> &mut RequestContext

返回当前请求独占的类型化上下文。

Source

pub fn with_tenant(self, tenant: TenantContext) -> Self

注入普通租户 capability。

Source

pub fn tenant(&self) -> Result<TenantContext, BaseError>

返回不可选的普通租户 capability。

Source

pub fn system_tenant(&self) -> Result<SystemTenantCapability, BaseError>

返回当前请求已获授的系统级租户 capability。

Source

pub fn actor(&self) -> Result<ActorContext, BaseError>

返回当前操作者上下文。

Source

pub fn request_id(&self) -> RequestId

返回请求标识。

Source

pub fn plugins(self) -> Result<Plugins, BaseError>

消费当前请求上下文并创建强类型内部 Action 调用器。

Source

pub fn authenticated_user(&self) -> Option<&User>

获取已认证用户的只读引用。

外部调用方只能读取认证结果,不能手动注入用户;用户注入仅由 crate 内受信任 中间件(如 TokenAuthMiddleware)完成。

Source

pub fn ui_catalog(&self) -> Result<UiCatalog, BaseError>

按当前请求认证身份返回可访问的版本化 UI 目录。

目录过滤与真实 Action dispatch 复用同一份构建期授权策略。

Source

pub fn with_request_id(self, request_id: RequestId) -> Self

设置本次派发的 request_id(链式调用)

通常由 RequestIdMiddleware 在洋葱链最外层调用以透传上游标识; 业务侧一般无需手动设置。

Source

pub fn with_request_meta(self, request_meta: RequestMeta) -> Self

注入由传输适配器构造的请求元数据(链式调用)。

Source

pub fn with_module(self, module: impl Into<String>) -> Self

设置所属模块名(链式调用)。

由 Registry::dispatch 注入,用于 metrics module 标签等可观测性标注。

Source

pub fn dispatch_target(&self) -> Option<(&str, &str)>

返回当前实际派发的 module 与 action。

该身份由 Registry 在进入中间件链前覆盖注入,可供安全中间件绑定目标; 未经 Registry 派发而直接构造的上下文返回 None。

Source

pub fn with_table_definition(self, definition: TableDefinition) -> Self

设置表定义(链式调用)。

Source

pub fn table_definition(&self) -> Result<&TableDefinition, BaseError>

返回当前 Action 绑定的表定义。

Source

pub fn datasource(&self) -> Option<&DatasourceId>

返回本次派发所属逻辑数据源。

Source

pub fn table_query(&self) -> Result<TableQuery, BaseError>

创建默认失败关闭的表查询构建器。

带 tenant key 的表必须存在普通 TenantContext,并始终自动施加租户条件。 系统身份不会隐式绕过;全域访问必须显式调用 ActionContext::system_table_query。

Source

pub fn system_table_query( &self, capability: SystemTenantCapability, ) -> Result<TableQuery, BaseError>

使用显式、已绑定当前请求 actor 的系统 capability 创建全域表查询。

调用方必须先通过 ActionContext::system_tenant 取得 capability,再在具体 repository 旁路中显式传回;普通 CRUD 只调用 ActionContext::table_query, 因而不会自动获得全租户访问。

Source

pub fn tables(&self) -> Result<Tables, BaseError>

创建 BR 心智连续的 Tables 入口。

Source

pub fn system_tables( &self, capability: SystemTenantCapability, ) -> Result<Tables, BaseError>

使用显式系统 capability 创建全域 Tables 入口。

Source

pub async fn begin_transaction(&self) -> Result<AnyTransaction, BaseError>

开启一个数据库事务(受保护层多步写的原子作用域)

返回 AnyTransaction,可传入 TableQuery 的 *_in_tx 系列方法(insert_in_tx/update_in_tx/delete_in_tx/ select_in_tx 等),使受权限/校验/软删保护的多步写在同一事务内原子提交或 整体回滚。调用方负责显式 commit();若 AnyTransaction 在未提交时被 drop, sqlx 会尽力回滚。

仅在启用 mysql 或 postgres feature 时可用。

§返回
  • Ok(AnyTransaction):活动事务(按运行时后端分派)
  • Err(BaseError::DatabaseNotInitialized):当前应用未配置数据库
  • Err(BaseError::DatabaseTransactionFailed):开启事务失败
§示例
ⓘ
let mut tx = ctx.begin_transaction().await?;
let id = ctx.table_query()?.insert_returning_id_in_tx(&mut tx, parent).await?.1;
ctx.table_query()?.insert_in_tx(&mut tx, child_with(id)).await?;
tx.commit().await?;
Source

pub async fn begin_transaction_on( &self, source: &DatasourceId, ) -> Result<AnyTransaction, BaseError>

在指定逻辑数据源上开启事务。

Source

pub fn database(&self) -> Result<&AnyDatabase, BaseError>

返回本请求使用的数据库容器(模块源 → 表定义源 → 默认源)。

Source

pub fn database_on( &self, source: &DatasourceId, ) -> Result<&AnyDatabase, BaseError>

返回指定数据源的数据库容器。

Source

pub async fn set_local( &self, tx: &mut AnyTransaction, key: &str, value: &str, ) -> Result<(), BaseError>

把键值写入当前事务的局部会话配置(PostgreSQL SET LOCAL 语义)。

委托 yang_db 的 Transaction::set_local:键名经严格标识符校验后作为字符串 常量进入 SQL,值走绑定参数;作用域限于当前事务,提交或回滚后由 PostgreSQL 自动还原。使用连接池时会话级配置可能被后续请求复用,因此这里固定用事务局部 (is_local = true),不提供会话级写入。

仅 PostgreSQL 支持;MySQL 事务返回 BaseError::ConfigError(MySQL 没有 等价的事务级 SET LOCAL,会话变量会跨池化连接泄漏)。

§示例
ⓘ
let mut tx = ctx.begin_transaction().await?;
ctx.set_local(&mut tx, "app.tenant_id", "42").await?;
// 事务内 RLS 策略可读取 current_setting('app.tenant_id')
tx.commit().await?;
Source

pub async fn set_tenant_local( &self, tx: &mut AnyTransaction, ) -> Result<(), BaseError>

把当前 TenantContext 的租户 ID 写入事务局部配置 ActionContext::TENANT_LOCAL_KEY(默认 app.tenant_id)。

供 PostgreSQL RLS 策略读取;缺少普通租户 capability 时返回 BaseError::Unauthorized。

Source

pub fn user_roles(&self) -> Vec<String>

获取用户角色列表(克隆为 Vec)

§返回
  • 用户角色列表(如果用户未登录则返回空列表)
Source

pub fn user_roles_set(&self) -> Option<&HashSet<String>>

获取用户角色集合引用

返回用户角色的 HashSet 引用,支持 O(1) 包含检查。 如果用户未登录则返回 None。

§返回
  • Some(&HashSet<String>): 用户角色集合引用
  • None: 用户未登录

Trait Implementations§

Source§

impl Clone for ActionContext

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ActionContext

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more