Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import org.a2aproject.sdk.spec.A2AError;
import org.a2aproject.sdk.spec.A2AServerException;
import org.a2aproject.sdk.spec.Event;
import org.a2aproject.sdk.spec.InternalError;
import org.a2aproject.sdk.spec.Message;
import org.a2aproject.sdk.spec.Task;
import org.a2aproject.sdk.spec.TaskState;
Expand Down Expand Up @@ -129,6 +130,21 @@ public Flow.Publisher<EventQueueItem> consumeAll() {
System.identityHashCode(queue), error, agentCompleted);
item = queue.dequeueEventItem(QUEUE_WAIT_MILLISECONDS);
if (item == null) {
// dequeueEventItem returns null on a timeout and also on an interrupt, with the
// interrupt flag still set. Only an interrupt ends this consumer: while the flag
// is set, each later poll returns at once, so polling again would spin.
if (Thread.currentThread().isInterrupted()) {
LOGGER.warn("EventConsumer polling thread interrupted, exiting polling loop for queue {}", System.identityHashCode(queue));
completed = true;
tube.fail(new InternalError("EventConsumer polling thread was interrupted"));
// The close can read the task store, which can throw on an interrupted thread
try {
queue.close(true);
} catch (RuntimeException e) {
LOGGER.warn("Failed to close the queue {} of an interrupted EventConsumer", System.identityHashCode(queue), e);
}
return;
}
int queueSize = queue.size();
boolean awaitingFinal = queue.isAwaitingFinalEvent();
LOGGER.debug("EventConsumer poll timeout (null item), agentCompleted={}, queue.size()={}, awaitingFinalEvent={}, timeoutCount={}, awaitingTimeoutCount={}",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,8 @@ public void enqueueEventLocalOnly(Event event) {
* </p>
*
* @param waitMilliSeconds the maximum time to wait in milliseconds
* @return the EventQueueItem, or null if timeout occurs
* @return the EventQueueItem, or null if timeout occurs or the wait is interrupted
* (in which case the thread's interrupt flag is set)
* @throws EventQueueClosedException if the queue is closed and empty
* @throws UnsupportedOperationException if called on MainQueue
*/
Expand Down Expand Up @@ -891,6 +892,9 @@ StreamCloseHandle getStreamCloseHandle() {

@Override
protected void doClose(boolean immediate) {
if (isClosed()) {
return;
}
// Invoke all callbacks BEFORE closing, so they can still enqueue events
if (!onCloseCallbacks.isEmpty()) {
LOGGER.debug("Invoking {} onClose callbacks for task {} BEFORE closing", onCloseCallbacks.size(), taskId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,11 @@ public void close(String taskId) {
if (existing == null) {
throw new NoTaskQueueException();
}
// Close the queue to stop EventConsumer polling loop
LOGGER.debug("Closing queue {} for task {}", System.identityHashCode(existing), taskId);
// A graceful MainQueue close leaves its children open, and EventConsumers poll the children
if (existing instanceof EventQueue.MainQueue mainQueue) {
mainQueue.closeChildren();
}
existing.close();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import static org.a2aproject.sdk.jsonrpc.common.json.JsonUtil.fromJson;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
Expand All @@ -11,17 +12,21 @@
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Flow;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

import org.a2aproject.sdk.jsonrpc.common.json.JsonProcessingException;
import org.a2aproject.sdk.server.tasks.InMemoryTaskStore;
import org.a2aproject.sdk.server.tasks.PushNotificationSender;
import org.a2aproject.sdk.server.tasks.TaskStateProvider;
import org.a2aproject.sdk.spec.A2AError;
import org.a2aproject.sdk.spec.A2AServerException;
import org.a2aproject.sdk.spec.Artifact;
import org.a2aproject.sdk.spec.Event;
import org.a2aproject.sdk.spec.InternalError;
import org.a2aproject.sdk.spec.Message;
import org.a2aproject.sdk.spec.Task;
import org.a2aproject.sdk.spec.TaskArtifactUpdateEvent;
Expand All @@ -32,6 +37,8 @@
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

public class EventConsumerTest {

Expand Down Expand Up @@ -139,7 +146,8 @@ public void testConsumeOneJsonRpcErrorEvent() throws Exception {

@Test
public void testConsumeOneQueueEmpty() throws A2AServerException {
assertThrows(A2AServerException.class, () -> eventConsumer.consumeOne());
A2AServerException exception = assertThrows(A2AServerException.class, () -> eventConsumer.consumeOne());
assertInstanceOf(InternalError.class, exception.getCause());
}

@Test
Expand Down Expand Up @@ -589,6 +597,89 @@ public void onComplete() {
assertEquals(0, receivedEvents.size(), "QueueClosedEvent should be intercepted, not delivered");
}

@ParameterizedTest(name = "agentCompleted={0}")
@ValueSource(booleans = {false, true})
public void testConsumeAllStopsWhenPollingThreadIsInterrupted(boolean agentCompleted) throws Exception {
assertInterruptedConsumerFailsAndClosesQueue(eventQueue, agentCompleted);
}

@Test
public void testInterruptedConsumerFailsWithInternalErrorWhenClosingItsQueueThrows() throws Exception {
EventQueue childQueue = EventQueueUtil.getEventQueueBuilder(mainEventBus)
.taskId(TASK_ID)
.mainEventBus(mainEventBus)
.taskStateProvider(new TaskStateProvider() {
@Override
public boolean isTaskActive(String taskId) {
return true;
}

@Override
public boolean isTaskFinalized(String taskId) {
// As a JDBC pool does when it must wait for a connection on an interrupted thread
if (Thread.currentThread().isInterrupted()) {
throw new IllegalStateException("Interrupted while acquiring");
}
return false;
}
})
.build().tap();
assertInterruptedConsumerFailsAndClosesQueue(childQueue, false);
}

private void assertInterruptedConsumerFailsAndClosesQueue(EventQueue queue, boolean agentCompleted) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
EventConsumer consumer = new EventConsumer(queue, executor);
if (agentCompleted) {
consumer.createAgentRunnableDoneCallback().done(new EnhancedRunnable() {
@Override
public void run() {
}
});
}
AtomicReference<Throwable> error = new AtomicReference<>();
CountDownLatch terminated = new CountDownLatch(1);

consumer.consumeAll().subscribe(new Flow.Subscriber<>() {
@Override
public void onSubscribe(Flow.Subscription subscription) {
subscription.request(Long.MAX_VALUE);
}

@Override
public void onNext(EventQueueItem item) {
}

@Override
public void onError(Throwable throwable) {
error.set(throwable);
terminated.countDown();
}

@Override
public void onComplete() {
terminated.countDown();
}
});

try {
queue.awaitQueuePollerStart();
executor.shutdownNow();

assertTrue(terminated.await(5, TimeUnit.SECONDS),
"Interrupted consumer should stop instead of polling again");
assertInstanceOf(InternalError.class, error.get());
// The consumer closes its queue after it fails the stream
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
assertTrue(queue.isClosed(), "Interrupted consumer should close its queue");
} finally {
// A loop that ignores the interrupt only ends when the queue closes; close it so the executor can terminate.
queue.close();
executor.shutdownNow();
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
}
}

private void enqueueAndConsumeOneEvent(Event event) throws Exception {
// Use callback to wait for event processing
waitForEventProcessing(() -> eventQueue.enqueueEvent(event));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,19 @@ public void testCloseExistingQueue() {
assertNull(result);
}

@Test
public void testCloseClosesChildQueues() {
String taskId = "close_children_task_id";
EventQueue first = queueManager.createOrTap(taskId);
EventQueue second = queueManager.tap(taskId);
assertNotNull(second);

queueManager.close(taskId);

assertTrue(first.isClosed(), "close(taskId) should close the ChildQueues that consumers poll");
assertTrue(second.isClosed(), "close(taskId) should close the ChildQueues that consumers poll");
}

@Test
public void testCloseNonexistentQueueThrowsException() {
assertThrows(NoTaskQueueException.class, () -> {
Expand Down
Loading