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 f814ca3c5512 CAMEL-27319: camel-core - Throttle EIP: a message without
the limit uses the old value also after the idle state was removed (#30567)
f814ca3c5512 is described below
commit f814ca3c5512e735a329bb29bdf6a4616e2febeb
Author: allthingssecurity <[email protected]>
AuthorDate: Sun Nov 22 19:08:24 2026 +0530
CAMEL-27319: camel-core - Throttle EIP: a message without the limit uses
the old value also after the idle state was removed (#30567)
The docs say that when the limit comes from a header and the header is
absent, the throttler uses the old value. The old
value was kept in the throttling state, which both throttlers remove when
it was not used for a while (concurrent
requests mode: 10 seconds after the last permit was returned; total
requests mode: about 10 time periods). The next
message without the header then failed with "The
maxConcurrentRequestsExpression was evaluated as null" (or
maxRequestsPerPeriodExpression).
Without a correlation expression, the throttler now keeps the last limit
the expression gave, and a new state uses it
when the expression gives none. With a correlation expression nothing
changes: keeping a limit per key would keep an
entry for every key.
The test executor keeps the clean tasks and runs them in runScheduled(). It
now gives
the thread pool a no-op with the 1-day delay instead of the clean itself,
so the clean
can only run when the test runs it. The throttler still gets a future with
a delay.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../apache/camel/processor/AbstractThrottler.java | 28 ++++
.../processor/ConcurrentRequestsThrottler.java | 7 +
.../camel/processor/TotalRequestsThrottler.java | 7 +
.../throttle/ThrottlerCleanKeepsLimitTest.java | 153 +++++++++++++++++++++
4 files changed, 195 insertions(+)
diff --git
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/AbstractThrottler.java
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/AbstractThrottler.java
index 43c234eb5d24..6cd0c437b16a 100644
---
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/AbstractThrottler.java
+++
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/AbstractThrottler.java
@@ -56,6 +56,9 @@ public abstract class AbstractThrottler extends
BaseProcessorSupport
protected boolean asyncDelayed;
protected boolean callerRunsWhenRejected = true;
protected volatile Expression maxRequestsExpression;
+ // without a correlation expression: the last limit the expression gave.
The state of the key is removed when it is
+ // idle, and a new state starts from this limit when the expression gives
none (such as a header that is absent)
+ private volatile int lastThrottleRate;
// the asynchronous tasks (asyncDelayed) that are queued in the thread
pool and not yet started: a task and
// doShutdown each claim a task by removing it, so an exchange is
processed, or failed when the thread pool is shut
// down, but never both
@@ -72,6 +75,31 @@ public abstract class AbstractThrottler extends
BaseProcessorSupport
this.maxRequestsExpression =
ObjectHelper.notNull(maxRequestsExpression, "maxRequestsExpression");
}
+ /**
+ * The limit to use when the expression gives none for a throttling state
that has no limit yet: the last limit,
+ * when there is no correlation expression (the state was removed when it
was idle), otherwise none.
+ */
+ Integer previousThrottleRate() {
+ int rate = lastThrottleRate;
+ return correlationExpression == null && rate > 0 ? rate : null;
+ }
+
+ /**
+ * Keeps the limit of the throttling state, without a correlation
expression, for {@link #previousThrottleRate()}.
+ */
+ void keepThrottleRate(int rate) {
+ if (correlationExpression == null) {
+ lastThrottleRate = rate;
+ }
+ }
+
+ /**
+ * Forgets the limit kept by {@link #keepThrottleRate(int)}, when the
throttling states are cleared.
+ */
+ void clearThrottleRate() {
+ lastThrottleRate = 0;
+ }
+
/**
* Schedules a clean of a throttling state, unless the pending one can
stay. This is called for every exchange, and
* scheduling and cancelling takes the executor queue lock about three
times. The pending clean stays while at least
diff --git
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/ConcurrentRequestsThrottler.java
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/ConcurrentRequestsThrottler.java
index e5eff47cf5e2..d6b780d7757f 100644
---
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/ConcurrentRequestsThrottler.java
+++
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/ConcurrentRequestsThrottler.java
@@ -225,6 +225,7 @@ public class ConcurrentRequestsThrottler extends
AbstractThrottler {
failAsyncCalls();
}
states.clear();
+ clearThrottleRate();
super.doShutdown();
}
@@ -345,6 +346,11 @@ public class ConcurrentRequestsThrottler extends
AbstractThrottler {
lock.lock();
try {
Integer newThrottle =
getMaximumRequestsExpression().evaluate(exchange, Integer.class);
+ if (newThrottle == null && throttleRate == 0) {
+ // the expression gives no limit (the old value is used)
for a state that has none: the state of the
+ // key was removed when it was idle, so it is the limit
the removed state had
+ newThrottle = previousThrottleRate();
+ }
if (newThrottle != null && newThrottle < 0) {
throw new IllegalStateException(
@@ -387,6 +393,7 @@ public class ConcurrentRequestsThrottler extends
AbstractThrottler {
}
}
throttleRate = newThrottle;
+ keepThrottleRate(newThrottle);
}
}
} finally {
diff --git
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/TotalRequestsThrottler.java
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/TotalRequestsThrottler.java
index 688cbfe901ec..ba8e4f4e332e 100644
---
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/TotalRequestsThrottler.java
+++
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/TotalRequestsThrottler.java
@@ -238,6 +238,7 @@ public class TotalRequestsThrottler extends
AbstractThrottler {
failAsyncCalls();
}
states.clear();
+ clearThrottleRate();
super.doShutdown();
}
@@ -350,6 +351,11 @@ public class TotalRequestsThrottler extends
AbstractThrottler {
try {
Integer newThrottle
=
TotalRequestsThrottler.this.getMaximumRequestsExpression().evaluate(exchange,
Integer.class);
+ if (newThrottle == null && throttleRate == 0) {
+ // the expression gives no limit (the old value is used)
for a state that has none: the state of the
+ // key was removed when it was idle, so it is the limit
the removed state had
+ newThrottle = previousThrottleRate();
+ }
if (newThrottle != null && newThrottle < 0) {
throw new IllegalStateException(
@@ -402,6 +408,7 @@ public class TotalRequestsThrottler extends
AbstractThrottler {
}
}
throttleRate = newThrottle;
+ keepThrottleRate(newThrottle);
}
}
} finally {
diff --git
a/core/camel-core/src/test/java/org/apache/camel/processor/throttle/ThrottlerCleanKeepsLimitTest.java
b/core/camel-core/src/test/java/org/apache/camel/processor/throttle/ThrottlerCleanKeepsLimitTest.java
new file mode 100644
index 000000000000..15828dbcf18e
--- /dev/null
+++
b/core/camel-core/src/test/java/org/apache/camel/processor/throttle/ThrottlerCleanKeepsLimitTest.java
@@ -0,0 +1,153 @@
+/*
+ * 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.List;
+import java.util.Map;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.CamelExecutionException;
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.RuntimeExchangeException;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.processor.Throttler;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * The throttler removes the state of a key some time after it was last used.
When the limit comes from a header, a
+ * message without the header uses the old value (throttle-eip.adoc): also
after the state was removed, and in both
+ * throttling modes.
+ */
+class ThrottlerCleanKeepsLimitTest extends ContextTestSupport {
+
+ private final CapturingExecutor executor = new CapturingExecutor();
+
+ @AfterEach
+ void shutdownExecutor() {
+ executor.shutdownNow();
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = { "total", "concurrent" })
+ void testNoHeaderUsesOldValueAfterClean(String mode) throws Exception {
+ getMockEndpoint("mock:result").expectedBodiesReceived("first",
"second");
+
+ template.sendBodyAndHeader("direct:" + mode, "first", "max", 3);
+ Throttler throttler = throttler(mode);
+ assertEquals(3, throttler.getCurrentMaximumRequests());
+
+ // the key was idle long enough: the clean removes its state
+ executor.runScheduled();
+ assertEquals(0, throttler.getCurrentMaximumRequests());
+
+ // no header: the old value is used
+ template.sendBody("direct:" + mode, "second");
+ assertEquals(3, throttler.getCurrentMaximumRequests());
+
+ assertMockEndpointsSatisfied();
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = { "total", "concurrent" })
+ void testNoHeaderWithoutOldValueFails(String mode) throws Exception {
+ getMockEndpoint("mock:result").expectedMessageCount(0);
+
+ Exception e = assertThrows(CamelExecutionException.class, () ->
template.sendBody("direct:" + mode, "first"));
+ assertInstanceOf(RuntimeExchangeException.class, e.getCause());
+
+ assertMockEndpointsSatisfied();
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = { "total", "concurrent" })
+ void testCorrelatedKeyHasNoOldValueAfterClean(String mode) throws
Exception {
+ getMockEndpoint("mock:result").expectedBodiesReceived("first");
+
+ // with a correlation expression the limit of a removed state is not
kept, as there can be any number of keys
+ template.sendBodyAndHeaders("direct:" + mode + "-key", "first",
Map.<String, Object> of("max", 3, "key", "a"));
+ executor.runScheduled();
+ Exception e = assertThrows(CamelExecutionException.class,
+ () -> template.sendBodyAndHeader("direct:" + mode + "-key",
"second", "key", "a"));
+ assertInstanceOf(RuntimeExchangeException.class, e.getCause());
+
+ assertMockEndpointsSatisfied();
+ }
+
+ private Throttler throttler(String mode) {
+ return context.getProcessor(mode, Throttler.class);
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("direct:total")
+
.throttle(header("max")).timePeriodMillis(TimeUnit.HOURS.toMillis(1)).executorService(executor)
+ .id("total")
+ .to("mock:result");
+ from("direct:concurrent")
+
.throttle(header("max")).concurrentRequestsMode().executorService(executor).id("concurrent")
+ .to("mock:result");
+ from("direct:total-key")
+
.throttle(header("max")).correlationExpression(header("key"))
+
.timePeriodMillis(TimeUnit.HOURS.toMillis(1)).executorService(executor)
+ .to("mock:result");
+ from("direct:concurrent-key")
+
.throttle(header("max")).correlationExpression(header("key")).concurrentRequestsMode()
+ .executorService(executor)
+ .to("mock:result");
+ }
+ };
+ }
+
+ /**
+ * Keeps the scheduled clean tasks so the test decides when they run.
+ */
+ private static final class CapturingExecutor extends
ScheduledThreadPoolExecutor {
+ private final List<Runnable> scheduled = new CopyOnWriteArrayList<>();
+
+ CapturingExecutor() {
+ super(1);
+ setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
+ }
+
+ @Override
+ public ScheduledFuture<?> schedule(Runnable command, long delay,
TimeUnit unit) {
+ scheduled.add(command);
+ // the clean runs only in runScheduled(): the executor gets a
no-op, so its future has a delay for the throttler
+ return super.schedule(() -> {
+ }, TimeUnit.DAYS.toMillis(1), TimeUnit.MILLISECONDS);
+ }
+
+ void runScheduled() {
+ for (Runnable task : scheduled) {
+ task.run();
+ }
+ scheduled.clear();
+ }
+ }
+}