diff --git a/src/crud.rs b/src/crud.rs index 5aaa4e7..63b0e53 100644 --- a/src/crud.rs +++ b/src/crud.rs @@ -49,9 +49,6 @@ 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 { let mut out: HashMap = HashMap::new(); @@ -296,10 +293,39 @@ fn body_text(body: &Value, key: &str) -> Option { } /// 计数查询(走绑定参数,绝不把值拼进 SQL 文本)。 -async fn count_matching(state: &AppState, sql: &str, bind: &str) -> Result { +/// +/// `like_mode = true` ⇒ `WHERE {col} LIKE CAST($1 AS text)`(取「当日同前缀行数」的序号基线); +/// 否则 ⇒ `WHERE {col} = CAST($1 AS text)`(查重)。 +/// +/// 🔴 **查重口径(有意分歧,裁决后保留)**:四个编码列统一按「该列**等值计数**」判定 +/// (**不**加 `f_delete_mark` 谓词)。这与上游 Product/Resource/DataInterface 一致; +/// 上游 **Datasource** 走基类 `newUniqueCode` ⇒ 用 `existsBy` ⇒ 谓词是 `ALIVE` +/// (软删行**不算**占用),本仓对 Datasource **更严**。理由:本仓 4 个编码列的唯一索引 +/// 都是 `WHERE f_delete_mark IS NULL` 的**部分索引** ⇒ 软删行的码在索引层同样不占位 ⇒ +/// 「更严」只会导致**不复用**软删行的旧码(少一个可复用码), +/// **绝不会**造成插入冲突;差异对用户不可观测。 +async fn count_matching( + state: &AppState, + table: &str, + code_key: &str, + bind: &str, + like_mode: bool, +) -> Result { + let col = json_key_to_column(code_key); + if valid_table(table).is_none() { + return Err(server_error(format!("注册表表名非法: {}", table))); + } + if valid_table(&col).is_none() { + return Err(server_error(format!("注册表编码列非法: {}", col))); + } + let op = if like_mode { "LIKE" } else { "=" }; + let sql = format!( + "SELECT count(*)::text FROM {} WHERE {} {} CAST($1 AS text)", + table, col, op + ); let raw = { let _g = state.db_lock.lock().await; - query_scalar_text(state.db.as_ref(), sql, &[&bind]).await + query_scalar_text(state.db.as_ref(), &sql, &[&bind]).await }; match raw { Ok(v) => Ok(v.and_then(|s| s.trim().parse::().ok()).unwrap_or(0)), @@ -310,50 +336,57 @@ async fn count_matching(state: &AppState, sql: &str, bind: &str) -> Result, ) -> Result { - 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? + count_matching(state, spec.table, code.key, &pattern, true).await? } CodeStyle::DayTail6 => 0, }; - for i in 0..CODE_RETRY { - let candidate = match code.style { + generate_code_with(state, spec, code, |i| { + 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 { + } + }) + .await +} + +/// 编码生成的**尝试循环**(候选生成器可注入 —— 供测试构造「恒冲突」场景)。 +/// +/// 逐个候选查重,命中未占用的即采用;`code.retries` 次全冲突 ⇒ `Err(code.fail_msg)`。 +/// +/// 🔴 **重试次数与失败文案都读 `CodeSpec`**(上游逐实体不同:Product/Resource 5 次、 +/// DataInterface/Datasource 3 次;文案也各不相同)—— 不再硬编码。 +async fn generate_code_with( + state: &AppState, + spec: &TableSpec, + code: &CodeSpec, + mut make: F, +) -> Result +where + F: FnMut(u32) -> String, +{ + for i in 0..code.retries { + let candidate = make(i); + let occupied = count_matching(state, spec.table, code.key, &candidate, false).await?; + if occupied == 0 { return Ok(candidate); } } - Err( - ActionResult::fail(format!("接口编码生成失败(重试 {} 次仍冲突)", CODE_RETRY)) - .into_response(), - ) + Err(ActionResult::fail(code.fail_msg).into_response()) } /// 分页列表:`GET /api/ssw/tdc/{Entity}`。 @@ -858,8 +891,13 @@ pub async fn detail_aggregate( #[cfg(test)] mod tests { use super::*; + use crate::config::Config; use crate::registry; + use crate::session::SessionStore; + use crate::state::BootstrapIdentity; + use pglite::PGlite; use serde_json::json; + use std::sync::Arc; #[test] fn parse_query_takes_first_occurrence_and_decodes() { @@ -963,4 +1001,77 @@ mod tests { assert_eq!(child_tables(ds), child_tables(res)); assert!(child_tables(prod).is_empty()); } + + /// 🔴 重试耗尽分支:**真的**走到「所有候选都冲突」⇒ 失败文案取自该实体的 `fail_msg`, + /// 尝试次数取自该实体的 `retries`(上游**逐实体不同**)。 + /// + /// **构造方式**:给生成器注入一个**恒定**候选(`CONST-CODE`),并在目标表预置一行同码 + /// ⇒ 每次查重都命中 ⇒ 必然耗尽。 + /// + /// ⚠️ **为什么必须注入**:真实候选带 **8 位随机尾**(`DaySeqTail8`)或 **6 位随机尾** + /// (`DayTail6`),空间 32^8 / 32^6 ⇒ **无法在集成层稳定构造出一次真实冲突** + /// (要撞中就得枚举十亿级组合)⇒ 只能把随机性从测试里「摘掉」,用可控候选代替。 + /// 这条用例验的是**引擎的决策**(试几次、用哪句文案),不是随机数本身。 + #[tokio::test] + async fn code_generation_gives_up_after_the_entity_specific_retries() { + // ⚠️ pglite-rs 每进程只允许一个 PGlite ⇒ 本单元测试二进制内**只有这一条**开库。 + let db = Arc::new(PGlite::open_temp().await.expect("打开临时 PGlite 失败")); + crate::db::ensure_schema(db.as_ref()) + .await + .expect("建表失败"); + let mut config = Config::from_env(std::env::current_dir().unwrap_or_default()); + config.identity_code = "TEST-CONNECTOR".to_string(); + let state = AppState::new( + config, + db.clone(), + Arc::new(SessionStore::new()), + BootstrapIdentity::default(), + ); + + // (实体, 预置行 SQL, 期望尝试次数, 期望失败文案) + let cases = [ + ( + "Datasource", + "INSERT INTO tdc_datasource (f_id, f_datasource_code, f_name, f_type) \ + VALUES (CAST('T-DS' AS character varying), CAST('CONST-CODE' AS character varying), \ + CAST('n' AS character varying), CAST('MYSQL' AS character varying))", + 3u32, + "系统标识生成失败(连续 3 次撞库),请重试", + ), + ( + "Product", + "INSERT INTO tdc_product (f_id, f_product_code, f_name) \ + VALUES (CAST('T-PR' AS character varying), CAST('CONST-CODE' AS character varying), \ + CAST('n' AS character varying))", + 5u32, + "产品编码生成失败(连续 5 次撞库),请重试", + ), + ]; + + for (api, insert_sql, retries, fail_msg) in cases { + { + let _g = state.db_lock.lock().await; + db.query(insert_sql, &[]) + .await + .expect("插入测试行失败"); + } + let spec = registry::find(api).expect("实体应在注册表里"); + let code = ®istry::create_codes(api)[0]; + let attempts = std::cell::Cell::new(0u32); + let resp = generate_code_with(&state, spec, code, |_| { + attempts.set(attempts.get() + 1); + "CONST-CODE".to_string() + }) + .await + .expect_err("恒冲突 ⇒ 应耗尽重试"); + + assert_eq!(attempts.get(), retries, "{} 的尝试次数", api); + let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX) + .await + .expect("读响应体失败"); + let body: Value = serde_json::from_slice(&bytes).expect("body 是 JSON"); + assert_eq!(body["code"], 400, "{} 的失败应是业务失败", api); + assert_eq!(body["msg"], fail_msg, "{} 的失败文案", api); + } + } } diff --git a/src/registry.rs b/src/registry.rs index 0fb9996..147c584 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -33,6 +33,10 @@ pub struct CodeSpec { pub prefix: &'static str, /// 编码格式(上游两套生成器) pub style: CodeStyle, + /// 撞库重试次数(上游逐实体不同:Product/Resource = 5,DataInterface/Datasource = 3)。 + pub retries: u32, + /// 重试用尽的失败文案(**上游逐字**)。 + pub fail_msg: &'static str, } /// 一个可 CRUD 实体的元数据。 @@ -527,29 +531,37 @@ pub fn validate() -> Result<(), String> { /// ⇒ 不生成就必 500。 pub fn create_codes(api_name: &str) -> &'static [CodeSpec] { match api_name { - // 上游 `ProductServiceImpl#nextProductCode`(TdcCodeUtil,"PRO") + // 上游 `ProductServiceImpl#nextProductCode`(TdcCodeUtil,"PRO"):5 次 "Product" => &[CodeSpec { key: "productCode", prefix: "PRO", style: CodeStyle::DaySeqTail8, + retries: 5, + fail_msg: "产品编码生成失败(连续 5 次撞库),请重试", }], - // 上游 `ResourceServiceImpl#nextResourceCode`(TdcCodeUtil,"RES") + // 上游 `ResourceServiceImpl#nextResourceCode`(TdcCodeUtil,"RES"):5 次 "Resource" => &[CodeSpec { key: "resourceCode", prefix: "RES", style: CodeStyle::DaySeqTail8, + retries: 5, + fail_msg: "资源编码生成失败(连续 5 次撞库),请重试", }], - // 上游 `DataInterfaceServiceImpl#prepare`(TdcCodeUtil,"API") + // 上游 `DataInterfaceServiceImpl#prepare`(TdcCodeUtil,"API"):`CODE_RETRY = 3` "DataInterface" => &[CodeSpec { key: "interfaceCode", prefix: "API", style: CodeStyle::DaySeqTail8, + retries: 3, + fail_msg: "接口编码生成失败(重试 3 次仍冲突)", }], - // 上游 `DatasourceController#beforeSave`(BizCodeUtil.of("DS")) + // 上游 `DatasourceController#beforeSave` → 基类 `newUniqueCode`(BizCodeUtil.of("DS")):3 次 "Datasource" => &[CodeSpec { key: "datasourceCode", prefix: "DS", style: CodeStyle::DayTail6, + retries: 3, + fail_msg: "系统标识生成失败(连续 3 次撞库),请重试", }], _ => &[], } @@ -676,20 +688,54 @@ mod tests { } /// 服务端生成的编码列:4 个实体各一列,且列名过白名单。 + /// + /// 🔴 `(key, prefix, style, retries, fail_msg)` **逐字**等于上游真源 + /// (2026-10-24 controller 逐字复核四份上游文件): + /// Product/Resource 重试 5 次、DataInterface/Datasource 重试 3 次,失败文案各不相同。 #[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), + ( + "Product", + "productCode", + "PRO", + CodeStyle::DaySeqTail8, + 5u32, + "产品编码生成失败(连续 5 次撞库),请重试", + ), + ( + "Resource", + "resourceCode", + "RES", + CodeStyle::DaySeqTail8, + 5u32, + "资源编码生成失败(连续 5 次撞库),请重试", + ), + ( + "DataInterface", + "interfaceCode", + "API", + CodeStyle::DaySeqTail8, + 3u32, + "接口编码生成失败(重试 3 次仍冲突)", + ), + ( + "Datasource", + "datasourceCode", + "DS", + CodeStyle::DayTail6, + 3u32, + "系统标识生成失败(连续 3 次撞库),请重试", + ), ]; - for (api, key, prefix, style) in expected { + for (api, key, prefix, style, retries, fail_msg) 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!( valid_table(&json_key_to_column(key)).is_some(), "编码列名须过白名单: {}", diff --git a/tests/crud_engine.rs b/tests/crud_engine.rs index 886e3ac..5a99c3b 100644 --- a/tests/crud_engine.rs +++ b/tests/crud_engine.rs @@ -479,3 +479,31 @@ async fn contract_cannot_be_deleted() { body ); } + +/// 🔴 编码生成的**逐实体**参数(重试次数 / 失败文案)等于**上游原文**,且**逐实体不同** +/// (上游 Product/Resource 重试 5 次、DataInterface/Datasource 重试 3 次;文案也各不相同)。 +/// +/// ⚠️ 「重试耗尽」这条分支**无法在集成层稳定构造**:真实候选带 8 位(`DaySeqTail8`)或 +/// 6 位(`DayTail6`)随机尾,撞中一次要枚举十亿级组合 ⇒ 该分支由 +/// `src/crud.rs` 里的单元测试(注入恒冲突候选)覆盖;本用例守的是**引擎读到的那份参数**。 +#[tokio::test] +async fn code_retry_counts_and_failure_messages_are_per_entity() { + let expected = [ + ("Product", 5u32, "产品编码生成失败(连续 5 次撞库),请重试"), + ("Resource", 5u32, "资源编码生成失败(连续 5 次撞库),请重试"), + ("DataInterface", 3u32, "接口编码生成失败(重试 3 次仍冲突)"), + ("Datasource", 3u32, "系统标识生成失败(连续 3 次撞库),请重试"), + ]; + for (api, retries, fail_msg) in expected { + let codes = registry::create_codes(api); + assert_eq!(codes.len(), 1, "{} 应恰好一个编码列", api); + assert_eq!(codes[0].retries, retries, "{} 的重试次数", api); + assert_eq!(codes[0].fail_msg, fail_msg, "{} 的失败文案", api); + } + // 逐实体不同 ⇒ 引擎不可能再用「统一的 5 次 + 统一文案」 + let msgs: Vec<&str> = expected.iter().map(|(_, _, m)| *m).collect(); + let mut uniq = msgs.clone(); + uniq.sort_unstable(); + uniq.dedup(); + assert_eq!(uniq.len(), 4, "四个实体的失败文案应各不相同:{:?}", msgs); +}