Skip to content

Commit ac80a5d

Browse files
committed
fix: drain OpenCLI reverse worker on restartable stop
1 parent 59f4ad9 commit ac80a5d

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
@@ -226,7 +226,9 @@ Protocol: edge sends `register`; center replies `registered`; center sends `coll
226226

227227
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`.
228228

229-
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.
229+
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.
230+
231+
`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.
230232

231233
### Diagnostic export
232234

‎README.zh-CN.md‎

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

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

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

230232
### 诊断导出
231233

‎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
- [ ] 2.2 用有限执行器替换 cached pool,加入容量校验和兼容 BUSY result。
1616
- [ ] 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

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

3737
`OpenCliWsReverseAgentSessionTest` 的回环服务同时覆盖提前收单、空白和超大 ID、队列溢出、重复请求、断线时在途工作、TLS 显式重发、明文会话隔离、关闭丢弃队列及关闭后拒绝重启。JDK 17 定向验证 27 项通过。JDK 21 使用仓库 Maven Wrapper 执行 `-B -ntp -o clean verify`,2,121 项通过,0 失败、0 错误、0 跳过。显式状态机、可重启 stop 的任务收尾合同和平台资源验收仍由相应任务跟踪。
38+
39+
## 2026-11-19 OC-WS-006 可重启停止
40+
41+
`restartableStopDropsQueuedCollectsAndCancelsPastDrainDeadline` 在回环中心提交持续心跳的真实 CLI 子进程,并填满等待队列。CLI 时限配置为 20 秒,确保 SDK 命令时限不会代替 Worker 的停止预算。旧实现返回后在途心跳仍递增,定向 1 项失败,退出 1。修复后 `stop()` 先停止准入、退役原连接、撤销未启动的排队任务,给已运行任务最多 5 秒收尾,再取消剩余任务。回归验证停止调用在 7 秒测试窗口内返回、心跳停止、排队任务没有启动、同一实例重连可接收任务。
42+
43+
已启动任务保留去重占位到实际执行收尾。等待任务撤销时释放占位。重连使用原有固定线程池及其容量。终态 `close()` 仍立即取消在途工作,丢弃队列并在共用预算内等待资源回收,关闭后拒绝重启。
44+
45+
JDK 17 定向 28 项通过。JDK 21 使用仓库 Maven Wrapper 执行 `-B -ntp -o clean verify`,2,122 项通过,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 tools.jackson.databind.node.ArrayNode;
66
import tools.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;
@@ -15,12 +16,13 @@
1516
import java.util.ArrayList;
1617
import java.util.Collections;
1718
import java.util.LinkedHashMap;
19+
import java.util.HashSet;
1820
import java.util.List;
1921
import java.util.Map;
2022
import java.util.Objects;
23+
import java.util.Set;
2124
import java.util.concurrent.BlockingQueue;
2225
import java.util.concurrent.CountDownLatch;
23-
import java.util.concurrent.ExecutorService;
2426
import java.util.concurrent.LinkedBlockingQueue;
2527
import java.util.concurrent.RejectedExecutionException;
2628
import java.util.concurrent.SynchronousQueue;
@@ -58,7 +60,8 @@ public final class OpenCliWsReverseAgentClient implements AutoCloseable {
5860

5961
private final OpenCliWsAgentConnectionProperties connectionProperties;
6062

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

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

6972
private Thread runnerThread;
73+
private boolean stopping;
74+
private long admissionEpoch;
7075

7176
/**
7277
* @param openCliProperties 本地 opencli 配置
@@ -98,7 +103,7 @@ public synchronized void start() {
98103
if (collectPool.isShutdown()) {
99104
throw new IllegalStateException("WebSocket worker is closed");
100105
}
101-
if (runnerThread != null && runnerThread.isAlive()) {
106+
if (stopping || (Objects.nonNull(runnerThread) && runnerThread.isAlive())) {
102107
return;
103108
}
104109
shutdownRequested = false;
@@ -108,47 +113,101 @@ public synchronized void start() {
108113
}
109114

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

128153
@Override
129154
public void close() {
155+
long deadline = System.nanoTime() + CLOSE_WAIT_NANOS;
156+
WebSocketClient client;
130157
Thread runner;
131158
synchronized (this) {
132159
if (collectPool.isShutdown()) {
133160
return;
134161
}
135-
stop();
162+
client = stopAdmission();
163+
cancelOutstandingCollects();
136164
collectPool.shutdownNow();
137165
collectRequests.clear();
138166
runner = runnerThread;
139167
}
140-
long deadline = System.nanoTime() + CLOSE_WAIT_NANOS;
168+
if (Objects.nonNull(client)) {
169+
closeSession(client);
170+
}
141171
try {
142-
collectPool.awaitTermination(CLOSE_WAIT_NANOS, TimeUnit.NANOSECONDS);
143172
long remaining = deadline - System.nanoTime();
144-
if (remaining > 0 && Objects.nonNull(runner) && runner != Thread.currentThread()) {
145-
TimeUnit.NANOSECONDS.timedJoin(runner, remaining);
173+
if (remaining > 0) {
174+
collectPool.awaitTermination(remaining, TimeUnit.NANOSECONDS);
146175
}
176+
awaitRunner(runner, deadline);
147177
} catch (InterruptedException e) {
148178
Thread.currentThread().interrupt();
149179
}
150180
}
151181

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

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

416-
private ObjectNode executeCollect(String requestId, JsonNode msg) {
510+
private ObjectNode executeCollect(String requestId, JsonNode msg, OpenCliCancellationToken cancellation) {
417511
try {
418512
String site = msg.path("site").asText("");
419513
String command = msg.path("command").asText("");
@@ -423,7 +517,7 @@ private ObjectNode executeCollect(String requestId, JsonNode msg) {
423517

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

0 commit comments

Comments
 (0)