This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new 090b9c86d5f5 CAMEL-27357: camel-a2a - the consumer no longer loses 
task permits or leaves queued tasks waiting (#30632)
090b9c86d5f5 is described below

commit 090b9c86d5f572fd02a0eab96bb63b28b8bca0aa
Author: allthingssecurity <[email protected]>
AuthorDate: Mon Nov 23 14:02:20 2026 +0530

    CAMEL-27357: camel-a2a - the consumer no longer loses task permits or 
leaves queued tasks waiting (#30632)
    
    The permit of an async task belongs to its run (TaskRun): whoever ends the 
run first (its worker, its timeout, a
    cancel or the stop) gives the permit back, exactly once, to the semaphore 
of the start of the consumer that gave it,
    and a run removes only its own entry of inFlightTasks. A follow-up message 
on a running task, and an async timeout that
    fires as the task completes, no longer lose a permit. A queued task is 
stored before it is queued (a full queue is
    refused before the store is touched), the request drains the queue once 
more after it queued a task, and a run does
    not start the route of a task that is already canceled.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../apache/camel/component/a2a/A2AConsumer.java    | 259 +++++++-----
 .../component/a2a/A2AConsumerTaskPermitsTest.java  | 464 +++++++++++++++++++++
 2 files changed, 628 insertions(+), 95 deletions(-)

diff --git 
a/components/camel-ai/camel-a2a/src/main/java/org/apache/camel/component/a2a/A2AConsumer.java
 
b/components/camel-ai/camel-a2a/src/main/java/org/apache/camel/component/a2a/A2AConsumer.java
index 84dbd0a7b03f..646a075b1f10 100644
--- 
a/components/camel-ai/camel-a2a/src/main/java/org/apache/camel/component/a2a/A2AConsumer.java
+++ 
b/components/camel-ai/camel-a2a/src/main/java/org/apache/camel/component/a2a/A2AConsumer.java
@@ -35,6 +35,7 @@ import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.Semaphore;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.function.Function;
 
 import org.apache.camel.Consumer;
@@ -107,8 +108,8 @@ public class A2AConsumer extends DefaultConsumer {
 
     private final MessageSendOperation messageSendOperation;
     private final List<Consumer> httpConsumers = new ArrayList<>();
-    private final ConcurrentHashMap<String, Future<?>> inFlightTasks = new 
ConcurrentHashMap<>();
-    private final ConcurrentHashMap<String, ScheduledFuture<?>> timeoutFutures 
= new ConcurrentHashMap<>();
+    // the latest run of each task on the async executor; a follow-up message 
on a running task starts a second run
+    private final ConcurrentHashMap<String, TaskRun> inFlightTasks = new 
ConcurrentHashMap<>();
     private final ConcurrentHashMap<String, String> taskOwners = new 
ConcurrentHashMap<>();
     private ExecutorService asyncExecutor;
     private ScheduledExecutorService asyncTimeoutScheduler;
@@ -285,17 +286,15 @@ public class A2AConsumer extends DefaultConsumer {
 
     private void cancelAllInFlight() {
         A2ATaskStore store = getEndpoint().getTaskStore();
-        inFlightTasks.forEach((taskId, future) -> {
-            if (inFlightTasks.remove(taskId, future)) {
-                future.cancel(true);
+        inFlightTasks.forEach((taskId, run) -> {
+            inFlightTasks.remove(taskId, run);
+            run.cancelTimeout();
+            if (run.end()) {
+                run.cancel();
                 store.updateStatusAndNotify(taskId, new 
TaskStatus(TaskState.FAILED));
-                releasePermit(false);
+                releasePermit(run, false);
             }
         });
-        for (ScheduledFuture<?> timeoutFuture : timeoutFutures.values()) {
-            timeoutFuture.cancel(false);
-        }
-        timeoutFutures.clear();
     }
 
     // ---- Capacity limiting ----
@@ -317,16 +316,33 @@ public class A2AConsumer extends DefaultConsumer {
         }
     }
 
+    /**
+     * Gives the permit of a run back to the semaphore it was taken from: a 
run that outlives a stop and a new start of
+     * the consumer must not add a permit to the semaphore of the new start.
+     */
+    private void releasePermit(TaskRun run, boolean drain) {
+        Semaphore permits = run.permits;
+        if (permits != null) {
+            permits.release();
+            if (drain) {
+                drainPendingQueue();
+            }
+        }
+    }
+
     private void drainPendingQueue() {
-        if (pendingTaskQueue == null || pendingTaskQueue.isEmpty()) {
+        // the stop sets both fields to null
+        LinkedBlockingQueue<PendingTask> queue = pendingTaskQueue;
+        Semaphore permits = taskPermits;
+        if (queue == null || permits == null || queue.isEmpty()) {
             return;
         }
-        if (!taskPermits.tryAcquire()) {
+        if (!permits.tryAcquire()) {
             return;
         }
-        PendingTask pending = pendingTaskQueue.poll();
+        PendingTask pending = queue.poll();
         if (pending == null) {
-            taskPermits.release();
+            permits.release();
             return;
         }
         try {
@@ -390,6 +406,46 @@ public class A2AConsumer extends DefaultConsumer {
     private record PendingTask(String taskId, String contextId, Exchange 
processorExchange) {
     }
 
+    /**
+     * One run of a task on the async executor and the permit it holds. A 
follow-up message on a task that is still
+     * running starts a second run of the same task, which replaces the first 
one in {@code inFlightTasks}, so the
+     * permit belongs to the run and not to the map entry. Whoever ends the 
run first (its worker, its timeout, a cancel
+     * or the stop) releases the permit, exactly once, to the semaphore of the 
start of the consumer that gave it.
+     */
+    private static final class TaskRun {
+        private final AtomicBoolean ended = new AtomicBoolean();
+        // null when maxConcurrentTasks is 0 (no limit)
+        private final Semaphore permits;
+        private volatile Future<?> future;
+        private volatile ScheduledFuture<?> timeout;
+
+        TaskRun(Semaphore permits) {
+            this.permits = permits;
+        }
+
+        /**
+         * @return true for the one caller that ends the run, which then 
releases its permit
+         */
+        boolean end() {
+            return ended.compareAndSet(false, true);
+        }
+
+        void cancelTimeout() {
+            ScheduledFuture<?> t = timeout;
+            if (t != null) {
+                t.cancel(false);
+            }
+        }
+
+        void cancel() {
+            Future<?> f = future;
+            if (f != null) {
+                f.cancel(true);
+            }
+            cancelTimeout();
+        }
+    }
+
     private void registerRoute(
             RestConsumerFactory factory, RestConfiguration restConfig,
             String verb, String path, A2ARequestHandler handler)
@@ -1268,11 +1324,11 @@ public class A2AConsumer extends DefaultConsumer {
                 releasePermit();
                 throw e;
             }
-        } else if (pendingTaskQueue != null
-                && pendingTaskQueue.offer(new PendingTask(taskId, contextId, 
processorExchange))) {
-            store.put(taskId, submittedTask);
+        } else if (queueTask(store, taskId, contextId, processorExchange, 
submittedTask)) {
             store.notifySubscribers(taskId, 
StreamResponse.ofStatusUpdate(buildStatusEvent(submittedTask)));
-            LOG.debug("Task {} queued (queue size: {})", taskId, 
pendingTaskQueue.size());
+            LOG.debug("Task {} queued", taskId);
+            // a task that ended while this request was queueing found the 
queue empty and did not start this one
+            drainPendingQueue();
         } else {
             throw new ServerBusyException(
                     "Agent at capacity: "
@@ -1286,12 +1342,49 @@ public class A2AConsumer extends DefaultConsumer {
         return response;
     }
 
+    /**
+     * Stores the task as SUBMITTED and queues it. The task is stored first: 
once it is queued, a task that ends on
+     * another thread can start it at once, and a SUBMITTED stored after its 
run would stay for good. A full queue is
+     * refused before the store is touched (a put of a new task can evict a 
terminal task once maxStoredTasks is
+     * reached); only when another request takes the last place in between is 
what was in the store put back.
+     *
+     * @return false if the queue is full (the store is then as before)
+     */
+    private boolean queueTask(
+            A2ATaskStore store, String taskId, String contextId, Exchange 
processorExchange, Task submittedTask) {
+        LinkedBlockingQueue<PendingTask> queue = pendingTaskQueue;
+        if (queue == null || queue.remainingCapacity() == 0) {
+            return false;
+        }
+        Task previous = store.get(taskId);
+        store.put(taskId, submittedTask);
+        if (queue.offer(new PendingTask(taskId, contextId, 
processorExchange))) {
+            return true;
+        }
+        if (previous == null) {
+            store.delete(taskId);
+        } else {
+            store.put(taskId, previous);
+        }
+        return false;
+    }
+
+    private static boolean isCanceled(Task task) {
+        return task != null && task.status() != null && task.status().state() 
== TaskState.CANCELED;
+    }
+
     private void submitAsyncTask(String taskId, String contextId, Exchange 
processorExchange) {
         A2ATaskStore store = getEndpoint().getTaskStore();
 
+        TaskRun run = new TaskRun(taskPermits);
         FutureTask<Void> future = new FutureTask<>(() -> {
             try {
                 Task workingTask = store.get(taskId);
+                if (isCanceled(workingTask)) {
+                    // canceled before this run started, for example while the 
drain of the queue held it
+                    LOG.debug("Not running canceled task {}", taskId);
+                    return null;
+                }
                 if (workingTask != null) {
                     store.updateStatusAndNotify(taskId, new 
TaskStatus(TaskState.WORKING));
                 }
@@ -1315,46 +1408,56 @@ public class A2AConsumer extends DefaultConsumer {
                 LOG.error("Async task processing failed for taskId={}", 
taskId, e);
                 store.updateStatusAndNotify(taskId, new 
TaskStatus(TaskState.FAILED));
             } finally {
-                boolean weOwnPermit = inFlightTasks.remove(taskId) != null;
-                ScheduledFuture<?> timeoutFuture = 
timeoutFutures.remove(taskId);
-                if (timeoutFuture != null) {
-                    timeoutFuture.cancel(false);
-                }
-                if (weOwnPermit) {
-                    releasePermit();
-                }
+                endRun(taskId, run);
             }
             return null;
         });
-        inFlightTasks.put(taskId, future);
-        ScheduledFuture<?> timeoutFuture = null;
+        submitRun(taskId, run, future, () -> {
+            store.updateStatusAndNotify(taskId, new 
TaskStatus(TaskState.FAILED));
+            LOG.warn("Async task timed out after {}ms for taskId={}",
+                    getEndpoint().getConfiguration().getAsyncTimeout(), 
taskId);
+        });
+    }
+
+    /**
+     * Registers the run, schedules its timeout and hands it to the async 
executor. The timeout ends the run (and
+     * releases its permit) only when the worker has not ended it yet.
+     */
+    private void submitRun(String taskId, TaskRun run, FutureTask<Void> 
future, Runnable onTimeout) {
+        run.future = future;
+        inFlightTasks.put(taskId, run);
         try {
             long asyncTimeout = 
getEndpoint().getConfiguration().getAsyncTimeout();
             if (asyncTimeout > 0) {
-                timeoutFuture = asyncTimeoutScheduler.schedule(() -> {
-                    timeoutFutures.remove(taskId);
-                    Future<?> f = inFlightTasks.remove(taskId);
-                    if (f != null && !f.isDone()) {
-                        f.cancel(true);
-                        store.updateStatusAndNotify(taskId, new 
TaskStatus(TaskState.FAILED));
-                        releasePermit();
-                        LOG.warn("Async task timed out after {}ms for 
taskId={}", asyncTimeout, taskId);
+                run.timeout = asyncTimeoutScheduler.schedule(() -> {
+                    if (run.end()) {
+                        inFlightTasks.remove(taskId, run);
+                        future.cancel(true);
+                        onTimeout.run();
+                        releasePermit(run, true);
                     }
                 }, asyncTimeout, TimeUnit.MILLISECONDS);
-                timeoutFutures.put(taskId, timeoutFuture);
             }
             asyncExecutor.execute(future);
         } catch (RuntimeException e) {
-            inFlightTasks.remove(taskId, future);
-            future.cancel(true);
-            if (timeoutFuture != null) {
-                timeoutFutures.remove(taskId, timeoutFuture);
-                timeoutFuture.cancel(false);
-            }
+            inFlightTasks.remove(taskId, run);
+            run.cancel();
             throw e;
         }
     }
 
+    /**
+     * The worker of the run is done: releases the permit unless the timeout, 
a cancel or the stop already ended the
+     * run.
+     */
+    private void endRun(String taskId, TaskRun run) {
+        inFlightTasks.remove(taskId, run);
+        run.cancelTimeout();
+        if (run.end()) {
+            releasePermit(run, true);
+        }
+    }
+
     private boolean resolveReturnImmediately(SendMessageRequest request, 
Exchange exchange) {
         SendMessageConfiguration configuration = request.getConfiguration();
         if (configuration != null && configuration.getReturnImmediately() != 
null) {
@@ -1467,14 +1570,10 @@ public class A2AConsumer extends DefaultConsumer {
         if (task == null) {
             throw new TaskNotFoundException("Task not found: " + taskId);
         }
-        Future<?> inFlight = inFlightTasks.remove(taskId);
-        if (inFlight != null) {
-            inFlight.cancel(true);
-            ScheduledFuture<?> timeoutFuture = timeoutFutures.remove(taskId);
-            if (timeoutFuture != null) {
-                timeoutFuture.cancel(false);
-            }
-            releasePermit();
+        TaskRun inFlight = inFlightTasks.remove(taskId);
+        if (inFlight != null && inFlight.end()) {
+            inFlight.cancel();
+            releasePermit(inFlight, true);
         }
         if (pendingTaskQueue != null) {
             pendingTaskQueue.removeIf(pending -> 
taskId.equals(pending.taskId()));
@@ -1497,8 +1596,13 @@ public class A2AConsumer extends DefaultConsumer {
         processorExchange.getMessage().setHeader(A2AConstants.STREAM_EMITTER, 
emitter);
 
         A2ATaskStore store = getEndpoint().getTaskStore();
+        TaskRun run = new TaskRun(taskPermits);
         FutureTask<Void> future = new FutureTask<>(() -> {
             try {
+                if (isCanceled(store.get(taskId))) {
+                    LOG.debug("Not running canceled streaming task {}", 
taskId);
+                    return null;
+                }
                 invokeExtensionHandlersBeforeRoute(processorExchange);
                 getProcessor().process(processorExchange);
                 if (processorExchange.getException() != null) {
@@ -1520,45 +1624,16 @@ public class A2AConsumer extends DefaultConsumer {
                 store.updateStatusAndNotify(taskId, new 
TaskStatus(TaskState.FAILED));
             } finally {
                 emitter.close();
-                boolean weOwnPermit = inFlightTasks.remove(taskId) != null;
-                ScheduledFuture<?> timeoutFuture = 
timeoutFutures.remove(taskId);
-                if (timeoutFuture != null) {
-                    timeoutFuture.cancel(false);
-                }
-                if (weOwnPermit) {
-                    releasePermit();
-                }
+                endRun(taskId, run);
             }
             return null;
         });
-        inFlightTasks.put(taskId, future);
-        ScheduledFuture<?> timeoutFuture = null;
-        try {
-            long asyncTimeout = 
getEndpoint().getConfiguration().getAsyncTimeout();
-            if (asyncTimeout > 0) {
-                timeoutFuture = asyncTimeoutScheduler.schedule(() -> {
-                    timeoutFutures.remove(taskId);
-                    Future<?> f = inFlightTasks.remove(taskId);
-                    if (f != null && !f.isDone()) {
-                        f.cancel(true);
-                        store.updateStatusAndNotify(taskId, new 
TaskStatus(TaskState.FAILED));
-                        emitter.close();
-                        releasePermit();
-                        LOG.warn("Streaming task timed out after {}ms for 
taskId={}", asyncTimeout, taskId);
-                    }
-                }, asyncTimeout, TimeUnit.MILLISECONDS);
-                timeoutFutures.put(taskId, timeoutFuture);
-            }
-            asyncExecutor.execute(future);
-        } catch (RuntimeException e) {
-            inFlightTasks.remove(taskId, future);
-            future.cancel(true);
-            if (timeoutFuture != null) {
-                timeoutFutures.remove(taskId, timeoutFuture);
-                timeoutFuture.cancel(false);
-            }
-            throw e;
-        }
+        submitRun(taskId, run, future, () -> {
+            store.updateStatusAndNotify(taskId, new 
TaskStatus(TaskState.FAILED));
+            emitter.close();
+            LOG.warn("Streaming task timed out after {}ms for taskId={}",
+                    getEndpoint().getConfiguration().getAsyncTimeout(), 
taskId);
+        });
     }
 
     private ListTasksResponse processListTasks(TaskListRequest request, 
Exchange exchange) {
@@ -1819,14 +1894,8 @@ public class A2AConsumer extends DefaultConsumer {
             return;
         }
         A2ATaskStore store = getEndpoint().getTaskStore();
-        Future<?> future = inFlightTasks.remove(taskId);
-        if (future != null) {
-            future.cancel(true);
-        }
-        ScheduledFuture<?> timeoutFuture = timeoutFutures.remove(taskId);
-        if (timeoutFuture != null) {
-            timeoutFuture.cancel(false);
-        }
+        // a run whose submission failed is removed by submitRun; a run in 
inFlightTasks belongs to another message of
+        // the same task
         if (subscriber != null) {
             store.removeSubscriber(taskId, subscriber);
         }
diff --git 
a/components/camel-ai/camel-a2a/src/test/java/org/apache/camel/component/a2a/A2AConsumerTaskPermitsTest.java
 
b/components/camel-ai/camel-a2a/src/test/java/org/apache/camel/component/a2a/A2AConsumerTaskPermitsTest.java
new file mode 100644
index 000000000000..4af03bfb5efc
--- /dev/null
+++ 
b/components/camel-ai/camel-a2a/src/test/java/org/apache/camel/component/a2a/A2AConsumerTaskPermitsTest.java
@@ -0,0 +1,464 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.a2a;
+
+import java.lang.reflect.Field;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.component.a2a.model.SendMessageResponse;
+import org.apache.camel.component.a2a.model.Task;
+import org.apache.camel.component.a2a.model.TaskState;
+import org.apache.camel.component.a2a.state.InMemoryTaskStore;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.support.DefaultExchange;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import tools.jackson.databind.DeserializationFeature;
+import tools.jackson.databind.ObjectMapper;
+import tools.jackson.databind.cfg.DateTimeFeature;
+import tools.jackson.databind.json.JsonMapper;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+
+/**
+ * The task permits (maxConcurrentTasks) and the pending task queue 
(taskQueueSize) of async tasks (returnImmediately).
+ * Each test forces one interleaving of the request thread, the async worker, 
the async timeout and a cancel with a hook
+ * on the queue, the executor or the in-flight map of the consumer; a hook 
only holds one thread at one step, so each
+ * ordering is one the consumer allows without it.
+ */
+class A2AConsumerTaskPermitsTest {
+
+    private static final ObjectMapper OBJECT_MAPPER = JsonMapper.builder()
+            .disable(DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS)
+            .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
+            .build();
+
+    private CamelContext context;
+    private A2AConsumer consumer;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        context = new DefaultCamelContext();
+        NoopRestConsumerFactory.bindTo(context);
+        context.getRestConfiguration().setComponent("noopRestConsumerFactory");
+        context.start();
+    }
+
+    @AfterEach
+    void tearDown() throws Exception {
+        if (consumer != null) {
+            consumer.doStop();
+        }
+        if (context != null) {
+            context.stop();
+        }
+    }
+
+    @Test
+    void followUpMessageOnARunningTaskGivesBothPermitsBack() throws Exception {
+        CountDownLatch release1 = new CountDownLatch(1);
+        AtomicInteger routeCalls = new AtomicInteger();
+        consumer = createConsumer(2, 0, 0, exchange -> {
+            if (routeCalls.incrementAndGet() == 1) {
+                release1.await(10, TimeUnit.SECONDS);
+            }
+        });
+        Semaphore permits = getField(consumer, "taskPermits");
+        Map<?, ?> inFlight = getField(consumer, "inFlightTasks");
+
+        String task1 = sendAsync();
+        // a follow-up message on task 1 while its first message is still 
being routed
+        Exchange followUp = sendAsyncExchange("\"taskId\":\"" + task1 + "\",");
+        
assertThat(followUp.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE, 
Integer.class)).isNull();
+        assertThat(permits.availablePermits()).isZero();
+        release1.countDown();
+
+        await().atMost(10, TimeUnit.SECONDS).until(() -> routeCalls.get() == 2 
&& inFlight.isEmpty());
+        await().atMost(5, TimeUnit.SECONDS).until(() -> 
permits.availablePermits() == 2);
+        // the agent still runs two tasks at once
+        sendAsync();
+        sendAsync();
+        await().atMost(10, TimeUnit.SECONDS).until(() -> routeCalls.get() == 4 
&& permits.availablePermits() == 2);
+    }
+
+    @Test
+    void timeoutFiringAsTheTaskCompletesGivesThePermitBack() throws Exception {
+        CountDownLatch routeMayEnd = new CountDownLatch(1);
+        AtomicInteger routeCalls = new AtomicInteger();
+        consumer = createConsumer(1, 1, 200, exchange -> {
+            if (routeCalls.incrementAndGet() == 1) {
+                routeMayEnd.await(10, TimeUnit.SECONDS);
+            }
+        });
+        TrackingExecutor exec = installTrackingExecutor(consumer);
+        AtomicBoolean armed = new AtomicBoolean(true);
+        // the timeout takes the task out of the in-flight map; right then the 
task completes
+        ConcurrentHashMap<String, Object> inFlight = new ConcurrentHashMap<>() 
{
+            @Override
+            public Object remove(Object key) {
+                Object removed = super.remove(key);
+                completeTaskIfTimeoutThread();
+                return removed;
+            }
+
+            @Override
+            public boolean remove(Object key, Object value) {
+                boolean removed = super.remove(key, value);
+                completeTaskIfTimeoutThread();
+                return removed;
+            }
+
+            private void completeTaskIfTimeoutThread() {
+                if 
(Thread.currentThread().getName().contains("A2AAsyncTimeout") && 
armed.compareAndSet(true, false)) {
+                    routeMayEnd.countDown();
+                    exec.awaitCompletions(1);
+                }
+            }
+        };
+        setField(consumer, "inFlightTasks", inFlight);
+        Semaphore permits = getField(consumer, "taskPermits");
+
+        String task1 = sendAsync();
+        await().atMost(10, TimeUnit.SECONDS).until(() -> !armed.get() && 
inFlight.isEmpty());
+        await().atMost(5, TimeUnit.SECONDS).until(() -> 
permits.availablePermits() == 1);
+        assertThat(state(task1)).isIn(TaskState.COMPLETED, TaskState.FAILED);
+
+        // the agent is not at capacity: the next task runs
+        String task2 = sendAsync();
+        await().atMost(10, TimeUnit.SECONDS).until(() -> state(task2) == 
TaskState.COMPLETED);
+        assertThat(routeCalls.get()).isEqualTo(2);
+    }
+
+    @Test
+    void taskQueuedWhileTheRunningTaskEndsIsStarted() throws Exception {
+        CountDownLatch release1 = new CountDownLatch(1);
+        AtomicInteger routeCalls = new AtomicInteger();
+        consumer = createConsumer(1, 1, 0, exchange -> {
+            if (routeCalls.incrementAndGet() == 1) {
+                release1.await(10, TimeUnit.SECONDS);
+            }
+        });
+        TrackingExecutor exec = installTrackingExecutor(consumer);
+        AtomicBoolean armed = new AtomicBoolean(true);
+        LinkedBlockingQueue<Object> queue = new LinkedBlockingQueue<>(1) {
+            @Override
+            public boolean offer(Object e) {
+                if (armed.compareAndSet(true, false)) {
+                    // the request found no free permit; before it queues its 
task, task 1 ends, gives its permit back
+                    // and finds the queue empty
+                    release1.countDown();
+                    exec.awaitCompletions(1);
+                }
+                return super.offer(e);
+            }
+        };
+        setField(consumer, "pendingTaskQueue", queue);
+        Semaphore permits = getField(consumer, "taskPermits");
+
+        String task1 = sendAsync();
+        String task2 = sendAsync();
+
+        await().atMost(10, TimeUnit.SECONDS).until(() -> state(task2) == 
TaskState.COMPLETED);
+        assertThat(state(task1)).isEqualTo(TaskState.COMPLETED);
+        assertThat(routeCalls.get()).isEqualTo(2);
+        assertThat(queue).isEmpty();
+        await().atMost(5, TimeUnit.SECONDS).until(() -> 
permits.availablePermits() == 1);
+    }
+
+    @Test
+    void queuedTaskCanceledWhileTheDrainHoldsItDoesNotRun() throws Exception {
+        CountDownLatch release1 = new CountDownLatch(1);
+        CountDownLatch polled = new CountDownLatch(1);
+        CountDownLatch cancelReturned = new CountDownLatch(1);
+        List<String> routeTaskIds = new CopyOnWriteArrayList<>();
+        consumer = createConsumer(1, 1, 0, exchange -> {
+            
routeTaskIds.add(exchange.getProperty(A2AConstants.REQUEST_TASK_ID, 
String.class));
+            if (routeTaskIds.size() == 1) {
+                release1.await(10, TimeUnit.SECONDS);
+            }
+        });
+        TrackingExecutor exec = installTrackingExecutor(consumer);
+        AtomicBoolean armed = new AtomicBoolean(true);
+        LinkedBlockingQueue<Object> queue = new LinkedBlockingQueue<>(1) {
+            @Override
+            public Object poll() {
+                Object e = super.poll();
+                if (e != null && armed.compareAndSet(true, false)) {
+                    // the drain took the task out of the queue and has not 
submitted it yet: the cancel runs now
+                    polled.countDown();
+                    try {
+                        cancelReturned.await(10, TimeUnit.SECONDS);
+                    } catch (InterruptedException ex) {
+                        Thread.currentThread().interrupt();
+                    }
+                }
+                return e;
+            }
+        };
+        setField(consumer, "pendingTaskQueue", queue);
+        Semaphore permits = getField(consumer, "taskPermits");
+
+        String task1 = sendAsync();
+        String task2 = sendAsync();
+        assertThat(state(task2)).isEqualTo(TaskState.SUBMITTED);
+        assertThat(queue).hasSize(1);
+
+        release1.countDown();
+        assertThat(polled.await(10, TimeUnit.SECONDS)).isTrue();
+        Exchange cancel = new DefaultExchange(context);
+        cancel.getMessage().setHeader(Exchange.HTTP_PATH, "/tasks/" + task2 + 
":cancel");
+        consumer.handleCancelTask(cancel);
+        Task canceled = 
OBJECT_MAPPER.readValue(cancel.getMessage().getBody(byte[].class), Task.class);
+        assertThat(canceled.status().state()).isEqualTo(TaskState.CANCELED);
+        cancelReturned.countDown();
+
+        // the drain submitted the canceled task: it ends without running the 
route
+        exec.awaitCompletions(2);
+        assertThat(routeTaskIds).containsExactly(task1);
+        assertThat(state(task2)).isEqualTo(TaskState.CANCELED);
+        await().atMost(5, TimeUnit.SECONDS).until(() -> 
permits.availablePermits() == 1);
+    }
+
+    @Test
+    void queuedTaskThatFailsBeforeTheRequestReturnsEndsFailed() throws 
Exception {
+        CountDownLatch release1 = new CountDownLatch(1);
+        AtomicInteger routeCalls = new AtomicInteger();
+        consumer = createConsumer(1, 1, 0, exchange -> {
+            if (routeCalls.incrementAndGet() == 1) {
+                release1.await(10, TimeUnit.SECONDS);
+            } else {
+                throw new IllegalStateException("route failure for the queued 
task");
+            }
+        });
+        TrackingExecutor exec = installTrackingExecutor(consumer);
+        AtomicBoolean armed = new AtomicBoolean(true);
+        LinkedBlockingQueue<Object> queue = new LinkedBlockingQueue<>(1) {
+            @Override
+            public boolean offer(Object e) {
+                boolean offered = super.offer(e);
+                if (offered && armed.compareAndSet(true, false)) {
+                    // right after the task is queued, task 1 ends and the 
drain runs the queued task, which fails,
+                    // all before the request returns
+                    release1.countDown();
+                    exec.awaitCompletions(2);
+                }
+                return offered;
+            }
+        };
+        setField(consumer, "pendingTaskQueue", queue);
+        Semaphore permits = getField(consumer, "taskPermits");
+
+        sendAsync();
+        String task2 = sendAsync();
+
+        assertThat(routeCalls.get()).isEqualTo(2);
+        assertThat(state(task2)).isEqualTo(TaskState.FAILED);
+        await().atMost(5, TimeUnit.SECONDS).until(() -> 
permits.availablePermits() == 1);
+    }
+
+    @Test
+    void fullQueueRejectsTheTaskWithoutTouchingTheStore() throws Exception {
+        CountDownLatch release1 = new CountDownLatch(1);
+        AtomicInteger routeCalls = new AtomicInteger();
+        consumer = createConsumer(1, 1, 0, exchange -> {
+            if (routeCalls.incrementAndGet() == 1) {
+                release1.await(10, TimeUnit.SECONDS);
+            }
+        });
+        Semaphore permits = getField(consumer, "taskPermits");
+        InMemoryTaskStore store = (InMemoryTaskStore) 
consumer.getEndpoint().getTaskStore();
+
+        String task1 = sendAsync();
+        // a queued task that is canceled: a terminal task the store keeps
+        String task2 = sendAsync();
+        Exchange cancel = new DefaultExchange(context);
+        cancel.getMessage().setHeader(Exchange.HTTP_PATH, "/tasks/" + task2 + 
":cancel");
+        consumer.handleCancelTask(cancel);
+        String task3 = sendAsync();
+        // the store is at its cap: a put of one more task would evict the 
oldest terminal task (task 2)
+        store.setMaxStoredTasks(3);
+
+        Exchange fourth = sendAsyncExchange("");
+        assertThat(fourth.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE, 
Integer.class)).isEqualTo(429);
+        assertThat(store.keys()).containsExactlyInAnyOrder(task1, task2, 
task3);
+        assertThat(state(task2)).isEqualTo(TaskState.CANCELED);
+
+        release1.countDown();
+        await().atMost(10, TimeUnit.SECONDS).until(() -> state(task3) == 
TaskState.COMPLETED);
+        await().atMost(5, TimeUnit.SECONDS).until(() -> 
permits.availablePermits() == 1);
+    }
+
+    @Test
+    void runThatOutlivesAStopGivesItsPermitToTheStartThatGaveIt() throws 
Exception {
+        CountDownLatch release1 = new CountDownLatch(1);
+        AtomicInteger routeCalls = new AtomicInteger();
+        consumer = createConsumer(2, 0, 0, exchange -> {
+            if (routeCalls.incrementAndGet() == 1) {
+                awaitIgnoringInterrupts(release1);
+            }
+        });
+        // the stop waits a short time for the run that does not react to the 
interrupt
+        context.getExecutorServiceManager().setShutdownAwaitTermination(200);
+        ExecutorService firstExecutor = getField(consumer, "asyncExecutor");
+
+        String task1 = sendAsync();
+        // a follow-up message on task 1 replaces the first run in the 
in-flight map: the stop reaches only the second
+        Exchange followUp = sendAsyncExchange("\"taskId\":\"" + task1 + "\",");
+        
assertThat(followUp.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE, 
Integer.class)).isNull();
+
+        consumer.doStop();
+        consumer.doStart();
+        Semaphore permits = getField(consumer, "taskPermits");
+        assertThat(permits.availablePermits()).isEqualTo(2);
+
+        // the first run ends after the new start
+        release1.countDown();
+        assertThat(firstExecutor.awaitTermination(10, 
TimeUnit.SECONDS)).isTrue();
+        assertThat(permits.availablePermits()).isEqualTo(2);
+    }
+
+    // ---- helpers ----
+
+    private A2AConsumer createConsumer(int maxTasks, int queueSize, long 
asyncTimeout, Processor processor)
+            throws Exception {
+        A2AConfiguration config = new A2AConfiguration();
+        config.setName("Capacity Agent");
+        config.setVersion("1.0.0");
+        config.setMaxConcurrentTasks(maxTasks);
+        config.setTaskQueueSize(queueSize);
+        config.setReturnImmediately(true);
+        config.setAsyncTimeout(asyncTimeout);
+
+        A2AComponent component = new A2AComponent();
+        component.setCamelContext(context);
+        A2AEndpoint endpoint = new A2AEndpoint("a2a:capacity-agent", 
component, config);
+        endpoint.setAgentCardSource("capacity-agent");
+        endpoint.setCamelContext(context);
+        endpoint.doStart();
+
+        A2AConsumer answer = new A2AConsumer(endpoint, processor);
+        answer.doStart();
+        return answer;
+    }
+
+    private Exchange sendAsyncExchange(String taskIdField) throws Exception {
+        Exchange exchange = new DefaultExchange(context);
+        exchange.getMessage().setBody("{\"message\":{\"messageId\":\"msg-" + 
UUID.randomUUID() + "\"," + taskIdField
+                                      + 
"\"role\":\"user\",\"parts\":[{\"text\":\"Hello\"}]}}");
+        consumer.handleSendMessage(exchange);
+        return exchange;
+    }
+
+    private String sendAsync() throws Exception {
+        Exchange exchange = sendAsyncExchange("");
+        
assertThat(exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE, 
Integer.class)).isNull();
+        SendMessageResponse response
+                = 
OBJECT_MAPPER.readValue(exchange.getMessage().getBody(byte[].class), 
SendMessageResponse.class);
+        return response.getTask().id();
+    }
+
+    private TaskState state(String taskId) {
+        Task task = consumer.getEndpoint().getTaskStore().get(taskId);
+        return task == null ? null : task.status().state();
+    }
+
+    private static void awaitIgnoringInterrupts(CountDownLatch latch) {
+        boolean interrupted = false;
+        try {
+            while (true) {
+                try {
+                    if (!latch.await(10, TimeUnit.SECONDS)) {
+                        throw new IllegalStateException("not released");
+                    }
+                    return;
+                } catch (InterruptedException e) {
+                    interrupted = true;
+                }
+            }
+        } finally {
+            if (interrupted) {
+                Thread.currentThread().interrupt();
+            }
+        }
+    }
+
+    private static TrackingExecutor installTrackingExecutor(A2AConsumer 
consumer) throws Exception {
+        TrackingExecutor exec = new TrackingExecutor();
+        ExecutorService previous = getField(consumer, "asyncExecutor");
+        setField(consumer, "asyncExecutor", exec);
+        previous.shutdownNow();
+        return exec;
+    }
+
+    @SuppressWarnings("unchecked")
+    private static <T> T getField(Object target, String name) throws Exception 
{
+        Field field = A2AConsumer.class.getDeclaredField(name);
+        field.setAccessible(true);
+        return (T) field.get(target);
+    }
+
+    private static void setField(Object target, String name, Object value) 
throws Exception {
+        Field field = A2AConsumer.class.getDeclaredField(name);
+        field.setAccessible(true);
+        field.set(target, value);
+    }
+
+    /**
+     * Same shape as the async executor of the consumer (one thread, FIFO 
queue); counts the tasks whose run returned.
+     */
+    private static final class TrackingExecutor extends ThreadPoolExecutor {
+        private final Semaphore completions = new Semaphore(0);
+
+        TrackingExecutor() {
+            super(1, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
+        }
+
+        @Override
+        protected void afterExecute(Runnable r, Throwable t) {
+            super.afterExecute(r, t);
+            completions.release();
+        }
+
+        void awaitCompletions(int n) {
+            try {
+                if (!completions.tryAcquire(n, 10, TimeUnit.SECONDS)) {
+                    throw new IllegalStateException("tasks did not complete");
+                }
+            } catch (InterruptedException e) {
+                Thread.currentThread().interrupt();
+                throw new IllegalStateException(e);
+            }
+        }
+    }
+}

Reply via email to