Skip to content

Commit 59f4ad9

Browse files
committed
fix: retire stopped OpenCLI WebSocket generations
1 parent 20d5d6b commit 59f4ad9

3 files changed

Lines changed: 98 additions & 23 deletions

File tree

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

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
# C05 Tasks · 反向 Worker 状态机、背压与去重
22

3-
> 全部为待执行实现任务。文档/格式检查通过不允许提前勾选。
3+
> 已勾选项有对应的实现和回归证据。
44
55
关联规范:[spec](specs/opencli-reverse-agent/spec.md)。
66

77
## 1. Worker fixture
88

9-
- [ ] 1.1 新增可控本地 WS server,覆盖未注册 collect、超大/空 ID、队列满与重复消息。
10-
- [ ] 1.2 加入断线写任务、代际结果路由、close竞态和重启边界的失败测试。
9+
- [x] 1.1 新增可控本地 WS server,覆盖未注册 collect、超大/空 ID、队列满与重复消息。
10+
- [x] 1.2 加入断线写任务、代际结果路由、close竞态和重启边界的失败测试。
1111

1212
## 2. 治理实现
1313

@@ -29,3 +29,9 @@
2929
## JDK 21 回移验证
3030

3131
回移 JDK 17 版本的注册前拒绝、执行与等待上限、关闭保护、请求去重、缓存过期和连接隔离。通过本地回环服务器、真实子进程和测试证书验证普通连接和 TLS 重连。运行 `bash ./mvnw -B -ntp -o clean verify`,2,112 项测试通过,零失败、零跳过,JaCoCo 行覆盖率为 2,890 / 3,148(91.80%)。
32+
33+
## 2026-11-19 OC-WS-005/006 代际发布与停止竞态
34+
35+
`stopDuringConnectionSetupDoesNotPublishAnotherGeneration` 在连接线程读取端点时阻塞配置读取,随后调用 `stop()`,再解除阻塞。修复前本地中心收到已停止 worker 的注册消息,1 项失败,退出 1。修复后停止和连接发布共用同步边界,晚到连接无法发布。异常、关闭及退出均只退役对应 socket,当前代际检查用于注册、收单和异步结果投递。同一个已验证 TLS 中心显式重发仍可读取对应缓存。异常的默认日志保持固定文本。
36+
37+
`OpenCliWsReverseAgentSessionTest` 的回环服务同时覆盖提前收单、空白和超大 ID、队列溢出、重复请求、断线时在途工作、TLS 显式重发、明文会话隔离、关闭丢弃队列及关闭后拒绝重启。JDK 17 定向验证 27 项通过。JDK 21 使用仓库 Maven Wrapper 执行 `-B -ntp -o clean verify`,2,121 项通过,0 失败、0 错误、0 跳过。显式状态机、可重启 stop 的任务收尾合同和平台资源验收仍由相应任务跟踪。

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

