fix(crud): 写路径对齐上游(编码服务端生成 + 审计 actor + 约束失败转业务失败)

- 4 个编码列改为服务端生成,格式逐字对齐上游两套生成器(TdcCodeUtil / BizCodeUtil)
- 审计 actor 由登录主体推导,不再恒为「系统(自动)」
- DB 约束失败按 SQLSTATE 映射为业务失败(400),不再一律 500
- Contract 恒拒删;validate() 覆盖范围补齐

Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
adminandClaude Code committed 2026-10-24 23:01:14 +08:00
1 parent 88464aaff9
commit b4edff79c4
5 files changed
+681 -13

No files matched your search

+172
View File
@@ -0,0 +1,172 @@
//! 业务编码生成 —— 逐字对齐上游**两套**生成器(**别混用**)。
//!
//! | 上游类 | 格式 | 用在 |
//! |---|---|---|
//! | `TdcCodeUtil.format(prefix, seq)` | `<前缀>-<yyyyMMdd>-<HHmmss>-<8位序号>-<8位随机>` | Product(`PRO`) / Resource(`RES`) / DataInterface(`API`) |
//! | `BizCodeUtil.of(prefix)` | `<前缀>-<yyyyMMdd>-<6位随机>` | Datasource(`DS`) |
//!
//! 两套共用同一个尾串字母表(去 0/O/1/I)。**本模块只做格式化、不碰数据库**(查重与取号
//! 在 `crud.rs` 的写路径里做)—— 与上游 `TdcCodeUtil` 的职责边界一致。
//!
//! 上游真源:`boot/ssw-tdc/ssw-tdc-biz/.../util/TdcCodeUtil.java`、
//! `boot/ssw-common/ssw-common-biz/.../util/BizCodeUtil.java`(2026-10-24 逐字核对)。
use chrono::{DateTime, Local};
use rand::Rng;
/// 尾串字母表:去掉易混的 0/O/1/I(上游 `TdcCodeUtil.TAIL_ALPHABET` / `BizCodeUtil.TAIL_ALPHABET`)。
pub const TAIL_ALPHABET: &str = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
/// 编码格式(上游两套生成器)。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodeStyle {
/// 上游 `TdcCodeUtil.format`:`<前缀>-<yyyyMMdd>-<HHmmss>-<8位序号>-<8位随机>`。
DaySeqTail8,
/// 上游 `BizCodeUtil.of`:`<前缀>-<yyyyMMdd>-<6位随机>`(**无序号**,免查库取号)。
DayTail6,
}
/// 当日前缀(用于「当日同前缀行数」计数):`<前缀>-<yyyyMMdd>-`。
///
/// 上游 `TdcCodeUtil.dayPrefix`;样例 `RES-20260929-`。
pub fn day_prefix(prefix: &str) -> String {
day_prefix_at(prefix, Local::now())
}
/// [`day_prefix`] 的**可注入时刻**版本(测试用;避免跨零点时日期漂移)。
pub fn day_prefix_at(prefix: &str, now: DateTime<Local>) -> String {
format!("{}-{}-", prefix, now.format("%Y%m%d"))
}
/// 随机尾(长度 `len`;字符只取自 [`TAIL_ALPHABET`])。
pub fn tail(len: usize) -> String {
let bytes = TAIL_ALPHABET.as_bytes();
let mut rng = rand::thread_rng();
(0..len)
.map(|_| bytes[rng.gen_range(0..bytes.len())] as char)
.collect()
}
/// 生成编码(用当前本地时间)。
///
/// 上游 `TdcCodeUtil.format` / `BizCodeUtil.of` 的等价物。
pub fn format_code(prefix: &str, seq: u64, style: CodeStyle) -> String {
format_code_at(prefix, seq, style, Local::now())
}
/// [`format_code`] 的**可注入时刻**版本(测试用;格式逐字符可断言)。
pub fn format_code_at(prefix: &str, seq: u64, style: CodeStyle, now: DateTime<Local>) -> String {
match style {
CodeStyle::DaySeqTail8 => format!(
"{}-{}-{}-{}-{}",
prefix,
now.format("%Y%m%d"),
now.format("%H%M%S"),
pad8(seq),
tail(8)
),
CodeStyle::DayTail6 => format!("{}-{}-{}", prefix, now.format("%Y%m%d"), tail(6)),
}
}
/// 序号补零到 8 位(上游 `TdcCodeUtil.pad8`:超过 8 位则**取末 8 位**)。
fn pad8(v: u64) -> String {
let s = v.to_string();
if s.len() >= 8 {
s[s.len() - 8..].to_string()
} else {
format!("{}{}", "0".repeat(8 - s.len()), s)
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::{NaiveDate, TimeZone};
/// 上游样例的时刻:`2026-09-21 12:36:08`。
fn sample_now() -> DateTime<Local> {
let naive = NaiveDate::from_ymd_opt(2026, 9, 21)
.expect("日期合法")
.and_hms_opt(12, 36, 8)
.expect("时刻合法");
Local
.from_local_datetime(&naive)
.single()
.expect("本地时刻唯一")
}
#[test]
fn tail_alphabet_drops_confusable_characters() {
assert_eq!(TAIL_ALPHABET.len(), 32);
for c in ['0', 'O', '1', 'I'] {
assert!(
!TAIL_ALPHABET.contains(c),
"易混字符不得进字母表: {}",
c
);
}
}
#[test]
fn tail_has_the_requested_length_and_only_alphabet_chars() {
for len in [6usize, 8] {
let t = tail(len);
assert_eq!(t.chars().count(), len);
assert!(
t.chars().all(|c| TAIL_ALPHABET.contains(c)),
"随机尾只能取自字母表: {}",
t
);
}
}
#[test]
fn day_prefix_is_prefix_date_and_dash() {
let p = day_prefix_at("PRO", sample_now());
assert_eq!(p, "PRO-20260921-");
assert!(p.ends_with('-'), "当日前缀须以分隔符结尾: {}", p);
}
/// 上游 `TdcCodeUtil.format` 的逐字符对齐:
/// `PRO-20260921-123608-00000011-XXXXXXXX`(5 段、4 个 `-`)。
#[test]
fn day_seq_tail8_matches_upstream_shape_char_by_char() {
let code = format_code_at("PRO", 11, CodeStyle::DaySeqTail8, sample_now());
let parts: Vec<&str> = code.split('-').collect();
assert_eq!(parts.len(), 5, "应 5 段: {}", code);
assert_eq!(parts[0], "PRO");
assert_eq!(parts[1], "20260921");
assert_eq!(parts[2], "123608");
assert_eq!(parts[3], "00000011", "序号补零到 8 位");
assert_eq!(parts[4].chars().count(), 8);
assert!(parts[4].chars().all(|c| TAIL_ALPHABET.contains(c)));
// 前 29 个字符逐字符对齐上游样例 `PRO-20260921-123608-00000011-`
assert_eq!(&code[..29], "PRO-20260921-123608-00000011-");
}
/// 上游 `BizCodeUtil.of` 的逐字符对齐:`DS-20260921-XXXXXX`(3 段、尾长 6)。
#[test]
fn day_tail6_has_three_segments_and_six_char_tail() {
let code = format_code_at("DS", 0, CodeStyle::DayTail6, sample_now());
let parts: Vec<&str> = code.split('-').collect();
assert_eq!(parts.len(), 3, "应 3 段: {}", code);
assert_eq!(parts[0], "DS");
assert_eq!(parts[1], "20260921");
assert_eq!(parts[2].chars().count(), 6);
assert!(parts[2].chars().all(|c| TAIL_ALPHABET.contains(c)));
}
#[test]
fn seq_is_zero_padded_to_eight_digits() {
let code = format_code_at("API", 1, CodeStyle::DaySeqTail8, sample_now());
assert!(code.contains("-00000001-"), "序号 1 应补零到 8 位: {}", code);
}
#[test]
fn seq_longer_than_eight_digits_keeps_the_last_eight() {
// 上游 pad8:超过 8 位则取末 8 位(不截断成空)
let code = format_code_at("API", 123_456_789, CodeStyle::DaySeqTail8, sample_now());
assert!(code.contains("-23456789-"), "应取末 8 位: {}", code);
}
}
+194 -8
View File
@@ -10,19 +10,22 @@
//! - 出参 camelCase(上游 Jackson 属性名),入参反查 `f_*` 列名。
//! - 业务失败一律 HTTP 200 + body `code != 200`(走 [`ActionResult`] 业务信封)。
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use axum::response::{IntoResponse, Response};
use chrono::{DateTime, Local};
use pglite::ToSql;
use serde_json::{Map, Value};
use crate::auth::{require_menu_permission, Principal};
use crate::codec::{day_prefix_at, format_code_at, CodeStyle};
use crate::db::{
column_to_json_key, column_types, json_key_to_column, query_json_params, query_scalar_text, ALIVE,
column_to_json_key, column_types, json_key_to_column, query_json_params, query_scalar_text,
valid_table, ALIVE,
};
use crate::envelope::{ActionResult, Pagination, CODE_SERVER_ERROR};
use crate::ids::next_id;
use crate::registry::{self, TableSpec};
use crate::registry::{self, CodeSpec, TableSpec};
use crate::state::AppState;
/// 系统列:请求体不得覆盖(对齐上游 `update` 里置 null 的那批 + 身份/排序列)。
@@ -46,6 +49,9 @@ pub const MAX_PAGE_SIZE: i64 = 500;
/// `/All` 的上限(上游 `wrapper.last("limit 1000")`)。
pub const ALL_LIMIT: i64 = 1000;
/// 业务编码生成的尝试次数(上游 `CODE_RETRY`)。
pub const CODE_RETRY: u32 = 5;
/// 解析查询串:同名参数取**第一个**(对齐 `request.getParameter`),并做百分号解码。
pub fn parse_query(raw: Option<&str>) -> HashMap<String, String> {
let mut out: HashMap<String, String> = HashMap::new();
@@ -223,6 +229,133 @@ fn server_error(e: impl std::fmt::Display) -> Response {
ActionResult::fail_code(CODE_SERVER_ERROR, format!("服务异常: {}", e)).into_response()
}
/// DB 约束失败 ⇒ 业务失败文案(按 **SQLSTATE** 精确判别,**不匹配错误文本**)。
///
/// | SQLSTATE | 含义 | 文案 |
/// |---|---|---|
/// | `23505` | 唯一约束冲突 | 唯一约束冲突:编码或标识重复 |
/// | `23502` | 非空约束违约 | 必填字段缺失 |
/// | `23503` | 外键约束违约 | 关联数据不存在 |
/// | `23514` | 检查约束违约 | 字段取值不被允许 |
/// | `22001` | 字符串超长 | 字段长度超出 |
fn constraint_message(e: &pglite::Error) -> Option<&'static str> {
match e {
pglite::Error::Database { sqlstate, .. } => match sqlstate.as_str() {
"23505" => Some("唯一约束冲突:编码或标识重复"),
"23502" => Some("必填字段缺失"),
"23503" => Some("关联数据不存在"),
"23514" => Some("字段取值不被允许"),
"22001" => Some("字段长度超出"),
_ => None,
},
_ => None,
}
}
/// 写路径的失败出口:约束类错误 ⇒ **业务失败**(HTTP 200 + `code=400`);其余仍 500。
fn write_error(e: pglite::Error) -> Response {
match constraint_message(&e) {
Some(msg) => ActionResult::fail(msg).into_response(),
None => server_error(format!("写入失败: {}", e)),
}
}
/// 审计 actor(上游 `TdcAuditLogServiceImpl#appendChain` 的**覆盖**语义)。
///
/// 🔴 上游注释明写:「我上一版兜底写死「连接器」是错的 —— 那是动作主体,不是操作人」,
/// 且「登录主体存在但名字没解析出来时**不得编造**名字」⇒ 这里一律**从主体推导**,
/// 推导不出来(`Internal` 无 operator / 无主体)才回落到 `create_defaults` 的兜底。
///
/// | principal | actorType | actorId | actorName |
/// |---|---|---|---|
/// | `Account` | `USER` | 账号 id | 账号名 |
/// | `Session` | `CONNECTOR` | 身份 id | 身份码 |
/// | `Internal{operator}` | `USER` | operator | operator |
fn audit_actor(principal: Option<&Principal>) -> Option<(&'static str, String, String)> {
match principal {
Some(Principal::Account { account_id, account }) => {
Some(("USER", account_id.clone(), account.clone()))
}
Some(Principal::Session {
identity_id,
identity_code,
}) => Some(("CONNECTOR", identity_id.clone(), identity_code.clone())),
Some(Principal::Internal {
operator: Some(op),
}) => Some(("USER", op.clone(), op.clone())),
_ => None,
}
}
/// 请求体里某个键的**非空字符串**值(空串 / null / 缺省 ⇒ `None`)。
fn body_text(body: &Value, key: &str) -> Option<String> {
match body.get(key) {
Some(Value::String(s)) if !s.trim().is_empty() => Some(s.clone()),
_ => None,
}
}
/// 计数查询(走绑定参数,绝不把值拼进 SQL 文本)。
async fn count_matching(state: &AppState, sql: &str, bind: &str) -> Result<u64, Response> {
let raw = {
let _g = state.db_lock.lock().await;
query_scalar_text(state.db.as_ref(), sql, &[&bind]).await
};
match raw {
Ok(v) => Ok(v.and_then(|s| s.trim().parse::<u64>().ok()).unwrap_or(0)),
Err(e) => Err(server_error(e)),
}
}
/// 生成唯一的业务编码(上游口径:**空值即生成、显式传入不覆盖**)。
///
/// - `DaySeqTail8`(`TdcCodeUtil`):序号基线 = **当日同前缀的行数**,
/// 依次试 `used+1 … used+5`,逐个查「该码是否已存在」,取第一个不冲突的。
/// - `DayTail6`(`BizCodeUtil`):无序号,每次**重掷**随机尾。
/// - 5 次全冲突 ⇒ **业务失败**(`code=400`),文案照上游。
async fn generate_code(
state: &AppState,
spec: &TableSpec,
code: &CodeSpec,
now: DateTime<Local>,
) -> Result<String, Response> {
let col = json_key_to_column(code.key);
if valid_table(&col).is_none() {
return Err(server_error(format!("注册表编码列非法: {}", col)));
}
let used = match code.style {
CodeStyle::DaySeqTail8 => {
// 模式串走绑定参数(`PRO-20261024-%`),不拼进 SQL 文本。
let pattern = format!("{}%", day_prefix_at(code.prefix, now));
let sql = format!(
"SELECT count(*)::text FROM {} WHERE {} LIKE CAST($1 AS text)",
spec.table, col
);
count_matching(state, &sql, &pattern).await?
}
CodeStyle::DayTail6 => 0,
};
for i in 0..CODE_RETRY {
let candidate = match code.style {
CodeStyle::DaySeqTail8 => {
format_code_at(code.prefix, used + 1 + i as u64, code.style, now)
}
CodeStyle::DayTail6 => format_code_at(code.prefix, 0, code.style, now),
};
let sql = format!(
"SELECT count(*)::text FROM {} WHERE {} = CAST($1 AS text)",
spec.table, col
);
if count_matching(state, &sql, &candidate).await? == 0 {
return Ok(candidate);
}
}
Err(
ActionResult::fail(format!("接口编码生成失败(重试 {} 次仍冲突)", CODE_RETRY))
.into_response(),
)
}
/// 分页列表:`GET /api/ssw/tdc/{Entity}`。
pub async fn list(
state: &AppState,
@@ -385,25 +518,74 @@ pub async fn create(
};
let op = operator(state, principal);
let id = next_id();
let now = Local::now();
let mut cols: Vec<String> = vec!["f_id".to_string()];
let mut vals: Vec<String> = Vec::new();
let mut binds: Vec<String> = vec![id.clone()];
vals.push(cast_param(&types, "f_id", 1));
// 🔴 `skip`:已被引擎消费(不再由 body 循环写入)的列 —— 否则同列 INSERT 两次 ⇒ 报错。
let mut skip: HashSet<String> = HashSet::new();
// ① 服务端生成的编码列 —— **必须先于 body 列循环被消费**:
// `f_product_code` 等列在 DDL 里 NOT NULL 且无 DEFAULT,而上游前端新建时**不送**
// ⇒ 服务端生成;body **显式给了非空值就不覆盖**(上游「空值即生成」规则)。
for cs in registry::create_codes(spec.api_name) {
let col = json_key_to_column(cs.key);
skip.insert(col.clone());
let value = match body_text(body, cs.key) {
Some(v) => v,
None => match generate_code(state, spec, cs, now).await {
Ok(v) => v,
Err(resp) => return resp,
},
};
binds.push(value);
let idx = binds.len();
cols.push(col.clone());
vals.push(cast_param(&types, &col, idx));
}
// ② 审计 actor:由登录主体推导(上游 `appendChain` 是**覆盖**语义 ⇒ 引擎值盖掉 body)。
if let Some((actor_type, actor_id, actor_name)) = audit_actor(principal) {
for (key, value) in [
("actorType", actor_type.to_string()),
("actorId", actor_id),
("actorName", actor_name),
] {
let col = json_key_to_column(key);
if !types.contains_key(&col) {
continue;
}
skip.insert(col.clone());
binds.push(value);
let idx = binds.len();
cols.push(col.clone());
vals.push(cast_param(&types, &col, idx));
}
}
// ③ body 列(跳过已被引擎消费的列)。
for (col, text) in body_to_columns(body, &types) {
if skip.contains(&col) {
continue;
}
binds.push(text);
let idx = binds.len();
cols.push(col.clone());
vals.push(cast_param(&types, &col, idx));
}
// 服务端补默认值(请求体已给该键 ⇒ 不补)。
// 服务端补默认值(请求体已给该键 ⇒ 不补;被引擎覆写的列 ⇒ 跳过)。
for (key, raw) in registry::create_defaults(spec.api_name) {
if body.get(key).is_some() {
continue;
}
let col = json_key_to_column(key);
if skip.contains(&col) {
continue;
}
binds.push(raw.replace("{id}", &id));
let idx = binds.len();
cols.push(col.clone());
@@ -413,7 +595,11 @@ pub async fn create(
if body.get(key).is_some() {
continue;
}
cols.push(json_key_to_column(key));
let col = json_key_to_column(key);
if skip.contains(&col) {
continue;
}
cols.push(col);
vals.push("now()".to_string());
}
@@ -445,7 +631,7 @@ pub async fn create(
};
match res {
Ok(_) => ActionResult::ok_msg("新增成功", id).into_response(),
Err(e) => server_error(format!("写入失败: {}", e)),
Err(e) => write_error(e),
}
}
@@ -531,7 +717,7 @@ pub async fn update(
};
match res {
Ok(_) => ActionResult::ok_msg("修改成功", id.to_string()).into_response(),
Err(e) => server_error(format!("写入失败: {}", e)),
Err(e) => write_error(e),
}
}
@@ -582,7 +768,7 @@ pub async fn delete(
};
match res {
Ok(_) => ActionResult::ok_msg("删除成功", id.to_string()).into_response(),
Err(e) => server_error(format!("写入失败: {}", e)),
Err(e) => write_error(e),
}
}
+1
View File
@@ -8,6 +8,7 @@
//! - 任意 SELECT 走 `db::query_json()`(row_to_json 包裹)。
pub mod auth;
pub mod codec;
pub mod config;
pub mod crud;
pub mod db;
+140 -5
View File
@@ -10,7 +10,8 @@
//! 2. 过滤一律 `CAST(col AS TEXT) = $1`(上游把 varchar 绑给 smallint 列会 PG 报错),
//! 这条落在 `crud.rs`,注册表本身不变。
use crate::db::valid_table;
use crate::codec::CodeStyle;
use crate::db::{json_key_to_column, valid_table};
/// 不可经编辑入口改写的「服务端权威列」。
#[derive(Debug, Clone, Copy)]
@@ -21,6 +22,19 @@ pub struct FrozenColumn {
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,
}
/// 一个可 CRUD 实体的元数据。
#[derive(Debug, Clone, Copy)]
pub struct TableSpec {
@@ -170,7 +184,8 @@ pub static REGISTRY: &[TableSpec] = &[
extra_where: None,
no_create: None,
no_update: None,
no_delete: None,
// 上游 `ContractController#beforeDelete` **无条件**抛(权威归档在平台,副本只随联动清退)
no_delete: Some("本地合约副本不可删除(权威归档在平台,副本仅随空间/合约清退联动)"),
frozen_columns: &[],
},
TableSpec {
@@ -459,22 +474,87 @@ pub fn find(api_name: &str) -> Option<&'static TableSpec> {
REGISTRY.iter().find(|s| s.api_name == api_name)
}
/// 注册表自检:所有表名必须过白名单(防拼接注入)。
/// 注册表自检:**所有拼进 SQL 的标识符**(表名、过滤列、关键字列、默认排序列、
/// 租户列、冻结列、服务端生成的编码列)都必须过白名单(防拼接注入)。
///
/// ⚠️ `filter_columns` 的**键**(`pname`,如 `status`)是**请求参数名**、不是列名,
/// **不**拿它过白名单。
pub fn validate() -> Result<(), String> {
for spec in REGISTRY {
if valid_table(spec.table).is_none() {
return Err(format!("注册表表名非法: {}", spec.table));
}
for (pname, col) in spec.filter_columns {
for (_pname, col) in spec.filter_columns {
if valid_table(col).is_none() {
return Err(format!("注册表过滤列非法: {}.{}", spec.table, col));
}
let _ = pname;
}
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 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")
"Product" => &[CodeSpec {
key: "productCode",
prefix: "PRO",
style: CodeStyle::DaySeqTail8,
}],
// 上游 `ResourceServiceImpl#nextResourceCode`(TdcCodeUtil,"RES")
"Resource" => &[CodeSpec {
key: "resourceCode",
prefix: "RES",
style: CodeStyle::DaySeqTail8,
}],
// 上游 `DataInterfaceServiceImpl#prepare`(TdcCodeUtil,"API")
"DataInterface" => &[CodeSpec {
key: "interfaceCode",
prefix: "API",
style: CodeStyle::DaySeqTail8,
}],
// 上游 `DatasourceController#beforeSave`(BizCodeUtil.of("DS"))
"Datasource" => &[CodeSpec {
key: "datasourceCode",
prefix: "DS",
style: CodeStyle::DayTail6,
}],
_ => &[],
}
}
/// 新增时由**服务端**补齐的默认值:`(camelCase JSON 键, 常量文本)`。
///
/// `{id}` 会被替换成本次新生成的雪花号 id。请求体已经给了的键**不覆盖**。
@@ -572,4 +652,59 @@ mod tests {
assert!(create_defaults("Product").is_empty());
assert!(create_now_columns("Product").is_empty());
}
/// 🔴 `validate()` 的覆盖范围:所有**会拼进 SQL 的标识符**都要过白名单。
#[test]
fn every_sql_identifier_in_the_registry_passes_the_whitelist() {
assert!(validate().is_ok(), "注册表自检应通过");
for spec in REGISTRY {
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 个实体各一列,且列名过白名单。
#[test]
fn code_columns_are_declared_for_the_four_code_bearing_entities() {
let expected = [
("Product", "productCode", "PRO", CodeStyle::DaySeqTail8),
("Resource", "resourceCode", "RES", CodeStyle::DaySeqTail8),
("DataInterface", "interfaceCode", "API", CodeStyle::DaySeqTail8),
("Datasource", "datasourceCode", "DS", CodeStyle::DayTail6),
];
for (api, key, prefix, style) 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!(
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("不可删除"));
}
}
+174
View File
@@ -305,3 +305,177 @@ async fn resource_detail_aggregate_carries_field_rules_and_mask_rules() {
let body = body_of(resp).await;
assert_eq!(body["code"], 400, "查无应是业务失败:{}", body);
}
/// 建一条实体并回读它的某个字段(简化测试样板)。
async fn create_and_read(
state: &tdc_connector::state::AppState,
spec: &'static tdc_connector::registry::TableSpec,
body: &Value,
field: &str,
principal: &Principal,
) -> String {
let resp = crud::create(state, spec, body, Some(principal)).await;
let resp_body = body_of(resp).await;
assert_eq!(resp_body["code"], 200, "新建应成功:{}", resp_body);
let id = resp_body["data"].as_str().expect("应返回 id").to_string();
let resp = crud::detail(state, spec, &id, Some(principal)).await;
let resp_body = body_of(resp).await;
assert_eq!(resp_body["code"], 200, "详情应成功:{}", resp_body);
resp_body["data"][field]
.as_str()
.unwrap_or_else(|| panic!("应有字段 {}:{}", field, resp_body))
.to_string()
}
/// 🔴 上游前端新建 Product **不送** `productCode`,而该列 NOT NULL 且无 DEFAULT
/// ⇒ 服务端必须生成(上游 `TdcCodeUtil`,`PRO-yyyyMMdd-HHmmss-8位序号-8位随机`)。
#[tokio::test]
async fn product_code_is_generated_server_side() {
let state = test_state().await;
let spec = registry::find("Product").unwrap();
let code = create_and_read(
&state,
spec,
&json!({"name": "编码生成产品甲"}),
"productCode",
&principal(),
)
.await;
let parts: Vec<&str> = code.split('-').collect();
assert_eq!(parts.len(), 5, "PRO 码应 5 段:{}", code);
assert_eq!(parts[0], "PRO");
assert_eq!(parts[1].len(), 8, "日期段 8 位:{}", code);
assert!(parts[1].chars().all(|c| c.is_ascii_digit()));
assert_eq!(parts[2].len(), 6, "时分秒段 6 位:{}", code);
assert!(parts[2].chars().all(|c| c.is_ascii_digit()));
assert_eq!(parts[3].len(), 8, "序号段补零到 8 位:{}", code);
assert!(parts[3].chars().all(|c| c.is_ascii_digit()));
assert_eq!(parts[4].chars().count(), 8, "随机尾 8 位:{}", code);
assert!(parts[4].chars().all(|c| c.is_ascii_alphanumeric()));
// 再建一条 ⇒ 两个码必须不同(唯一性)
let code2 = create_and_read(
&state,
spec,
&json!({"name": "编码生成产品乙"}),
"productCode",
&principal(),
)
.await;
assert_ne!(code, code2, "两次生成的码不得相同");
}
/// 上游规则「**空值即生成;显式传入不覆盖**」⇒ body 显式给了码就保留 body 的。
#[tokio::test]
async fn explicit_product_code_is_not_overwritten() {
let state = test_state().await;
let spec = registry::find("Product").unwrap();
let code = create_and_read(
&state,
spec,
&json!({"name": "固定码产品", "productCode": "FIXED-CODE"}),
"productCode",
&principal(),
)
.await;
assert_eq!(code, "FIXED-CODE", "显式传入的码不得被覆盖");
}
/// Datasource 用上游**另一套**生成器(`BizCodeUtil.of("DS")`):3 段、随机尾 6 位。
#[tokio::test]
async fn datasource_code_uses_the_six_char_tail_shape() {
let state = test_state().await;
let spec = registry::find("Datasource").unwrap();
let code = create_and_read(
&state,
spec,
&json!({"name": "码生成数据源", "type": "MYSQL"}),
"datasourceCode",
&principal(),
)
.await;
let parts: Vec<&str> = code.split('-').collect();
assert_eq!(parts.len(), 3, "DS 码应 3 段:{}", code);
assert_eq!(parts[0], "DS");
assert_eq!(parts[1].len(), 8, "日期段 8 位:{}", code);
assert!(parts[1].chars().all(|c| c.is_ascii_digit()));
assert_eq!(parts[2].chars().count(), 6, "随机尾 6 位:{}", code);
assert!(parts[2].chars().all(|c| c.is_ascii_alphanumeric()));
}
/// 🔴 NOT NULL 违约 ⇒ **业务失败**(HTTP 200 + `code=400`),不是 500。
#[tokio::test]
async fn missing_required_field_is_a_business_failure_not_a_500() {
let state = test_state().await;
let spec = registry::find("Product").unwrap();
// 不给 `name`(`f_name` NOT NULL 无 DEFAULT)⇒ 23502
let resp = crud::create(&state, spec, &json!({}), Some(&principal())).await;
let body = body_of(resp).await;
assert_eq!(body["code"], 400, "应是业务失败而非 500:{}", body);
assert!(
body["msg"].as_str().unwrap().contains("必填"),
"msg 应说明必填缺失:{}",
body
);
assert!(body["data"].is_null(), "业务失败的 data 键仍在但为 null");
}
/// 🔴 审计 actor 来自**登录主体**,不再恒为「系统(自动)」。
#[tokio::test]
async fn audit_actor_comes_from_the_login_principal() {
let state = test_state().await;
let spec = registry::find("AuditLog").unwrap();
// 本地账号 ⇒ USER / 账号 id / 账号名
let account = Principal::Account {
account_id: "U-1".to_string(),
account: "张三".to_string(),
};
let resp = crud::create(&state, spec, &json!({"action": "LOGIN"}), Some(&account)).await;
let body = body_of(resp).await;
assert_eq!(body["code"], 200, "{}", body);
let id = body["data"].as_str().unwrap().to_string();
let resp = crud::detail(&state, spec, &id, Some(&account)).await;
let body = body_of(resp).await;
assert_eq!(body["data"]["actorType"], "USER");
assert_eq!(body["data"]["actorId"], "U-1");
assert_eq!(body["data"]["actorName"], "张三");
// 连接器身份会话 ⇒ CONNECTOR / 身份 id / 身份码
let resp = crud::create(&state, spec, &json!({"action": "LOGIN"}), Some(&principal())).await;
let body = body_of(resp).await;
assert_eq!(body["code"], 200, "{}", body);
let id = body["data"].as_str().unwrap().to_string();
let resp = crud::detail(&state, spec, &id, Some(&principal())).await;
let body = body_of(resp).await;
assert_eq!(body["data"]["actorType"], "CONNECTOR");
assert_eq!(body["data"]["actorId"], "TEST-OP");
assert_eq!(body["data"]["actorName"], "TEST-CONNECTOR");
// 内部令牌但没有 operator ⇒ 回落 create_defaults 的兜底
let internal = Principal::Internal { operator: None };
let resp = crud::create(&state, spec, &json!({"action": "LOGIN"}), Some(&internal)).await;
let body = body_of(resp).await;
assert_eq!(body["code"], 200, "{}", body);
let id = body["data"].as_str().unwrap().to_string();
let resp = crud::detail(&state, spec, &id, Some(&internal)).await;
let body = body_of(resp).await;
assert_eq!(body["data"]["actorType"], "CONNECTOR");
assert_eq!(body["data"]["actorName"], "系统(自动)");
}
/// 上游 `ContractController#beforeDelete` **无条件**拒删。
#[tokio::test]
async fn contract_cannot_be_deleted() {
let state = test_state().await;
let spec = registry::find("Contract").unwrap();
let resp = crud::delete(&state, spec, "NO-SUCH-ID", Some(&principal())).await;
let body = body_of(resp).await;
assert_eq!(body["code"], 400, "合约恒拒删:{}", body);
assert!(
body["msg"].as_str().unwrap().contains("不可删除"),
"msg 应含「不可删除」:{}",
body
);
}