feat(p6): 平台改为预编译 rlib 接入,依赖全部来自包内闭包
- 新增 scripts/fetch-platform.sh:读 .sspf-version 解包 vendor/ + 生成 .cargo/config.toml(rustflags + rustdocflags),只校工具链 channel - Cargo.toml 的 [dependencies]/[dev-dependencies] 清空:17 个 crate 全部 --extern 自平台闭包 - release profile lto 由 thin 改 false(平台 rlib bitcode-free,开 LTO 找不到 __bitcode) - tower-http 不在闭包 ⇒ 自研 platform::static_files(ServeDir 等价,含 Range 206)与 platform::cors(permissive 等价) - reqwest 与 extern tokio 双 runtime 必 panic(no reactor running)⇒ 自研 platform::http(HTTP/1.1 明文) - tests/auth_flow 的 reqwest 调用改用 lib 客户端;tds_biz 的头白名单补 connection - 新增尺子 check-platform-package.sh:依赖单一来源 + 真编一次证明平台闭包零重编 - 验收:cargo test 306 passed / 七把尺子 + 新尺子全绿;dev 构建 2.5s 只编本仓
This commit is contained in:
1 parent
d875ed9964
commit
400d883e1a
20 files changed
+1504
-2596
No files matched your search
@@ -14,3 +14,8 @@
|
||||
# Python 字节码缓存(scripts/ 下的自检脚本会产生)
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# 平台包(预编译 rlib 闭包,~450MB):用 scripts/fetch-platform.sh 取,不进版本库
|
||||
/vendor/
|
||||
# 由 fetch-platform.sh 生成,含本机绝对路径与每版本会变的 rlib hash
|
||||
/.cargo/config.toml
|
||||
@@ -0,0 +1 @@
|
||||
0.5.0
|
||||
@@ -0,0 +1,75 @@
|
||||
# 2026-11-05
|
||||
|
||||
## P6:平台改为预编译 rlib 发布,业务仓接入(依赖模型整体换掉)
|
||||
|
||||
### 平台侧交付(`ssw-platform` HEAD `6ee0cd1`,方案 C)
|
||||
|
||||
`scripts/release.sh` 每版本出 `dist/sspf-vX.Y.Z.tar.gz`(159MB),包内:
|
||||
|
||||
| 路径 | 内容 |
|
||||
|---|---|
|
||||
| `lib/` | **预编译闭包 422 个文件**:`.rlib` + `.rmeta` + proc-macro `.dylib` + 原生 `.a`;**bitcode-free**(出包时关 `lto`/`embed-bitcode`,否则 macOS ld 的 libLTO21 解析不了 LLVM22 bitcode);ABI 锁 rustc **1.95.0** |
|
||||
| `bin/sspf-admin` | 预编译平台二进制 |
|
||||
| `crates/*` / `src/backend` / `Cargo.toml` / `Cargo.lock` | 源码回退(path 依赖,可改平台,但要重编 17 个 crate) |
|
||||
|
||||
消费方不把 `sspf` 写成 cargo 依赖,用 `.cargo/config.toml` 的 `--extern` + `-L dependency` 直接喂 rustc。
|
||||
|
||||
### 三条**实测**结论(不是文档推演)
|
||||
|
||||
1. **Cargo.toml 里声明 `axum` ⇒ 必炸**。cargo 另编一份 axum,业务 `Router` 与 `sspf::Finish.router`
|
||||
是两个实例 ⇒ `E0308 mismatched types`(探针 `/tmp/rlib-a`)。`serde` / `serde_json` / `http` /
|
||||
`bytes` / `tokio` 同理(跨边界类型)。
|
||||
2. **`reqwest` 彻底不能用**。它自带一份 tokio,而 `#[tokio::main]` 用闭包里那份;tokio 的 runtime
|
||||
context 是 crate 实例内 thread-local ⇒ 一调就 panic `there is no reactor running`
|
||||
(探针 `/tmp/rlib-c`,编译能过、运行必崩)⇒ 出向必须自研。
|
||||
3. 平台 README 里「保留你自己代码直用的依赖(axum/tokio/serde)」这句**是错的**(那是
|
||||
`f6c3ff6` 旧版写的,`6ee0cd1` 的 §6.3 才是对的)。已在业务仓文档记录,平台 README 未改。
|
||||
|
||||
### 业务侧落地
|
||||
|
||||
- `scripts/fetch-platform.sh`(新增):读 `.sspf-version` → 解包到 `vendor/sspf-vX.Y.Z/` →
|
||||
解析 `lib/*.d` 里的源码版本号挑对同名 crate(`rand` 有 0.8/0.10、`md5` 有 0.10/0.11 各两份)→
|
||||
生成 `.cargo/config.toml`(**rustflags + rustdocflags 两份**,rustdoc 不吃 rustflags,漏了 doc-test 全红)
|
||||
→ 只校 `rust-toolchain.toml` 的 channel(**不整份覆盖**,否则本仓注释被换成平台的 cdylib 说明)。
|
||||
⚠️ 踩过:`.rlib` 叫 `libfoo-<hash>.rlib`,对应的 `.d` 却叫 `foo-<hash>.d`(无 `lib` 前缀)。
|
||||
- `Cargo.toml`:`[dependencies]` / `[dev-dependencies]` **清空**(17 个 crate 全来自闭包);
|
||||
`lto` 由 `"thin"` 改 **`false`**(rlib bitcode-free)。17 个 extern:sspf / axum / tokio / serde /
|
||||
serde_json / http / bytes / tower / http_body_util / serde_urlencoded / chrono / hex / rand /
|
||||
md5 / aes / ecb / pglite。
|
||||
- `vendor/`(452MB)与 `.cargo/config.toml`(含本机绝对路径 + 每版本变的 hash)**都不进版本库**;
|
||||
`.sspf-version` 与两个脚本进库。
|
||||
|
||||
### 两个自研替身(平台闭包里没有,且与 axum 必须同源 ⇒ 不能单独编)
|
||||
|
||||
| 替换 | 新模块 | 语义对位 |
|
||||
|---|---|---|
|
||||
| `tower_http::services::ServeDir` | `src/platform/static_files.rs` | GET/HEAD、`.`/`..` 归一化、目录追加 `index.html`、Content-Type、**Content-Length 必显式设**(DDL 内容级守卫靠它)、`Range` 片段 206 + `Content-Range`、整份 Range 回 **200**、非 GET/HEAD 405 + `Allow` |
|
||||
| `tower_http::cors::CorsLayer::permissive()` | `src/platform/cors.rs` | `allow-origin/methods/headers: *`、预检**短路**(不进业务链,否则无 token 的 OPTIONS 吃 401) |
|
||||
| `reqwest`(TDS 出向) | `src/platform/http.rs` | HTTP/1.1 **明文只支持 http://**(闭包无 TLS,`https` 显式报错不静默降级)、`Connection: close` 一请求一连接、连接超时 + 整次读取超时、Content-Length / chunked / EOF 三种收尾、**不读代理**、错误分档 `ConnectTimeout/ReadTimeout/Connect/Io/Parse/Unsupported` |
|
||||
| `tests/auth_flow.rs` 的 reqwest 调用 | 测试内 `http_call()` | 用 lib 的 `platform::http` |
|
||||
|
||||
🔴 踩坑:`platform::http::HttpClient` 已失 `reqwest` 的 `.json()` / `.text()`,`tds.rs` 的 `send()`
|
||||
改为 `serde_json::to_vec` + 读 `resp.body`;`outbound_read_error_text` 合并进 `outbound_error_text`
|
||||
(按 `ErrorKind` 分「不可达 / 读失败 / 超时」)。
|
||||
|
||||
🔴 踩坑:`static_files::serve` 原来收 `&Request` ⇒ `Body` 不是 `Sync`,`&Request` 跨 `await` 让
|
||||
handler future 变 `!Send` ⇒ `Handler` 约束不满足编译不过。改成先把 method/path/range 取成 owned 值。
|
||||
|
||||
### 验收
|
||||
|
||||
- `cargo test` **306 passed / 0 failed / 1 ignored**(P5 296 + 新增 10:`static_files` 5 条纯函数
|
||||
单测(Range/归一化/MIME)+ `http` 5 条(URL 解析/https 拒绝/状态头/chunked))。
|
||||
- 七把尺子全绿:smoke **80/80**、check-contract **132 条端点一致**、双契约 **18/18**、
|
||||
boundary / entity / upstream / db-access 全过。
|
||||
- 新尺子 `scripts/check-platform-package.sh`(5 组判据):版本与包结构 / config 里每个绝对路径存在 /
|
||||
跨边界 7 个 crate 都 `--extern` / 工具链三方一致 / **touch 源码真编一次,构建输出不得出现
|
||||
`Compiling sspf|axum|tokio|serde…`** ⇒「零重编」端到端可验。
|
||||
- 构建实测:`cargo build` **只编本仓,2.50s**;`cargo build --release` **20.58s**,二进制 39MB。
|
||||
- `check-citations.py` 仍是基线那 32 条失效(全指向上游 Java/TS 文件),无新增。
|
||||
|
||||
### 遗留 / 注意
|
||||
|
||||
- **TDS 出向不再支持 TLS**:闭包无 rustls。现网 TDS 是内网 `http://`,若将来要 https,
|
||||
得让平台把 TLS 栈打进闭包。
|
||||
- 平台 README 的消费方步骤 4 与 `docs/SSPF-PLATFORM-PACKAGE.md` §6.3 自相矛盾,建议平台侧修。
|
||||
- 新克隆/换机的第一步是 `bash scripts/fetch-platform.sh`,否则 `cargo build` 会「一个依赖都没有」。
|
||||
@@ -15,7 +15,7 @@ This file provides guidance to AI coding agents (CodeBuddy / Claude Code / Curso
|
||||
|
||||
| 层 | 技术栈 | 职责 |
|
||||
|---|---|---|
|
||||
| 平台底座 | **`sspf` v0.5.0**(`ssw-platform` 发布的标准平台包,git tag 锁版本) | **单进程 / 单库 / 单端口 / 单锁**:开唯一的 PGlite 实例、建平台 `base_*` 表、提供面 B(JNPF 兼容)全套端点。`Cargo.toml` 里只认这一个依赖 |
|
||||
| 平台底座 | **`sspf` v0.5.0**(`ssw-platform` 发布的**预编译 rlib 包**,`.sspf-version` 锁版本) | **单进程 / 单库 / 单端口 / 单锁**:开唯一的 PGlite 实例、建平台 `base_*` 表、提供面 B(JNPF 兼容)全套端点。**`Cargo.toml` 里没有依赖**——依赖由 `.cargo/config.toml` 的 `--extern` 指向包内 `lib/` |
|
||||
| 后端 | Rust 2021 + axum 0.8 + tokio(**业务层**) | 鉴权 / 会话 / 18 实体 CRUD / 聚合详情 / 账号层 / 静态托管;由 `sspf::Platform` **两阶段装配**(`assemble()` → 引导业务状态 → `finish()`) |
|
||||
| 数据库 | `pglite-rs` 0.2(进程内原生 PostgreSQL,**平台与业务共用同一个实例**) | 平台 `base_*` 表(百余张)+ `tdc_*` 业务表(**30 张**);`migrate.sql` 声明的 3 张账号层表由平台代建,数据落盘 `data/tdc.pg/` |
|
||||
| 前端 | **上游(Java/Vue)完整前端的构建产物**,托管在 `static/` | **零自研前端、零构建步骤**(`scripts/build-frontend.sh` 可重放) |
|
||||
@@ -48,6 +48,28 @@ This file provides guidance to AI coding agents (CodeBuddy / Claude Code / Curso
|
||||
> 验收:`tests/sspf_db_lock.rs` 真库验「不归一 + 平台持锁时业务写排队」,`check-dual-contract.sh`
|
||||
> 第 18 条断言靠启动日志自证 `install_sspf_db` 真的成功。
|
||||
|
||||
> **P6 平台改为预编译 rlib 发布(依赖模型整体换掉)**:平台 v0.5.0 起每版本出
|
||||
> `dist/sspf-vX.Y.Z.tar.gz`,包内 `lib/` 是构建产物 `deps/` 的**完整副本**(422 个文件:
|
||||
> `.rlib` + `.rmeta` + proc-macro `.dylib` + 原生 `.a`,**bitcode-free**,ABI 锁 rustc 1.95.0)。
|
||||
> 消费方不把 `sspf` 写成 cargo 依赖,而是用 `--extern` + `-L dependency` 直接喂给 rustc。
|
||||
>
|
||||
> - **取包**:`bash scripts/fetch-platform.sh`(读 `.sspf-version` → 解到 `vendor/sspf-vX.Y.Z/`
|
||||
> → 生成 `.cargo/config.toml`(含本机绝对路径与每版本会变的 rlib hash,**不进版本库**)
|
||||
> → 同步 `rust-toolchain.toml`)。升级平台 = 改 `.sspf-version` + 重跑脚本。
|
||||
> - 🔴 **`Cargo.toml` 里 `[dependencies]` 必须为空**。重新声明 `axum`/`tokio`/`serde`/… 会让
|
||||
> cargo **另编一份**,于是「同名 crate 两个实例」⇒ 把业务 `Router` 交给 `sspf::Finish`
|
||||
> 时 `E0308 mismatched types`(**实测**,`/tmp/rlib-a` 探针)。
|
||||
> - 🔴 **`reqwest` 彻底不能用**:它自带一份 tokio,而 `#[tokio::main]` 用的是闭包里那份 ⇒
|
||||
> tokio 的 runtime context 是 crate 实例内的 thread-local,两套互不可见 ⇒ 一调就 panic
|
||||
> `there is no reactor running`(**实测**,`/tmp/rlib-c` 探针)。⇒ 出向改走自研
|
||||
> [`platform::http`](tokio `TcpStream` + `http` 类型,**HTTP/1.1 明文,不支持 TLS**)。
|
||||
> - 🔴 **`tower-http` 也不在闭包里**(且它必须与 `axum` 同源,不能单独编)⇒ 自研
|
||||
> [`platform::static_files`](`ServeDir` 等价:GET/HEAD、Content-Type、Content-Length、
|
||||
> Range 206 + Content-Range、目录穿越防护)与 [`platform::cors`](`permissive()` 等价)。
|
||||
> - **`lto` 必须 `false`**(平台 rlib 是 bitcode-free 的,开 LTO 找不到 `__bitcode` 段)。
|
||||
> - 验收:`cargo test` 306 passed;新增尺子 `check-platform-package.sh` 5 组判据
|
||||
> (版本/包结构、config 路径、工具链一致、`Cargo.toml` 无依赖、**真编一次证明零重编**)。
|
||||
|
||||
> **pglite-rs ≠ 浏览器 PGlite**。crate 名 `pglite-rs`、import 名 `pglite`;它把 postgres-pglite 编译成原生静态库链接进二进制,
|
||||
> 是**真实 PostgreSQL 语义**(类型 / MVCC / 事务 / 扩展 / 线协议),进程内单 backend,**无服务器、无 Docker、无 WASM**。
|
||||
> 浏览器端 WASM 版(`@electric-sql/pglite` + IndexedDB)曾是本项目的错误实现,已废弃删除,勿再引入。
|
||||
@@ -56,9 +78,12 @@ This file provides guidance to AI coding agents (CodeBuddy / Claude Code / Curso
|
||||
|
||||
```
|
||||
tdc-rs/
|
||||
├── Cargo.toml # 依赖(含 sspf git tag)+ release 优化(lto=thin / strip / unwind)
|
||||
├── Cargo.lock # 锁定版本
|
||||
├── rust-toolchain.toml # 锁 rustc 1.95.0(与 sspf 平台包同版本,L3 dylib ABI 前提)
|
||||
├── Cargo.toml # 🔴 **[dependencies] 必须为空**(依赖全来自平台包)+ release 优化(lto=false / strip / unwind)
|
||||
├── Cargo.lock # 本仓无 cargo 依赖后只剩自身一条
|
||||
├── .sspf-version # 🔴 平台包版本(唯一真相:fetch-platform.sh 读它解包)
|
||||
├── rust-toolchain.toml # 锁 rustc 1.95.0(与 sspf 平台包同版本,rlib ABI 前提)
|
||||
├── .cargo/config.toml # 🔴 **生成物、不进版本库**:--extern 17 个 crate + -L dependency=vendor/.../lib
|
||||
├── vendor/sspf-vX.Y.Z/ # 🔴 **不进版本库**(~450MB):包内 lib/ 是预编译 rlib 闭包
|
||||
├── src/
|
||||
│ ├── main.rs # 启动装配:sspf::Platform::assemble() 开唯一库 / on_ready 补建 tdc 表 / 引导身份与账号层 / finish() 嵌套路由
|
||||
│ ├── lib.rs # 模块声明(只暴露 `platform` 与 `tdc` 两层,bin 只做装配)
|
||||
@@ -76,6 +101,9 @@ tdc-rs/
|
||||
│ │ ├── protocol.rs # 协议版本闸门
|
||||
│ │ ├── body.rs # 宽松 JSON 体
|
||||
│ │ ├── mw.rs # 405 JSON 改写中间件
|
||||
│ │ ├── cors.rs # **P6 自研**:permissive CORS 中间件(tower-http 不在平台闭包里)
|
||||
│ │ ├── static_files.rs # **P6 自研**:静态文件服务(ServeDir 等价,含 Range 206 + Content-Range)
|
||||
│ │ ├── http.rs # **P6 自研**:极简 HTTP/1.1 出向客户端(reqwest 不在闭包里;明文无 TLS)
|
||||
│ │ └── fallback.rs # 404 JSON + SPA 静态兜底 + DDL 两层守卫
|
||||
│ └── tdc/ # 【业务层】对位上游 `ssw.tdc.*` 包族
|
||||
│ ├── entity/ # 18 个实体各一文件 + mod.rs(ALL_SPECS / validate / 子表挂载声明)
|
||||
@@ -95,11 +123,13 @@ tdc-rs/
|
||||
├── schema/
|
||||
│ └── migrate.sql # tdc_* + base_* schema(include_str! 内嵌进二进制,**30 + 3 表**,**不在 web root**)
|
||||
├── scripts/ # build-frontend.sh / gen-migrate.sh / reset-data.sh / reap-ipc-leaks.sh
|
||||
│ # + **fetch-platform.sh**(**P6**:读 .sspf-version 解包 + 生成 .cargo/config.toml)
|
||||
│ # + **五把尺子**:smoke.sh(HTTP 契约)/ check-boundary.sh(边界静态)
|
||||
│ # / check-entity.sh(实体静态)/ check-contract.sh(契约对账)
|
||||
│ # / check-upstream-tests.sh(**上游测试用例移植台账**对账)
|
||||
│ # + check-dual-contract.sh(**P2 附加尺子**:双契约 + P3 会话桥 + P5 单锁,真进程,18 断言)
|
||||
│ # + check-db-access.sh(**P4 附加静态尺子**:库操作单一出口,0 处越界)
|
||||
│ # + check-platform-package.sh(**P6 附加尺子**:依赖单一来源 + 平台闭包零重编)
|
||||
│ # + contract_probe.py(check-contract 的探针)/ check-citations.py(文档引用自检)
|
||||
│ # + upstream-action-census.py(上游动作端点普查 · 只读上游克隆)
|
||||
│ # + upstream-test-census.py(**上游测试类普查**)/ upstream-test-ledger.tsv(台账真源)
|
||||
@@ -175,6 +205,9 @@ tdc-rs/
|
||||
cargo build # debug
|
||||
cargo build --release # 发布版
|
||||
|
||||
# 🔴 首次克隆 / 换机 / 升级平台包:**先取包**(生成 .cargo/config.toml,否则一个依赖都没有)
|
||||
bash scripts/fetch-platform.sh # 读 .sspf-version → 解包到 vendor/ → 生成 rustflags + 同步工具链
|
||||
|
||||
# 测试(⚠️ 跑之前先看 SysV 信号量余量,见「已知踩坑」最后几行)
|
||||
cargo test # 全量(lib + bin + 集成 + 文档)
|
||||
cargo test --test upstream_guard_parity --test upstream_tds_timeout_parity # 上游用例移植(29 条)
|
||||
@@ -218,6 +251,7 @@ python3 scripts/check-citations.py # 附:文档引用自检(`文件:行号`
|
||||
```bash
|
||||
bash scripts/check-dual-contract.sh # PASS=18 FAIL=0
|
||||
bash scripts/check-db-access.sh # 库操作单一出口:7 处命中全在白名单,0 处越界
|
||||
bash scripts/check-platform-package.sh # P6:依赖单一来源 + 平台闭包零重编(真编一次)
|
||||
```
|
||||
|
||||
一个进程、一个端口、一个库同时验:业务侧 `/api/health` 裸对象(`tables=30` / `baseTables=3`)、
|
||||
@@ -368,7 +402,8 @@ bash scripts/check-db-access.sh # 库操作单一出口:7 处命中全
|
||||
13. **出向 TDS 判定成功必须看 `body.code == 200`**(TDS 业务失败也是 HTTP 200)。
|
||||
解包型端点用 `tds::unwrap_data`、整包型用 `tds_biz::unwrap_envelope` —— **别混用**。
|
||||
14. **出向请求只带 6 个应用层头**(`src/tdc/client/tds.rs` 的 `internal_headers()`);
|
||||
`reqwest` 会自己加 `host` / `content-length` / `accept` ⇒ 断言「头数」时别把这三个算进去。
|
||||
自研客户端(`platform::http`)会自己加 `host` / `content-length` / `connection`
|
||||
⇒ 断言「头数」时别把这三个传输层头算进去。
|
||||
15. **CRUD 出参要过 `row_to_json_spec(spec, row)`**(不是 `row_to_json`)——
|
||||
它按 `spec.hidden_fields` 把上游 `@JsonIgnore` 的键**整条删掉**(不是置 null);
|
||||
写路径用 `body_to_columns(body, &types, spec.hidden_fields)` **静默跳过**同一批键。
|
||||
@@ -417,7 +452,7 @@ bash scripts/check-db-access.sh # 库操作单一出口:7 处命中全
|
||||
逐条对照见 `docs/UPSTREAM-TEST-PARITY.md` §2.1,决策见 `docs/decisions.md` **D22**。
|
||||
23. **出向 TDS 的超时分类靠 cause 链,不靠错误文案**:
|
||||
`src/tdc/client/tds.rs` 的 `cause_chain_has_timeout()` 沿 `Error::source()` **有界**(`depth < 16`,照抄上游)往下找。
|
||||
- 🔴 **只有** cause 链里有超时(`reqwest::Error::is_timeout()` 或 `io::ErrorKind::TimedOut`)才改写成
|
||||
- 🔴 **只有** cause 链里有超时(`platform::http::HttpError::is_timeout()` 或 `io::ErrorKind::TimedOut`)才改写成
|
||||
「调用 TDS 超时(当前 connect=…ms / read=…ms,可用 `SSW_TDS_CONNECT_TIMEOUT_MS` / `SSW_TDS_READ_TIMEOUT_MS` 调大)」;
|
||||
**连接被拒 / DNS 失败 / 无 cause ⇒ 不改写**(仍是「TDS 不可达」)——
|
||||
🔴 **把连接被拒说成"超时"会把排查引向错误方向**(调超时没用,要查网络/证书)。
|
||||
@@ -548,11 +583,18 @@ JSON 文件**保留不删**,但**后端不再读取**(存量账号**不导
|
||||
- sccache 0.18 经 `~/.cargo/config.toml` 的 `[build] rustc-wrapper` + `[env] SCCACHE_DIR` 启用
|
||||
- 缓存实体在 `~/.cache/sccache`(`~/Library/Caches/Mozilla.sccache` 软链透明访问)
|
||||
|
||||
`cargo build` 直接命中。**不要**在仓库内新建 `.cargo/config.toml` 或把 `target/` 挪走。
|
||||
`cargo build` 直接命中。
|
||||
|
||||
🔴 **唯一的例外是 `.cargo/config.toml` —— 它是平台包接入的必需件,由 `scripts/fetch-platform.sh`
|
||||
生成**(`rustflags` / `rustdocflags` 里的 `--extern` 清单),**不进版本库**。除此之外不要在仓库内
|
||||
另建 cargo 配置,也不要把 `target/` 挪走。
|
||||
|
||||
## 发布与体积
|
||||
|
||||
- release 配置:`opt-level=2` / `lto="thin"` / `strip="symbols"` / `codegen-units=16`;
|
||||
- release 配置:`opt-level=2` / **`lto=false`** / `strip="symbols"` / `codegen-units=16`;
|
||||
🔴 **`lto` 必须 `false`**:平台预编译 rlib 是 **bitcode-free** 的(出包时关了
|
||||
`lto` / `embed-bitcode`),开 LTO 会因找不到 `__bitcode` 段直接失败。平台 rlib 已是
|
||||
`opt-level=2`,损失很小。
|
||||
**不设 `panic="abort"`** —— 单进程链接 sspf 后平台契约要求 panic ⇒ HTTP 200 + `code=400`,
|
||||
catch-all 中间件依赖默认 `unwind`。
|
||||
- 体积构成:debug 二进制 **~35 MB**(主体是内嵌的 PostgreSQL 引擎)+ static **2 MB**(上游 SPA 产物)。
|
||||
@@ -582,10 +624,10 @@ JSON 文件**保留不删**,但**后端不再读取**(存量账号**不导
|
||||
| 边界尺子漏报(代码整片消失) | 朴素正则剥注释把**字符串里的 `/*`** 当成块注释开头 | 用**字符串感知的状态机**剥注释(`scripts/check-boundary.sh` 的 `strip_comments()`) |
|
||||
| 「不含 `secretKey`」断言恒真通过 | 取键名的辅助模式对对象返回 `ERR` ⇒ 断言变成真空 | 用 `objkeys`(取对象键名)模式,别用 `listkeys` |
|
||||
| 自动化里 antd 抽屉停在屏幕外、点不到「保存」 | 内核浏览器在**后台标签** ⇒ `visibilityState=hidden` ⇒ rAF + CSS transition 全冻结 | 注入 `*{transition:none !important}` + 摘掉卡住的 motion 类(**测试环境假象,非产品缺陷**,见 `docs/CONSOLE-ACCEPTANCE.md` §5) |
|
||||
| 出向 TDS 得 502 / 连接超时 | `reqwest` 读了**系统代理**(`HTTP_PROXY` / macOS 网络设置)⇒ loopback 被劫持 | `ClientBuilder::no_proxy()`(TDS 是**内网直连**服务) |
|
||||
| 出向 TDS 得 502 / 连接超时 | 历史上是 `reqwest` 读**系统代理**(`HTTP_PROXY` / macOS 网络设置)⇒ loopback 被劫持 | P6 起自研 `platform::http` **不实现代理**(等价 `.no_proxy()`)⇒ 这类故障不再出现;若仍 502,查 `SSW_TDS_BASE_URL` 与实际监听端口 |
|
||||
| 出向 TDS 拿到 200 却当成功 | TDS 业务失败也走 **HTTP 200 + `code != 200`** | 判 `body.code == 200`(解包型)/ `unwrap_envelope`(整包型) |
|
||||
| 上游动作端点**不 404**,前端下拉框却是空的 | 通用详情路由 `/{Entity}/{id}`(`src/tdc/controller/crud.rs:65-93`)把 `/{Entity}/{action}` **吞掉** ⇒ HTTP 200 + `code:400` | **必须读 body 的 `code`**;26 条形态 A 的清单见 `docs/known-limitations.md` **L7**(`python3 scripts/upstream-action-census.py` 可复算) |
|
||||
| 出向头被算成 8 个 | `reqwest` 会**自己加** `host` / `content-length` / `accept` | 应用层只断言自己那 6 个(传输层头不在管辖范围) |
|
||||
| 出向头比 6 个多 | 传输层会自己加 `host` / `content-length` / `connection` | 应用层只断言自己那 6 个(传输层头不在管辖范围) |
|
||||
| `Billing/{id}/Dispute` 等越权时仍看到出向请求 | `ownsLedger` 自检本身**就要**发一次 `BillingLedger/Internal/List` | 只断言**动作端点没被调用**,别断言「零出向」 |
|
||||
| `ServiceCatalog/Buy` 空体报「请求体格式有误」 | 用了 `JsonBody`(空体 ⇒ 拒) | 这几个端点体**可空** ⇒ 用 `tds_biz::OptionalJsonBody`(空体当空对象) |
|
||||
| 出向 URL 拼出注入 | 用户输入直接进 URL 路径 | 只用固定模板 + `tds::is_safe_path_segment` 校验过的段 |
|
||||
|
||||
Generated
-2411
File diff suppressed because it is too large.
Load diff
+23
-44
@@ -8,56 +8,35 @@ description = "TDC (数据接入连接器) MVP — Rust + 静态 HTML + PGlite
|
||||
name = "tdc-connector"
|
||||
path = "src/main.rs"
|
||||
|
||||
# ============================ 依赖:全部来自平台包 ============================
|
||||
#
|
||||
# 🔴 **本仓没有 cargo 依赖**(`[dependencies]` / `[dev-dependencies]` 都是空的),这不是漏写。
|
||||
#
|
||||
# 平台从 v0.5.0 起以**预编译 rlib 闭包**发布(`scripts/release.sh` 出的
|
||||
# `sspf-vX.Y.Z.tar.gz`,包内 `lib/` 是构建产物 `deps/` 的完整副本)。消费方把包解到
|
||||
# `vendor/sspf-vX.Y.Z/`,由 `scripts/fetch-platform.sh` 生成 `.cargo/config.toml`,
|
||||
# 用 `--extern` + `-L dependency` 直接把 rlib 喂给 rustc ⇒ **平台闭包与 axum/tokio/
|
||||
# serde 全部零重编**(实测 dev 1s 级)。
|
||||
#
|
||||
# ⇒ 依赖声明在 `.cargo/config.toml` 里,不在本文件。**这里一旦再写 `axum = "0.8"`,
|
||||
# cargo 会另编一份 axum**,于是「同名 crate 两个实例」⇒ 把业务 `Router` 交给
|
||||
# `sspf::Finish` 时必然 `E0308 mismatched types`(已实测)。
|
||||
#
|
||||
# 🔴 两个**不在闭包里**的 crate,因此业务侧自研替身(见各自模块头部的说明):
|
||||
# - `tower-http`(`ServeDir` / `CorsLayer`)⇒ `src/platform/static_files.rs`、`src/platform/cors.rs`
|
||||
# - `reqwest`(TDS 出向)⇒ `src/platform/http.rs`(它必须与 extern 的 tokio 同源,
|
||||
# 否则 reqwest 自带的 tokio 实例与运行时不是同一个 ⇒ 实测 panic `no reactor running`)
|
||||
|
||||
[dependencies]
|
||||
# 🔴 sspf 标准平台包(JNPF 兼容底座)—— 业务仓唯一的平台依赖,按 tag 锁版本。
|
||||
# 开发期调试可临时换 path = "../ssw-platform/crates/sspf";交付一律用 git tag。
|
||||
# 🔴 v0.5.0 起业务库操作与平台共用同一把 `Db.lock`(`query_json_raw` / `query_rows` /
|
||||
# `exec_params`),见 `src/platform/db.rs`。
|
||||
sspf = { git = "http://127.0.0.1:13300/ssw/ssw-platform.git", tag = "v0.5.0" }
|
||||
|
||||
# Web 框架 / 运行时
|
||||
axum = "0.8"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
tower-http = { version = "0.6", features = ["fs", "cors", "trace"] }
|
||||
|
||||
# 序列化
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
|
||||
# TDS 跨方 HTTP 契约客户端(红线:TDC 与 TDS 只走 HTTP,不编译期耦合)
|
||||
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
|
||||
|
||||
rand = "0.8"
|
||||
hex = "0.4"
|
||||
|
||||
# 登录口令加解密(与上游前端 cipher.ts 对齐):AES-256-ECB + MD5
|
||||
# 🔴 版本组合自洽,别混用:aes 0.8 / ecb 0.1 都依赖 cipher 0.4 家族;
|
||||
# aes 0.9 / ecb 0.2 是 cipher 0.5 家族,两套泛型不通用。
|
||||
# 🔴 md-5 钉 0.10(crate 名 `md5`,`use md5::{Digest, Md5};`);0.11 的 API 不同。
|
||||
aes = "0.8"
|
||||
ecb = "0.1"
|
||||
md-5 = "0.10"
|
||||
# 登录表单解析(application/x-www-form-urlencoded)。
|
||||
# ⚠️ axum 0.8.9 的 `Form<T>` 只实现 `FromRequest`、不实现 `OptionalFromRequest`
|
||||
# ⇒ `Option<Form<T>>` 编译不过 ⇒ 改为「取原始 body + serde_urlencoded 自己解析」。
|
||||
# `serde_urlencoded 0.7.1` 已在 `Cargo.lock` 里(axum 的传递依赖)⇒ 不引入新下载。
|
||||
serde_urlencoded = "0.7"
|
||||
|
||||
# 内嵌 PostgreSQL(进程内原生编译,非 WASM):承载全部 tdc_* 业务数据
|
||||
# 包名 pglite-rs,import 为 pglite。无需扩展时不用 build.rs/export_dynamic。
|
||||
pglite-rs = "0.2"
|
||||
|
||||
# 真实 UTC 时间戳(last_heartbeat / 同步日志用,避免手写日历换算)
|
||||
chrono = { version = "0.4", default-features = false, features = ["clock"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# 路由级中间件测试(Task 5 fix round 1):`tower::ServiceExt::oneshot` 打请求
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
http-body-util = "0.1"
|
||||
|
||||
[profile.release]
|
||||
opt-level = 2
|
||||
lto = "thin"
|
||||
# 🔴 必须 `false`:平台预编译 rlib 是 **bitcode-free** 的(出包时关了
|
||||
# `lto` / `embed-bitcode`)⇒ 本仓开 LTO 会因找不到 `__bitcode` 段直接失败。
|
||||
# 平台 rlib 本身已是 opt-level=2,损失很小。
|
||||
lto = false
|
||||
strip = "symbols" # 发布包剥离符号表,体积减半以上
|
||||
# 🔴 不要设 `panic = "abort"`:单进程链接 sspf 后,平台契约 §6.5 要求
|
||||
# panic ⇒ HTTP 200 + code=400,catch-all 中间件依赖默认的 `panic = "unwind"`。
|
||||
|
||||
@@ -28,7 +28,8 @@
|
||||
|
||||
```bash
|
||||
cd tdc-rs
|
||||
cargo build # 编译(自动走 sccache + 统一 registry 缓存)
|
||||
bash scripts/fetch-platform.sh # 🔴 首次/换机/升级平台包:取预编译 rlib 包(生成 .cargo/config.toml)
|
||||
cargo build # 编译(自动走 sccache + 统一 registry 缓存;平台闭包零重编,~2.5s)
|
||||
PORT=30000 ./target/debug/tdc-connector
|
||||
# 浏览器打开 http://localhost:30000
|
||||
```
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
|
||||
```bash
|
||||
cd /Users/xs/Desktop/workspace/tdc-rs
|
||||
bash scripts/fetch-platform.sh # 首次/换机/升级平台包:取预编译 rlib 包(生成 .cargo/config.toml)
|
||||
cargo build
|
||||
PORT=30000 ./target/debug/tdc-connector
|
||||
```
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
#!/usr/bin/env bash
|
||||
# 平台包接入自检(**P6 新增尺子**):证明「依赖全部来自预编译 rlib 闭包」这件事没漂。
|
||||
#
|
||||
# 判据(任一红即失败):
|
||||
# 1. `.sspf-version` 与 `vendor/sspf-v<版本>/` 对得上,且包结构完整(`lib/` 存在);
|
||||
# 2. `.cargo/config.toml` 已生成,里面**每一个** `--extern` / `-L` 指向的路径真实存在;
|
||||
# 3. 工具链与包内 `rust-toolchain.toml` 的 channel **一字不差**(rlib ABI 前提);
|
||||
# 4. `Cargo.toml` 的 `[dependencies]` / `[dev-dependencies]` **必须为空**
|
||||
# —— 重新声明 `axum` / `tokio` / `serde` 会编出第二份 ⇒ 把业务 `Router` 交给
|
||||
# `sspf::Finish` 时 `E0308 mismatched types`(已实测);
|
||||
# 5. 真的编一次(touch 本仓源码触发重编):构建输出里**不得**出现
|
||||
# `Compiling sspf` / `Compiling axum` / `Compiling tokio` / `Compiling serde*`
|
||||
# ⇒ 「平台闭包零重编」是端到端可验的,不是文档承诺。
|
||||
set -uo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
cd "$ROOT"
|
||||
FAIL=0
|
||||
pass() { printf ' ✅ %s\n' "$1"; }
|
||||
fail() { printf ' ❌ %s\n' "$1"; FAIL=$((FAIL + 1)); }
|
||||
|
||||
echo "── 1. 版本与包结构 ─────────────────────────────"
|
||||
if [ ! -f .sspf-version ]; then
|
||||
fail ".sspf-version 缺失(先跑 scripts/fetch-platform.sh)"
|
||||
VERSION=""
|
||||
else
|
||||
VERSION="$(tr -d '[:space:]' < .sspf-version)"
|
||||
pass ".sspf-version = ${VERSION}"
|
||||
fi
|
||||
|
||||
VENDOR="$ROOT/vendor/sspf-v${VERSION}"
|
||||
if [ -n "$VERSION" ] && [ -d "$VENDOR/lib" ] && [ -f "$VENDOR/rust-toolchain.toml" ]; then
|
||||
pass "vendor/sspf-v${VERSION}/ 结构完整(lib/ + rust-toolchain.toml)"
|
||||
else
|
||||
fail "vendor/sspf-v${VERSION}/ 不完整 ⇒ 跑 bash scripts/fetch-platform.sh"
|
||||
fi
|
||||
|
||||
echo "── 2. .cargo/config.toml ───────────────────────"
|
||||
CFG="$ROOT/.cargo/config.toml"
|
||||
if [ ! -f "$CFG" ]; then
|
||||
fail ".cargo/config.toml 缺失 ⇒ 跑 bash scripts/fetch-platform.sh"
|
||||
else
|
||||
pass ".cargo/config.toml 存在"
|
||||
# 抽出所有 `k=v` / `dependency=...` 形式的路径,逐个判存在
|
||||
MISSING=0
|
||||
while IFS= read -r p; do
|
||||
[ -n "$p" ] || continue
|
||||
if [ ! -e "$p" ]; then
|
||||
fail "配置里的路径不存在: ${p}"
|
||||
MISSING=1
|
||||
fi
|
||||
done < <(grep -oE '(dependency=|=)[^",]+' "$CFG" | sed 's/^dependency=//; s/^=//' | grep '^/' || true)
|
||||
[ "$MISSING" -eq 0 ] && pass "配置里所有绝对路径都存在"
|
||||
|
||||
# extern 必须覆盖跨边界的那 7 个 crate(少了任何一个,跨 `sspf` 边界传参就 E0308)
|
||||
for c in sspf axum tokio serde serde_json http bytes; do
|
||||
if grep -q "\"--extern\", \"${c}=" "$CFG"; then
|
||||
:
|
||||
else
|
||||
fail "缺少 --extern ${c}(跨边界类型必须与平台同一实例)"
|
||||
fi
|
||||
done
|
||||
pass "跨边界 7 个 crate 均已 --extern"
|
||||
fi
|
||||
|
||||
echo "── 3. 工具链一致 ───────────────────────────────"
|
||||
if [ -n "$VERSION" ] && [ -f "$VENDOR/rust-toolchain.toml" ]; then
|
||||
WANT="$(grep -oE 'channel = "[^"]+"' "$VENDOR/rust-toolchain.toml" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+')"
|
||||
HAVE="$(rustc --version 2>/dev/null | awk '{print $2}')"
|
||||
LOCAL="$(grep -oE 'channel = "[^"]+"' "$ROOT/rust-toolchain.toml" 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+')"
|
||||
if [ "$WANT" = "$HAVE" ] && [ "$WANT" = "$LOCAL" ]; then
|
||||
pass "rustc ${HAVE} == 包内 channel == 本仓 rust-toolchain.toml"
|
||||
else
|
||||
fail "工具链不一致:包内 ${WANT} / 本仓 ${LOCAL} / 实际 ${HAVE}(rlib ABI 会不匹配)"
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "── 4. Cargo.toml 不许声明依赖 ─────────────────"
|
||||
# 取 `[dependencies]` 与 `[dev-dependencies]` 段的有效行(去掉注释与空行)
|
||||
for section in dependencies dev-dependencies; do
|
||||
BAD="$(awk -v s="[$section]" '
|
||||
$0 == s { inside = 1; next }
|
||||
/^\[/ { inside = 0 }
|
||||
inside {
|
||||
line = $0
|
||||
sub(/#.*/, "", line)
|
||||
gsub(/[[:space:]]/, "", line)
|
||||
if (line != "") print line
|
||||
}' Cargo.toml)"
|
||||
if [ -z "$BAD" ]; then
|
||||
pass "[${section}] 为空(依赖全部来自平台包)"
|
||||
else
|
||||
fail "[${section}] 出现依赖声明: ${BAD}"
|
||||
fi
|
||||
done
|
||||
|
||||
echo "── 5. 平台闭包零重编(真编一次)───────────────"
|
||||
touch src/lib.rs
|
||||
BUILD="$(cargo build 2>&1)"
|
||||
if printf '%s' "$BUILD" | grep -qE '^ *Compiling (sspf|sspf_|ssw_platform|axum|tokio|serde|serde_json|http|bytes|tower|pglite|hyper)'; then
|
||||
fail "构建时重编了平台闭包(应只编本仓):"
|
||||
printf '%s\n' "$BUILD" | grep -E '^ *Compiling' | sed 's/^/ /'
|
||||
else
|
||||
pass "构建只编本仓(平台 rlib 直链,零重编)"
|
||||
fi
|
||||
|
||||
echo "────────────────────────────────────────────────"
|
||||
if [ "$FAIL" -eq 0 ]; then
|
||||
echo "平台包接入自检通过 ✅(预编译 rlib / 零重编 / 依赖单一来源)"
|
||||
exit 0
|
||||
fi
|
||||
echo "平台包接入自检失败 ❌(${FAIL} 处)"
|
||||
exit 1
|
||||
@@ -0,0 +1,187 @@
|
||||
#!/usr/bin/env bash
|
||||
# 取 sspf 标准平台包(预编译 rlib 闭包),并生成本仓的 `.cargo/config.toml`。
|
||||
#
|
||||
# 用法:
|
||||
# bash scripts/fetch-platform.sh # 用 .sspf-version 里的版本,从 ../ssw-platform/dist 取
|
||||
# bash scripts/fetch-platform.sh --pkg <tar.gz> # 显式指定包文件
|
||||
# bash scripts/fetch-platform.sh --url <url> # 从 http(s) 取
|
||||
#
|
||||
# 产出(**都不进版本库**,见 .gitignore):
|
||||
# vendor/sspf-vX.Y.Z/ 解包后的平台包(lib/ 是预编译闭包,422 个文件)
|
||||
# .cargo/config.toml rustflags:--extern sspf/axum/tokio/... + -L dependency=vendor/.../lib
|
||||
#
|
||||
# 🔴 为什么要有这个脚本:方案 C 的 rustflags 里写的是**本机绝对路径 + 每版本会变的
|
||||
# rlib hash**,手抄必错、且换机就废。脚本每次重新解析 `.d` 文件里的源码路径来确定
|
||||
# 「同名 crate 的哪一份才是对的」(例如 rand 有 0.8 与 0.10 两份、md5 有 0.10 与 0.11 两份)。
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
VERSION_FILE="$ROOT/.sspf-version"
|
||||
VERSION="$(cat "$VERSION_FILE" 2>/dev/null | tr -d '[:space:]')"
|
||||
PKG=""
|
||||
URL=""
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--pkg) PKG="${2:?--pkg 需要一个路径}"; shift 2 ;;
|
||||
--url) URL="${2:?--url 需要一个 URL}"; shift 2 ;;
|
||||
--version) VERSION="${2:?--version 需要一个版本号}"; shift 2 ;;
|
||||
*) echo "未知参数: $1" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
[ -n "$VERSION" ] || { echo "缺少版本:写 .sspf-version 或用 --version" >&2; exit 2; }
|
||||
|
||||
VENDOR="$ROOT/vendor/sspf-v$VERSION"
|
||||
|
||||
# ---------------- 1. 解包 ----------------
|
||||
if [ ! -d "$VENDOR/lib" ]; then
|
||||
mkdir -p "$ROOT/vendor"
|
||||
if [ -z "$PKG" ] && [ -z "$URL" ]; then
|
||||
PKG="$ROOT/../ssw-platform/dist/sspf-v$VERSION.tar.gz"
|
||||
fi
|
||||
if [ -n "$URL" ]; then
|
||||
TMP="$(mktemp -t sspf-pkg).tar.gz"
|
||||
echo "→ 下载 $URL"
|
||||
curl -fsSL "$URL" -o "$TMP"
|
||||
PKG="$TMP"
|
||||
fi
|
||||
[ -f "$PKG" ] || { echo "找不到发布包: ${PKG}(用 --pkg 或 --url 指定)" >&2; exit 1; }
|
||||
echo "→ 解包 $PKG"
|
||||
tar -xzf "$PKG" -C "$ROOT/vendor"
|
||||
fi
|
||||
[ -d "$VENDOR/lib" ] || { echo "包结构不对,缺 $VENDOR/lib" >&2; exit 1; }
|
||||
|
||||
LIB="$VENDOR/lib"
|
||||
|
||||
# ---------------- 2. 挑 rlib:同名多版本时按 .d 里的源码版本定 ----------------
|
||||
# $1 = rustc crate 名(= 文件名里的名字),$2 = 期望的**包名+版本**(可空)
|
||||
#
|
||||
# `.d` 文件里记着源码绝对路径(`.../md-5-0.10.6/src/lib.rs`),是唯一能
|
||||
# 把 rlib hash 与「哪个版本」对上号的线索。
|
||||
pick_rlib() {
|
||||
local crate="$1" want="${2:-}"
|
||||
local -a cands=()
|
||||
local f
|
||||
for f in "$LIB/lib${crate}-"*.rlib; do
|
||||
[ -e "$f" ] || continue
|
||||
cands+=("$f")
|
||||
done
|
||||
if [ "${#cands[@]}" -eq 0 ]; then
|
||||
echo " ✗ $crate 不在闭包里" >&2
|
||||
return 1
|
||||
fi
|
||||
if [ "${#cands[@]}" -eq 1 ]; then
|
||||
printf '%s\n' "${cands[0]}"
|
||||
return 0
|
||||
fi
|
||||
# 多份 ⇒ 按 .d 里的源码目录名过滤(`want` 形如 `md-5-0.10`,前缀匹配)
|
||||
[ -n "$want" ] || {
|
||||
echo " ✗ $crate 有 ${#cands[@]} 份却没说版本(want=)" >&2
|
||||
return 1
|
||||
}
|
||||
for f in "${cands[@]}"; do
|
||||
# 🔴 rlib 叫 `libfoo-<hash>.rlib`,对应的 `.d` 却叫 `foo-<hash>.d`(没 `lib` 前缀)
|
||||
local base d
|
||||
base="$(basename "$f" .rlib)"
|
||||
d="$LIB/${base#lib}.d"
|
||||
[ -f "$d" ] || continue
|
||||
if grep -qE "/${want//./\\.}\.[0-9]+/" "$d"; then
|
||||
printf '%s\n' "$f"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
echo " ✗ $crate 找不到版本 $want 对应的 rlib" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
# 业务仓代码**直接具名**的 crate(跨 sspf 边界的类型都在这张表里)。
|
||||
# - sspf/axum/tokio/serde/serde_json/http/bytes:跨边界 ⇒ **必须**是闭包里那一份
|
||||
# - rand/md5/aes/ecb/...:只在业务仓内部用,但仍取闭包版本 ⇒ 全进程只有一份
|
||||
EXTERNS=(
|
||||
"sspf:"
|
||||
"axum:"
|
||||
"tokio:"
|
||||
"serde:"
|
||||
"serde_json:"
|
||||
"http:"
|
||||
"bytes:"
|
||||
"tower:"
|
||||
"http_body_util:"
|
||||
"serde_urlencoded:"
|
||||
"chrono:"
|
||||
"hex:"
|
||||
"rand:rand-0.8"
|
||||
"md5:md-5-0.10"
|
||||
"aes:"
|
||||
"ecb:"
|
||||
"pglite:pglite-0.2"
|
||||
)
|
||||
|
||||
echo "→ 解析 rlib(${LIB})"
|
||||
declare -a FLAGS=()
|
||||
for spec in "${EXTERNS[@]}"; do
|
||||
name="${spec%%:*}"
|
||||
want="${spec#*:}"
|
||||
path="$(pick_rlib "$name" "$want")"
|
||||
FLAGS+=("--extern" "$name=$path")
|
||||
printf ' %-18s %s\n' "$name" "$(basename "$path")"
|
||||
done
|
||||
FLAGS+=("-L" "dependency=$LIB")
|
||||
|
||||
# ---------------- 3. 写 .cargo/config.toml ----------------
|
||||
mkdir -p "$ROOT/.cargo"
|
||||
{
|
||||
echo "# 本文件**由 scripts/fetch-platform.sh 生成**,含本机绝对路径 ⇒ 不进版本库。"
|
||||
echo "# 换机 / 升级平台包版本:重跑一次脚本即可。"
|
||||
echo "[build]"
|
||||
# 🔴 rustflags 只管 rustc,**doc-test / rustdoc 走另一套**(`rustdocflags`)
|
||||
# ⇒ 两边都要给,否则 `cargo test` 到 Doc-tests 阶段会因为找不到 axum 而红。
|
||||
echo "rustflags = ["
|
||||
i=0
|
||||
while [ "$i" -lt "${#FLAGS[@]}" ]; do
|
||||
echo " \"${FLAGS[$i]}\", \"${FLAGS[$((i + 1))]}\","
|
||||
i=$((i + 2))
|
||||
done
|
||||
echo "]"
|
||||
echo "rustdocflags = ["
|
||||
i=0
|
||||
while [ "$i" -lt "${#FLAGS[@]}" ]; do
|
||||
echo " \"${FLAGS[$i]}\", \"${FLAGS[$((i + 1))]}\","
|
||||
i=$((i + 2))
|
||||
done
|
||||
echo "]"
|
||||
} >"$ROOT/.cargo/config.toml"
|
||||
echo "→ 已写 .cargo/config.toml(rustflags + rustdocflags)"
|
||||
|
||||
# ---------------- 4. 工具链锁 ----------------
|
||||
# rlib 的 ABI 取决于产出它的 rustc ⇒ 版本必须一字不差。
|
||||
# ⚠️ **只校 channel,不整份覆盖**:本仓的 `rust-toolchain.toml` 有自己的说明注释,
|
||||
# 整份拷平台包那份会把注释换成讲 cdylib 插件的话(与本仓无关)。
|
||||
PKG_CHANNEL="$(grep -oE 'channel = "[^"]+"' "$VENDOR/rust-toolchain.toml" | head -1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+')"
|
||||
TOOL="$ROOT/rust-toolchain.toml"
|
||||
if [ ! -f "$TOOL" ]; then
|
||||
cat >"$TOOL" <<EOF
|
||||
# 🔴 必须与平台包 sspf(ssw-platform)锁同一个 rustc。
|
||||
# 预编译 rlib 的 ABI 取决于产出它的 rustc:版本不一致 ⇒ 链接失败 / 类型解析异常,
|
||||
# 报错点常在无关代码里,极难定位。
|
||||
# ⚠️ 本文件由 scripts/fetch-platform.sh 按包内 rust-toolchain.toml 的 channel 校验。
|
||||
|
||||
[toolchain]
|
||||
channel = "${PKG_CHANNEL}"
|
||||
components = ["rustfmt", "clippy"]
|
||||
profile = "minimal"
|
||||
EOF
|
||||
echo "→ 已创建 rust-toolchain.toml(channel = ${PKG_CHANNEL})"
|
||||
else
|
||||
LOCAL_CHANNEL="$(grep -oE 'channel = "[^"]+"' "$TOOL" | head -1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+')"
|
||||
if [ "$LOCAL_CHANNEL" = "$PKG_CHANNEL" ]; then
|
||||
echo "→ rust-toolchain.toml 已是 ${PKG_CHANNEL}(与包内一致)"
|
||||
else
|
||||
# 只改 channel 那一行,保留本仓注释
|
||||
sed -i '' -E "s/^channel = \"[^\"]+\"/channel = \"${PKG_CHANNEL}\"/" "$TOOL"
|
||||
echo "→ rust-toolchain.toml:${LOCAL_CHANNEL} → ${PKG_CHANNEL}(已对齐包内)"
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "✓ 平台包就绪:v$VERSION"
|
||||
+4
-2
@@ -27,12 +27,12 @@ use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::{routing::any, Router};
|
||||
use tower_http::cors::CorsLayer;
|
||||
|
||||
use sspf::{Config as SspfConfig, Finish, Platform};
|
||||
|
||||
use tdc_connector::platform::auth::{auth_middleware, AuthState};
|
||||
use tdc_connector::platform::config::Config;
|
||||
use tdc_connector::platform::cors;
|
||||
use tdc_connector::tdc::schema::ensure_schema_coexist;
|
||||
use tdc_connector::platform::fallback::{api_not_found, spa_fallback};
|
||||
use tdc_connector::platform::mw::json_method_not_allowed;
|
||||
@@ -259,9 +259,11 @@ async fn main() {
|
||||
// (`/api/health` / `/api/oauth/Login` / `/api/permission/Users` …)由业务侧胜出,
|
||||
// 平台独有路径仍由面 B 提供,两边都没命中才走 SPA 兜底。
|
||||
// CORS 挂在最外层 ⇒ 与原来全局 `CorsLayer::permissive()` 的作用域一致。
|
||||
// ⚠️ P6:`tower-http` 不在平台 rlib 闭包里 ⇒ 换成自研的 permissive 中间件
|
||||
// (语义逐条对位,见 `src/platform/cors.rs`)。
|
||||
let app: Router = biz
|
||||
.fallback_service(platform_app)
|
||||
.layer(CorsLayer::permissive());
|
||||
.layer(axum::middleware::from_fn(cors::permissive));
|
||||
|
||||
let addr = std::net::SocketAddr::from(([0, 0, 0, 0], config.port));
|
||||
println!(
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
//! CORS(`tower_http::cors::CorsLayer::permissive()` 的等价中间件)。
|
||||
//!
|
||||
//! ## 为什么自己写
|
||||
//!
|
||||
//! 平台 v0.5.0 起以预编译 rlib 闭包发布,`lib/` 里没有 `tower-http`;而
|
||||
//! `CorsLayer` 是 `tower::Layer`,必须与 `axum` 用同一份 `http`/`tower` 实例
|
||||
//! ⇒ 不能由本仓单独编译。本仓只需要「permissive」这一档,实现成本很低。
|
||||
//!
|
||||
//! ## `permissive()` 的语义(tower-http 0.6.11,逐条对位)
|
||||
//!
|
||||
//! | 项 | 值 |
|
||||
//! |---|---|
|
||||
//! | `Access-Control-Allow-Origin` | `*`(**普通请求与预检都带**) |
|
||||
//! | `Access-Control-Allow-Methods` | `*`(仅预检) |
|
||||
//! | `Access-Control-Allow-Headers` | `*`(仅预检) |
|
||||
//! | `Access-Control-Allow-Credentials` | **不设**(`permissive` 不开凭据) |
|
||||
//! | 预检短路 | `OPTIONS` **且**带 `Access-Control-Request-Method` ⇒ 直接 200 空体,**不进**业务链 |
|
||||
//!
|
||||
//! 🔴 `permissive()` **不**开 `allow_credentials`:浏览器侧 `*` 与凭据互斥,
|
||||
//! 本仓前端用 `Authorization` 头(不是 Cookie)⇒ 不需要凭据模式。
|
||||
//!
|
||||
//! 🔴 预检必须**短路**:`/api/**` 上有业务鉴权中间件,若让 `OPTIONS` 进业务链,
|
||||
//! 没有 `Authorization` 的预检会吃 401 ⇒ 浏览器报 CORS 失败而不是鉴权失败,
|
||||
//! 排查方向直接被带偏。
|
||||
|
||||
use axum::extract::Request;
|
||||
use axum::http::{header, HeaderValue, Method, StatusCode};
|
||||
use axum::middleware::Next;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
|
||||
/// permissive CORS 中间件(挂在**最外层**,面 A / 面 B 都经过)。
|
||||
pub async fn permissive(req: Request, next: Next) -> Response {
|
||||
// 预检:不带 token,必须在进业务链前回答。
|
||||
let is_preflight = req.method() == Method::OPTIONS
|
||||
&& req
|
||||
.headers()
|
||||
.contains_key(header::ACCESS_CONTROL_REQUEST_METHOD);
|
||||
if is_preflight {
|
||||
let mut resp = StatusCode::OK.into_response();
|
||||
let h = resp.headers_mut();
|
||||
h.insert(
|
||||
header::ACCESS_CONTROL_ALLOW_ORIGIN,
|
||||
HeaderValue::from_static("*"),
|
||||
);
|
||||
h.insert(
|
||||
header::ACCESS_CONTROL_ALLOW_METHODS,
|
||||
HeaderValue::from_static("*"),
|
||||
);
|
||||
h.insert(
|
||||
header::ACCESS_CONTROL_ALLOW_HEADERS,
|
||||
HeaderValue::from_static("*"),
|
||||
);
|
||||
return resp;
|
||||
}
|
||||
|
||||
let mut resp = next.run(req).await;
|
||||
resp.headers_mut().insert(
|
||||
header::ACCESS_CONTROL_ALLOW_ORIGIN,
|
||||
HeaderValue::from_static("*"),
|
||||
);
|
||||
resp
|
||||
}
|
||||
+45
-17
@@ -13,7 +13,7 @@
|
||||
//! | 路径中**任意一段**的**扩展名**(去尾部空白与尾部 `.`、**Unicode 大写折叠**后)等于 `SQL` | **404 + JSON**(**前置守卫** `ddl_guard`) |
|
||||
//! | 响应体与**内嵌 DDL 逐字节相同**(**不论文件名**) | **404 + JSON**(**内容级兜底** `ddl_content_guard`) |
|
||||
//! | 响应体是**内嵌 DDL 的某一片段**(`Range` 分块下载) | **404 + JSON**(**内容级兜底** `ddl_content_guard`) |
|
||||
//! | 命中 `static/` 里的真实文件、且响应体**不**与内嵌 DDL 逐字节相同 | 由 `ServeDir` 直接出 |
|
||||
//! | 命中 `static/` 里的真实文件、且响应体**不**与内嵌 DDL 逐字节相同 | 由静态文件服务直接出 |
|
||||
//! | 其余未命中路径(`/tdc/home`、`/login` 等 SPA 深链) | **200 + `text/html`**(`static/index.html`) |
|
||||
//!
|
||||
//! ⚠️ **「不命中上表」不等于「响应形状一定是 200 HTML」**:例如 `/migrate.sql%00`
|
||||
@@ -67,7 +67,6 @@ use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::any;
|
||||
use axum::Router;
|
||||
use serde_json::json;
|
||||
use tower_http::services::ServeDir;
|
||||
|
||||
/// DDL 的**扩展名**(判定用,见 [`is_ddl_path`])。
|
||||
///
|
||||
@@ -105,28 +104,54 @@ pub async fn api_not_found() -> Response {
|
||||
.into_response()
|
||||
}
|
||||
|
||||
/// 兜底服务:`ServeDir`(出 `static/` 里的真实文件)+ **找不到文件时**的决策层。
|
||||
/// 兜底服务:[静态文件服务](crate::platform::static_files)(出 `static/` 里的真实文件)
|
||||
/// + **找不到文件时**的决策层。
|
||||
///
|
||||
/// 决策层是一个内层 `Router<()>`(`Router` 本身就是 `Service`,可直接当 `ServeDir` 的 fallback):
|
||||
/// `/api` 命名空间 ⇒ 404 JSON;其余 ⇒ `static/index.html`(200 `text/html`)。
|
||||
/// 决策层:`/api` 命名空间 ⇒ 404 JSON;其余 ⇒ `static/index.html`(200 `text/html`)。
|
||||
///
|
||||
/// 🔴 返回的是 `Router`(不是 `ServeDir`)——因为 **DDL 前置守卫 `ddl_guard` 必须跑在
|
||||
/// `ServeDir` 之前**:`axum 0.8.9` 的 `Router::layer` 会同时包住 `fallback_router`
|
||||
/// 🔴 返回的是 `Router`(不是静态服务本身)——因为 **DDL 前置守卫 `ddl_guard` 必须跑在
|
||||
/// 读文件之前**:`axum 0.8.9` 的 `Router::layer` 会同时包住 `fallback_router`
|
||||
/// 与 `catch_all_fallback`(`axum-0.8.9/src/routing/mod.rs:303-317`)
|
||||
/// ⇒ 守卫先于 `ServeDir` 执行 ⇒ **扩展名命中 `.sql` 的路径不会由 `ServeDir` 吐出**。
|
||||
/// ⇒ 守卫先于读文件执行 ⇒ **扩展名命中 `.sql` 的路径不会由静态服务吐出**。
|
||||
///
|
||||
/// ⚠️ 为什么不用 `tower::service_fn`:`tower` 只是 **dev-dependency**,
|
||||
/// **lib 代码里不许用** `tower::service_fn` / `ServiceExt` ⇒ 用 axum 自己的 `any(handler)`。
|
||||
/// ⚠️ 为什么不用 `tower::service_fn`:`tower` 只作 extern 依赖、且本仓刻意不在 lib
|
||||
/// 代码里用它(否则要自己拼 `Service` 的 future 类型)⇒ 用 axum 自己的 `any(handler)`。
|
||||
///
|
||||
/// ⚠️ **P6 变更**:原来这里是 `tower_http::services::ServeDir`。平台改为预编译 rlib
|
||||
/// 发布后,`tower-http` 不在闭包里,且它必须与 `axum` 同源 ⇒ 不能由本仓单独编译
|
||||
/// ⇒ 换成自研的 [`crate::platform::static_files::serve`](语义逐条对位,见该模块文档)。
|
||||
pub fn spa_fallback(static_dir: impl Into<PathBuf>) -> Router {
|
||||
let static_dir = static_dir.into();
|
||||
let index_file = static_dir.join("index.html");
|
||||
// 内层 Router:把「找不到文件」的决策交给 handler(`Router<()>` ⇒ 状态类型被钉死为 `()`)。
|
||||
let decision: Router = Router::new().fallback(any(move |uri: Uri| {
|
||||
let index_file = index_file.clone();
|
||||
async move { fallback_response(&index_file, &uri).await }
|
||||
}));
|
||||
Router::new()
|
||||
.fallback_service(ServeDir::new(&static_dir).fallback(decision))
|
||||
.fallback(any(move |req: Request| {
|
||||
// 🔴 先把要用的字段**同步**取成 owned 值:`Request` 里的 `Body` 不是 `Sync`,
|
||||
// 持有 `&Request` 跨 `await` 会让 handler future 变成 `!Send` ⇒ 编译不过。
|
||||
let static_dir = static_dir.clone();
|
||||
let index_file = index_file.clone();
|
||||
let method = req.method().clone();
|
||||
let path = req.uri().path().to_string();
|
||||
let range = req
|
||||
.headers()
|
||||
.get(header::RANGE)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(str::to_string);
|
||||
let uri = req.uri().clone();
|
||||
async move {
|
||||
match crate::platform::static_files::serve(
|
||||
&static_dir,
|
||||
&method,
|
||||
&path,
|
||||
range.as_deref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Some(resp) => resp,
|
||||
// 没这个文件 ⇒ 决策层(`/api` 404 JSON / 其余回 SPA 外壳)
|
||||
None => fallback_response(&index_file, &uri).await,
|
||||
}
|
||||
}
|
||||
}))
|
||||
.layer(axum::middleware::from_fn(ddl_guard))
|
||||
}
|
||||
|
||||
@@ -309,7 +334,10 @@ fn decoded_path(raw_path: &str) -> String {
|
||||
}
|
||||
|
||||
/// 最小实现的 percent-decode(只处理 `%XX`;非法的 `%` 原样保留)。
|
||||
fn percent_decode(s: &str) -> String {
|
||||
///
|
||||
/// ⚠️ `pub(crate)`:静态文件服务([`crate::platform::static_files`])必须与守卫用
|
||||
/// **同一个**解码口径,否则会出现「守卫认为在 `/api` 下、静态服务不认为」的错位。
|
||||
pub(crate) fn percent_decode(s: &str) -> String {
|
||||
let bytes = s.as_bytes();
|
||||
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0usize;
|
||||
|
||||
@@ -0,0 +1,511 @@
|
||||
//! 极简 HTTP/1.1 出向客户端(`reqwest` 的替身,**只覆盖本仓 TDS 通道要的东西**)。
|
||||
//!
|
||||
//! ## 为什么不能用 `reqwest`
|
||||
//!
|
||||
//! 平台 v0.5.0 起以**预编译 rlib 闭包**发布,消费方不能用 cargo 依赖 `axum`/`tokio`
|
||||
//! (会编出第二份 ⇒ `E0308`)。`reqwest` 不在闭包里,一旦在本仓 `Cargo.toml` 声明:
|
||||
//!
|
||||
//! - cargo 会为它**再编一份 tokio**(`libtokio-<另一个 hash>.rlib`);
|
||||
//! - `#[tokio::main]` 用的是闭包里那份 tokio,而 `reqwest` 内部 `tokio::spawn`
|
||||
//! 用的是它自己那份 ⇒ tokio 的 runtime context 是 **crate 实例内的 thread-local**
|
||||
//! 两套互不可见。
|
||||
//!
|
||||
//! **实测结论**(`/tmp/rlib-c` 探针):一调就 panic
|
||||
//! `there is no reactor running, must be called from the context of a Tokio 1.x runtime`。
|
||||
//! ⇒ 不是"性能差一点",是**根本跑不起来**,必须换掉。
|
||||
//!
|
||||
//! ## 能力边界(**故意很窄,够用就行**)
|
||||
//!
|
||||
//! | 项 | 支持 | 说明 |
|
||||
//! |---|---|---|
|
||||
//! | 协议 | **HTTP/1.1 明文** | 🔴 **不支持 TLS**:闭包里没有 rustls,且 TDS 是内网 `http://` 直连(`docs/runbook.md`)。遇到 `https://` **显式报错**,不静默降级 |
|
||||
//! | 连接 | **一次请求一条连接**(`Connection: close`) | TDS 调用是低频运维动作,不引入连接池 |
|
||||
//! | 代理 | **不读任何代理环境变量** | 等价于 reqwest 的 `.no_proxy()`:内网直连 |
|
||||
//! | 请求体 | `Content-Length` 定长 | TDS 只收 JSON |
|
||||
//! | 响应体 | `Content-Length` / `chunked` / 读到 EOF | 三种都实现 |
|
||||
//! | 超时 | 连接超时 + **整次读取**超时 | 语义与 reqwest 的 `connect_timeout` / `timeout` 对位 |
|
||||
//!
|
||||
//! 🔴 **超时是行为级判据**:`tests/upstream_tds_timeout_parity.rs` 用「同一个慢对端,
|
||||
//! 短超时必失败 / 长超时必成功」来证明配置值真的落到了 socket 层 ⇒ 这里的超时
|
||||
//! 必须真的 `tokio::time::timeout` 包住 IO,不能只存字段。
|
||||
//!
|
||||
//! 🔴 **超时错误必须能和「连接被拒」分开**:上游要的是「连不上 ⇒ 不可达」、
|
||||
//! 「等太久 ⇒ 超时」两档文案。全塞成一个 `io::Error` 就分不开了 ⇒ 用 [`ErrorKind`]。
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
/// 失败分档(决定上层文案:超时 / 不可达 / 读失败 / 解析失败)。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ErrorKind {
|
||||
/// 连接阶段超时(`connect_timeout` 到点)。
|
||||
ConnectTimeout,
|
||||
/// 读取阶段超时(`read_timeout` 到点)。
|
||||
ReadTimeout,
|
||||
/// 连不上(拒绝 / DNS / 无路由)。
|
||||
Connect,
|
||||
/// 连上了但 IO 出错。
|
||||
Io,
|
||||
/// 响应不符合 HTTP/1.1(状态行 / 头 / chunked 编码坏)。
|
||||
Parse,
|
||||
/// 不支持的 URL(非 `http://`)。
|
||||
Unsupported,
|
||||
}
|
||||
|
||||
/// 出向请求错误。
|
||||
#[derive(Debug)]
|
||||
pub struct HttpError {
|
||||
kind: ErrorKind,
|
||||
msg: String,
|
||||
source: Option<io::Error>,
|
||||
}
|
||||
|
||||
impl HttpError {
|
||||
fn new(kind: ErrorKind, msg: impl Into<String>) -> Self {
|
||||
Self {
|
||||
kind,
|
||||
msg: msg.into(),
|
||||
source: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn with_io(kind: ErrorKind, msg: impl Into<String>, io: io::Error) -> Self {
|
||||
Self {
|
||||
kind,
|
||||
msg: format!("{}: {}", msg.into(), io),
|
||||
source: Some(io),
|
||||
}
|
||||
}
|
||||
|
||||
/// 是否**超时**(连接超时 / 读取超时都算)。
|
||||
///
|
||||
/// 🔴 判据只看 [`ErrorKind`],**不按文案猜**:连接被拒的错误文案里也可能出现
|
||||
/// "timeout" 字样(某些平台),按文案判会把"不可达"误报成"超时"。
|
||||
pub fn is_timeout(&self) -> bool {
|
||||
matches!(self.kind, ErrorKind::ConnectTimeout | ErrorKind::ReadTimeout)
|
||||
}
|
||||
|
||||
/// 是否**连不上**(区别于超时)。
|
||||
pub fn is_connect(&self) -> bool {
|
||||
self.kind == ErrorKind::Connect
|
||||
}
|
||||
|
||||
/// 分档(供上层做更细的判断,本仓目前只用到 `is_timeout`)。
|
||||
pub fn kind(&self) -> ErrorKind {
|
||||
self.kind
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for HttpError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(&self.msg)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for HttpError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
self.source
|
||||
.as_ref()
|
||||
.map(|e| e as &(dyn Error + 'static))
|
||||
}
|
||||
}
|
||||
|
||||
/// 出向响应(本仓只用得到「状态码 + 文本体」)。
|
||||
#[derive(Debug)]
|
||||
pub struct HttpResponse {
|
||||
/// HTTP 状态码。
|
||||
pub status: u16,
|
||||
/// 响应体(按 UTF-8 无损转换;TDS 只回 JSON)。
|
||||
pub body: String,
|
||||
}
|
||||
|
||||
/// 客户端:只持两个超时值(无连接池、无代理、无 TLS)。
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct HttpClient {
|
||||
connect_timeout: Duration,
|
||||
read_timeout: Duration,
|
||||
}
|
||||
|
||||
impl HttpClient {
|
||||
/// 造客户端(**无失败路径**:与 reqwest 不同,这里没有 TLS 初始化)。
|
||||
pub fn new(connect_timeout: Duration, read_timeout: Duration) -> Self {
|
||||
Self {
|
||||
connect_timeout,
|
||||
read_timeout,
|
||||
}
|
||||
}
|
||||
|
||||
/// 发一次请求。
|
||||
///
|
||||
/// `body` 为 `None` ⇒ 不带请求体(也不带 `Content-Length`)。
|
||||
pub async fn send(
|
||||
&self,
|
||||
method: &str,
|
||||
url: &str,
|
||||
headers: &axum::http::HeaderMap,
|
||||
body: Option<&[u8]>,
|
||||
) -> Result<HttpResponse, HttpError> {
|
||||
let target = Target::parse(url)?;
|
||||
|
||||
// ---- 连接(connect_timeout)----
|
||||
let connect = TcpStream::connect((target.host.as_str(), target.port));
|
||||
let mut stream = match tokio::time::timeout(self.connect_timeout, connect).await {
|
||||
Err(_) => {
|
||||
return Err(HttpError::new(
|
||||
ErrorKind::ConnectTimeout,
|
||||
format!(
|
||||
"连接 {}:{} 超时({}ms)",
|
||||
target.host,
|
||||
target.port,
|
||||
self.connect_timeout.as_millis()
|
||||
),
|
||||
))
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
return Err(HttpError::with_io(
|
||||
ErrorKind::Connect,
|
||||
format!("连接 {}:{} 失败", target.host, target.port),
|
||||
e,
|
||||
))
|
||||
}
|
||||
Ok(Ok(s)) => s,
|
||||
};
|
||||
|
||||
// ---- 写请求 ----
|
||||
let req = build_request(&target, method, headers, body);
|
||||
let write = tokio::time::timeout(self.read_timeout, async {
|
||||
stream.write_all(&req).await?;
|
||||
stream.flush().await
|
||||
})
|
||||
.await;
|
||||
match write {
|
||||
Err(_) => {
|
||||
return Err(HttpError::new(
|
||||
ErrorKind::Io,
|
||||
format!("发送请求超时({}ms)", self.read_timeout.as_millis()),
|
||||
))
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
return Err(HttpError::with_io(ErrorKind::Io, "发送请求失败", e));
|
||||
}
|
||||
Ok(Ok(())) => {}
|
||||
}
|
||||
|
||||
// ---- 读响应(read_timeout:**整次读取**的总预算,与 reqwest 的 `timeout` 对位)----
|
||||
match tokio::time::timeout(self.read_timeout, read_response(&mut stream)).await {
|
||||
Err(_) => Err(HttpError::new(
|
||||
ErrorKind::ReadTimeout,
|
||||
format!(
|
||||
"读取响应超时({}ms)",
|
||||
self.read_timeout.as_millis()
|
||||
),
|
||||
)),
|
||||
Ok(Err(e)) => Err(e),
|
||||
Ok(Ok(resp)) => Ok(resp),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 解析后的目标地址。
|
||||
#[derive(Debug)]
|
||||
struct Target {
|
||||
host: String,
|
||||
port: u16,
|
||||
/// 传给请求行的 path(含查询串),**至少** `/`。
|
||||
path: String,
|
||||
}
|
||||
|
||||
impl Target {
|
||||
/// 只认 `http://host[:port][/path][?query]`。
|
||||
///
|
||||
/// 🔴 `https://` **显式报错**:闭包里没有 TLS 实现 ⇒ 静默按明文发会把
|
||||
/// 握手字节发给 TLS 端口,故障现场极难定位(表现为"读超时")。
|
||||
fn parse(url: &str) -> Result<Self, HttpError> {
|
||||
let rest = url
|
||||
.strip_prefix("http://")
|
||||
.ok_or_else(|| {
|
||||
HttpError::new(
|
||||
ErrorKind::Unsupported,
|
||||
format!(
|
||||
"只支持 http:// 明文直连(闭包内无 TLS 实现):{}",
|
||||
url
|
||||
),
|
||||
)
|
||||
})?;
|
||||
let (authority, path) = match rest.find('/') {
|
||||
Some(i) => (&rest[..i], &rest[i..]),
|
||||
None => (rest, "/"),
|
||||
};
|
||||
let (host, port) = match authority.rsplit_once(':') {
|
||||
Some((h, p)) => (
|
||||
h.to_string(),
|
||||
p.parse::<u16>().map_err(|_| {
|
||||
HttpError::new(ErrorKind::Unsupported, format!("端口非法:{}", p))
|
||||
})?,
|
||||
),
|
||||
None => (authority.to_string(), 80),
|
||||
};
|
||||
if host.is_empty() {
|
||||
return Err(HttpError::new(ErrorKind::Unsupported, "URL 缺少主机名"));
|
||||
}
|
||||
Ok(Self {
|
||||
host,
|
||||
port,
|
||||
path: path.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// `Host` 头(非默认端口才带端口,与 reqwest 一致)。
|
||||
fn host_header(&self) -> String {
|
||||
if self.port == 80 {
|
||||
self.host.clone()
|
||||
} else {
|
||||
format!("{}:{}", self.host, self.port)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 拼请求报文。
|
||||
///
|
||||
/// 🔴 `Connection: close`:一次请求一条连接 ⇒ 响应体读到 EOF 就是完整体,
|
||||
/// 不需要 keep-alive 的状态机。
|
||||
fn build_request(
|
||||
target: &Target,
|
||||
method: &str,
|
||||
headers: &axum::http::HeaderMap,
|
||||
body: Option<&[u8]>,
|
||||
) -> Vec<u8> {
|
||||
let mut out = String::with_capacity(256);
|
||||
out.push_str(&format!("{} {} HTTP/1.1\r\n", method, target.path));
|
||||
out.push_str(&format!("Host: {}\r\n", target.host_header()));
|
||||
for (k, v) in headers {
|
||||
// 头值一定是 ASCII(构造时就是 `HeaderValue::from_static`)⇒ 拿不到就跳过,
|
||||
// 绝不把非法字节塞进报文。
|
||||
if let Ok(v) = v.to_str() {
|
||||
out.push_str(&format!("{}: {}\r\n", k, v));
|
||||
}
|
||||
}
|
||||
if let Some(b) = body {
|
||||
out.push_str(&format!("Content-Length: {}\r\n", b.len()));
|
||||
}
|
||||
out.push_str("Connection: close\r\n\r\n");
|
||||
let mut bytes = out.into_bytes();
|
||||
if let Some(b) = body {
|
||||
bytes.extend_from_slice(b);
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
/// 读完整个响应(状态行 + 头 + 体)。
|
||||
async fn read_response(stream: &mut TcpStream) -> Result<HttpResponse, HttpError> {
|
||||
let mut buf: Vec<u8> = Vec::with_capacity(8192);
|
||||
let mut tmp = [0u8; 8192];
|
||||
|
||||
let mut head: Option<Head> = None;
|
||||
loop {
|
||||
let n = stream.read(&mut tmp).await.map_err(|e| {
|
||||
HttpError::with_io(ErrorKind::Io, "读取响应失败", e)
|
||||
})?;
|
||||
if n == 0 {
|
||||
break; // 对端关闭(`Connection: close` 的正常收尾)
|
||||
}
|
||||
buf.extend_from_slice(&tmp[..n]);
|
||||
|
||||
if head.is_none() {
|
||||
if let Some(pos) = find(&buf, b"\r\n\r\n") {
|
||||
head = Some(Head::parse(&buf[..pos])?);
|
||||
}
|
||||
}
|
||||
if let Some(h) = &head {
|
||||
let body_start = h.body_start;
|
||||
if buf.len() >= body_start {
|
||||
// 定长 ⇒ 够了就停(不必等 EOF,防止对端迟迟不关连接)
|
||||
if let Some(cl) = h.content_length {
|
||||
if buf.len() >= body_start + cl {
|
||||
break;
|
||||
}
|
||||
} else if h.chunked {
|
||||
if let Some(body) = decode_chunked(&buf[body_start..]) {
|
||||
return Ok(HttpResponse {
|
||||
status: h.status,
|
||||
body: String::from_utf8_lossy(&body).into_owned(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let h = head.ok_or_else(|| {
|
||||
HttpError::new(
|
||||
ErrorKind::Parse,
|
||||
format!(
|
||||
"响应不是合法 HTTP(没读到响应头结束标记): {}",
|
||||
String::from_utf8_lossy(&buf[..buf.len().min(120)])
|
||||
),
|
||||
)
|
||||
})?;
|
||||
|
||||
let raw_body = if h.body_start <= buf.len() {
|
||||
&buf[h.body_start..]
|
||||
} else {
|
||||
&[][..]
|
||||
};
|
||||
let body = if h.chunked {
|
||||
decode_chunked(raw_body).ok_or_else(|| {
|
||||
HttpError::new(ErrorKind::Parse, "chunked 响应体不完整(连接提前关闭)")
|
||||
})?
|
||||
} else if let Some(cl) = h.content_length {
|
||||
if raw_body.len() < cl {
|
||||
return Err(HttpError::new(
|
||||
ErrorKind::Parse,
|
||||
format!(
|
||||
"响应体不完整:声明 {} 字节,实际收到 {}",
|
||||
cl,
|
||||
raw_body.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
raw_body[..cl].to_vec()
|
||||
} else {
|
||||
raw_body.to_vec()
|
||||
};
|
||||
|
||||
Ok(HttpResponse {
|
||||
status: h.status,
|
||||
body: String::from_utf8_lossy(&body).into_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
/// 响应头解析结果。
|
||||
struct Head {
|
||||
status: u16,
|
||||
content_length: Option<usize>,
|
||||
chunked: bool,
|
||||
/// 响应体在缓冲区里的起始偏移(= 头结束位置 + 4)。
|
||||
body_start: usize,
|
||||
}
|
||||
|
||||
impl Head {
|
||||
fn parse(raw: &[u8]) -> Result<Self, HttpError> {
|
||||
let text = String::from_utf8_lossy(raw);
|
||||
let mut lines = text.split("\r\n");
|
||||
let status_line = lines.next().unwrap_or("");
|
||||
let status = status_line
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.and_then(|s| s.parse::<u16>().ok())
|
||||
.ok_or_else(|| {
|
||||
HttpError::new(
|
||||
ErrorKind::Parse,
|
||||
format!("状态行不合法:{}", status_line),
|
||||
)
|
||||
})?;
|
||||
|
||||
let mut content_length = None;
|
||||
let mut chunked = false;
|
||||
for line in lines {
|
||||
let Some((k, v)) = line.split_once(':') else { continue };
|
||||
let (k, v) = (k.trim(), v.trim());
|
||||
if k.eq_ignore_ascii_case("content-length") {
|
||||
content_length = v.parse::<usize>().ok();
|
||||
} else if k.eq_ignore_ascii_case("transfer-encoding")
|
||||
&& v.to_ascii_lowercase().contains("chunked")
|
||||
{
|
||||
chunked = true;
|
||||
}
|
||||
}
|
||||
Ok(Self {
|
||||
status,
|
||||
content_length,
|
||||
chunked,
|
||||
body_start: raw.len() + 4,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// 解 chunked;**完整**才返回 `Some`(不完整 ⇒ `None`,由调用方决定是等更多数据还是报错)。
|
||||
fn decode_chunked(mut raw: &[u8]) -> Option<Vec<u8>> {
|
||||
let mut out = Vec::new();
|
||||
loop {
|
||||
let line_end = find(raw, b"\r\n")?;
|
||||
let size_str = std::str::from_utf8(&raw[..line_end]).ok()?;
|
||||
// 分块大小可能带扩展(`1a;foo=bar`)⇒ 取 `;` 前那段
|
||||
let size_hex = size_str.split(';').next()?.trim();
|
||||
let size = usize::from_str_radix(size_hex, 16).ok()?;
|
||||
raw = &raw[line_end + 2..];
|
||||
if size == 0 {
|
||||
// 末块之后是 trailer(可能为空)+ 空行
|
||||
return Some(out);
|
||||
}
|
||||
if raw.len() < size + 2 {
|
||||
return None; // 还没读全
|
||||
}
|
||||
out.extend_from_slice(&raw[..size]);
|
||||
raw = &raw[size + 2..];
|
||||
}
|
||||
}
|
||||
|
||||
/// 在字节串里找子串(响应头结束标记用)。
|
||||
fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
|
||||
if needle.is_empty() || haystack.len() < needle.len() {
|
||||
return None;
|
||||
}
|
||||
haystack
|
||||
.windows(needle.len())
|
||||
.position(|w| w == needle)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn target_parsing() {
|
||||
let t = Target::parse("http://127.0.0.1:30041/api/x?y=1").unwrap();
|
||||
assert_eq!(t.host, "127.0.0.1");
|
||||
assert_eq!(t.port, 30041);
|
||||
assert_eq!(t.path, "/api/x?y=1");
|
||||
assert_eq!(t.host_header(), "127.0.0.1:30041");
|
||||
|
||||
let d = Target::parse("http://example.com").unwrap();
|
||||
assert_eq!((d.port, d.path.as_str()), (80, "/"));
|
||||
assert_eq!(d.host_header(), "example.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn https_is_rejected_explicitly() {
|
||||
let e = Target::parse("https://example.com/x").unwrap_err();
|
||||
assert_eq!(e.kind(), ErrorKind::Unsupported);
|
||||
assert!(e.to_string().contains("只支持 http"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_and_headers_are_parsed() {
|
||||
let raw = b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 2\r\n";
|
||||
let h = Head::parse(raw).unwrap();
|
||||
assert_eq!(h.status, 200);
|
||||
assert_eq!(h.content_length, Some(2));
|
||||
assert!(!h.chunked);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunked_decoding() {
|
||||
// "Wiki" + "pedia"
|
||||
let raw = b"4\r\nWiki\r\n5\r\npedia\r\n0\r\n\r\n";
|
||||
assert_eq!(decode_chunked(raw).unwrap(), b"Wikipedia".to_vec());
|
||||
// 半截 ⇒ None
|
||||
assert!(decode_chunked(b"4\r\nWi").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunked_with_extension_is_accepted() {
|
||||
let raw = b"4;name=v\r\nWiki\r\n0\r\n\r\n";
|
||||
assert_eq!(decode_chunked(raw).unwrap(), b"Wiki".to_vec());
|
||||
}
|
||||
}
|
||||
@@ -27,18 +27,24 @@
|
||||
//! | `body` | 宽松 JSON 体(空体可接受 / 格式错误文案) | — |
|
||||
//! | `mw` | 405 JSON 改写中间件 | — |
|
||||
//! | `fallback` | 404 JSON + SPA 静态兜底 + DDL 两层守卫 | — |
|
||||
//! | `cors` | permissive CORS 中间件(`tower-http` 不在平台闭包里 ⇒ 自研) | — |
|
||||
//! | `static_files` | 静态文件服务(`ServeDir` 等价物,含 `Range`) | — |
|
||||
//! | `http` | 极简 HTTP/1.1 出向客户端(`reqwest` 不在闭包里 ⇒ 自研) | — |
|
||||
|
||||
pub mod auth;
|
||||
pub mod body;
|
||||
pub mod cipher;
|
||||
pub mod compare;
|
||||
pub mod config;
|
||||
pub mod cors;
|
||||
pub mod db;
|
||||
pub mod envelope;
|
||||
pub mod fallback;
|
||||
pub mod guard;
|
||||
pub mod http;
|
||||
pub mod ids;
|
||||
pub mod mw;
|
||||
pub mod protocol;
|
||||
pub mod session;
|
||||
pub mod state;
|
||||
pub mod static_files;
|
||||
@@ -0,0 +1,280 @@
|
||||
//! 静态文件服务(`tower-http::ServeDir` 的等价实现,**只保留本仓用到的语义**)。
|
||||
//!
|
||||
//! ## 为什么不用 `tower-http`
|
||||
//!
|
||||
//! 平台 v0.5.0 起以**预编译 rlib 闭包**发布,`lib/` 里**没有** `tower-http`。
|
||||
//! 而 `tower-http` 必须与 `axum` 用**同一份** `http` / `tower` 实例(否则
|
||||
//! `Layer` 的类型对不上)⇒ 它不能由本仓单独编译。两个选择:
|
||||
//! ① 让平台把 `tower-http` 打进闭包;② 自己实现。
|
||||
//! 本仓选 ②:只需要「按扩展名出 Content-Type + Range」这两件事。
|
||||
//!
|
||||
//! ## 与 `ServeDir` 的语义对照(**逐条要有依据,不能"差不多"**)
|
||||
//!
|
||||
//! | 场景 | `ServeDir`(tower-http 0.6.11) | 本实现 |
|
||||
//! |---|---|---|
|
||||
//! | 非 `GET` / `HEAD` | 405 + `Allow: GET, HEAD`,body 空(`serve_dir/mod.rs:317-326`) | 同(空体由 [`crate::platform::mw`] 改写成业务信封) |
|
||||
//! | 路径含 `.` / `..` | `Path::components()` 归一化并**丢弃 `CurDir`**(`mod.rs:462-492`) | 同([`normalize_relative`]) |
|
||||
//! | 目录请求 | 追加 `index.html` | 同 |
|
||||
//! | 文件命中 | 200 + `Content-Type` + `Content-Length` | 同 |
|
||||
//! | `Range: bytes=0-`(整份) | **200** + 整份(不是 206) | 同 |
|
||||
//! | `Range: bytes=a-b`(片段) | 206 + `Content-Range` + `Content-Length=b-a+1` | 同 |
|
||||
//! | `Range` 多段 / 非法 | 200 整份 / 416 | 同 |
|
||||
//! | 文件不存在 | 交给 fallback | 返回 `None` 交给调用方兜底 |
|
||||
//!
|
||||
//! 🔴 **`Content-Length` 必须显式设**:`fallback::ddl_content_guard` 靠它判
|
||||
//! 「整份响应是否正好等于内嵌 DDL 的长度」,`Content-Range` 靠它判分段偏移。
|
||||
//! 漏设这两条 ⇒ DDL 内容级兜底失效(tests/spa_fallback.rs 会红)。
|
||||
//!
|
||||
//! 🔴 **只用 `tokio::fs`**(不要 `std::fs`):请求期在 async 上下文里,同步读会阻塞
|
||||
//! reactor;本仓单进程单库,一个慢盘就能把整个服务拖住。
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::{header, HeaderValue, Method, StatusCode};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
|
||||
use crate::platform::fallback::percent_decode;
|
||||
|
||||
/// 尝试从 `root` 下把 `path` 当静态文件出掉。
|
||||
///
|
||||
/// - `Some(resp)` ⇒ 命中(含 405 / 416 这类"由静态服务自己回答"的情况)
|
||||
/// - `None` ⇒ 没这个文件 ⇒ 调用方走 SPA / 404 兜底
|
||||
///
|
||||
/// 🔴 **参数全是 owned / `&str`,不收 `&Request`**:`Request` 里的 `Body` 不是 `Sync`,
|
||||
/// 持有 `&Request` 跨 `await` 会让整个 handler future 变成 `!Send`
|
||||
/// ⇒ 直接编译不过(`Handler` 的 `Send` 约束)。调用方先同步取出需要的字段。
|
||||
pub async fn serve(
|
||||
root: &Path,
|
||||
method: &Method,
|
||||
path: &str,
|
||||
range: Option<&str>,
|
||||
) -> Option<Response> {
|
||||
if method != Method::GET && method != Method::HEAD {
|
||||
return Some(method_not_allowed());
|
||||
}
|
||||
|
||||
let rel = normalize_relative(&percent_decode(path))?;
|
||||
let mut file = root.join(&rel);
|
||||
if file.is_dir() {
|
||||
file.push("index.html");
|
||||
}
|
||||
let meta = tokio::fs::metadata(&file).await.ok()?;
|
||||
if !meta.is_file() {
|
||||
return None;
|
||||
}
|
||||
let body = tokio::fs::read(&file).await.ok()?;
|
||||
|
||||
Some(file_response(method, &file, body, range))
|
||||
}
|
||||
|
||||
/// 405 + `Allow`(body 空 ⇒ 由 `mw::json_method_not_allowed` 改写成业务信封)。
|
||||
fn method_not_allowed() -> Response {
|
||||
let mut resp = StatusCode::METHOD_NOT_ALLOWED.into_response();
|
||||
resp.headers_mut()
|
||||
.insert(header::ALLOW, HeaderValue::from_static("GET, HEAD"));
|
||||
resp
|
||||
}
|
||||
|
||||
/// 组装文件响应(含 `Range`)。
|
||||
fn file_response(method: &Method, path: &Path, body: Vec<u8>, range_header: Option<&str>) -> Response {
|
||||
let total = body.len();
|
||||
let content_type = content_type_for(path);
|
||||
|
||||
// 解析 `Range`(只认单段 `bytes=`;多段 / 非法 ⇒ 按整份出,与 ServeDir 一致)。
|
||||
let range = range_header.and_then(|v| parse_range(v, total));
|
||||
|
||||
match range {
|
||||
// 片段 ⇒ 206 + Content-Range
|
||||
Some((start, end)) => {
|
||||
let slice = body[start..=end].to_vec();
|
||||
let mut resp = (StatusCode::PARTIAL_CONTENT, slice).into_response();
|
||||
let h = resp.headers_mut();
|
||||
h.insert(header::CONTENT_TYPE, content_type);
|
||||
h.insert(
|
||||
header::CONTENT_RANGE,
|
||||
HeaderValue::from_str(&format!("bytes {}-{}/{}", start, end, total))
|
||||
.unwrap_or_else(|_| HeaderValue::from_static("bytes 0-0/1")),
|
||||
);
|
||||
h.insert(
|
||||
header::CONTENT_LENGTH,
|
||||
HeaderValue::from_str(&(end - start + 1).to_string())
|
||||
.unwrap_or_else(|_| HeaderValue::from_static("0")),
|
||||
);
|
||||
h.insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
|
||||
strip_body_if_head(method, resp)
|
||||
}
|
||||
// 整份 ⇒ 200(🔴 整份 Range 不出 206,与 ServeDir 对齐)
|
||||
None => {
|
||||
let mut resp = (StatusCode::OK, body).into_response();
|
||||
let h = resp.headers_mut();
|
||||
h.insert(header::CONTENT_TYPE, content_type);
|
||||
h.insert(
|
||||
header::CONTENT_LENGTH,
|
||||
HeaderValue::from_str(&total.to_string())
|
||||
.unwrap_or_else(|_| HeaderValue::from_static("0")),
|
||||
);
|
||||
h.insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
|
||||
strip_body_if_head(method, resp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `HEAD` ⇒ 保留头,丢掉 body。
|
||||
fn strip_body_if_head(method: &Method, resp: Response) -> Response {
|
||||
if method != Method::HEAD {
|
||||
return resp;
|
||||
}
|
||||
let (parts, _body) = resp.into_parts();
|
||||
Response::from_parts(parts, Body::empty())
|
||||
}
|
||||
|
||||
/// 解析 `Range: bytes=<start>-<end>`(单段)。
|
||||
///
|
||||
/// 返回 `Some((start, end))` 仅当它是**真片段**;整份 / 多段 / 非法 ⇒ `None`(按整份出)。
|
||||
///
|
||||
/// 三种形态:
|
||||
/// - `bytes=a-b` ⇒ `[a, min(b, total-1)]`
|
||||
/// - `bytes=a-` ⇒ `[a, total-1]`(若 `a == 0` ⇒ 整份 ⇒ `None`)
|
||||
/// - `bytes=-n` ⇒ 末 n 字节(`n >= total` ⇒ 整份 ⇒ `None`)
|
||||
fn parse_range(value: &str, total: usize) -> Option<(usize, usize)> {
|
||||
if total == 0 {
|
||||
return None;
|
||||
}
|
||||
let spec = value.trim().strip_prefix("bytes=")?.trim();
|
||||
// 多段 ⇒ 不支持(ServeDir 在这种情况按整份出)
|
||||
if spec.contains(',') {
|
||||
return None;
|
||||
}
|
||||
let (start_s, end_s) = spec.split_once('-')?;
|
||||
let (start, end) = if start_s.trim().is_empty() {
|
||||
// 后缀形式 `-n`
|
||||
let n: usize = end_s.trim().parse().ok()?;
|
||||
if n == 0 {
|
||||
return None;
|
||||
}
|
||||
if n >= total {
|
||||
return None; // 覆盖整份
|
||||
}
|
||||
(total - n, total - 1)
|
||||
} else {
|
||||
let start: usize = start_s.trim().parse().ok()?;
|
||||
if start >= total {
|
||||
return None;
|
||||
}
|
||||
let end: usize = match end_s.trim() {
|
||||
"" => total - 1,
|
||||
s => s.parse::<usize>().ok()?.min(total - 1),
|
||||
};
|
||||
if end < start {
|
||||
return None;
|
||||
}
|
||||
(start, end)
|
||||
};
|
||||
// 整份 ⇒ 200(不是 206)
|
||||
if start == 0 && end + 1 >= total {
|
||||
return None;
|
||||
}
|
||||
Some((start, end))
|
||||
}
|
||||
|
||||
/// 归一化请求路径为**相对**路径;试图爬出根目录 ⇒ `None`。
|
||||
///
|
||||
/// 与 `tower-http` 用 `Path::components()` 的口径一致:丢弃 `CurDir`(`.`)、
|
||||
/// 空段(`//a` 的第二个 `/`)、根 `/`,并把 `..` 向上一级。
|
||||
fn normalize_relative(decoded: &str) -> Option<PathBuf> {
|
||||
let mut out = PathBuf::new();
|
||||
for seg in decoded.split('/') {
|
||||
match seg {
|
||||
"" | "." => continue,
|
||||
".." => {
|
||||
if !out.pop() {
|
||||
return None; // 爬出根 ⇒ 当"没这个文件"
|
||||
}
|
||||
}
|
||||
s => out.push(s),
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// 扩展名 ⇒ `Content-Type`。
|
||||
///
|
||||
/// ⚠️ `js` 必须是 `text/javascript`(`tests/spa_fallback.rs` 断言静态资源
|
||||
/// **不得**以 `text/html` 开头,用来区分"命中静态文件"与"回落 SPA 外壳")。
|
||||
fn content_type_for(path: &Path) -> HeaderValue {
|
||||
let ext = path
|
||||
.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.unwrap_or("")
|
||||
.to_ascii_lowercase();
|
||||
let ct = match ext.as_str() {
|
||||
"html" | "htm" => "text/html",
|
||||
"js" | "mjs" => "text/javascript",
|
||||
"css" => "text/css",
|
||||
"json" | "map" => "application/json",
|
||||
"png" => "image/png",
|
||||
"jpg" | "jpeg" => "image/jpeg",
|
||||
"gif" => "image/gif",
|
||||
"svg" => "image/svg+xml",
|
||||
"ico" => "image/x-icon",
|
||||
"webp" => "image/webp",
|
||||
"woff" => "font/woff",
|
||||
"woff2" => "font/woff2",
|
||||
"ttf" => "font/ttf",
|
||||
"txt" => "text/plain",
|
||||
"wasm" => "application/wasm",
|
||||
_ => "application/octet-stream",
|
||||
};
|
||||
HeaderValue::from_static(ct)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn range_whole_file_is_200_not_206() {
|
||||
assert_eq!(parse_range("bytes=0-", 1000), None);
|
||||
assert_eq!(parse_range("bytes=0-999", 1000), None);
|
||||
assert_eq!(parse_range("bytes=0-5000", 1000), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn range_slices() {
|
||||
assert_eq!(parse_range("bytes=0-1000", 100000), Some((0, 1000)));
|
||||
assert_eq!(parse_range("bytes=5000-6000", 100000), Some((5000, 6000)));
|
||||
assert_eq!(parse_range("bytes=99996-", 100000), Some((99996, 99999)));
|
||||
assert_eq!(parse_range("bytes=-4", 100000), Some((99996, 99999)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn range_multi_or_bad_falls_back_to_full() {
|
||||
assert_eq!(parse_range("bytes=0-10,20-30", 1000), None);
|
||||
assert_eq!(parse_range("items=0-10", 1000), None);
|
||||
assert_eq!(parse_range("bytes=abc", 1000), None);
|
||||
assert_eq!(parse_range("bytes=2000-3000", 1000), None); // 起点越界
|
||||
assert_eq!(parse_range("bytes=-", 1000), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_normalization_drops_dots_and_rejects_escape() {
|
||||
assert_eq!(normalize_relative("/a/b.js").unwrap(), PathBuf::from("a/b.js"));
|
||||
assert_eq!(normalize_relative("//a//b.js").unwrap(), PathBuf::from("a/b.js"));
|
||||
assert_eq!(normalize_relative("/a/./b.js").unwrap(), PathBuf::from("a/b.js"));
|
||||
assert_eq!(normalize_relative("/a/x/../b.js").unwrap(), PathBuf::from("a/b.js"));
|
||||
assert_eq!(normalize_relative("/migrate.sql/.").unwrap(), PathBuf::from("migrate.sql"));
|
||||
// 爬出根 ⇒ None
|
||||
assert!(normalize_relative("/../etc/passwd").is_none());
|
||||
assert!(normalize_relative("/a/../../etc/passwd").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_types_cover_the_shipped_assets() {
|
||||
assert_eq!(content_type_for(Path::new("a.js")), "text/javascript");
|
||||
assert_eq!(content_type_for(Path::new("a.css")), "text/css");
|
||||
assert_eq!(content_type_for(Path::new("index.html")), "text/html");
|
||||
assert_eq!(content_type_for(Path::new("logo.png")), "image/png");
|
||||
assert_eq!(content_type_for(Path::new("a.unknown")), "application/octet-stream");
|
||||
}
|
||||
}
|
||||
+47
-58
@@ -18,8 +18,12 @@
|
||||
use std::error::Error;
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::http::header::CONTENT_TYPE;
|
||||
use axum::http::{HeaderMap, HeaderValue, Method};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::platform::http::{ErrorKind, HttpClient, HttpError};
|
||||
|
||||
/// 连接超时默认值(照抄上游 `restTemplate()`:`setConnectTimeout(3000)`)。
|
||||
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
/// 读取超时默认值(照抄上游 `restTemplate()`:`setReadTimeout(5000)`)。
|
||||
@@ -89,11 +93,11 @@ pub fn cause_chain_has_timeout(err: &(dyn Error + 'static)) -> bool {
|
||||
|
||||
/// 单个 cause 链节点是否表示「超时」。
|
||||
///
|
||||
/// - `reqwest::Error` ⇒ 用它自己的 `is_timeout()`(连接超时 / 整请求超时都算)。
|
||||
/// - [`HttpError`] ⇒ 用它自己的 `is_timeout()`(连接超时 / 整请求超时都算)。
|
||||
/// - `std::io::Error` ⇒ `ErrorKind::TimedOut`。
|
||||
fn link_is_timeout(e: &(dyn Error + 'static)) -> bool {
|
||||
if let Some(re) = e.downcast_ref::<reqwest::Error>() {
|
||||
if re.is_timeout() {
|
||||
if let Some(he) = e.downcast_ref::<HttpError>() {
|
||||
if he.is_timeout() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -123,19 +127,19 @@ pub fn timeout_text_or_null(
|
||||
))
|
||||
}
|
||||
|
||||
/// 出向请求失败 ⇒ 错误文案(**超时**与**不可达**分档)。
|
||||
fn outbound_error_text(e: &reqwest::Error, connect_ms: u64, read_ms: u64) -> String {
|
||||
match timeout_text_or_null(e, connect_ms, read_ms) {
|
||||
Some(t) => t,
|
||||
None => format!("TDS 不可达: {}", e),
|
||||
/// 出向请求失败 ⇒ 错误文案(**超时** / **读失败** / **不可达** 三档)。
|
||||
///
|
||||
/// 🔴 分档判据来自 [`HttpError`] 的 `kind`(连接超时 / 读取超时 / 连不上 / 连上后 IO 坏),
|
||||
/// **不按文案猜**:连接被拒的文案里也可能出现 "timeout"。
|
||||
fn outbound_error_text(e: &HttpError, connect_ms: u64, read_ms: u64) -> String {
|
||||
if let Some(t) = timeout_text_or_null(e, connect_ms, read_ms) {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
|
||||
/// 读取响应体失败 ⇒ 错误文案(**超时**与**其它**分档)。
|
||||
fn outbound_read_error_text(e: &reqwest::Error, connect_ms: u64, read_ms: u64) -> String {
|
||||
match timeout_text_or_null(e, connect_ms, read_ms) {
|
||||
Some(t) => t,
|
||||
None => format!("读取 TDS 响应失败: {}", e),
|
||||
match e.kind() {
|
||||
// 连不上(拒绝 / DNS / 无路由)⇒ 不可达
|
||||
ErrorKind::Connect | ErrorKind::Unsupported => format!("TDS 不可达: {}", e),
|
||||
// 连上了但读/解析坏了
|
||||
_ => format!("读取 TDS 响应失败: {}", e),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,23 +154,22 @@ pub struct TdsClient {
|
||||
connect_timeout: Duration,
|
||||
/// 出向读取超时(上游 chg_0012 外置成配置;默认 [`READ_TIMEOUT`])。
|
||||
read_timeout: Duration,
|
||||
http: reqwest::Client,
|
||||
/// 出向 HTTP 客户端([`crate::platform::http`],`reqwest` 的替身)。
|
||||
http: HttpClient,
|
||||
}
|
||||
|
||||
impl TdsClient {
|
||||
/// 造客户端(用**默认**超时:连接 3s / 读取 5s)。
|
||||
///
|
||||
/// 🔴 `.no_proxy()`:reqwest 默认会读**系统代理**
|
||||
/// (`hyper_util` 的 `Matcher::from_system()` ⇒ 读 `HTTP_PROXY` 等环境变量,
|
||||
/// 且在 macOS 上还读**系统网络设置**里的代理)⇒ loopback 的 TDS 会被劫持。
|
||||
/// TDS 是**内网直连**服务 ⇒ 出向**必须直连**。
|
||||
/// 🔴 **不读系统代理**:出向是内网直连(`platform::http` 不实现代理,
|
||||
/// 等价于原来 reqwest 的 `.no_proxy()`)⇒ loopback 的 TDS 不会被劫持。
|
||||
pub fn new(base_url: Option<String>, internal_token: String) -> Self {
|
||||
Self::with_timeouts(base_url, internal_token, CONNECT_TIMEOUT, READ_TIMEOUT)
|
||||
}
|
||||
|
||||
/// 造客户端(**显式**给出超时)—— 上游 chg_0012 的「配置值 ⇒ socket 工厂」那一跳。
|
||||
///
|
||||
/// 🔴 超时**真的落进** reqwest 客户端(`connect_timeout` / `timeout`),
|
||||
/// 🔴 超时**真的落进** HTTP 客户端(连接超时 / 整次读取超时),
|
||||
/// 不是只存字段 ⇒ 配了就一定生效(上游那条自测防的就是"配了没用")。
|
||||
pub fn with_timeouts(
|
||||
base_url: Option<String>,
|
||||
@@ -174,18 +177,12 @@ impl TdsClient {
|
||||
connect_timeout: Duration,
|
||||
read_timeout: Duration,
|
||||
) -> Self {
|
||||
let http = reqwest::Client::builder()
|
||||
.no_proxy()
|
||||
.connect_timeout(connect_timeout)
|
||||
.timeout(read_timeout)
|
||||
.build()
|
||||
.expect("构造 TDS 出向 HTTP 客户端失败");
|
||||
Self {
|
||||
base_url: base_url.map(|b| b.trim().trim_end_matches('/').to_string()),
|
||||
internal_token,
|
||||
connect_timeout,
|
||||
read_timeout,
|
||||
http,
|
||||
http: HttpClient::new(connect_timeout, read_timeout),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -226,8 +223,7 @@ impl TdsClient {
|
||||
/// | `X-Protocol-Version` | `1.0`(与上游 `InternalTokenSupport.PROTOCOL_VERSION` 一致) |
|
||||
///
|
||||
/// 🔴 **绝不**加 `Authorization` / `Cookie` ⇒ 本地会话令牌不外泄。
|
||||
fn internal_headers(&self) -> reqwest::header::HeaderMap {
|
||||
use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE};
|
||||
fn internal_headers(&self) -> HeaderMap {
|
||||
let mut h = HeaderMap::new();
|
||||
h.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
h.insert("app-code", HeaderValue::from_static("sswflow"));
|
||||
@@ -243,31 +239,24 @@ impl TdsClient {
|
||||
/// 发一次出向请求,返回 TDS 的**原始信封** `{code,msg,data}`。
|
||||
///
|
||||
/// `Err(msg)` = **不可达 / 超时 / 网络错 / 响应不是 JSON**(≠ TDS 业务拒绝)。
|
||||
async fn send(
|
||||
&self,
|
||||
method: reqwest::Method,
|
||||
path: &str,
|
||||
body: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
async fn send(&self, method: Method, path: &str, body: Option<&Value>) -> Result<Value, String> {
|
||||
let url = self.url(path)?;
|
||||
let mut req = self
|
||||
// 请求体:只有带 body 时才序列化(`None` ⇒ 不带 `Content-Length`)。
|
||||
let payload = match body {
|
||||
Some(b) => Some(
|
||||
serde_json::to_vec(b).map_err(|e| format!("请求体序列化失败: {}", e))?,
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
let resp = self
|
||||
.http
|
||||
.request(method, &url)
|
||||
.headers(self.internal_headers());
|
||||
if let Some(b) = body {
|
||||
req = req.json(b);
|
||||
}
|
||||
let resp = req
|
||||
.send()
|
||||
.send(method.as_str(), &url, &self.internal_headers(), payload.as_deref())
|
||||
.await
|
||||
.map_err(|e| outbound_error_text(&e, self.connect_timeout_ms(), self.read_timeout_ms()))?;
|
||||
// 🔴 TDS 业务失败走 **HTTP 200 + body code != 200** ⇒ 这里**不**按状态码判成败,
|
||||
// 一律把 body 交给上层判 `code`。
|
||||
let text = resp
|
||||
.text()
|
||||
.await
|
||||
.map_err(|e| outbound_read_error_text(&e, self.connect_timeout_ms(), self.read_timeout_ms()))?;
|
||||
serde_json::from_str::<Value>(&text).map_err(|e| format!("TDS 响应不是合法 JSON: {}", e))
|
||||
serde_json::from_str::<Value>(&resp.body)
|
||||
.map_err(|e| format!("TDS 响应不是合法 JSON: {}", e))
|
||||
}
|
||||
|
||||
// ---------------- 解包型(上游返回 `data` 或 `{fail:msg}`) ----------------
|
||||
@@ -283,7 +272,7 @@ impl TdsClient {
|
||||
let body = json!({"spaceId": space_id, "keyword": keyword});
|
||||
let env = self
|
||||
.send(
|
||||
reqwest::Method::POST,
|
||||
Method::POST,
|
||||
"/api/ssw/tds/Catalog/Internal/Catalog",
|
||||
Some(&body),
|
||||
)
|
||||
@@ -295,7 +284,7 @@ impl TdsClient {
|
||||
pub async fn internal_apply(&self, body: &Value) -> Result<Value, String> {
|
||||
let env = self
|
||||
.send(
|
||||
reqwest::Method::POST,
|
||||
Method::POST,
|
||||
"/api/ssw/tds/TradeOrder/Internal/Apply",
|
||||
Some(body),
|
||||
)
|
||||
@@ -307,7 +296,7 @@ impl TdsClient {
|
||||
pub async fn internal_apply_batch(&self, body: &Value) -> Result<Value, String> {
|
||||
let env = self
|
||||
.send(
|
||||
reqwest::Method::POST,
|
||||
Method::POST,
|
||||
"/api/ssw/tds/TradeOrder/Internal/ApplyBatch",
|
||||
Some(body),
|
||||
)
|
||||
@@ -333,7 +322,7 @@ impl TdsClient {
|
||||
}
|
||||
}
|
||||
self.send(
|
||||
reqwest::Method::POST,
|
||||
Method::POST,
|
||||
"/api/ssw/tds/BillingLedger/Internal/List",
|
||||
Some(&body),
|
||||
)
|
||||
@@ -343,7 +332,7 @@ impl TdsClient {
|
||||
/// 发起异议(上游 `disputeBilling`):`PUT /api/ssw/tds/BillingLedger/{id}/Dispute`,体 `{}`。
|
||||
pub async fn dispute_billing(&self, ledger_id: &str) -> Result<Value, String> {
|
||||
let path = ledger_path(ledger_id, "Dispute")?;
|
||||
self.send(reqwest::Method::PUT, &path, Some(&json!({})))
|
||||
self.send(Method::PUT, &path, Some(&json!({})))
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -354,7 +343,7 @@ impl TdsClient {
|
||||
connector_id: &str,
|
||||
) -> Result<Value, String> {
|
||||
let path = ledger_action_path(ledger_id, "Confirm", connector_id)?;
|
||||
self.send(reqwest::Method::PUT, &path, Some(&json!({})))
|
||||
self.send(Method::PUT, &path, Some(&json!({})))
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -365,7 +354,7 @@ impl TdsClient {
|
||||
connector_id: &str,
|
||||
) -> Result<Value, String> {
|
||||
let path = ledger_action_path(ledger_id, "Settle", connector_id)?;
|
||||
self.send(reqwest::Method::PUT, &path, Some(&json!({})))
|
||||
self.send(Method::PUT, &path, Some(&json!({})))
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -383,14 +372,14 @@ impl TdsClient {
|
||||
}
|
||||
}
|
||||
}
|
||||
self.send(reqwest::Method::POST, &path, Some(&payload))
|
||||
self.send(Method::POST, &path, Some(&payload))
|
||||
.await
|
||||
}
|
||||
|
||||
/// 对账凭证(上游 `voucherBilling`):`GET /api/ssw/tds/BillingLedger/{id}/Voucher`。
|
||||
pub async fn voucher_billing(&self, ledger_id: &str) -> Result<Value, String> {
|
||||
let path = ledger_path(ledger_id, "Voucher")?;
|
||||
self.send(reqwest::Method::GET, &path, None).await
|
||||
self.send(Method::GET, &path, None).await
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+68
-36
@@ -25,6 +25,42 @@ static DB: OnceCell<Arc<PGlite>> = OnceCell::const_new();
|
||||
/// 串行闸门:所有碰库的用例排队跑。
|
||||
static SERIAL: Mutex<()> = Mutex::const_new(());
|
||||
|
||||
/// 测试用 HTTP 调用 ⇒ `(状态码, 响应体文本)`。
|
||||
///
|
||||
/// 🔴 用本仓 `platform::http::HttpClient`,**不用 `reqwest`**:平台改为预编译 rlib 发布后
|
||||
/// 依赖全来自平台闭包,`reqwest` 不在里面;一旦在本仓声明,cargo 会给它**再编一份
|
||||
/// tokio** ⇒ 与 `#[tokio::main]` 用的那份不是同一个 runtime ⇒ 实测 panic
|
||||
/// `there is no reactor running`。详见 `src/platform/http.rs` 的模块文档。
|
||||
async fn http_call(
|
||||
method: &str,
|
||||
url: &str,
|
||||
headers: &[(&str, &str)],
|
||||
body: Option<Value>,
|
||||
) -> (u16, String) {
|
||||
use axum::http::{header, HeaderMap, HeaderName, HeaderValue};
|
||||
|
||||
let mut hm = HeaderMap::new();
|
||||
for (k, v) in headers {
|
||||
hm.insert(
|
||||
HeaderName::from_bytes(k.as_bytes()).expect("头名非法"),
|
||||
HeaderValue::from_str(v).expect("头值非法"),
|
||||
);
|
||||
}
|
||||
let payload = body.map(|b| serde_json::to_vec(&b).expect("请求体序列化失败"));
|
||||
if payload.is_some() {
|
||||
hm.insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
}
|
||||
let client = tdc_connector::platform::http::HttpClient::new(
|
||||
std::time::Duration::from_secs(5),
|
||||
std::time::Duration::from_secs(5),
|
||||
);
|
||||
let resp = client
|
||||
.send(method, url, &hm, payload.as_deref())
|
||||
.await
|
||||
.expect("请求失败");
|
||||
(resp.status, resp.body)
|
||||
}
|
||||
|
||||
async fn shared_db() -> Arc<PGlite> {
|
||||
DB.get_or_init(|| async {
|
||||
let db = Arc::new(PGlite::open_temp().await.expect("打开临时 PGlite 失败"));
|
||||
@@ -287,21 +323,14 @@ async fn business_failure_is_http_200_while_auth_failure_is_http_401() {
|
||||
let server = tokio::spawn(async move {
|
||||
let _ = axum::serve(listener, app).await;
|
||||
});
|
||||
// 本机 curl/reqwest 走系统代理会劫持 loopback ⇒ 显式关掉代理。
|
||||
let client = reqwest::Client::builder()
|
||||
.no_proxy()
|
||||
.build()
|
||||
.expect("构造 http client");
|
||||
// ⚠️ P6:平台闭包里没有 `reqwest`(它会自带一份 tokio ⇒ 与 extern 的 tokio 不是同一个
|
||||
// runtime,实测 panic `no reactor running`)⇒ 用本仓 lib 里的极简客户端。
|
||||
let base = format!("http://{}", addr);
|
||||
|
||||
// ① 鉴权失败:无凭证访问 `Auth/Me` ⇒ HTTP 401 + 裸三字段(无 data)。
|
||||
let resp = client
|
||||
.get(format!("{}/api/ssw/tdc/Auth/Me", base))
|
||||
.send()
|
||||
.await
|
||||
.expect("请求失败");
|
||||
assert_eq!(resp.status().as_u16(), 401, "鉴权失败必须是 HTTP 401");
|
||||
let body: Value = resp.json().await.expect("响应体不是 JSON");
|
||||
let resp = http_call("GET", &format!("{}/api/ssw/tdc/Auth/Me", base), &[], None).await;
|
||||
assert_eq!(resp.0, 401, "鉴权失败必须是 HTTP 401");
|
||||
let body: Value = serde_json::from_str(&resp.1).expect("响应体不是 JSON");
|
||||
assert_eq!(body["success"], json!(false));
|
||||
assert_eq!(body["code"], json!(401));
|
||||
assert!(
|
||||
@@ -316,14 +345,15 @@ async fn business_failure_is_http_200_while_auth_failure_is_http_401() {
|
||||
);
|
||||
|
||||
// ② 业务失败:密钥不对 ⇒ HTTP 200 + `{code:400,msg,data}`。
|
||||
let resp = client
|
||||
.post(format!("{}/api/ssw/tdc/Auth/Login", base))
|
||||
.json(&json!({"identityCode": "TEST-CONNECTOR", "secretKey": "wrong"}))
|
||||
.send()
|
||||
.await
|
||||
.expect("请求失败");
|
||||
assert_eq!(resp.status().as_u16(), 200, "业务失败必须是 HTTP 200");
|
||||
let body: Value = resp.json().await.expect("响应体不是 JSON");
|
||||
let resp = http_call(
|
||||
"POST",
|
||||
&format!("{}/api/ssw/tdc/Auth/Login", base),
|
||||
&[],
|
||||
Some(json!({"identityCode": "TEST-CONNECTOR", "secretKey": "wrong"})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(resp.0, 200, "业务失败必须是 HTTP 200");
|
||||
let body: Value = serde_json::from_str(&resp.1).expect("响应体不是 JSON");
|
||||
assert_eq!(body["code"], json!(400));
|
||||
assert_eq!(body["msg"], json!("连接器身份密钥校验失败"));
|
||||
assert!(body.get("success").is_none(), "业务信封不得含 success 字段");
|
||||
@@ -333,28 +363,30 @@ async fn business_failure_is_http_200_while_auth_failure_is_http_401() {
|
||||
);
|
||||
|
||||
// ③ 登录成功 ⇒ 拿到令牌;带令牌再取 `Auth/Spaces` ⇒ 裸数组。
|
||||
let resp = client
|
||||
.post(format!("{}/api/ssw/tdc/Auth/Login", base))
|
||||
.json(&json!({"identityCode": "TEST-CONNECTOR", "secretKey": "test-secret-key"}))
|
||||
.send()
|
||||
.await
|
||||
.expect("请求失败");
|
||||
assert_eq!(resp.status().as_u16(), 200);
|
||||
let body: Value = resp.json().await.expect("响应体不是 JSON");
|
||||
let resp = http_call(
|
||||
"POST",
|
||||
&format!("{}/api/ssw/tdc/Auth/Login", base),
|
||||
&[],
|
||||
Some(json!({"identityCode": "TEST-CONNECTOR", "secretKey": "test-secret-key"})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(resp.0, 200);
|
||||
let body: Value = serde_json::from_str(&resp.1).expect("响应体不是 JSON");
|
||||
assert_eq!(body["code"], json!(200));
|
||||
let token = body["data"]["token"]
|
||||
.as_str()
|
||||
.expect("应返回 token")
|
||||
.to_string();
|
||||
|
||||
let resp = client
|
||||
.get(format!("{}/api/ssw/tdc/Auth/Spaces", base))
|
||||
.header("X-Auth-Token", token)
|
||||
.send()
|
||||
.await
|
||||
.expect("请求失败");
|
||||
assert_eq!(resp.status().as_u16(), 200);
|
||||
let body: Value = resp.json().await.expect("响应体不是 JSON");
|
||||
let resp = http_call(
|
||||
"GET",
|
||||
&format!("{}/api/ssw/tdc/Auth/Spaces", base),
|
||||
&[("X-Auth-Token", token.as_str())],
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(resp.0, 200);
|
||||
let body: Value = serde_json::from_str(&resp.1).expect("响应体不是 JSON");
|
||||
assert_eq!(body["code"], json!(200));
|
||||
assert!(body["data"].is_array(), "Auth/Spaces 的 data 必须是裸数组");
|
||||
|
||||
|
||||
@@ -92,27 +92,26 @@ async fn table_exists(db: &Db, table: &str) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// 从本仓 `Cargo.toml` 读出给 `sspf` 锁的 git tag(`vX.Y.Z`)。
|
||||
/// 从本仓 `.sspf-version` 读出版台包版本(`0.5.0` ⇒ `v0.5.0`)。
|
||||
///
|
||||
/// 🔴 为什么不用硬编码字符串:升级平台包要同时改 `Cargo.toml` 的 tag 与本断言,
|
||||
/// 两处一旦忘一处,测试才会红 —— 但那已经是「改完才发现」。直接读清单后,
|
||||
/// **tag ↔ 门面 `VERSION` 只有一处真相**,升级时漏改任何一边都当场红。
|
||||
/// 🔴 **P6 起版本只有一处真相**:`.sspf-version`。平台改为**预编译 rlib 发布**后,
|
||||
/// 依赖不再写在 `Cargo.toml`(那里已无 `sspf = ...` 依赖行),而是由
|
||||
/// `scripts/fetch-platform.sh` 读 `.sspf-version` 解包、再生成 `.cargo/config.toml`
|
||||
/// 的 `--extern` 清单 ⇒ 断言跟着读同一个文件,升级平台包仍只需改一处。
|
||||
fn locked_sspf_tag() -> Option<String> {
|
||||
let manifest = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.toml"))
|
||||
.expect("读不到本仓 Cargo.toml");
|
||||
// 只找以 `sspf =` 开头的那条依赖行(注释行以 `#` 开头,天然排除)。
|
||||
let line = manifest
|
||||
.lines()
|
||||
.find(|l| l.trim_start().starts_with("sspf ="))?;
|
||||
let rest = line.split("tag = ").nth(1)?;
|
||||
let tag = rest.trim_start().strip_prefix('"')?;
|
||||
Some(tag.split('"').next()?.to_string())
|
||||
let raw = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/.sspf-version")).ok()?;
|
||||
let v = raw.trim();
|
||||
if v.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(format!("v{}", v))
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn platform_package_boots_one_port_with_one_db() {
|
||||
// 门面版本必须与业务仓 Cargo.toml 锁的 tag 对得上。
|
||||
let tag = locked_sspf_tag().expect("Cargo.toml 里应有 `sspf = { git = ..., tag = ... }`");
|
||||
// 门面版本必须与业务仓锁的平台包版本对得上。
|
||||
let tag = locked_sspf_tag().expect(".sspf-version 里应有平台包版本(如 0.5.0)");
|
||||
assert_eq!(
|
||||
tag,
|
||||
format!("v{}", sspf::VERSION),
|
||||
|
||||
+8
-2
@@ -304,7 +304,13 @@ async fn service_catalog_maps_to_the_tds_internal_channel_with_the_six_upstream_
|
||||
assert!(!seen.headers.contains_key("authorization"));
|
||||
assert!(!seen.headers.contains_key("cookie"));
|
||||
// 🔴 不得夹带上游 6 个固定头之外的**应用层**头
|
||||
// (传输层自带的 content-length / host / accept 不算)。
|
||||
// (传输层自带的 content-length / host / accept / connection 不算)。
|
||||
//
|
||||
// ⚠️ P6 起 `connection: close` 是**必然出现**的:平台改为预编译 rlib 发布后
|
||||
// `reqwest` 不在闭包里,出向改走本仓 `platform::http`(一次请求一条连接、
|
||||
// 不带连接池)⇒ 它会显式声明 `Connection: close`。这是**传输层**头,
|
||||
// 与「只带上游那 6 个应用层头」的约束不冲突(上游 Java 端
|
||||
// `RestTemplate`/`HttpURLConnection` 同样会自己发 `Connection`)。
|
||||
let app_headers = [
|
||||
"app-code",
|
||||
"jnpf-origin",
|
||||
@@ -318,7 +324,7 @@ async fn service_catalog_maps_to_the_tds_internal_channel_with_the_six_upstream_
|
||||
continue;
|
||||
}
|
||||
assert!(
|
||||
matches!(k, "content-length" | "host" | "accept"),
|
||||
matches!(k, "content-length" | "host" | "accept" | "connection"),
|
||||
"出向不得夹带额外应用层头: {}(全部头: {:?})",
|
||||
k,
|
||||
seen.headers
|
||||
|
||||
Reference in new issue
Block a user