**影响** - 生产档弱密钥守卫从「只比默认值」升级为上游 `ProdGuard` 的**六条判据**(纯函数), 弱令牌用「默认值加后缀」绕过、弱标记词、长度下限三类都拦得住;`CIPHER_KEY`(协议共享值)**不受管**。 - 出向 TDS 超时**外置到 env**(`SSW_TDS_CONNECT_TIMEOUT_MS` / `SSW_TDS_READ_TIMEOUT_MS`), 且**只有 cause 链里真有超时**才改写文案 ⇒ 连接被拒 / DNS 失败不再被误报成「超时」(排查方向不被带偏)。 - 上游 15 个测试类全部**登记在册**:3 个已移植(29 条对位用例)、12 个判定超范围(逐条记理由)。 - 新增第五把尺子 `scripts/check-upstream-tests.sh`:台账 ⇄ 代码 ⇄ 上游测试类集合三向对账, 上游新增测试类而台账没登记 ⇒ **红**(不靠"记得看"防漂移)。 - 回归网:`cargo test` 246 → **278**(+32),其余四把尺子与引用自检**全绿**。 **改动** - `src/platform/guard.rs`(新):上游 `ProdGuard.violations` 的纯函数移植(弱值清单 / 弱标记词整体词匹配 / `MIN_LEN=12` / 逐条点名)。 - `src/platform/config.rs`:`check_secret_guard` 改走守卫判据;新增 `guard_values`(只放本部署真有的键) 与出向超时两项配置(非法值回落默认,不让连接器起不来)。 - `src/tdc/client/tds.rs`:新增 `cause_chain_has_timeout` / `timeout_text_or_null`(cause 链遍历**有界** `depth<16`), `TdsClient::with_timeouts` 接受超时。 - `tests/upstream_guard_parity.rs`(新 · 19 条)+ `tests/upstream_tds_timeout_parity.rs`(新 · 10 条)。 - `scripts/upstream-test-ledger.tsv`(台账真源)+ `scripts/upstream-test-census.py`(上游测试类普查/对账) + `scripts/check-upstream-tests.sh`(第五把尺子)。 - 文档:`docs/UPSTREAM-TEST-PARITY.md`(新)+ `docs/known-limitations.md` L8 + `docs/decisions.md` D22/D23 + `CLAUDE.md` 同步(尺子表 / 目录树 / 命令速查 / 实现细节 22–23 / 坑位表)。 **设计** - 上游 hop 1 的「反射读 socket 工厂」**抄不了**(`reqwest::Client` 不暴露超时 getter)⇒ 改用**行为级**判别 (同一延迟 TCP 服务器:短超时⇒超时错、长超时⇒成功)⇒ 结论等价且更强(真跑 socket 层)。 - 上游 `*SelfTest.java` **surefire 不跑**(无统一入口)⇒ 判据落成 `cargo test` 常规用例(纯函数 ⇒ 可离线断言)。 - 超范围判定原则:**本仓没有对应功能 ⇒ 不搬**(硬搬只会是假绿);「机制」已覆盖的(P2P 那条)按机制记账。 Co-Authored-By: Claude Code <[email protected]>
316 lines
12 KiB
Rust
316 lines
12 KiB
Rust
//! **上游测试用例移植**:出向调用的超时配置与错误文案
|
||
//! (上游 `ProviderInvokeTimeoutsSelfTest` 的两跳)。
|
||
//!
|
||
//! ## 上游真源(只读克隆)
|
||
//!
|
||
//! | 上游 | 路径 | 关键断言 |
|
||
//! |---|---|---|
|
||
//! | `ssw.tdc.client.ProviderInvokeTimeoutsSelfTest` | `/tmp/sswtdc-probe/boot/ssw-tdc/ssw-tdc-biz/src/test/java/ssw/tdc/client/ProviderInvokeTimeoutsSelfTest.java` | 第 1 跳(配置值 ⇒ socket 工厂)· 第 2 跳(异常 ⇒ 文案),共 9 条 |
|
||
//! | `ssw.tdc.client.ProviderInvokeClient` | `/tmp/sswtdc-probe/boot/ssw-tdc/ssw-tdc-biz/src/main/java/ssw/tdc/client/ProviderInvokeClient.java` | `restTemplate()`(超时落进 socket 工厂)· `timeoutTextOrNull`(有界 cause 链) |
|
||
//!
|
||
//! ## 两跳的对应关系
|
||
//!
|
||
//! | 上游 | 本仓 | 为什么这么落 |
|
||
//! |---|---|---|
|
||
//! | 第 1 跳:反射读 `SimpleClientHttpRequestFactory` 的 `connectTimeout` / `readTimeout` | [`TdsClient::connect_timeout_ms`] / [`TdsClient::read_timeout_ms`] + **行为级**判别性用例 | Rust 的 `reqwest::Client` **不暴露**超时(无 getter)⇒ 反射那一跳**无法照搬** ⇒ 改成「配置值落进客户端」+「**行为**随配置变」(短超时⇒超时、长超时⇒成功)⇒ 结论等价且更强 |
|
||
//! | 第 2 跳:`timeoutTextOrNull(e, CT, RT)` 只在 cause 链里有 `SocketTimeoutException` 时改写 | [`cause_chain_has_timeout`] + [`timeout_text_or_null`] | Java 靠**异常类型**判;Rust 无同构类型 ⇒ 判据落到「`reqwest::Error::is_timeout()` 或 cause 链里有 `io::Error(TimedOut)`」⇒ 语义等价 |
|
||
|
||
use std::error::Error;
|
||
use std::fmt;
|
||
use std::io::{ErrorKind, Read, Write};
|
||
use std::net::TcpListener;
|
||
use std::time::Duration;
|
||
|
||
use tdc_connector::tdc::client::tds::{
|
||
cause_chain_has_timeout, timeout_text_or_null, TdsClient, MAX_CAUSE_DEPTH,
|
||
};
|
||
|
||
/// 上游测试里用的两个注入值(**故意不用默认值** ⇒ "写死"与"生效"分得开)。
|
||
const CT: u64 = 3000;
|
||
const RT: u64 = 8000;
|
||
|
||
/// 造一个 cause 为 `io::Error(TimedOut)` 的错误(上游 `SocketTimeoutException` 的对位物)。
|
||
fn timeout_error(msg: &str) -> std::io::Error {
|
||
std::io::Error::new(ErrorKind::TimedOut, msg.to_string())
|
||
}
|
||
|
||
/// 造一个 cause 为 `io::Error(ConnectionRefused)` 的错误(上游 `ConnectException` 的对位物)。
|
||
fn refused_error(msg: &str) -> std::io::Error {
|
||
std::io::Error::new(ErrorKind::ConnectionRefused, msg.to_string())
|
||
}
|
||
|
||
/// 造一个 cause 为 `io::Error(NotFound)` 的错误(上游 `UnknownHostException` 的对位物)。
|
||
fn dns_error(msg: &str) -> std::io::Error {
|
||
std::io::Error::new(ErrorKind::NotFound, msg.to_string())
|
||
}
|
||
|
||
/// 无 cause 的错误(上游 `new ResourceAccessException("boom")` 的对位物)。
|
||
#[derive(Debug)]
|
||
struct NoCause(&'static str);
|
||
|
||
impl fmt::Display for NoCause {
|
||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||
write!(f, "{}", self.0)
|
||
}
|
||
}
|
||
|
||
impl Error for NoCause {
|
||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||
None
|
||
}
|
||
}
|
||
|
||
/// 包装一层(模拟「cause 链被再包一层」)。
|
||
#[derive(Debug)]
|
||
struct Wrap<E: Error + 'static>(E);
|
||
|
||
impl<E: Error + 'static> fmt::Display for Wrap<E> {
|
||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||
write!(f, "wrapped: {}", self.0)
|
||
}
|
||
}
|
||
|
||
impl<E: Error + 'static> Error for Wrap<E> {
|
||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||
Some(&self.0)
|
||
}
|
||
}
|
||
|
||
/// 递归的 cause 链(用来造「很深」的链,验证遍历**有界**)。
|
||
#[derive(Debug)]
|
||
enum Chain {
|
||
Leaf(std::io::Error),
|
||
Node(Box<Chain>),
|
||
}
|
||
|
||
impl fmt::Display for Chain {
|
||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||
write!(f, "chain")
|
||
}
|
||
}
|
||
|
||
impl Error for Chain {
|
||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||
match self {
|
||
Chain::Leaf(e) => Some(e),
|
||
Chain::Node(inner) => Some(inner.as_ref()),
|
||
}
|
||
}
|
||
}
|
||
|
||
// ============================================================================
|
||
// 第 2 跳:异常 ⇒ 文案(上游 `ProviderInvokeTimeoutsSelfTest:86-139`)
|
||
// ============================================================================
|
||
|
||
/// 上游 ①(`:94`):**read 超时** ⇒ 文案含「调用提供方超时」+ 点名 connect / read 当前值。
|
||
#[test]
|
||
fn hop2_read_timeout_is_rewritten_and_names_current_values() {
|
||
let e = Wrap(timeout_error("Read timed out"));
|
||
let text = timeout_text_or_null(&e, CT, RT).expect("read 超时必须改写文案");
|
||
assert!(
|
||
text.contains("调用 TDS 超时"),
|
||
"文案须说明是超时,实得:{}",
|
||
text
|
||
);
|
||
assert!(text.contains(&CT.to_string()), "文案须点名 connect 当前值:{}", text);
|
||
assert!(text.contains(&RT.to_string()), "文案须点名 read 当前值:{}", text);
|
||
}
|
||
|
||
/// 上游 ②(`:105`):**connect 超时** ⇒ 也判超时。
|
||
#[test]
|
||
fn hop2_connect_timeout_is_rewritten() {
|
||
let e = Wrap(timeout_error("Connect timed out"));
|
||
let text = timeout_text_or_null(&e, CT, RT).expect("connect 超时必须改写文案");
|
||
assert!(text.contains("调用 TDS 超时"), "实得:{}", text);
|
||
}
|
||
|
||
/// 上游 ③(`:112`):🔴 **连接被拒** ⇒ **不得**被标成超时(否则"不可达"被误报成"超时")。
|
||
#[test]
|
||
fn hop2_connection_refused_is_not_rewritten() {
|
||
let e = Wrap(refused_error("Connection refused: getsockopt"));
|
||
assert!(
|
||
timeout_text_or_null(&e, CT, RT).is_none(),
|
||
"连接被拒不得被标成超时(仍算不可达)"
|
||
);
|
||
assert!(!cause_chain_has_timeout(&e));
|
||
}
|
||
|
||
/// 上游 ④(`:119`):🔴 **DNS 失败** ⇒ 同上(不��写文案)。
|
||
#[test]
|
||
fn hop2_dns_failure_is_not_rewritten() {
|
||
let e = Wrap(dns_error("no-such-host.invalid"));
|
||
assert!(
|
||
timeout_text_or_null(&e, CT, RT).is_none(),
|
||
"DNS 失败不得被标成超时"
|
||
);
|
||
}
|
||
|
||
/// 上游 ⑤(`:123`):**无 cause** ⇒ 不改写。
|
||
#[test]
|
||
fn hop2_no_cause_is_not_rewritten() {
|
||
let e = NoCause("boom");
|
||
assert!(timeout_text_or_null(&e, CT, RT).is_none(), "无 cause 不得改写");
|
||
}
|
||
|
||
/// 上游 ⑥(`:135`):🔴 判据须**走到底** —— cause 链被再包一层后仍须判出超时。
|
||
#[test]
|
||
fn hop2_multilevel_wrapped_cause_is_still_detected() {
|
||
let e = Wrap(Wrap(Wrap(timeout_error("Read timed out"))));
|
||
let text = timeout_text_or_null(&e, CT, RT).expect("多层包装仍须判出超时");
|
||
assert!(text.contains("调用 TDS 超时"), "实得:{}", text);
|
||
}
|
||
|
||
/// 上游的 cause 链遍历是**有界**的(`depth < 16`)⇒ 本仓同样有界([`MAX_CAUSE_DEPTH`])。
|
||
#[test]
|
||
fn hop2_cause_chain_walk_is_bounded() {
|
||
assert_eq!(MAX_CAUSE_DEPTH, 16);
|
||
// 造一条 40 层深的链 ⇒ 仍然有界返回(不死循环)
|
||
let mut e = Chain::Leaf(timeout_error("Read timed out"));
|
||
for _ in 0..40 {
|
||
e = Chain::Node(Box::new(e));
|
||
}
|
||
// 底层的超时在 40 层之外 ⇒ 有界遍历**找不到**它(但**不**死循环)
|
||
assert!(
|
||
!cause_chain_has_timeout(&e),
|
||
"超出深度上限后不应再命中(证明遍历有界)"
|
||
);
|
||
}
|
||
|
||
// ============================================================================
|
||
// 第 1 跳:配置值 ⇒ socket 层(上游 `ProviderInvokeTimeoutsSelfTest:61-83`)
|
||
// ============================================================================
|
||
|
||
/// 起一个「**先连上、但迟迟不响应**」的假对端(用来把读超时逼出来)。
|
||
///
|
||
/// 返回它的基地址。
|
||
fn spawn_delayed_server(delay: Duration) -> String {
|
||
let listener = TcpListener::bind("127.0.0.1:0").expect("绑定本地端口失败");
|
||
let addr = listener.local_addr().expect("取本地地址失败");
|
||
std::thread::spawn(move || {
|
||
for stream in listener.incoming() {
|
||
let Ok(mut stream) = stream else { continue };
|
||
std::thread::spawn(move || {
|
||
let mut buf = [0u8; 2048];
|
||
let _ = stream.read(&mut buf); // 把请求读掉(读多少都无所谓)
|
||
std::thread::sleep(delay);
|
||
let body = b"{\"code\":200,\"data\":{\"ok\":true}}";
|
||
let head = format!(
|
||
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
|
||
body.len()
|
||
);
|
||
let _ = stream.write_all(head.as_bytes());
|
||
let _ = stream.write_all(body);
|
||
let _ = stream.flush();
|
||
});
|
||
}
|
||
});
|
||
format!("http://{}", addr)
|
||
}
|
||
|
||
/// 上游第 1 跳的**行为级**对位:注入的超时值**真的落进 socket 层**。
|
||
///
|
||
/// 上游用反射读 socket 工厂;Rust 的 `reqwest::Client` 不暴露超时 ⇒ 改成
|
||
/// 「**换一组值 ⇒ 结论必须跟着变**」的行为判别(上游第 1 跳的判别性同款)。
|
||
#[tokio::test]
|
||
async fn hop1_injected_timeout_actually_reaches_the_socket_layer() {
|
||
let base = spawn_delayed_server(Duration::from_millis(800));
|
||
|
||
// ① 短读超时 ⇒ 必须**超时**(文案点名当前值)
|
||
let short = TdsClient::with_timeouts(
|
||
Some(base.clone()),
|
||
"tok".to_string(),
|
||
Duration::from_millis(CT),
|
||
Duration::from_millis(150),
|
||
);
|
||
assert_eq!(short.read_timeout_ms(), 150, "配置值必须落进客户端");
|
||
let err = short
|
||
.internal_catalog("space-1", None)
|
||
.await
|
||
.expect_err("短读超时必须失败");
|
||
assert!(
|
||
err.contains("调用 TDS 超时"),
|
||
"短超时必须被判成超时(而不是「不可达」),实得:{}",
|
||
err
|
||
);
|
||
assert!(
|
||
err.contains("150"),
|
||
"文案须点名当前 read 值,实得:{}",
|
||
err
|
||
);
|
||
|
||
// ② 换成长读超时 ⇒ 同样的对端**必须成功**(判别性:值变了,结论跟着变)
|
||
let long = TdsClient::with_timeouts(
|
||
Some(base.clone()),
|
||
"tok".to_string(),
|
||
Duration::from_millis(CT),
|
||
Duration::from_millis(5000),
|
||
);
|
||
assert_eq!(long.read_timeout_ms(), 5000);
|
||
let ok = long
|
||
.internal_catalog("space-1", None)
|
||
.await
|
||
.expect("长读超时必须成功(证明超时值真的生效)");
|
||
// `internal_catalog` 走**解包型**语义 ⇒ 返回的是信封里的 `data`
|
||
assert_eq!(
|
||
ok.get("ok").and_then(|v| v.as_bool()),
|
||
Some(true),
|
||
"响应体必须被完整收到并解开(实得:{})",
|
||
ok
|
||
);
|
||
}
|
||
|
||
/// 上游第 1 跳的另一半:**换注入值 ⇒ 跟着变**(防"判据恒等于常量")。
|
||
#[test]
|
||
fn hop1_changing_the_injected_value_changes_the_client() {
|
||
let a = TdsClient::with_timeouts(
|
||
Some("http://127.0.0.1:1".to_string()),
|
||
"tok".to_string(),
|
||
Duration::from_millis(1234),
|
||
Duration::from_millis(5678),
|
||
);
|
||
assert_eq!(a.connect_timeout_ms(), 1234);
|
||
assert_eq!(a.read_timeout_ms(), 5678);
|
||
|
||
let b = TdsClient::with_timeouts(
|
||
Some("http://127.0.0.1:1".to_string()),
|
||
"tok".to_string(),
|
||
Duration::from_millis(4321),
|
||
Duration::from_millis(8765),
|
||
);
|
||
assert_eq!(b.connect_timeout_ms(), 4321);
|
||
assert_eq!(b.read_timeout_ms(), 8765);
|
||
}
|
||
|
||
/// 🔴 **连接被拒 ⇒ 仍算「不可达」**(不得被误报成超时)—— 端到端行为级对位。
|
||
///
|
||
/// 上游第 2 跳 ③ 的**行为**版本:真去连一个没人听的端口 ⇒ reqwest 报 connect 失败
|
||
/// ⇒ 本仓文案必须是「TDS 不可达」,**不是**「调用 TDS 超时」。
|
||
#[tokio::test]
|
||
async fn hop2_end_to_end_connection_refused_stays_unreachable() {
|
||
// 绑一个端口拿到地址后立刻关闭 ⇒ 几乎必然「连接被拒」
|
||
let addr = {
|
||
let l = TcpListener::bind("127.0.0.1:0").expect("绑定失败");
|
||
l.local_addr().expect("取地址失败")
|
||
};
|
||
let client = TdsClient::with_timeouts(
|
||
Some(format!("http://{}", addr)),
|
||
"tok".to_string(),
|
||
Duration::from_millis(CT),
|
||
Duration::from_millis(RT),
|
||
);
|
||
let err = client
|
||
.internal_catalog("space-1", None)
|
||
.await
|
||
.expect_err("没人监听必须失败");
|
||
assert!(
|
||
err.contains("TDS 不可达"),
|
||
"连接被拒必须仍算不可达,实得:{}",
|
||
err
|
||
);
|
||
assert!(
|
||
!err.contains("调用 TDS 超时"),
|
||
"连接被拒不得被误报成超时,实得:{}",
|
||
err
|
||
);
|
||
}
|