Skip to content

Commit 76e92d4

Browse files
committed
fix: retire stopped OpenCLI WebSocket generations
1 parent 324b9e1 commit 76e92d4

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

@@ -37,3 +37,9 @@ OC-WS-002 使用实际子进程启动标记验证容量。旧实现启动第五
3737
OC-WS-006 的关闭回归先复现旧实现关闭后仍启动队列任务。关闭现在丢弃队列、请求中断在途执行,并为执行器与重连线程共用最多 5 秒等待。回归验证队列中的子进程未启动、重复关闭安全、已关闭实例拒绝重启。JDK 17 `clean verify` 通过 2,108 项测试,零跳过,行覆盖率为 2,838 / 3,095(91.70%)。完整的断线代际及三线资源回收验收仍由对应任务跟踪。
3838

3939
OC-WS-003/004/005 本地回环验证覆盖 128 字节请求 ID 边界、相同请求在途去重、同 ID 不同载荷拒绝、完成缓存淘汰与过期。断线测试保留真实子进程在途,验证旧结果未主动发送到新连接。经过 JVM 信任及主机名校验的 TLS 连接显式重发后得到缓存结果。明文连接按会话隔离。缓存默认保留最近 1,024 条已完成结果,每条最多 10 分钟,进程重启后重新建立去重状态。JDK 17 全量构建通过 2,113 项测试,零失败、零跳过,JaCoCo 行覆盖率为 2,891 / 3,149(91.81%)。
40+
41+
## 2026-11-19 OC-WS-005/006 代际发布与停止竞态
42+
43+
`stopDuringConnectionSetupDoesNotPublishAnotherGeneration` 在连接线程读取端点时阻塞配置读取,随后调用 `stop()`,再解除阻塞。修复前本地中心收到已停止 worker 的注册消息,1 项失败,退出 1。修复后停止和连接发布共用同步边界,晚到连接无法发布。异常、关闭及退出均只退役对应 socket,当前代际检查用于注册、收单和异步结果投递。同一个已验证 TLS 中心显式重发仍可读取对应缓存。异常的默认日志保持固定文本。
44+
45+
`OpenCliWsReverseAgentSessionTest` 的回环服务同时覆盖提前收单、空白和超大 ID、队列溢出、重复请求、断线时在途工作、TLS 显式重发、明文会话隔离、关闭丢弃队列及关闭后拒绝重启。JDK 17 定向验证 27 项通过。JDK 17 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,122 项通过,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
@@ -65,7 +65,7 @@ public final class OpenCliWsReverseAgentClient implements AutoCloseable {
6565

6666
private volatile boolean shutdownRequested;
6767

68-
private volatile WebSocketClient activeClient;
68+
private final AtomicReference<WebSocketClient> activeClient = new AtomicReference<>();
6969

7070
private Thread runnerThread;
7171

@@ -113,8 +113,7 @@ public synchronized void start() {
113113
*/
114114
public synchronized void stop() {
115115
shutdownRequested = true;
116-
WebSocketClient client = activeClient;
117-
activeClient = null;
116+
WebSocketClient client = activeClient.getAndSet(null);
118117
if (Objects.nonNull(client)) {
119118
try {
120119
client.close();
@@ -201,6 +200,10 @@ private void runOneSession() throws Exception {
201200
new WebSocketClient(endpoint) {
202201
@Override
203202
public void onOpen(ServerHandshake handshake) {
203+
if (!isCurrentSession(this)) {
204+
closeSession(this);
205+
return;
206+
}
204207
try {
205208
send(buildRegisterJson());
206209
} catch (Exception e) {
@@ -221,6 +224,7 @@ public void onMessage(String message) {
221224

222225
@Override
223226
public void onClose(int code, String reason, boolean remote) {
227+
activeClient.compareAndSet(this, null);
224228
if (registered.getCount() > 0) {
225229
handshakeFailure.compareAndSet(
226230
null,
@@ -235,6 +239,7 @@ public void onClose(int code, String reason, boolean remote) {
235239

236240
@Override
237241
public void onError(Exception ex) {
242+
activeClient.compareAndSet(this, null);
238243
log.warn("WebSocket error");
239244
if (registered.getCount() > 0) {
240245
handshakeFailure.compareAndSet(null, ex);
@@ -244,26 +249,48 @@ public void onError(Exception ex) {
244249
}
245250
};
246251

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

252-
if (!registered.await(connectionProperties.getHandshakeTimeoutMillis(), TimeUnit.MILLISECONDS)) {
253-
client.close();
254-
throw new IllegalStateException("Timeout waiting for 'registered' from center");
276+
private synchronized boolean publishSession(WebSocketClient client) {
277+
if (shutdownRequested) {
278+
return false;
255279
}
256-
Throwable hf = handshakeFailure.get();
257-
if (Objects.nonNull(hf)) {
280+
activeClient.set(client);
281+
return true;
282+
}
283+
284+
private boolean isCurrentSession(WebSocketClient client) {
285+
return !shutdownRequested && activeClient.get() == client;
286+
}
287+
288+
private static void closeSession(WebSocketClient client) {
289+
try {
258290
client.close();
259-
if (hf instanceof Exception) {
260-
throw (Exception) hf;
261-
}
262-
throw new IllegalStateException(hf);
291+
} catch (Exception e) {
292+
log.debug("ws session close failed");
263293
}
264-
265-
sessionClosed.await();
266-
activeClient = null;
267294
}
268295

269296
private void validateConnectionProperties() {
@@ -316,6 +343,9 @@ private void handleTextMessage(
316343
CountDownLatch registered,
317344
AtomicReference<Throwable> handshakeFailure)
318345
throws Exception {
346+
if (!isCurrentSession(ws)) {
347+
return;
348+
}
319349
JsonNode root = MAPPER.readTree(payload);
320350
String type = root.path("type").asText("");
321351
if ("registered".equals(type)) {
@@ -336,7 +366,7 @@ private void handleTextMessage(
336366
sendResult(ws, result("", false, Collections.emptyList(), "invalid worker request ID"));
337367
return;
338368
}
339-
if (shutdownRequested || !ws.isOpen() || registered.getCount() > 0
369+
if (!isCurrentSession(ws) || !ws.isOpen() || registered.getCount() > 0
340370
|| Objects.nonNull(handshakeFailure.get())) {
341371
sendResult(ws, result(requestId, false, Collections.emptyList(), "worker is not registered"));
342372
return;
@@ -379,7 +409,7 @@ private void runCollectSafe(WebSocketClient ws, OpenCliWsCollectRequests.Key key
379409
} finally {
380410
collectRequests.complete(key, response);
381411
}
382-
if (Objects.nonNull(response) && ws.isOpen()) {
412+
if (Objects.nonNull(response) && isCurrentSession(ws) && ws.isOpen()) {
383413
sendResult(ws, response);
384414
}
385415
}

‎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 ObjectMapper MAPPER = new ObjectMapper();
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)