Skip to content

Commit e2b956c

Browse files
committed
fix: bound and gate OpenCLI WebSocket ingress
1 parent ae4d409 commit e2b956c

6 files changed

Lines changed: 177 additions & 75 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,8 @@ 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+
The reverse agent accepts collect only after the current connection acknowledges registration. Incoming WebSocket messages are capped at 1 MiB by default, including the assembled size of fragments. Set `maxInboundMessageBytes` before constructing the agent to configure the finite byte limit. Oversized messages close the affected connection before any command is queued.
245+
244246
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.
245247

246248
`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.

‎README.zh-CN.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,8 @@ agent.close();
241241

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

244+
当前连接收到合法注册确认后,反向 Agent 才开始收单。入站 WebSocket 消息默认上限为 1 MiB,分片按聚合后的字节数计量。需要调整上限时,在创建 Agent 前设置有限的 `maxInboundMessageBytes`。超限消息会关闭对应连接,不会提交命令。
245+
244246
collect 请求 ID 必须为非空白字符串,长度上限 128 个 UTF-8 字节。相同的在途请求只执行一次,同一个 ID 对应不同载荷时会明确拒绝。显式重试已完成的请求有可能收到标记为 `cached: true` 的结果。内存缓存最多保留 1,024 条完成结果,每条最长 10 分钟。跨连接重放要求使用同一个经过 TLS 校验的端点,明文 WebSocket 的去重范围为当前连接。创建新 Agent 实例时从空缓存开始。
245247

246248
`stop()` 停止接单并丢弃等待任务,为已在途任务保留最多 5 秒的收尾时间,随后请求取消。连接线程退出后,同一实例可再次调用 `start()` 重连。`close()` 立即请求取消,并永久关闭该实例。

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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
## 2. 治理实现
1313

14-
- [ ] 2.1 建立显式状态机及 READY gate,接收线程仅做有界解析与准入。
14+
- [x] 2.1 建立显式状态机及 READY gate,接收线程仅做有界解析与准入。见本文入站验证。
1515
- [x] 2.2 用有限执行器替换 cached pool,加入容量校验和兼容 BUSY result。
1616
- [x] 2.3 实现 payload digest、在途记录与有界完成缓存;同 ID 不同载荷拒绝。
1717
- [x] 2.4 实现连接代际与有界 drain/cancel,CLOSED 终态。见 OC-WS-006 验证。
@@ -51,3 +51,11 @@ OC-WS-003/004/005 本地回环验证覆盖 128 字节请求 ID 边界、相同
5151
已启动任务保留去重占位到实际执行收尾。等待任务撤销时释放占位。重连使用原有固定线程池及其容量。终态 `close()` 仍立即取消在途工作,丢弃队列并在共用预算内等待资源回收,关闭后拒绝重启。
5252

5353
JDK 17 定向 28 项通过。JDK 17 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,123 项通过,0 失败、0 错误、0 跳过。显式连接状态机和独立平台资源验收仍由 2.1 和 3.3 跟踪。
54+
55+
## 2026-11-19 OC-WS-001 入站状态与消息上限
56+
57+
每条连接的状态从 `CONNECTING` 经 `REGISTERING` 到 `READY`,退役为 `RETIRED`。只有当前连接收到单个 JSON 对象的合法注册确认后才接单。WebSocket 解码使用默认 1 MiB 的有限上限,覆盖单帧和分片聚合,可在创建 Agent 前配置。超限在 JSON 解析和任务入队前关闭该连接,后续重连需要重新注册。
58+
59+
JDK 17 定向红灯复现三项失败,退出 1。拼接 JSON 错误推进注册,超长单帧和分片均未关闭连接。修复后验证合法确认仍可接单,两个超限场景均关闭连接、没有 CLI 标记且重新注册。发送单个超长帧时,接收方可能在对端写完前关闭连接,对端可观察到 1006 或 1009。分片超限场景验证 1009。补充拒绝零、负数及库定义的无限哨兵设置。JDK 17 定向 34 项通过。
60+
61+
JDK 17 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,129 项通过,0 失败、0 错误、0 跳过。

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,9 @@ public class OpenCliWsAgentConnectionProperties {
6565
/** 排队的 collect 任务上限,零表示没有等待队列。 */
6666
private int maxPendingCollects = 32;
6767

68+
/** 单条入站 WebSocket 消息的 UTF-8 字节上限,包括分片聚合。 */
69+
private int maxInboundMessageBytes = 1024 * 1024;
70+
6871
/**
6972
* 首次 {@code registered} 应答等待上限(毫秒)。
7073
*/

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

Lines changed: 93 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package io.github.easy4j.opencli.center.ws;
22

3+
import com.fasterxml.jackson.databind.DeserializationFeature;
34
import com.fasterxml.jackson.databind.JsonNode;
45
import com.fasterxml.jackson.databind.ObjectMapper;
6+
import com.fasterxml.jackson.databind.ObjectReader;
57
import com.fasterxml.jackson.databind.node.ArrayNode;
68
import com.fasterxml.jackson.databind.node.ObjectNode;
79
import io.github.easy4j.opencli.OpenCliProperties;
@@ -32,6 +34,7 @@
3234
import java.util.concurrent.atomic.AtomicReference;
3335
import lombok.extern.slf4j.Slf4j;
3436
import org.java_websocket.client.WebSocketClient;
37+
import org.java_websocket.drafts.Draft_6455;
3538
import org.java_websocket.handshake.ServerHandshake;
3639

3740
/**
@@ -55,12 +58,14 @@
5558
public final class OpenCliWsReverseAgentClient implements AutoCloseable {
5659

5760
private static final ObjectMapper MAPPER = new ObjectMapper();
61+
private static final ObjectReader MESSAGE_READER = MAPPER.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
5862
private static final long CLOSE_WAIT_NANOS = TimeUnit.SECONDS.toNanos(5);
5963

6064
private final OpenCliExecutor localExecutor;
6165

6266
private final OpenCliWsAgentConnectionProperties connectionProperties;
6367

68+
private final int maxInboundMessageBytes;
6469
private final ThreadPoolExecutor collectPool;
6570
private final Set<CollectTask> collectTasks = new HashSet<>();
6671
private final OpenCliWsCollectRequests collectRequests =
@@ -83,6 +88,10 @@ public OpenCliWsReverseAgentClient(
8388
Objects.requireNonNull(openCliProperties, "openCliProperties");
8489
this.connectionProperties =
8590
Objects.requireNonNull(connectionProperties, "connectionProperties");
91+
this.maxInboundMessageBytes = connectionProperties.getMaxInboundMessageBytes();
92+
if (maxInboundMessageBytes <= 0 || maxInboundMessageBytes == Integer.MAX_VALUE) {
93+
throw new IllegalArgumentException("Inbound WebSocket message size must have a positive finite limit");
94+
}
8695
int workers = connectionProperties.getMaxConcurrentCollects();
8796
int pending = connectionProperties.getMaxPendingCollects();
8897
if (workers <= 0 || pending < 0 || (long) workers + pending >= Integer.MAX_VALUE) {
@@ -250,88 +259,103 @@ private void runOneSession() throws Exception {
250259
// The default TLS client verifies the endpoint hostname. Plain WS has session-local identity.
251260
Object centerIdentity = "wss".equalsIgnoreCase(endpoint.getScheme()) ? endpoint : new Object();
252261

253-
final CountDownLatch registered = new CountDownLatch(1);
254-
final CountDownLatch sessionClosed = new CountDownLatch(1);
255-
final AtomicReference<Throwable> handshakeFailure = new AtomicReference<>();
256-
257262
log.info("opencli ws connecting");
258-
WebSocketClient client =
259-
new WebSocketClient(endpoint) {
260-
@Override
261-
public void onOpen(ServerHandshake handshake) {
262-
if (!isCurrentSession(this)) {
263-
closeSession(this);
264-
return;
265-
}
266-
try {
267-
send(buildRegisterJson());
268-
} catch (Exception e) {
269-
handshakeFailure.set(e);
270-
registered.countDown();
271-
close();
272-
}
273-
}
274-
275-
@Override
276-
public void onMessage(String message) {
277-
try {
278-
handleTextMessage(this, centerIdentity, message, registered, handshakeFailure);
279-
} catch (Exception e) {
280-
log.warn("handle ws message failed");
281-
}
282-
}
283-
284-
@Override
285-
public void onClose(int code, String reason, boolean remote) {
286-
activeClient.compareAndSet(this, null);
287-
if (registered.getCount() > 0) {
288-
handshakeFailure.compareAndSet(
289-
null,
290-
new IllegalStateException(
291-
"WebSocket closed before 'registered' (code="
292-
+ code
293-
+ ")"));
294-
registered.countDown();
295-
}
296-
sessionClosed.countDown();
297-
}
298-
299-
@Override
300-
public void onError(Exception ex) {
301-
activeClient.compareAndSet(this, null);
302-
log.warn("WebSocket error");
303-
if (registered.getCount() > 0) {
304-
handshakeFailure.compareAndSet(null, ex);
305-
registered.countDown();
306-
}
307-
sessionClosed.countDown();
308-
}
309-
};
310-
263+
WorkerSession client = new WorkerSession(endpoint, centerIdentity);
311264
if (!publishSession(client)) {
312265
return;
313266
}
314267
try {
315268
if (!client.connectBlocking(30, TimeUnit.SECONDS)) {
316269
throw new IllegalStateException("WebSocket connectBlocking returned false");
317270
}
318-
if (!registered.await(connectionProperties.getHandshakeTimeoutMillis(), TimeUnit.MILLISECONDS)) {
271+
if (!client.registered.await(connectionProperties.getHandshakeTimeoutMillis(), TimeUnit.MILLISECONDS)) {
319272
throw new IllegalStateException("Timeout waiting for 'registered' from center");
320273
}
321-
Throwable hf = handshakeFailure.get();
274+
Throwable hf = client.handshakeFailure.get();
322275
if (Objects.nonNull(hf)) {
323276
if (hf instanceof Exception) {
324277
throw (Exception) hf;
325278
}
326279
throw new IllegalStateException(hf);
327280
}
328-
sessionClosed.await();
281+
client.sessionClosed.await();
329282
} finally {
330-
activeClient.compareAndSet(client, null);
283+
client.retire(null);
331284
closeSession(client);
332285
}
333286
}
334287

288+
private enum SessionPhase {
289+
CONNECTING, REGISTERING, READY, RETIRED
290+
}
291+
292+
private final class WorkerSession extends WebSocketClient {
293+
private final Object centerIdentity;
294+
private final AtomicReference<SessionPhase> phase = new AtomicReference<>(SessionPhase.CONNECTING);
295+
private final CountDownLatch registered = new CountDownLatch(1);
296+
private final CountDownLatch sessionClosed = new CountDownLatch(1);
297+
private final AtomicReference<Throwable> handshakeFailure = new AtomicReference<>();
298+
299+
WorkerSession(URI endpoint, Object centerIdentity) {
300+
super(endpoint, new Draft_6455(Collections.emptyList(), maxInboundMessageBytes));
301+
this.centerIdentity = centerIdentity;
302+
}
303+
304+
@Override
305+
public void onOpen(ServerHandshake handshake) {
306+
if (!isCurrentSession(this) || !phase.compareAndSet(SessionPhase.CONNECTING, SessionPhase.REGISTERING)) {
307+
closeSession(this);
308+
return;
309+
}
310+
try {
311+
send(buildRegisterJson());
312+
} catch (Exception e) {
313+
retire(e);
314+
closeSession(this);
315+
}
316+
}
317+
318+
@Override
319+
public void onMessage(String message) {
320+
try {
321+
handleTextMessage(this, message);
322+
} catch (Exception e) {
323+
log.warn("handle ws message failed");
324+
}
325+
}
326+
327+
@Override
328+
public void onClose(int code, String reason, boolean remote) {
329+
retire(new IllegalStateException("WebSocket closed before 'registered' (code=" + code + ")"));
330+
}
331+
332+
@Override
333+
public void onError(Exception ex) {
334+
log.warn("WebSocket error");
335+
retire(ex);
336+
}
337+
338+
void acknowledgeRegistration() {
339+
if (phase.compareAndSet(SessionPhase.REGISTERING, SessionPhase.READY)) {
340+
registered.countDown();
341+
}
342+
}
343+
344+
boolean isReady() {
345+
return phase.get() == SessionPhase.READY;
346+
}
347+
348+
void retire(Throwable cause) {
349+
SessionPhase previous = phase.getAndSet(SessionPhase.RETIRED);
350+
activeClient.compareAndSet(this, null);
351+
if (previous == SessionPhase.CONNECTING || previous == SessionPhase.REGISTERING) {
352+
handshakeFailure.compareAndSet(null, cause);
353+
registered.countDown();
354+
}
355+
sessionClosed.countDown();
356+
}
357+
}
358+
335359
private synchronized boolean publishSession(WebSocketClient client) {
336360
if (shutdownRequested) {
337361
return false;
@@ -395,20 +419,17 @@ private String buildRegisterJson() throws Exception {
395419
return MAPPER.writeValueAsString(reg);
396420
}
397421

398-
private void handleTextMessage(
399-
WebSocketClient ws,
400-
Object centerIdentity,
401-
String payload,
402-
CountDownLatch registered,
403-
AtomicReference<Throwable> handshakeFailure)
404-
throws Exception {
422+
private void handleTextMessage(WorkerSession ws, String payload) throws Exception {
405423
if (!isCurrentSession(ws)) {
406424
return;
407425
}
408-
JsonNode root = MAPPER.readTree(payload);
426+
JsonNode root = MESSAGE_READER.readTree(payload);
427+
if (Objects.isNull(root) || !root.isObject()) {
428+
return;
429+
}
409430
String type = root.path("type").asText("");
410431
if ("registered".equals(type)) {
411-
registered.countDown();
432+
ws.acknowledgeRegistration();
412433
return;
413434
}
414435
if ("ping".equals(type)) {
@@ -425,12 +446,11 @@ private void handleTextMessage(
425446
sendResult(ws, result("", false, Collections.emptyList(), "invalid worker request ID"));
426447
return;
427448
}
428-
if (!isCurrentSession(ws) || !ws.isOpen() || registered.getCount() > 0
429-
|| Objects.nonNull(handshakeFailure.get())) {
449+
if (!isCurrentSession(ws) || !ws.isOpen() || !ws.isReady()) {
430450
sendResult(ws, result(requestId, false, Collections.emptyList(), "worker is not registered"));
431451
return;
432452
}
433-
admitCollect(ws, centerIdentity, requestId, root);
453+
admitCollect(ws, ws.centerIdentity, requestId, root);
434454
}
435455
}
436456

0 commit comments

Comments
 (0)