diff --git a/src/crud.rs b/src/crud.rs index 63b0e53..5d6e2ea 100644 --- a/src/crud.rs +++ b/src/crud.rs @@ -206,12 +206,18 @@ fn bind_refs(binds: &[String]) -> Vec<&(dyn ToSql + Sync)> { binds.iter().map(|s| s as &(dyn ToSql + Sync)).collect() } -/// 当前操作人:内部令牌通道的 `X-Internal-Operator` > 会话身份 > 本地账号 > 本地引导身份 > `SYSTEM`。 +/// 当前操作人(**操作人 id**):内部令牌通道的 `X-Internal-Operator` > 会话身份 > 本地账号 id > 本地引导身份 > `SYSTEM`。 +/// +/// 🔴 上游 `TdcCrudController#safeUserId()`(`:383-388`)返回 `operatorResolver.currentOperatorId()` +/// ⇒ 是**操作人 id**、不是名字 ⇒ 本函数写的是 `f_creator_user_id` / +/// `f_last_modify_user_id` / `f_delete_user_id` 三列 ⇒ 本地账号必须取 **`account_id`**。 +/// (`audit_actor` 是**独立**函数,actor 的 `actorName` 仍取账号**名** —— 上游 actor 是「id + 名」两列。) pub fn operator(state: &AppState, principal: Option<&Principal>) -> String { match principal { Some(Principal::Internal { operator: Some(op) }) => op.clone(), Some(Principal::Session { identity_id, .. }) => identity_id.clone(), - Some(Principal::Account { account, .. }) => account.clone(), + // 上游 safeUserId() 返回**操作人 id**(不是名字)⇒ Account 走 account_id + Some(Principal::Account { account_id, .. }) => account_id.clone(), _ => { if state.bootstrap.identity_id.is_empty() { "SYSTEM".to_string() @@ -222,8 +228,13 @@ pub fn operator(state: &AppState, principal: Option<&Principal>) -> String { } } +/// 内部错误 ⇒ 客户端**固定文案** + 完整错误**只进 stderr**。 +/// +/// 🔴 **不得回显数据库原文**(PG 错误里含表名 / 列名 / 约束名 / `Failing row contains (...)` +/// **整行数据**)⇒ 客户端只看到「服务异常,请稍后重试」,排障信息走服务端日志。 fn server_error(e: impl std::fmt::Display) -> Response { - ActionResult::fail_code(CODE_SERVER_ERROR, format!("服务异常: {}", e)).into_response() + eprintln!("[tdc] 内部错误: {}", e); + ActionResult::fail_code(CODE_SERVER_ERROR, "服务异常,请稍后重试".to_string()).into_response() } /// DB 约束失败 ⇒ 业务失败文案(按 **SQLSTATE** 精确判别,**不匹配错误文本**)。 @@ -297,6 +308,9 @@ fn body_text(body: &Value, key: &str) -> Option { /// `like_mode = true` ⇒ `WHERE {col} LIKE CAST($1 AS text)`(取「当日同前缀行数」的序号基线); /// 否则 ⇒ `WHERE {col} = CAST($1 AS text)`(查重)。 /// +/// `alive == true` ⇒ 追加 `AND (f_delete_mark IS NULL OR f_delete_mark = 0)`(`ALIVE` 谓词)。 +/// ⚠️ `f_delete_mark` 是**字面量**(不是用户输入)⇒ 不用绑参。 +/// /// 🔴 **查重口径(有意分歧,裁决后保留)**:四个编码列统一按「该列**等值计数**」判定 /// (**不**加 `f_delete_mark` 谓词)。这与上游 Product/Resource/DataInterface 一致; /// 上游 **Datasource** 走基类 `newUniqueCode` ⇒ 用 `existsBy` ⇒ 谓词是 `ALIVE` @@ -310,6 +324,7 @@ async fn count_matching( code_key: &str, bind: &str, like_mode: bool, + alive: bool, ) -> Result { let col = json_key_to_column(code_key); if valid_table(table).is_none() { @@ -319,9 +334,14 @@ async fn count_matching( return Err(server_error(format!("注册表编码列非法: {}", col))); } let op = if like_mode { "LIKE" } else { "=" }; + let alive_clause = if alive { + format!(" AND {}", ALIVE) + } else { + String::new() + }; let sql = format!( - "SELECT count(*)::text FROM {} WHERE {} {} CAST($1 AS text)", - table, col, op + "SELECT count(*)::text FROM {} WHERE {} {} CAST($1 AS text){}", + table, col, op, alive_clause ); let raw = { let _g = state.db_lock.lock().await; @@ -333,6 +353,36 @@ async fn count_matching( } } +/// 「当日同前缀行数」基线(序号的起点,`used`)。 +/// +/// 🔴 上游**逐实体不同**:DataInterface 的 `countByCodePrefix` **带 `ALIVE`** +/// (`DataInterfaceServiceImpl:263-268`),Product / Resource 的基线**不带** +/// (`ProductServiceImpl:168` / `ResourceServiceImpl:135` 都是裸 `count(likeRight)`) +/// ⇒ 由 `CodeSpec::baseline_alive` 表达。 +async fn code_baseline( + state: &AppState, + spec: &TableSpec, + code: &CodeSpec, + now: DateTime, +) -> Result { + match code.style { + CodeStyle::DaySeqTail8 => { + // 模式串走绑定参数(`PRO-20261024-%`),不拼进 SQL 文本。 + let pattern = format!("{}%", day_prefix_at(code.prefix, now)); + count_matching( + state, + spec.table, + code.key, + &pattern, + true, + code.baseline_alive, + ) + .await + } + CodeStyle::DayTail6 => Ok(0), + } +} + /// 生成唯一的业务编码(上游口径:**空值即生成、显式传入不覆盖**)。 /// /// - `DaySeqTail8`(`TdcCodeUtil`):序号基线 = **当日同前缀的行数**, @@ -345,14 +395,7 @@ async fn generate_code( code: &CodeSpec, now: DateTime, ) -> Result { - let used = match code.style { - CodeStyle::DaySeqTail8 => { - // 模式串走绑定参数(`PRO-20261024-%`),不拼进 SQL 文本。 - let pattern = format!("{}%", day_prefix_at(code.prefix, now)); - count_matching(state, spec.table, code.key, &pattern, true).await? - } - CodeStyle::DayTail6 => 0, - }; + let used = code_baseline(state, spec, code, now).await?; generate_code_with(state, spec, code, |i| { match code.style { CodeStyle::DaySeqTail8 => { @@ -381,7 +424,7 @@ where { for i in 0..code.retries { let candidate = make(i); - let occupied = count_matching(state, spec.table, code.key, &candidate, false).await?; + let occupied = count_matching(state, spec.table, code.key, &candidate, false, false).await?; if occupied == 0 { return Ok(candidate); } @@ -610,9 +653,10 @@ pub async fn create( vals.push(cast_param(&types, &col, idx)); } - // 服务端补默认值(请求体已给该键 ⇒ 不补;被引擎覆写的列 ⇒ 跳过)。 + // 服务端补默认值(body 显式给了该键且**值非 null** ⇒ 不补;被引擎覆写的列 ⇒ 跳过)。 for (key, raw) in registry::create_defaults(spec.api_name) { - if body.get(key).is_some() { + // body 显式给了该键且**值非 null** ⇒ 才算业务已给(上游:字段为 null ⇒ 照样补默认值) + if body.get(key).map(|v| !v.is_null()).unwrap_or(false) { continue; } let col = json_key_to_column(key); @@ -625,7 +669,8 @@ pub async fn create( vals.push(cast_param(&types, &col, idx)); } for key in registry::create_now_columns(spec.api_name) { - if body.get(key).is_some() { + // 同上:显式 null **不得**抑制服务端补的 now() + if body.get(key).map(|v| !v.is_null()).unwrap_or(false) { continue; } let col = json_key_to_column(key); @@ -764,9 +809,8 @@ pub async fn delete( if let Err(resp) = require_menu_permission(principal) { return resp; } - if let Some(msg) = spec.no_delete { - return ActionResult::fail(msg).into_response(); - } + // 🔴 **「不存在」判定必须先于「禁删」守卫**(上游 `TdcCrudController#delete:250-266`: + // `getAlive(id)` → 为空则 `fail("记录不存在或已删除")` → **之后**才 `beforeDelete(exists)`)。 let current = match fetch_alive(state, spec, id).await { Ok(v) => v, Err(e) => return server_error(e), @@ -774,6 +818,9 @@ pub async fn delete( if current.is_none() { return ActionResult::fail("记录不存在或已删除").into_response(); } + if let Some(msg) = spec.no_delete { + return ActionResult::fail(msg).into_response(); + } let types = { let _g = state.db_lock.lock().await; match column_types(state.db.as_ref(), spec.table).await { diff --git a/src/registry.rs b/src/registry.rs index 147c584..c0bb115 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -37,6 +37,9 @@ pub struct CodeSpec { pub retries: u32, /// 重试用尽的失败文案(**上游逐字**)。 pub fail_msg: &'static str, + /// 「当日同前缀行数」基线是否带 `ALIVE` 谓词(上游逐实体不同: + /// DataInterface 带(`DataInterfaceServiceImpl:263-268`),Product/Resource 不带)。 + pub baseline_alive: bool, } /// 一个可 CRUD 实体的元数据。 @@ -538,6 +541,7 @@ pub fn create_codes(api_name: &str) -> &'static [CodeSpec] { style: CodeStyle::DaySeqTail8, retries: 5, fail_msg: "产品编码生成失败(连续 5 次撞库),请重试", + baseline_alive: false, }], // 上游 `ResourceServiceImpl#nextResourceCode`(TdcCodeUtil,"RES"):5 次 "Resource" => &[CodeSpec { @@ -546,6 +550,7 @@ pub fn create_codes(api_name: &str) -> &'static [CodeSpec] { style: CodeStyle::DaySeqTail8, retries: 5, fail_msg: "资源编码生成失败(连续 5 次撞库),请重试", + baseline_alive: false, }], // 上游 `DataInterfaceServiceImpl#prepare`(TdcCodeUtil,"API"):`CODE_RETRY = 3` "DataInterface" => &[CodeSpec { @@ -554,6 +559,8 @@ pub fn create_codes(api_name: &str) -> &'static [CodeSpec] { 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 { @@ -562,6 +569,8 @@ pub fn create_codes(api_name: &str) -> &'static [CodeSpec] { style: CodeStyle::DayTail6, retries: 3, fail_msg: "系统标识生成失败(连续 3 次撞库),请重试", + // `BizCodeUtil` 无序号 ⇒ 该字段对它无意义 + baseline_alive: false, }], _ => &[], } @@ -569,11 +578,20 @@ pub fn create_codes(api_name: &str) -> &'static [CodeSpec] { /// 新增时由**服务端**补齐的默认值:`(camelCase JSON 键, 常量文本)`。 /// -/// `{id}` 会被替换成本次新生成的雪花号 id。请求体已经给了的键**不覆盖**。 +/// `{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 再补)。 +/// - `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" => &[ @@ -584,11 +602,18 @@ pub fn create_defaults(api_name: &str) -> &'static [(&'static str, &'static str) ("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 键);请求体已给则不补。 +/// 新增时由服务端补 `now()` 的列(camelCase JSON 键); +/// 请求体给了该键**且值非 null** 时不补(上游:字段为 null ⇒ 照样补)。 pub fn create_now_columns(api_name: &str) -> &'static [&'static str] { match api_name { "AuditLog" => &["logTime"], @@ -626,6 +651,18 @@ mod tests { 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(); @@ -661,10 +698,62 @@ mod tests { 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_defaults("Product").is_empty()); 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() { @@ -689,9 +778,11 @@ mod tests { /// 服务端生成的编码列:4 个实体各一列,且列名过白名单。 /// - /// 🔴 `(key, prefix, style, retries, fail_msg)` **逐字**等于上游真源 + /// 🔴 `(key, prefix, style, retries, fail_msg, baseline_alive)` **逐字**等于上游真源 /// (2026-10-24 controller 逐字复核四份上游文件): - /// Product/Resource 重试 5 次、DataInterface/Datasource 重试 3 次,失败文案各不相同。 + /// 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 = [ @@ -702,6 +793,7 @@ mod tests { CodeStyle::DaySeqTail8, 5u32, "产品编码生成失败(连续 5 次撞库),请重试", + false, ), ( "Resource", @@ -710,6 +802,7 @@ mod tests { CodeStyle::DaySeqTail8, 5u32, "资源编码生成失败(连续 5 次撞库),请重试", + false, ), ( "DataInterface", @@ -718,6 +811,7 @@ mod tests { CodeStyle::DaySeqTail8, 3u32, "接口编码生成失败(重试 3 次仍冲突)", + true, ), ( "Datasource", @@ -726,9 +820,10 @@ mod tests { CodeStyle::DayTail6, 3u32, "系统标识生成失败(连续 3 次撞库),请重试", + false, ), ]; - for (api, key, prefix, style, retries, fail_msg) in expected { + 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); @@ -736,6 +831,10 @@ mod tests { 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(), "编码列名须过白名单: {}", diff --git a/tests/crud_engine.rs b/tests/crud_engine.rs index 5a99c3b..b4fe0da 100644 --- a/tests/crud_engine.rs +++ b/tests/crud_engine.rs @@ -17,6 +17,26 @@ use tokio::sync::OnceCell; static DB: OnceCell> = OnceCell::const_new(); +/// 🔴 序列化「会写 `tdc_product` 的用例」。 +/// +/// 编码的序号基线是「**当日同前缀的行数**」⇒ 并行跑的用例会互相抬高基线 ⇒ +/// 绝对值断言不可靠 ⇒ 需要一个进程内互斥量把写 `tdc_product` 的用例串起来。 +/// +/// ⚠️ 加锁顺序恒为 `PRODUCT_LOCK` → `db_lock`(`crud::*` 内部再拿 `db_lock`)⇒ 不会死锁。 +static PRODUCT_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +/// 数「当日同前缀」的行数(**含软删行** —— 与 Product/Resource 的基线口径一致:不带 `ALIVE`)。 +async fn count_today_products(state: &tdc_connector::state::AppState, pattern: &str) -> u64 { + let sql = "SELECT count(*)::text FROM tdc_product WHERE f_product_code LIKE CAST($1 AS text)"; + let raw = { + let _g = state.db_lock.lock().await; + tdc_connector::db::query_scalar_text(state.db.as_ref(), sql, &[&pattern]) + .await + .expect("计数失败") + }; + raw.and_then(|s| s.trim().parse::().ok()).unwrap_or(0) +} + async fn shared_db() -> Arc { DB.get_or_init(|| async { let db = Arc::new(PGlite::open_temp().await.expect("打开临时 PGlite 失败")); @@ -62,6 +82,7 @@ async fn body_of(resp: axum::response::Response) -> Value { #[tokio::test] async fn product_crud_roundtrip() { let state = test_state().await; + let _p = PRODUCT_LOCK.lock().await; let spec = registry::find("Product").unwrap(); // 新增 @@ -307,13 +328,15 @@ async fn resource_detail_aggregate_carries_field_rules_and_mask_rules() { } /// 建一条实体并回读它的某个字段(简化测试样板)。 +/// +/// 返回 `(新记录 id, 字段值)` —— id 是 `create` 响应 `data` 里的**新记录 id**。 async fn create_and_read( state: &tdc_connector::state::AppState, spec: &'static tdc_connector::registry::TableSpec, body: &Value, field: &str, principal: &Principal, -) -> String { +) -> (String, 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); @@ -321,10 +344,22 @@ async fn create_and_read( 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] + let value = resp_body["data"][field] .as_str() .unwrap_or_else(|| panic!("应有字段 {}:{}", field, resp_body)) - .to_string() + .to_string(); + (id, value) +} + +/// 取编码里的**序号段**(第 4 段,索引 3)。 +/// +/// ⚠️ **只能相对比较**:序号基线是「当日同前缀行数」,同一测试库里别的用例当天建过 +/// 同前缀记录就会让基线不是 0 ⇒ 绝不能断言它等于 `00000001`。 +fn seq_of(code: &str, prefix: &str) -> u64 { + let parts: Vec<&str> = code.split('-').collect(); + assert_eq!(parts.len(), 5, "编码应 5 段: {}", code); + assert_eq!(parts[0], prefix, "前缀应 {}: {}", prefix, code); + parts[3].parse::().expect("序号段应可解析为数字") } /// 🔴 上游前端新建 Product **不送** `productCode`,而该列 NOT NULL 且无 DEFAULT @@ -332,9 +367,10 @@ async fn create_and_read( #[tokio::test] async fn product_code_is_generated_server_side() { let state = test_state().await; + let _p = PRODUCT_LOCK.lock().await; let spec = registry::find("Product").unwrap(); - let code = create_and_read( + let (_id, code) = create_and_read( &state, spec, &json!({"name": "编码生成产品甲"}), @@ -353,25 +389,17 @@ async fn product_code_is_generated_server_side() { 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, "两次生成的码不得相同"); + // 🔴 「两个码不相等」由 `product_code_sequence_starts_at_baseline_plus_one` + // 用**序号段的相对差**证明(那才是有鉴别力的断言)⇒ 这里不再写近乎恒真的弱断言。 } /// 上游规则「**空值即生成;显式传入不覆盖**」⇒ body 显式给了码就保留 body 的。 #[tokio::test] async fn explicit_product_code_is_not_overwritten() { let state = test_state().await; + let _p = PRODUCT_LOCK.lock().await; let spec = registry::find("Product").unwrap(); - let code = create_and_read( + let (_id, code) = create_and_read( &state, spec, &json!({"name": "固定码产品", "productCode": "FIXED-CODE"}), @@ -387,7 +415,7 @@ async fn explicit_product_code_is_not_overwritten() { 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( + let (_id, code) = create_and_read( &state, spec, &json!({"name": "码生成数据源", "type": "MYSQL"}), @@ -408,6 +436,7 @@ async fn datasource_code_uses_the_six_char_tail_shape() { #[tokio::test] async fn missing_required_field_is_a_business_failure_not_a_500() { let state = test_state().await; + let _p = PRODUCT_LOCK.lock().await; let spec = registry::find("Product").unwrap(); // 不给 `name`(`f_name` NOT NULL 无 DEFAULT)⇒ 23502 let resp = crud::create(&state, spec, &json!({}), Some(&principal())).await; @@ -418,7 +447,14 @@ async fn missing_required_field_is_a_business_failure_not_a_500() { "msg 应说明必填缺失:{}", body ); - assert!(body["data"].is_null(), "业务失败的 data 键仍在但为 null"); + // 🔴 `body["data"].is_null()` 对**缺失键**也恒真 ⇒ 必须显式断言「键存在且值为 null」 + let obj = body.as_object().expect("响应体应是对象"); + assert!(obj.contains_key("data"), "失败响应须带 data 键(值为 null)"); + assert_eq!( + obj.get("data"), + Some(&Value::Null), + "失败响应的 data 应为 null" + ); } /// 🔴 审计 actor 来自**登录主体**,不再恒为「系统(自动)」。 @@ -465,29 +501,55 @@ async fn audit_actor_comes_from_the_login_principal() { assert_eq!(body["data"]["actorName"], "系统(自动)"); } -/// 上游 `ContractController#beforeDelete` **无条件**拒删。 +/// 🔴 上游 `TdcCrudController#delete:250-266`:**先判存在性**(`getAlive` 为空 ⇒ +/// 「记录不存在或已删除」)→ **之后**才走禁删守卫(`beforeDelete`)。 +/// ⇒ 对**不存在**的 id,即使该实体受保护,也必须回「记录不存在或已删除」。 #[tokio::test] -async fn contract_cannot_be_deleted() { +async fn contract_delete_reports_missing_before_the_delete_guard() { let state = test_state().await; let spec = registry::find("Contract").unwrap(); + + // 不存在的 id ⇒ 「记录不存在或已删除」(**先于**禁删守卫) let resp = crud::delete(&state, spec, "NO-SUCH-ID", Some(&principal())).await; let body = body_of(resp).await; + assert_eq!(body["code"], 400, "不存在的 id ⇒ 业务失败:{}", body); + assert_eq!(body["msg"], "记录不存在或已删除", "存在性判定须先于禁删守卫"); + + // 存在的 Contract 行 ⇒ 禁删文案(上游原文,逐字) + { + let _g = state.db_lock.lock().await; + state + .db + .query( + "INSERT INTO tdc_contract (f_id, f_contract_code) \ + VALUES (CAST('C-GUARD' AS character varying), CAST('CC-GUARD' AS character varying))", + &[], + ) + .await + .expect("插入合约失败"); + } + let resp = crud::delete(&state, spec, "C-GUARD", Some(&principal())).await; + let body = body_of(resp).await; assert_eq!(body["code"], 400, "合约恒拒删:{}", body); - assert!( - body["msg"].as_str().unwrap().contains("不可删除"), - "msg 应含「不可删除」:{}", - body + assert_eq!( + body["msg"], + "本地合约副本不可删除(权威归档在平台,副本仅随空间/合约清退联动)", + "禁删文案须逐字等于上游原文" ); } -/// 🔴 编码生成的**逐实体**参数(重试次数 / 失败文案)等于**上游原文**,且**逐实体不同** +/// 🔴 **注册表常量**层的哨兵:编码生成的**逐实体**参数(重试次数 / 失败文案) +/// 等于**上游原文**,且**逐实体不同** /// (上游 Product/Resource 重试 5 次、DataInterface/Datasource 重试 3 次;文案也各不相同)。 /// -/// ⚠️ 「重试耗尽」这条分支**无法在集成层稳定构造**:真实候选带 8 位(`DaySeqTail8`)或 -/// 6 位(`DayTail6`)随机尾,撞中一次要枚举十亿级组合 ⇒ 该分支由 -/// `src/crud.rs` 里的单元测试(注入恒冲突候选)覆盖;本用例守的是**引擎读到的那份参数**。 +/// ⚠️ **本用例只守「注册表常量」**(`registry::create_codes`),**不触引擎**。 +/// 引擎真的读了 `retries` / `fail_msg`(含「重试耗尽」分支)由 `src/crud.rs` 里的 +/// **单元测试**守(`code_generation_gives_up_after_the_entity_specific_retries`, +/// 它注入恒冲突候选 ⇒ 真的走到耗尽分支)。 +/// 「重试耗尽」这条分支**无法在集成层稳定构造**:真实候选带 8 位(`DaySeqTail8`)或 +/// 6 位(`DayTail6`)随机尾,撞中一次要枚举十亿级组合。 #[tokio::test] -async fn code_retry_counts_and_failure_messages_are_per_entity() { +async fn registry_declares_per_entity_code_retry_policy() { let expected = [ ("Product", 5u32, "产品编码生成失败(连续 5 次撞库),请重试"), ("Resource", 5u32, "资源编码生成失败(连续 5 次撞库),请重试"), @@ -507,3 +569,224 @@ async fn code_retry_counts_and_failure_messages_are_per_entity() { uniq.dedup(); assert_eq!(uniq.len(), 4, "四个实体的失败文案应各不相同:{:?}", msgs); } + +/// 🔴 **序号口径 `used + 1 + i` 的护栏**(评审 Important-1 / fix round 3 F-1)。 +/// +/// 上游 Product/Resource/DataInterface 三处都是 `used + 1 + i`(`used` = 当日同前缀行数)。 +/// 变异实验:把它改成 `used + i` 后旧测试**全绿** ⇒ 零覆盖 ⇒ 这里补一条**相对**断言。 +/// +/// ⚠️ **必须相对断言**:基线 `used` 是「当日同前缀的行数」,同一测试库里别的用例当天建过 +/// Product 就会让基线不是 0 ⇒ 绝不能断言序号段等于 `00000001`。 +#[tokio::test] +async fn product_code_sequence_starts_at_baseline_plus_one() { + let state = test_state().await; + let _p = PRODUCT_LOCK.lock().await; + let spec = registry::find("Product").unwrap(); + + let (_id1, code1) = create_and_read( + &state, + spec, + &json!({"name": "序号口径产品"}), + "productCode", + &principal(), + ) + .await; + // 顺带:两条 Product **同名**也能建(业务级「名称唯一」校验本轮不做 ⇒ 不该拦) + // 🔴 **绝对断言**(相对断言杀不掉 `used + i` 变异:两条码的基线各差 1, + // 偏移量在**差**里会互相抵消 ⇒ 变异后仍然 `seq2 == seq1 + 1`)。 + // 这里数「当日同前缀的行数」(**建完第 1 条之后**的计数 = 基线 + 1): + // 序号必须**正好等于**它 ⇒ 把 `used + 1 + i` 的 `+1` 钉死。 + // (`PRODUCT_LOCK` 保证此刻没有别的用例在写 `tdc_product` ⇒ 计数确定。) + let day = code1 + .split('-') + .nth(1) + .expect("编码应含日期段") + .to_string(); + let count = count_today_products(&state, &format!("PRO-{}-%", day)).await; + assert_eq!( + seq_of(&code1, "PRO"), + count, + "序号必须等于「当日同前缀行数」(used + 1 ⇒ 建完后的计数)" + ); + + let (_id2, code2) = create_and_read( + &state, + spec, + &json!({"name": "序号口径产品"}), + "productCode", + &principal(), + ) + .await; + + assert_eq!( + seq_of(&code2, "PRO"), + seq_of(&code1, "PRO") + 1, + "序号应从基线 +1 递增(used + 1 + i)" + ); + assert_ne!(code1, code2, "整体编码应不同(由序号段的差异解释)"); +} + +/// 🔴 **新建默认值对齐上游**(评审 Important-2 / fix round 3 F-2)。 +/// +/// 上游:Product 新建默认**未上架**(`status = DISABLED`,DDL 里是 `'ENABLED'` ⇒ 必须显式覆盖); +/// Resource 新建默认**停用** + `mountStatus = UNMOUNTED`;Datasource `testStatus = UNTESTED`。 +#[tokio::test] +async fn new_rows_carry_the_upstream_creation_defaults() { + let state = test_state().await; + let _p = PRODUCT_LOCK.lock().await; + + // Product:默认 DISABLED + let spec = registry::find("Product").unwrap(); + let (_id, status) = create_and_read( + &state, + spec, + &json!({"name": "默认状态产品"}), + "status", + &principal(), + ) + .await; + assert_eq!(status, "DISABLED", "Product 新建默认未上架"); + + // Resource:默认 DISABLED + UNMOUNTED + let spec = registry::find("Resource").unwrap(); + let (_id, status) = create_and_read( + &state, + spec, + &json!({"name": "默认状态资源"}), + "status", + &principal(), + ) + .await; + assert_eq!(status, "DISABLED", "Resource 新建默认停用"); + let (_id, mount) = create_and_read( + &state, + spec, + &json!({"name": "默认状态资源"}), + "mountStatus", + &principal(), + ) + .await; + assert_eq!(mount, "UNMOUNTED", "Resource 新建默认未挂载"); + + // Datasource:默认 UNTESTED + let spec = registry::find("Datasource").unwrap(); + let (_id, test_status) = create_and_read( + &state, + spec, + &json!({"name": "默认测试态数据源", "type": "MYSQL"}), + "testStatus", + &principal(), + ) + .await; + assert_eq!(test_status, "UNTESTED", "Datasource 新建默认未测试"); +} + +/// 🔴 `f_creator_user_id` 写**操作人 id**(上游 `safeUserId()` 返回 id,不是名字)。 +#[tokio::test] +async fn creator_user_id_records_the_operator_id_not_the_account_name() { + let state = test_state().await; + let _p = PRODUCT_LOCK.lock().await; + let spec = registry::find("Product").unwrap(); + let account = Principal::Account { + account_id: "U-9".to_string(), + account: "李四".to_string(), + }; + let (_id, creator) = create_and_read( + &state, + spec, + &json!({"name": "归属口径产品"}), + "creatorUserId", + &account, + ) + .await; + assert_eq!(creator, "U-9", "creator 列应写操作人 id"); + assert_ne!(creator, "李四", "creator 列不得写账号名"); +} + +/// 🔴 body 显式 `null` **不得**抑制服务端默认值(上游:字段为 null ⇒ 照样补)。 +/// +/// `f_actor_type` 有 DB DEFAULT `'USER'`;「无主体 + body 显式 null」时, +/// 若引擎把 null 当成「业务已给」⇒ 兜底被静默吞掉 ⇒ 落库会是 DB 的 `'USER'`。 +#[tokio::test] +async fn explicit_null_does_not_suppress_the_server_side_default() { + let state = test_state().await; + let spec = registry::find("AuditLog").unwrap(); + // 无 operator 的内部令牌 ⇒ actor 推导不出来 ⇒ 走 `create_defaults` 的兜底 + let internal = Principal::Internal { operator: None }; + let (_id, actor_type) = create_and_read( + &state, + spec, + &json!({"action": "LOGIN", "actorType": Value::Null}), + "actorType", + &internal, + ) + .await; + assert_eq!( + actor_type, "CONNECTOR", + "显式 null 不得抑制服务端兜底(应落 CONNECTOR,而不是 DB 默认的 USER)" + ); +} + +/// 🔴 **DataInterface 的当日同前缀基线带 `ALIVE`**(上游 `countByCodePrefix:263-268`)。 +/// +/// 构造方式:建一条接口 → 软删它 → 再建一条 ⇒ 若基线带 `ALIVE`,软删行**不占基线** +/// ⇒ 第 2 条的序号与第 1 条**相同**;若不带,第 2 条的序号会 +1。 +/// ⇒ 这条用例**真的走到引擎**(读的是引擎算出来的序号段,不是注册表常量)。 +#[tokio::test] +async fn data_interface_baseline_ignores_soft_deleted_rows() { + let state = test_state().await; + let spec = registry::find("DataInterface").unwrap(); + + let (id1, code1) = create_and_read( + &state, + spec, + &json!({"name": "基线接口甲", "type": "API"}), + "interfaceCode", + &principal(), + ) + .await; + // 软删第 1 条 + let resp = crud::delete(&state, spec, &id1, Some(&principal())).await; + let body = body_of(resp).await; + assert_eq!(body["code"], 200, "软删应成功:{}", body); + + let (_id2, code2) = create_and_read( + &state, + spec, + &json!({"name": "基线接口乙", "type": "API"}), + "interfaceCode", + &principal(), + ) + .await; + + assert_eq!( + seq_of(&code2, "API"), + seq_of(&code1, "API"), + "基线带 ALIVE ⇒ 软删行不占序号基线(上游 DataInterface 口径)" + ); +} + +/// 🔴 500 **不得回显数据库原文**(评审 Minor-7 / fix round 3 F-7)。 +/// +/// 构造:给 `f_price`(`numeric(18,4)`)送一个非数字串 ⇒ PG 报 `22P02` +/// (不在约束映射表里)⇒ 走 500 分支 ⇒ 客户端只能看到固定文案。 +#[tokio::test] +async fn internal_errors_do_not_echo_the_database_message() { + let state = test_state().await; + let _p = PRODUCT_LOCK.lock().await; + let spec = registry::find("Product").unwrap(); + let resp = crud::create( + &state, + spec, + &json!({"name": "脱敏产品", "price": "不是数字"}), + Some(&principal()), + ) + .await; + let body = body_of(resp).await; + assert_eq!(body["code"], 500, "非约束类 DB 错误 ⇒ 500:{}", body); + assert_eq!(body["msg"], "服务异常,请稍后重试", "500 文案须是固定文案"); + let msg = body["msg"].as_str().unwrap(); + assert!(!msg.contains("tdc_product"), "不得回显表名:{}", msg); + assert!(!msg.contains("f_price"), "不得回显列名:{}", msg); + assert!(!msg.contains("numeric"), "不得回显数据库原文:{}", msg); +}