Skip to content

Commit ec49fff

Browse files
committed
fix: bound reverse WebSocket collect execution and waiting
1 parent cddc146 commit ec49fff

6 files changed

Lines changed: 149 additions & 11 deletions

File tree

‎README.md‎

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

240240
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`.
241241

242+
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`.
243+
242244
### Diagnostic export
243245

244246
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: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,8 @@ agent.close();
239239

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

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

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

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
## 2. 治理实现
1313

1414
- [ ] 2.1 建立显式状态机及 READY gate,接收线程仅做有界解析与准入。
15-
- [ ] 2.2 用有限执行器替换 cached pool,加入容量校验和兼容 BUSY result。
15+
- [x] 2.2 用有限执行器替换 cached pool,加入容量校验和兼容 BUSY result。
1616
- [ ] 2.3 实现 payload digest、在途记录与有界完成缓存;同 ID 不同载荷拒绝。
1717
- [ ] 2.4 实现连接代际与有界 drain/cancel,CLOSED 终态。
1818

@@ -31,3 +31,5 @@
3131
`OpenCliWsReverseAgentSessionTest` 在回环接口启动独立 WebSocket 服务,验证注册默认值、心跳、异常帧后的继续处理、collect 参数到真实子进程的传递、错误结果,以及注册前和注册后断线重连。JDK 17 `mvn -B -ntp -o clean verify` 通过 2,092 项测试,零失败、零错误、零跳过。JaCoCo XML 记录 2,806 / 3,067 行覆盖(91.49%)。准入、背压、去重、完整生命周期和三线验收仍由上面的任务跟踪。
3232

3333
OC-WS-001 的提前收单场景使用子进程启动标记验证。旧实现收到 `registered` 之前的 collect 后会创建标记,定向用例因此失败。修复后同一回环请求收到明确失败结果,临时目录里没有启动标记。已注册成功的收单行为继续通过回归。JDK 17 `clean verify` 共通过 2,093 项测试,零跳过,JaCoCo 行覆盖率为 2,810 / 3,071(91.50%)。
34+
35+
OC-WS-002 使用实际子进程启动标记验证容量。旧实现启动第五个子进程,定向用例失败。修复后默认保持四个并行任务,等待任务在释放后启动。队列容量为零和一的用例验证超额请求返回 `worker is busy`,且从未启动对应子进程。负数、零并发及溢出配置在创建客户端时拒绝。

‎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
*/

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

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,13 @@
1818
import java.util.List;
1919
import java.util.Map;
2020
import java.util.Objects;
21+
import java.util.concurrent.BlockingQueue;
2122
import java.util.concurrent.CountDownLatch;
2223
import java.util.concurrent.ExecutorService;
23-
import java.util.concurrent.Executors;
24+
import java.util.concurrent.LinkedBlockingQueue;
25+
import java.util.concurrent.RejectedExecutionException;
26+
import java.util.concurrent.SynchronousQueue;
27+
import java.util.concurrent.ThreadPoolExecutor;
2428
import java.util.concurrent.TimeUnit;
2529
import java.util.concurrent.atomic.AtomicReference;
2630
import lombok.extern.slf4j.Slf4j;
@@ -53,13 +57,7 @@ public final class OpenCliWsReverseAgentClient implements AutoCloseable {
5357

5458
private final OpenCliWsAgentConnectionProperties connectionProperties;
5559

56-
private final ExecutorService collectPool =
57-
Executors.newCachedThreadPool(
58-
r -> {
59-
Thread t = new Thread(r, "opencli-ws-collect");
60-
t.setDaemon(true);
61-
return t;
62-
});
60+
private final ExecutorService collectPool;
6361

6462
private volatile boolean shutdownRequested;
6563

@@ -76,6 +74,17 @@ public OpenCliWsReverseAgentClient(
7674
Objects.requireNonNull(openCliProperties, "openCliProperties");
7775
this.connectionProperties =
7876
Objects.requireNonNull(connectionProperties, "connectionProperties");
77+
int workers = connectionProperties.getMaxConcurrentCollects();
78+
int pending = connectionProperties.getMaxPendingCollects();
79+
if (workers <= 0 || pending < 0 || (long) workers + pending >= Integer.MAX_VALUE) {
80+
throw new IllegalArgumentException("Collect capacity requires positive concurrency and a finite pending queue");
81+
}
82+
BlockingQueue<Runnable> queue = pending == 0 ? new SynchronousQueue<>() : new LinkedBlockingQueue<>(pending);
83+
this.collectPool = new ThreadPoolExecutor(workers, workers, 0L, TimeUnit.MILLISECONDS, queue, runnable -> {
84+
Thread thread = new Thread(runnable, "opencli-ws-collect");
85+
thread.setDaemon(true);
86+
return thread;
87+
});
7988
this.localExecutor = new OpenCliExecutor(openCliProperties.copyForLocalCliExecution());
8089
}
8190

@@ -300,8 +309,11 @@ private void handleTextMessage(
300309
"worker is not registered");
301310
return;
302311
}
303-
final JsonNode msg = root;
304-
collectPool.submit(() -> runCollectSafe(ws, msg));
312+
try {
313+
collectPool.execute(() -> runCollectSafe(ws, root));
314+
} catch (RejectedExecutionException e) {
315+
sendResult(ws, root.path("request_id").asText(""), false, Collections.emptyList(), "worker is busy");
316+
}
305317
}
306318
}
307319

