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 228e67a22220 CAMEL-27445: camel-resilience4j - a call that times out
before it starts is not started later, in asynchronous mode and in synchronous
mode with a bulkhead (#30810)
228e67a22220 is described below
commit 228e67a22220baebc2cbce7423cbd3bf712c9d36
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 14:33:50 2026 +0530
CAMEL-27445: camel-resilience4j - a call that times out before it starts is
not started later, in asynchronous mode and in synchronous mode with a bulkhead
(#30810)
When the timeout of a call fired while the call still waited in the queue
of the
thread pool, the exchange went on with the timeout or the fallback, but the
call ran
later in two cases. In asynchronous mode nothing cancelled the submitted
task, and
timeoutCancelRunningFuture had no effect. In synchronous mode with a
bulkhead the
time limiter cancelled the future of the bulkhead, not the one of the call,
and the
call kept its bulkhead permit until it ran. So the backend got a call for
an exchange
that had already timed out, possibly after the circuit breaker had opened.
The task of the call and the caller that cancels it now both claim the
call, and only
one of them gets it. A call that has not started when it times out is
cancelled (when
timeoutCancelRunningFuture is true, the default), is never started, and
releases its
bulkhead permit at once. A call that has started keeps running, as before,
and keeps
its permit until it is done. Synchronous mode without a bulkhead is
unchanged.
* CAMEL-27445: camel-resilience4j - review follow-up: comments on the
skipped call and the permit check
- ResilienceProcessor: the comment on the queued task says that a call
skipped because it
timed out before it started has a future that callStart.cancel() already
cancelled, not
one completed with a TimeoutException.
- ResilienceTimedOutQueuedCallTest: a comment says why the available
bulkhead permits are
read after X2 timed out and before X1 ends.
Comments only.
* CAMEL-27445: camel-resilience4j - review follow-up: upgrade guide entry,
comment on the skipped call, longer test waits
- Upgrade guide 4.24: in asynchronous mode, timeoutCancelRunningFuture
(default true) now has an effect: a call that
times out while it is queued no longer reaches the backend, and with a
bulkhead its permit is released at the
timeout, not when a thread takes the call.
timeoutCancelRunningFuture=false keeps the old asynchronous behaviour.
- ResilienceProcessor: the comment on the skipped call is right without a
bulkhead too: callStart.cancel() claimed
the call on the timeout (without a bulkhead the future was completed with
the TimeoutException, not cancelled).
- ResilienceTimedOutQueuedCallTest: the waits are 20 seconds instead of 5,
for a loaded CI machine.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../resilience4j/ResilienceProcessor.java | 119 ++++++++++++-
.../ResilienceTimedOutQueuedCallTest.java | 186 +++++++++++++++++++++
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 10 ++
3 files changed, 311 insertions(+), 4 deletions(-)
diff --git
a/components/camel-resilience4j/src/main/java/org/apache/camel/component/resilience4j/ResilienceProcessor.java
b/components/camel-resilience4j/src/main/java/org/apache/camel/component/resilience4j/ResilienceProcessor.java
index 6791e301a9d0..12b5cd5f52d6 100644
---
a/components/camel-resilience4j/src/main/java/org/apache/camel/component/resilience4j/ResilienceProcessor.java
+++
b/components/camel-resilience4j/src/main/java/org/apache/camel/component/resilience4j/ResilienceProcessor.java
@@ -28,6 +28,7 @@ import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@@ -639,7 +640,11 @@ public class ResilienceProcessor extends
BaseProcessorSupport
ExchangeWriteGuard exchangeWriteGuard = new ExchangeWriteGuard();
task.exchangeWriteGuard = exchangeWriteGuard;
fallbackTask.exchangeWriteGuard = exchangeWriteGuard;
- final CircuitBreakerTask ftask = task; // annoying final java
thingy!
+ final CircuitBreakerTask ctask = task; // annoying final java
thingy!
+ // with a bulkhead, the call claims its start, so that a call that
timed out before it started is not
+ // started later (without a bulkhead, the time limiter cancels the
future of the call itself)
+ final CallStart callStart = timeLimiter != null && bulkhead !=
null ? new CallStart() : null;
+ final Supplier<Exchange> ftask = callStart != null ?
callStart.claiming(ctask) : ctask;
Callable<Exchange> callable;
if (timeLimiter != null) {
@@ -647,7 +652,10 @@ public class ResilienceProcessor extends
BaseProcessorSupport
if (bulkhead != null) {
// the bulkhead goes inside the time limiter, so the
permit is held until the task is done,
// and not released when the timeout fires while the task
is still running
- stage = Bulkhead.decorateCompletionStage(bulkhead, stage);
+ stage = Bulkhead.decorateCompletionStage(bulkhead,
callStart.submitting(stage));
+ // on timeout the time limiter cancels the future of the
bulkhead, and not the one of the call:
+ // pass the cancel on to a call that has not started yet
+ stage = cancelOnCancel(exchange, stage, callStart);
}
final Supplier<CompletionStage<Exchange>> fstage = stage;
Supplier<CompletableFuture<Exchange>> futureSupplier = () ->
fstage.get().toCompletableFuture();
@@ -703,12 +711,19 @@ public class ResilienceProcessor extends
BaseProcessorSupport
// build the CompletionStage supplier for the main task
Supplier<CompletionStage<Exchange>> supplier;
+ final CallStart callStart = timeLimiter != null ? new CallStart()
: null;
if (timeLimiter != null) {
// with timeout: submit work to executor so the supplier
returns immediately
// and the TimeLimiter can schedule the timeout check
supplier = () -> {
- CompletableFuture<Exchange> future = new
CompletableFuture<>();
- executorService.submit(() -> processTaskAsync(exchange,
exchangeWriteGuard, future));
+ CompletableFuture<Exchange> future =
callStart.submitted(new CompletableFuture<>());
+ executorService.submit(() -> {
+ // a call that timed out before it started is not
started: callStart.cancel() claimed it on the
+ // timeout
+ if (callStart.tryStart()) {
+ processTaskAsync(exchange, exchangeWriteGuard,
future);
+ }
+ });
return future;
};
} else {
@@ -726,6 +741,11 @@ public class ResilienceProcessor extends
BaseProcessorSupport
ScheduledExecutorService scheduler
= scheduledExecutorService != null ?
scheduledExecutorService : timeoutScheduler;
supplier = TimeLimiter.decorateCompletionStage(timeLimiter,
scheduler, supplier);
+ if
(timeLimiter.getTimeLimiterConfig().shouldCancelRunningFuture()) {
+ // the timeout completes the future, and nothing cancels
the call: cancel a call that has not
+ // started yet, as the time limiter does in synchronous
mode
+ supplier = cancelOnTimeout(exchange, supplier, callStart);
+ }
}
supplier = CircuitBreaker.decorateCompletionStage(circuitBreaker,
supplier);
@@ -936,6 +956,97 @@ public class ResilienceProcessor extends
BaseProcessorSupport
return future;
}
+ /**
+ * Asynchronous mode: cancels the call when the time limiter completes the
future with a timeout.
+ */
+ private static Supplier<CompletionStage<Exchange>> cancelOnTimeout(
+ Exchange exchange, Supplier<CompletionStage<Exchange>> supplier,
CallStart callStart) {
+ return () -> supplier.get().whenComplete((result, throwable) -> {
+ Throwable cause = throwable instanceof CompletionException ?
throwable.getCause() : throwable;
+ if (cause instanceof TimeoutException) {
+ cancelCall(exchange, callStart);
+ }
+ });
+ }
+
+ /**
+ * Synchronous mode with a bulkhead: cancels the call when the time
limiter cancels the future of the bulkhead (it
+ * does so on timeout, when timeoutCancelRunningFuture is true).
+ */
+ private static Supplier<CompletionStage<Exchange>> cancelOnCancel(
+ Exchange exchange, Supplier<CompletionStage<Exchange>> supplier,
CallStart callStart) {
+ return () -> {
+ CompletableFuture<Exchange> future =
supplier.get().toCompletableFuture();
+ future.whenComplete((result, throwable) -> {
+ if (future.isCancelled()) {
+ cancelCall(exchange, callStart);
+ }
+ });
+ return future;
+ };
+ }
+
+ private static void cancelCall(Exchange exchange, CallStart callStart) {
+ if (callStart.cancel()) {
+ LOG.debug("Exchange: {} timed out before its call started: the
call is not started", exchange.getExchangeId());
+ }
+ }
+
+ /**
+ * The start of one call on the thread pool, when the caller may give up
on the call (on timeout) before a thread of
+ * the pool starts it. The thread that starts the call and the caller that
cancels it both claim the call, and only
+ * one of them gets it: a call that has started is not cancelled (nor
interrupted) and keeps its bulkhead permit
+ * until it is done, and a call that is cancelled is never started.
Cancelling completes the future of the call at
+ * once, which releases its bulkhead permit.
+ */
+ private static final class CallStart {
+ private final AtomicBoolean claimed = new AtomicBoolean();
+ private volatile CompletableFuture<Exchange> future;
+
+ /**
+ * Records the future of the call, which {@link #cancel()} completes.
+ */
+ CompletableFuture<Exchange> submitted(CompletableFuture<Exchange>
future) {
+ this.future = future;
+ return future;
+ }
+
+ Supplier<CompletionStage<Exchange>>
submitting(Supplier<CompletionStage<Exchange>> stage) {
+ return () -> submitted(stage.get().toCompletableFuture());
+ }
+
+ /**
+ * The task of the call, which runs only if it claims the call first
(else it returns null, to a future that is
+ * already cancelled).
+ */
+ Supplier<Exchange> claiming(Supplier<Exchange> task) {
+ return () -> tryStart() ? task.get() : null;
+ }
+
+ /**
+ * Claims the call for its start.
+ *
+ * @return true to start the call, false if it was cancelled
+ */
+ boolean tryStart() {
+ return claimed.compareAndSet(false, true);
+ }
+
+ /**
+ * Cancels the call if it has not started.
+ *
+ * @return true if the call was cancelled, false if it had started (or
was not submitted)
+ */
+ boolean cancel() {
+ CompletableFuture<Exchange> f = future;
+ if (f != null && claimed.compareAndSet(false, true)) {
+ f.cancel(false);
+ return true;
+ }
+ return false;
+ }
+ }
+
/**
* Makes the write-back of the task and the takeover by the caller (the
fallback, or the timeout exception) mutually
* exclusive, for one call. The task writes its result only if it claims
the exchange before the caller. The caller
diff --git
a/components/camel-resilience4j/src/test/java/org/apache/camel/component/resilience4j/ResilienceTimedOutQueuedCallTest.java
b/components/camel-resilience4j/src/test/java/org/apache/camel/component/resilience4j/ResilienceTimedOutQueuedCallTest.java
new file mode 100644
index 000000000000..d51aed83f6eb
--- /dev/null
+++
b/components/camel-resilience4j/src/test/java/org/apache/camel/component/resilience4j/ResilienceTimedOutQueuedCallTest.java
@@ -0,0 +1,186 @@
+/*
+ * 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.resilience4j;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import io.github.resilience4j.bulkhead.Bulkhead;
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.model.Resilience4jConfigurationDefinition;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+
+/**
+ * A call that times out while its task still waits for a thread of the pool
must not start later: its exchange has
+ * already gone on with the timeout (or the fallback). Each route runs its
calls on a pool of one thread, so a blocked
+ * call holds the only thread and the next call waits in the queue until it
times out.
+ */
+class ResilienceTimedOutQueuedCallTest extends CamelTestSupport {
+
+ private static final int BULKHEAD_LIMIT = 5;
+
+ private final CountDownLatch release = new CountDownLatch(1);
+ private final AtomicInteger backendStarts = new AtomicInteger();
+ private final ExecutorService syncPool =
Executors.newSingleThreadExecutor();
+ private final ScheduledExecutorService asyncPool =
Executors.newScheduledThreadPool(1);
+ private final Processor backend = exchange -> {
+ backendStarts.incrementAndGet();
+ if (exchange.getIn().getHeader("block", false, Boolean.class)) {
+ // a backend that does not answer, until the test releases it
+ release.await(10, TimeUnit.SECONDS);
+ }
+ exchange.getMessage().setBody("Bye");
+ };
+
+ @Override
+ protected CamelContext createCamelContext() throws Exception {
+ CamelContext ctx = super.createCamelContext();
+ ctx.getRegistry().bind("syncPool", syncPool);
+ ctx.getRegistry().bind("asyncPool", asyncPool);
+ return ctx;
+ }
+
+ @AfterEach
+ void releaseBlockedCalls() {
+ release.countDown();
+ syncPool.shutdownNow();
+ asyncPool.shutdownNow();
+ }
+
+ @Test
+ void testSyncQueuedTimedOutCallDoesNotStart() throws Exception {
+ assertQueuedTimedOutCall("direct:sync", "cbSync", syncPool, 1);
+ }
+
+ @Test
+ void testSyncBulkheadQueuedTimedOutCallDoesNotStart() throws Exception {
+ assertQueuedTimedOutCall("direct:syncBulkhead", "cbSyncBulkhead",
syncPool, 1);
+ }
+
+ @Test
+ void testAsyncQueuedTimedOutCallDoesNotStart() throws Exception {
+ assertQueuedTimedOutCall("direct:async", "cbAsync", asyncPool, 1);
+ }
+
+ @Test
+ void testAsyncBulkheadQueuedTimedOutCallDoesNotStart() throws Exception {
+ assertQueuedTimedOutCall("direct:asyncBulkhead", "cbAsyncBulkhead",
asyncPool, 1);
+ }
+
+ @Test
+ void testAsyncQueuedTimedOutCallStartsWithoutCancelRunningFuture() throws
Exception {
+ // timeoutCancelRunningFuture=false: the call is not cancelled, and
starts once a thread is free
+ assertQueuedTimedOutCall("direct:asyncNoCancel", "cbAsyncNoCancel",
asyncPool, 2);
+ }
+
+ private void assertQueuedTimedOutCall(String uri, String id,
ExecutorService pool, int expectedStarts)
+ throws Exception {
+ Bulkhead bulkhead = bulkhead(id);
+ // the thread of the pool is started and idle before X1, so X1 starts
well within its timeout (a call that
+ // has not started when it times out is not started at all)
+ pool.submit(() -> {
+ }).get(20, TimeUnit.SECONDS);
+
+ // X1 blocks the only thread of the pool, times out and keeps running
+ Future<Exchange> x1 = template.asyncSend(uri, e ->
e.getIn().setHeader("block", true));
+ await().atMost(20, TimeUnit.SECONDS).until(() -> backendStarts.get()
== 1);
+ assertInstanceOf(TimeoutException.class, x1.get(20,
TimeUnit.SECONDS).getException(), "X1 times out");
+
+ // X2 waits in the queue of the pool and times out before it starts
+ Exchange x2 = template.send(uri, e -> e.getIn().setBody("X2"));
+ assertInstanceOf(TimeoutException.class, x2.getException(), "X2 times
out");
+ assertEquals(1, backendStarts.get(), "X2 has not started when its
exchange completes");
+ // the permit of X1 is held while it runs; the one of X2 is released
when X2 is cancelled. This is read on
+ // purpose now, after X2 timed out and before X1 ends: had X2 kept its
permit, one fewer would be available
+ int availableWhileX1Runs = bulkhead != null ?
bulkhead.getMetrics().getAvailableConcurrentCalls() : -1;
+
+ // X1 ends, and the thread takes what is queued behind it: the task of
X2, then this one
+ release.countDown();
+ pool.submit(() -> {
+ }).get(20, TimeUnit.SECONDS);
+
+ assertEquals(expectedStarts, backendStarts.get(), "calls that reached
the backend");
+ if (bulkhead != null) {
+ assertEquals(BULKHEAD_LIMIT - 1, availableWhileX1Runs, "bulkhead
permits while X1 runs");
+ assertEquals(BULKHEAD_LIMIT,
bulkhead.getMetrics().getAvailableConcurrentCalls(), "bulkhead permits at the
end");
+ }
+ }
+
+ private Bulkhead bulkhead(String id) {
+ ResilienceProcessor processor = context.getProcessor(id,
ResilienceProcessor.class);
+ return processor.isBulkheadEnabled() ?
processor.getBulkheadRegistry().bulkhead(id) : null;
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("direct:sync").circuitBreaker().id("cbSync")
+
.resilience4jConfiguration().timeoutEnabled(true).timeoutDuration("200")
+ .timeoutExecutorService("syncPool").end()
+ .process(backend)
+ .end();
+
+
from("direct:syncBulkhead").circuitBreaker().id("cbSyncBulkhead")
+
.resilience4jConfiguration().timeoutEnabled(true).timeoutDuration("200")
+ .timeoutExecutorService("syncPool")
+
.bulkheadEnabled(true).bulkheadMaxConcurrentCalls(BULKHEAD_LIMIT).end()
+ .process(backend)
+ .end();
+
+ from("direct:async").circuitBreaker().id("cbAsync")
+
.resilience4jConfiguration().asynchronous(true).timeoutEnabled(true).timeoutDuration("200")
+ .timeoutExecutorService("asyncPool").end()
+ .process(backend)
+ .end();
+
+
from("direct:asyncBulkhead").circuitBreaker().id("cbAsyncBulkhead")
+
.resilience4jConfiguration().asynchronous(true).timeoutEnabled(true).timeoutDuration("200")
+ .timeoutExecutorService("asyncPool")
+
.bulkheadEnabled(true).bulkheadMaxConcurrentCalls(BULKHEAD_LIMIT).end()
+ .process(backend)
+ .end();
+
+ Resilience4jConfigurationDefinition noCancel =
from("direct:asyncNoCancel").circuitBreaker()
+ .id("cbAsyncNoCancel")
+
.resilience4jConfiguration().asynchronous(true).timeoutEnabled(true).timeoutDuration("200")
+ .timeoutExecutorService("asyncPool");
+ noCancel.setTimeoutCancelRunningFuture("false");
+ noCancel.end()
+ .process(backend)
+ .end();
+
+ }
+ };
+ }
+}
diff --git
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index 3b5a91c094ba..5620c4ce877d 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -436,6 +436,16 @@ restart is gone. A class that extends `SedaConsumer` and
overrides `doRun()` mus
instead, and should keep the loop condition `isCurrentStart(start) &&
isRunAllowed()` of the default implementation.
The new protected method `isCurrentStart(int start)` returns true while no
later start of the consumer has happened.
+=== camel-resilience4j - a call that times out before it starts is not started
later
+
+In asynchronous mode (`asynchronous=true`) with a timeout, the
`timeoutCancelRunningFuture` option (`true` by default)
+now has an effect, where before it had none. A call that times out while its
task still waits for a thread of the
+timeout executor service is no longer started once a thread is free, so it no
longer reaches the backend after its
+exchange has gone on with the timeout (or the fallback). With a bulkhead, the
permit of such a call is released at the
+timeout, and not when a thread takes the call. In synchronous mode with a
bulkhead, a call that times out while it waits
+for a thread is not started later either. Set
`timeoutCancelRunningFuture=false` to keep the old asynchronous behaviour,
+where the timed out call still runs once a thread is free.
+
=== camel-ehcache - shared CacheManager and changed defaults
The following user-visible changes take effect in 4.24: