yang-base 0.6.0

个人使用构建后端服务器
Documentation

yang-base

yang-base 0.6.0 是 YANG 后端基础库,提供构建期定义内核(Addon/Module/Action/fields/params → 冻结 Catalog + Registry)、类型化 Action、显式资源所有权(Tools)、schema-first 数据表、HTTP 客户端、JWT Token 管理和可选 Axum HTTP 传输。

当前应用侧的核心链路是:

fields! / params! / #[derive(Action)]
  -> AppBuilder::build(tools)
  -> BuiltApp(DefinitionCatalog + Registry + TableDefinition)
  -> ActionContext + TableQuery

应用定义在构建期一次性校验冻结,请求期只剩 slot 派发、类型化反序列化与受控 SQL。

Features

Feature 默认 能力
mysql 是 Tools MySQL 资源槽、schema 同步、TableHandle、TableQuery 与内置 CRUD
postgres 否 Tools PostgreSQL 资源槽(AnyDatabase)、schema 同步、Record 动态解码与 TableQuery 执行
redis 是 Tools Redis 资源槽与 Redis 数据结构 API
token 是 JWT 签发、刷新与 Redis 撤销列表;自动启用 redis
http 是 带超时、重试和熔断的 HTTP 客户端(Tools http 槽)
validator 是 Email、Phone、Regex 严格验证
plugin-schema 是 插件配置 JSON Schema 验证
metrics 否 Action 指标门面,不绑定 exporter
openapi 否 从 DefinitionCatalog 投影 OpenAPI 3.1 JSON
admin-metadata 否 后台展示元数据;不改变 dispatch
transport-axum 否 Axum 0.8 HTTP 传输适配器(CORS/超时/压缩/健康端点/文件与重定向响应)

default-features = false 保留插件、definition 内核、Action 和表定义核心,不引入数据库或网络驱动。

安装

发布版本:

[dependencies]
yang-base = "0.6.0"

同一 workspace 联调:

[dependencies]
yang-base = { path = "../yang-base" }

按需选择 feature:

# 仅核心模型
yang-base = { version = "0.6.0", default-features = false }

# 核心模型 + MySQL
yang-base = { version = "0.6.0", default-features = false, features = ["mysql"] }

# 核心模型 + PostgreSQL
yang-base = { version = "0.6.0", default-features = false, features = ["postgres"] }

# 核心模型 + MySQL 与 PostgreSQL 双后端
yang-base = { version = "0.6.0", default-features = false, features = ["mysql", "postgres"] }

# 核心模型 + Redis
yang-base = { version = "0.6.0", default-features = false, features = ["redis"] }

快速开始:定义表并注册 CRUD

use std::sync::Arc;
use yang_base::definition::{
    AddonSpec, AppBuilder, BuildError, BuiltApp, Key, ModuleSpec, Str, TableSpec, Timestamp,
};
use yang_base::tools::Tools;
use yang_base::{addon, fields, module, table};

fn build_app(tools: Arc<Tools>) -> Result<BuiltApp, BuildError> {
    let users = TableSpec::new(table!("users"))
        .title("用户表")
        .fields(fields! {
            id => Key::new(),
            username => Str::new()
                .title("用户名")
                .require(true)
                .min_length(3)
                .max_length(64)
                .unique(true)
                .filterable(true)
                .sortable(true),
            email => Str::new()
                .title("邮箱")
                .require(true)
                .max_length(128)
                .email()
                .unique(true),
            created_at => Timestamp::new().created_at(),
            updated_at => Timestamp::new().updated_at(),
            deleted_at => Timestamp::new().soft_delete(),
        });

    let user_module = ModuleSpec::new(module!("user.users"))
        .table(users)
        .crud()
        .expect("合法主表应注册六个标准 CRUD Action");

    Ok(AppBuilder::new()
        .addon(AddonSpec::new(addon!("user")).module(user_module))
        .build(tools)?)
}

.crud() 原子注册六个标准 API:

Action Method Path 用途
add POST /api/user/users 插入一条 Record
put PUT /api/user/users 按主键更新 data 中的字段
del DELETE /api/user/users 按主键删除或软删除
get GET /api/user/users 按主键读取一条 Record
select POST /api/user/users/query where 树、排序与分页查询
table GET /api/user/users/schema 返回输入/输出 JSON Schema

默认前缀由完整 Module 名生成(点替换为 /),user.users 即上表路径;需要自定义路径时改用 crud_at。.crud() 同时生成运行时授权契约:add、put、del 需要 user.users:write,get、select、table 需要 user.users:read;把 user.users 替换为实际的 Module 全名即得到其它模块的权限名。六个 Action 的 Catalog schema 不是通用 Record 占位符,而是从当前主表的 TableDefinition 生成,包含真实主键类型、可读/可写字段,以及允许筛选和排序的字段枚举。

