- TableSpec 增字段 aggregate_detail: bool
- Resource / Dataset 置 true,其余 16 个置 false
- controller/crud.rs 删掉 find("Resource")/find("Dataset") + expect,改为遍历 ALL_SPECS 按 flag 注册
- 补单测 aggregate_detail_is_pinned_to_the_resource_side(聚合体 ⊆ 有子表)
- 边界账本删掉已失效的两条 CP3(controller/crud.rs find(...))
849 lines
32 KiB
Rust
849 lines
32 KiB
Rust
//! 18 个实体的表注册表 —— 通用 CRUD 引擎的**唯一**元数据来源。
|
||
//!
|
||
//! **布局(v3 spec §2.1)**:**每个实体一个文件**(18 个子模块),本文件只放
|
||
//! ① 三种元数据结构([`TableSpec`] / [`CodeSpec`] / [`FrozenColumn`])、
|
||
//! ② 跨实体共享的常量([`DELIVERY_TASK_FROZEN`] / [`DATASET_EXTRA_WHERE`])、
|
||
//! ③ [`ALL_SPECS`] 汇总、④ 启动自检 [`validate`]、⑤ 按实体名查表的三张元数据清单
|
||
//! ([`create_codes`] / [`create_defaults`] / [`create_now_columns`])。
|
||
//!
|
||
//! 数据来源:上游 `boot/ssw-tdc/ssw-tdc-controller` 下 18 个 `extends TdcCrudController`
|
||
//! 的子类,逐个抄下 `keywordColumns()` / `filterColumns()` / `tenantColumn()` /
|
||
//! `defaultOrderColumn()`;2026-10-24 用脚本对全仓 18 个控制器全量提取核对,零差异。
|
||
//!
|
||
//! 🔴 **有意偏离上游的两处**(上游缺陷,Rust 侧修正,见设计文档 §6):
|
||
//! 1. `ApiConsumeLog` 的关键字列不用基类默认的 `f_name`(该表**没有**这一列,
|
||
//! 上游一搜就 PG `42703`),改用 `f_order_code/f_app_id/f_product_id`。
|
||
//! 2. 过滤一律 `CAST(col AS TEXT) = $1`(上游把 varchar 绑给 smallint 列会 PG 报错),
|
||
//! 这条落在 `tdc/mapper.rs`,注册表本身不变。
|
||
|
||
use crate::tdc::util::code::CodeStyle;
|
||
use crate::platform::db::{json_key_to_column, valid_table};
|
||
|
||
/// 不可经编辑入口改写的「服务端权威列」。
|
||
#[derive(Debug, Clone, Copy)]
|
||
pub struct FrozenColumn {
|
||
/// DB 列名。
|
||
pub column: &'static str,
|
||
/// 中文标签(拒改时回显给调用方)。
|
||
pub label: &'static str,
|
||
}
|
||
|
||
/// 服务端生成的编码列(上游 `beforeSave` 在**创建期**生成,客户端不送)。
|
||
///
|
||
/// 键是 **camelCase JSON 键**(与 `create_defaults` 一致),由引擎换算成列名。
|
||
#[derive(Debug, Clone, Copy)]
|
||
pub struct CodeSpec {
|
||
/// camelCase JSON 键(如 `productCode`)
|
||
pub key: &'static str,
|
||
/// 业务前缀(PRO / RES / API / DS)
|
||
pub prefix: &'static str,
|
||
/// 编码格式(上游两套生成器)
|
||
pub style: CodeStyle,
|
||
/// 撞库重试次数(上游逐实体不同:Product/Resource = 5,DataInterface/Datasource = 3)。
|
||
pub retries: u32,
|
||
/// 重试用尽的失败文案(**上游逐字**)。
|
||
pub fail_msg: &'static str,
|
||
/// 「当日同前缀行数」基线是否带 `ALIVE` 谓词(上游逐实体不同:
|
||
/// DataInterface 带(`DataInterfaceServiceImpl:263-268`),Product/Resource 不带)。
|
||
pub baseline_alive: bool,
|
||
}
|
||
|
||
/// 一个可 CRUD 实体的元数据。
|
||
#[derive(Debug, Clone, Copy)]
|
||
pub struct TableSpec {
|
||
/// 实体名(路由末段,如 `Product`)。
|
||
pub api_name: &'static str,
|
||
/// 路由前缀(如 `/api/ssw/tdc/Product`)。
|
||
pub path: &'static str,
|
||
/// 物理表名(如 `tdc_product`)。
|
||
pub table: &'static str,
|
||
/// 关键字模糊匹配列(多列 OR)。
|
||
pub keyword_columns: &'static [&'static str],
|
||
/// 精确过滤:`(请求参数名, DB 列名)`。
|
||
pub filter_columns: &'static [(&'static str, &'static str)],
|
||
/// 租户列;`Some` 时客户端传 `tenantId` 一律拒(对齐上游 `tenantColumn()` 默认值)。
|
||
pub tenant_column: Option<&'static str>,
|
||
/// 默认排序列(**倒序**)。
|
||
pub default_order_column: &'static str,
|
||
/// 附加固定谓词(与 `ALIVE` AND 起来)。
|
||
pub extra_where: Option<&'static str>,
|
||
/// 禁止新建时的拒因(`None` = 允许)。
|
||
pub no_create: Option<&'static str>,
|
||
/// 禁止修改时的拒因。
|
||
pub no_update: Option<&'static str>,
|
||
/// 禁止删除时的拒因。
|
||
pub no_delete: Option<&'static str>,
|
||
/// 不可经编辑入口改写的列。
|
||
pub frozen_columns: &'static [FrozenColumn],
|
||
/// **不外泄字段**(上游实体上标了 `@JsonIgnore` 的属性)—— 键是 **camelCase JSON 键**。
|
||
///
|
||
/// 🔴 语义**逐字照抄 Jackson 的 `@JsonIgnore`**(既管序列化,也管反序列化):
|
||
/// - **出参**:该键**整条删掉**(不是置 null);
|
||
/// - **入参**:请求体里带这个键 ⇒ **静默忽略**(不写库),与上游绑定不到实体字段一致。
|
||
///
|
||
/// 上游真源(2026-10-25 核对,全仓只有这 3 个属性标了 `@JsonIgnore`):
|
||
/// - `IdentityEntity.f_secret_key`(接入 SK = 连接器前端登录密钥)
|
||
/// - `DeliveryTaskEntity.f_dev_url`(工作台外网入口,URL 内含 token)
|
||
/// - `DeliveryTaskEntity.f_dev_token`(工作台控制通道令牌 `X-Session-Token`)
|
||
///
|
||
/// ⚠️ 与 [`TableSpec::frozen_columns`] 的区别:frozen 是「**拒改**并回话术」,
|
||
/// hidden 是「**当它不存在**」—— 上游两者对 `f_dev_url` / `f_dev_token` **同时存在**
|
||
/// (实体 `@JsonIgnore` + 控制器 `changedAuthorityColumn`),本仓照抄。
|
||
pub hidden_fields: &'static [&'static str],
|
||
/// **子表聚合声明**(上游 `ResourceService.withChildren`)——
|
||
/// `(输出 JSON 键, 子表名)`;**空 = 该实体没有 `/Detail` 聚合体**。
|
||
///
|
||
/// 🔴 引擎**零 `match api_name`** ⇒ 子表由**业务 spec 声明**
|
||
/// (v3 spec §2.3.1 C1;与技能 `EntitySpec.creator_fixed` 同一手法)。
|
||
/// 声明顺序 = 输出顺序(上游 `fieldRules` 在前、`maskRules` 在后)。
|
||
pub child_tables: &'static [(&'static str, &'static str)],
|
||
/// 「查无此条」文案(**上游逐字**)。
|
||
///
|
||
/// - 默认「记录不存在或已删除」(上游 `ResourceController#detailOf`)
|
||
/// - `Dataset` 是「数据集不存在或资源已删除」(上游 `DatasetController#detailOf`,`:142`)
|
||
///
|
||
/// 🔴 引擎**零 `match api_name`** ⇒ 文案由**业务 spec 声明**
|
||
/// (v3 spec §2.3.1 C2;与技能 `EntitySpec.creator_fixed` 同一手法)。
|
||
pub not_found_msg: &'static str,
|
||
/// 是否注册**只读聚合体**路由 `GET {path}/{id}/Detail`(上游 `ResourceController#detailOf` /
|
||
/// `DatasetController#detailOf`)。
|
||
///
|
||
/// 🔴 引擎**零硬编码实体名** ⇒ 控制器**遍历 spec** 决定注册哪条
|
||
/// (v3 spec §2.3.1 C3)。聚合体里挂哪些子表由 [`TableSpec::child_tables`] 决定。
|
||
pub aggregate_detail: bool,
|
||
}
|
||
|
||
/// `DeliveryTask` 的 41 个服务端权威列。
|
||
///
|
||
/// 逐字抄自上游 `DeliveryTaskController#changedAuthorityColumn()`(2026-10-24 核对)。
|
||
/// 判定口径:**只拒「值真的变化」**——前端编辑弹窗会整行回传,按「字段出现即拒」会误伤正常编辑。
|
||
pub const DELIVERY_TASK_FROZEN: &[FrozenColumn] = &[
|
||
FrozenColumn {
|
||
column: "f_self_role",
|
||
label: "本端角色",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_self_connector_id",
|
||
label: "本端连接器",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_provider_connector_id",
|
||
label: "提供方连接器",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_consumer_connector_id",
|
||
label: "使用方连接器",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_tds_task_id",
|
||
label: "平台任务号",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_status_version",
|
||
label: "状态版本",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_ready_status",
|
||
label: "就绪状态",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_status",
|
||
label: "任务状态",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_run_status",
|
||
label: "运行状态",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_event_seq",
|
||
label: "事件序号",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_app_id",
|
||
label: "数据面 AppId",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_app_key",
|
||
label: "数据面 AppKey",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_destroy_status",
|
||
label: "销毁状态",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_peer_endpoint",
|
||
label: "对端地址",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_peer_public_key",
|
||
label: "对端公钥快照",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_contract_id",
|
||
label: "合约",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_product_id",
|
||
label: "产品",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_business_space_id",
|
||
label: "业务空间",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_session_status",
|
||
label: "会话状态",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_session_end",
|
||
label: "会话结束时刻",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_session_pod",
|
||
label: "会话 Pod",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_session_start",
|
||
label: "会话开始时刻",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_session_expire",
|
||
label: "会话到期时刻",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_session_node_port",
|
||
label: "会话 NodePort",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_session_control_port",
|
||
label: "会话控制端口",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_session_url",
|
||
label: "会话地址",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_session_token",
|
||
label: "会话令牌",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_sandbox_image",
|
||
label: "沙箱镜像",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_sandbox_mode",
|
||
label: "沙箱形态",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_export_reject_reason",
|
||
label: "导出被拒原因",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_dev_pod_name",
|
||
label: "工作台Pod",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_dev_work_ref",
|
||
label: "工作目录引用",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_algorithm_hash",
|
||
label: "算法哈希",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_dev_url",
|
||
label: "工作台地址",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_dev_token",
|
||
label: "工作台令牌",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_dev_node_port",
|
||
label: "工作台NodePort",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_dev_control_port",
|
||
label: "工作台控制端口",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_audit_status",
|
||
label: "审核状态",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_audit_opinion",
|
||
label: "审核意见",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_audit_user_id",
|
||
label: "审核人",
|
||
},
|
||
FrozenColumn {
|
||
column: "f_audit_time",
|
||
label: "审核时间",
|
||
},
|
||
];
|
||
|
||
/// 数据集(派生态只读视图)的固定谓词。
|
||
///
|
||
/// 逐字抄自上游 `DatasetController#buildWrapper`。🔴 `(f_source_kind='DATASOURCE' OR IS NULL)`
|
||
/// 必须写全 —— 只写 `='DATASOURCE'` 会让存量 NULL 行**静默消失**。
|
||
pub const DATASET_EXTRA_WHERE: &str = "f_status = 'ENABLED' \
|
||
AND f_mount_status = 'MOUNTED' \
|
||
AND f_dataset_name IS NOT NULL \
|
||
AND (f_source_kind = 'DATASOURCE' OR f_source_kind IS NULL) \
|
||
AND EXISTS (SELECT 1 FROM tdc_datasource d WHERE d.f_id = tdc_resource.f_datasource_id \
|
||
AND d.f_status = 'ENABLED' AND (d.f_delete_mark IS NULL OR d.f_delete_mark = 0))";
|
||
|
||
/// 全部可 CRUD 实体(上游 18 个 `TdcCrudController` 子类)—— **每个实体一个文件**。
|
||
pub mod api_consume_log;
|
||
pub mod audit_log;
|
||
pub mod contract;
|
||
pub mod credential;
|
||
pub mod data_interface;
|
||
pub mod dataset;
|
||
pub mod datasource;
|
||
pub mod delivery_log;
|
||
pub mod delivery_task;
|
||
pub mod destroy_log;
|
||
pub mod identity;
|
||
pub mod notification;
|
||
pub mod order;
|
||
pub mod policy;
|
||
pub mod policy_check_log;
|
||
pub mod policy_template;
|
||
pub mod product;
|
||
pub mod resource;
|
||
|
||
/// 全部可 CRUD 实体(上游 18 个 `TdcCrudController` 子类,顺序按路由注册顺序)。
|
||
///
|
||
/// 🔴 每个实体一个文件([`super`] 下 18 个子模块)⇒ 加实体只需**新建一个文件**
|
||
/// + 在这里加一行 `pub mod xxx;` + 在 `ALL_SPECS` 里加一行 ⇒ 不用碰引擎。
|
||
pub static ALL_SPECS: &[TableSpec] = &[
|
||
api_consume_log::SPEC,
|
||
audit_log::SPEC,
|
||
contract::SPEC,
|
||
credential::SPEC,
|
||
data_interface::SPEC,
|
||
dataset::SPEC,
|
||
datasource::SPEC,
|
||
delivery_log::SPEC,
|
||
delivery_task::SPEC,
|
||
destroy_log::SPEC,
|
||
identity::SPEC,
|
||
notification::SPEC,
|
||
order::SPEC,
|
||
policy::SPEC,
|
||
policy_check_log::SPEC,
|
||
policy_template::SPEC,
|
||
product::SPEC,
|
||
resource::SPEC,
|
||
];
|
||
|
||
/// 实体 → 权限键(设计文档 §5.1「声明式权限键」)。
|
||
///
|
||
/// 键名 = 实体名的 snake_case;**只用于服务端对写操作的二次校验**,不用于隐藏菜单。
|
||
/// 18 个实体一个不少 —— `permission_keys_cover_every_entity` 会守住这条。
|
||
pub const PERMISSION_KEYS: &[(&str, &str)] = &[
|
||
("ApiConsumeLog", "api_consume_log"),
|
||
("AuditLog", "audit_log"),
|
||
("Contract", "contract"),
|
||
("Credential", "credential"),
|
||
("DataInterface", "data_interface"),
|
||
("Dataset", "dataset"),
|
||
("Datasource", "datasource"),
|
||
("DeliveryLog", "delivery_log"),
|
||
("DeliveryTask", "delivery_task"),
|
||
("DestroyLog", "destroy_log"),
|
||
("Identity", "identity"),
|
||
("Notification", "notification"),
|
||
("Order", "order"),
|
||
("Policy", "policy"),
|
||
("PolicyCheckLog", "policy_check_log"),
|
||
("PolicyTemplate", "policy_template"),
|
||
("Product", "product"),
|
||
("Resource", "resource"),
|
||
];
|
||
|
||
/// 查实体的权限键。
|
||
pub fn permission_key(api_name: &str) -> Option<&'static str> {
|
||
PERMISSION_KEYS
|
||
.iter()
|
||
.find(|(name, _)| *name == api_name)
|
||
.map(|(_, key)| *key)
|
||
}
|
||
|
||
/// 按实体名查注册表。
|
||
pub fn find(api_name: &str) -> Option<&'static TableSpec> {
|
||
ALL_SPECS.iter().find(|s| s.api_name == api_name)
|
||
}
|
||
|
||
/// 注册表自检:**所有拼进 SQL 的标识符**(表名、过滤列、关键字列、默认排序列、
|
||
/// 租户列、冻结列、服务端生成的编码列)都必须过白名单(防拼接注入)。
|
||
///
|
||
/// ⚠️ `filter_columns` 的**键**(`pname`,如 `status`)是**请求参数名**、不是列名,
|
||
/// **不**拿它过白名单。
|
||
pub fn validate() -> Result<(), String> {
|
||
for spec in ALL_SPECS {
|
||
if valid_table(spec.table).is_none() {
|
||
return Err(format!("注册表表名非法: {}", spec.table));
|
||
}
|
||
for (_pname, col) in spec.filter_columns {
|
||
if valid_table(col).is_none() {
|
||
return Err(format!("注册表过滤列非法: {}.{}", spec.table, col));
|
||
}
|
||
}
|
||
for col in spec.keyword_columns {
|
||
if valid_table(col).is_none() {
|
||
return Err(format!("注册表关键字列非法: {}.{}", spec.table, col));
|
||
}
|
||
}
|
||
if valid_table(spec.default_order_column).is_none() {
|
||
return Err(format!(
|
||
"注册表默认排序列非法: {}.{}",
|
||
spec.table, spec.default_order_column
|
||
));
|
||
}
|
||
if let Some(col) = spec.tenant_column {
|
||
if valid_table(col).is_none() {
|
||
return Err(format!("注册表租户列非法: {}.{}", spec.table, col));
|
||
}
|
||
}
|
||
for fc in spec.frozen_columns {
|
||
if valid_table(fc.column).is_none() {
|
||
return Err(format!("注册表冻结列非法: {}.{}", spec.table, fc.column));
|
||
}
|
||
}
|
||
for key in spec.hidden_fields {
|
||
let col = json_key_to_column(key);
|
||
if valid_table(&col).is_none() {
|
||
return Err(format!("注册表不外泄字段非法: {}.{}", spec.table, col));
|
||
}
|
||
}
|
||
for cs in create_codes(spec.api_name) {
|
||
let col = json_key_to_column(cs.key);
|
||
if valid_table(&col).is_none() {
|
||
return Err(format!("注册表编码列非法: {}.{}", spec.table, col));
|
||
}
|
||
}
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
/// 查实体的「服务端生成编码列」清单。
|
||
///
|
||
/// 🔴 **空值即生成、显式传入不覆盖**(上游 `BizCodeUtil` javadoc 的规则)——
|
||
/// 这 4 列在 `migrate.sql` 里 NOT NULL **且无 DEFAULT**,而上游前端新建时**不送**
|
||
/// ⇒ 不生成就必 500。
|
||
pub fn create_codes(api_name: &str) -> &'static [CodeSpec] {
|
||
match api_name {
|
||
// 上游 `ProductServiceImpl#nextProductCode`(TdcCodeUtil,"PRO"):5 次
|
||
"Product" => &[CodeSpec {
|
||
key: "productCode",
|
||
prefix: "PRO",
|
||
style: CodeStyle::DaySeqTail8,
|
||
retries: 5,
|
||
fail_msg: "产品编码生成失败(连续 5 次撞库),请重试",
|
||
baseline_alive: false,
|
||
}],
|
||
// 上游 `ResourceServiceImpl#nextResourceCode`(TdcCodeUtil,"RES"):5 次
|
||
"Resource" => &[CodeSpec {
|
||
key: "resourceCode",
|
||
prefix: "RES",
|
||
style: CodeStyle::DaySeqTail8,
|
||
retries: 5,
|
||
fail_msg: "资源编码生成失败(连续 5 次撞库),请重试",
|
||
baseline_alive: false,
|
||
}],
|
||
// 上游 `DataInterfaceServiceImpl#prepare`(TdcCodeUtil,"API"):`CODE_RETRY = 3`
|
||
"DataInterface" => &[CodeSpec {
|
||
key: "interfaceCode",
|
||
prefix: "API",
|
||
style: CodeStyle::DaySeqTail8,
|
||
retries: 3,
|
||
fail_msg: "接口编码生成失败(重试 3 次仍冲突)",
|
||
// 上游 `DataInterfaceServiceImpl#countByCodePrefix:263-268` 的基线**带 ALIVE**
|
||
baseline_alive: true,
|
||
}],
|
||
// 上游 `DatasourceController#beforeSave` → 基类 `newUniqueCode`(BizCodeUtil.of("DS")):3 次
|
||
"Datasource" => &[CodeSpec {
|
||
key: "datasourceCode",
|
||
prefix: "DS",
|
||
style: CodeStyle::DayTail6,
|
||
retries: 3,
|
||
fail_msg: "系统标识生成失败(连续 3 次撞库),请重试",
|
||
// `BizCodeUtil` 无序号 ⇒ 该字段对它无意义
|
||
baseline_alive: false,
|
||
}],
|
||
_ => &[],
|
||
}
|
||
}
|
||
|
||
/// 新增时由**服务端**补齐的默认值:`(camelCase JSON 键, 常量文本)`。
|
||
///
|
||
/// `{id}` 会被替换成本次新生成的雪花号 id。请求体已经给了的键**不覆盖**
|
||
/// (「给了」= 键存在**且值非 null** —— 上游 Jackson 把 body 的 `null` 映射成字段 `null`
|
||
/// ⇒ 上游的 `if (entity.getXxx() == null)` **照样成立** ⇒ 默认值照补)。
|
||
///
|
||
/// - `AuditLog`:上游 `TdcAuditLogServiceImpl#appendChain` 在 `beforeSave` 里
|
||
/// 补 `logNo / result / logType / actorType / actorName / reportMark`,
|
||
/// Rust 侧照抄这批**非哈希链**默认值(`seqNo / prevHash / hash` 属哈希链 ⇒ P2 再补)。
|
||
/// - `Product`:新建默认**未上架**(上游 `ProductServiceImpl:130-141`,
|
||
/// `f_status` 是上架/下架动作的写点 ⇒ 默认 DISABLED;DDL 里是 `'ENABLED'` ⇒ 此处覆盖)。
|
||
/// - `Resource`:新建默认**停用**(上游 `ResourceServiceImpl:305-334`,设计 §12-1:
|
||
/// 启用态禁止挂载 ⇒ 默认启用会让「挂载数据」永远做不了)+ `mountStatus = UNMOUNTED`
|
||
/// (DDL 无 DEFAULT、可空)。
|
||
/// - `Datasource`:上游 `DatasourceController:167-172` ⇒ `testStatus = UNTESTED`
|
||
/// (DDL 无 DEFAULT、可空)。
|
||
pub fn create_defaults(api_name: &str) -> &'static [(&'static str, &'static str)] {
|
||
match api_name {
|
||
"AuditLog" => &[
|
||
("logNo", "{id}"),
|
||
("result", "SUCCESS"),
|
||
("logType", "OPERATION"),
|
||
("actorType", "CONNECTOR"),
|
||
("actorName", "系统(自动)"),
|
||
("reportMark", "0"),
|
||
],
|
||
// Product:新建默认**未上架**(上游 ProductServiceImpl:130-141,`f_status` 是上架/下架动作的写点)
|
||
"Product" => &[("status", "DISABLED")],
|
||
// Resource:新建默认**停用**(上游 ResourceServiceImpl:305-334,设计 §12-1:启用态禁止挂载)
|
||
"Resource" => &[("status", "DISABLED"), ("mountStatus", "UNMOUNTED")],
|
||
// Datasource:上游 DatasourceController:167-172 —— 启用 + 未测试
|
||
"Datasource" => &[("testStatus", "UNTESTED")],
|
||
_ => &[],
|
||
}
|
||
}
|
||
|
||
/// 新增时由服务端补 `now()` 的列(camelCase JSON 键);
|
||
/// 请求体给了该键**且值非 null** 时不补(上游:字段为 null ⇒ 照样补)。
|
||
pub fn create_now_columns(api_name: &str) -> &'static [&'static str] {
|
||
match api_name {
|
||
"AuditLog" => &["logTime"],
|
||
_ => &[],
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
use std::collections::HashSet;
|
||
|
||
#[test]
|
||
fn registry_has_exactly_18_entities_with_unique_paths() {
|
||
assert_eq!(ALL_SPECS.len(), 18);
|
||
let mut paths = HashSet::new();
|
||
for s in ALL_SPECS {
|
||
assert!(paths.insert(s.path), "路径重复: {}", s.path);
|
||
assert!(
|
||
s.path.starts_with("/api/ssw/tdc/"),
|
||
"路径前缀错: {}",
|
||
s.path
|
||
);
|
||
assert!(valid_table(s.table).is_some(), "表名非法: {}", s.table);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn identity_has_no_tenant_column_and_others_do() {
|
||
assert!(find("Identity").unwrap().tenant_column.is_none());
|
||
assert_eq!(find("Product").unwrap().tenant_column, Some("f_tenant_id"));
|
||
}
|
||
|
||
/// 🔴 **聚合体路由的注册口径**(C3):只有资源侧两个实体有 `/Detail`,
|
||
/// 且**开了聚合体就必须有子表**(否则聚合体与普通详情无异 ⇒ 白开一条路由)。
|
||
#[test]
|
||
fn aggregate_detail_is_pinned_to_the_resource_side() {
|
||
let agg: Vec<&str> = ALL_SPECS
|
||
.iter()
|
||
.filter(|s| s.aggregate_detail)
|
||
.map(|s| s.api_name)
|
||
.collect();
|
||
assert_eq!(agg, vec!["Dataset", "Resource"]);
|
||
for s in ALL_SPECS.iter().filter(|s| s.aggregate_detail) {
|
||
assert!(
|
||
!s.child_tables.is_empty(),
|
||
"{} 开了聚合体却没有子表",
|
||
s.api_name
|
||
);
|
||
}
|
||
}
|
||
|
||
/// 🔴 **不外泄字段清单**(上游 `@JsonIgnore`)**字面钉住**。
|
||
///
|
||
/// 上游全仓只有 **3 个属性**标了 `@JsonIgnore`(2026-10-25 核对 `ssw-tdc-entity`):
|
||
/// `IdentityEntity.f_secret_key`、`DeliveryTaskEntity.f_dev_url` / `f_dev_token`。
|
||
/// 本仓另有一处**有意更严**:`CredentialEntity.f_secret_key`(上游漏标,该列是预留空列)。
|
||
#[test]
|
||
fn json_ignored_fields_are_pinned_literally() {
|
||
assert_eq!(find("Identity").unwrap().hidden_fields, &["secretKey"]);
|
||
assert_eq!(
|
||
find("DeliveryTask").unwrap().hidden_fields,
|
||
&["devUrl", "devToken"]
|
||
);
|
||
assert_eq!(find("Credential").unwrap().hidden_fields, &["secretKey"]);
|
||
// 其余 15 个实体一个都不许有不外泄字段(上游没有别的 @JsonIgnore)。
|
||
for s in ALL_SPECS {
|
||
if matches!(s.api_name, "Identity" | "DeliveryTask" | "Credential") {
|
||
continue;
|
||
}
|
||
assert!(
|
||
s.hidden_fields.is_empty(),
|
||
"{} 不该有不外泄字段(上游无 @JsonIgnore):{:?}",
|
||
s.api_name,
|
||
s.hidden_fields
|
||
);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn permission_keys_cover_every_entity() {
|
||
assert_eq!(PERMISSION_KEYS.len(), 18);
|
||
let mut seen = HashSet::new();
|
||
for (name, key) in PERMISSION_KEYS {
|
||
assert!(seen.insert(*name), "权限键重复: {}", name);
|
||
assert!(!key.is_empty(), "权限键不得为空: {}", name);
|
||
}
|
||
for s in ALL_SPECS {
|
||
assert!(
|
||
permission_key(s.api_name).is_some(),
|
||
"实体 {} 缺权限键",
|
||
s.api_name
|
||
);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn api_consume_log_keyword_columns_exist_in_its_table() {
|
||
// 上游用基类默认的 f_name,但 tdc_api_consume_log 没有该列 —— Rust 侧必须改掉
|
||
let s = find("ApiConsumeLog").unwrap();
|
||
assert!(!s.keyword_columns.contains(&"f_name"));
|
||
assert_eq!(
|
||
s.keyword_columns,
|
||
&["f_order_code", "f_app_id", "f_product_id"]
|
||
);
|
||
}
|
||
|
||
/// 🔴 Product 的关键字列**字面**钉住(fix round 3 / F-11)。
|
||
///
|
||
/// 引擎侧那条 OR 断言是**注册表驱动**的(`binds.len() == 1 + keyword_columns.len()`)
|
||
/// ⇒ 「Product 到底是哪几个关键字列」就没人钉了 ⇒ 这里补一条字面断言。
|
||
#[test]
|
||
fn product_keyword_columns_are_pinned_literally() {
|
||
assert_eq!(
|
||
find("Product").expect("Product 应在注册表").keyword_columns,
|
||
&["f_name", "f_product_code", "f_resource_name", "f_tags"]
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn dataset_is_readonly_with_derived_predicate() {
|
||
let s = find("Dataset").unwrap();
|
||
assert_eq!(s.table, "tdc_resource");
|
||
assert!(s.no_create.is_some() && s.no_update.is_some() && s.no_delete.is_some());
|
||
assert!(s
|
||
.extra_where
|
||
.unwrap()
|
||
.contains("f_mount_status = 'MOUNTED'"));
|
||
}
|
||
|
||
#[test]
|
||
fn delivery_task_freezes_forty_one_authority_columns() {
|
||
let s = find("DeliveryTask").unwrap();
|
||
assert_eq!(s.frozen_columns.len(), 41);
|
||
assert_eq!(s.frozen_columns[0].label, "本端角色");
|
||
assert_eq!(s.frozen_columns[0].column, "f_self_role");
|
||
assert!(s.no_create.is_some(), "上游已废弃直建入口");
|
||
assert!(s.no_delete.is_some(), "交付任务是审计证据");
|
||
}
|
||
|
||
#[test]
|
||
fn log_tables_are_write_guarded() {
|
||
assert!(find("AuditLog").unwrap().no_update.is_some());
|
||
assert!(find("AuditLog").unwrap().no_delete.is_some());
|
||
assert!(
|
||
find("AuditLog").unwrap().no_create.is_none(),
|
||
"审计日志允许 HTTP 写入"
|
||
);
|
||
assert!(find("DeliveryLog").unwrap().no_delete.is_some());
|
||
assert!(find("PolicyCheckLog").unwrap().no_delete.is_some());
|
||
assert!(find("DestroyLog").unwrap().no_create.is_some());
|
||
assert!(find("ApiConsumeLog").unwrap().no_create.is_some());
|
||
}
|
||
|
||
#[test]
|
||
fn audit_log_has_server_side_create_defaults() {
|
||
let defaults = create_defaults("AuditLog");
|
||
assert!(defaults
|
||
.iter()
|
||
.any(|(k, v)| *k == "logType" && *v == "OPERATION"));
|
||
assert!(defaults
|
||
.iter()
|
||
.any(|(k, v)| *k == "result" && *v == "SUCCESS"));
|
||
assert_eq!(create_now_columns("AuditLog"), &["logTime"]);
|
||
assert!(create_now_columns("Product").is_empty());
|
||
}
|
||
|
||
/// 🔴 新建默认值对齐上游(fix round 3 / F-2):走 `create_defaults` 钩子,**不改 DDL**。
|
||
///
|
||
/// - Product:新建默认**未上架**(上游 `ProductServiceImpl:130-141`)⇒ `status = DISABLED`
|
||
/// (本仓 DDL 默认是 `'ENABLED'` ⇒ 引擎必须显式覆盖)。
|
||
/// - Resource:新建默认**停用**(上游 `ResourceServiceImpl:305-334`,设计 §12-1)
|
||
/// + `mountStatus = UNMOUNTED`(DDL 无 DEFAULT)。
|
||
/// - Datasource:上游 `DatasourceController:167-172` ⇒ `testStatus = UNTESTED`(DDL 无 DEFAULT)。
|
||
#[test]
|
||
fn creation_defaults_match_upstream_status_semantics() {
|
||
let product = create_defaults("Product");
|
||
assert!(
|
||
product
|
||
.iter()
|
||
.any(|(k, v)| *k == "status" && *v == "DISABLED"),
|
||
"Product 新建默认未上架:{:?}",
|
||
product
|
||
);
|
||
let resource = create_defaults("Resource");
|
||
assert!(
|
||
resource
|
||
.iter()
|
||
.any(|(k, v)| *k == "status" && *v == "DISABLED"),
|
||
"Resource 新建默认停用:{:?}",
|
||
resource
|
||
);
|
||
assert!(
|
||
resource
|
||
.iter()
|
||
.any(|(k, v)| *k == "mountStatus" && *v == "UNMOUNTED"),
|
||
"Resource 新建默认未挂载:{:?}",
|
||
resource
|
||
);
|
||
let datasource = create_defaults("Datasource");
|
||
assert!(
|
||
datasource
|
||
.iter()
|
||
.any(|(k, v)| *k == "testStatus" && *v == "UNTESTED"),
|
||
"Datasource 新建默认未测试:{:?}",
|
||
datasource
|
||
);
|
||
// 上游默认值只有「字段为 null 才补」这一种补法 ⇒ 钩子里的键必须能换算成真实列
|
||
for (api, defaults) in [
|
||
("Product", product),
|
||
("Resource", resource),
|
||
("Datasource", datasource),
|
||
] {
|
||
for (key, _) in defaults {
|
||
assert!(
|
||
valid_table(&json_key_to_column(key)).is_some(),
|
||
"{} 的默认键换算出的列名非法: {}",
|
||
api,
|
||
key
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 🔴 `validate()` 的覆盖范围:所有**会拼进 SQL 的标识符**都要过白名单。
|
||
#[test]
|
||
fn every_sql_identifier_in_the_registry_passes_the_whitelist() {
|
||
assert!(validate().is_ok(), "注册表自检应通过");
|
||
for spec in ALL_SPECS {
|
||
assert!(valid_table(spec.table).is_some());
|
||
assert!(valid_table(spec.default_order_column).is_some());
|
||
for col in spec.keyword_columns {
|
||
assert!(valid_table(col).is_some(), "{}.{}", spec.table, col);
|
||
}
|
||
for (_pname, col) in spec.filter_columns {
|
||
assert!(valid_table(col).is_some(), "{}.{}", spec.table, col);
|
||
}
|
||
if let Some(col) = spec.tenant_column {
|
||
assert!(valid_table(col).is_some(), "{}.{}", spec.table, col);
|
||
}
|
||
for fc in spec.frozen_columns {
|
||
assert!(
|
||
valid_table(fc.column).is_some(),
|
||
"{}.{}",
|
||
spec.table,
|
||
fc.column
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 服务端生成的编码列:4 个实体各一列,且列名过白名单。
|
||
///
|
||
/// 🔴 `(key, prefix, style, retries, fail_msg, baseline_alive)` **逐字**等于上游真源
|
||
/// (2026-10-24 controller 逐字复核四份上游文件):
|
||
/// Product/Resource 重试 5 次、DataInterface/Datasource 重试 3 次,失败文案各不相同;
|
||
/// 「当日同前缀行数」基线**只有 DataInterface 带 `ALIVE`**
|
||
/// (上游 `DataInterfaceServiceImpl#countByCodePrefix:263-268`)。
|
||
#[test]
|
||
fn code_columns_are_declared_for_the_four_code_bearing_entities() {
|
||
let expected = [
|
||
(
|
||
"Product",
|
||
"productCode",
|
||
"PRO",
|
||
CodeStyle::DaySeqTail8,
|
||
5u32,
|
||
"产品编码生成失败(连续 5 次撞库),请重试",
|
||
false,
|
||
),
|
||
(
|
||
"Resource",
|
||
"resourceCode",
|
||
"RES",
|
||
CodeStyle::DaySeqTail8,
|
||
5u32,
|
||
"资源编码生成失败(连续 5 次撞库),请重试",
|
||
false,
|
||
),
|
||
(
|
||
"DataInterface",
|
||
"interfaceCode",
|
||
"API",
|
||
CodeStyle::DaySeqTail8,
|
||
3u32,
|
||
"接口编码生成失败(重试 3 次仍冲突)",
|
||
true,
|
||
),
|
||
(
|
||
"Datasource",
|
||
"datasourceCode",
|
||
"DS",
|
||
CodeStyle::DayTail6,
|
||
3u32,
|
||
"系统标识生成失败(连续 3 次撞库),请重试",
|
||
false,
|
||
),
|
||
];
|
||
for (api, key, prefix, style, retries, fail_msg, baseline_alive) in expected {
|
||
let codes = create_codes(api);
|
||
assert_eq!(codes.len(), 1, "{} 应恰好一个编码列", api);
|
||
assert_eq!(codes[0].key, key);
|
||
assert_eq!(codes[0].prefix, prefix);
|
||
assert_eq!(codes[0].style, style);
|
||
assert_eq!(codes[0].retries, retries, "{} 的重试次数", api);
|
||
assert_eq!(codes[0].fail_msg, fail_msg, "{} 的失败文案", api);
|
||
assert_eq!(
|
||
codes[0].baseline_alive, baseline_alive,
|
||
"{} 的基线是否带 ALIVE",
|
||
api
|
||
);
|
||
assert!(
|
||
valid_table(&json_key_to_column(key)).is_some(),
|
||
"编码列名须过白名单: {}",
|
||
key
|
||
);
|
||
}
|
||
assert!(create_codes("Contract").is_empty());
|
||
assert!(create_codes("Order").is_empty());
|
||
}
|
||
|
||
/// 上游 `ContractController#beforeDelete` 无条件拒删。
|
||
#[test]
|
||
fn contract_is_never_deletable() {
|
||
let s = find("Contract").unwrap();
|
||
assert!(s.no_delete.is_some());
|
||
assert!(s.no_delete.unwrap().contains("不可删除"));
|
||
}
|
||
}
|