Skip to content

Commit ae4d409

Browse files
committed
fix: drain OpenCLI reverse worker on restartable stop
1 parent 76e92d4 commit ae4d409

5 files changed

Lines changed: 201 additions & 48 deletions

File tree

‎README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,9 @@ Protocol: edge sends `register`; center replies `registered`; center sends `coll
241241

242242
The reverse agent accepts up to four concurrent collect tasks and 32 queued tasks by default. Set `maxConcurrentCollects` and `maxPendingCollects` on the connection properties before constructing the agent to change the limits. A queue capacity of zero disables waiting. When full, the agent replies with a failed `result` and the error `worker is busy`.
243243

244-
Collect request IDs must be nonblank strings of at most 128 UTF-8 bytes. The agent suppresses identical in-flight requests and rejects a reused ID with a different payload. An explicit retry may return a result marked `cached: true`. The in-memory cache keeps up to 1,024 completed results for at most ten minutes. Replay across reconnects requires the same TLS-verified endpoint. Plain WebSocket connections keep session-local deduplication. Restarting the agent discards its cache.
244+
Collect request IDs must be nonblank strings of at most 128 UTF-8 bytes. The agent suppresses identical in-flight requests and rejects a reused ID with a different payload. An explicit retry may return a result marked `cached: true`. The in-memory cache keeps up to 1,024 completed results for at most ten minutes. Replay across reconnects requires the same TLS-verified endpoint. Plain WebSocket connections keep session-local deduplication. A new agent instance starts with an empty cache.
245+
246+
`stop()` stops admission, discards queued tasks and allows in-flight work up to five seconds to finish before requesting cancellation. After the runner has stopped, `start()` can reconnect the same instance. `close()` immediately requests cancellation and closes the instance permanently.
245247

246248
### Diagnostic export
247249

‎README.zh-CN.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,9 @@ agent.close();
241241

242242
反向 Agent 默认最多同时执行 4 个 collect 任务,另有 32 个等待名额。构建 Agent 前,可在连接配置中设置 `maxConcurrentCollects` 和 `maxPendingCollects`。等待容量为零时直接拒绝超额请求。容量用尽时返回失败的 `result`,错误为 `worker is busy`。
243243

244-
collect 请求 ID 必须为非空白字符串,长度上限 128 个 UTF-8 字节。相同的在途请求只执行一次,同一个 ID 对应不同载荷时会明确拒绝。显式重试已完成的请求有可能收到标记为 `cached: true` 的结果。内存缓存最多保留 1,024 条完成结果,每条最长 10 分钟。跨连接重放要求使用同一个经过 TLS 校验的端点,明文 WebSocket 的去重范围为当前连接。Agent 重启后会清空缓存。
244+
collect 请求 ID 必须为非空白字符串,长度上限 128 个 UTF-8 字节。相同的在途请求只执行一次,同一个 ID 对应不同载荷时会明确拒绝。显式重试已完成的请求有可能收到标记为 `cached: true` 的结果。内存缓存最多保留 1,024 条完成结果,每条最长 10 分钟。跨连接重放要求使用同一个经过 TLS 校验的端点,明文 WebSocket 的去重范围为当前连接。创建新 Agent 实例时从空缓存开始。
245+
246+
`stop()` 停止接单并丢弃等待任务,为已在途任务保留最多 5 秒的收尾时间,随后请求取消。连接线程退出后,同一实例可再次调用 `start()` 重连。`close()` 立即请求取消,并永久关闭该实例。
245247

246248
### 诊断导出
247249

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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
- [ ] 2.1 建立显式状态机及 READY gate,接收线程仅做有界解析与准入。
1515
- [x] 2.2 用有限执行器替换 cached pool,加入容量校验和兼容 BUSY result。
1616
- [x] 2.3 实现 payload digest、在途记录与有界完成缓存;同 ID 不同载荷拒绝。
17-
- [ ] 2.4 实现连接代际与有界 drain/cancel,CLOSED 终态。
17+
- [x] 2.4 实现连接代际与有界 drain/cancel,CLOSED 终态。见 OC-WS-006 验证。
1818

1919
## 3. 兼容与验收
2020

@@ -43,3 +43,11 @@ OC-WS-003/004/005 本地回环验证覆盖 128 字节请求 ID 边界、相同
4343
`stopDuringConnectionSetupDoesNotPublishAnotherGeneration` 在连接线程读取端点时阻塞配置读取,随后调用 `stop()`,再解除阻塞。修复前本地中心收到已停止 worker 的注册消息,1 项失败,退出 1。修复后停止和连接发布共用同步边界,晚到连接无法发布。异常、关闭及退出均只退役对应 socket,当前代际检查用于注册、收单和异步结果投递。同一个已验证 TLS 中心显式重发仍可读取对应缓存。异常的默认日志保持固定文本。
4444

4545
`OpenCliWsReverseAgentSessionTest` 的回环服务同时覆盖提前收单、空白和超大 ID、队列溢出、重复请求、断线时在途工作、TLS 显式重发、明文会话隔离、关闭丢弃队列及关闭后拒绝重启。JDK 17 定向验证 27 项通过。JDK 17 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,122 项通过,0 失败、0 错误、0 跳过。显式状态机、可重启 stop 的任务收尾合同和平台资源验收仍由相应任务跟踪。
46+
47+
## 2026-11-19 OC-WS-006 可重启停止
48+
49+
`restartableStopDropsQueuedCollectsAndCancelsPastDrainDeadline` 在回环中心提交持续心跳的真实 CLI 子进程,并填满等待队列。CLI 时限配置为 20 秒,确保 SDK 命令时限不会代替 Worker 的停止预算。旧实现返回后在途心跳仍递增,定向 1 项失败,退出 1。修复后 `stop()` 先停止准入、退役原连接、撤销未启动的排队任务,给已运行任务最多 5 秒收尾,再取消剩余任务。回归验证停止调用在 7 秒测试窗口内返回、心跳停止、排队任务没有启动、同一实例重连可接收任务。
50+
51+
已启动任务保留去重占位到实际执行收尾。等待任务撤销时释放占位。重连使用原有固定线程池及其容量。终态 `close()` 仍立即取消在途工作,丢弃队列并在共用预算内等待资源回收,关闭后拒绝重启。
52+
53+
JDK 17 定向 28 项通过。JDK 17 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,123 项通过,0 失败、0 错误、0 跳过。显式连接状态机和独立平台资源验收仍由 2.1 和 3.3 跟踪。

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

Lines changed: 139 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import com.fasterxml.jackson.databind.node.ArrayNode;
66
import com.fasterxml.jackson.databind.node.ObjectNode;
77
import io.github.easy4j.opencli.OpenCliProperties;
8+
import io.github.easy4j.opencli.core.OpenCliCancellationToken;
89
import io.github.easy4j.opencli.core.OpenCliExecutor;
910
import io.github.easy4j.opencli.core.OpenCliResult;
1011
import io.github.easy4j.opencli.exception.OpenCliException;
@@ -14,14 +15,15 @@
1415
import java.security.MessageDigest;
1516
import java.util.ArrayList;
1617
import java.util.Collections;
18+
import java.util.HashSet;
1719
import java.util.Iterator;
1820
import java.util.LinkedHashMap;
1921
import java.util.List;
2022
import java.util.Map;
2123
import java.util.Objects;
24+
import java.util.Set;
2225
import java.util.concurrent.BlockingQueue;
2326
import java.util.concurrent.CountDownLatch;
24-
import java.util.concurrent.ExecutorService;
2527
import java.util.concurrent.LinkedBlockingQueue;
2628
import java.util.concurrent.RejectedExecutionException;
2729
import java.util.concurrent.SynchronousQueue;
@@ -59,7 +61,8 @@ public final class OpenCliWsReverseAgentClient implements AutoCloseable {
5961

6062
private final OpenCliWsAgentConnectionProperties connectionProperties;
6163

62-
private final ExecutorService collectPool;
64+
private final ThreadPoolExecutor collectPool;
65+
private final Set<CollectTask> collectTasks = new HashSet<>();
6366
private final OpenCliWsCollectRequests collectRequests =
6467
new OpenCliWsCollectRequests(1024, TimeUnit.MINUTES.toNanos(10), System::nanoTime);
6568

@@ -68,6 +71,8 @@ public final class OpenCliWsReverseAgentClient implements AutoCloseable {
6871
private final AtomicReference<WebSocketClient> activeClient = new AtomicReference<>();
6972

7073
private Thread runnerThread;
74+
private boolean stopping;
75+
private long admissionEpoch;
7176

7277
/**
7378
* @param openCliProperties 本地 opencli 配置
@@ -99,7 +104,7 @@ public synchronized void start() {
99104
if (collectPool.isShutdown()) {
100105
throw new IllegalStateException("WebSocket worker is closed");
101106
}
102-
if (runnerThread != null && runnerThread.isAlive()) {
107+
if (stopping || (Objects.nonNull(runnerThread) && runnerThread.isAlive())) {
103108
return;
104109
}
105110
shutdownRequested = false;
@@ -109,47 +114,101 @@ public synchronized void start() {
109114
}
110115

111116
/**
112-
* 请求停止并关闭当前 WebSocket。
117+
* 停止接单并丢弃未开始的任务。在有限时间内等待已在途任务,随后请求取消。
118+
* 停止完成后可重新启动同一实例。
113119
*/
114-
public synchronized void stop() {
115-
shutdownRequested = true;
116-
WebSocketClient client = activeClient.getAndSet(null);
117-
if (Objects.nonNull(client)) {
118-
try {
119-
client.close();
120-
} catch (Exception e) {
121-
log.debug("ws close failed during stop");
120+
public void stop() {
121+
long deadline = System.nanoTime() + CLOSE_WAIT_NANOS;
122+
WebSocketClient client;
123+
Thread runner;
124+
synchronized (this) {
125+
if (shutdownRequested || collectPool.isShutdown()) {
126+
return;
122127
}
128+
stopping = true;
129+
client = stopAdmission();
130+
runner = runnerThread;
123131
}
124-
if (runnerThread != null) {
125-
runnerThread.interrupt();
132+
try {
133+
if (Objects.nonNull(client)) {
134+
closeSession(client);
135+
}
136+
synchronized (this) {
137+
long remaining = deadline - System.nanoTime();
138+
while (!collectTasks.isEmpty() && remaining > 0) {
139+
TimeUnit.NANOSECONDS.timedWait(this, remaining);
140+
remaining = deadline - System.nanoTime();
141+
}
142+
}
143+
awaitRunner(runner, deadline);
144+
} catch (InterruptedException e) {
145+
Thread.currentThread().interrupt();
146+
} finally {
147+
synchronized (this) {
148+
cancelOutstandingCollects();
149+
stopping = false;
150+
}
126151
}
127152
}
128153

129154
@Override
130155
public void close() {
156+
long deadline = System.nanoTime() + CLOSE_WAIT_NANOS;
157+
WebSocketClient client;
131158
Thread runner;
132159
synchronized (this) {
133160
if (collectPool.isShutdown()) {
134161
return;
135162
}
136-
stop();
163+
client = stopAdmission();
164+
cancelOutstandingCollects();
137165
collectPool.shutdownNow();
138166
collectRequests.clear();
139167
runner = runnerThread;
140168
}
141-
long deadline = System.nanoTime() + CLOSE_WAIT_NANOS;
169+
if (Objects.nonNull(client)) {
170+
closeSession(client);
171+
}
142172
try {
143-
collectPool.awaitTermination(CLOSE_WAIT_NANOS, TimeUnit.NANOSECONDS);
144173
long remaining = deadline - System.nanoTime();
145-
if (remaining > 0 && Objects.nonNull(runner) && runner != Thread.currentThread()) {
146-
TimeUnit.NANOSECONDS.timedJoin(runner, remaining);
174+
if (remaining > 0) {
175+
collectPool.awaitTermination(remaining, TimeUnit.NANOSECONDS);
147176
}
177+
awaitRunner(runner, deadline);
148178
} catch (InterruptedException e) {
149179
Thread.currentThread().interrupt();
150180
}
151181
}
152182

183+
// The caller holds this worker's monitor while invalidating admission and the queue.
184+
private WebSocketClient stopAdmission() {
185+
shutdownRequested = true;
186+
admissionEpoch++;
187+
WebSocketClient client = activeClient.getAndSet(null);
188+
List<Runnable> pending = new ArrayList<>();
189+
collectPool.getQueue().drainTo(pending);
190+
for (Runnable waiting : pending) {
191+
finishCollect((CollectTask) waiting, null);
192+
}
193+
if (Objects.nonNull(runnerThread)) {
194+
runnerThread.interrupt();
195+
}
196+
return client;
197+
}
198+
199+
private void cancelOutstandingCollects() {
200+
for (CollectTask task : collectTasks) {
201+
task.cancellation.cancel();
202+
}
203+
}
204+
205+
private static void awaitRunner(Thread runner, long deadline) throws InterruptedException {
206+
long remaining = deadline - System.nanoTime();
207+
if (remaining > 0 && Objects.nonNull(runner) && runner != Thread.currentThread()) {
208+
TimeUnit.NANOSECONDS.timedJoin(runner, remaining);
209+
}
210+
}
211+
153212
private void runLoop() {
154213
int attempt = 0;
155214
while (!shutdownRequested) {
@@ -379,42 +438,77 @@ private void admitCollect(WebSocketClient ws, Object centerIdentity, String requ
379438
throws Exception {
380439
OpenCliWsCollectRequests.Key key = new OpenCliWsCollectRequests.Key(centerIdentity, requestId);
381440
byte[] digest = MessageDigest.getInstance("SHA-256").digest(MAPPER.writeValueAsBytes(payload));
382-
OpenCliWsCollectRequests.Admission admission = collectRequests.reserve(key, digest);
383-
switch (admission.status()) {
384-
case IN_FLIGHT:
385-
return;
386-
case CONFLICT:
387-
sendResult(ws, result(requestId, false, Collections.emptyList(), "worker request ID conflict"));
388-
return;
389-
case CACHED:
390-
sendResult(ws, admission.cachedResult());
441+
OpenCliWsCollectRequests.Admission admission;
442+
boolean busy = false;
443+
synchronized (this) {
444+
if (!isCurrentSession(ws)) {
391445
return;
392-
case ACCEPTED:
446+
}
447+
admission = collectRequests.reserve(key, digest);
448+
if (admission.status() == OpenCliWsCollectRequests.Status.ACCEPTED) {
449+
CollectTask task = new CollectTask(ws, key, payload, admissionEpoch);
450+
collectTasks.add(task);
393451
try {
394-
collectPool.execute(() -> runCollectSafe(ws, key, payload));
452+
collectPool.execute(task);
395453
} catch (RejectedExecutionException e) {
396-
collectRequests.complete(key, null);
397-
sendResult(ws, result(requestId, false, Collections.emptyList(), "worker is busy"));
454+
finishCollect(task, null);
455+
busy = true;
398456
}
399-
return;
457+
}
458+
}
459+
if (!isCurrentSession(ws)) {
460+
return;
461+
}
462+
if (busy) {
463+
sendResult(ws, result(requestId, false, Collections.emptyList(), "worker is busy"));
464+
} else if (admission.status() == OpenCliWsCollectRequests.Status.CONFLICT) {
465+
sendResult(ws, result(requestId, false, Collections.emptyList(), "worker request ID conflict"));
466+
} else if (admission.status() == OpenCliWsCollectRequests.Status.CACHED) {
467+
sendResult(ws, admission.cachedResult());
400468
}
401469
}
402470

403-
private void runCollectSafe(WebSocketClient ws, OpenCliWsCollectRequests.Key key, JsonNode msg) {
404-
ObjectNode response = null;
405-
try {
406-
if (!collectPool.isShutdown() && !Thread.currentThread().isInterrupted()) {
407-
response = executeCollect(key.requestId(), msg);
408-
}
409-
} finally {
410-
collectRequests.complete(key, response);
471+
private synchronized void finishCollect(CollectTask task, ObjectNode response) {
472+
collectRequests.complete(task.key, response);
473+
collectTasks.remove(task);
474+
notifyAll();
475+
}
476+
477+
private synchronized boolean mayStartCollect(long epoch) {
478+
return !shutdownRequested && epoch == admissionEpoch && !Thread.currentThread().isInterrupted();
479+
}
480+
481+
private final class CollectTask implements Runnable {
482+
private final WebSocketClient socket;
483+
private final OpenCliWsCollectRequests.Key key;
484+
private final JsonNode message;
485+
private final long epoch;
486+
private final OpenCliCancellationToken cancellation = new OpenCliCancellationToken();
487+
488+
CollectTask(WebSocketClient socket, OpenCliWsCollectRequests.Key key, JsonNode message, long epoch) {
489+
this.socket = socket;
490+
this.key = key;
491+
this.message = message;
492+
this.epoch = epoch;
411493
}
412-
if (Objects.nonNull(response) && isCurrentSession(ws) && ws.isOpen()) {
413-
sendResult(ws, response);
494+
495+
@Override
496+
public void run() {
497+
ObjectNode response = null;
498+
try {
499+
if (mayStartCollect(epoch)) {
500+
response = executeCollect(key.requestId(), message, cancellation);
501+
}
502+
} finally {
503+
finishCollect(this, response);
504+
}
505+
if (Objects.nonNull(response) && isCurrentSession(socket) && socket.isOpen()) {
506+
sendResult(socket, response);
507+
}
414508
}
415509
}
416510

417-
private ObjectNode executeCollect(String requestId, JsonNode msg) {
511+
private ObjectNode executeCollect(String requestId, JsonNode msg, OpenCliCancellationToken cancellation) {
418512
try {
419513
String site = msg.path("site").asText("");
420514
String command = msg.path("command").asText("");
@@ -424,7 +518,7 @@ private ObjectNode executeCollect(String requestId, JsonNode msg) {
424518

425519
List<String> argv =
426520
OpenCliCenterWsCollectToArgv.toArgv(site, command, positional, args, format);
427-
OpenCliResult r = localExecutor.invoke(argv);
521+
OpenCliResult r = localExecutor.invoke(argv, cancellation);
428522
List<JsonNode> items = OpenCliWsCollectStdoutItems.parseItems(r.getStdout(), format);
429523
if (!r.isSuccess()) {
430524
return result(requestId, false, items, "opencli reported failure");

0 commit comments

Comments
 (0)