Repository navigation
fix(api): 按传输阶段判定可重试,修复连接超时不 failover - #54
Conversation
用 Quint/Apalache 对 §7.3 P2 failover 重试策略建模(specs/quint/failover.qnt, failover_current=现状策略 / failover_fixed=对照,仅差 retryable 一行)。 N=2、budget=1 最小实例下 Apalache 穷尽验证:现状策略唯一违反 availability, 反例 [ConnectTimeout, Up]——主网关握手超时、备用健康却直接失败。 JDK 实测证实连接超时与读超时同为 SocketTimeoutException、均不命中 isPreSendRetryable 白名单,模型与现实逐点对应。 findings.md 记录证据链与三个修复方向(均涉接口变更,待裁决)。 不接 CI/lefthook:quint 为本地工具链,CI 引入是独立决策。
主网关 TCP 握手超时(丢包/黑洞/防火墙 DROP)时请求字节未发出,语义上属于 发送前失败,但 JDK 与 OkHttp 抛出的连接超时与读超时同为 SocketTimeoutException,原白名单(ConnectException/UnknownHostException/ NoRouteToHostException)全部落空,异常直接上抛,备用网关不被尝试—— failover 在最需要它的场景失效。 - WopSdkException 新增 Phase(UNKNOWN/CONNECT/SENT)与三参构造器; 旧构造器一律 UNKNOWN,第三方 Transport 行为不变。 - FailoverTransport.isPreSendRetryable 先按 phase 判定,UNKNOWN 才退回 异常类型白名单;wrapExhausted 保留末次失败阶段。 - jdkhttp:以显式 connect() 作为阶段边界(setRequestMethod/setDoOutput 相应上移至 connect 之前)。 - okhttp:以 network interceptor 为边界——它在 ConnectInterceptor 之后, 连接/DNS/TLS 失败时不执行,读超时与写体失败时已置 SENT。 行为变化:TLS 握手失败此前不重试,打标后归 CONNECT 变为可重试(请求未发出)。 Unirest 未改码:其 java.net.http 后端的连接超时 cause 链含 ConnectException, 现白名单已命中;模块 release=8 无法引用 java.net.http.*。 api-baseline 快照同步刷新(新增公共类型 Phase 与三参构造器)。
Architecture Inside the changed components — 1 viewComponent view — Transport failover & adapters Internal interaction between failover policy and tagged HTTP transport adapters
Data flow Review 1 finding addressed · reviewed
|
|
Important
This repository does not receive automatic reviews because it has fewer than 10 stars.
|
审阅者指南API添加公共传输阶段 API,并更新 API 基线以记录新增的枚举和构造函数。
实现在故障转移中使用感知阶段的重试决策,并在 JDK 和 OkHttp 适配器中标记连接到发送的边界。
文档记录正式的故障转移分析结果、实现证据、行为变更和已知限制。
测试将故障转移可用性的反例和修正后的策略指定为形式模型。
验证感知阶段的故障转移决策、适配器超时分类,以及每次调用之间的阶段隔离。
提示和命令与 Sourcery 交互
自定义使用体验访问你的控制面板以:
获取帮助Original review guide in EnglishReviewer's GuideAPIAdd the public transport phase API and update the API baseline to record the new enum and constructor.
ImplementationUse phase-aware retry decisions in failover and mark the connection-to-send boundary in the JDK and OkHttp adapters.
DocumentationRecord the formal failover findings, implementation evidence, behavior changes, and known limitations.
TestsSpecify the failover availability counterexample and the corrected policy as a formal model.
Verify phase-aware failover decisions, adapter timeout classification, and per-call phase isolation.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
嗨——我发现了 5 个问题
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="wop-sdk-core/src/main/java/com/wanlianyida/wop/WopSdkException.java" line_range="28" />
<code_context>
+ SENT
+ }
+
+ private final Phase phase;
+
+ /** 以明确语义消息构造(阶段 {@link Phase#UNKNOWN})。 */
</code_context>
<issue_to_address>
**Older exceptions stop deserializing**
When a consumer deserializes a `WopSdkException` serialized by an earlier SDK version, the added field and API change the computed `serialVersionUID`, so Java throws `InvalidClassException` instead of restoring the exception.
Declare an explicit `serialVersionUID` that matches the value used by the earlier SDK version.
Also at `wop-sdk-core/src/main/java/com/wanlianyida/wop/WopSdkException.java:40-48`.
</issue_to_address>
### Comment 2
<location path="wop-sdk-jdkhttp/src/test/java/com/wanlianyida/wop/jdkhttp/JdkHttpTransportPhaseTest.java" line_range="76" />
<code_context>
+
+ @Test
+ void connectTimeoutReportsConnectPhase() throws Exception {
+ String root = "http://10.255.255.1:81";
+ WopSdkException ex = withoutProxy(() -> assertThrows(WopSdkException.class,
+ () -> new JdkHttpTransport().send(draft(), fastCall(root))));
</code_context>
<issue_to_address>
**Connect-timeout tests fail on some networks**
When the test runner rejects, routes, or otherwise handles `10.255.255.1:81` instead of silently dropping the connection, the connect-timeout tests in the JDK and OkHttp transports receive a connection or routing exception instead of `SocketTimeoutException`, so `mvn verify` fails even when phase classification is correct.
Replace the hard-coded endpoint with a deterministic test setup that reliably produces a connect timeout.
Also at `wop-sdk-okhttp/src/test/java/com/wanlianyida/wop/okhttp/OkHttpTransportPhaseTest.java:46-48`.
</issue_to_address>
### Comment 3
<location path="wop-sdk-jdkhttp/src/test/java/com/wanlianyida/wop/jdkhttp/JdkHttpTransportPhaseTest.java" line_range="125-128" />
<code_context>
+ }
+
+ private static int freePort() {
+ try (java.net.ServerSocket socket = new java.net.ServerSocket(0)) {
+ return socket.getLocalPort();
+ } catch (IOException e) {
+ throw new IllegalStateException(e);
+ }
+ }
</code_context>
<issue_to_address>
**Connection-refused test is flaky**
When another process binds the selected port after `freePort()` closes its socket but before the transport connects, the request can connect to that listener or fail after connection, so the connection-refused phase assertions fail even when the transport is correct.
Change the refusal test setup so the port cannot be claimed by another process between selection and the connection attempt.
Also at `wop-sdk-jdkhttp/src/test/java/com/wanlianyida/wop/jdkhttp/JdkHttpTransportPhaseTest.java:101-102`.
</issue_to_address>
### Comment 4
<location path="wop-sdk-jdkhttp/src/test/java/com/wanlianyida/wop/jdkhttp/JdkHttpTransportPhaseTest.java" line_range="53-66" />
<code_context>
+ /** 在禁代理上下文中执行:否则 http.proxyHost 会把连接劫持成功。 */
+ private static <T> T withoutProxy(ThrowingSupplier<T> body) throws Exception {
+ ProxySelector original = ProxySelector.getDefault();
+ ProxySelector.setDefault(new ProxySelector() {
+ @Override
+ public List<Proxy> select(URI uri) {
+ return Collections.singletonList(Proxy.NO_PROXY);
+ }
+
+ @Override
+ public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
+ }
+ });
+ try {
+ return body.get();
+ } finally {
+ ProxySelector.setDefault(original);
+ }
+ }
</code_context>
<issue_to_address>
**Concurrent tests corrupt proxy selection**
When JUnit runs multiple tests using `withoutProxy` concurrently, two test threads can save and replace the JVM-wide `ProxySelector`, then restore their saved values out of order; the final selector can differ from the original, routing later requests unexpectedly and making tests flaky.
Avoid changing the JVM-wide selector, or serialize all code that changes and depends on the default selector.
</issue_to_address>
### Comment 5
<location path="wop-sdk-core/src/test/java/com/wanlianyida/wop/FailoverTransportPhaseTest.java" line_range="70" />
<code_context>
+ new SocketTimeoutException("Connect timed out"),
+ WopSdkException.Phase.CONNECT);
+ }
+ return new TransportResponse(200, new LinkedHashMap<String, String>(), new byte[0]);
+ }
+ };
</code_context>
<issue_to_address>
**Backup gateway can go untested**
When retry logic repeats the primary server root instead of advancing to the backup, `connectPhaseSocketTimeoutFailsOver` returns 200 on every call after the first, regardless of `call.serverRoot()`, and only checks the response status and attempt count. A regression that retries the primary instead of selecting the backup therefore still passes.
Assert that the second call uses the configured backup server root.
</issue_to_address>Sourcery 评估
等待批准。 请先处理 5 项发现。
阻塞项:wop-sdk-core/src/main/java/com/wanlianyida/wop/WopSdkException.java:28、wop-sdk-jdkhttp/src/test/java/com/wanlianyida/wop/jdkhttp/JdkHttpTransportPhaseTest.java:76、wop-sdk-jdkhttp/src/test/java/com/wanlianyida/wop/jdkhttp/JdkHttpTransportPhaseTest.java:128、wop-sdk-jdkhttp/src/test/java/com/wanlianyida/wop/jdkhttp/JdkHttpTransportPhaseTest.java:66、wop-sdk-core/src/test/java/com/wanlianyida/wop/FailoverTransportPhaseTest.java:70
Original comment in English
Hey - I've found 5 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="wop-sdk-core/src/main/java/com/wanlianyida/wop/WopSdkException.java" line_range="28" />
<code_context>
+ SENT
+ }
+
+ private final Phase phase;
+
+ /** 以明确语义消息构造(阶段 {@link Phase#UNKNOWN})。 */
</code_context>
<issue_to_address>
**Older exceptions stop deserializing**
When a consumer deserializes a `WopSdkException` serialized by an earlier SDK version, the added field and API change the computed `serialVersionUID`, so Java throws `InvalidClassException` instead of restoring the exception.
Declare an explicit `serialVersionUID` that matches the value used by the earlier SDK version.
Also at `wop-sdk-core/src/main/java/com/wanlianyida/wop/WopSdkException.java:40-48`.
</issue_to_address>
### Comment 2
<location path="wop-sdk-jdkhttp/src/test/java/com/wanlianyida/wop/jdkhttp/JdkHttpTransportPhaseTest.java" line_range="76" />
<code_context>
+
+ @Test
+ void connectTimeoutReportsConnectPhase() throws Exception {
+ String root = "http://10.255.255.1:81";
+ WopSdkException ex = withoutProxy(() -> assertThrows(WopSdkException.class,
+ () -> new JdkHttpTransport().send(draft(), fastCall(root))));
</code_context>
<issue_to_address>
**Connect-timeout tests fail on some networks**
When the test runner rejects, routes, or otherwise handles `10.255.255.1:81` instead of silently dropping the connection, the connect-timeout tests in the JDK and OkHttp transports receive a connection or routing exception instead of `SocketTimeoutException`, so `mvn verify` fails even when phase classification is correct.
Replace the hard-coded endpoint with a deterministic test setup that reliably produces a connect timeout.
Also at `wop-sdk-okhttp/src/test/java/com/wanlianyida/wop/okhttp/OkHttpTransportPhaseTest.java:46-48`.
</issue_to_address>
### Comment 3
<location path="wop-sdk-jdkhttp/src/test/java/com/wanlianyida/wop/jdkhttp/JdkHttpTransportPhaseTest.java" line_range="125-128" />
<code_context>
+ }
+
+ private static int freePort() {
+ try (java.net.ServerSocket socket = new java.net.ServerSocket(0)) {
+ return socket.getLocalPort();
+ } catch (IOException e) {
+ throw new IllegalStateException(e);
+ }
+ }
</code_context>
<issue_to_address>
**Connection-refused test is flaky**
When another process binds the selected port after `freePort()` closes its socket but before the transport connects, the request can connect to that listener or fail after connection, so the connection-refused phase assertions fail even when the transport is correct.
Change the refusal test setup so the port cannot be claimed by another process between selection and the connection attempt.
Also at `wop-sdk-jdkhttp/src/test/java/com/wanlianyida/wop/jdkhttp/JdkHttpTransportPhaseTest.java:101-102`.
</issue_to_address>
### Comment 4
<location path="wop-sdk-jdkhttp/src/test/java/com/wanlianyida/wop/jdkhttp/JdkHttpTransportPhaseTest.java" line_range="53-66" />
<code_context>
+ /** 在禁代理上下文中执行:否则 http.proxyHost 会把连接劫持成功。 */
+ private static <T> T withoutProxy(ThrowingSupplier<T> body) throws Exception {
+ ProxySelector original = ProxySelector.getDefault();
+ ProxySelector.setDefault(new ProxySelector() {
+ @Override
+ public List<Proxy> select(URI uri) {
+ return Collections.singletonList(Proxy.NO_PROXY);
+ }
+
+ @Override
+ public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
+ }
+ });
+ try {
+ return body.get();
+ } finally {
+ ProxySelector.setDefault(original);
+ }
+ }
</code_context>
<issue_to_address>
**Concurrent tests corrupt proxy selection**
When JUnit runs multiple tests using `withoutProxy` concurrently, two test threads can save and replace the JVM-wide `ProxySelector`, then restore their saved values out of order; the final selector can differ from the original, routing later requests unexpectedly and making tests flaky.
Avoid changing the JVM-wide selector, or serialize all code that changes and depends on the default selector.
</issue_to_address>
### Comment 5
<location path="wop-sdk-core/src/test/java/com/wanlianyida/wop/FailoverTransportPhaseTest.java" line_range="70" />
<code_context>
+ new SocketTimeoutException("Connect timed out"),
+ WopSdkException.Phase.CONNECT);
+ }
+ return new TransportResponse(200, new LinkedHashMap<String, String>(), new byte[0]);
+ }
+ };
</code_context>
<issue_to_address>
**Backup gateway can go untested**
When retry logic repeats the primary server root instead of advancing to the backup, `connectPhaseSocketTimeoutFailsOver` returns 200 on every call after the first, regardless of `call.serverRoot()`, and only checks the response status and attempt count. A regression that retries the primary instead of selecting the backup therefore still passes.
Assert that the second call uses the configured backup server root.
</issue_to_address>Sourcery assessment
Approval pending. 5 findings to address first.
Blocking findings: wop-sdk-core/src/main/java/com/wanlianyida/wop/WopSdkException.java:28, wop-sdk-jdkhttp/src/test/java/com/wanlianyida/wop/jdkhttp/JdkHttpTransportPhaseTest.java:76, wop-sdk-jdkhttp/src/test/java/com/wanlianyida/wop/jdkhttp/JdkHttpTransportPhaseTest.java:128, wop-sdk-jdkhttp/src/test/java/com/wanlianyida/wop/jdkhttp/JdkHttpTransportPhaseTest.java:66, wop-sdk-core/src/test/java/com/wanlianyida/wop/FailoverTransportPhaseTest.java:70
|
|
@sourcery-ai resolve |
问题
FailoverTransport.isPreSendRetryable用异常类型白名单(ConnectException/UnknownHostException/NoRouteToHostException)判定「发送前失败」,但连接超时不在此列:主网关 TCP 握手超时(丢包、黑洞、防火墙 DROP——正是 failover 最该生效的场景)会直接上抛给调用方,备用网关一次都不尝试。根因不是漏了一个类型:JDK 与 OkHttp 下连接超时与读超时同为
java.net.SocketTimeoutException(仅消息串不同),按类型永远无法区分二者,而两者的 failover 安全性相反——前者请求字节未发出(重发无副作用),后者已发出(重发可能重复扣款)。修复
WopSdkException新增Phase(UNKNOWN/CONNECT/SENT),由适配器在真正的阶段边界打标;core 先按 phase 判定,UNKNOWN才退回异常类型白名单(第三方Transport行为不变)。wop-sdk-jdkhttpconnection.connect()返回后置SENTconnect()返回后请求体才会写出,是唯一边界。附带约束:setRequestMethod/setDoOutput必须在connect()前调用,故上移wop-sdk-okhttpSENTRetryAndFollowUp → Bridge → Cache → ConnectInterceptor → network interceptors:连接/DNS/TLS 失败时拦截器不执行(保持CONNECT),读超时与写体失败时已置SENT。应用拦截器做不到——它跑在RetryAndFollowUp之前,早于建连wop-sdk-unirestjava.net.http后端连接超时的 cause 链最内层为java.net.ConnectException,现有白名单已命中;且模块release=8无法编译期引用java.net.http.*证据链
1. falsifier:Quint 形式化反例(
specs/quint/)最小实例 N=2 候选 / budget=1,Apalache 穷尽验证(
--max-steps=6):failover_current(修复前)failover_fixed(修复后)两者仅差
retryable一行。复现:quint verify --main=failover_current --invariant=availability --max-steps=6 specs/quint/failover.qnt(quint 0.33.1 + apalache 0.62.4,需 JDK 21)。2. 原始素材:异常类型实测
JDK 21 探针(对 RFC5737 黑洞地址设 1s 连接超时 / 对 accept 后不响应的服务端设读超时)→ 两者均
SocketTimeoutException,instanceof ConnectException = false。修复后由OkHttpTransportPhaseTest/JdkHttpTransportPhaseTest固化为可重跑断言。3. 门灵敏度先行:4 处变异逐一击穿
connectPhaseSocketTimeoutFailsOver)readTimeoutReportsSentPhase等)connect()connectTimeoutReportsConnectPhase、connectionRefusedReportsConnectPhase)变体后全绿仅因未跑测试的写法未被采纳:三处变异各自导致对应用例失败,还原后全绿。
4. 门禁
mvn -o verify全绿(core 473 + okhttp 49 + jdkhttp 28 + unirest 46;jacoco 分支 100%);pitestcore:1175 变异 / 1132 killed,test strength 96%,阈值 90 通过。api-baseline快照随Phase新增同步刷新。需要评审注意的行为变化
CONNECT→ 变为可重试。 请求字节未发出,重发无重复副作用,但意味着握手失败时会在备用网关上再试一次。WopSdkException默认serialVersionUID随公共成员变化而变(japicmp 报Default serialversionuid changed)。本类非长期序列化载体,未钉 UID;若下游有跨版本反序列化需求请提出。retryOnConnectionFailure保持默认 true。 已实测确认其与FailoverTransport计数不冲突:仅在同 host 多 A 记录时叠加,单 IP 下 true/false 行为完全一致,跨网关绝不发生;唯一影响是把单次 attempt 的耗时上限抬到「DNS 路由数 × connectTimeout」。关掉它会削弱单网关场景韧性而收益为零,故不改。缺证声明
java.net.http保留ConnectException于 cause 链。上游若改为裸HttpTimeoutException会退化为「不重试」——安全侧,但可用性缺口回归。该模块无法在编译期引用java.net.http.*,无法自行打标。jdkhttp的「连接超时」用例必须强制ProxySelector为NO_PROXY:本机http.proxyHost会把黑洞地址变成「连接成功」,测试已在 try/finally 内替换并还原。范围
两个 commit:
022bcee(实现 + 测试 + baseline)、f121255(findings 同步)。未触docs/、pom、crypto/、WopClient.java等 PERIMETER 面。Sourcery 摘要
根据请求是否已发送来决定是否进行故障转移,从而让连接超时可以安全重试,同时避免重复发送请求。
新功能:
错误修复:
改进:
文档:
测试:
杂项:
Original summary in English
Sourcery 总结
在判定请求是否已发送后再执行故障转移,使连接超时能够安全地切换到备用网关,并避免重复发送请求。
新功能:
错误修复:
增强功能:
文档:
测试:
杂项:
Original summary in English
Sourcery 摘要
判定请求是否已发送后执行故障转移,使连接超时能够切换到备用网关,同时避免请求发送后的重复重试。
新功能:
WopSdkException上公开明确的传输阶段,以便故障转移决策能够区分连接失败与请求发送后的失败。错误修复:
增强功能:
文档:
测试:
杂项:
Original summary in English
Summary by Sourcery
判定请求是否已发送后执行故障转移,使连接超时能够切换到备用网关,同时避免请求发送后的重复重试。
New Features:
WopSdkExceptionso failover decisions can distinguish connection failures from failures after request transmission.Bug Fixes:
Enhancements:
Documentation:
Tests:
Chores: