# yang-base/action — Action System
**Parent:** `crates/yang-base/AGENTS.md`
## OVERVIEW
类型化后端操作边界。本模块负责请求提取、用户/请求上下文、静态 Action 元数据、统一响应,以及运行在运行时 `TableDefinition` + `Record` 之上的非泛型内置 CRUD Handler。Action 的定义与注册由 `../definition/` 内核承载:`ModuleSpec` 聚合 `(ActionSpec, Arc<dyn DynAction>)`,`AppBuilder::build` 交叉校验后冻结为 `Registry`,运行期只认 slot 派发。
## STRUCTURE
```text
action/
├── mod.rs # public re-exports
├── action_trait.rs # Permission and PermissionMode
├── auth/ # token feature: 内置 Login/Refresh/Logout + TokenAuthMiddleware
│ ├── mod.rs # 模块文档 + 子模块声明 + re-export(公开路径不变)
│ ├── dto.rs # 输入/输出 DTO(凭证/Token 字段含 Debug 脱敏)+ TokenPairClaims/VerifiedSubject
│ ├── audit.rs # AuthAuditEvent/AuthAuditHook/TracingAuditHook + token_fingerprint
│ ├── login.rs # CredentialVerifier trait + LoginAction
│ ├── refresh.rs # RefreshClaimsResolver/DefaultRefreshClaims + RefreshAction(Token Rotation)
│ ├── logout.rs # LogoutAction(AUTH-4 所有权校验 + subject 水位线撤销)
│ ├── middleware.rs # TokenAuthMiddleware + TokenClaimsValidator/IntoUserProjection
│ ├── password.rs # PasswordEngine:Argon2 + spawn_blocking + 并发上限;verify_or_dummy 等时校验端口
│ ├── rate_limit.rs # AuthRateLimiter/AuthOperation:Redis 原子限流与失败计数
│ ├── email_verification.rs # 一次性邮箱验证码(摘要存储/防枚举/原子消费 + verify_only 只验不消费,投递 trait 注入)
│ ├── browser_session.rs # BrowserSession:会话 Cookie 签发/清除 + 同源校验
│ ├── mfa.rs # TotpVerifier/TotpLiteVerifier:TOTP 第二因子校验端口(±1 窗口、Redis 原子防重放)
│ └── __tests__/ # auth_test.rs:原 mod.rs 内联测试原样迁移
├── context.rs # ActionContext, User(资源经 Arc<Tools> 显式持有)
├── functional.rs # FnAction(crate 内部)/ CrudFnAction(公开,供 crud_at_with_mutations 注入自定义写 Handler)
├── meta.rs # ActionMeta generated by #[derive(Action)]
├── request.rs # JSON body, headers, query and path params
├── request_context.rs # RequestContext / TenantContext / ActorContext
├── request_id.rs # process-local u128 request id
├── request_meta.rs # transport-neutral method/URI/address 元数据
├── response.rs # ApiResponse / ResponseBody / wrap_dispatch_output
├── sql_bridge.rs # count_query:对已完成搜索/筛选/租户注入的 TableQuery 执行 COUNT(mysql/postgres feature)
├── step_up.rs # token feature: Step-up 重认证
├── tenant.rs # TenantResolver / TenantResolverMiddleware
├── typed.rs # Action(业务 trait) / TypedHandler / TypedAction / DynAction
├── ui_catalog.rs # 请求级 UI 目录 Action
├── upload.rs # UploadedFile 句柄
├── builtin/ # mysql/postgres feature:add, put, del, get, select, table + relation_options
└── __tests__/ # colocated unit tests
```
## WHERE TO LOOK
| Define a custom Action (derive) | `typed.rs` | 实现业务 `Action` trait(`index` + 强类型 Input/Output),`#[derive(Action)]` 生成元数据 |
| Define a custom Action (fn) | `../definition/interface.rs` | `ModuleSpec::action_fn(name, f)` 返回终结式 `ActionFnBuilder` |
| Register an endpoint | `../definition/spec.rs`、`../definition/interface.rs` | `ModuleSpec::native_action` / `action_fn(...).register()` / `action(spec, handler)` |
| Install table CRUD | `../definition/spec.rs` | `ModuleSpec::crud()` / `crud_at(prefix)` 安装六个内置 Action;`crud_at_with_mutations(prefix, add, put, del)` 注入自定义写 Handler |
| Extract params | `context.rs` | `request` 字段经 `ParamInput::decode` 一次反序列化;`param`/path/query helpers |
| Access table data | `context.rs` | `table_definition` and guarded `table_query` |
| Current user/roles | `context.rs` | `User`, permission and role helpers |
| 资源访问 | `context.rs` | `ctx.tools()`(`Arc<Tools>`)、`ctx.http()?`;无全局单例 |
| Request wrapper | `request.rs` | headers/query/path params and Bearer token extraction |
| Response wrapper | `response.rs` | `ApiResponse::success`, `success_value`, `fail`, `from_error` |
| Builtin behavior | `builtin/*.rs` | Dynamic row CRUD and schema response contracts |
## 两种 Action 注册形态
### 1. 派生通道:`#[derive(Action)]` + 业务 `Action` trait
```rust
#[derive(yang_base::Action)]
#[action(name = "create", display_name = "创建", permissions("org.user:write"))]
struct CreateAction;
#[async_trait::async_trait]
impl yang_base::action::Action for CreateAction {
type Input = CreateInput; // 由 params! 生成:ParamInput + DeserializeOwned + JsonSchema
type Output = CreateOutput; // Serialize + JsonSchema
async fn index(&self, ctx: ActionContext, input: Self::Input)
-> Result<Self::Output, BaseError> { /* ... */ }
}
```
- `TypedHandler` 由 blanket impl 桥接;`TypedAction` 元数据由派生宏生成,不要手写。
- 经 `ModuleSpec::native_action(handler)` 或 `actions![...]`(配合 `Module::actions()`)原子注册:route/params/权限从同一类型读出,与 Handler 同源。
### 2. 函数式通道:`ModuleSpec::action_fn` + 终结式 Builder
业务逻辑可以只是一个普通 async fn(或标注了参数类型的闭包),不实现任何 trait:
```rust
async fn create(ctx: ActionContext, input: CreateInput) -> Result<CreateOutput, BaseError> { /* ... */ }
let module = ModuleSpec::new(module_name)
.action_fn(ActionName::new("create")?, create)
.route(HttpMethod::Post, "/users") // 缺省 POST /{name}
.display_name("创建")
.permissions(["org.user:write"])
.register(); // 终结注册,返回 ModuleSpec
```
- `ActionFnBuilder` 持有半成品 `ActionSpec`;`register()` 填充 `I::params()` 与
`schemars::schema_for!(I)/(O)` 生成的 JSON Schema、补全 `operation_id` 为
`<module>.<name>`,再经 `dyn_action` 原子压入 Module。
- Schema 在注册期填充,`bind_handler_contract` 因此跳过 `DynAction::meta()`
的占位实现(`functional.rs` 的 `placeholder_meta()`,无运行期语义)。
- 两种通道产出的 `ActionSpec` 完全一致,构建期校验、Catalog/OpenAPI 投影、
中间件匹配(按 `ActionRef`)与权限语义不分通道。
## 运行期派发
```text
Registry::dispatch(handle, ctx)
-> 模块中间件洋葱链(按注册顺序,可按 ActionRef 限定目标)
-> authorize(AuthorizationPolicy)(is_public / permissions / permission_mode)
-> DynAction::dispatch
ParamInput::decode(&mut ctx.request) // body/query/path/header 只解码一次
-> 业务 Handler
-> wrap_dispatch_output(output, "成功") // ApiResponse 原样透传;ResponseBody 转附件;其余进 data
```
- 强类型内部调用走 `Registry::resolve_typed::<I, O>` + `Registry::call`
(或 `ctx.plugins()?.api_run(...)`),不经过 JSON 序列化,也不经过中间件链;
两种注册通道都支持。
- 资源一律经 `ToolsBuilder` 注册、`ctx.tools()` 获取;禁止新增进程级全局单例。
## BUILTIN ACTIONS
| `AddAction` | `Record` | `InsertResult` |
| `PutAction` | `PutInput { id: Value, data: Record }` | `AffectedResult` |
| `DelAction` | `GetByPk { id: Value }` | `AffectedResult` |
| `GetAction` | `GetByPk { id: Value }` | `Record` |
| `SelectAction` | `SelectQuery` | `SelectResult { items: Vec<Record>, ... }` |
| `TableAction` | `EmptyInput` | `TableSchemaResponse` |
| `RelationOptionsAction` | `RelationOptionsRequest` | `RelationOptionsResponse` |
These handlers are non-generic. The bound `TableDefinition` supplies the table name, primary key, schema and field permissions at runtime:
```rust
let module = ModuleSpec::new(module_name)
.table(users_table_spec)
.crud()?;
```
## CONVENTIONS
- Keep display names and descriptions in Chinese; they are user-visible catalog/OpenAPI content.
- Prefer strongly typed Input/Output structures(`params!` 生成输入)for custom Actions.
- Use `ApiResponse::success` for serializable Rust values and `success_value` only when data is already a `serde_json::Value`.
- Table-backed handlers require `ActionContext::with_table_definition`(Registry dispatch 自动注入模块主表);otherwise `table_definition` / `table_query` returns `TableDefinitionNotSet`.
- 自定义端点用 `native_action` 或 `action_fn` 注册;标准表 surface 用 `.crud()` / `.crud_at()`。
## ANTI-PATTERNS
- Do not split handler registration from HTTP route registration;两种注册通道都是原子/终结式的。
- Do not use a bare `serde_json::Value` as the whole custom Action contract to avoid defining Input/Output types.
- Do not mark an Action public unless the endpoint intentionally requires no authentication.
- Do not bypass `ctx.table_query()` with a raw global pool for user-driven table access.
- Avoid bare `unwrap()` in tests; prefer contextual `expect` or explicit error-shape assertions.
## SECURITY: raw database bypass
The pool behind `Tools::mysql()` (`ctx.tools().mysql()?`, 仅 mysql feature) / `Tools::database()`(MySQL 或 PostgreSQL 的 `AnyDatabase`)以及 `AnyDatabase::pool()` is unguarded. Queries built from them bypass field permissions, soft-delete filters, validated where trees, slow-query metadata and request-id propagation. Custom Actions should use `ctx.table_query()?` for user-facing table access.
Direct pool use is reserved for narrow system operations such as offline migrations, health probes, or carefully controlled multi-table transactions. Those paths must perform their own authorization and observability wiring.