ModuleSpec::table 绑定模块主表;当前定义内核只支持单个主表,不提供附属表 schema 入口。

自定义 API

自定义 Action 实现 TypedHandler 并派生 Action。注册时用 ModuleSpec::action 将 handler 与承载 HTTP method、path、operation id、状态码和标签的 ActionSpec 原子绑定:

use yang_base::action::TypedAction;
use yang_base::definition::{ActionSpec, HttpMethod, ModuleSpec, RouteSpec};
use yang_base::{action_name, module};

fn build_system_module(health_action: impl TypedAction) -> ModuleSpec {
    ModuleSpec::new(module!("system.health")).action(
        ActionSpec::new(
            action_name!("health"),
            RouteSpec::new(HttpMethod::Get, "/health", "system.health"),
        )
        .tag("system"),
        health_action,
    )
}

多个端点可链式多次调用 ModuleSpec::action;每次调用接受不同的 DynAction 实现。

公开与受保护 Action 可以注册在同一个 ModuleSpec。Action 默认受保护,只有带 #[action(..., public)] 的端点跳过认证;TokenAuthMiddleware 默认 scope 为 ProtectedActions,因此登录、注册等公开端点不会被强制要求 Bearer Token;调用 authenticate_public_actions() 后切换为 AllActions(公开端点也会校验可选的 Bearer Token)。日志、限流等普通中间件仍默认覆盖全部端点。

路由模板与跨模块冲突统一在 AppBuilder::build 构建期校验。动态段必须使用 Axum 0.8 的 /users/{id} 与 /files/{*path} 语法,旧式 :id / *path 会在 transport 启动前返回配置错误。同一路径可以注册不同 HTTP method,但匹配集合相同的模板会被视为冲突。

动态行:Record

Record 是内置 CRUD 与动态查询统一使用的行对象,序列化后就是普通 JSON object:

use yang_base::table::Record;

let mut row = Record::new()
    .set("username", "alice")
    .set("email", "alice@example.com");
row.insert("active", true);

let username: String = row.require("username").expect("username 必须是字符串");
let nickname: Option<String> = row.optional("nickname").expect("nickname 类型应有效");
  • set:链式写入字段。
  • insert:原地写入并返回旧值。
  • require::<T>:必需字段的类型化读取。
  • optional::<T>:缺失或 null 返回 None。
  • as_map / into_map:以只读引用或所有权形式访问底层 JSON 字段映射。

表字段能力

常用 Field 构造器:

  • id、string、integer、bigint、float、double、boolean
  • date、datetime、timestamp
  • json、text、enumeration
  • created_at、updated_at、soft_delete

常用修饰器:

  • 结构:label、required、nullable、default、primary_key、auto_increment
  • 校验:length、min_length、max_length、min、max、email、phone、url、regex
  • 索引:unique、unique_named、index、index_named
  • 权限:readable_by、writable_by、filterable_by、sortable_by、secret
  • 关联:relation、relation_display_fields

字段存储类型与关系元数据正交。普通外键列先按真实数据库类型构造,再附加关系,例如 Field::bigint("user_id").relation("users", "id", RelationType::ManyToOne)。

Table::build() 是集中校验边界:它检查表/字段标识符、主键、重复字段、索引引用、时间戳角色、默认排序和字段形态,然后生成不可变 TableDefinition。

完整示例见 表定义指南 和 batch_field_config.rs。

数据库与 Redis

启用默认 feature 后,MySQL/Redis 客户端经 ToolsBuilder 注册进应用资源并由每个 BuiltApp 显式持有(无进程级全局单例)。postgres 是可选 feature,启用后 PostgreSQL 连接池进入同一个 AnyDatabase 数据库槽。初始化配置类型来自 yang-db;直接构造这些客户端的应用还需声明匹配的依赖:

yang-db = { version = "0.3.1", default-features = false, features = ["mysql", "redis"] }

初始化示例:

use std::sync::Arc;
use yang_base::tools::ToolsBuilder;
use yang_base::BaseError;
use yang_db::{redis::RedisConfig, Database, DatabaseConfig, RedisClient};

async fn build_tools() -> Result<Arc<yang_base::tools::Tools>, BaseError> {
    let database = Database::connect_with_config(
        "mysql://root:password@localhost/mydb",
        DatabaseConfig::default(),
    )
    .await?;
    let cache = RedisClient::connect_with_config(
        "redis://127.0.0.1:6379",
        RedisConfig::default(),
    )
    .await?;

    let tools = ToolsBuilder::new()
        .mysql(database)
        .cache(cache)
        .build()?;
    Ok(Arc::new(tools))
}

