style: 修 3 处历史 rustfmt 违规 + 边界③ 端口冲突改「打印 + exit 1」
- tests/{auth_flow,bootstrap_fail,crud_engine}.rs:仅格式化(语义零改动)
- main.rs:TcpListener::bind 的 unwrap 换成明确的错误文案 + exit 1,不再抛 panic 回溯
Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
1 parent
7f76cce56e
commit
2ba0b74e89
4 files changed
+144
-30
No files matched your search
+47
-1
@@ -212,6 +212,52 @@ async fn main() {
|
||||
"NOOP"
|
||||
}
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
|
||||
// 🔴 边界③:端口冲突不再 panic(回溯对运维无意义)⇒ 打印一句人话 + 退出码 1。
|
||||
let listener = match tokio::net::TcpListener::bind(addr).await {
|
||||
Ok(l) => l,
|
||||
Err(e) => {
|
||||
eprintln!("[tdc-connector] {}", bind_failure_message(&addr, &e));
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
}
|
||||
|
||||
/// 端口绑定失败的文案(**纯函数** ⇒ 可单测)。
|
||||
///
|
||||
/// 🔴 边界③:原先是 `TcpListener::bind(addr).await.unwrap()`
|
||||
/// ⇒ 端口被占用时进程 panic,抛一坨 Rust 回溯给运维看。
|
||||
/// 这里改成「打印一句人话 + exit 1」。
|
||||
///
|
||||
/// ⚠️ 文案里**不得**含任何敏感信息(只含地址与操作系统错误码)。
|
||||
fn bind_failure_message(addr: &std::net::SocketAddr, err: &std::io::Error) -> String {
|
||||
format!(
|
||||
"无法绑定监听地址 {}:{}。请确认该端口未被占用,或用 PORT=<其它端口> 重新启动。",
|
||||
addr, err
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::bind_failure_message;
|
||||
use std::net::SocketAddr;
|
||||
|
||||
#[test]
|
||||
fn bind_failure_message_names_the_address_and_the_cause() {
|
||||
let addr: SocketAddr = "127.0.0.1:30000".parse().unwrap();
|
||||
let err = std::io::Error::new(std::io::ErrorKind::AddrInUse, "Address already in use");
|
||||
let msg = bind_failure_message(&addr, &err);
|
||||
assert!(msg.contains("127.0.0.1:30000"), "文案应含监听地址:{}", msg);
|
||||
assert!(msg.contains("Address already in use"), "文案应含系统错误:{}", msg);
|
||||
assert!(msg.contains("PORT="), "文案应给出改端口的办法:{}", msg);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bind_failure_message_carries_no_secret_material() {
|
||||
let addr: SocketAddr = "0.0.0.0:30000".parse().unwrap();
|
||||
let err = std::io::Error::other("boom");
|
||||
let msg = bind_failure_message(&addr, &err);
|
||||
assert!(!msg.contains("token"), "文案不得含令牌字样:{}", msg);
|
||||
assert!(!msg.contains("password"), "文案不得含口令字样:{}", msg);
|
||||
}
|
||||
}
|
||||
+48
-13
@@ -131,7 +131,9 @@ async fn login_rejects_unknown_identity_and_wrong_secret() {
|
||||
|
||||
let resp = identity::login(
|
||||
State(state.clone()),
|
||||
Some(axum::Json(json!({"identityCode": "NOPE", "secretKey": "x"}))),
|
||||
Some(axum::Json(
|
||||
json!({"identityCode": "NOPE", "secretKey": "x"}),
|
||||
)),
|
||||
)
|
||||
.await;
|
||||
let body = body_of(resp).await;
|
||||
@@ -140,15 +142,20 @@ async fn login_rejects_unknown_identity_and_wrong_secret() {
|
||||
|
||||
let resp = identity::login(
|
||||
State(state.clone()),
|
||||
Some(axum::Json(json!({"identityCode": "TEST-CONNECTOR", "secretKey": "wrong"}))),
|
||||
Some(axum::Json(
|
||||
json!({"identityCode": "TEST-CONNECTOR", "secretKey": "wrong"}),
|
||||
)),
|
||||
)
|
||||
.await;
|
||||
let body = body_of(resp).await;
|
||||
assert_eq!(body["code"], 400);
|
||||
assert_eq!(body["msg"], "连接器身份密钥校验失败");
|
||||
|
||||
let resp = identity::login(State(state.clone()), Some(axum::Json(json!({"secretKey": "x"}))))
|
||||
.await;
|
||||
let resp = identity::login(
|
||||
State(state.clone()),
|
||||
Some(axum::Json(json!({"secretKey": "x"}))),
|
||||
)
|
||||
.await;
|
||||
let body = body_of(resp).await;
|
||||
assert_eq!(body["msg"], "identityCode 必填");
|
||||
}
|
||||
@@ -161,12 +168,17 @@ async fn login_succeeds_and_me_returns_identity_without_secret() {
|
||||
|
||||
let resp = identity::login(
|
||||
State(state.clone()),
|
||||
Some(axum::Json(json!({"identityCode": "TEST-CONNECTOR", "secretKey": "test-secret-key"}))),
|
||||
Some(axum::Json(
|
||||
json!({"identityCode": "TEST-CONNECTOR", "secretKey": "test-secret-key"}),
|
||||
)),
|
||||
)
|
||||
.await;
|
||||
let body = body_of(resp).await;
|
||||
assert_eq!(body["code"], 200);
|
||||
let token = body["data"]["token"].as_str().expect("应返回 token").to_string();
|
||||
let token = body["data"]["token"]
|
||||
.as_str()
|
||||
.expect("应返回 token")
|
||||
.to_string();
|
||||
assert_eq!(body["data"]["identityCode"], "TEST-CONNECTOR");
|
||||
|
||||
// 会话可查
|
||||
@@ -249,10 +261,15 @@ async fn business_failure_is_http_200_while_auth_failure_is_http_401() {
|
||||
sessions: sessions.clone(),
|
||||
};
|
||||
let app: Router = build_router(state.clone())
|
||||
.layer(axum::middleware::from_fn_with_state(auth_state, auth_middleware))
|
||||
.layer(axum::middleware::from_fn_with_state(
|
||||
auth_state,
|
||||
auth_middleware,
|
||||
))
|
||||
.with_state(state);
|
||||
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.expect("绑定端口");
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("绑定端口");
|
||||
let addr = listener.local_addr().expect("读本地地址");
|
||||
let server = tokio::spawn(async move {
|
||||
let _ = axum::serve(listener, app).await;
|
||||
@@ -265,13 +282,25 @@ async fn business_failure_is_http_200_while_auth_failure_is_http_401() {
|
||||
let base = format!("http://{}", addr);
|
||||
|
||||
// ① 鉴权失败:无凭证访问 `Auth/Me` ⇒ HTTP 401 + 裸三字段(无 data)。
|
||||
let resp = client.get(format!("{}/api/ssw/tdc/Auth/Me", base)).send().await.expect("请求失败");
|
||||
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");
|
||||
assert_eq!(body["success"], json!(false));
|
||||
assert_eq!(body["code"], json!(401));
|
||||
assert!(body.get("data").is_none(), "鉴权失败 body 不得含 data:{}", body);
|
||||
assert_eq!(body.as_object().unwrap().len(), 3, "鉴权失败 body 恰好三个键");
|
||||
assert!(
|
||||
body.get("data").is_none(),
|
||||
"鉴权失败 body 不得含 data:{}",
|
||||
body
|
||||
);
|
||||
assert_eq!(
|
||||
body.as_object().unwrap().len(),
|
||||
3,
|
||||
"鉴权失败 body 恰好三个键"
|
||||
);
|
||||
|
||||
// ② 业务失败:密钥不对 ⇒ HTTP 200 + `{code:400,msg,data}`。
|
||||
let resp = client
|
||||
@@ -285,7 +314,10 @@ async fn business_failure_is_http_200_while_auth_failure_is_http_401() {
|
||||
assert_eq!(body["code"], json!(400));
|
||||
assert_eq!(body["msg"], json!("连接器身份密钥校验失败"));
|
||||
assert!(body.get("success").is_none(), "业务信封不得含 success 字段");
|
||||
assert!(body.get("data").is_some(), "业务信封带 data 键(此处为 null)");
|
||||
assert!(
|
||||
body.get("data").is_some(),
|
||||
"业务信封带 data 键(此处为 null)"
|
||||
);
|
||||
|
||||
// ③ 登录成功 ⇒ 拿到令牌;带令牌再取 `Auth/Spaces` ⇒ 裸数组。
|
||||
let resp = client
|
||||
@@ -297,7 +329,10 @@ async fn business_failure_is_http_200_while_auth_failure_is_http_401() {
|
||||
assert_eq!(resp.status().as_u16(), 200);
|
||||
let body: Value = resp.json().await.expect("响应体不是 JSON");
|
||||
assert_eq!(body["code"], json!(200));
|
||||
let token = body["data"]["token"].as_str().expect("应返回 token").to_string();
|
||||
let token = body["data"]["token"]
|
||||
.as_str()
|
||||
.expect("应返回 token")
|
||||
.to_string();
|
||||
|
||||
let resp = client
|
||||
.get(format!("{}/api/ssw/tdc/Auth/Spaces", base))
|
||||
|
||||
@@ -14,7 +14,9 @@ use tdc_connector::state::{AppState, BootstrapIdentity};
|
||||
#[tokio::test]
|
||||
async fn bootstrap_insert_failure_yields_no_secret() {
|
||||
let db = Arc::new(PGlite::open_temp().await.expect("打开临时 PGlite 失败"));
|
||||
tdc_connector::db::ensure_schema(db.as_ref()).await.expect("建表失败");
|
||||
tdc_connector::db::ensure_schema(db.as_ref())
|
||||
.await
|
||||
.expect("建表失败");
|
||||
// 让 INSERT 必然失败:把目标表删掉
|
||||
// (`PGlite::exec(&self, sql: &str)` 是无参版本;带参的是 `query(sql, &[&(dyn ToSql + Sync)])`)
|
||||
db.exec("DROP TABLE tdc_identity").await.expect("删表失败");
|
||||
|
||||
+46
-15
@@ -98,7 +98,10 @@ async fn product_crud_roundtrip() {
|
||||
assert_eq!(body["msg"], "新增成功");
|
||||
let id = body["data"].as_str().expect("应返回 id").to_string();
|
||||
assert!(!id.is_empty());
|
||||
assert!(id.chars().all(|c| c.is_ascii_digit()), "id 应是雪花号十进制串");
|
||||
assert!(
|
||||
id.chars().all(|c| c.is_ascii_digit()),
|
||||
"id 应是雪花号十进制串"
|
||||
);
|
||||
|
||||
// 列表(关键字)
|
||||
let mut params = HashMap::new();
|
||||
@@ -183,12 +186,25 @@ async fn readonly_and_guarded_entities_reject_writes() {
|
||||
|
||||
// AuditLog:允许写,但不许改/删
|
||||
let spec = registry::find("AuditLog").unwrap();
|
||||
let resp = crud::create(&state, spec, &json!({"action": "LOGIN"}), Some(&principal())).await;
|
||||
let resp = crud::create(
|
||||
&state,
|
||||
spec,
|
||||
&json!({"action": "LOGIN"}),
|
||||
Some(&principal()),
|
||||
)
|
||||
.await;
|
||||
let body = body_of(resp).await;
|
||||
assert_eq!(body["code"], 200, "审计日志允许 HTTP 写入:{}", body);
|
||||
let id = body["data"].as_str().unwrap().to_string();
|
||||
|
||||
let resp = crud::update(&state, spec, &id, &json!({"action": "X"}), Some(&principal())).await;
|
||||
let resp = crud::update(
|
||||
&state,
|
||||
spec,
|
||||
&id,
|
||||
&json!({"action": "X"}),
|
||||
Some(&principal()),
|
||||
)
|
||||
.await;
|
||||
let body = body_of(resp).await;
|
||||
assert_eq!(body["code"], 400);
|
||||
assert_eq!(body["msg"], "审计日志不允许修改");
|
||||
@@ -449,7 +465,10 @@ async fn missing_required_field_is_a_business_failure_not_a_500() {
|
||||
);
|
||||
// 🔴 `body["data"].is_null()` 对**缺失键**也恒真 ⇒ 必须显式断言「键存在且值为 null」
|
||||
let obj = body.as_object().expect("响应体应是对象");
|
||||
assert!(obj.contains_key("data"), "失败响应须带 data 键(值为 null)");
|
||||
assert!(
|
||||
obj.contains_key("data"),
|
||||
"失败响应须带 data 键(值为 null)"
|
||||
);
|
||||
assert_eq!(
|
||||
obj.get("data"),
|
||||
Some(&Value::Null),
|
||||
@@ -479,7 +498,13 @@ async fn audit_actor_comes_from_the_login_principal() {
|
||||
assert_eq!(body["data"]["actorName"], "张三");
|
||||
|
||||
// 连接器身份会话 ⇒ CONNECTOR / 身份 id / 身份码
|
||||
let resp = crud::create(&state, spec, &json!({"action": "LOGIN"}), Some(&principal())).await;
|
||||
let resp = crud::create(
|
||||
&state,
|
||||
spec,
|
||||
&json!({"action": "LOGIN"}),
|
||||
Some(&principal()),
|
||||
)
|
||||
.await;
|
||||
let body = body_of(resp).await;
|
||||
assert_eq!(body["code"], 200, "{}", body);
|
||||
let id = body["data"].as_str().unwrap().to_string();
|
||||
@@ -513,7 +538,10 @@ async fn contract_delete_reports_missing_before_the_delete_guard() {
|
||||
let resp = crud::delete(&state, spec, "NO-SUCH-ID", Some(&principal())).await;
|
||||
let body = body_of(resp).await;
|
||||
assert_eq!(body["code"], 400, "不存在的 id ⇒ 业务失败:{}", body);
|
||||
assert_eq!(body["msg"], "记录不存在或已删除", "存在性判定须先于禁删守卫");
|
||||
assert_eq!(
|
||||
body["msg"], "记录不存在或已删除",
|
||||
"存在性判定须先于禁删守卫"
|
||||
);
|
||||
|
||||
// 存在的 Contract 行 ⇒ 禁删文案(上游原文,逐字)
|
||||
{
|
||||
@@ -532,8 +560,7 @@ async fn contract_delete_reports_missing_before_the_delete_guard() {
|
||||
let body = body_of(resp).await;
|
||||
assert_eq!(body["code"], 400, "合约恒拒删:{}", body);
|
||||
assert_eq!(
|
||||
body["msg"],
|
||||
"本地合约副本不可删除(权威归档在平台,副本仅随空间/合约清退联动)",
|
||||
body["msg"], "本地合约副本不可删除(权威归档在平台,副本仅随空间/合约清退联动)",
|
||||
"禁删文案须逐字等于上游原文"
|
||||
);
|
||||
}
|
||||
@@ -552,9 +579,17 @@ async fn contract_delete_reports_missing_before_the_delete_guard() {
|
||||
async fn registry_declares_per_entity_code_retry_policy() {
|
||||
let expected = [
|
||||
("Product", 5u32, "产品编码生成失败(连续 5 次撞库),请重试"),
|
||||
("Resource", 5u32, "资源编码生成失败(连续 5 次撞库),请重试"),
|
||||
(
|
||||
"Resource",
|
||||
5u32,
|
||||
"资源编码生成失败(连续 5 次撞库),请重试",
|
||||
),
|
||||
("DataInterface", 3u32, "接口编码生成失败(重试 3 次仍冲突)"),
|
||||
("Datasource", 3u32, "系统标识生成失败(连续 3 次撞库),请重试"),
|
||||
(
|
||||
"Datasource",
|
||||
3u32,
|
||||
"系统标识生成失败(连续 3 次撞库),请重试",
|
||||
),
|
||||
];
|
||||
for (api, retries, fail_msg) in expected {
|
||||
let codes = registry::create_codes(api);
|
||||
@@ -597,11 +632,7 @@ async fn product_code_sequence_starts_at_baseline_plus_one() {
|
||||
// 这里数「当日同前缀的行数」(**建完第 1 条之后**的计数 = 基线 + 1):
|
||||
// 序号必须**正好等于**它 ⇒ 把 `used + 1 + i` 的 `+1` 钉死。
|
||||
// (`PRODUCT_LOCK` 保证此刻没有别的用例在写 `tdc_product` ⇒ 计数确定。)
|
||||
let day = code1
|
||||
.split('-')
|
||||
.nth(1)
|
||||
.expect("编码应含日期段")
|
||||
.to_string();
|
||||
let day = code1.split('-').nth(1).expect("编码应含日期段").to_string();
|
||||
let count = count_today_products(&state, &format!("PRO-{}-%", day)).await;
|
||||
assert_eq!(
|
||||
seq_of(&code1, "PRO"),
|
||||
|
||||
Reference in new issue
Block a user