Lines changed: 50 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ public final class OpenCliWsReverseAgentClient implements AutoCloseable {
6464

6565
private volatile boolean shutdownRequested;
6666

67-
private volatile WebSocketClient activeClient;
67+
private final AtomicReference<WebSocketClient> activeClient = new AtomicReference<>();
6868

6969
private Thread runnerThread;
7070

@@ -112,8 +112,7 @@ public synchronized void start() {
112112
*/
113113
public synchronized void stop() {
114114
shutdownRequested = true;
115-
WebSocketClient client = activeClient;
116-
activeClient = null;
115+
WebSocketClient client = activeClient.getAndSet(null);
117116
if (Objects.nonNull(client)) {
118117
try {
119118
client.close();
@@ -200,6 +199,10 @@ private void runOneSession() throws Exception {
200199
new WebSocketClient(endpoint) {
201200
@Override
202201
public void onOpen(ServerHandshake handshake) {
202+
if (!isCurrentSession(this)) {
203+
closeSession(this);
204+
return;
205+
}
203206
try {
204207
send(buildRegisterJson());
205208
} catch (Exception e) {
@@ -220,6 +223,7 @@ public void onMessage(String message) {
220223

221224
@Override
222225
public void onClose(int code, String reason, boolean remote) {
226+
activeClient.compareAndSet(this, null);
223227
if (registered.getCount() > 0) {
224228
handshakeFailure.compareAndSet(
225229
null,
@@ -234,6 +238,7 @@ public void onClose(int code, String reason, boolean remote) {
234238

235239
@Override
236240
public void onError(Exception ex) {
241+
activeClient.compareAndSet(this, null);
237242
log.warn("WebSocket error");
238243
if (registered.getCount() > 0) {
239244
handshakeFailure.compareAndSet(null, ex);
@@ -243,26 +248,48 @@ public void onError(Exception ex) {
243248
}
244249
};
245250

246-
activeClient = client;
247-
if (!client.connectBlocking(30, TimeUnit.SECONDS)) {
248-
throw new IllegalStateException("WebSocket connectBlocking returned false");
251+
if (!publishSession(client)) {
252+
return;
249253
}
254+
try {
255+
if (!client.connectBlocking(30, TimeUnit.SECONDS)) {
256+
throw new IllegalStateException("WebSocket connectBlocking returned false");
257+
}
258+
if (!registered.await(connectionProperties.getHandshakeTimeoutMillis(), TimeUnit.MILLISECONDS)) {
259+
throw new IllegalStateException("Timeout waiting for 'registered' from center");
260+
}
261+
Throwable hf = handshakeFailure.get();
262+
if (Objects.nonNull(hf)) {
263+
if (hf instanceof Exception) {
264+
throw (Exception) hf;
265+
}
266+
throw new IllegalStateException(hf);
267+
}
268+
sessionClosed.await();
269+
} finally {
270+
activeClient.compareAndSet(client, null);
271+
closeSession(client);
272+
}
273+
}
250274

251-
if (!registered.await(connectionProperties.getHandshakeTimeoutMillis(), TimeUnit.MILLISECONDS)) {
252-
client.close();
253-
throw new IllegalStateException("Timeout waiting for 'registered' from center");
275+
private synchronized boolean publishSession(WebSocketClient client) {
276+
if (shutdownRequested) {
277+
return false;
254278
}
255-
Throwable hf = handshakeFailure.get();
256-
if (Objects.nonNull(hf)) {
279+
activeClient.set(client);
280+
return true;
281+
}
282+
283+
private boolean isCurrentSession(WebSocketClient client) {
284+
return !shutdownRequested && activeClient.get() == client;
285+
}
286+
287+
private static void closeSession(WebSocketClient client) {
288+
try {
257289
client.close();
258-
if (hf instanceof Exception) {
259-
throw (Exception) hf;
260-
}
261-
throw new IllegalStateException(hf);
290+
} catch (Exception e) {
291+
log.debug("ws session close failed");
262292
}
263-
264-
sessionClosed.await();
265-
activeClient = null;
266293
}
267294

268295
private void validateConnectionProperties() {
@@ -315,6 +342,9 @@ private void handleTextMessage(
315342
CountDownLatch registered,
316343
AtomicReference<Throwable> handshakeFailure)
317344
throws Exception {
345+
if (!isCurrentSession(ws)) {
346+
return;
347+
}
318348
JsonNode root = MAPPER.readTree(payload);
319349
String type = root.path("type").asText("");
320350
if ("registered".equals(type)) {
@@ -335,7 +365,7 @@ private void handleTextMessage(
335365
sendResult(ws, result("", false, Collections.emptyList(), "invalid worker request ID"));
336366
return;
337367
}
338-
if (shutdownRequested || !ws.isOpen() || registered.getCount() > 0
368+
if (!isCurrentSession(ws) || !ws.isOpen() || registered.getCount() > 0
339369
|| Objects.nonNull(handshakeFailure.get())) {
340370
sendResult(ws, result(requestId, false, Collections.emptyList(), "worker is not registered"));
341371
return;
@@ -378,7 +408,7 @@ private void runCollectSafe(WebSocketClient ws, OpenCliWsCollectRequests.Key key
378408
} finally {
379409
collectRequests.complete(key, response);
380410
}
381-
if (Objects.nonNull(response) && ws.isOpen()) {
411+
if (Objects.nonNull(response) && isCurrentSession(ws) && ws.isOpen()) {
382412
sendResult(ws, response);
383413
}
384414
}

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

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,45 @@ class OpenCliWsReverseAgentSessionTest {
5555
private static final JsonMapper MAPPER = new JsonMapper();
5656
private static final String AGENT_URL = "http://127.0.0.1:19823";
5757

58+
@Test
59+
void stopDuringConnectionSetupDoesNotPublishAnotherGeneration() throws Exception {
60+
CountDownLatch resolving = new CountDownLatch(1);
61+
CountDownLatch release = new CountDownLatch(1);
62+
try (LocalCenter center = new LocalCenter()) {
63+
OpenCliWsAgentConnectionProperties connection = new OpenCliWsAgentConnectionProperties() {
64+
@Override
65+
public String getCentralApiBaseUrl() {
66+
resolving.countDown();
67+
boolean interrupted = false;
68+
while (release.getCount() > 0) {
69+
try {
70+
release.await();
71+
} catch (InterruptedException failure) {
72+
interrupted = true;
73+
}
74+
}
75+
if (interrupted) {
76+
Thread.currentThread().interrupt();
77+
}
78+
return super.getCentralApiBaseUrl();
79+
}
80+
};
81+
connection.setCentralApiBaseUrl(center.agentProperties().getCentralApiBaseUrl());
82+
connection.setAgentAdvertiseUrl(AGENT_URL);
83+
try (OpenCliWsReverseAgentClient agent = new OpenCliWsReverseAgentClient(
84+
probe(ContractProbe.class.getName()), connection)) {
85+
try {
86+
agent.start();
87+
assertTrue(resolving.await(5, TimeUnit.SECONDS));
88+
agent.stop();
89+
} finally {
90+
release.countDown();
91+
}
92+
assertNull(center.messages.poll(1, TimeUnit.SECONDS), "stopped worker published a registration");
93+
}
94+
}
95+
}
96+
5897
@Test
5998
void exchangesRegistrationAndCollectResultsAndReconnectsAfterRemoteClose() throws Exception {
6099
try (LocalCenter center = new LocalCenter()) {

0 commit comments

Comments
 (0)