- 新增 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 只编本仓
204 lines
8.2 KiB
Rust
204 lines
8.2 KiB
Rust
//! P1 接入探针 —— 业务仓只靠 `sspf` 门面就能起一个「单端口 + 单库」的服务。
|
||
//!
|
||
//! 🔴 pglite 是**进程级单例** ⇒ 本文件只允许一个 `#[tokio::test]`。
|
||
//! 想加断言就加在这一个函数里,别新开测试(第二个 `PGlite::open()` 会直接失败)。
|
||
//!
|
||
//! 🔴 这条测试**不改** tdc 自研装配(`src/main.rs` 仍走老链),验的是「平台包在
|
||
//! 业务仓里可用」:`Platform` builder 能编译、能开库、能注入 tdc 风格的 DDL 与
|
||
//! 自定义路由、面 B 全套仍在、示例业务包不会跟着进门。这是 P1 换装配的前置判据。
|
||
|
||
use std::path::PathBuf;
|
||
use std::sync::{Arc, Mutex};
|
||
|
||
use axum::routing::get;
|
||
use serde_json::Value;
|
||
use sspf::{Config, Db, Platform};
|
||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||
use tokio::net::{TcpListener, TcpStream};
|
||
|
||
/// 注入的业务建表 SQL(tdc 风格列名)。走 `Platform::ddl` 建进**同一个 `Db`**。
|
||
const PROBE_DDL: &str = r#"
|
||
CREATE TABLE IF NOT EXISTS p1_probe_item (
|
||
f_id VARCHAR(36) NOT NULL,
|
||
f_title VARCHAR(200),
|
||
f_tenant_id VARCHAR(36) DEFAULT '0' NOT NULL,
|
||
PRIMARY KEY (f_id, f_tenant_id)
|
||
)
|
||
"#;
|
||
|
||
/// 模拟 tdc 的一条自定义业务端点(不依赖平台状态)。
|
||
async fn ping() -> &'static str {
|
||
"pong"
|
||
}
|
||
|
||
/// 起一个监听,返回端口。
|
||
async fn serve(app: axum::Router) -> u16 {
|
||
let listener = TcpListener::bind("127.0.0.1:0")
|
||
.await
|
||
.expect("绑定本地端口失败");
|
||
let port = listener.local_addr().expect("取本地地址失败").port();
|
||
let server = tokio::spawn(async move {
|
||
let _ = axum::serve(listener, app).await;
|
||
});
|
||
tokio::task::yield_now().await;
|
||
// 🔴 服务要活到测试结束(drop JoinHandle 会 abort 掉 task)。
|
||
std::mem::forget(server);
|
||
port
|
||
}
|
||
|
||
/// 发一次请求,返回 `(状态码, JSON body)`。`body` 为空 ⇒ GET。
|
||
async fn http(port: u16, method: &str, path: &str, body: &str) -> (u16, Value) {
|
||
let req = if body.is_empty() {
|
||
format!("{method} {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n")
|
||
} else {
|
||
format!(
|
||
"{method} {path} HTTP/1.1\r\n\
|
||
Host: 127.0.0.1\r\n\
|
||
Content-Type: application/x-www-form-urlencoded\r\n\
|
||
Content-Length: {}\r\n\
|
||
Connection: close\r\n\r\n{body}",
|
||
body.len()
|
||
)
|
||
};
|
||
let mut stream = TcpStream::connect(("127.0.0.1", port))
|
||
.await
|
||
.expect("连接失败");
|
||
stream.write_all(req.as_bytes()).await.expect("写请求失败");
|
||
let mut buf = Vec::new();
|
||
tokio::time::timeout(std::time::Duration::from_secs(20), stream.read_to_end(&mut buf))
|
||
.await
|
||
.expect("读响应超时")
|
||
.expect("读响应失败");
|
||
let text = String::from_utf8_lossy(&buf).to_string();
|
||
let (head, body) = text.split_once("\r\n\r\n").expect("响应必须有头体分隔");
|
||
let status = head
|
||
.lines()
|
||
.next()
|
||
.and_then(|l| l.split_whitespace().nth(1))
|
||
.and_then(|s| s.parse::<u16>().ok())
|
||
.expect("响应首行必须是 HTTP/1.1 <code> ...");
|
||
(status, serde_json::from_str(body.trim()).unwrap_or(Value::Null))
|
||
}
|
||
|
||
/// 某张表在 `public` schema 里存在吗(走平台自己的 `Db`,不新开库)。
|
||
async fn table_exists(db: &Db, table: &str) -> bool {
|
||
let sql = format!(
|
||
"SELECT count(*) FROM information_schema.tables \
|
||
WHERE table_schema = 'public' AND table_name = '{table}'"
|
||
);
|
||
match db.scalar_text(&sql).await.ok().flatten() {
|
||
Some(n) => n.trim() != "0",
|
||
None => false,
|
||
}
|
||
}
|
||
|
||
/// 从本仓 `.sspf-version` 读出版台包版本(`0.5.0` ⇒ `v0.5.0`)。
|
||
///
|
||
/// 🔴 **P6 起版本只有一处真相**:`.sspf-version`。平台改为**预编译 rlib 发布**后,
|
||
/// 依赖不再写在 `Cargo.toml`(那里已无 `sspf = ...` 依赖行),而是由
|
||
/// `scripts/fetch-platform.sh` 读 `.sspf-version` 解包、再生成 `.cargo/config.toml`
|
||
/// 的 `--extern` 清单 ⇒ 断言跟着读同一个文件,升级平台包仍只需改一处。
|
||
fn locked_sspf_tag() -> Option<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() {
|
||
// 门面版本必须与业务仓锁的平台包版本对得上。
|
||
let tag = locked_sspf_tag().expect(".sspf-version 里应有平台包版本(如 0.5.0)");
|
||
assert_eq!(
|
||
tag,
|
||
format!("v{}", sspf::VERSION),
|
||
"业务仓锁的 tag 必须与门面 VERSION 一致(改 Cargo.toml 忘改 tag 会在这里红)"
|
||
);
|
||
|
||
// ---- 配置:临时库(进程级单例 ⇒ 全文件只有这一个测试)----
|
||
let mut config = Config::from_env(PathBuf::from("/tmp/tdc-p1-platform-probe"));
|
||
config.pg_dir = PathBuf::from("memory://");
|
||
config.seed_admin_password = "123456".to_string();
|
||
|
||
// `on_ready` 是业务仓拿 `AppState`(同一个库)的唯一公开途径。
|
||
let slot: Arc<Mutex<Option<Db>>> = Arc::new(Mutex::new(None));
|
||
let slot_in_hook = slot.clone();
|
||
|
||
let app = Platform::new()
|
||
.config(config)
|
||
.ddl("p1_probe_item", PROBE_DDL)
|
||
// tdc 的 132 条自定义端点将来就从这里整体注入(形状 `/api/ssw/tdc/**`)。
|
||
.router(axum::Router::new().route("/api/ssw/tdc/P1Probe", get(ping)))
|
||
.on_ready(move |state| {
|
||
let slot = slot_in_hook.clone();
|
||
async move {
|
||
*slot.lock().expect("钩子里的锁不该中毒") = Some((*state.db).clone());
|
||
Ok(())
|
||
}
|
||
})
|
||
.build_app()
|
||
.await
|
||
.expect("业务仓必须能只靠 sspf 起一个 app");
|
||
|
||
let port = serve(app).await;
|
||
|
||
// ---- ① 平台端点活着,平台表已建(不是空库)----
|
||
let (status, health) = http(port, "GET", "/api/health", "").await;
|
||
assert_eq!(status, 200, "GET /api/health 必须 200");
|
||
assert_eq!(health["ok"], true, "health 必须 ok: {health}");
|
||
let tables = health["tables"].as_u64().expect("health 必须带 tables");
|
||
assert!(tables > 100, "平台表没建起来(tables={tables})");
|
||
|
||
// ---- ② 注入的业务 DDL 建进了**同一个库** ----
|
||
let db = slot
|
||
.lock()
|
||
.expect("锁不该中毒")
|
||
.clone()
|
||
.expect("on_ready 必须跑过(拿不到 Db ⇒ 启动钩子没执行)");
|
||
assert!(
|
||
table_exists(&db, "p1_probe_item").await,
|
||
"Platform::ddl 建的表必须落在同一个库里"
|
||
);
|
||
|
||
// ---- ③ 平台包里零业务:示例包的表与路由都不该出现 ----
|
||
for table in ["demo_item", "shop_product", "book_shop_book", "asset_data_resource"] {
|
||
assert!(
|
||
!table_exists(&db, table).await,
|
||
"示例包的表 {table} 不该存在 —— 门面默认不注入任何业务包"
|
||
);
|
||
}
|
||
let (status, body) = http(port, "GET", "/api/demo/DemoItem", "").await;
|
||
assert_eq!(status, 404, "示例包的路由不该注册: {body}");
|
||
|
||
// ---- ④ JNPF 兼容面(面 B)仍在:官方登录形状必须 200 ----
|
||
let enc = sspf::cipher::encrypt_password("123456");
|
||
let (status, body) = http(
|
||
port,
|
||
"POST",
|
||
"/api/oauth/Login",
|
||
&format!("account=admin&password={enc}"),
|
||
)
|
||
.await;
|
||
assert_eq!(status, 200, "面 B 登录必须 200: {body}");
|
||
assert_eq!(body["code"], 200, "登录必须成功(种子 admin 已就位): {body}");
|
||
assert!(
|
||
body["data"]["token"].as_str().is_some_and(|t| !t.is_empty()),
|
||
"登录必须返回 token: {body}"
|
||
);
|
||
|
||
// ---- ⑤ 注入的业务端点与平台端点**同一个端口** ----
|
||
let (status, body) = http(port, "GET", "/api/ssw/tdc/P1Probe", "").await;
|
||
assert_eq!(status, 200, "注入的业务端点必须 200: {body}");
|
||
|
||
// ---- ⑥ 表数不随请求变化(同一个库、同一个装配)----
|
||
let (_, again) = http(port, "GET", "/api/health", "").await;
|
||
assert_eq!(
|
||
again["tables"].as_u64().expect("health 必须带 tables"),
|
||
tables,
|
||
"表数不该随请求变化"
|
||
);
|
||
}
|