diff --git a/.workbuddy/memory/2026-10-26.md b/.workbuddy/memory/2026-10-26.md index 6b19eb0..0fe0173 100644 --- a/.workbuddy/memory/2026-10-26.md +++ b/.workbuddy/memory/2026-10-26.md @@ -121,7 +121,8 @@ cargo test → exit 0(全绿) | C5 | 免鉴权端点清单归业务层(`tdc::support::public_paths`)⇒ 平台层零端点字面量 | `df7ce37` | | C6 | 「假权限层」拆除清单**先记账**(零代码改动) | `8618465` | | C7 | `/api/health` 补 `baseTables`(W5 契约的账号层表数) | `f8764b2` | -| C8 | 配置分家:平台 `Config` 削掉 5 个业务字段,业务配置进 `tdc::config::TdcConfig` | 本次提交 | +| C8 | 配置分家:平台 `Config` 削掉 5 个业务字段,业务配置进 `tdc::config::TdcConfig` | `1797aa0` | +| C9 | 状态分家:平台 `AppState` 只留配置/db/锁/会话,业务态进 `tdc::state::TdcState`(Deref + FromRef) | 本次提交 | **关键决定** @@ -134,13 +135,36 @@ cargo test → exit 0(全绿) **C8 之后的实测**:`cargo test` **235 passed / 0 failed / 1 ignored**(新增 6 条:TdcConfig 4 + 业务常量 2)· `smoke.sh` **PASS=75 FAIL=0**(断言数不变)· `check-boundary.sh` **exit 0**(未记账越界 0 · 失效条目 0)· `check-entity.sh` **PASS=15 FAIL=0**。 +**C9 之后的实测**:`cargo test` **237 passed / 0 failed / 1 ignored**(新增 2 条:业务态默认值 + deref 取平台那半)· +`smoke.sh` **PASS=75 FAIL=0** · `check-boundary.sh` **exit 0**(CP5 = 新增的第 5 个接触点,平台层零 `use crate::tdc::`)· `check-entity.sh` **PASS=15 FAIL=0**。 + +**C9 的技术选型**:业务层 `TdcState` **deref 到** `platform::state::AppState`(⇒ `state.db` 等字段访问零改动) ++ `impl FromRef for AppState`(⇒ axum 里 `State` 可用,平台端点不必认识业务类型)。 +🔴 `FromRef` 在 **`axum::extract::FromRef`**(`axum::core::extract::FromRef` 不存在)。 + +**平台→业务的反向依赖怎么钉住的**:新增 **CP5** 接触点(`scripts/check-boundary.sh`):平台层不得 `use crate::tdc::`。 +CP1 只查「表名前缀 / 端点前缀」,查不出模块引用 ⇒ 必须单独立一条。 + +**⚠️ 环境事故:macOS SysV 信号量泄漏(本轮最大的一次环境排障)** + +- **症状**:`cargo test` 全挂在 `initdb failed: … could not create semaphores: No space left on device`。 +- **根因**:macOS(XNU) 的 SysV 信号量集**在创建进程退出后不回收**,系统也**不带 `ipcrm`/`ipcs`**。 + 本仓每轮 `cargo test` 新建若干 PGlite 实例(initdb 阶段 `semget(key, 20, 03600)`)⇒ 每实例漏 20 个信号量。 +- **实测规模**:现存 set 4662 个 / 信号量 87312 个(上限 `kern.sysv.semmns`=87381)⇒ 其中 + **nsems=20 的 4350 个 = 87000 个信号量**(全是 PGlite 泄漏,uid=501=本用户), + 另有 nsems=1 的 312 个(别的程序,**保留不动**);可建 set 上限只剩 9 个信号量 ⇒ PG 要 20 ⇒ 起不来。 +- **解法**:`scripts/ipc-reap.c` + `scripts/reap-ipc-leaks.sh`(新增,commit `6e14fbe`)—— + 扫 id 空间用 `semctl(IPC_STAT)` 找现存 set,再对「**nsems==20 且 uid==本用户且最近一次 semop 超过 1 小时**」 + 的做 `IPC_RMID`。实测回收 4350 个 set / 87000 个信号量 ⇒ 可建上限回到 4096。 +- **代价**:跑测试前留意余量;跑够约 400 轮会再次撑满 ⇒ 跑 `bash scripts/reap-ipc-leaks.sh` 即可。 +- ⚠️ **杀进程没用**(退出即漏),**只有 IPC_RMID 或重启**能清。 + --- ## 当前状态 - 分支 `feat/mvc-align-v3`;**回退点 = `06f5a79`**(v3 spec 落点)。 -- B1b 已完成 **C1–C8**;下一条 = **C9**(`AppState` 拆两半:平台 `AppState` + 业务 `TdcState`)。 - C9 之后还剩 **C10**(`tdc_identity` 领域 SQL 收口到 `tdc/service/identity.rs` + 只 SELECT 明确列)/ +- B1b 已完成 **C1–C9**;下一条 = **C10**(`tdc_identity` 领域 SQL 收口到 `tdc/service/identity.rs` + 只 SELECT 明确列)/ **C11**(`constant_time_eq` 上收到平台)/ **C12**(`civil_from_days`/`now_iso` 换 `chrono`,口径 **UTC**)。 - B1b 验收:`cargo test` 全绿 + `smoke.sh` 断言数 **== 75** + `check-boundary.sh` 全绿 (**7 条 B1b 账本条目已清空**)+ `check-entity.sh` 全绿 + 浏览器验收重跑(**未重跑** ⇒ B5 前补)。 diff --git a/CLAUDE.md b/CLAUDE.md index db41f82..9de7cf4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -34,7 +34,7 @@ tdc-rs/ │ ├── main.rs # 启动装配:PGlite open / 引导身份 / 账号库 / 路由 / 中间件 / 静态兜底 │ ├── lib.rs # 模块声明(只暴露 `platform` 与 `tdc` 两层,bin 只做装配) │ ├── platform/ # 【平台层】与业务**零**知识(边界由 check-boundary.sh 静态钉住) -│ │ ├── state.rs # AppState(config + db + db_lock + sessions + accounts + bootstrap + tds) +│ │ ├── state.rs # AppState(config + db + db_lock + sessions)—— **零业务字段**(业务态在 `tdc/state.rs`) │ │ ├── config.rs # **平台**环境变量配置(端口/数据目录/令牌/出向地址)+ 密钥守卫(**零业务字段**) │ │ ├── db.rs # PGlite 封装(query_json / ensure_schema / f_↔camelCase 映射) │ │ ├── session.rs # 会话存储(两种 kind:Identity / Account) @@ -55,6 +55,7 @@ tdc-rs/ │ ├── util/code.rs # 业务编码生成器(原 src/codec.rs:PRO/RES/API/DS 前缀 + 两套上游生成器) │ ├── config.rs # **业务**配置 TdcConfig(身份码/身份名/身份密钥/引导管理员账号口令) │ ├── constant.rs # **业务**常量(身份码/身份名默认值 + 业务 env 名清单) +│ ├── state.rs # **业务**态 TdcState(platform + 业务配置 + 引导身份 + 账号库 + TDS 客户端) │ ├── support/ # 业务侧公共清单(public_paths:免鉴权端点) │ └── policy/ engine/ schedule/ notify/ heartbeat/ sso/ # 上游同名包占位(后续批) ├── static/ # 上游 SPA 构建产物(index.html + logo.png + assets/,8 个产物文件) @@ -77,9 +78,15 @@ tdc-rs/ - 🔴 **平台层 / 业务层边界**(v3 spec §2.3):`src/platform/` 里**不许出现业务知识** ——业务表名(`tdc_*`)、实体名(`Product` / `Resource` / …)、具体端点路径(`/api/ssw/tdc/…`)、 业务表数量;`src/tdc/` 里**不许出现平台能力的第二份实现**。 - 这条**可被静态检查** ⇒ `scripts/check-boundary.sh` 的 4 个接触点(CP1–CP4)。 + 这条**可被静态检查** ⇒ `scripts/check-boundary.sh` 的 **5 个接触点(CP1–CP5)**。 🔴 **通用 CRUD 引擎住在业务层**(`tdc/mapper.rs` + `tdc/service/crud.rs` + `tdc/controller/crud.rs`, 对位上游 `TdcCrudController`)但**逻辑必须实体无关(零 `match api_name`)** ⇒ 分支只能读 `TableSpec` 字段。 +- 🔴 **平台态与业务态分家**(v3 spec §2.3.1 C9):平台 `platform::state::AppState` 只留 + **配置 / db / db_lock / 会话**;**引导身份 / 本地账号库 / TDS 客户端 / 业务配置** 归业务层 + `tdc::state::TdcState`(`platform` 那一半 + 业务字段)⇒ **平台层不再 import 业务模块** + (CP5 专门盯这条)。 + 业务层拿平台那一半靠两件套:`TdcState: Deref`(字段直取) + + `impl FromRef for AppState`(axum 里 `State` 可用)。 - 🔴 **平台配置与业务配置分家**(v3 spec §2.3.1 C8):平台 `platform::config::Config` 只留 **端口 / 数据目录 / 入向令牌 / 出向令牌与地址 / 单机模式 / 密钥守卫**; **身份码 / 身份名 / 身份密钥 / 引导管理员账号与口令** 归业务层 `tdc::config::TdcConfig` @@ -123,6 +130,10 @@ curl -s --noproxy '*' http://127.0.0.1:30000/api/health curl -s --noproxy '*' -X POST http://127.0.0.1:30000/api/oauth/Login \ -H 'Content-Type: application/x-www-form-urlencoded' \ --data-urlencode 'account=admin' --data-urlencode "password=<密文hex>" --data-urlencode 'grant_type=password' + +# 回收 macOS 上泄漏的 SysV 信号量(PGlite 专用;见「已知踩坑」最后一行) +bash scripts/reap-ipc-leaks.sh --dry-run # 只报不删 +bash scripts/reap-ipc-leaks.sh # 回收(会改系统 IPC 表) ``` > 本机 curl 走系统代理,**测 localhost 必须加 `--noproxy '*'`**,否则会得到 502。 @@ -257,6 +268,10 @@ bash scripts/check-entity.sh # ③ 实体静态(加实体的接触点完 16. **引导身份要显式递业务配置**(C8):`identity::bootstrap_identity(state, &tdc_config)` ——身份码/身份名/身份密钥**不在** `state.config` 里 ⇒ 由装配层(`main.rs`)造 `TdcConfig::from_env()` 递进去。`TdcConfig::from_raw(..)` 是**纯函数**(不读全局 env)⇒ 可单测。 +17. **状态两半的取法**(C9):业务层 `TdcState` **deref 到** `platform::state::AppState` + ⇒ `state.db` / `state.db_lock` / `state.sessions` / `state.config` 照旧可用; + axum 里想只拿平台那一半 ⇒ `State`(靠 `impl FromRef for AppState`)。 + 🔴 `FromRef` 在 **`axum::extract::FromRef`**(不是 `axum::core::extract::FromRef`)。 ## 数据模型 @@ -361,6 +376,7 @@ bash scripts/check-entity.sh # ③ 实体静态(加实体的接触点完 | `ServiceCatalog/Buy` 空体报「请求体格式有误」 | 用了 `JsonBody`(空体 ⇒ 拒) | 这几个端点体**可空** ⇒ 用 `tds_biz::OptionalJsonBody`(空体当空对象) | | 出向 URL 拼出注入 | 用户输入直接进 URL 路径 | 只用固定模板 + `tds::is_safe_path_segment` 校验过的段 | | `GET /api/ssw/tdc/Identity` 回显 `secretKey` | CRUD 出参是 `SELECT *` + camelCase 直出,没走上游 `@JsonIgnore` 白名单 | 出参过 `crud::row_to_json_spec()`(按 `spec.hidden_fields` 删键)⇒ 新增实体先对照上游 `ssw-tdc-entity` 查 `@JsonIgnore` | +| `cargo test` 全挂在 `initdb failed: … could not create semaphores: No space left on device` | **macOS 不回收进程退出时创建的 SysV 信号量集**(且无 `ipcrm`)⇒ 每轮 `cargo test` 的 PGlite 实例各漏 20 个信号量,攒够就把 `kern.sysv.semmns`(87381) 撑满 | 跑 `bash scripts/reap-ipc-leaks.sh` 回收(只删 `nsems==20` + 本 uid + 久未使用的 set);**跑测试前先看一眼余量** | ## 明确不在本仓库范围 diff --git a/scripts/check-boundary.sh b/scripts/check-boundary.sh index 35f36e0..641e8f0 100644 --- a/scripts/check-boundary.sh +++ b/scripts/check-boundary.sh @@ -13,13 +13,18 @@ # 没记账的越界 ⇒ 红(当场抓新增泄漏);记账已失效的条目 ⇒ 红(账本只许变短)。 # ⇒ B1b 的 C1–C12 做完,账本必须清空。 # -# 扫描口径(**四条接触点的判定规则,写死在这里,避免"尺子随实现漂移"**): +# 扫描口径(**接触点的判定规则,写死在这里,避免"尺子随实现漂移"**): # ① 只扫**非测试代码**:每个文件里第一处 `#[cfg(test)]` 之后的内容不计入 # (单元测试必须引用具体实体/端点才有意义;生产代码不许)。 # ② 注释不计入(`//` 行注释、`/* */` 块注释都先剥掉)。 # ③ 平台层 = `src/platform/**`(新布局)或旧布局的平台件清单(见 `PLATFORM_LEGACY`)。 # ④ 通用 CRUD 引擎 = `src/tdc/{mapper,service/crud,controller/crud}.rs`(新布局) # 或 `src/crud.rs` + `src/routes/crud.rs`(旧布局)。 +# +# 🔴 **CP5 是 C9 之后补的第 5 条**(v3 spec §2.3.2 的 4 条接触点之外): +# 「平台层不得 import 业务层」—— 拆 `AppState` 之前 `src/platform/state.rs` +# 直接 `use crate::tdc::service::account::AccountStore` ⇒ 依赖方向反了, +# 而 CP1(只查表名/端点前缀)查不出来 ⇒ 补这条钉住。 set -u @@ -232,6 +237,20 @@ for path in PLATFORM_FILES: if pat in s: add("CP1", path, lineno, s, pat) +# CP5:平台层**不得 import 业务层**(平台 → 业务的反向依赖) +# +# 🔴 这条是 C9 之后补上的:拆 `AppState` 之前,`src/platform/state.rs` 直接 +# `use crate::tdc::service::account::AccountStore` / `use crate::tdc::client::tds::TdsClient` +# ⇒ 平台层被迫认识业务类型 ⇒ 依赖方向反了。 +# CP1 只查「表名前缀 / 端点前缀」,查不出 `crate::tdc::` 这种**模块引用** ⇒ 补这条。 +for path in PLATFORM_FILES: + lines = code_lines(path) + if lines is None: + continue + for lineno, s in lines: + for m in re.finditer(r"\buse\s+(?:crate|super)::tdc\b", s): + add("CP5", path, lineno, s, m.group(0)) + # CP2:平台层不得出现具体实体名 for path in PLATFORM_FILES: lines = code_lines(path) @@ -307,8 +326,9 @@ RULE_DESC = { "CP2": "平台层不得出现具体业务实体名", "CP3": "通用 CRUD 引擎不得按实体名分支(只能读 TableSpec 字段)", "CP4": "平台 auth 不得出现字面量端点路径(只能引用业务层清单)", + "CP5": "平台层不得 import 业务层(平台 → 业务的反向依赖)", } -for rule in ("CP1", "CP2", "CP3", "CP4"): +for rule in ("CP1", "CP2", "CP3", "CP4", "CP5"): rs = [f for f in findings if f[0] == rule] print("%s:%d 处发现 —— %s" % (rule, len(rs), RULE_DESC[rule])) for f in rs: diff --git a/src/main.rs b/src/main.rs index 6cc2c20..ffee682 100644 --- a/src/main.rs +++ b/src/main.rs @@ -31,7 +31,8 @@ use tdc_connector::tdc::controller::build_router; use tdc_connector::tdc::support::public_paths; use tdc_connector::platform::fallback::{api_not_found, spa_fallback}; use tdc_connector::platform::session::SessionStore; -use tdc_connector::platform::state::{AppState, BootstrapIdentity}; +use tdc_connector::platform::state::AppState; +use tdc_connector::tdc::state::TdcState; const APP_VERSION: &str = env!("CARGO_PKG_VERSION"); @@ -109,16 +110,15 @@ async fn main() { // ⚠️ pglite-rs **每进程只允许一个 PGlite 实例**(crate 内部 `static OPEN`), // ⇒ 引导身份必须复用上面这个 db(不能另开 `open_temp`)。 - // ⚠️ 全进程只造**一个** `AppState`(两个 `AppState` 意味着两把 db_lock ⇒ 序列化前提被破坏); + // ⚠️ 全进程只造**一个**状态(两个状态意味着两把 db_lock ⇒ 序列化前提被破坏); // 引导完用 `with_bootstrap` 把结果换回去。 - let state = AppState::new( - config.clone(), - db.clone(), - sessions.clone(), - BootstrapIdentity::default(), - ); + // + // 🔴 **状态分两半**(v3 spec §2.3.1 C9):平台层 `AppState`(配置 / db / 锁 / 会话) + // + 业务层 `TdcState`(引导身份 / 账号库 / TDS 客户端 / 业务配置)。 + // 引导在**装配期**跑 ⇒ 那时业务状态还没组装 ⇒ 引导函数只吃平台那一半。 + let platform = AppState::new(config.clone(), db.clone(), sessions.clone()); let bootstrap = - tdc_connector::tdc::service::identity::bootstrap_identity(&state, &tdc_config).await; + tdc_connector::tdc::service::identity::bootstrap_identity(&platform, &tdc_config).await; // 🔴 没有身份(引导 INSERT 失败)⇒ 直接退出:一个连登录都做不了的连接器, // 「启动失败一眼看得出」远好于「服务起着但一登录就报错」。 if bootstrap.identity_id.is_empty() { @@ -140,10 +140,10 @@ async fn main() { println!("[tdc-connector] ⚠️ 密钥只打印这一次,请立刻保存"); } - let state = state.with_bootstrap(bootstrap); + // 业务状态:平台那一半 + 引导身份 + 业务配置(账号库与 TDS 客户端随后挂上去)。 + let state = TdcState::new(platform, tdc_config.clone(), bootstrap); // 本地账号库(上游完整前端的 JNPF 兼容登录用):JSON 文件,不进数据库。 - // 🔴 挂在 `with_bootstrap` **之后**(`with_accounts` 只换 `accounts` 字段,其余保留)。 // ⚠️ `data_dir` 已在上面定义(来自 `config.data_dir`)⇒ 这里**不重新定义**。 // 🔴 引导口令可被 `TDC_BOOTSTRAP_ADMIN_PASSWORD` 覆盖(**只对空库生效**)。 let accounts = Arc::new( diff --git a/src/platform/mod.rs b/src/platform/mod.rs index 3871efc..8b922a1 100644 --- a/src/platform/mod.rs +++ b/src/platform/mod.rs @@ -4,15 +4,16 @@ //! 业务表名(`tdc_*`)、实体名(`Product` / `Resource` / …)、 //! 具体端点路径(`/api/ssw/tdc/…`)、业务表数量。 //! -//! 这条规约**可被静态检查** ⇒ `scripts/check-boundary.sh` 的 4 个接触点: +//! 这条规约**可被静态检查** ⇒ `scripts/check-boundary.sh` 的 5 个接触点: //! ① `tdc_` / `/api/ssw/tdc/` 字面量; //! ② 业务实体名; //! ③ 通用 CRUD 引擎按实体名分支(引擎住在业务层,但逻辑必须实体无关); -//! ④ 平台 auth 出现字面量端点路径(白名单清单归业务层 `tdc/support/public_paths.rs`)。 +//! ④ 平台 auth 出现字面量端点路径(白名单清单归业务层 `tdc/support/public_paths.rs`); +//! ⑤ **平台层 import 业务层**(平台 → 业务的反向依赖;C9 之后补的钉子)。 //! //! | 模块 | 职责 | 对位上游 | //! |---|---|---| -//! | `state` | `AppState`(配置 + db + 锁 + 会话 + 账号 + 引导身份) | — | +//! | `state` | `AppState`(配置 + db + 锁 + 会话)—— **业务态在 `tdc::state::TdcState`** | — | //! | `config` | 环境变量配置 + 密钥守卫 | — | //! | `db` | PGlite 封装 + SQL 切分 + `f_`↔camelCase 映射契约 | — | //! | `session` | 内存会话(`Identity` / `Account` 两种 kind) | — | diff --git a/src/platform/state.rs b/src/platform/state.rs index fafc0e5..aadf36b 100644 --- a/src/platform/state.rs +++ b/src/platform/state.rs @@ -1,14 +1,16 @@ -//! 全局应用状态:PGlite 句柄 + DB 锁 + 会话存储 + 配置。 +//! 全局应用状态(**平台部分**):PGlite 句柄 + DB 锁 + 会话存储 + 配置。 +//! +//! 🔴 **平台层零业务知识**(v3 spec §2.3.1 C9):本 struct 只装「与业务无关」的运行态。 +//! 业务态(引导身份 / 本地账号库 / TDS 出向客户端 / 业务配置)归业务层 +//! `crate::tdc::state::TdcState` ⇒ 平台层**不认识** `tdc_*` 实体,也**不 import** 业务模块。 use std::sync::{Arc, OnceLock}; use pglite::PGlite; use tokio::sync::Mutex; -use crate::tdc::service::account::AccountStore; use crate::platform::config::Config; use crate::platform::session::SessionStore; -use crate::tdc::client::tds::TdsClient; /// 进程级唯一的 DB 锁。 /// @@ -22,6 +24,10 @@ pub fn process_db_lock() -> Arc> { DB_LOCK.get_or_init(|| Arc::new(Mutex::new(()))).clone() } +/// 平台层状态(**业务无关**)。 +/// +/// 🔴 业务态(引导身份 / 账号库 / TDS 客户端 / 业务配置)在 +/// `crate::tdc::state::TdcState` 里 ⇒ 业务层用 `Deref` 把本 struct 当作「平台那一半」。 #[derive(Clone)] pub struct AppState { pub config: Arc, @@ -32,56 +38,15 @@ pub struct AppState { /// `AppState`(哪怕指向同一个 `PGlite`)都共享它。 pub db_lock: Arc>, pub sessions: Arc, - /// 首次启动引导出来的本地身份。 - pub bootstrap: Arc, - /// 本连接器的本地账号库(默认是**内存空库** ⇒ 早期任务与单测不必改)。 - pub accounts: Arc, - /// TDS 出向客户端(≡ 上游 `TdsReportClient` 的 internal 通道)。 - /// - /// 🔴 未配 `SSW_TDS_BASE_URL` ⇒ **NOOP 模式**(出向请求一律回业务失败, - /// 不发任何网络请求)⇒ 本地单机模式不会因为「没配 TDS」而 500。 - pub tds: Arc, -} - -#[derive(Debug, Clone, Default)] -pub struct BootstrapIdentity { - pub identity_id: String, - pub identity_code: String, - /// 仅当本次启动**新建**了身份时才有值 —— 用于把密钥打印一次。 - pub issued_secret: Option, } impl AppState { - pub fn new( - config: Config, - db: Arc, - sessions: Arc, - bootstrap: BootstrapIdentity, - ) -> Self { - // 🔴 先从 `config` 取值再 move(`config` 随后被包进 `Arc`)。 - let tds = Arc::new(TdsClient::new( - config.tds_base_url.clone(), - config.tds_internal_token.clone(), - )); + pub fn new(config: Config, db: Arc, sessions: Arc) -> Self { Self { config: Arc::new(config), db, db_lock: process_db_lock(), sessions, - bootstrap: Arc::new(bootstrap), - accounts: Arc::new(AccountStore::empty()), - tds, - } - } - - /// 换掉引导身份(**其余字段原样保留**,特别是 `db_lock`)。 - /// - /// 用途:启动时先用 `BootstrapIdentity::default()` 造状态、跑引导,再把结果换回来 —— - /// 这样全程只有**一个** `AppState`(也就只有一把 `db_lock`)。 - pub fn with_bootstrap(self, bootstrap: BootstrapIdentity) -> Self { - Self { - bootstrap: Arc::new(bootstrap), - ..self } } @@ -89,41 +54,12 @@ impl AppState { pub fn cfg(&self) -> &Config { &self.config } - - /// 挂上本地账号库(**其余字段原样保留**,特别是 `db_lock`)。 - /// - /// 用途:启动时先造状态、跑身份引导,再把账号库换上去 —— - /// 这样全程只有**一个** `AppState`(也就只有一把 `db_lock`)。 - pub fn with_accounts(self, accounts: Arc) -> Self { - Self { accounts, ..self } - } - - /// 换掉 TDS 出向客户端(**其余字段原样保留**,特别是 `db_lock`)。 - /// - /// 用途:集成测试里把客户端指向**假 TDS**(起一个本地 axum server)。 - pub fn with_tds(self, tds: TdsClient) -> Self { - Self { - tds: Arc::new(tds), - ..self - } - } } #[cfg(test)] mod tests { use super::*; - // 说明:`AppState::new` 需要一个真实的 `PGlite` 句柄,而 pglite-rs **每进程只允许一个实例** - // ⇒ 单元测试里不能随便开库(会与集成测试抢 `static OPEN`)。 - // 这里只断言「不依赖库的纯字段」,避免在 `--lib` 阶段开第二个 PGlite。 - #[test] - fn bootstrap_identity_defaults_to_empty_and_no_secret() { - let b = BootstrapIdentity::default(); - assert!(b.identity_id.is_empty()); - assert!(b.identity_code.is_empty()); - assert!(b.issued_secret.is_none(), "未引导时不得有密钥"); - } - #[test] fn state_exposes_the_config_and_session_store() { // `AppState` 只做「装订」:配置进 `config`、会话进 `sessions`。 diff --git a/src/tdc/controller/account.rs b/src/tdc/controller/account.rs index 6dd3161..4607a77 100644 --- a/src/tdc/controller/account.rs +++ b/src/tdc/controller/account.rs @@ -16,7 +16,7 @@ use crate::tdc::service::account::{constant_time_eq, Account}; use crate::platform::auth::Principal; use crate::platform::cipher::decrypt_login_password; use crate::platform::envelope::{ActionResult, Pagination}; -use crate::platform::state::AppState; +use crate::tdc::state::TdcState; /// 登录表单(`application/x-www-form-urlencoded`)。 #[derive(Debug, Deserialize)] @@ -31,7 +31,7 @@ pub struct LoginForm { pub grant_type: Option, } -pub fn router() -> Router { +pub fn router() -> Router { Router::new() .route("/api/oauth/Login", post(login)) .route("/api/permission/Users", get(list_users).post(create_user)) @@ -46,7 +46,7 @@ pub fn router() -> Router { .route("/api/permission/Users/{id}/Actions/State", put(set_state)) } -async fn login(State(state): State, body: axum::body::Bytes) -> Response { +async fn login(State(state): State, body: axum::body::Bytes) -> Response { // 🔴 axum 0.8.9:`Form` 只实现了 `FromRequest`,**没有** `OptionalFromRequest` // ⇒ `Option>` **编译不过**(`axum-0.8.9/src/form.rs` 只有 // `impl FromRequest for Form`)⇒ 自己取原始 body 解析。 @@ -115,7 +115,7 @@ fn account_view(a: &Account) -> Value { /// /// 🔴 **fail-closed**(对齐上游 `TdcConnectorAdminGuard`):账号查不到 ⇒ `false` ⇒ 403。 #[allow(clippy::result_large_err)] -fn require_admin(state: &AppState, p: Option<&Extension>) -> Result<(), Response> { +fn require_admin(state: &TdcState, p: Option<&Extension>) -> Result<(), Response> { match p.map(|e| &e.0) { Some(Principal::Session { .. }) => Ok(()), Some(Principal::Account { account_id, .. }) => { @@ -158,7 +158,7 @@ pub struct UserQuery { } async fn list_users( - State(state): State, + State(state): State, p: Option>, Query(q): Query, ) -> Response { @@ -216,7 +216,7 @@ pub struct CreateUserBody { } async fn create_user( - State(state): State, + State(state): State, p: Option>, body: Option>, ) -> Response { @@ -255,7 +255,7 @@ pub struct UpdateUserBody { } async fn update_user( - State(state): State, + State(state): State, p: Option>, Path(id): Path, body: Option>, @@ -283,7 +283,7 @@ async fn update_user( } async fn remove_user( - State(state): State, + State(state): State, p: Option>, Path(id): Path, ) -> Response { @@ -307,7 +307,7 @@ pub struct ResetPasswordBody { } async fn reset_password( - State(state): State, + State(state): State, p: Option>, Path(id): Path, body: Option>, @@ -344,7 +344,7 @@ pub struct StateBody { } async fn set_state( - State(state): State, + State(state): State, p: Option>, Path(id): Path, body: Option>, diff --git a/src/tdc/controller/auth.rs b/src/tdc/controller/auth.rs index dcd604c..0daa8f6 100644 --- a/src/tdc/controller/auth.rs +++ b/src/tdc/controller/auth.rs @@ -4,9 +4,9 @@ use axum::routing::{get, post}; use axum::Router; use crate::tdc::service::identity; -use crate::platform::state::AppState; +use crate::tdc::state::TdcState; -pub fn router() -> Router { +pub fn router() -> Router { Router::new() .route("/api/ssw/tdc/Auth/Login", post(identity::login)) .route("/api/ssw/tdc/Auth/Me", get(identity::me)) diff --git a/src/tdc/controller/crud.rs b/src/tdc/controller/crud.rs index 69dfc03..667ace1 100644 --- a/src/tdc/controller/crud.rs +++ b/src/tdc/controller/crud.rs @@ -22,9 +22,9 @@ use crate::platform::auth::Principal; use crate::tdc::service::crud; use crate::tdc::entity::{self, TableSpec}; use crate::tdc::mapper; -use crate::platform::state::AppState; +use crate::tdc::state::TdcState; -pub fn router() -> Router { +pub fn router() -> Router { let mut r = Router::new(); for spec in entity::ALL_SPECS { let s: &'static TableSpec = spec; @@ -32,7 +32,7 @@ pub fn router() -> Router { .route( s.path, get( - move |State(st): State, + move |State(st): State, q: RawQuery, p: Option>| { let params = mapper::parse_query(q.0.as_deref()); @@ -41,7 +41,7 @@ pub fn router() -> Router { }, ) .post( - move |State(st): State, + move |State(st): State, p: Option>, b: JsonBody| { let principal = p.map(|e| e.0); @@ -53,7 +53,7 @@ pub fn router() -> Router { .route( &format!("{}/All", s.path), get( - move |State(st): State, + move |State(st): State, q: RawQuery, p: Option>| { let params = mapper::parse_query(q.0.as_deref()); @@ -66,7 +66,7 @@ pub fn router() -> Router { &format!("{}/{{id}}", s.path), get( move |Path(id): Path, - State(st): State, + State(st): State, p: Option>| { let principal = p.map(|e| e.0); async move { crud::detail(&st, s, &id, principal.as_ref()).await } @@ -74,7 +74,7 @@ pub fn router() -> Router { ) .put( move |Path(id): Path, - State(st): State, + State(st): State, p: Option>, b: JsonBody| { let principal = p.map(|e| e.0); @@ -84,7 +84,7 @@ pub fn router() -> Router { ) .delete( move |Path(id): Path, - State(st): State, + State(st): State, p: Option>| { let principal = p.map(|e| e.0); async move { crud::delete(&st, s, &id, principal.as_ref()).await } @@ -110,7 +110,7 @@ pub fn router() -> Router { &format!("{}/{{id}}/Detail", s.path), get( move |Path(id): Path, - State(st): State, + State(st): State, p: Option>| { let principal = p.map(|e| e.0); async move { crud::detail_aggregate(&st, s, &id, principal.as_ref()).await } diff --git a/src/tdc/controller/health.rs b/src/tdc/controller/health.rs index 2b85a62..8fe16fb 100644 --- a/src/tdc/controller/health.rs +++ b/src/tdc/controller/health.rs @@ -17,9 +17,9 @@ use axum::extract::State; use axum::routing::get; use axum::Router; -use crate::platform::state::AppState; +use crate::tdc::state::TdcState; -pub fn router() -> Router { +pub fn router() -> Router { Router::new().route("/api/health", get(health)) } @@ -28,7 +28,7 @@ pub fn router() -> Router { /// /// ⚠️ 保留 `tdsMode` / `tdsBaseUrl` 两个旧字段(`CLAUDE.md` 记录的既有契约), /// 避免 `/api/health` 迁到本模块后丢字段。 -async fn health(State(state): State) -> axum::Json { +async fn health(State(state): State) -> axum::Json { // 一次查询同时数两类表(少一次往返)⇒ `tables` = tdc_*,`baseTables` = base_*。 let (tables, base_tables) = { let _g = state.db_lock.lock().await; diff --git a/src/tdc/controller/mod.rs b/src/tdc/controller/mod.rs index 6481838..960ac87 100644 --- a/src/tdc/controller/mod.rs +++ b/src/tdc/controller/mod.rs @@ -11,20 +11,20 @@ pub mod tds_biz; use axum::Router; -use crate::platform::state::AppState; +use crate::tdc::state::TdcState; /// 组装全部业务路由(不含静态资源与中间件装配,那部分在 `main.rs`)。 /// /// ⚠️ axum 0.8 的 `Router` 语义:**S 是「还缺什么状态」**,不是「有什么状态」。 /// `with_state(state)` 会把状态烤进**当前已有**的 endpoint;之后新增的 endpoint -/// 仍需再 `with_state` 一次才能拿到状态 ⇒ 这里返回 `Router`(仍缺 AppState), +/// 仍需再 `with_state` 一次才能拿到状态 ⇒ 这里返回 `Router`(仍缺 TdcState), /// 由 `main.rs` 在挂完静态兜底与中间件后统一 `with_state` 收口。 /// /// 🔴 **405 的 JSON 兜底不在这里**:旧的 `.method_not_allowed_fallback(...)` 只对 /// 调用那一刻已注册的路由生效(且会丢掉 `Allow` 头),管不到 `main.rs` 之后追加的 /// 路由与 SPA 静态兜底 ⇒ 改由 `mw::json_method_not_allowed` 这个**响应改写中间件** /// 统一处理(挂载点在 `main.rs` 链尾)。 -pub fn build_router(state: AppState) -> Router { +pub fn build_router(state: TdcState) -> Router { Router::new() .merge(health::router()) .merge(auth::router()) diff --git a/src/tdc/controller/tds_biz.rs b/src/tdc/controller/tds_biz.rs index d3e6856..e608473 100644 --- a/src/tdc/controller/tds_biz.rs +++ b/src/tdc/controller/tds_biz.rs @@ -25,11 +25,11 @@ use crate::platform::auth::Principal; use crate::tdc::mapper::{param, parse_query, row_to_json}; use crate::platform::db::query_json_params; use crate::platform::envelope::{ActionResult, CODE_SERVER_ERROR}; -use crate::platform::state::AppState; +use crate::tdc::state::TdcState; use crate::tdc::client::tds; /// 装配 10 个端点(路径/方法**逐字对齐上游**)。 -pub fn router() -> Router { +pub fn router() -> Router { Router::new() // ---- 服务目录(上游 ServiceCatalogController) ---- .route("/api/ssw/tdc/ServiceCatalog", get(service_catalog_list)) @@ -102,7 +102,7 @@ struct LocalIdentity { /// /// 🔴 取**默认身份行**(`f_default_mark` 优先,其次 `f_id` 序)⇒ 与上游「固定实例身份」同口径。 /// 两列 schema 里**已存在**(`tdc_identity.f_tds_space_id` / `f_tds_connector_id`)。 -async fn local_identity(state: &AppState) -> LocalIdentity { +async fn local_identity(state: &TdcState) -> LocalIdentity { let sql = "SELECT f_tds_space_id, f_tds_connector_id FROM tdc_identity \ WHERE f_delete_mark IS NULL OR f_delete_mark = 0 \ ORDER BY f_default_mark DESC, f_id LIMIT 1"; @@ -188,7 +188,7 @@ fn resolve_connector_id_strict(explicit: Option, local: &LocalIdentity) /// /// 先 `listBillingForConnector(cid)`(**不带 keyword**),在 `data.list` 里找 id 匹配 ⇒ 不匹配 ⇒ 拒。 /// 🔴 任何异常(TDS 不可达 / 拒 / 形状不符)⇒ **false**(fail-closed)。 -async fn owns_ledger(state: &AppState, connector_id: &str, ledger_id: &str) -> bool { +async fn owns_ledger(state: &TdcState, connector_id: &str, ledger_id: &str) -> bool { let env = match state .tds .list_billing_for_connector(connector_id, None) @@ -282,7 +282,7 @@ fn unreachable_msg(upstream_msg: &str, err: &str) -> String { /// /// ⚠️ 上游 standalone 分支**不翻页**(`internalCatalog` 无分页参数)⇒ `currentPage`/`pageSize` 忽略。 async fn service_catalog_list( - State(state): State, + State(state): State, q: RawQuery, _p: Option>, ) -> Response { @@ -305,7 +305,7 @@ async fn service_catalog_list( /// `POST /api/ssw/tdc/ServiceCatalog/Buy`(上游 `buy` 的 standalone 分支)。 async fn service_catalog_buy( - State(state): State, + State(state): State, _p: Option>, body: OptionalJsonBody, ) -> Response { @@ -321,7 +321,7 @@ async fn service_catalog_buy( /// `POST /api/ssw/tdc/ServiceCatalog/BuyBatch`(上游 `buyBatch`)。 async fn service_catalog_buy_batch( - State(state): State, + State(state): State, _p: Option>, body: OptionalJsonBody, ) -> Response { @@ -340,7 +340,7 @@ async fn service_catalog_buy_batch( /// 买方连接器自动带出(照抄上游 `buy` / `buyBatch`)。 /// /// 上游口径:**body 里没有 `buyerConnectorId`**(null 或空白)⇒ 用本端固定身份补上。 -async fn fill_buyer_connector_id(state: &AppState, payload: &mut Value) { +async fn fill_buyer_connector_id(state: &TdcState, payload: &mut Value) { let existing = body_text(payload, "buyerConnectorId"); if existing.map(|s| !is_blank(&s)).unwrap_or(false) { return; @@ -359,7 +359,7 @@ async fn fill_buyer_connector_id(state: &AppState, payload: &mut Value) { /// `GET /api/ssw/tdc/Billing/List?connectorId=&keyword=`(上游 `list`)。 async fn billing_list( - State(state): State, + State(state): State, q: RawQuery, _p: Option>, ) -> Response { @@ -390,7 +390,7 @@ async fn billing_list( /// `PUT /api/ssw/tdc/Billing/{id}/Dispute`(上游 `dispute`,**宽松**身份口径)。 async fn billing_dispute( - State(state): State, + State(state): State, Path(id): Path, _p: Option>, body: OptionalJsonBody, @@ -417,7 +417,7 @@ async fn billing_dispute( /// `PUT /api/ssw/tdc/Billing/{id}/Confirm`(上游 `confirm`,**严格**身份口径)。 async fn billing_confirm( - State(state): State, + State(state): State, Path(id): Path, _p: Option>, body: OptionalJsonBody, @@ -446,7 +446,7 @@ async fn billing_confirm( /// `PUT /api/ssw/tdc/Billing/{id}/Settle`(上游 `settle`,**严格**身份口径)。 async fn billing_settle( - State(state): State, + State(state): State, Path(id): Path, _p: Option>, body: OptionalJsonBody, @@ -475,7 +475,7 @@ async fn billing_settle( /// `PUT /api/ssw/tdc/Billing/{id}/Receipt`(上游 `receipt`,**宽松**身份口径)。 async fn billing_receipt( - State(state): State, + State(state): State, Path(id): Path, _p: Option>, body: OptionalJsonBody, @@ -502,7 +502,7 @@ async fn billing_receipt( /// `GET /api/ssw/tdc/Billing/{id}/Voucher`(上游 `voucher`)。 async fn billing_voucher( - State(state): State, + State(state): State, Path(id): Path, q: RawQuery, _p: Option>, @@ -539,7 +539,7 @@ async fn billing_voucher( /// /// 🔴 **本地表**(`tdc_api_consume_log`),**不发任何出向请求**。 async fn billing_local_compare( - State(state): State, + State(state): State, q: RawQuery, _p: Option>, ) -> Response { diff --git a/src/tdc/mod.rs b/src/tdc/mod.rs index 514d29e..540fc01 100644 --- a/src/tdc/mod.rs +++ b/src/tdc/mod.rs @@ -9,6 +9,7 @@ //! | `support/` | `ssw.tdc.support` | 公共放行清单 / 管理员闸门 / 内部令牌等 | //! | `util/` | `ssw.tdc.util` | **业务**工具(业务编码生成器 `code.rs`) | //! | `client/` | `ssw.tdc.client` | TDS 出向客户端 | +//! | `state.rs` | —(上游无对应) | **业务**状态 `TdcState`(引导身份 / 账号库 / TDS 客户端 / 业务配置;v3 spec §2.3.1 C9) | //! | `config.rs` `constant.rs` | `ssw.tdc.config` / `ssw.tdc.constant` | **业务**配置与常量(v3 spec §2.3.1 C8) | //! | `policy/` `engine/` `schedule/` `notify/` `heartbeat/` `sso/` | 同名包 | **占位**,后续批 | //! @@ -27,6 +28,7 @@ pub mod notify; pub mod policy; pub mod schedule; pub mod service; +pub mod state; pub mod sso; pub mod support; pub mod util; diff --git a/src/tdc/service/crud.rs b/src/tdc/service/crud.rs index c435e7f..027a760 100644 --- a/src/tdc/service/crud.rs +++ b/src/tdc/service/crud.rs @@ -23,7 +23,7 @@ use crate::platform::auth::{require_menu_permission, Principal}; use crate::platform::db::{query_json_params, query_scalar_text, ALIVE}; use crate::platform::envelope::{ActionResult, Pagination, CODE_SERVER_ERROR}; use crate::platform::ids::next_id; -use crate::platform::state::AppState; +use crate::tdc::state::TdcState; use crate::tdc::entity::{self, CodeSpec, TableSpec}; use crate::tdc::mapper::{ bind_refs, body_to_columns, build_where, cast_param, count_matching, row_to_json, @@ -37,7 +37,7 @@ use crate::tdc::util::code::{day_prefix_at, format_code_at, CodeStyle}; /// ⇒ 是**操作人 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 { +pub fn operator(state: &TdcState, principal: Option<&Principal>) -> String { match principal { Some(Principal::Internal { operator: Some(op) }) => op.clone(), Some(Principal::Session { identity_id, .. }) => identity_id.clone(), @@ -134,7 +134,7 @@ fn body_text(body: &Value, key: &str) -> Option { /// (`ProductServiceImpl:168` / `ResourceServiceImpl:135` 都是裸 `count(likeRight)`) /// ⇒ 由 `CodeSpec::baseline_alive` 表达。 async fn code_baseline( - state: &AppState, + state: &TdcState, spec: &TableSpec, code: &CodeSpec, now: DateTime, @@ -164,7 +164,7 @@ async fn code_baseline( /// - `DayTail6`(`BizCodeUtil`):无序号,每次**重掷**随机尾。 /// - `retries` 次全冲突 ⇒ **业务失败**(`code=400`),文案取该实体的 `fail_msg`(**上游逐字**)。 async fn generate_code( - state: &AppState, + state: &TdcState, spec: &TableSpec, code: &CodeSpec, now: DateTime, @@ -184,7 +184,7 @@ async fn generate_code( /// 🔴 **重试次数与失败文案都读 `CodeSpec`**(上游逐实体不同:Product/Resource 5 次、 /// DataInterface/Datasource 3 次;文案也各不相同)—— 不再硬编码。 pub async fn generate_code_with( - state: &AppState, + state: &TdcState, spec: &TableSpec, code: &CodeSpec, mut make: F, @@ -205,7 +205,7 @@ where /// 分页列表:`GET /api/ssw/tdc/{Entity}`。 pub async fn list( - state: &AppState, + state: &TdcState, spec: &'static TableSpec, params: &HashMap, principal: Option<&Principal>, @@ -270,7 +270,7 @@ pub async fn list( /// 全量列表:`GET /api/ssw/tdc/{Entity}/All`(裸数组,≤1000)。 pub async fn all( - state: &AppState, + state: &TdcState, spec: &'static TableSpec, params: &HashMap, principal: Option<&Principal>, @@ -305,7 +305,7 @@ pub async fn all( /// 详情:`GET /api/ssw/tdc/{Entity}/{id}`。 pub async fn detail( - state: &AppState, + state: &TdcState, spec: &'static TableSpec, id: &str, principal: Option<&Principal>, @@ -333,7 +333,7 @@ pub async fn detail( /// 取一行(带 `ALIVE`)用于「改前取当前值」与「删前校验」。 async fn fetch_alive( - state: &AppState, + state: &TdcState, spec: &TableSpec, id: &str, ) -> Result, pglite::Error> { @@ -369,7 +369,7 @@ async fn fetch_alive( /// `identity::capabilities()`、本函数、以及 create/update/delete 三处调用点。 /// - 🔴 **B4 只删假权限层,**不**把权限收紧成 fail-closed**(D6 的原话)。 pub async fn require_write_permission( - state: &AppState, + state: &TdcState, spec: &'static TableSpec, principal: Option<&Principal>, ) -> Result<(), Response> { @@ -410,7 +410,7 @@ pub async fn require_write_permission( /// 新增:`POST /api/ssw/tdc/{Entity}`。 pub async fn create( - state: &AppState, + state: &TdcState, spec: &'static TableSpec, body: &Value, principal: Option<&Principal>, @@ -551,7 +551,7 @@ pub async fn create( /// 修改:`PUT /api/ssw/tdc/{Entity}/{id}`。 pub async fn update( - state: &AppState, + state: &TdcState, spec: &'static TableSpec, id: &str, body: &Value, @@ -649,7 +649,7 @@ pub async fn update( /// 逻辑删除:`DELETE /api/ssw/tdc/{Entity}/{id}`。 pub async fn delete( - state: &AppState, + state: &TdcState, spec: &'static TableSpec, id: &str, principal: Option<&Principal>, @@ -705,7 +705,7 @@ pub async fn delete( /// /// 与 [`detail`] 的差别**只有**「多挂子表」;无子表的实体完全等价于 `detail()`。 pub async fn detail_aggregate( - state: &AppState, + state: &TdcState, spec: &'static TableSpec, id: &str, principal: Option<&Principal>, @@ -760,8 +760,9 @@ mod tests { use super::*; use crate::platform::config::Config; use crate::platform::session::SessionStore; - use crate::platform::state::BootstrapIdentity; + use crate::platform::state::AppState; use crate::tdc::entity; + use crate::tdc::state::BootstrapIdentity; use pglite::PGlite; use std::sync::Arc; @@ -821,10 +822,9 @@ mod tests { .await .expect("建表失败"); let config = Config::from_env(std::env::current_dir().unwrap_or_default()); - let state = AppState::new( - config, - db.clone(), - Arc::new(SessionStore::new()), + let state = TdcState::new( + AppState::new(config, db.clone(), Arc::new(SessionStore::new())), + crate::tdc::config::TdcConfig::default(), BootstrapIdentity::default(), ); diff --git a/src/tdc/service/identity.rs b/src/tdc/service/identity.rs index dd2d024..9ce16f5 100644 --- a/src/tdc/service/identity.rs +++ b/src/tdc/service/identity.rs @@ -18,7 +18,8 @@ use crate::platform::auth::Principal; use crate::platform::db::query_json_params; use crate::platform::envelope::{ActionResult, CODE_SERVER_ERROR}; use crate::platform::ids::next_id; -use crate::platform::state::{AppState, BootstrapIdentity}; +use crate::platform::state::AppState; +use crate::tdc::state::{BootstrapIdentity, TdcState}; use crate::tdc::config::TdcConfig; /// 冻结态(登录拒)。 @@ -82,6 +83,9 @@ pub fn space_view(id: &str, name: &str, space_code: &str) -> Value { /// 🔴 **业务配置走显式入参**(v3 spec §2.3.1 C8):身份码 / 身份名 / 身份密钥是 /// **业务口径**,不在平台层的 `Config` 里 ⇒ 由装配层把 `TdcConfig` 递进来。 /// +/// 🔴 **只吃平台那一半**(v3 spec §2.3.1 C9):本函数在**装配期**跑(那时业务状态 +/// `TdcState` 还没组装出来)⇒ 入参是 `&AppState`(db + 锁)。 +/// /// 🔴 **检查与插入在同一把 `db_lock` 里**(pglite 单 backend;且「查不到 ⇒ 插入」 /// 必须是原子的,否则并发启动会建出两条身份)。 pub async fn bootstrap_identity(state: &AppState, tdc_config: &TdcConfig) -> BootstrapIdentity { @@ -200,7 +204,7 @@ fn random_bytes() -> [u8; 32] { /// ③ 兜底:库里唯一存活身份(`f_default_mark` 优先)。 /// /// ③ 是为「`AppState` 尚未跑过引导」的路径兜底(例如测试里直接 `AppState::new`)。 -async fn current_identity_id(state: &AppState, p: Option<&Principal>) -> Option { +async fn current_identity_id(state: &TdcState, p: Option<&Principal>) -> Option { if let Some(Principal::Session { identity_id, .. }) = p { if !identity_id.trim().is_empty() { return Some(identity_id.clone()); @@ -225,7 +229,7 @@ async fn current_identity_id(state: &AppState, p: Option<&Principal>) -> Option< } /// 登录:`POST /api/ssw/tdc/Auth/Login`(在白名单里,免内部令牌)。 -pub async fn login(State(state): State, payload: Option>) -> Response { +pub async fn login(State(state): State, payload: Option>) -> Response { let body = payload.map(|Json(v)| v).unwrap_or(Value::Null); let identity_code = match str_field(&body, "identityCode") { @@ -315,7 +319,7 @@ pub async fn login(State(state): State, payload: Option>) /// (塞空串或编造 `http://127.0.0.1:{port}` 都会**预填进身份表单** ⇒ 错的预填比空字段危险)。 /// 真实闭环:用户在身份表单里填了 `endpoint` / `tdsEndpoint` /// ⇒ 落进 `tdc_identity.f_endpoint` / `f_tds_endpoint` ⇒ 之后 `me` 就带出来 ⇒ 编辑时自动回填 ✓ -pub async fn me(State(state): State, p: Option>) -> Response { +pub async fn me(State(state): State, p: Option>) -> Response { let (access_allowed, account) = match p.as_ref().map(|e| &e.0) { Some(Principal::Account { account, .. }) => (true, account.clone()), Some(Principal::Session { identity_code, .. }) => (true, identity_code.clone()), @@ -391,7 +395,7 @@ pub fn me_payload(row: &Value, access_allowed: bool, account: &str) -> Value { /// ⇒ 本地返回本连接器绑定空间,好过 404。 /// /// 形状:裸数组,元素是 `space_view`(`{id, name, spaceCode}`)⇒ 与上游一致。 -pub async fn spaces(State(state): State) -> Response { +pub async fn spaces(State(state): State) -> Response { let identity_id = match current_identity_id(&state, None).await { Some(id) => id, None => return ActionResult::ok(Vec::::new()).into_response(), @@ -452,7 +456,7 @@ pub async fn sso_config() -> Response { /// - `None` ⇒ **解析不出**(列为空 / 行不存在)⇒ 调用方按 **fail-open** 放行 /// (对齐上游 `SswPermissionGuard` 的「菜单未映射即放行」口径)。 /// - `Some(set)` ⇒ 解析成功 ⇒ 写操作必须命中该实体的权限键(或通配符 `*` / `all`)。 -pub async fn capabilities(state: &AppState, identity_code: &str) -> Option> { +pub async fn capabilities(state: &TdcState, identity_code: &str) -> Option> { let sql = "SELECT f_capability FROM tdc_identity \ WHERE f_identity_code = CAST($1 AS character varying) \ AND (f_delete_mark IS NULL OR f_delete_mark = 0) LIMIT 1"; diff --git a/src/tdc/state.rs b/src/tdc/state.rs new file mode 100644 index 0000000..078c5e1 --- /dev/null +++ b/src/tdc/state.rs @@ -0,0 +1,153 @@ +//! 业务层状态(**业务那一半**):引导身份 + 本地账号库 + TDS 出向客户端 + 业务配置。 +//! +//! 🔴 **为什么要拆**(v3 spec §2.3.1 C9):`platform::state::AppState` 之前同时装着 +//! 「平台运行态」与「业务态」⇒ 平台层被迫 `import` 业务模块 +//! (`crate::tdc::service::account::AccountStore` / `crate::tdc::client::tds::TdsClient`) +//! ⇒ **平台 → 业务的反向依赖**,边界尺子(CP1)迟早会红。 +//! +//! 拆成两半后: +//! +//! | 层 | struct | 内容 | +//! |---|---|---| +//! | 平台 | `platform::state::AppState` | 配置 / db / db_lock / sessions | +//! | 业务 | `tdc::state::TdcState` | `platform` + 业务配置 + 引导身份 + 账号库 + TDS 客户端 | +//! +//! ## 业务层怎么拿到平台那一半 +//! +//! - **字段访问**:`TdcState` 实现 `Deref` ⇒ `state.db` / `state.db_lock` +//! / `state.sessions` / `state.config` 直接可用(与拆之前写法一致)。 +//! - **只写平台的端点**:`impl FromRef for AppState` ⇒ axum 里可以写 +//! `State`(axum 会从 `TdcState` 里抽出平台那一半),平台端点因此**不需要** +//! 认识业务类型。 + +use std::ops::Deref; +use std::sync::Arc; + +use axum::extract::FromRef; + +use crate::platform::state::AppState; +use crate::tdc::client::tds::TdsClient; +use crate::tdc::config::TdcConfig; +use crate::tdc::service::account::AccountStore; + +/// 首次启动引导出来的本地身份。 +/// +/// 🔴 它是**业务态**(`tdc_identity` 的一行)⇒ 归业务层,不留在平台层。 +#[derive(Debug, Clone, Default)] +pub struct BootstrapIdentity { + pub identity_id: String, + pub identity_code: String, + /// 仅当本次启动**新建**了身份时才有值 —— 用于把密钥打印一次。 + pub issued_secret: Option, +} + +/// 业务层状态(平台那一半 + 业务那一半)。 +#[derive(Clone)] +pub struct TdcState { + /// 平台状态(配置 / db / db_lock / sessions)。 + pub platform: AppState, + /// 业务配置(身份与引导;v3 spec §2.3.1 C8)。 + pub tdc_config: Arc, + /// 首次启动引导出来的本地身份。 + pub bootstrap: Arc, + /// 本连接器的本地账号库(默认是**内存空库** ⇒ 早期任务与单测不必改)。 + pub accounts: Arc, + /// TDS 出向客户端(≡ 上游 `TdsReportClient` 的 internal 通道)。 + /// + /// 🔴 未配 `SSW_TDS_BASE_URL` ⇒ **NOOP 模式**(出向请求一律回业务失败, + /// 不发任何网络请求)⇒ 本地单机模式不会因为「没配 TDS」而 500。 + pub tds: Arc, +} + +impl TdcState { + /// 造一个业务状态:平台部分 + 业务配置 + 引导身份。 + /// + /// 🔴 账号库默认**内存空库**、TDS 客户端按平台配置构造(`None` ⇒ NOOP)—— + /// 与拆分前 `AppState::new` 的行为**逐字一致**。 + pub fn new(platform: AppState, tdc_config: TdcConfig, bootstrap: BootstrapIdentity) -> Self { + let tds = Arc::new(TdsClient::new( + platform.config.tds_base_url.clone(), + platform.config.tds_internal_token.clone(), + )); + Self { + platform, + tdc_config: Arc::new(tdc_config), + bootstrap: Arc::new(bootstrap), + accounts: Arc::new(AccountStore::empty()), + tds, + } + } + + /// 换掉引导身份(**其余字段原样保留**,特别是 `db_lock`)。 + /// + /// 用途:启动时先用 `BootstrapIdentity::default()` 造状态、跑引导,再把结果换回来 —— + /// 这样全程只有**一个**状态(也就只有一把 `db_lock`)。 + pub fn with_bootstrap(self, bootstrap: BootstrapIdentity) -> Self { + Self { + bootstrap: Arc::new(bootstrap), + ..self + } + } + + /// 挂上本地账号库(**其余字段原样保留**,特别是 `db_lock`)。 + /// + /// 用途:启动时先造状态、跑身份引导,再把账号库换上去 —— + /// 这样全程只有**一个**状态(也就只有一把 `db_lock`)。 + pub fn with_accounts(self, accounts: Arc) -> Self { + Self { accounts, ..self } + } + + /// 换掉 TDS 出向客户端(**其余字段原样保留**,特别是 `db_lock`)。 + /// + /// 用途:集成测试里把客户端指向**假 TDS**(起一个本地 axum server)。 + pub fn with_tds(self, tds: TdsClient) -> Self { + Self { + tds: Arc::new(tds), + ..self + } + } +} + +/// 🔴 业务层把平台那一半「摊开」⇒ `state.db` / `state.db_lock` / `state.sessions` +/// / `state.config` 的写法与拆分前**完全一致**(少写一层 `.platform.`)。 +impl Deref for TdcState { + type Target = AppState; + + fn deref(&self) -> &Self::Target { + &self.platform + } +} + +/// 🔴 axum 的状态抽取:`Router` 里的端点可以写 `State` +/// (平台端点因此**不需要**认识任何业务类型)。 +impl FromRef for AppState { + fn from_ref(state: &TdcState) -> Self { + state.platform.clone() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// 🔴 未引导时不得有 id / 密钥。 + #[test] + fn bootstrap_identity_defaults_to_empty_and_no_secret() { + let b = BootstrapIdentity::default(); + assert!(b.identity_id.is_empty()); + assert!(b.identity_code.is_empty()); + assert!(b.issued_secret.is_none(), "未引导时不得有密钥"); + } + + /// 🔴 业务层**不得**反向依赖平台层的内部实现细节:`TdcState` 的平台那一半 + /// 必须能被 `FromRef` 原样抽出来(平台端点写 `State` 即可)。 + /// + /// ⚠️ 这条断言**不需要真库** ⇒ 只比对「抽出来的另一半与原的一半同源」。 + #[test] + fn the_platform_half_is_reachable_through_deref() { + // `Deref` 的目标类型就是平台那一半 ⇒ 类型层面已经保证字段访问可用。 + fn takes_platform(_: &AppState) {} + // 编译期即证明 `&TdcState` 能当作 `&AppState` 用(deref 强制转换)。 + let _f: fn(&TdcState) = |s| takes_platform(s); + } +} diff --git a/tests/account_api.rs b/tests/account_api.rs index 540e57d..1403758 100644 --- a/tests/account_api.rs +++ b/tests/account_api.rs @@ -19,7 +19,9 @@ use tdc_connector::platform::config::Config; use tdc_connector::tdc::controller::build_router; use tdc_connector::tdc::support::public_paths; use tdc_connector::platform::session::SessionStore; -use tdc_connector::platform::state::{AppState, BootstrapIdentity}; +use tdc_connector::platform::state::AppState; +use tdc_connector::tdc::config::TdcConfig; +use tdc_connector::tdc::state::{BootstrapIdentity, TdcState}; use tokio::sync::OnceCell; use tower::ServiceExt; @@ -73,10 +75,9 @@ async fn build(tag: &str) -> (Router, Arc) { .await .expect("插入测试身份失败"); } - let state = AppState::new( - config.clone(), - db, - sessions.clone(), + let state = TdcState::new( + AppState::new(config.clone(), db, sessions.clone()), + TdcConfig::default(), BootstrapIdentity { identity_id, identity_code, diff --git a/tests/api_smoke.rs b/tests/api_smoke.rs index 65c0e67..6707fce 100644 --- a/tests/api_smoke.rs +++ b/tests/api_smoke.rs @@ -5,6 +5,7 @@ use std::sync::Arc; use axum::body::Body; +use axum::extract::FromRef; use axum::http::{Request, StatusCode}; use axum::Router; use http_body_util::BodyExt; @@ -16,7 +17,9 @@ use tdc_connector::tdc::controller::build_router; use tdc_connector::tdc::support::public_paths; use tdc_connector::platform::mw::json_method_not_allowed; use tdc_connector::platform::session::SessionStore; -use tdc_connector::platform::state::{AppState, BootstrapIdentity}; +use tdc_connector::platform::state::AppState; +use tdc_connector::tdc::config::TdcConfig; +use tdc_connector::tdc::state::{BootstrapIdentity, TdcState}; use tokio::sync::OnceCell; use tower::ServiceExt; @@ -35,15 +38,14 @@ async fn shared_db() -> Arc { } /// 构造一个带鉴权中间件的 router,并返回当前生效的内部令牌与状态。 -async fn build() -> (Router, String, AppState) { +async fn build() -> (Router, String, TdcState) { let db = shared_db().await; let config = Config::from_env(std::env::current_dir().unwrap()); let sessions = Arc::new(SessionStore::new()); let token = config.internal_token.clone(); - let state = AppState::new( - config.clone(), - db, - sessions.clone(), + let state = TdcState::new( + AppState::new(config.clone(), db, sessions.clone()), + TdcConfig::default(), BootstrapIdentity { identity_id: "TEST-OP".to_string(), identity_code: "TEST-CONNECTOR".to_string(), @@ -627,3 +629,23 @@ async fn identity_secret_key_is_never_exposed_over_http() { "客户端送的 secretKey 不应被写库" ); } + +/// 🔴 **状态分两半**(v3 spec §2.3.1 C9):业务状态 `TdcState` 能被 `FromRef` +/// 原样抽出**平台那一半** ⇒ 只写平台的端点可以写 `State`, +/// 而平台层**不需要**认识任何业务类型。 +#[tokio::test] +async fn the_business_state_yields_the_platform_half() { + let (_app, _token, state) = build().await; + + let platform = tdc_connector::platform::state::AppState::from_ref(&state); + assert!( + Arc::ptr_eq(&platform.db_lock, &state.db_lock), + "抽出来的平台状态必须共用同一把 db_lock" + ); + assert!( + Arc::ptr_eq(&platform.sessions, &state.sessions), + "抽出来的平台状态必须共用同一个会话存储" + ); + // 业务那一半只挂在 `TdcState` 上(平台状态里没有 accounts / tds / bootstrap)。 + let _business_only = (&state.accounts, &state.tds, &state.bootstrap); +} diff --git a/tests/auth_flow.rs b/tests/auth_flow.rs index ca6e0c8..1c44543 100644 --- a/tests/auth_flow.rs +++ b/tests/auth_flow.rs @@ -17,7 +17,8 @@ use tdc_connector::tdc::config::TdcConfig; use tdc_connector::tdc::controller::build_router; use tdc_connector::tdc::support::public_paths; use tdc_connector::platform::session::SessionStore; -use tdc_connector::platform::state::{AppState, BootstrapIdentity}; +use tdc_connector::platform::state::AppState; +use tdc_connector::tdc::state::{BootstrapIdentity, TdcState}; use tokio::sync::{Mutex, OnceCell}; static DB: OnceCell> = OnceCell::const_new(); @@ -36,15 +37,19 @@ async fn shared_db() -> Arc { .clone() } -async fn test_state() -> AppState { +async fn test_state() -> TdcState { test_state_with(Arc::new(SessionStore::new())).await } /// 与 `main.rs` 一致:**登录签发的会话与鉴权中间件必须共用同一个 store**。 -async fn test_state_with(sessions: Arc) -> AppState { +async fn test_state_with(sessions: Arc) -> TdcState { let db = shared_db().await; let config = Config::from_env(std::env::current_dir().unwrap()); - AppState::new(config, db, sessions, BootstrapIdentity::default()) + TdcState::new( + AppState::new(config, db, sessions), + TdcConfig::default(), + BootstrapIdentity::default(), + ) } /// 🔴 业务配置(身份与引导)**不在平台 Config 里**(v3 spec §2.3.1 C8)⇒ 单独造一份。 @@ -69,21 +74,19 @@ async fn two_app_states_on_the_same_db_share_one_db_lock() { let sessions = Arc::new(SessionStore::new()); let config = Config::from_env(std::env::current_dir().unwrap()); - let s1 = AppState::new( - config.clone(), - db.clone(), - sessions.clone(), + let s1 = TdcState::new( + AppState::new(config.clone(), db.clone(), sessions.clone()), + TdcConfig::default(), BootstrapIdentity::default(), ); - let s2 = AppState::new( - config.clone(), - db.clone(), - sessions.clone(), + let s2 = TdcState::new( + AppState::new(config.clone(), db.clone(), sessions.clone()), + TdcConfig::default(), BootstrapIdentity::default(), ); assert!( Arc::ptr_eq(&s1.db_lock, &s2.db_lock), - "同一个 PGlite 上的所有 AppState 必须共享同一把 db_lock" + "同一个 PGlite 上的所有状态必须共享同一把 db_lock" ); // `with_bootstrap` 换引导身份时**不得**换掉锁 let s3 = s1.with_bootstrap(BootstrapIdentity { diff --git a/tests/bootstrap_fail.rs b/tests/bootstrap_fail.rs index c6f2590..74452ae 100644 --- a/tests/bootstrap_fail.rs +++ b/tests/bootstrap_fail.rs @@ -10,7 +10,8 @@ use tdc_connector::platform::config::Config; use tdc_connector::tdc::config::TdcConfig; use tdc_connector::tdc::service::identity::bootstrap_identity; use tdc_connector::platform::session::SessionStore; -use tdc_connector::platform::state::{AppState, BootstrapIdentity}; +use tdc_connector::platform::state::AppState; +use tdc_connector::tdc::state::{BootstrapIdentity, TdcState}; #[tokio::test] async fn bootstrap_insert_failure_yields_no_secret() { @@ -23,10 +24,9 @@ async fn bootstrap_insert_failure_yields_no_secret() { db.exec("DROP TABLE tdc_identity").await.expect("删表失败"); let config = Config::from_env(std::env::current_dir().unwrap()); - let state = AppState::new( - config, - db, - Arc::new(SessionStore::new()), + let state = TdcState::new( + AppState::new(config, db, Arc::new(SessionStore::new())), + TdcConfig::default(), BootstrapIdentity::default(), ); diff --git a/tests/crud_engine.rs b/tests/crud_engine.rs index ecf0af1..f0a7396 100644 --- a/tests/crud_engine.rs +++ b/tests/crud_engine.rs @@ -12,7 +12,9 @@ use tdc_connector::platform::config::Config; use tdc_connector::tdc::service::crud; use tdc_connector::tdc::entity; use tdc_connector::platform::session::SessionStore; -use tdc_connector::platform::state::{AppState, BootstrapIdentity}; +use tdc_connector::platform::state::AppState; +use tdc_connector::tdc::config::TdcConfig; +use tdc_connector::tdc::state::{BootstrapIdentity, TdcState}; use tokio::sync::OnceCell; static DB: OnceCell> = OnceCell::const_new(); @@ -26,7 +28,7 @@ static DB: OnceCell> = OnceCell::const_new(); static PRODUCT_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); /// 数「当日同前缀」的行数(**含软删行** —— 与 Product/Resource 的基线口径一致:不带 `ALIVE`)。 -async fn count_today_products(state: &tdc_connector::platform::state::AppState, pattern: &str) -> u64 { +async fn count_today_products(state: &tdc_connector::tdc::state::TdcState, 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; @@ -49,13 +51,12 @@ async fn shared_db() -> Arc { .clone() } -async fn test_state() -> AppState { +async fn test_state() -> TdcState { let db = shared_db().await; let config = Config::from_env(std::env::current_dir().unwrap()); - AppState::new( - config, - db, - Arc::new(SessionStore::new()), + TdcState::new( + AppState::new(config, db, Arc::new(SessionStore::new())), + TdcConfig::default(), BootstrapIdentity { identity_id: "TEST-OP".to_string(), identity_code: "TEST-CONNECTOR".to_string(), @@ -346,7 +347,7 @@ async fn resource_detail_aggregate_carries_field_rules_and_mask_rules() { /// /// 返回 `(新记录 id, 字段值)` —— id 是 `create` 响应 `data` 里的**新记录 id**。 async fn create_and_read( - state: &tdc_connector::platform::state::AppState, + state: &tdc_connector::tdc::state::TdcState, spec: &'static tdc_connector::tdc::entity::TableSpec, body: &Value, field: &str, diff --git a/tests/permission_gate.rs b/tests/permission_gate.rs index bb5c873..9c63d71 100644 --- a/tests/permission_gate.rs +++ b/tests/permission_gate.rs @@ -12,7 +12,9 @@ use tdc_connector::tdc::service::crud::require_write_permission; use tdc_connector::tdc::service::identity; use tdc_connector::tdc::entity; use tdc_connector::platform::session::SessionStore; -use tdc_connector::platform::state::{AppState, BootstrapIdentity}; +use tdc_connector::platform::state::AppState; +use tdc_connector::tdc::config::TdcConfig; +use tdc_connector::tdc::state::{BootstrapIdentity, TdcState}; use tokio::sync::OnceCell; static DB: OnceCell> = OnceCell::const_new(); @@ -29,13 +31,12 @@ async fn shared_db() -> Arc { .clone() } -async fn test_state() -> AppState { +async fn test_state() -> TdcState { let db = shared_db().await; let config = Config::from_env(std::env::current_dir().unwrap()); - AppState::new( - config, - db, - Arc::new(SessionStore::new()), + TdcState::new( + AppState::new(config, db, Arc::new(SessionStore::new())), + TdcConfig::default(), BootstrapIdentity::default(), ) } diff --git a/tests/tds_biz.rs b/tests/tds_biz.rs index 34b0503..db34571 100644 --- a/tests/tds_biz.rs +++ b/tests/tds_biz.rs @@ -26,7 +26,9 @@ use tdc_connector::tdc::controller::build_router; use tdc_connector::tdc::support::public_paths; use tdc_connector::platform::mw::json_method_not_allowed; use tdc_connector::platform::session::SessionStore; -use tdc_connector::platform::state::{AppState, BootstrapIdentity}; +use tdc_connector::platform::state::AppState; +use tdc_connector::tdc::config::TdcConfig; +use tdc_connector::tdc::state::{BootstrapIdentity, TdcState}; use tdc_connector::tdc::client::tds::TdsClient; use tokio::sync::OnceCell; use tower::ServiceExt; @@ -176,10 +178,9 @@ async fn build(base_url: Option) -> (Router, String) { let config = Config::from_env(std::env::current_dir().unwrap()); let sessions = Arc::new(SessionStore::new()); let token = config.internal_token.clone(); - let state = AppState::new( - config.clone(), - db, - sessions.clone(), + let state = TdcState::new( + AppState::new(config.clone(), db, sessions.clone()), + TdcConfig::default(), BootstrapIdentity { identity_id: "ID-TEST-1".to_string(), identity_code: "TEST-CONNECTOR".to_string(),