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 b327ed33766c CAMEL-27437: camel-core - Route policies resume the
consumer only when no other policy keeps it suspended (#30835)
b327ed33766c is described below
commit b327ed33766c931d6fb3dc89dc0e6fe03ae08a76
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 14:40:53 2026 +0530
CAMEL-27437: camel-core - Route policies resume the consumer only when no
other policy keeps it suspended (#30835)
With ThrottlingInflightRoutePolicy and ThrottlingExceptionRoutePolicy on the
same route, each policy resumed the consumer on its own. The inflight policy
suspends the consumer when too many exchanges are in flight; the circuit
opens meanwhile (the suspend does nothing, the consumer is suspended
already); then the exchanges in flight complete and the inflight policy
resumed the consumer, as it only checks its own set of suspended consumers
(CAMEL-25018) and the route status. The consumer took new messages while
the circuit was open, and sent them to the failing downstream. The other
way round, half opening (or closing) the circuit resumed a consumer that
the inflight policy still kept suspended. Both orders of the policies.
This generalises the CAMEL-25018 approach, where a policy only resumes a
consumer it suspended, to the policies of a route. RoutePolicySupport has a
new protected hook, isConsumerKeptSuspended(Route), and
isConsumerKeptSuspendedByAnotherPolicy(Route), which asks the other
RoutePolicySupport policies of the route:
- ThrottlingInflightRoutePolicy keeps the consumer suspended while it is in
its set. When it would resume the consumer, it removes it from its set
first, and then does not resume it if another policy keeps it suspended.
If the resume throws, the consumer is put back in its set, as before.
- ThrottlingExceptionRoutePolicy keeps the consumer suspended while the
circuit is open. When it half opens or closes the open circuit, it lets go
first (a volatile flag, under its lock), and then does not resume the
consumer if another policy keeps it suspended. The state changes as
before, after the resume; if the resume throws, the circuit stays open and
keeps the consumer suspended again.
A policy lets go before it checks the other one, so when both let go at the
same time, at least one of them resumes the consumer. The exception policy
reads its flag before its state for that: the other way round it could see
the circuit still open and then the flag already cleared, and neither
policy would resume the consumer. The policy that is
left resumes the consumer when it lets go: the inflight policy on a later
completion, the exception policy when the circuit is half opened.
Docs: route-policy.adoc and the 4.24 upgrade guide.
* CAMEL-27437: camel-core - review follow-up: the exception policy keeps
suspended only the consumers it suspended
ThrottlingExceptionRoutePolicy claimed every consumer while its circuit
was open, whatever the route. With one policy on several routes, the
inflight policy of another route then kept its consumer suspended, and
the half open check (scheduled for the route that opened the circuit)
never resumed it. The same after a CamelContext restart or a route
removed and added again: the circuit stays open with no half open check,
and the started consumer was kept suspended for good once the inflight
policy suspended it.
The policy now remembers the consumer it suspended (or found suspended)
when it opened the circuit, one per route, and claims only those. The
set is cleared when the circuit is half opened or closed and when the
policy stops; a route drops its consumer when it is started or removed.
The flag is still the first read of the claim, the consumer is added
before the state becomes open.
Tests: one exception policy on two routes, each with its own inflight
policy (route B is resumed by its inflight policy while A's circuit is
open), and a CamelContext restart with the circuit still open.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
...ottlingInflightAndExceptionRoutePolicyTest.java | 404 +++++++++++++++++++++
.../apache/camel/support/RoutePolicySupport.java | 37 ++
.../throttling/ThrottlingExceptionRoutePolicy.java | 75 +++-
.../throttling/ThrottlingInflightRoutePolicy.java | 22 +-
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 11 +
.../modules/ROOT/pages/route-policy.adoc | 8 +
6 files changed, 550 insertions(+), 7 deletions(-)
diff --git
a/core/camel-core/src/test/java/org/apache/camel/processor/throttle/ThrottlingInflightAndExceptionRoutePolicyTest.java
b/core/camel-core/src/test/java/org/apache/camel/processor/throttle/ThrottlingInflightAndExceptionRoutePolicyTest.java
new file mode 100644
index 000000000000..e041257c5768
--- /dev/null
+++
b/core/camel-core/src/test/java/org/apache/camel/processor/throttle/ThrottlingInflightAndExceptionRoutePolicyTest.java
@@ -0,0 +1,404 @@
+/*
+ * 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.processor.throttle;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.Consumer;
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Exchange;
+import org.apache.camel.ProducerTemplate;
+import org.apache.camel.Route;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.support.service.ServiceSupport;
+import org.apache.camel.throttling.ThrottlingExceptionRoutePolicy;
+import org.apache.camel.throttling.ThrottlingInflightRoutePolicy;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A route with both {@link ThrottlingInflightRoutePolicy} and {@link
ThrottlingExceptionRoutePolicy}, in both orders:
+ * each policy resumes the consumer only when the other one no longer keeps it
suspended.
+ * <p>
+ * Four exchanges are in flight at the same time (four concurrent consumers,
at most one inflight exchange), and the
+ * test decides the order in which they complete. The half open check of the
circuit is run by the test, not by a timer.
+ * <p>
+ * The exception policy keeps suspended only the consumer it suspended when it
opened the circuit: not the consumer of
+ * another route that uses the same policy, and not a consumer started again
while the circuit is still open.
+ */
+class ThrottlingInflightAndExceptionRoutePolicyTest extends ContextTestSupport
{
+
+ private final Map<String, CountDownLatch> gates = new
ConcurrentHashMap<>();
+ private final AtomicInteger entered = new AtomicInteger();
+ private final Map<String, CountingInflightPolicy> inflightPolicies = new
ConcurrentHashMap<>();
+ private final Map<String, ManualHalfOpenPolicy> breakers = new
ConcurrentHashMap<>();
+
+ @ParameterizedTest
+ @ValueSource(strings = { "inflightFirst", "exceptionFirst" })
+ void inflightPolicyDoesNotResumeTheConsumerWhileTheCircuitIsOpen(String
routeId) throws Exception {
+ Route route = context.getRoute(routeId);
+ ServiceSupport consumer = (ServiceSupport) route.getConsumer();
+ ManualHalfOpenPolicy breaker = breakers.get(routeId);
+
+ startFourExchanges(routeId);
+
+ // A fails with 3 still in flight (more than 1): the inflight policy
suspends the consumer
+ complete(routeId, "A", 1);
+ assertTrue(consumer.isSuspended());
+ assertEquals("closed", breaker.getStateAsString());
+
+ // B fails, the second failure: the circuit opens (the consumer is
suspended already)
+ complete(routeId, "B", 2);
+ assertEquals("opened", breaker.getStateAsString());
+ assertTrue(consumer.isSuspended());
+
+ // C succeeds with 1 in flight: the inflight policy would resume the
consumer, but the circuit is open
+ complete(routeId, "C", 3);
+ assertEquals("opened", breaker.getStateAsString());
+ assertTrue(consumer.isSuspended(), "the consumer must stay suspended
while the circuit is open");
+
+ complete(routeId, "D", 4);
+ assertTrue(consumer.isSuspended());
+
+ // the half open check resumes the consumer, as no other policy keeps
it suspended
+ breaker.halfOpen(route);
+ assertEquals("half opened", breaker.getStateAsString());
+ assertTrue(consumer.isStarted());
+
+ // the next exchange succeeds and closes the circuit
+ gate("E").countDown();
+ template.sendBody("seda:" + routeId, "E");
+ awaitDone(routeId, 5);
+ assertEquals("closed", breaker.getStateAsString());
+ assertTrue(consumer.isStarted());
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = { "inflightFirst", "exceptionFirst" })
+ void
halfOpenCheckDoesNotResumeTheConsumerTheInflightPolicySuspended(String routeId)
throws Exception {
+ Route route = context.getRoute(routeId);
+ ServiceSupport consumer = (ServiceSupport) route.getConsumer();
+ ManualHalfOpenPolicy breaker = breakers.get(routeId);
+
+ startFourExchanges(routeId);
+
+ complete(routeId, "A", 1);
+ complete(routeId, "B", 2);
+ assertEquals("opened", breaker.getStateAsString());
+ assertTrue(consumer.isSuspended());
+
+ // half open with 2 still in flight (more than 1): the inflight policy
still keeps the consumer suspended
+ breaker.halfOpen(route);
+ assertEquals("half opened", breaker.getStateAsString());
+ assertTrue(consumer.isSuspended(), "the consumer must stay suspended
while the inflight policy keeps it suspended");
+
+ // C succeeds with 1 in flight: the inflight policy resumes the
consumer, and the success closes the circuit
+ complete(routeId, "C", 3);
+ assertTrue(consumer.isStarted());
+ assertEquals("closed", breaker.getStateAsString());
+
+ complete(routeId, "D", 4);
+ assertTrue(consumer.isStarted());
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = { "inflightFirst", "exceptionFirst" })
+ void
closingTheOpenCircuitDoesNotResumeTheConsumerTheInflightPolicySuspended(String
routeId) throws Exception {
+ Route route = context.getRoute(routeId);
+ ServiceSupport consumer = (ServiceSupport) route.getConsumer();
+ ManualHalfOpenPolicy breaker = breakers.get(routeId);
+
+ startFourExchanges(routeId);
+
+ complete(routeId, "A", 1);
+ complete(routeId, "B", 2);
+ assertEquals("opened", breaker.getStateAsString());
+
+ // closing the open circuit (as with a halfOpenHandler that is ready)
with 2 still in flight: the inflight
+ // policy still keeps the consumer suspended
+ breaker.close(route);
+ assertEquals("closed", breaker.getStateAsString());
+ assertTrue(consumer.isSuspended(), "the consumer must stay suspended
while the inflight policy keeps it suspended");
+
+ // C succeeds with 1 in flight: the inflight policy resumes the
consumer
+ complete(routeId, "C", 3);
+ assertTrue(consumer.isStarted());
+
+ complete(routeId, "D", 4);
+ assertTrue(consumer.isStarted());
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = { "inflightFirst", "exceptionFirst" })
+ void circuitStaysOpenWhenTheResumeOfTheHalfOpenCheckFails(String routeId)
throws Exception {
+ Route route = context.getRoute(routeId);
+ ServiceSupport consumer = (ServiceSupport) route.getConsumer();
+ ManualHalfOpenPolicy breaker = breakers.get(routeId);
+
+ startFourExchanges(routeId);
+ complete(routeId, "A", 1);
+ complete(routeId, "B", 2);
+ complete(routeId, "C", 3);
+ complete(routeId, "D", 4);
+ assertEquals("opened", breaker.getStateAsString());
+
+ // the policy lets go of the consumer before it resumes it: if the
resume fails, the circuit stays open
+ breaker.failResume = true;
+ breaker.halfOpen(route);
+ assertEquals("opened", breaker.getStateAsString());
+ assertTrue(consumer.isSuspended());
+
+ breaker.failResume = false;
+ breaker.halfOpen(route);
+ assertEquals("half opened", breaker.getStateAsString());
+ assertTrue(consumer.isStarted());
+ }
+
+ @Test
+ void sharedExceptionPolicyKeepsSuspendedOnlyTheConsumerItSuspended() {
+ Route routeA = context.getRoute("sharedA");
+ ServiceSupport consumerA = (ServiceSupport) routeA.getConsumer();
+ ServiceSupport consumerB = (ServiceSupport)
context.getRoute("sharedB").getConsumer();
+ ManualHalfOpenPolicy shared = breakers.get("sharedA");
+
+ // B1 succeeds with 3 still in flight on route B: the inflight policy
of route B suspends its consumer
+ startExchanges("sharedB", 4, "B1", "B2", "B3", "B4");
+ gate("B1").countDown();
+ awaitSharedDone("sharedB", 1, 1);
+ assertTrue(consumerB.isSuspended());
+ assertEquals("closed", shared.getStateAsString());
+
+ // two failures on route A open the circuit of the shared policy,
which suspends the consumer of route A
+ gate("A1").countDown();
+ template.sendBody("seda:sharedA", "A1");
+ awaitSharedDone("sharedA", 1, 2);
+ gate("A2").countDown();
+ template.sendBody("seda:sharedA", "A2");
+ awaitSharedDone("sharedA", 2, 3);
+ assertEquals("opened", shared.getStateAsString());
+ assertTrue(consumerA.isSuspended());
+
+ // the exchanges of route B complete while the circuit is open: the
inflight policy of route B resumes its
+ // consumer, as the circuit was not opened for it (the half open check
resumes only the consumer of route A)
+ gate("B2").countDown();
+ gate("B3").countDown();
+ gate("B4").countDown();
+ awaitSharedDone("sharedB", 4, 6);
+ assertEquals("opened", shared.getStateAsString());
+ assertTrue(consumerB.isStarted(), "the consumer of route B must be
resumed by its inflight policy");
+ assertTrue(consumerA.isSuspended());
+
+ shared.halfOpen(routeA);
+ assertEquals("half opened", shared.getStateAsString());
+ assertTrue(consumerA.isStarted());
+ }
+
+ @Test
+ void
consumerStartedAgainWhileTheCircuitIsOpenIsResumedByTheInflightPolicy() throws
Exception {
+ String routeId = "inflightFirst";
+ ManualHalfOpenPolicy breaker = breakers.get(routeId);
+
+ startExchanges(routeId, 4, "A", "B", "C", "D");
+ complete(routeId, "A", 1);
+ complete(routeId, "B", 2);
+ complete(routeId, "C", 3);
+ complete(routeId, "D", 4);
+ assertEquals("opened", breaker.getStateAsString());
+ assertTrue(((ServiceSupport)
context.getRoute(routeId).getConsumer()).isSuspended());
+
+ // the circuit stays open when the CamelContext is stopped and started
again, and the routes start their
+ // consumers, but no half open check is scheduled then
+ context.stop();
+ context.start();
+ ServiceSupport consumer = (ServiceSupport)
context.getRoute(routeId).getConsumer();
+ assertTrue(consumer.isStarted());
+ assertEquals("opened", breaker.getStateAsString());
+
+ // F fails with 3 still in flight: the inflight policy suspends the
consumer (a new template, as the one of the
+ // test was stopped with the CamelContext)
+ try (ProducerTemplate producer = context.createProducerTemplate()) {
+ startExchanges(producer, routeId, 8, "F", "G", "H", "I");
+ }
+ complete(routeId, "F", 5);
+ assertTrue(consumer.isSuspended());
+
+ // the inflight policy resumes the consumer when the others are done,
as the open circuit did not suspend it
+ complete(routeId, "G", 6);
+ complete(routeId, "H", 7);
+ complete(routeId, "I", 8);
+ assertEquals("opened", breaker.getStateAsString());
+ assertTrue(consumer.isStarted(), "the consumer must be resumed by the
inflight policy");
+ }
+
+ private void startFourExchanges(String routeId) {
+ startExchanges(routeId, 4, "A", "B", "C", "D");
+ }
+
+ private void startExchanges(String routeId, int totalEntered, String...
bodies) {
+ startExchanges(template, routeId, totalEntered, bodies);
+ }
+
+ private void startExchanges(ProducerTemplate producer, String routeId, int
totalEntered, String... bodies) {
+ for (String body : bodies) {
+ gate(body);
+ producer.sendBody("seda:" + routeId, body);
+ }
+ await().atMost(10, TimeUnit.SECONDS).until(() -> entered.get() ==
totalEntered);
+ }
+
+ // waits until the inflight policy of the route and the shared exception
policy (of both routes) are done
+ private void awaitSharedDone(String routeId, int inflightDone, int
sharedDone) {
+ await().atMost(10, TimeUnit.SECONDS)
+ .until(() -> inflightPolicies.get(routeId).done.get() ==
inflightDone
+ && breakers.get(routeId).done.get() == sharedDone);
+ }
+
+ // lets the exchange complete, and waits until both policies are done with
it
+ private void complete(String routeId, String body, int done) {
+ gate(body).countDown();
+ awaitDone(routeId, done);
+ }
+
+ private void awaitDone(String routeId, int done) {
+ await().atMost(10, TimeUnit.SECONDS)
+ .until(() -> inflightPolicies.get(routeId).done.get() == done
&& breakers.get(routeId).done.get() == done);
+ }
+
+ private CountDownLatch gate(String body) {
+ return gates.computeIfAbsent(body, b -> new CountDownLatch(1));
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ CountingInflightPolicy inflight1 = new
CountingInflightPolicy();
+ ManualHalfOpenPolicy breaker1 = new ManualHalfOpenPolicy();
+ inflightPolicies.put("inflightFirst", inflight1);
+ breakers.put("inflightFirst", breaker1);
+
from("seda:inflightFirst?concurrentConsumers=4").routeId("inflightFirst")
+ .routePolicy(inflight1, breaker1)
+ .process(e -> route(e));
+
+ CountingInflightPolicy inflight2 = new
CountingInflightPolicy();
+ ManualHalfOpenPolicy breaker2 = new ManualHalfOpenPolicy();
+ inflightPolicies.put("exceptionFirst", inflight2);
+ breakers.put("exceptionFirst", breaker2);
+
from("seda:exceptionFirst?concurrentConsumers=4").routeId("exceptionFirst")
+ .routePolicy(breaker2, inflight2)
+ .process(e -> route(e));
+
+ // one exception policy on two routes, each with its own
inflight policy
+ ManualHalfOpenPolicy shared = new ManualHalfOpenPolicy();
+ CountingInflightPolicy inflightA = new
CountingInflightPolicy();
+ CountingInflightPolicy inflightB = new
CountingInflightPolicy();
+ inflightPolicies.put("sharedA", inflightA);
+ inflightPolicies.put("sharedB", inflightB);
+ breakers.put("sharedA", shared);
+ breakers.put("sharedB", shared);
+ from("seda:sharedA?concurrentConsumers=4").routeId("sharedA")
+ .routePolicy(inflightA, shared)
+ .process(e -> sharedRoute(e));
+ from("seda:sharedB?concurrentConsumers=4").routeId("sharedB")
+ .routePolicy(shared, inflightB)
+ .process(e -> sharedRoute(e));
+ }
+ };
+ }
+
+ private void route(Exchange exchange) throws Exception {
+ String body = exchange.getMessage().getBody(String.class);
+ entered.incrementAndGet();
+ assertTrue(gate(body).await(20, TimeUnit.SECONDS));
+ // the downstream fails, except for C and E
+ if (!"C".equals(body) && !"E".equals(body)) {
+ throw new IllegalStateException("Downstream failure: " + body);
+ }
+ }
+
+ private void sharedRoute(Exchange exchange) throws Exception {
+ String body = exchange.getMessage().getBody(String.class);
+ entered.incrementAndGet();
+ assertTrue(gate(body).await(20, TimeUnit.SECONDS));
+ // the downstream of route A fails
+ if (body.startsWith("A")) {
+ throw new IllegalStateException("Downstream failure: " + body);
+ }
+ }
+
+ private static class CountingInflightPolicy extends
ThrottlingInflightRoutePolicy {
+ private final AtomicInteger done = new AtomicInteger();
+
+ CountingInflightPolicy() {
+ setMaxInflightExchanges(1);
+ setResumePercentOfMax(70);
+ }
+
+ @Override
+ public void onExchangeDone(Route route, Exchange exchange) {
+ super.onExchangeDone(route, exchange);
+ done.incrementAndGet();
+ }
+ }
+
+ // opens the circuit on the second failure; the half open check runs only
when the test calls halfOpen
+ private static class ManualHalfOpenPolicy extends
ThrottlingExceptionRoutePolicy {
+ private final AtomicInteger done = new AtomicInteger();
+ private volatile boolean failResume;
+
+ ManualHalfOpenPolicy() {
+ super(2, 60000, 60000, null);
+ }
+
+ @Override
+ public void onExchangeDone(Route route, Exchange exchange) {
+ super.onExchangeDone(route, exchange);
+ done.incrementAndGet();
+ }
+
+ @Override
+ protected void addHalfOpenTimer(Route route, long delay) {
+ // no timer: the test runs the half open check
+ }
+
+ @Override
+ public boolean resumeOrStartConsumer(Consumer consumer) throws
Exception {
+ if (failResume) {
+ throw new IllegalStateException("Cannot resume the consumer");
+ }
+ return super.resumeOrStartConsumer(consumer);
+ }
+
+ void halfOpen(Route route) {
+ halfOpenCircuit(route);
+ }
+
+ void close(Route route) {
+ closeCircuit(route);
+ }
+ }
+}
diff --git
a/core/camel-support/src/main/java/org/apache/camel/support/RoutePolicySupport.java
b/core/camel-support/src/main/java/org/apache/camel/support/RoutePolicySupport.java
index 68d06a621bcf..a28ae7c4cf75 100644
---
a/core/camel-support/src/main/java/org/apache/camel/support/RoutePolicySupport.java
+++
b/core/camel-support/src/main/java/org/apache/camel/support/RoutePolicySupport.java
@@ -144,6 +144,43 @@ public abstract class RoutePolicySupport extends
ServiceSupport implements Route
&& !status.isStopped();
}
+ /**
+ * Whether this policy keeps the consumer of the route suspended (or
stopped), because it has suspended the consumer
+ * itself and still wants it suspended (for example while a circuit
breaker is open).
+ * <p>
+ * Another policy of the same route does not resume or start the consumer
while this returns <code>true</code>, see
+ * {@link #isConsumerKeptSuspendedByAnotherPolicy(Route)}. This policy
then resumes the consumer when it lets go of
+ * it. A policy that lets go of the consumer must make this return
<code>false</code> before it checks the other
+ * policies, so that when two policies let go at the same time, at least
one of them resumes the consumer. When the
+ * answer depends on more than one field, read the one that marks letting
go first, so that a let go that happens
+ * between the reads is not missed.
+ * <p>
+ * Returns <code>false</code> by default.
+ *
+ * @param route the route
+ * @return <code>true</code> if this policy keeps the consumer of
the route suspended
+ */
+ protected boolean isConsumerKeptSuspended(Route route) {
+ return false;
+ }
+
+ /**
+ * Whether another policy of the route keeps the consumer of the route
suspended (or stopped), and so this policy
+ * must not resume or start it.
+ *
+ * @param route the route
+ * @return <code>true</code> if another {@link RoutePolicySupport}
of the route keeps the consumer suspended
+ * @see #isConsumerKeptSuspended(Route)
+ */
+ protected boolean isConsumerKeptSuspendedByAnotherPolicy(Route route) {
+ for (RoutePolicy policy : route.getRoutePolicyList()) {
+ if (policy != this && policy instanceof RoutePolicySupport other
&& other.isConsumerKeptSuspended(route)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
public void startRoute(Route route) throws Exception {
controller(route).startRoute(route.getId());
}
diff --git
a/core/camel-support/src/main/java/org/apache/camel/throttling/ThrottlingExceptionRoutePolicy.java
b/core/camel-support/src/main/java/org/apache/camel/throttling/ThrottlingExceptionRoutePolicy.java
index e8b77db388aa..7ef46bf7bf10 100644
---
a/core/camel-support/src/main/java/org/apache/camel/throttling/ThrottlingExceptionRoutePolicy.java
+++
b/core/camel-support/src/main/java/org/apache/camel/throttling/ThrottlingExceptionRoutePolicy.java
@@ -22,6 +22,7 @@ import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@@ -32,6 +33,7 @@ import java.util.concurrent.locks.ReentrantLock;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelContextAware;
+import org.apache.camel.Consumer;
import org.apache.camel.Exchange;
import org.apache.camel.LoggingLevel;
import org.apache.camel.Route;
@@ -118,6 +120,12 @@ public class ThrottlingExceptionRoutePolicy extends
RoutePolicySupport implement
private boolean halfOpenStopped;
private volatile long lastFailure;
private volatile long openedAt;
+ // set while the open circuit is half opened or closed (under lock), as
this policy then lets go of the consumer
+ private volatile boolean releasingConsumer;
+ // the consumers this policy suspended (or found suspended) when it opened
the circuit, and so keeps suspended while
+ // the circuit is open: one per route that opened it, as one policy can be
used by several routes. Written under
+ // lock, cleared when the circuit is half opened or closed, and read
without the lock by the other policies
+ private final Set<Consumer> openedConsumers =
ConcurrentHashMap.newKeySet();
// the times of the most recent failures (at most failureThreshold of
them), oldest first, guarded by failureLock
// (not by lock, which is held while the consumer is suspended or resumed)
private final Lock failureLock = new ReentrantLock();
@@ -209,6 +217,8 @@ public class ThrottlingExceptionRoutePolicy extends
RoutePolicySupport implement
// also here, not only in onInit, so that a started route is always
tracked (a CamelContext that is stopped
// calls onRemove for each route; when started again it creates the
routes again and calls onInit too)
addRoute(route);
+ // the route controller has started the consumer, so this policy no
longer keeps it suspended
+ releaseOpenedConsumer(route);
// if keepOpen then start w/ the circuit open
if (keepOpenBool.get()) {
// the circuit may still be open from before the route was
stopped, and then the started consumer must
@@ -220,6 +230,8 @@ public class ThrottlingExceptionRoutePolicy extends
RoutePolicySupport implement
@Override
public void onRemove(Route route) {
// the policy is a service of the CamelContext, which does not stop it
when its routes are removed
+ // no half open check resumes the consumer of a removed route
+ releaseOpenedConsumer(route);
schedulerLock.lock();
try {
routeIds.remove(route.getRouteId());
@@ -239,6 +251,15 @@ public class ThrottlingExceptionRoutePolicy extends
RoutePolicySupport implement
@Override
protected void doStop() throws Exception {
shutdownHalfOpenScheduler();
+ // no half open check resumes them now
+ openedConsumers.clear();
+ }
+
+ private void releaseOpenedConsumer(Route route) {
+ Consumer consumer = route.getConsumer();
+ if (consumer != null) {
+ openedConsumers.remove(consumer);
+ }
}
private void addRoute(Route route) {
@@ -476,13 +497,31 @@ public class ThrottlingExceptionRoutePolicy extends
RoutePolicySupport implement
return output;
}
+ /**
+ * While the circuit is open, this policy keeps the consumer suspended
that it suspended when it opened the circuit:
+ * another policy of the route, such as {@link
ThrottlingInflightRoutePolicy}, does not resume it then. The consumer
+ * of another route that uses this policy too, or a consumer that the
route controller has started since, is not
+ * kept suspended, as the half open check does not resume it.
+ */
+ @Override
+ protected boolean isConsumerKeptSuspended(Route route) {
+ // releasingConsumer is read before the state: while it is set, the
state changes from open to half open or
+ // closed. Reading the state first could see it still open, and then
the flag already cleared, so a policy that
+ // let go of the consumer at the same time would not resume it either
+ if (releasingConsumer || state.get() != STATE_OPEN) {
+ return false;
+ }
+ Consumer consumer = route.getConsumer();
+ return consumer != null && openedConsumers.contains(consumer);
+ }
+
protected void openCircuit(Route route) {
try {
lock.lock();
if (state.get() == STATE_OPEN) {
return;
}
- suspendOrStopConsumer(route.getConsumer());
+ suspendConsumerOfOpenCircuit(route);
state.set(STATE_OPEN);
openedAt = TimeSource.currentTimeMillis();
this.addHalfOpenTimer(route);
@@ -502,7 +541,7 @@ public class ThrottlingExceptionRoutePolicy extends
RoutePolicySupport implement
protected void reopenCircuit(Route route) {
try {
lock.lock();
- suspendOrStopConsumer(route.getConsumer());
+ suspendConsumerOfOpenCircuit(route);
state.set(STATE_OPEN);
openedAt = TimeSource.currentTimeMillis();
this.addHalfOpenTimer(route);
@@ -514,6 +553,16 @@ public class ThrottlingExceptionRoutePolicy extends
RoutePolicySupport implement
}
}
+ private void suspendConsumerOfOpenCircuit(Route route) throws Exception {
+ Consumer consumer = route.getConsumer();
+ suspendOrStopConsumer(consumer);
+ // also when it was suspended already (such as by
ThrottlingInflightRoutePolicy): this policy now keeps it
+ // suspended too. Added before the state is set to open, so that the
open state is never seen without it
+ if (consumer != null) {
+ openedConsumers.add(consumer);
+ }
+ }
+
/**
* Schedules the check of the open circuit after {@link
#getHalfOpenAfter()} milliseconds, and cancels the check
* scheduled before, if any.
@@ -555,15 +604,23 @@ public class ThrottlingExceptionRoutePolicy extends
RoutePolicySupport implement
protected void halfOpenCircuit(Route route) {
try {
lock.lock();
- // do not resume the consumer if the route controller has
suspended or stopped the route in the meantime
- if (isResumeOrStartConsumerAllowed(route)) {
+ // this policy lets go of the consumer before it checks the other
policies of the route, so that when one of them
+ // lets go at the same time, at least one of the two resumes the
consumer (if resuming fails, the circuit
+ // stays open and keeps the consumer suspended again)
+ releasingConsumer = true;
+ // do not resume the consumer if the route controller has
suspended or stopped the route in the meantime,
+ // or if another policy (such as ThrottlingInflightRoutePolicy)
still keeps it suspended, as that policy
+ // resumes it when it lets go
+ if (isResumeOrStartConsumerAllowed(route) &&
!isConsumerKeptSuspendedByAnotherPolicy(route)) {
resumeOrStartConsumer(route.getConsumer());
}
state.set(STATE_HALF_OPEN);
+ openedConsumers.clear();
logState();
} catch (Exception e) {
handleException(e);
} finally {
+ releasingConsumer = false;
lock.unlock();
}
}
@@ -571,10 +628,14 @@ public class ThrottlingExceptionRoutePolicy extends
RoutePolicySupport implement
protected void closeCircuit(Route route) {
try {
lock.lock();
+ // this policy lets go of the consumer before it checks the other
policies of the route (as when half opening)
+ releasingConsumer = true;
// only resume the consumer when the circuit is open, as then this
policy has suspended the consumer
// (when half open the consumer has already been resumed, so if it
is suspended now, then by the route
- // controller), and not if the route controller has suspended or
stopped the route in the meantime
- if (state.get() == STATE_OPEN &&
isResumeOrStartConsumerAllowed(route)) {
+ // controller or another policy), and not if the route controller
has suspended or stopped the route in the
+ // meantime, or another policy still keeps it suspended
+ if (state.get() == STATE_OPEN &&
isResumeOrStartConsumerAllowed(route)
+ && !isConsumerKeptSuspendedByAnotherPolicy(route)) {
resumeOrStartConsumer(route.getConsumer());
}
failures.set(0);
@@ -583,10 +644,12 @@ public class ThrottlingExceptionRoutePolicy extends
RoutePolicySupport implement
lastFailure = 0;
openedAt = 0;
state.set(STATE_CLOSED);
+ openedConsumers.clear();
logState();
} catch (Exception e) {
handleException(e);
} finally {
+ releasingConsumer = false;
lock.unlock();
}
}
diff --git
a/core/camel-support/src/main/java/org/apache/camel/throttling/ThrottlingInflightRoutePolicy.java
b/core/camel-support/src/main/java/org/apache/camel/throttling/ThrottlingInflightRoutePolicy.java
index 0b13973ecd63..a2fe9b46fded 100644
---
a/core/camel-support/src/main/java/org/apache/camel/throttling/ThrottlingInflightRoutePolicy.java
+++
b/core/camel-support/src/main/java/org/apache/camel/throttling/ThrottlingInflightRoutePolicy.java
@@ -142,6 +142,12 @@ public class ThrottlingInflightRoutePolicy extends
RoutePolicySupport implements
routeControllerTookOver(route);
}
+ @Override
+ protected boolean isConsumerKeptSuspended(Route route) {
+ Consumer consumer = route.getConsumer();
+ return consumer != null && suspendedConsumers.contains(consumer);
+ }
+
private void routeControllerTookOver(Route route) {
// the route controller has started, stopped, suspended or resumed the
consumer, so it is no longer suspended by
// this policy
@@ -321,8 +327,22 @@ public class ThrottlingInflightRoutePolicy extends
RoutePolicySupport implements
if (!suspendedConsumers.contains(consumer) ||
!isResumeOrStartConsumerAllowed(route)) {
return;
}
- boolean started = resumeOrStartConsumer(consumer);
+ // this policy lets go of the consumer before it checks the other
policies of the route, so that when one of them
+ // lets go at the same time, at least one of the two resumes the
consumer
suspendedConsumers.remove(consumer);
+ if (isConsumerKeptSuspendedByAnotherPolicy(route)) {
+ // such as ThrottlingExceptionRoutePolicy with an open circuit:
that policy resumes the consumer
+ LOG.debug("Not resuming consumer: {} as another route policy keeps
it suspended", consumer);
+ return;
+ }
+ boolean started;
+ try {
+ started = resumeOrStartConsumer(consumer);
+ } catch (Exception e) {
+ // still suspended by this policy, so the next exchange that is
done tries again
+ suspendedConsumers.add(consumer);
+ throw e;
+ }
if (started) {
getLogger().log("Throttling consumer: " + size + " <= " +
resumeInflight
+ " inflight exchange by resuming consumer: " +
consumer);
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 1a782932fc07..04260c6cadac 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
@@ -418,6 +418,17 @@ a route template now has its own copy of the expression,
so a template parameter
route created from the template. Route dumps and the JMX attributes of the
aggregator (`CompletionSizeExpression`,
`CompletionSizeExpressionLanguage` and the others) now show the language and
the expression.
+=== camel-core - throttling route policies on the same route wait for each
other
+
+When a route has both `ThrottlingInflightRoutePolicy` and
`ThrottlingExceptionRoutePolicy`, each of them now resumes the
+consumer only when the other one no longer keeps it suspended. The inflight
policy no longer resumes the consumer while
+the circuit of the exception policy is open and the exception policy suspended
that consumer when it opened the circuit,
+so no new messages are taken until the circuit is half open. When the circuit
is half open, the exception policy does
+not resume a consumer that the inflight policy has suspended; the inflight
policy resumes it when the number of inflight
+exchanges is low enough again.
+
+A custom `RoutePolicySupport` can take part by overriding
`isConsumerKeptSuspended(Route)`.
+
=== camel-seda - a discarded request-reply message fails at once
When the SEDA producer waits for the reply (`InOut` messages, or
`waitForTaskToComplete=Always`) and discards the
diff --git a/docs/user-manual/modules/ROOT/pages/route-policy.adoc
b/docs/user-manual/modules/ROOT/pages/route-policy.adoc
index e2de7ae70fea..2abb28e3619d 100644
--- a/docs/user-manual/modules/ROOT/pages/route-policy.adoc
+++ b/docs/user-manual/modules/ROOT/pages/route-policy.adoc
@@ -108,6 +108,14 @@ when the handler returns `true`.
The circuit closes by itself, so you do not need to resume the route.
+A route can have both a `ThrottlingInflightRoutePolicy` and a
`ThrottlingExceptionRoutePolicy`. Then each of them
+resumes the consumer only when the other one no longer keeps it suspended: the
inflight policy does not resume the
+consumer while the circuit is open, and when the circuit is half open, a
consumer that the inflight policy has suspended
+stays suspended until the inflight policy resumes it. The exception policy
keeps suspended only the consumer of the
+route it opened the circuit for: when it is shared by several routes, the
inflight policy of another route resumes its
+consumer as before, and so it does for a consumer that is started again (such
as when the CamelContext is restarted)
+while the circuit is still open.
+
The throttling exception route policy has the following options:
[width="100%",cols="10%,10%,80%",options="header",]