11package org .a2aproject .sdk .server .events ;
22
3- import java .util .ArrayList ;
3+ import java .util .HashSet ;
44import java .util .List ;
55import java .util .Objects ;
6+ import java .util .Set ;
67import java .util .concurrent .BlockingQueue ;
78import java .util .concurrent .CopyOnWriteArrayList ;
89import java .util .concurrent .CountDownLatch ;
910import java .util .concurrent .LinkedBlockingDeque ;
1011import java .util .concurrent .Semaphore ;
1112import java .util .concurrent .TimeUnit ;
1213import java .util .concurrent .atomic .AtomicBoolean ;
13- import java .util .concurrent .atomic .AtomicInteger ;
1414
1515import org .a2aproject .sdk .server .tasks .TaskStateProvider ;
1616import org .a2aproject .sdk .spec .A2AError ;
@@ -224,6 +224,22 @@ public void enqueueEvent(Event event) {
224224 enqueueItem (new LocalEventQueueItem (event ));
225225 }
226226
227+ /**
228+ * Enqueues an event using the queue's bounded backpressure operation.
229+ *
230+ * @param event the event to enqueue
231+ * @param timeout the maximum time to wait for queue capacity; must be non-negative
232+ * @param unit the timeout unit
233+ * @throws IllegalArgumentException if timeout is negative
234+ * @throws UnsupportedOperationException if this queue does not support bounded enqueues
235+ */
236+ public void enqueueEvent (Event event , long timeout , TimeUnit unit ) {
237+ if (timeout < 0 ) {
238+ throw new IllegalArgumentException ("timeout must be non-negative" );
239+ }
240+ enqueueItem (new LocalEventQueueItem (event ), timeout , Objects .requireNonNull (unit , "unit" ));
241+ }
242+
227243 /**
228244 * Enqueues an event queue item for processing.
229245 * <p>
@@ -236,6 +252,29 @@ public void enqueueEvent(Event event) {
236252 */
237253 public abstract void enqueueItem (EventQueueItem item );
238254
255+ /** Timed form of {@link #enqueueItem(EventQueueItem)}. */
256+ public void enqueueItem (EventQueueItem item , long timeout , TimeUnit unit ) {
257+ throw new UnsupportedOperationException ("This event queue does not support bounded enqueues" );
258+ }
259+
260+ /** Runtime exception used when a queue acquire was interrupted. */
261+ public static class EnqueueInterruptedException extends RuntimeException {
262+ private static final long serialVersionUID = 1L ;
263+
264+ public EnqueueInterruptedException (InterruptedException cause ) {
265+ super ("Unable to acquire the semaphore to enqueue the event" , cause );
266+ }
267+ }
268+
269+ /** Runtime exception used when a timed queue acquire expires. */
270+ public static class EnqueueTimeoutException extends RuntimeException {
271+ private static final long serialVersionUID = 1L ;
272+
273+ public EnqueueTimeoutException () {
274+ super ("Timed out waiting for queue capacity to enqueue the event" );
275+ }
276+ }
277+
239278 /**
240279 * Enqueues an event directly to this specific queue only, bypassing the MainEventBus.
241280 * <p>
@@ -349,6 +388,20 @@ public void clearAwaitingFinalEvent() {
349388 // Default no-op implementation - overridden by ChildQueue
350389 }
351390
391+ /**
392+ * Closes this queue if it is not currently waiting for an in-flight final event.
393+ * ChildQueue overrides this with an atomic check-and-close operation.
394+ *
395+ * @return true if the queue was closed, false if a final event is still expected
396+ */
397+ public boolean closeIfNotAwaitingFinalEvent () {
398+ if (isAwaitingFinalEvent ()) {
399+ return false ;
400+ }
401+ close ();
402+ return true ;
403+ }
404+
352405 /**
353406 * Closes this event queue gracefully, allowing pending events to be consumed.
354407 */
@@ -502,6 +555,18 @@ public int size() {
502555
503556 @ Override
504557 public void enqueueItem (EventQueueItem item ) {
558+ enqueueItemInternal (item , -1 , null );
559+ }
560+
561+ @ Override
562+ public void enqueueItem (EventQueueItem item , long timeout , TimeUnit unit ) {
563+ if (timeout < 0 ) {
564+ throw new IllegalArgumentException ("timeout must be non-negative" );
565+ }
566+ enqueueItemInternal (item , timeout , Objects .requireNonNull (unit , "unit" ));
567+ }
568+
569+ private void enqueueItemInternal (EventQueueItem item , long timeout , @ Nullable TimeUnit unit ) {
505570 // MainQueue must accept events even when closed to support:
506571 // 1. Late-arriving replicated events for non-finalized tasks
507572 // 2. Events enqueued during onClose callbacks (before super.doClose())
@@ -518,29 +583,37 @@ public void enqueueItem(EventQueueItem item) {
518583 // Notify current children before waiting for capacity. A consumer may already be
519584 // marked complete (for example, while waiting for a replicated final event) and
520585 // otherwise close its queue before this producer is able to submit the event.
521- List <ChildQueue > awaitingChildren = new ArrayList <>();
586+ Set <ChildQueue > awaitingChildren = new HashSet <>();
522587 if (finalEvent ) {
523- awaitingChildren .addAll (children );
524- awaitingChildren .forEach (ChildQueue ::expectFinalEvent );
588+ for (ChildQueue child : children ) {
589+ if (child .expectFinalEvent ()) {
590+ awaitingChildren .add (child );
591+ }
592+ }
525593 }
526594
527595 // Acquire semaphore for backpressure
528596 try {
529- semaphore .acquire ();
597+ if (unit == null ) {
598+ semaphore .acquire ();
599+ } else if (!semaphore .tryAcquire (timeout , unit )) {
600+ awaitingChildren .forEach (ChildQueue ::cancelPendingFinalEvent );
601+ throw new EnqueueTimeoutException ();
602+ }
530603 } catch (InterruptedException e ) {
531- awaitingChildren .forEach (ChildQueue ::cancelExpectedFinalEvent );
604+ awaitingChildren .forEach (ChildQueue ::cancelPendingFinalEvent );
532605 Thread .currentThread ().interrupt ();
533- throw new RuntimeException ( "Unable to acquire the semaphore to enqueue the event" , e );
606+ throw new EnqueueInterruptedException ( e );
534607 }
535608
536609 // Include children that subscribed while this producer was waiting for capacity.
537610 if (finalEvent ) {
538611 for (ChildQueue child : children ) {
539- if (!awaitingChildren .contains (child )) {
540- child .expectFinalEvent ();
612+ if (!awaitingChildren .contains (child ) && child .expectFinalEvent ()) {
541613 awaitingChildren .add (child );
542614 }
543615 }
616+ awaitingChildren .forEach (ChildQueue ::submitExpectedFinalEvent );
544617 }
545618
546619 LOGGER .debug ("Enqueued event {} {}" , event instanceof Throwable ? event .toString () : event , this );
@@ -557,7 +630,7 @@ public void enqueueItem(EventQueueItem item) {
557630 // Release the permit here to avoid leaking it and eventually blocking
558631 // all event processing for this task.
559632 semaphore .release ();
560- awaitingChildren .forEach (ChildQueue ::cancelExpectedFinalEvent );
633+ awaitingChildren .forEach (ChildQueue ::cancelSubmittedFinalEvent );
561634 throw e ;
562635 }
563636 }
@@ -795,7 +868,8 @@ static class ChildQueue extends EventQueue {
795868 private final MainQueue parent ;
796869 private final BlockingQueue <EventQueueItem > queue ;
797870 private volatile boolean immediateClose = false ;
798- private final AtomicInteger expectedFinalEvents = new AtomicInteger ();
871+ private int pendingFinalEvents ;
872+ private int submittedFinalEvents ;
799873
800874 public ChildQueue (MainQueue parent ) {
801875 this .parent = parent ;
@@ -816,6 +890,11 @@ public void enqueueItem(EventQueueItem item) {
816890 parent .enqueueItem (item );
817891 }
818892
893+ @ Override
894+ public void enqueueItem (EventQueueItem item , long timeout , TimeUnit unit ) {
895+ parent .enqueueItem (item , timeout , unit );
896+ }
897+
819898 private void internalEnqueueItem (EventQueueItem item ) {
820899 // Internal method called by MainEventBusProcessor to add to local queue
821900 // Note: Semaphore is managed by parent MainQueue (acquire/release), not ChildQueue
@@ -833,9 +912,13 @@ private void internalEnqueueItem(EventQueueItem item) {
833912 LOGGER .debug ("Enqueued event {} {}" , event instanceof Throwable ? event .toString () : event , this );
834913
835914 // If we were awaiting a final event and this is it, clear the flag
836- if (isAwaitingFinalEvent () && isFinalEvent (event )) {
837- expectedFinalEvents .set (0 );
838- LOGGER .debug ("ChildQueue {} received awaited final event" , System .identityHashCode (this ));
915+ if (isFinalEvent (event )) {
916+ synchronized (this ) {
917+ if (submittedFinalEvents > 0 ) {
918+ submittedFinalEvents = 0 ;
919+ LOGGER .debug ("ChildQueue {} received awaited final event" , System .identityHashCode (this ));
920+ }
921+ }
839922 }
840923 }
841924 }
@@ -914,8 +997,8 @@ public int size() {
914997 }
915998
916999 @ Override
917- public boolean isAwaitingFinalEvent () {
918- return expectedFinalEvents . get () > 0 ;
1000+ public synchronized boolean isAwaitingFinalEvent () {
1001+ return pendingFinalEvents > 0 || submittedFinalEvents > 0 ;
9191002 }
9201003
9211004 @ Override
@@ -933,9 +1016,14 @@ protected void doClose(boolean immediate) {
9331016 super .doClose (immediate ); // Sets closed flag
9341017 if (immediate ) {
9351018 // Immediate close: clear pending events from local queue
936- this .immediateClose = true ;
937- int clearedCount = queue .size ();
938- queue .clear ();
1019+ int clearedCount ;
1020+ synchronized (this ) {
1021+ this .immediateClose = true ;
1022+ pendingFinalEvents = 0 ;
1023+ submittedFinalEvents = 0 ;
1024+ clearedCount = queue .size ();
1025+ queue .clear ();
1026+ }
9391027 LOGGER .debug ("Cleared {} events from ChildQueue for immediate close: {}" , clearedCount , this );
9401028 }
9411029 // For graceful close, let the queue drain naturally through normal consumption
@@ -946,28 +1034,58 @@ protected void doClose(boolean immediate) {
9461034 * Called by MainQueue when it enqueues a final event, BEFORE submitting to MainEventBus.
9471035 * This ensures the ChildQueue keeps polling until the final event arrives (after MainEventBusProcessor).
9481036 */
949- void expectFinalEvent () {
950- expectedFinalEvents .incrementAndGet ();
1037+ synchronized boolean expectFinalEvent () {
1038+ if (isClosed ()) {
1039+ return false ;
1040+ }
1041+ pendingFinalEvents ++;
9511042 LOGGER .debug ("ChildQueue {} now awaiting final event" , System .identityHashCode (this ));
1043+ return true ;
9521044 }
9531045
954- /**
955- * Removes one expectation when the corresponding final event could not be submitted.
956- */
957- void cancelExpectedFinalEvent () {
958- expectedFinalEvents .updateAndGet (count -> Math .max (0 , count - 1 ));
1046+ synchronized void submitExpectedFinalEvent () {
1047+ if (pendingFinalEvents > 0 ) {
1048+ pendingFinalEvents --;
1049+ if (!isClosed ()) {
1050+ submittedFinalEvents ++;
1051+ }
1052+ }
1053+ }
1054+
1055+ synchronized void cancelPendingFinalEvent () {
1056+ if (pendingFinalEvents > 0 ) {
1057+ pendingFinalEvents --;
1058+ }
1059+ }
1060+
1061+ synchronized void cancelSubmittedFinalEvent () {
1062+ if (submittedFinalEvents > 0 ) {
1063+ submittedFinalEvents --;
1064+ }
9591065 }
9601066
9611067 /**
9621068 * Called by EventConsumer when it has waited too long for the final event.
9631069 * This allows normal timeout logic to proceed if the final event never arrives.
9641070 */
9651071 @ Override
966- public void clearAwaitingFinalEvent () {
967- expectedFinalEvents . set ( 0 ) ;
1072+ public synchronized void clearAwaitingFinalEvent () {
1073+ submittedFinalEvents = 0 ;
9681074 LOGGER .debug ("ChildQueue {} cleared awaitingFinalEvent flag (timeout)" , System .identityHashCode (this ));
9691075 }
9701076
1077+ @ Override
1078+ public boolean closeIfNotAwaitingFinalEvent () {
1079+ synchronized (this ) {
1080+ if (pendingFinalEvents > 0 || submittedFinalEvents > 0 ) {
1081+ return false ;
1082+ }
1083+ doClose (false );
1084+ }
1085+ parent .childClosing (this , false );
1086+ return true ;
1087+ }
1088+
9711089 @ Override
9721090 public void close () {
9731091 close (false );
0 commit comments