Skip to content

Commit e5bf005

Browse files
committed
fix: reconnect OpenCLI worker after failed result delivery
1 parent 4270441 commit e5bf005

3 files changed

Lines changed: 87 additions & 11 deletions

File tree

‎openspec/changes/harden-opencli-reverse-agent/tasks.md‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@
1818

1919
## 3. 兼容与验收
2020

21-
- [ ] 3.1 证明重连不自动重复写入,完成发送失败不被误标为执行失败。
22-
- [ ] 3.2 验证现有消息结构在 legacy fixture 中不变,安全日志符合 C09。
21+
- [x] 3.1 证明重连不自动重复写入,完成发送失败不被误标为执行失败。
22+
- [x] 3.2 验证现有消息结构在 legacy fixture 中不变,安全日志符合 C09。
2323
- [ ] 3.3 分别在三线运行 WS压力/断线fixture,记录执行次数、线程数与终结资源结果。
2424

2525
## 证据交付模板(实施时填写)
@@ -51,3 +51,9 @@ JDK 17 定向 28 项通过。JDK 21 使用仓库 Maven Wrapper 执行 `-B -ntp -
5151
JDK 17 定向红灯复现三项失败,退出 1。拼接 JSON 错误推进注册,超长单帧和分片均未关闭连接。修复后验证合法确认仍可接单,两个超限场景均关闭连接、没有 CLI 标记且重新注册。发送单个超长帧时,接收方可能在对端写完前关闭连接,对端可观察到 1006 或 1009。分片超限场景验证 1009。补充拒绝零、负数及库定义的无限哨兵设置。JDK 17 定向 34 项通过。
5252

5353
JDK 21 使用仓库 Maven Wrapper 执行 `-B -ntp -o clean verify`,2,128 项通过,0 失败、0 错误、0 跳过。
54+
55+
## 2026-11-19 OC-WS-005 投递失败和旧协议兼容
56+
57+
在 TLS 回环环境向第一次结果发送注入异常,CLI 子进程实际写入执行标记。修复前中心等待第二次注册超时,定向 2 项中 1 项失败,退出 1。修复后失败连接退役。第二条连接完成注册和心跳时,中心仍未收到自动投递。中心显式重发相同请求后,收到原成功结果和 `cached: true`,`error` 为空,实际子进程标记始终为一条。日志捕获包含固定的投递失败消息,异常内测试密钥未出现在日志中。
58+
59+
旧协议夹具继续核对 register 的五个字段、pong 的单字段、成功与失败 result 的五个字段,以及实际进程收到的完整 argv。三个版本的直接字段断言通过。JDK 17 定向 35 项通过。JDK 21 使用仓库 Maven Wrapper 执行 `-B -ntp -o clean verify`,2,129 项通过,0 失败、0 错误、0 跳过。全量通过后单独复跑加严的旧协议字段断言,1 项通过。此处的诊断结论覆盖反向 Worker,跨传输隐私仍由 C09 跟踪。

‎src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentClient.java‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
import java.util.concurrent.ThreadPoolExecutor;
3232
import java.util.concurrent.TimeUnit;
3333
import java.util.concurrent.atomic.AtomicReference;
34+
import java.util.function.BiConsumer;
3435
import lombok.extern.slf4j.Slf4j;
3536
import org.java_websocket.client.WebSocketClient;
3637
import org.java_websocket.drafts.Draft_6455;
@@ -61,6 +62,7 @@ public final class OpenCliWsReverseAgentClient implements AutoCloseable {
6162
private static final long CLOSE_WAIT_NANOS = TimeUnit.SECONDS.toNanos(5);
6263

6364
private final OpenCliExecutor localExecutor;
65+
private final BiConsumer<WebSocketClient, String> resultSender;
6466

6567
private final OpenCliWsAgentConnectionProperties connectionProperties;
6668

@@ -84,6 +86,12 @@ public final class OpenCliWsReverseAgentClient implements AutoCloseable {
8486
*/
8587
public OpenCliWsReverseAgentClient(
8688
OpenCliProperties openCliProperties, OpenCliWsAgentConnectionProperties connectionProperties) {
89+
this(openCliProperties, connectionProperties, WebSocketClient::send);
90+
}
91+
92+
OpenCliWsReverseAgentClient(OpenCliProperties openCliProperties,
93+
OpenCliWsAgentConnectionProperties connectionProperties, BiConsumer<WebSocketClient, String> resultSender) {
94+
this.resultSender = Objects.requireNonNull(resultSender, "resultSender");
8795
Objects.requireNonNull(openCliProperties, "openCliProperties");
8896
this.connectionProperties =
8997
Objects.requireNonNull(connectionProperties, "connectionProperties");
@@ -453,7 +461,7 @@ private void handleTextMessage(WorkerSession ws, String payload) throws Exceptio
453461
}
454462
}
455463

456-
private void admitCollect(WebSocketClient ws, Object centerIdentity, String requestId, JsonNode payload)
464+
private void admitCollect(WorkerSession ws, Object centerIdentity, String requestId, JsonNode payload)
457465
throws Exception {
458466
OpenCliWsCollectRequests.Key key = new OpenCliWsCollectRequests.Key(centerIdentity, requestId);
459467
byte[] digest = MessageDigest.getInstance("SHA-256").digest(MAPPER.writeValueAsBytes(payload));
@@ -498,13 +506,13 @@ private synchronized boolean mayStartCollect(long epoch) {
498506
}
499507

500508
private final class CollectTask implements Runnable {
501-
private final WebSocketClient socket;
509+
private final WorkerSession socket;
502510
private final OpenCliWsCollectRequests.Key key;
503511
private final JsonNode message;
504512
private final long epoch;
505513
private final OpenCliCancellationToken cancellation = new OpenCliCancellationToken();
506514

507-
CollectTask(WebSocketClient socket, OpenCliWsCollectRequests.Key key, JsonNode message, long epoch) {
515+
CollectTask(WorkerSession socket, OpenCliWsCollectRequests.Key key, JsonNode message, long epoch) {
508516
this.socket = socket;
509517
this.key = key;
510518
this.message = message;
@@ -617,11 +625,13 @@ private static ObjectNode result(String requestId, boolean success, List<JsonNod
617625
return out;
618626
}
619627

620-
private static void sendResult(WebSocketClient ws, ObjectNode result) {
628+
private void sendResult(WorkerSession ws, ObjectNode result) {
621629
try {
622-
ws.send(MAPPER.writeValueAsString(result));
630+
resultSender.accept(ws, MAPPER.writeValueAsString(result));
623631
} catch (Exception e) {
624632
log.error("failed to send WS result");
633+
ws.retire(e);
634+
closeSession(ws);
625635
}
626636
}
627637
}

‎src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java‎

Lines changed: 64 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
import io.github.easy4j.opencli.OpenCliProperties;
77
import io.github.easy4j.opencli.contract.ContractProbe;
88
import io.github.easy4j.opencli.contract.LifecycleProbe;
9+
import java.io.ByteArrayOutputStream;
10+
import java.io.PrintStream;
911
import java.io.File;
1012
import tools.jackson.core.JacksonException;
1113
import java.io.InputStream;
@@ -26,6 +28,7 @@
2628
import java.util.concurrent.CountDownLatch;
2729
import java.util.concurrent.LinkedBlockingQueue;
2830
import java.util.concurrent.TimeUnit;
31+
import java.util.concurrent.atomic.AtomicBoolean;
2932
import java.util.concurrent.atomic.AtomicReference;
3033
import java.util.stream.Collectors;
3134
import javax.net.ssl.KeyManagerFactory;
@@ -106,24 +109,27 @@ void exchangesRegistrationAndCollectResultsAndReconnectsAfterRemoteClose() throw
106109
try (OpenCliWsReverseAgentClient agent = new OpenCliWsReverseAgentClient(probe(ContractProbe.class.getName()), connection)) {
107110
agent.start();
108111
WireMessage registration = center.receive("register");
112+
assertEquals(5, registration.body.size());
109113
assertEquals(AGENT_URL, registration.body.path("agent_url").asText());
110114
assertEquals("cdp", registration.body.path("mode").asText());
111115
assertEquals("shell", registration.body.path("node_type").asText());
116+
assertTrue(registration.body.path("label").isTextual());
112117
assertTrue(registration.body.path("label").asText().isEmpty());
113118

114119
registration.socket.send("{\"type\":\"registered\"}");
115120
agent.start();
116121
registration.socket.send("malformed-json");
117122
registration.socket.send("{\"type\":\"pong\"}");
118123
registration.socket.send("{\"type\":\"ping\"}");
119-
center.receive("pong");
124+
assertEquals(1, center.receive("pong").body.size());
120125

121126
registration.socket.send("{\"type\":\"collect\",\"request_id\":\"valid\","
122127
+ "\"site\":\"demo\",\"command\":\"echo\",\"format\":\"text\","
123128
+ "\"positional_args\":[\" kept \",null,42],\"args\":{"
124129
+ "\"flag\":null,\"boolean\":false,\"count\":7,\"long\":2147483648,"
125130
+ "\"double\":1.5,\"text\":\"a b\",\"structured\":{\"key\":1}}}");
126131
JsonNode result = center.receive("result").body;
132+
assertEquals(5, result.size());
127133
assertEquals("valid", result.path("request_id").asText());
128134
assertTrue(result.path("success").asBoolean());
129135
assertTrue(result.path("error").isNull());
@@ -137,6 +143,7 @@ void exchangesRegistrationAndCollectResultsAndReconnectsAfterRemoteClose() throw
137143

138144
registration.socket.send("{\"type\":\"collect\",\"request_id\":\"invalid\",\"command\":\"echo\"}");
139145
JsonNode invalid = center.receive("result").body;
146+
assertEquals(5, invalid.size());
140147
assertEquals("invalid", invalid.path("request_id").asText());
141148
assertFalse(invalid.path("success").asBoolean());
142149
assertTrue(invalid.path("items").isEmpty());
@@ -471,8 +478,9 @@ void plainWebSocketReconnectDoesNotExposePreviousSessionCache(@TempDir Path temp
471478
verifyReconnectReplay(temporary, null, false);
472479
}
473480

474-
@Test
475-
void verifiedTlsReconnectReplaysOnlyAfterAnExplicitRetry(@TempDir Path temporary) throws Exception {
481+
@ParameterizedTest
482+
@ValueSource(booleans = {false, true})
483+
void verifiedTlsReconnectReplaysOnlyAfterAnExplicitRetry(boolean failDelivery, @TempDir Path temporary) throws Exception {
476484
Path storePath = temporary.resolve("center.p12");
477485
String keytool = System.getProperty("os.name").startsWith("Windows") ? "keytool.exe" : "keytool";
478486
Path tool = Paths.get(System.getProperty("java.home"), "bin", keytool);
@@ -503,12 +511,64 @@ void verifiedTlsReconnectReplaysOnlyAfterAnExplicitRetry(@TempDir Path temporary
503511
SSLContext previous = SSLContext.getDefault();
504512
try {
505513
SSLContext.setDefault(trustedClient);
506-
verifyReconnectReplay(temporary, server, true);
514+
if (failDelivery) {
515+
verifyFailedDeliveryReplay(temporary, server);
516+
} else {
517+
verifyReconnectReplay(temporary, server, true);
518+
}
507519
} finally {
508520
SSLContext.setDefault(previous);
509521
}
510522
}
511523

524+
private static void verifyFailedDeliveryReplay(Path temporary, SSLContext tls) throws Exception {
525+
Path marker = temporary.resolve("delivery-start");
526+
Path release = Files.createFile(temporary.resolve("delivery-release"));
527+
ObjectNode request = collect("delivery", "count-hold", marker);
528+
request.putArray("positional_args").add(release.toString());
529+
String canary = "delivery-exception-private-canary";
530+
AtomicBoolean firstSend = new AtomicBoolean(true);
531+
ByteArrayOutputStream diagnostics = new ByteArrayOutputStream();
532+
PrintStream previousErr = System.err;
533+
try (LocalCenter center = new LocalCenter(tls);
534+
OpenCliWsReverseAgentClient agent = new OpenCliWsReverseAgentClient(
535+
probe(LifecycleProbe.class.getName()), center.agentProperties(), (socket, json) -> {
536+
if (firstSend.getAndSet(false)) {
537+
throw new IllegalStateException(canary);
538+
}
539+
socket.send(json);
540+
});
541+
PrintStream capture = new PrintStream(diagnostics, true, "UTF-8")) {
542+
System.setErr(capture);
543+
try {
544+
agent.start();
545+
WebSocket first = center.receive("register").socket;
546+
first.send("{\"type\":\"registered\"}");
547+
first.send(request.toString());
548+
549+
WebSocket second = center.receive("register").socket;
550+
assertNotSame(first, second);
551+
second.send("{\"type\":\"registered\"}");
552+
second.send("{\"type\":\"ping\"}");
553+
center.receive("pong");
554+
assertEquals(Arrays.asList("started"), Files.readAllLines(marker, StandardCharsets.UTF_8));
555+
556+
second.send(request.toString());
557+
JsonNode replayed = center.receive("result").body;
558+
assertEquals("delivery", replayed.path("request_id").asText());
559+
assertTrue(replayed.path("success").asBoolean());
560+
assertTrue(replayed.path("cached").asBoolean());
561+
assertTrue(replayed.path("error").isNull());
562+
assertEquals(Arrays.asList("started"), Files.readAllLines(marker, StandardCharsets.UTF_8));
563+
} finally {
564+
System.setErr(previousErr);
565+
}
566+
}
567+
String logText = diagnostics.toString(StandardCharsets.UTF_8.name());
568+
assertTrue(logText.contains("failed to send WS result"));
569+
assertFalse(logText.contains(canary));
570+
}
571+
512572
private static void verifyReconnectReplay(Path temporary, SSLContext tls, boolean expectCache) throws Exception {
513573
Path marker = temporary.resolve("reconnect-start");
514574
Path release = temporary.resolve("reconnect-release");

0 commit comments

Comments
 (0)