55import com .fasterxml .jackson .databind .node .ArrayNode ;
66import com .fasterxml .jackson .databind .node .ObjectNode ;
77import io .github .easy4j .opencli .OpenCliProperties ;
8+ import io .github .easy4j .opencli .core .OpenCliCancellationToken ;
89import io .github .easy4j .opencli .core .OpenCliExecutor ;
910import io .github .easy4j .opencli .core .OpenCliResult ;
1011import io .github .easy4j .opencli .exception .OpenCliException ;
1415import java .security .MessageDigest ;
1516import java .util .ArrayList ;
1617import java .util .Collections ;
18+ import java .util .HashSet ;
1719import java .util .Iterator ;
1820import java .util .LinkedHashMap ;
1921import java .util .List ;
2022import java .util .Map ;
2123import java .util .Objects ;
24+ import java .util .Set ;
2225import java .util .concurrent .BlockingQueue ;
2326import java .util .concurrent .CountDownLatch ;
24- import java .util .concurrent .ExecutorService ;
2527import java .util .concurrent .LinkedBlockingQueue ;
2628import java .util .concurrent .RejectedExecutionException ;
2729import 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