# yang-base/action — Action System
**Parent:** `crates/yang-base/AGENTS.md`
## OVERVIEW
Typed backend operation boundary. It owns request extraction, user/global context, static Action metadata, unified responses, and the non-generic builtin CRUD handlers that operate on runtime `TableDefinition` plus `Record`.
## STRUCTURE
```text
action/
├── mod.rs # public re-exports
├── action_trait.rs # Permission and PermissionMode
├── auth.rs # token feature: LoginAction / RefreshAction / LogoutAction
├── context.rs # ActionContext, GlobalTools, User
├── meta.rs # ActionMeta generated by #[derive(Action)]
├── request.rs # JSON body, headers, query and path params
├── request_id.rs # process-local u128 request id
├── response.rs # ApiResponse helpers
├── sql_bridge.rs # WhereCondition -> TableQuery bridge
├── typed.rs # TypedHandler / TypedAction / DynAction
├── builtin/ # add, put, del, get, select and table
└── __tests__/ # colocated unit tests
```
## WHERE TO LOOK
| Define a custom Action | `typed.rs` | Implement `TypedHandler`; derive `Action` for static metadata |
| Register an endpoint | `../router/api.rs` | Build `Api::{get,post,put,patch,delete}` and pass it to `ModuleRouter::api` / `apis` |
| Install table CRUD | `../router/module_router.rs` | `.table(definition).crud()` installs all six builtin APIs |
| Extract params | `context.rs` | `extract_input_owned`, `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 |
| Global tools | `context.rs` | `GlobalTools` singleton; optional `TokenManager` |
| 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 |
## TYPED ACTION SYSTEM
### 1. `TypedHandler` — application code implements this
```rust
#[async_trait::async_trait]
pub trait TypedHandler: Send + Sync + 'static {
type Input: serde::de::DeserializeOwned + schemars::JsonSchema + Send;
type Output: serde::Serialize + schemars::JsonSchema + Send;
async fn handle(
&self,
ctx: ActionContext,
input: Self::Input,
) -> Result<Self::Output, BaseError>;
}
```
- Input is deserialized once at the erased dispatch boundary.
- Output is serialized into a successful `ApiResponse` by the blanket implementation.
- Keep the whole contract typed; `Record` is the appropriate type only for intentionally dynamic row objects.
### 2. `TypedAction` — generated metadata layer
`#[derive(Action)]` generates the implementation and its `ActionMeta`, including name, display text, permissions, public flag, permission mode, and input/output JSON Schemas. Do not implement this trait manually.
### 3. `DynAction` — router storage layer
Every `TypedAction` automatically implements the object-safe `DynAction`. `ModuleRouter` stores `Arc<dyn DynAction>`; application code normally never constructs this erased value itself.
### Registration flow
```text
impl TypedHandler + #[derive(Action)]
-> TypedAction metadata
-> Api(method, path, handler)
-> ModuleRouter::api / apis
-> DynAction + route descriptor stored atomically
```
The `Api` value is the single registration unit. It prevents handler metadata and HTTP route metadata from drifting apart.
## 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` |
These handlers are non-generic. The bound `TableDefinition` supplies the table name, primary key, schema and field permissions at runtime:
```rust
let module = ModuleRouter::new("user", "用户管理")
.table(users_definition)
.crud()?;
```
## CUSTOM API EXAMPLE
```rust
use yang_base::router::{Api, ModuleRouter};
let module = ModuleRouter::new("health", "健康检查")
.api(Api::get("/health", HealthAction).operation_id("health.check"))?;
```
## CONVENTIONS
- Keep display names and descriptions in Chinese; they are user-visible catalog/OpenAPI content.
- Prefer strongly typed Input/Output structures for custom Actions.
- Use `ApiResponse::success` for serializable Rust values and `success_value` only when data is already a `serde_json::Value`.
- Initialize `GlobalTools` once before `ActionContext::new_with_global_tools`; repeated initialization returns a configuration error.
- Table-backed handlers require `ActionContext::with_table_definition`; otherwise `table_definition` / `table_query` returns `TableDefinitionNotSet`.
- Register custom endpoints through `Api`; use `.crud()` for the standard table surface.
## 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()?`) is unguarded. Queries built from it 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.