Skip to content

Commit 896a637

Browse files
committed
fix: backport reverse WebSocket worker safeguards
1 parent 86564e4 commit 896a637

9 files changed

Lines changed: 871 additions & 56 deletions

File tree

‎README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,10 @@ agent.close();
224224

225225
Protocol: edge sends `register`; center replies `registered`; center sends `collect` (request_id, site, command, args, positional_args, format, mode); the SDK executes `opencli` locally (via `copyForLocalCliExecution()` to avoid loops) and replies `result`; plus `ping` / `pong`.
226226

227+
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`.
228+
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.
230+
227231
### Diagnostic export
228232

229233
Call `OpenCliDiagnosticExport.export(result, 512)` explicitly with an `OpenCliResult` or an exception's partial result. The byte budget applies to UTF-8 text. Output contains only status and field lengths, with a `truncated=true` marker when fields do not fit. Field lengths can disclose how much data was present.

‎README.zh-CN.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,10 @@ agent.close();
223223

224224
协议摘要:边缘发送 `register`;中心回执 `registered`;中心下发 `collect`(request_id、site、command、args、positional_args、format、mode);SDK 在本机执行 `opencli`(通过 `copyForLocalCliExecution()` 强制本地子进程,避免回路)并回执 `result`;另有 `ping` / `pong`。
225225

226+
反向 Agent 默认最多同时执行 4 个 collect 任务,另有 32 个等待名额。构建 Agent 前,可在连接配置中设置 `maxConcurrentCollects` 和 `maxPendingCollects`。等待容量为零时直接拒绝超额请求。容量用尽时返回失败的 `result`,错误为 `worker is busy`。
227+
228+
collect 请求 ID 必须为非空白字符串,长度上限 128 个 UTF-8 字节。相同的在途请求只执行一次,同一个 ID 对应不同载荷时会明确拒绝。显式重试已完成的请求有可能收到标记为 `cached: true` 的结果。内存缓存最多保留 1,024 条完成结果,每条最长 10 分钟。跨连接重放要求使用同一个经过 TLS 校验的端点,明文 WebSocket 的去重范围为当前连接。Agent 重启后会清空缓存。
229+
226230
### 诊断导出
227231

228232
如需导出诊断,请调用 `OpenCliDiagnosticExport.export(result, 512)`,传入 `OpenCliResult` 或异常中的部分结果。上限按 UTF-8 字节计算。输出只包含状态和字段长度,字段放不下时会标明 `truncated=true`。字段长度仍可能反映数据规模。

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,7 @@
2525
## 证据交付模板(实施时填写)
2626

2727
每项任务的完成记录包含:Requirement/Scenario、分支HEAD、测试命令、失败→通过证据、测试数/跳过数、退出码、报告位置。没有记录的任务保持未完成。
28+
29+
## JDK 8 回移验证
30+
31+
回移 JDK 17 版本的注册前拒绝、执行与等待上限、关闭保护、请求去重、缓存过期和连接隔离。通过本地回环服务器、真实子进程和测试证书验证普通连接和 TLS 重连。运行 `mvn -B -ntp -o clean verify`,2,112 项测试通过,零失败、零跳过,JaCoCo 行覆盖率为 2,905 / 3,167(91.73%)。

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,12 @@ public class OpenCliWsAgentConnectionProperties {
5959
*/
6060
private String nodeType = "shell";
6161

62+
/** 并行执行的 collect 任务上限,必须为正数。 */
63+
private int maxConcurrentCollects = 4;
64+
65+
/** 排队的 collect 任务上限,零表示没有等待队列。 */
66+
private int maxPendingCollects = 32;
67+
6268
/**
6369
* 首次 {@code registered} 应答等待上限(毫秒)。
6470
*/
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
package io.github.easy4j.opencli.center.ws;
2+
3+
import com.fasterxml.jackson.databind.node.ObjectNode;
4+
import java.util.Arrays;
5+
import java.util.HashMap;
6+
import java.util.Iterator;
7+
import java.util.LinkedHashMap;
8+
import java.util.Map;
9+
import java.util.Objects;
10+
import java.util.function.LongSupplier;
11+
12+
/** Tracks accepted requests and bounded, instance-local replay results. */
13+
final class OpenCliWsCollectRequests {
14+
15+
enum Status {
16+
ACCEPTED, IN_FLIGHT, CONFLICT, CACHED
17+
}
18+
19+
static final class Key {
20+
private final Object center;
21+
private final String requestId;
22+
23+
Key(Object center, String requestId) {
24+
this.center = center;
25+
this.requestId = requestId;
26+
}
27+
28+
String requestId() {
29+
return requestId;
30+
}
31+
32+
@Override
33+
public boolean equals(Object other) {
34+
if (!(other instanceof Key)) {
35+
return false;
36+
}
37+
Key key = (Key) other;
38+
return center.equals(key.center) && requestId.equals(key.requestId);
39+
}
40+
41+
@Override
42+
public int hashCode() {
43+
return 31 * center.hashCode() + requestId.hashCode();
44+
}
45+
}
46+
47+
static final class Admission {
48+
private final Status status;
49+
private final ObjectNode cachedResult;
50+
51+
Admission(Status status, ObjectNode cachedResult) {
52+
this.status = status;
53+
this.cachedResult = cachedResult;
54+
}
55+
56+
Status status() {
57+
return status;
58+
}
59+
60+
ObjectNode cachedResult() {
61+
return cachedResult;
62+
}
63+
}
64+
65+
private static final class Completed {
66+
private final byte[] digest;
67+
private final ObjectNode result;
68+
private final long completedAt;
69+
70+
Completed(byte[] digest, ObjectNode result, long completedAt) {
71+
this.digest = digest;
72+
this.result = result;
73+
this.completedAt = completedAt;
74+
}
75+
}
76+
77+
private final Map<Key, byte[]> inFlight = new HashMap<>();
78+
private final Map<Key, Completed> completed = new LinkedHashMap<>();
79+
private final int maxCompleted;
80+
private final long ttlNanos;
81+
private final LongSupplier clock;
82+
83+
OpenCliWsCollectRequests(int maxCompleted, long ttlNanos, LongSupplier clock) {
84+
this.maxCompleted = maxCompleted;
85+
this.ttlNanos = ttlNanos;
86+
this.clock = clock;
87+
}
88+
89+
synchronized Admission reserve(Key key, byte[] digest) {
90+
byte[] active = inFlight.get(key);
91+
if (Objects.nonNull(active)) {
92+
return new Admission(Arrays.equals(active, digest) ? Status.IN_FLIGHT : Status.CONFLICT, null);
93+
}
94+
expire(clock.getAsLong());
95+
Completed previous = completed.get(key);
96+
if (Objects.nonNull(previous)) {
97+
if (!Arrays.equals(previous.digest, digest)) {
98+
return new Admission(Status.CONFLICT, null);
99+
}
100+
return new Admission(Status.CACHED, previous.result.deepCopy().put("cached", true));
101+
}
102+
inFlight.put(key, digest);
103+
return new Admission(Status.ACCEPTED, null);
104+
}
105+
106+
synchronized void complete(Key key, ObjectNode result) {
107+
byte[] digest = inFlight.remove(key);
108+
if (Objects.isNull(digest) || Objects.isNull(result)) {
109+
return;
110+
}
111+
long now = clock.getAsLong();
112+
expire(now);
113+
if (completed.size() >= maxCompleted) {
114+
Iterator<Key> entries = completed.keySet().iterator();
115+
entries.next();
116+
entries.remove();
117+
}
118+
completed.put(key, new Completed(digest, result, now));
119+
}
120+
121+
synchronized void clear() {
122+
inFlight.clear();
123+
completed.clear();
124+
}
125+
126+
private void expire(long now) {
127+
Iterator<Completed> entries = completed.values().iterator();
128+
while (entries.hasNext() && now - entries.next().completedAt >= ttlNanos) {
129+
entries.remove();
130+
}
131+
}
132+
}

0 commit comments

Comments
 (0)