面向请求的单表访问优先走 ActionContext::table_query();它携带字段权限、软删除、慢查询阈值和 request id。Tools::mysql()(MySQL 连接池)与 Tools::database()(AnyDatabase)返回的都是不受保护的数据库句柄,只适合初始化、系统任务和明确承担授权责任的底层操作。

TableQuery 会在 SQL 生成前按 TableDefinition 校验 WHERE 字段、筛选权限、操作符和值类型;IN 与 BETWEEN 的每个值都逐项校验。where_eq(field, null) / where_ne(field, null) 分别生成 IS NULL / IS NOT NULL,也可以显式调用 where_null / where_not_null,不会生成语义错误的 = NULL 或 != NULL。

PostgreSQL 接入状态

postgres feature 与 mysql 独立编译,也可同时启用。下表说明能力在 yang-base 层的实际接入 状态,而非底层数据库自身能力:

能力 yang-db 支持 base 接入状态 说明
连接池与生命周期(health_check / close / pool_status) 是 已接入 AnyDatabase::postgres + Tools 统一数据库槽
Record 动态行解码 是 已接入 覆盖 PG 类型族,见 integration_record_pg
声明式 schema 同步 是 已接入 DatabaseInitializer::from_any;PG 使用单事务 DDL + pg_advisory_lock,枚举字段 fail-closed
事务 / 保存点 是 已接入(保存点需直接用 yang-db) ActionContext::begin_transaction 返回 AnyTransaction,提交/回滚按后端分派
事务局部配置(SET LOCAL) 是 已接入 ActionContext::set_local / set_tenant_local 用 set_config(..., true) 写入 app.tenant_id;仅 PostgreSQL,MySQL 明确返回配置错误
TableQuery / 内置 CRUD / 受保护查询 是 已接入 SELECT/分页/COUNT/软删/租户/权限/insert/update/delete 均有 PG 执行分支
ORDER BY ... NULLS FIRST/LAST 是 已接入 TableQuery::order_nulls;MySQL 用 field IS NULL 排序表达式模拟
批量 upsert(ON CONFLICT) 是 已接入 TableQuery::{upsert_batch, upsert_batch_do_nothing} 及 _in_tx 变体,冲突列必须显式传入
RETURNING(INSERT) 是 已接入 TableQuery::insert_returning(ReturningTarget::{Pk, Columns, All});UUID/text/numeric 主键可回填;MySQL 仅支持整型主键
update/delete RETURNING、CTE、窗口、SKIP LOCKED 是 未接入 可直接使用 yang-db 的 PostgreSQL API,但 base 的 TableQuery 未暴露这些入口
COPY / LISTEN / NOTIFY 是 未封装 yang-db 已提供 copy_from_csv / copy_to_csv / PgNotificationListener;base 不额外声明
range / jsonpath / 全文检索 / EXPLAIN / 内省 / 2PC / 表锁 是 未封装 通过 yang-db 的 PostgreSQL API 使用;base 不重复包装

逻辑复制 / FDW / backup / restore / 迁移 CLI / 多主机 / PgBouncer 属部署或运维层能力, 不在 yang-base 与 yang-db 的承诺范围内;完整边界见 docs/reference/BACKEND_CAPABILITIES.md。

Tools::mysql() 在运行期配置为 PostgreSQL 时返回 DatabaseNotInitialized,避免把 PG 连接池 误当 MySQL 使用;需要 PG 后端时通过 Tools::database() 取得 AnyDatabase,再调用 as_postgres()。

PG 集成测试为 #[ignore],需要真实实例:

PG_TEST_URL=postgres://postgres:postgres@127.0.0.1:55432/test \
  cargo test -p yang-base --no-default-features --features postgres \
  --test integration_record_pg -- --ignored --test-threads=1

目录

src/
├── action/       # Action(业务 trait) / TypedHandler / TypedAction / DynAction 与 builtin CRUD
├── definition/   # AppBuilder / BuiltApp / Catalog / Registry / fields! / params!
├── tools.rs      # ToolsBuilder / Tools(db/cache/token/http + 类型化扩展)
├── database/     # DatabaseInitializer(迁移治理与启动期 schema 同步)
├── router/       # 洋葱中间件(RequestId / 鉴权)
├── table/        # Table、Field、TableDefinition、Record、TableQuery
├── plugin/       # 旧代插件生命周期与依赖管理
├── transport/    # 可选 Axum 0.8 HTTP 适配器(transport-axum)
├── http/         # 可选 HTTP 客户端
├── token/        # 可选 JWT 与撤销列表
└── error/        # BaseError

验证

cargo fmt --check
cargo test --lib -p yang-base
cargo check -p yang-base --examples --all-features
cargo clippy -p yang-base --all-targets --all-features -- -D warnings

需要真实 MySQL/Redis 的 ignored 测试应在容器就绪后单线程运行。

许可证

MIT OR Apache-2.0