diff --git a/backend-java/src/main/java/com/nanri/aiimage/common/retry/UnreachableCooldown.java b/backend-java/src/main/java/com/nanri/aiimage/common/retry/UnreachableCooldown.java index c91bdfe6f..f53da63d6 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/common/retry/UnreachableCooldown.java +++ b/backend-java/src/main/java/com/nanri/aiimage/common/retry/UnreachableCooldown.java @@ -23,6 +23,14 @@ import java.util.concurrent.atomic.AtomicLong; * {@link #recordConnectFailure}(返回 true 的那方打一条进入冷却的 warn); * 连接成功或"连上了没答好"(读超时/5xx/解析失败)记 {@link #recordConnected} 清零证据。 * 窗长 {@code <= 0} 表示关闭冷却,全部方法退化为无操作——调用方退回各自的调用内短路行为。 + * + *

第二条证据道(B24 扩围,2026-10-26 拍板):{@link #recordNoAnswerFailure} 收的是 + * 「连接已建立、但对端没给出可结算的响应」——现网两个形状(BACKLOG B26):16890 卡死后 + * 在给出响应前收连接({@code header parser received no bytes}),以及 HTTP 200 里 + * {@code query_faild_data} 成片带解密失败。两形都按次即时记证:任何一次可结算结论 + * (干净返回/命中侵权/余额不足)都把证据清零,脏品牌名混在好品牌里永远攒不满两条。 + * no-answer 道与 connect 道分账:{@link #recordConnected} 只清 connect 证据, + * no-answer 证据由 {@link #clearNoAnswerEvidence} 在调用方自己的批次语义里清。 */ @Component public class UnreachableCooldown { @@ -38,6 +46,8 @@ public class UnreachableCooldown { private static final class State { final AtomicInteger evidence = new AtomicInteger(); final AtomicLong cooldownUntilMillis = new AtomicLong(); + final AtomicInteger noAnswerEvidence = new AtomicInteger(); + final AtomicLong noAnswerCooldownUntilMillis = new AtomicLong(); } /** @@ -56,13 +66,31 @@ public class UnreachableCooldown { return false; } - /** 该 host 是否正处冷却窗内:true 时调用方不发请求,直接按既有不可达归因文案快速失败。 */ + /** 该 host 是否正处冷却窗内(connect 道或 no-answer 道任一):true 时调用方不发请求,直接按既有不可达归因文案快速失败。 */ public boolean isCoolingDown(String host, long windowMillis) { + return connectLaneCooling(host, windowMillis) || noAnswerLaneCooling(host, windowMillis); + } + + /** 只问 connect 道:品牌客户端据此在两条快失败分支里选归因文案;两道的窗口径一致。 */ + public boolean connectLaneCooling(String host, long windowMillis) { + return laneCooling(host, windowMillis, true); + } + + /** 只问 no-answer 道(B24 扩围):品牌客户端据此选用「不回包/解密成片」的归因文案。 */ + public boolean noAnswerLaneCooling(String host, long windowMillis) { + return laneCooling(host, windowMillis, false); + } + + private boolean laneCooling(String host, long windowMillis, boolean connectLane) { if (windowMillis <= 0) { return false; } State state = states.get(normalizeHost(host)); - return state != null && state.cooldownUntilMillis.get() > System.currentTimeMillis(); + if (state == null) { + return false; + } + AtomicLong until = connectLane ? state.cooldownUntilMillis : state.noAnswerCooldownUntilMillis; + return until.get() > System.currentTimeMillis(); } /** @@ -72,22 +100,37 @@ public class UnreachableCooldown { * 调用方据此打一条进入冷却的 warn,期中快失败不刷屏 */ public boolean recordConnectFailure(String host, long windowMillis) { + return openWindow(host, windowMillis, true); + } + + /** + * no-answer 道证据 +1(B24 扩围):形状由调用方判定——异常侧认「对端在给出响应前 + * 关闭连接」,响应侧认「行级结论带解密失败」。窗长/阈值/到期语义与 connect 道同款 + * (同格到期一次失败即重进)。 + */ + public boolean recordNoAnswerFailure(String host, long windowMillis) { + return openWindow(host, windowMillis, false); + } + + private boolean openWindow(String host, long windowMillis, boolean connectLane) { if (windowMillis <= 0) { return false; } State state = states.computeIfAbsent(normalizeHost(host), key -> new State()); - if (state.evidence.incrementAndGet() < EVIDENCE_THRESHOLD) { + AtomicInteger evidence = connectLane ? state.evidence : state.noAnswerEvidence; + if (evidence.incrementAndGet() < EVIDENCE_THRESHOLD) { return false; } long now = System.currentTimeMillis(); - long previous = state.cooldownUntilMillis.get(); + AtomicLong until = connectLane ? state.cooldownUntilMillis : state.noAnswerCooldownUntilMillis; + long previous = until.get(); if (previous > now) { return false; } - return state.cooldownUntilMillis.compareAndSet(previous, now + windowMillis); + return until.compareAndSet(previous, now + windowMillis); } - /** 连接成功或"连上了没答好":证据清零(已开的冷却窗不受影响,等它自然到期)。 */ + /** 连接成功或"连上了没答好":connect 道证据清零(已开的冷却窗不受影响,等它自然到期)。 */ public void recordConnected(String host) { State state = states.get(normalizeHost(host)); if (state != null) { @@ -95,6 +138,14 @@ public class UnreachableCooldown { } } + /** no-answer 道证据清零:批次里出现任何一次可结算结论即「服务活着」,重新攒两次证据。 */ + public void clearNoAnswerEvidence(String host) { + State state = states.get(normalizeHost(host)); + if (state != null) { + state.noAnswerEvidence.set(0); + } + } + /** host 归一:两个 LLM 客户端配的同一网关必须落进同一格,别因尾斜杠/大小写裂成两份。 */ static String normalizeHost(String host) { String normalized = host == null ? "" : host.trim().toLowerCase(); diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/brand/client/BrandCheckClient.java b/backend-java/src/main/java/com/nanri/aiimage/modules/brand/client/BrandCheckClient.java index 7356df7df..65cad724b 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/brand/client/BrandCheckClient.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/brand/client/BrandCheckClient.java @@ -72,6 +72,27 @@ public class BrandCheckClient { private static final int CONNECT_FAILURE_EVIDENCE = 2; private static final String REASON_SERVICE_UNREACHABLE = "品牌检测服务不可达(连接未建立,非本行数据问题)"; + /** + * 「连上了但不回包」的形状指纹(B24 扩围,2026-10-26 拍板):JDK HttpClient 在对端 + * 给出响应前关闭连接时抛的两句原文(2026-10-24 现网 B→A:16890 87/88 条是前者)。 + * 读超时不算——那仍是"慢",2026-10-24 立账时按口径故意留在重试有意义的一侧。 + */ + private static final java.util.regex.Pattern PEER_CLOSED_WITHOUT_RESPONSE = + java.util.regex.Pattern.compile("header parser received no bytes|EOF reached while reading"); + + /** + * 「解密失败成片」的形状指纹:16890 侧解密/JSON 解析失败的行级 reason(现网三形—— + * {@code 查询或解密失败: …Malformed UTF-8 data}/{@code Expecting value: line 1 column 1} + * /三层嵌套的旧版 {@code 解密失败:} 前缀,见 BACKLOG B26)。 + */ + private static final java.util.regex.Pattern DECRYPT_FAILURE_REASON = + java.util.regex.Pattern.compile("解密失败|Expecting value"); + + /** no-answer 道的解密失败条数:与 connect 道同数字,两次同形且整批零干净结论才是服务在掉。 */ + private static final int NO_ANSWER_FAILURE_EVIDENCE = 2; + private static final String REASON_SERVICE_DEGRADED = + "品牌检测服务不可达(解密链路成片失败,非本行数据问题)"; + /** * 代理出口被上游拒绝的证据条数:同一批里已有这么多个品牌在换过出口后仍被拒, * 后面的品牌不再发起首轮探针。2026-10-23 现网:16890 每个品牌最多换 2 个 IP, @@ -301,7 +322,7 @@ public class BrandCheckClient { return outcomes; } long cooldownMillis = Math.max(0, properties.getUnreachableCooldownMillis()); - if (unreachableCooldown.isCoolingDown(properties.getBaseUrl(), cooldownMillis)) { + if (unreachableCooldown.connectLaneCooling(properties.getBaseUrl(), cooldownMillis)) { // 客户端级冷却(B24):上一批已确认连接层不可达,本批连首轮探针都不发。 // 结论与批内短路版逐字一致(每行仍判查询失败、reason 同文案),差别只是不再为 // "确认还是断的"每批各烧一轮连接探针;到期后下一批的真实请求兼作探针。 @@ -312,6 +333,17 @@ public class BrandCheckClient { } return outcomes; } + if (unreachableCooldown.noAnswerLaneCooling(properties.getBaseUrl(), cooldownMillis)) { + // B24 扩围(2026-10-26 拍板):上一批已确认「连上了但不回包」或「解密链路成片失败」, + // 本批同样一个请求都不发。行级结论不变(每品牌仍判查询失败),只是归因从空 reason/ + // 逐行白等 45~65 秒,换成一条可运维的服务级降级文案;到期后下一批的真实请求兼作探针。 + log.warn("[brand-check] NO_ANSWER_COOLDOWN 客户端级冷却中(不回包/解密成片),整批不打上游" + + " brands={} window={}ms", brands.size(), cooldownMillis); + for (String brand : brands) { + outcomes.put(brand, new BrandCheckOutcome(List.of(), List.of(brand), REASON_SERVICE_DEGRADED)); + } + return outcomes; + } long firstAttemptDeadlineNanos = deadlineNanos == Long.MAX_VALUE ? Long.MAX_VALUE : deadlineNanos + FIRST_ATTEMPT_QUEUE_GRACE_MILLIS * 1_000_000L; @@ -325,6 +357,9 @@ public class BrandCheckClient { AtomicInteger connectFailures = new AtomicInteger(); // 出口被上游拒绝的证据跨品牌累计:达到阈值后不再给后续品牌发首轮探针。 AtomicInteger egressRejections = new AtomicInteger(); + // no-answer 道的解密形状批内计数(B24 扩围):批终态才记证,见 awaitOutcome 循环后的聚合。 + AtomicInteger decryptFailures = new AtomicInteger(); + AtomicBoolean sawCleanConclusion = new AtomicBoolean(false); for (String brand : brands) { AtomicBoolean started = new AtomicBoolean(false); AtomicBoolean rejected = new AtomicBoolean(false); @@ -335,7 +370,8 @@ public class BrandCheckClient { () -> { started.set(true); return checkOneBrand(brand, strategy, deadlineNanos, upstreamRejecting, - proxyUrl, userId, connectFailures, egressRejections); + proxyUrl, userId, connectFailures, egressRejections, + decryptFailures, sawCleanConclusion); }, checkExecutor); } finally { @@ -355,6 +391,20 @@ public class BrandCheckClient { outcomes.put(brands.get(index), awaitOutcome(brands.get(index), futures.get(index), startedFlags.get(index), deadlineNanos, firstAttemptDeadlineNanos)); } + // 批终态才动 no-answer 表(B24 扩围):一枚可结算结论就整票作废并清零, + // 零干净的批次按票数逐条记证(阈值 2 与 connect 道同数字)。本批请求不受影响—— + // 冷却只掐后续批次,行级差异的证据面一字不动。 + if (sawCleanConclusion.get()) { + unreachableCooldown.clearNoAnswerEvidence(properties.getBaseUrl()); + } else { + for (int i = 0; i < decryptFailures.get(); i++) { + if (unreachableCooldown.recordNoAnswerFailure(properties.getBaseUrl(), cooldownMillis)) { + log.warn("[brand-check] NO_ANSWER_COOLDOWN 批内解密失败 {} 枚且零干净结论," + + "进入客户端级冷却 {}ms host={}", + decryptFailures.get(), cooldownMillis, properties.getBaseUrl()); + } + } + } return outcomes; } @@ -366,7 +416,9 @@ public class BrandCheckClient { private BrandCheckOutcome checkOneBrand(String brand, String strategy, long deadlineNanos, AtomicBoolean upstreamRejecting, String proxyUrl, Long userId, AtomicInteger connectFailures, - AtomicInteger egressRejections) { + AtomicInteger egressRejections, + AtomicInteger decryptFailures, + AtomicBoolean sawCleanConclusion) { int attempts = Math.max(1, properties.getRetryTimes()); BrandCheckResponse response = null; Exception lastFailure = null; @@ -428,6 +480,12 @@ public class BrandCheckClient { CONNECT_FAILURE_EVIDENCE, brand, attempt, attempts, ex.getMessage()); break; } + } else if (isPeerClosedWithoutResponse(ex)) { + // 连上了、对端却在给出响应前把连接收了(B26 主形 header parser received no + // bytes):重试救不回这一形状,按 no-answer 道即时记证;本品牌照旧重试收尾。 + log.warn("[brand-check] NO_ANSWER 对端在给出响应前关闭连接 brand={} attempt={}/{} err={}", + brand, attempt, attempts, ex.getMessage()); + recordNoAnswerFailure(); } else { // 连上了只是这次没答好(读超时/解析失败):连接层证据不作数 connectFailures.set(0); @@ -444,6 +502,14 @@ public class BrandCheckClient { // 拿到响应=连接是通的,证据清零,别跨到下一次真断连时凑数 connectFailures.set(0); unreachableCooldown.recordConnected(properties.getBaseUrl()); + if (response != null && !nullToEmpty(response.getQueryFaildData()).isEmpty() + && isDecryptFailure(response.getReason())) { + // 解密形状(B26 成片主形):先计一条批内票;是否在服务级记证由批终态聚合决定 + // ——同批里只要有一枚可结算结论,就认定这是本行数据问题而不是服务在掉。 + decryptFailures.incrementAndGet(); + } else if (response != null) { + sawCleanConclusion.set(true); + } if (response != null && nullToEmpty(response.getQueryFaildData()).isEmpty()) { // 本次查询完成且无失败项:命中侵权(faild_data)属有效结论,不重试。 return new BrandCheckOutcome(nullToEmpty(response.getFaildData()), List.of(), ""); @@ -632,6 +698,37 @@ public class BrandCheckClient { } } + /** no-answer 道即时记证(不回包形状):达到阈值的那一方打进入冷却的 warn(B24 扩围)。 */ + private void recordNoAnswerFailure() { + long cooldownMillis = Math.max(0, properties.getUnreachableCooldownMillis()); + if (unreachableCooldown.recordNoAnswerFailure(properties.getBaseUrl(), cooldownMillis)) { + log.warn("[brand-check] NO_ANSWER_COOLDOWN 不回包证据累计到阈值,进入客户端级冷却 {}ms host={}", + cooldownMillis, properties.getBaseUrl()); + } + } + + /** + * 「连上了但对端在给出响应前关闭连接」(B24 扩围):顺着 cause 链认 + * {@link #PEER_CLOSED_WITHOUT_RESPONSE} 那两句 JDK HttpClient 原文。 + * 与 {@link #isConnectFailure} 互斥(会话没建立的形状归连接道),读超时不算—— + * 那侧注释在 B19 就写死了:慢≠掉。 + */ + static boolean isPeerClosedWithoutResponse(Throwable error) { + for (Throwable t = error; t != null && t != t.getCause(); t = t.getCause()) { + String message = t.getMessage(); + if (message != null && PEER_CLOSED_WITHOUT_RESPONSE.matcher(message).find()) { + return true; + } + } + return false; + } + + /** 「解密链路失败」的行级 reason(B24 扩围):上游已回话、内容解不开,供批终态聚合判定。 */ + static boolean isDecryptFailure(String reason) { + String trimmed = reason == null ? "" : reason.trim(); + return !trimmed.isEmpty() && DECRYPT_FAILURE_REASON.matcher(trimmed).find(); + } + /** * 连接层判定下沉 {@code UnreachableCooldown.isConnectFailure}(B24):判定口径与 * 两个 LLM 客户端共用一份,不再各留包内副本。 diff --git a/backend-java/src/test/java/com/nanri/aiimage/common/retry/UnreachableCooldownTest.java b/backend-java/src/test/java/com/nanri/aiimage/common/retry/UnreachableCooldownTest.java index 272014e9e..f1ead9f70 100644 --- a/backend-java/src/test/java/com/nanri/aiimage/common/retry/UnreachableCooldownTest.java +++ b/backend-java/src/test/java/com/nanri/aiimage/common/retry/UnreachableCooldownTest.java @@ -74,4 +74,82 @@ class UnreachableCooldownTest { assertThat(UnreachableCooldown.isConnectFailure(new RuntimeException("read timeout"))).isFalse(); assertThat(UnreachableCooldown.isConnectFailure(null)).isFalse(); } + + // ---- no-answer 道(B24 扩围,2026-10-26 拍板):阈值/窗长/到期语义与 connect 道同款 ---- + + @Test + void twoNoAnswerFailuresEnterCooldownOneDoesNot() { + String host = "http://16890.example"; + assertThat(cooldown.recordNoAnswerFailure(host, WINDOW)).isFalse(); + assertThat(cooldown.isCoolingDown(host, WINDOW)).isFalse(); + assertThat(cooldown.recordNoAnswerFailure(host, WINDOW)).isTrue(); + assertThat(cooldown.noAnswerLaneCooling(host, WINDOW)).isTrue(); + assertThat(cooldown.isCoolingDown(host, WINDOW)).isTrue(); + } + + @Test + void noAnswerWindowExpiresAndSingleFailureReenters() throws InterruptedException { + String host = "http://expire-16890.example"; + cooldown.recordNoAnswerFailure(host, 50); + cooldown.recordNoAnswerFailure(host, 50); + assertThat(cooldown.noAnswerLaneCooling(host, 50)).isTrue(); + + Thread.sleep(120); + assertThat(cooldown.noAnswerLaneCooling(host, 50)).isFalse(); + + // 历史证据不清零:到期后批次再判成片,一次即重进(与 connect 道同拍板口径) + assertThat(cooldown.recordNoAnswerFailure(host, 50)).isTrue(); + assertThat(cooldown.noAnswerLaneCooling(host, 50)).isTrue(); + } + + @Test + void clearNoAnswerEvidenceRequiresTwoFreshFailures() { + String host = "http://clear.example"; + cooldown.recordNoAnswerFailure(host, WINDOW); + cooldown.clearNoAnswerEvidence(host); + assertThat(cooldown.recordNoAnswerFailure(host, WINDOW)).isFalse(); + assertThat(cooldown.noAnswerLaneCooling(host, WINDOW)).isFalse(); + } + + @Test + void clearOnlyTouchesNoAnswerEvidenceAndNeverAnOpenedWindow() { + String host = "http://window-stays.example"; + cooldown.recordNoAnswerFailure(host, WINDOW); + cooldown.recordNoAnswerFailure(host, WINDOW); + // 已开的窗不因清零提前放行:快失败只按窗长自然到期(connect 道同语义) + cooldown.clearNoAnswerEvidence(host); + assertThat(cooldown.noAnswerLaneCooling(host, WINDOW)).isTrue(); + // 到期后靠那一次成片失败重进:清零历史后证据要重新攒满两条,这里只缺一条 + cooldown.clearNoAnswerEvidence(host); + assertThat(cooldown.recordNoAnswerFailure(host, WINDOW)).isFalse(); + } + + @Test + void zeroWindowDisablesNoAnswerLaneToo() { + for (int i = 0; i < 5; i++) { + assertThat(cooldown.recordNoAnswerFailure("http://off.example", 0)).isFalse(); + } + assertThat(cooldown.noAnswerLaneCooling("http://off.example", 0)).isFalse(); + } + + @Test + void connectLaneAndNoAnswerLaneAreSeparateAccounts() { + String host = "http://lanes.example"; + cooldown.recordConnectFailure(host, WINDOW); + assertThat(cooldown.noAnswerLaneCooling(host, WINDOW)).isFalse(); + cooldown.recordNoAnswerFailure(host, WINDOW); + // 两条道各计各的:一条 connect + 一条 no-answer 都不到阈值 + assertThat(cooldown.connectLaneCooling(host, WINDOW)).isFalse(); + assertThat(cooldown.noAnswerLaneCooling(host, WINDOW)).isFalse(); + + cooldown.recordConnectFailure(host, WINDOW); + assertThat(cooldown.connectLaneCooling(host, WINDOW)).isTrue(); + assertThat(cooldown.noAnswerLaneCooling(host, WINDOW)).isFalse(); + + // recordConnected 只清 connect 证据;no-answer 证据必须活过它 + cooldown.recordConnected(host); + assertThat(cooldown.recordNoAnswerFailure(host, WINDOW)).isTrue(); + assertThat(cooldown.noAnswerLaneCooling(host, WINDOW)).isTrue(); + assertThat(cooldown.connectLaneCooling(host, WINDOW)).isTrue(); + } } diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/brand/client/BrandCheckClientTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/brand/client/BrandCheckClientTest.java index 768141697..dea67841b 100644 --- a/backend-java/src/test/java/com/nanri/aiimage/modules/brand/client/BrandCheckClientTest.java +++ b/backend-java/src/test/java/com/nanri/aiimage/modules/brand/client/BrandCheckClientTest.java @@ -81,6 +81,161 @@ class BrandCheckClientTest { } } + // ---- B24 扩围(2026-10-26 拍板):冷却纳入「连上了不回包」与「解密失败成片」两形 ---- + + /** + * 「连上了但不回包」(B26 主形 {@code header parser received no bytes})按次记进 no-answer 道: + * 首批两条阶梯证据把窗打开,第二批整批快失败、零请求。行级结论仍是查询失败, + * 变的只有归因与耗时。 + */ + @Test + void peerClosedWithoutResponseOpensCooldownAndNextBatchHitsZeroProbes() throws Exception { + AtomicInteger connections = new AtomicInteger(); + ServerSocket listener = new ServerSocket(0, 16, java.net.InetAddress.getByName("127.0.0.1")); + Thread closer = new Thread(() -> { + while (!listener.isClosed()) { + try (java.net.Socket socket = listener.accept()) { + connections.incrementAndGet(); + // 不读不写直接关:JDK HttpClient 在响应解析器处拿到 0 字节 + } catch (IOException ignored) { + return; + } + } + }, "no-bytes-closer"); + closer.setDaemon(true); + closer.start(); + try { + UnreachableCooldown cooldown = new UnreachableCooldown(); + BrandCheckProperties props = new BrandCheckProperties(); + props.setBaseUrl("http://127.0.0.1:" + listener.getLocalPort()); + props.setPath("/brand_check"); + props.setRetryTimes(2); + props.setRetryIntervalMillis(1); + props.setUnreachableCooldownMillis(300_000); + BrandCheckClient client = + new BrandCheckClient(props, null, stubbedUserSecrets(), cooldown); + + BrandCheckClient.BrandCheckBatchResult first = + client.checkAll(List.of("Apple"), "Terms", 7L); + assertThat(connections.get()).as("首批两条阶梯都真发(no-answer 不改本批重试形状)").isGreaterThanOrEqualTo(2); + assertThat(cooldown.noAnswerLaneCooling(props.getBaseUrl(), 300_000L)).isTrue(); + assertThat(first.reason()).doesNotContain("解密链路成片失败"); + + int connectionsBefore = connections.get(); + BrandCheckClient.BrandCheckBatchResult second = + client.checkAll(List.of("Nike"), "Terms", 7L); + assertThat(connections.get()).as("冷却期内一个请求都不该发").isEqualTo(connectionsBefore); + assertThat(second.queryFaildData()).containsExactly("Nike"); + assertThat(second.reason()).contains("品牌检测服务不可达(解密链路成片失败,非本行数据问题)"); + } finally { + listener.close(); + } + } + + /** + * 「解密失败成片」在批终态按票记证(阈值 2 与 connect 道同数字):一批两枚脏名真探 + * (上游标了不可重试,白等已被既有短路掐住)即开窗,第二批准一个请求不发。 + */ + @Test + void decryptShapedBatchOpensCooldownAndNextBatchHitsZeroProbes() throws Exception { + AtomicInteger requests = new AtomicInteger(); + HttpServer server = startBrandCheckServer(exchange -> { + requests.incrementAndGet(); + respond(exchange, "{\"faild_data\":[],\"query_faild_data\":[\"x\"]," + + "\"reason\":\"查询或解密失败: 解密失败: Malformed UTF-8 data\",\"retryable\":false}"); + }); + try { + UnreachableCooldown cooldown = new UnreachableCooldown(); + BrandCheckProperties props = new BrandCheckProperties(); + props.setBaseUrl("http://127.0.0.1:" + server.getAddress().getPort()); + props.setPath("/brand_check"); + props.setRetryTimes(2); + props.setRetryIntervalMillis(1); + props.setUnreachableCooldownMillis(300_000); + BrandCheckClient client = + new BrandCheckClient(props, null, stubbedUserSecrets(), cooldown); + + client.checkAll(List.of("Small)"), "Terms", 7L); + assertThat(cooldown.noAnswerLaneCooling(props.getBaseUrl(), 300_000L)) + .as("一批只有一枚解密票:不到阈值不进冷却").isFalse(); + + client.checkAll(List.of("XX-Large)", "Small)"), "Terms", 7L); + assertThat(requests.get()).as("两批真发合计至少三枚请求").isGreaterThanOrEqualTo(3); + assertThat(cooldown.noAnswerLaneCooling(props.getBaseUrl(), 300_000L)) + .as("零干净批次攒到两条解密票:进入冷却").isTrue(); + + int requestsBefore = requests.get(); + BrandCheckClient.BrandCheckBatchResult cooled = + client.checkAll(List.of("4\" Width x 2\" Height)"), "Terms", 7L); + assertThat(requests.get()).as("冷却期内一个请求都不该发").isEqualTo(requestsBefore); + assertThat(cooled.reason()).contains("品牌检测服务不可达(解密链路成片失败,非本行数据问题)"); + } finally { + server.stop(0); + } + } + + /** + * 反向对照(行级差异必须保留):脏品牌名混在干净品牌里=本行数据问题,不是服务在掉。 + * 零干净结论的条件不成立 ⇒ 永远不进冷却,各品牌照旧各查各的。 + */ + @Test + void mixedDecryptFailuresWithCleanBrandsNeverEnterCooldown() throws Exception { + AtomicInteger decryptRequests = new AtomicInteger(); + HttpServer server = startBrandCheckServer(exchange -> { + String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8); + if (body.contains("Small")) { + decryptRequests.incrementAndGet(); + respond(exchange, "{\"faild_data\":[],\"query_faild_data\":[\"Small)\"]," + + "\"reason\":\"查询或解密失败: 解密失败: Malformed UTF-8 data\"}"); + } else { + respond(exchange, "{\"faild_data\":[],\"query_faild_data\":[]}"); + } + }); + try { + UnreachableCooldown cooldown = new UnreachableCooldown(); + BrandCheckProperties props = new BrandCheckProperties(); + props.setBaseUrl("http://127.0.0.1:" + server.getAddress().getPort()); + props.setPath("/brand_check"); + props.setRetryTimes(2); + props.setRetryIntervalMillis(1); + props.setUnreachableCooldownMillis(300_000); + BrandCheckClient client = + new BrandCheckClient(props, null, stubbedUserSecrets(), cooldown); + + client.checkAll(List.of("Nike", "Small)"), "Terms", 7L); + client.checkAll(List.of("Apple", "Small)"), "Terms", 7L); + + assertThat(cooldown.noAnswerLaneCooling(props.getBaseUrl(), 300_000L)).isFalse(); + assertThat(decryptRequests.get()) + .as("混批里脏名品牌照旧逐行真查(行级证据面不变)").isGreaterThanOrEqualTo(4); + } finally { + server.stop(0); + } + } + + /** 两个形状判定的口径钉死:不回包只认那两句原文,读超时不算;解密形状认现网三形。 */ + @Test + void noAnswerPredicatesPinTheLiveShapes() { + assertThat(BrandCheckClient.isPeerClosedWithoutResponse(new ResourceAccessException( + "I/O error on POST request for \"http://47.110.241.161:16890/brand_check\"", + new java.io.IOException("HTTP/1.1 header parser received no bytes")))).isTrue(); + assertThat(BrandCheckClient.isPeerClosedWithoutResponse( + new java.io.IOException("EOF reached while reading"))).isTrue(); + assertThat(BrandCheckClient.isPeerClosedWithoutResponse( + new SocketTimeoutException("Read timed out"))).isFalse(); + assertThat(BrandCheckClient.isPeerClosedWithoutResponse( + new HttpTimeoutException("request timed out"))).isFalse(); + assertThat(BrandCheckClient.isPeerClosedWithoutResponse(null)).isFalse(); + + assertThat(BrandCheckClient.isDecryptFailure("查询或解密失败: 解密失败: Malformed UTF-8 data")).isTrue(); + assertThat(BrandCheckClient.isDecryptFailure("解密失败: 解密失败: Malformed UTF-8 data")).isTrue(); + assertThat(BrandCheckClient.isDecryptFailure( + "查询或解密失败: Expecting value: line 1 column 1 (char 0)")).isTrue(); + assertThat(BrandCheckClient.isDecryptFailure("有 2~3 行抓取失败(未取得商品页数据):B07P5TR7Q5")).isFalse(); + assertThat(BrandCheckClient.isDecryptFailure("")).isFalse(); + assertThat(BrandCheckClient.isDecryptFailure(null)).isFalse(); + } + @Test void pausedAccountStopsBatchWithoutHittingUpstream() throws Exception { AtomicInteger attempts = new AtomicInteger();