55import tools .jackson .databind .node .ArrayNode ;
66import tools .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 ;
1516import java .util .ArrayList ;
1617import java .util .Collections ;
1718import java .util .LinkedHashMap ;
19+ import java .util .HashSet ;
1820import java .util .List ;
1921import java .util .Map ;
2022import java .util .Objects ;
23+ import java .util .Set ;
2124import java .util .concurrent .BlockingQueue ;
2225import java .util .concurrent .CountDownLatch ;
23- import java .util .concurrent .ExecutorService ;
2426import java .util .concurrent .LinkedBlockingQueue ;
2527import java .util .concurrent .RejectedExecutionException ;
2628import 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