‎src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import com.fasterxml.jackson.databind.JsonNode;
44
import com.fasterxml.jackson.databind.ObjectMapper;
5+
import com.fasterxml.jackson.databind.node.ObjectNode;
56
import io.github.easy4j.opencli.OpenCliProperties;
67
import io.github.easy4j.opencli.contract.ContractProbe;
78
import io.github.easy4j.opencli.contract.LifecycleProbe;
@@ -13,6 +14,8 @@
1314
import java.nio.file.Path;
1415
import java.util.Arrays;
1516
import java.util.Base64;
17+
import java.util.HashSet;
18+
import java.util.Set;
1619
import java.util.List;
1720
import java.util.Objects;
1821
import java.util.concurrent.BlockingQueue;
@@ -26,12 +29,16 @@
2629
import org.java_websocket.server.WebSocketServer;
2730
import org.junit.jupiter.api.Test;
2831
import org.junit.jupiter.api.io.TempDir;
32+
import org.junit.jupiter.params.ParameterizedTest;
33+
import org.junit.jupiter.params.provider.CsvSource;
34+
import org.junit.jupiter.params.provider.ValueSource;
2935

3036
import static org.junit.jupiter.api.Assertions.assertEquals;
3137
import static org.junit.jupiter.api.Assertions.assertFalse;
3238
import static org.junit.jupiter.api.Assertions.assertNotNull;
3339
import static org.junit.jupiter.api.Assertions.assertNotSame;
3440
import static org.junit.jupiter.api.Assertions.assertNull;
41+
import static org.junit.jupiter.api.Assertions.assertThrows;
3542
import static org.junit.jupiter.api.Assertions.assertTrue;
3643

3744
class OpenCliWsReverseAgentSessionTest {
@@ -112,6 +119,113 @@ void collectBeforeRegistrationAcknowledgementDoesNotStartChild(@TempDir Path tem
112119
}
113120
}
114121

122+
@Test
123+
void defaultsToFourActiveCollects(@TempDir Path temporary) throws Exception {
124+
Path release = temporary.resolve("release");
125+
OpenCliProperties properties = probe(LifecycleProbe.class.getName());
126+
properties.setMaxConcurrentExecutions(8);
127+
properties.setCommandTimeoutMillis(10_000);
128+
try (LocalCenter center = new LocalCenter();
129+
OpenCliWsReverseAgentClient agent = new OpenCliWsReverseAgentClient(properties, center.agentProperties())) {
130+
agent.start();
131+
WebSocket socket = center.receive("register").socket;
132+
socket.send("{\"type\":\"registered\"}");
133+
try {
134+
for (int index = 0; index < 4; index++) {
135+
sendHeldCollect(socket, "collect-" + index, temporary.resolve("child-" + index), release);
136+
}
137+
for (int index = 0; index < 4; index++) {
138+
assertTrue(awaitMarker(temporary.resolve("child-" + index), 5_000), "initial child did not start");
139+
}
140+
Path queued = temporary.resolve("child-4");
141+
sendHeldCollect(socket, "collect-4", queued, release);
142+
assertFalse(awaitMarker(queued, 1_250), "a fifth collect started before a worker was free");
143+
} finally {
144+
Files.createFile(release);
145+
}
146+
Set<String> completed = new HashSet<>();
147+
for (int index = 0; index < 5; index++) {
148+
JsonNode result = center.receive("result").body;
149+
assertTrue(result.path("success").asBoolean(), result::toString);
150+
completed.add(result.path("request_id").asText());
151+
}
152+
assertEquals(new HashSet<>(Arrays.asList("collect-0", "collect-1", "collect-2", "collect-3", "collect-4")),
153+
completed);
154+
assertTrue(Files.exists(temporary.resolve("child-4")));
155+
}
156+
}
157+
158+
@ParameterizedTest
159+
@ValueSource(ints = {0, 1})
160+
void rejectsOverflowWithoutLaunchingAnotherChild(int queueCapacity, @TempDir Path temporary) throws Exception {
161+
Path release = temporary.resolve("release");
162+
Path active = temporary.resolve("active");
163+
Path queued = temporary.resolve("queued");
164+
Path rejected = temporary.resolve("rejected");
165+
try (LocalCenter center = new LocalCenter()) {
166+
OpenCliWsAgentConnectionProperties connection = center.agentProperties();
167+
connection.setMaxConcurrentCollects(1);
168+
connection.setMaxPendingCollects(queueCapacity);
169+
try (OpenCliWsReverseAgentClient agent = new OpenCliWsReverseAgentClient(
170+
probe(LifecycleProbe.class.getName()), connection)) {
171+
agent.start();
172+
WebSocket socket = center.receive("register").socket;
173+
socket.send("{\"type\":\"registered\"}");
174+
try {
175+
sendHeldCollect(socket, "active", active, release);
176+
assertTrue(awaitMarker(active, 3_000), "first collect did not start");
177+
if (queueCapacity > 0) {
178+
sendHeldCollect(socket, "queued", queued, release);
179+
}
180+
sendHeldCollect(socket, "overflow", rejected, release);
181+
JsonNode busy = center.receive("result").body;
182+
assertEquals("overflow", busy.path("request_id").asText());
183+
assertFalse(busy.path("success").asBoolean());
184+
assertEquals("worker is busy", busy.path("error").asText());
185+
assertFalse(Files.exists(rejected));
186+
assertFalse(Files.exists(queued));
187+
} finally {
188+
Files.createFile(release);
189+
}
190+
JsonNode completed = center.receive("result").body;
191+
assertEquals("active", completed.path("request_id").asText());
192+
assertTrue(completed.path("success").asBoolean());
193+
if (queueCapacity > 0) {
194+
JsonNode drained = center.receive("result").body;
195+
assertEquals("queued", drained.path("request_id").asText());
196+
assertTrue(drained.path("success").asBoolean());
197+
assertTrue(Files.exists(queued));
198+
}
199+
assertFalse(Files.exists(rejected));
200+
}
201+
}
202+
}
203+
204+
@ParameterizedTest
205+
@CsvSource({"0,32", "-1,32", "4,-1", "4,2147483647", "4,2147483644"})
206+
void rejectsInvalidCapacityBeforeConnection(int workers, int pending) {
207+
OpenCliWsAgentConnectionProperties connection = new OpenCliWsAgentConnectionProperties();
208+
connection.setMaxConcurrentCollects(workers);
209+
connection.setMaxPendingCollects(pending);
210+
assertThrows(IllegalArgumentException.class,
211+
() -> new OpenCliWsReverseAgentClient(new OpenCliProperties(), connection));
212+
}
213+
214+
private static void sendHeldCollect(WebSocket socket, String id, Path marker, Path release) {
215+
ObjectNode message = MAPPER.createObjectNode()
216+
.put("type", "collect").put("request_id", id).put("site", "hold").put("command", marker.toString());
217+
message.putArray("positional_args").add(release.toString());
218+
socket.send(message.toString());
219+
}
220+
221+
private static boolean awaitMarker(Path marker, long timeoutMillis) throws InterruptedException {
222+
long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMillis);
223+
while (!Files.exists(marker) && System.nanoTime() < deadline) {
224+
Thread.sleep(10);
225+
}
226+
return Files.exists(marker);
227+
}
228+
115229
@Test
116230
void retriesAfterHandshakeCloseAndReturnsChildFailureToCenter() throws Exception {
117231
try (LocalCenter center = new LocalCenter();

0 commit comments

Comments
 (0)