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 05aa82c98a0c CAMEL-27510: camel-azure-servicebus - the Camel lock
renewer runs on a thread of its own, so a slow periodic task no longer lets
message locks expire and a stop no longer leaves it registered (#30831)
05aa82c98a0c is described below
commit 05aa82c98a0cda742621af385ebc0d053b0e1e6f
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 13:32:23 2026 +0530
CAMEL-27510: camel-azure-servicebus - the Camel lock renewer runs on a
thread of its own, so a slow periodic task no longer lets message locks expire
and a stop no longer leaves it registered (#30831)
The Camel lock renewer of ServiceBusConsumer (peek-lock mode,
maxAutoLockRenewDuration above 0, no
sessions) was a task of the PeriodTaskScheduler of the CamelContext. That
scheduler runs all its
tasks one after another on one shared timer thread, and it has no way to
remove a task:
- a periodic task that is slow on that thread (a vault secret refresh task
waiting on a remote
call, or the context reload it starts there, which waits for the
exchanges in flight) held up
every renewal. The first renewal of a lock comes with about 15 seconds
left, so a stall longer
than that let the lock expire, and Service Bus delivered the message
again while its exchange
was still running;
- doStop only set a flag, so every start (route restart, supervised
restart, context reload)
left one more renewer task registered until the CamelContext stopped,
keeping the stopped
consumer reachable and running every 5 seconds for nothing.
CAMEL-27066 kept the renewer on that task with "no new thread, timer or
Reactor delay", and noted
that its margins are smaller when the shared timer thread is late. The
shared thread is the cause
of both problems above, so this reverses that choice: the renewer now runs
on a single-thread
scheduled executor of the consumer, from the ExecutorServiceManager of the
CamelContext
("ServiceBusLockRenewer[<topic or queue name>]"), created in doStart and
shut down with
shutdownNow in doStop and doShutdown. shutdownNow, because a run only
subscribes renewals (the
callbacks run on threads of the SDK) and never blocks, so there is nothing
to wait for, and the
renewal client is closed right after. It runs 5 seconds after the end of
its previous run and
still renews a lock that expires within 20 seconds, so the first renewal
comes with about 15
seconds left and a retry after a transient error with about 10. One thread
per consumer rather
than one per component: the renewer then depends only on its own consumer,
and starts and stops
with it; the consumer already has the threads of its processor client. An
exception or an Error
in a run is logged and the next run goes on, as the shared timer did since
CAMEL-26906 (anything
thrown would end a scheduled task); a VirtualMachineError is thrown on, as
there.
Two more changes to the renewer, from the same review:
- at most one renewal of a message in flight: a run does not renew a lock
while a renewal of it
has not answered, unless that renewal was sent 10 seconds (two runs) ago.
The SDK ends a
request only after its tryTimeout (1 minute by default), which can be
after the lock expired,
so a renewal that hangs gets one more attempt. With a lock duration of 30
seconds or more (the
Service Bus default is 60) it comes with about 5 to 10 seconds left. With
a shorter lock it
comes later in the lock: with 15 seconds, 0 to 5 seconds left, where
before the next run sent
one more 5 seconds earlier. Before, a slow broker got one more renewal of
the same message on
every run. The mark is cleared by the answer, a transient error, or a
call that throws (so only
a renewal that hangs waits for the 10 seconds); a non-transient error
removes the entry as
before;
- an answer only moves the stored lock expiry forward: the answer of an
earlier renewal could
arrive after that of a later one and move it back (which only made the
renewer renew sooner).
The decision and the in-flight mark are taken in one computeIfPresent, so a
callback or the
completion of the exchange in between is not lost, and a late answer still
does not add a
completed exchange.
The renewer and its executor are set up before client.start(): they were
set up after it, so a
message the client delivered right after the start was not tracked, and on
an asynchronous
route its lock got no Camel renewal at all. If the start fails after that,
BaseService.start
calls doStop, which shuts them down.
processMessage reads the lockRenewer field once (it is now volatile): it
read it twice, and a
stop in between gave a NullPointerException.
Not changed: two transient renewal errors in a row late in a lock can still
lose it (the margin
documented by CAMEL-27066), and a VirtualMachineError thrown by a task of
the
TimerListenerManager still ends that timer (deliberate); the renewer no
longer depends on it.
Tests: new ServiceBusConsumerLockRenewerTest (stop/start leaves no renewer
task on the
PeriodTaskScheduler and no renewer thread; a periodic task that blocks the
shared timer does not
hold up a renewal; a slow broker gets one renewal at a time and a late
answer does not move the
expiry back; a message delivered while the client starts is tracked; a
failed start shuts the
renewer down; a failed renewal, by an error answer or a call that throws,
keeps the entry and is
retried by the next run; a run that throws does not end the later runs).
ServiceBusConsumerTest
captures the renewer from the executor instead of the PeriodTaskScheduler
and checks an executor
per start, shut down by the stop. DST world comments updated to the new
thread model; its fake
answers a renewal when it is called, so it does not exercise the in-flight
rule. Upgrade guide
entry for 4.24 (one more thread per consumer).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../azure/servicebus/ServiceBusConsumer.java | 212 ++++++++---
.../ServiceBusConsumerLockRenewerTest.java | 414 +++++++++++++++++++++
.../azure/servicebus/ServiceBusConsumerTest.java | 39 +-
.../azure/servicebus/dst/ServiceBusWorld.java | 39 +-
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 11 +
5 files changed, 626 insertions(+), 89 deletions(-)
diff --git
a/components/camel-azure/camel-azure-servicebus/src/main/java/org/apache/camel/component/azure/servicebus/ServiceBusConsumer.java
b/components/camel-azure/camel-azure-servicebus/src/main/java/org/apache/camel/component/azure/servicebus/ServiceBusConsumer.java
index eb3775b035b8..252da4474de0 100644
---
a/components/camel-azure/camel-azure-servicebus/src/main/java/org/apache/camel/component/azure/servicebus/ServiceBusConsumer.java
+++
b/components/camel-azure/camel-azure-servicebus/src/main/java/org/apache/camel/component/azure/servicebus/ServiceBusConsumer.java
@@ -23,6 +23,8 @@ import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
@@ -43,10 +45,8 @@ import org.apache.camel.Processor;
import org.apache.camel.ShutdownRunningTask;
import org.apache.camel.spi.ExceptionHandler;
import org.apache.camel.spi.HeaderFilterStrategy;
-import org.apache.camel.spi.PeriodTaskScheduler;
import org.apache.camel.spi.ShutdownAware;
import org.apache.camel.support.DefaultConsumer;
-import org.apache.camel.support.PluginHelper;
import org.apache.camel.support.SynchronizationAdapter;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.StringHelper;
@@ -56,11 +56,17 @@ import org.slf4j.LoggerFactory;
public class ServiceBusConsumer extends DefaultConsumer implements
ShutdownAware {
private static final Logger LOG =
LoggerFactory.getLogger(ServiceBusConsumer.class);
- // the lock renewer runs every LOCK_RENEW_INTERVAL_SECONDS (or a second
later) and renews a lock that expires
- // within LOCK_RENEW_BEFORE_EXPIRY_SECONDS, so its first renewal comes
with more than 14 seconds left, and a
- // transient failure of it is retried by the next run with more than 8
seconds left (when the runs come on time)
+ // the lock renewer runs on a thread of its own,
LOCK_RENEW_INTERVAL_SECONDS after the end of its previous run, and
+ // renews a lock that expires within LOCK_RENEW_BEFORE_EXPIRY_SECONDS, so
its first renewal comes with about 15
+ // seconds left, and a transient failure of it is retried by the next run
with about 10 seconds left
private static final int LOCK_RENEW_INTERVAL_SECONDS = 5;
private static final int LOCK_RENEW_BEFORE_EXPIRY_SECONDS = 20;
+ // a run does not renew a lock while a renewal of it is in flight, unless
that renewal has not answered for this
+ // long (two runs): the SDK ends a request only after its tryTimeout (60
seconds by default), which can be after the
+ // lock expired, so a renewal that hangs gets one more attempt. With a
lock duration of 30 seconds or more (the
+ // default is 60) it comes with about 5 to 10 seconds left; with a shorter
lock it comes later in the lock (with 15
+ // seconds, 0 to 5 seconds left, 5 seconds later than without this rule)
+ private static final int LOCK_RENEW_IN_FLIGHT_SECONDS = 2 *
LOCK_RENEW_INTERVAL_SECONDS;
// Azure recommends putting the exception type in the dead-letter reason
and its stack trace in the description,
// but both are length-limited: the .NET and JavaScript SDKs cap them at
4096 (MaxDeadLetterReasonLength, applied
// to the description as well), and Azure separately warns that a stack
trace here can push a message past the
@@ -74,7 +80,8 @@ public class ServiceBusConsumer extends DefaultConsumer
implements ShutdownAware
private ServiceBusProcessorClient client;
private boolean clientCloseable;
private ServiceBusReceiverAsyncClient renewalClient;
- private LockRenewer lockRenewer;
+ private volatile LockRenewer lockRenewer;
+ private ScheduledExecutorService lockRenewerExecutor;
private final AtomicInteger pendingExchanges = new AtomicInteger();
// Set by deferShutdown in peek-lock mode: a graceful stop waits for the
exchanges in flight, which settle their
// message through the processor client, so the client stays open and the
messages it delivers meanwhile are held
@@ -122,11 +129,11 @@ public class ServiceBusConsumer extends DefaultConsumer
implements ShutdownAware
clientCloseable = false;
}
- client.start();
-
// set up Camel-managed lock renewal for PEEK_LOCK mode
// the Azure SDK's built-in lock renewal is tied to the processMessage
callback duration,
- // which returns immediately for async routes, making
maxAutoLockRenewDuration ineffective
+ // which returns immediately for async routes, making
maxAutoLockRenewDuration ineffective.
+ // Set up before the client starts, so a message it delivers right
away is tracked too; if the start fails,
+ // BaseService.start calls doStop, which shuts it down
if (getConfiguration().getProcessorClient() == null
&& getConfiguration().getServiceBusReceiveMode() ==
ServiceBusReceiveMode.PEEK_LOCK
&& getConfiguration().getMaxAutoLockRenewDuration() > 0
@@ -137,9 +144,17 @@ public class ServiceBusConsumer extends DefaultConsumer
implements ShutdownAware
long maxRenewMs = getConfiguration().getMaxAutoLockRenewDuration();
lockRenewer = new LockRenewer(renewalClient,
Duration.ofMillis(maxRenewMs));
- PeriodTaskScheduler scheduler =
PluginHelper.getPeriodTaskScheduler(getEndpoint().getCamelContext());
- scheduler.schedulePeriodTask(lockRenewer,
LOCK_RENEW_INTERVAL_SECONDS * 1000L);
+ // a thread of its own, not the shared timer of the
PeriodTaskScheduler: there the renewer waits behind every
+ // other periodic task of the context (a slow one lets the locks
expire), and a task cannot be removed, so
+ // every start would leave one more renewer registered. A run only
subscribes renewals, it never blocks
+ lockRenewerExecutor =
getEndpoint().getCamelContext().getExecutorServiceManager()
+ .newSingleThreadScheduledExecutor(this,
+ "ServiceBusLockRenewer[" +
getConfiguration().getTopicOrQueueName() + "]");
+ lockRenewerExecutor.scheduleWithFixedDelay(lockRenewer,
LOCK_RENEW_INTERVAL_SECONDS * 1000L,
+ LOCK_RENEW_INTERVAL_SECONDS * 1000L,
TimeUnit.MILLISECONDS);
}
+
+ client.start();
}
private void processMessage(ServiceBusReceivedMessageContext
messageContext) {
@@ -160,8 +175,9 @@ public class ServiceBusConsumer extends DefaultConsumer
implements ShutdownAware
// add exchange callback
exchange.getExchangeExtension().addOnCompletion(onCompletion);
// track for Camel-managed lock renewal
- if (lockRenewer != null) {
- lockRenewer.add(exchange, message);
+ final LockRenewer renewer = lockRenewer;
+ if (renewer != null) {
+ renewer.add(exchange, message);
}
// use default consumer callback
AsyncCallback cb = defaultConsumerCallback(exchange, true);
@@ -207,10 +223,7 @@ public class ServiceBusConsumer extends DefaultConsumer
implements ShutdownAware
@Override
protected void doStop() throws Exception {
- if (lockRenewer != null) {
- lockRenewer.cancel();
- lockRenewer = null;
- }
+ stopLockRenewer();
if (renewalClient != null) {
renewalClient.close();
renewalClient = null;
@@ -237,10 +250,7 @@ public class ServiceBusConsumer extends DefaultConsumer
implements ShutdownAware
@Override
protected void doShutdown() throws Exception {
// defensive cleanup in case doStop() was not called
- if (lockRenewer != null) {
- lockRenewer.cancel();
- lockRenewer = null;
- }
+ stopLockRenewer();
if (renewalClient != null) {
renewalClient.close();
renewalClient = null;
@@ -254,6 +264,36 @@ public class ServiceBusConsumer extends DefaultConsumer
implements ShutdownAware
super.doShutdown();
}
+ /**
+ * Stops the lock renewer and its thread. shutdownNow: there is nothing to
wait for, as a run only subscribes
+ * renewals (their callbacks run on threads of the SDK), and the renewal
client is closed right after.
+ */
+ private void stopLockRenewer() {
+ if (lockRenewer != null) {
+ lockRenewer.cancel();
+ lockRenewer = null;
+ }
+ if (lockRenewerExecutor != null) {
+
getEndpoint().getCamelContext().getExecutorServiceManager().shutdownNow(lockRenewerExecutor);
+ lockRenewerExecutor = null;
+ }
+ }
+
+ /**
+ * For tests: one run of the lock renewer, as its thread runs it at the
given time.
+ */
+ void runLockRenewer(Instant now) {
+ lockRenewer.renewDueLocks(now);
+ }
+
+ /**
+ * For tests: the lock expiry the lock renewer holds for the exchange, or
null when it does not renew its lock.
+ */
+ OffsetDateTime lockRenewerLockedUntil(String exchangeId) {
+ LockRenewer.LockRenewerEntry entry =
lockRenewer.entries.get(exchangeId);
+ return entry != null ? entry.lockedUntil : null;
+ }
+
@Override
public boolean deferShutdown(ShutdownRunningTask shutdownRunningTask) {
if (clientCloseable && getConfiguration().getServiceBusReceiveMode()
== ServiceBusReceiveMode.PEEK_LOCK) {
@@ -342,6 +382,8 @@ public class ServiceBusConsumer extends DefaultConsumer
implements ShutdownAware
private final ServiceBusReceiverAsyncClient client;
private final Duration maxRenewDuration;
private final AtomicBoolean run = new AtomicBoolean(true);
+ // changed only through the atomic operations of the map: add, the run
(on the renewer thread), the renewal
+ // callbacks (on threads of the SDK) and the completion of the exchange
private final Map<String, LockRenewerEntry> entries = new
ConcurrentHashMap<>();
LockRenewer(ServiceBusReceiverAsyncClient client, Duration
maxRenewDuration) {
@@ -368,7 +410,7 @@ public class ServiceBusConsumer extends DefaultConsumer
implements ShutdownAware
});
entries.put(exchange.getExchangeId(),
- new LockRenewerEntry(message, message.getLockedUntil(),
Instant.now()));
+ new LockRenewerEntry(message, message.getLockedUntil(),
Instant.now(), null));
}
public void cancel() {
@@ -377,50 +419,91 @@ public class ServiceBusConsumer extends DefaultConsumer
implements ShutdownAware
@Override
public void run() {
+ try {
+ renewDueLocks(Instant.now());
+ } catch (VirtualMachineError e) {
+ // as the TimerListenerManager: a JVM-level failure is thrown
on, and ends the task
+ throw e;
+ } catch (Exception | Error e) {
+ // keep the scheduled task alive: anything thrown would end
it, and no lock would be renewed any more
+ LOG.warn("Error in the lock renewer, the next run renews the
locks again: {}", e.toString());
+ LOG.debug("Error in the lock renewer", e);
+ }
+ }
+
+ void renewDueLocks(Instant now) {
if (!run.get()) {
return;
}
- Instant now = Instant.now();
- for (Map.Entry<String, LockRenewerEntry> mapEntry :
entries.entrySet()) {
- String exchangeId = mapEntry.getKey();
- LockRenewerEntry entry = mapEntry.getValue();
-
- // skip if max renewal duration exceeded
- Duration elapsed = Duration.between(entry.startTime, now);
- if (elapsed.compareTo(maxRenewDuration) >= 0) {
+ for (String exchangeId : entries.keySet()) {
+ LockRenewerEntry[] started = new LockRenewerEntry[1];
+ boolean[] exceeded = new boolean[1];
+ // decided and marked in one atomic step, so a callback or the
completion of the exchange in between
+ // cannot be lost; the renewal is subscribed after it (its
callback can run at once, on this thread)
+ entries.computeIfPresent(exchangeId, (k, entry) -> {
+ // skip if max renewal duration exceeded
+ if (Duration.between(entry.startTime,
now).compareTo(maxRenewDuration) >= 0) {
+ exceeded[0] = true;
+ return null;
+ }
+ // renew if the lock expires within
LOCK_RENEW_BEFORE_EXPIRY_SECONDS (several runs before it
+ // expires), and no renewal of it is in flight
+ if
(!now.plusSeconds(LOCK_RENEW_BEFORE_EXPIRY_SECONDS).isAfter(entry.lockedUntil.toInstant())
+ || entry.renewal != null &&
entry.renewal.awaited(now)) {
+ return entry;
+ }
+ started[0] = new LockRenewerEntry(entry.message,
entry.lockedUntil, entry.startTime, new Renewal(now));
+ return started[0];
+ });
+ if (exceeded[0]) {
LOG.debug("Max lock renewal duration exceeded for
exchangeId {}, stopping renewal", exchangeId);
- entries.remove(exchangeId);
- continue;
+ } else if (started[0] != null) {
+ renew(exchangeId, started[0].message, started[0].renewal);
}
+ }
+ }
- // renew if the lock expires within
LOCK_RENEW_BEFORE_EXPIRY_SECONDS (several runs before it expires)
- Instant lockExpiry = entry.lockedUntil.toInstant();
- if
(now.plusSeconds(LOCK_RENEW_BEFORE_EXPIRY_SECONDS).isAfter(lockExpiry)) {
- client.renewMessageLock(entry.message)
- .subscribe(
- newLockedUntil -> {
- LOG.trace("Renewed lock for exchangeId
{}, new expiry: {}", exchangeId,
- newLockedUntil);
- entries.computeIfPresent(exchangeId,
- (k, e) -> new
LockRenewerEntry(e.message, newLockedUntil, e.startTime));
- },
- error -> {
- if (isTransient(error)) {
- // the SDK makes one attempt: keep
the entry, so the next run renews
- // the lock again while it is
still held
- LOG.warn("Failed to renew lock for
exchangeId {}, will try again: {}",
- exchangeId,
error.getMessage());
- } else {
- LOG.warn("Failed to renew lock for
exchangeId {}: {}", exchangeId,
- error.getMessage());
- entries.remove(exchangeId);
- }
- });
- }
+ private void renew(String exchangeId, ServiceBusReceivedMessage
message, Renewal renewal) {
+ try {
+ client.renewMessageLock(message)
+ .subscribe(
+ newLockedUntil -> {
+ LOG.trace("Renewed lock for exchangeId {},
new expiry: {}", exchangeId, newLockedUntil);
+ // the answer of an earlier renewal can
come after that of a later one: keep the
+ // later expiry. computeIfPresent: a late
answer does not add a completed exchange
+ entries.computeIfPresent(exchangeId,
+ (k, e) -> new LockRenewerEntry(
+ e.message,
+
newLockedUntil.isAfter(e.lockedUntil) ? newLockedUntil : e.lockedUntil,
+ e.startTime, e.renewal ==
renewal ? null : e.renewal));
+ },
+ error -> {
+ if (isTransient(error)) {
+ // the SDK makes one attempt: keep the
entry, so the next run renews
+ // the lock again while it is still
held
+ LOG.warn("Failed to renew lock for
exchangeId {}, will try again: {}",
+ exchangeId,
error.getMessage());
+ answered(exchangeId, renewal);
+ } else {
+ LOG.warn("Failed to renew lock for
exchangeId {}: {}", exchangeId,
+ error.getMessage());
+ entries.remove(exchangeId);
+ }
+ });
+ } catch (Exception e) {
+ // as a transient error: the next run tries again
+ LOG.warn("Failed to renew lock for exchangeId {}, will try
again: {}", exchangeId, e.toString());
+ answered(exchangeId, renewal);
}
}
+ /** The renewal is no longer in flight: the next run may renew the
lock again. */
+ private void answered(String exchangeId, Renewal renewal) {
+ entries.computeIfPresent(exchangeId,
+ (k, e) -> e.renewal == renewal ? new
LockRenewerEntry(e.message, e.lockedUntil, e.startTime, null) : e);
+ }
+
/**
* A transient error (such as a busy server or a connection that was
lost) can be retried, as the processor of
* the Service Bus .NET SDK does for its own lock renewal; another
error (such as a lost lock) ends the renewal.
@@ -429,7 +512,22 @@ public class ServiceBusConsumer extends DefaultConsumer
implements ShutdownAware
return error instanceof ServiceBusException sbe &&
sbe.isTransient();
}
- private record LockRenewerEntry(ServiceBusReceivedMessage message,
OffsetDateTime lockedUntil, Instant startTime) {
+ /** The renewal of a lock in flight, compared by identity. */
+ private static final class Renewal {
+ private final Instant sentAt;
+
+ private Renewal(Instant sentAt) {
+ this.sentAt = sentAt;
+ }
+
+ /** Whether a run at this time waits for its answer: it was sent
less than two runs ago. */
+ boolean awaited(Instant now) {
+ return
now.isBefore(sentAt.plusSeconds(LOCK_RENEW_IN_FLIGHT_SECONDS));
+ }
+ }
+
+ private record LockRenewerEntry(
+ ServiceBusReceivedMessage message, OffsetDateTime lockedUntil,
Instant startTime, Renewal renewal) {
}
}
diff --git
a/components/camel-azure/camel-azure-servicebus/src/test/java/org/apache/camel/component/azure/servicebus/ServiceBusConsumerLockRenewerTest.java
b/components/camel-azure/camel-azure-servicebus/src/test/java/org/apache/camel/component/azure/servicebus/ServiceBusConsumerLockRenewerTest.java
new file mode 100644
index 000000000000..ae3f6087bc72
--- /dev/null
+++
b/components/camel-azure/camel-azure-servicebus/src/test/java/org/apache/camel/component/azure/servicebus/ServiceBusConsumerLockRenewerTest.java
@@ -0,0 +1,414 @@
+/*
+ * 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.azure.servicebus;
+
+import java.time.Instant;
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+
+import com.azure.core.amqp.exception.AmqpErrorCondition;
+import com.azure.core.amqp.exception.AmqpException;
+import com.azure.messaging.servicebus.ServiceBusErrorContext;
+import com.azure.messaging.servicebus.ServiceBusErrorSource;
+import com.azure.messaging.servicebus.ServiceBusException;
+import com.azure.messaging.servicebus.ServiceBusProcessorClient;
+import com.azure.messaging.servicebus.ServiceBusReceivedMessage;
+import com.azure.messaging.servicebus.ServiceBusReceivedMessageContext;
+import com.azure.messaging.servicebus.ServiceBusReceiverAsyncClient;
+import com.azure.messaging.servicebus.models.ServiceBusReceiveMode;
+import org.apache.camel.AsyncCallback;
+import org.apache.camel.AsyncProcessor;
+import org.apache.camel.CamelContext;
+import org.apache.camel.Endpoint;
+import org.apache.camel.Exchange;
+import org.apache.camel.ExtendedCamelContext;
+import
org.apache.camel.component.azure.servicebus.client.ServiceBusClientFactory;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.spi.ExchangeFactory;
+import org.apache.camel.spi.ExecutorServiceManager;
+import org.apache.camel.spi.HeaderFilterStrategy;
+import org.apache.camel.spi.PeriodTaskScheduler;
+import org.apache.camel.spi.Synchronization;
+import org.apache.camel.spi.UuidGenerator;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.support.PluginHelper;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.ArgumentCaptor;
+import reactor.core.publisher.Mono;
+import reactor.core.publisher.Sinks;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.awaitility.Awaitility.await;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+/**
+ * The Camel lock renewer of the consumer runs on a thread of its own, not on
the shared timer of the
+ * PeriodTaskScheduler: a stop ends it (the scheduler has no way to remove a
task), and another periodic task cannot
+ * hold up a renewal. At most one renewal of a lock is in flight, and a late
answer does not move the lock expiry
+ * backwards. The renewer is set up before the processor client starts, a
failed renewal is retried by the next run, and
+ * a run that throws does not end the later runs.
+ */
+class ServiceBusConsumerLockRenewerTest {
+
+ private static final String QUEUE = "lock-renewer-queue";
+ private static final String RENEWER_THREAD = "ServiceBusLockRenewer[" +
QUEUE + "]";
+
+ private final ServiceBusConfiguration configuration = mock();
+ private final ServiceBusClientFactory clientFactory = mock();
+ private final ServiceBusProcessorClient client = mock();
+ private final ServiceBusComponent component = mock();
+ private final ServiceBusEndpoint endpoint = mock();
+ private final ServiceBusReceivedMessageContext messageContext = mock();
+ private final ServiceBusReceivedMessage message = mock();
+ private final AsyncProcessor processor = mock();
+ private final CamelContext context = mock();
+ private final ExtendedCamelContext ecc = mock();
+ private final ExchangeFactory ef = mock();
+ private final HeaderFilterStrategy headerFilterStrategy = mock();
+ private final UuidGenerator uuidGenerator = mock();
+ private final ServiceBusReceiverAsyncClient renewalClient = mock();
+ private final PeriodTaskScheduler periodTaskScheduler = mock();
+ private final ExecutorServiceManager executorServiceManager = mock();
+ private final ScheduledExecutorService lockRenewerExecutor = mock();
+ private final ArgumentCaptor<Consumer<ServiceBusReceivedMessageContext>>
processMessageCaptor = ArgumentCaptor.captor();
+ private final ArgumentCaptor<Consumer<ServiceBusErrorContext>>
processErrorCaptor = ArgumentCaptor.captor();
+
+ private DefaultCamelContext realContext;
+
+ @BeforeEach
+ void beforeEach() {
+ when(endpoint.getCamelContext()).thenReturn(context);
+ when(context.getCamelContextExtension()).thenReturn(ecc);
+ when(ecc.getExchangeFactory()).thenReturn(ef);
+ when(ef.newExchangeFactory(any())).thenReturn(ef);
+ when(ef.create(any(Endpoint.class), anyBoolean()))
+ .thenAnswer(inv ->
DefaultExchange.newFromEndpoint(inv.getArgument(0)));
+ when(endpoint.getComponent()).thenReturn(component);
+ when(endpoint.getConfiguration()).thenReturn(configuration);
+ when(endpoint.getServiceBusClientFactory()).thenReturn(clientFactory);
+ when(clientFactory.createServiceBusProcessorClient(any(),
processMessageCaptor.capture(), processErrorCaptor.capture()))
+ .thenReturn(client);
+ // an asynchronous route: the exchange stays in flight, only the Camel
lock renewer keeps its lock
+ when(processor.process(any(Exchange.class),
any(AsyncCallback.class))).thenReturn(false);
+
when(configuration.getHeaderFilterStrategy()).thenReturn(headerFilterStrategy);
+ when(context.getUuidGenerator()).thenReturn(uuidGenerator);
+ when(uuidGenerator.generateExchangeUuid()).thenReturn("exchange-1");
+
when(clientFactory.createServiceBusReceiverAsyncClient(any())).thenReturn(renewalClient);
+ when(configuration.getTopicOrQueueName()).thenReturn(QUEUE);
+
when(configuration.getServiceBusReceiveMode()).thenReturn(ServiceBusReceiveMode.PEEK_LOCK);
+ when(configuration.getMaxAutoLockRenewDuration()).thenReturn(300000L);
+ when(configuration.isSessionEnabled()).thenReturn(false);
+ when(messageContext.getMessage()).thenReturn(message);
+
when(message.getApplicationProperties()).thenReturn(Collections.emptyMap());
+ // the period task scheduler of the context, which the renewer must
not use
+
when(ecc.getContextPlugin(PeriodTaskScheduler.class)).thenReturn(periodTaskScheduler);
+ }
+
+ @AfterEach
+ void afterEach() {
+ if (realContext != null) {
+ realContext.stop();
+ }
+ }
+
+ /**
+ * The consumer runs with the thread pools and the period task scheduler
of a real CamelContext.
+ */
+ private PeriodTaskScheduler useRealContext() {
+ realContext = new DefaultCamelContext();
+ realContext.start();
+ PeriodTaskScheduler scheduler =
PluginHelper.getPeriodTaskScheduler(realContext);
+
when(ecc.getContextPlugin(PeriodTaskScheduler.class)).thenReturn(scheduler);
+
when(context.getExecutorServiceManager()).thenReturn(realContext.getExecutorServiceManager());
+ return scheduler;
+ }
+
+ /**
+ * The consumer gets a mocked executor for its lock renewer, so a test
runs the renewer itself.
+ */
+ private ScheduledExecutorService useMockedExecutor() {
+
when(context.getExecutorServiceManager()).thenReturn(executorServiceManager);
+ when(executorServiceManager.newSingleThreadScheduledExecutor(any(),
anyString())).thenReturn(lockRenewerExecutor);
+ return lockRenewerExecutor;
+ }
+
+ private static long lockRenewerTasks(PeriodTaskScheduler scheduler) {
+ return scheduler.getTasks().stream()
+ .filter(t ->
t.getClass().getName().endsWith("ServiceBusConsumer$LockRenewer"))
+ .count();
+ }
+
+ private static long lockRenewerThreads() {
+ return Thread.getAllStackTraces().keySet().stream()
+ .filter(t -> t.isAlive() &&
t.getName().endsWith(RENEWER_THREAD))
+ .count();
+ }
+
+ @Test
+ void stopEndsTheLockRenewerAndItsThread() throws Exception {
+ PeriodTaskScheduler scheduler = useRealContext();
+
+ ServiceBusConsumer consumer = new ServiceBusConsumer(endpoint,
processor);
+ for (int i = 0; i < 5; i++) {
+ consumer.doStart();
+ consumer.doStop();
+ }
+ // a fresh consumer per start, as after a context reload, which
creates new consumers
+ for (int i = 0; i < 3; i++) {
+ ServiceBusConsumer c = new ServiceBusConsumer(endpoint, processor);
+ c.doStart();
+ c.doStop();
+ c.doShutdown();
+ }
+ // the PeriodTaskScheduler cannot remove a task: a renewer registered
there would stay until the context stops
+ assertThat(lockRenewerTasks(scheduler)).isZero();
+ await().atMost(10, TimeUnit.SECONDS).until(() -> lockRenewerThreads()
== 0);
+
+ // one thread while the consumer is started, none after it stopped
+ consumer.doStart();
+ assertThat(lockRenewerThreads()).isEqualTo(1);
+ consumer.doStop();
+ await().atMost(10, TimeUnit.SECONDS).until(() -> lockRenewerThreads()
== 0);
+ assertThat(lockRenewerTasks(scheduler)).isZero();
+ }
+
+ @Test
+ void aBlockedSharedTimerDoesNotHoldUpTheRenewal() throws Exception {
+ PeriodTaskScheduler scheduler = useRealContext();
+
+ List<Instant> renewCalls = Collections.synchronizedList(new
ArrayList<>());
+
when(renewalClient.renewMessageLock(any(ServiceBusReceivedMessage.class))).thenAnswer(inv
-> {
+ renewCalls.add(Instant.now());
+ return
Mono.just(OffsetDateTime.now(ZoneOffset.UTC).plusSeconds(60));
+ });
+
+ // another periodic task of the context hangs in a call (a vault
refresh task, or the context reload it
+ // starts) and holds the shared timer thread until the end of the test
+ CountDownLatch blocking = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ scheduler.schedulePeriodTask(() -> {
+ blocking.countDown();
+ try {
+ release.await(60, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }, 100);
+ assertThat(blocking.await(10, TimeUnit.SECONDS)).isTrue();
+
+ try (ServiceBusConsumer consumer = new ServiceBusConsumer(endpoint,
processor)) {
+ consumer.doStart();
+ // the lock has 15 seconds left: the first run of the renewer, 5
seconds after the start, renews it
+ OffsetDateTime lockedUntil =
OffsetDateTime.now(ZoneOffset.UTC).plusSeconds(15);
+ when(message.getLockedUntil()).thenReturn(lockedUntil);
+ processMessageCaptor.getValue().accept(messageContext);
+
+ await().atMost(14, TimeUnit.SECONDS).until(() ->
!renewCalls.isEmpty());
+ assertThat(renewCalls.get(0)).isBefore(lockedUntil.toInstant());
+ consumer.doStop();
+ } finally {
+ release.countDown();
+ }
+ }
+
+ @Test
+ void
slowBrokerGetsOneRenewalAtATimeAndALateAnswerDoesNotMoveTheExpiryBack() throws
Exception {
+ useMockedExecutor();
+ // the broker answers only when the test says so
+ List<Sinks.One<OffsetDateTime>> pending = new ArrayList<>();
+
when(renewalClient.renewMessageLock(any(ServiceBusReceivedMessage.class))).thenAnswer(inv
-> {
+ Sinks.One<OffsetDateTime> sink = Sinks.one();
+ pending.add(sink);
+ return sink.asMono();
+ });
+ Instant t0 = Instant.now();
+
when(message.getLockedUntil()).thenReturn(OffsetDateTime.ofInstant(t0.plusSeconds(18),
ZoneOffset.UTC));
+
+ try (ServiceBusConsumer consumer = new ServiceBusConsumer(endpoint,
processor)) {
+ consumer.doStart();
+ processMessageCaptor.getValue().accept(messageContext);
+
+ // the lock expires within 20 seconds: renewed
+ consumer.runLockRenewer(t0);
+ verify(renewalClient, times(1)).renewMessageLock(message);
+
+ // the next run, 5 seconds later: the renewal has not answered
yet, no second one
+ consumer.runLockRenewer(t0.plusSeconds(5));
+ verify(renewalClient, times(1)).renewMessageLock(message);
+
+ // two runs after it, the renewal still has not answered: it may
hang until the SDK gives up on it, which
+ // can be after the lock expired, so the lock is renewed once more
+ consumer.runLockRenewer(t0.plusSeconds(10));
+ verify(renewalClient, times(2)).renewMessageLock(message);
+ assertThat(pending).hasSize(2);
+
+ // the answers come newest first: the expiry moves forward only
+ OffsetDateTime first =
OffsetDateTime.ofInstant(t0.plusSeconds(60), ZoneOffset.UTC);
+ OffsetDateTime second = first.plusSeconds(10);
+ pending.get(1).tryEmitValue(second);
+
assertThat(consumer.lockRenewerLockedUntil("exchange-1")).isEqualTo(second);
+ pending.get(0).tryEmitValue(first);
+
assertThat(consumer.lockRenewerLockedUntil("exchange-1")).isEqualTo(second);
+
+ // both answered: no renewal until the lock expires within 20
seconds again
+ consumer.runLockRenewer(t0.plusSeconds(15));
+ verify(renewalClient, times(2)).renewMessageLock(message);
+ consumer.runLockRenewer(t0.plusSeconds(51));
+ verify(renewalClient, times(3)).renewMessageLock(message);
+ }
+ verifyNoInteractions(periodTaskScheduler);
+ }
+
+ @Test
+ void aMessageDeliveredAsTheClientStartsIsTracked() throws Exception {
+ useMockedExecutor();
+ Instant t0 = Instant.now();
+ OffsetDateTime lockedUntil =
OffsetDateTime.ofInstant(t0.plusSeconds(18), ZoneOffset.UTC);
+ when(message.getLockedUntil()).thenReturn(lockedUntil);
+
when(renewalClient.renewMessageLock(any(ServiceBusReceivedMessage.class)))
+
.thenReturn(Mono.just(OffsetDateTime.ofInstant(t0.plusSeconds(60),
ZoneOffset.UTC)));
+ // the processor client delivers a message as soon as it starts,
before doStart returns
+ doAnswer(inv -> {
+ processMessageCaptor.getValue().accept(messageContext);
+ return null;
+ }).when(client).start();
+
+ try (ServiceBusConsumer consumer = new ServiceBusConsumer(endpoint,
processor)) {
+ consumer.doStart();
+
+
assertThat(consumer.lockRenewerLockedUntil("exchange-1")).isEqualTo(lockedUntil);
+ consumer.runLockRenewer(t0);
+ verify(renewalClient, times(1)).renewMessageLock(message);
+ }
+ }
+
+ @Test
+ void aFailedStartShutsTheLockRenewerDown() {
+ ScheduledExecutorService executor = useMockedExecutor();
+
when(configuration.getConnectionString()).thenReturn("Endpoint=sb://localhost/");
+ doThrow(new IllegalStateException("cannot
connect")).when(client).start();
+
+ ServiceBusConsumer consumer = new ServiceBusConsumer(endpoint,
processor);
+
assertThatThrownBy(consumer::start).isInstanceOf(IllegalStateException.class).hasMessage("cannot
connect");
+
+ // the renewer was set up before the client failed to start; the stop
that BaseService.start makes after the
+ // failure shut it down
+ verify(executorServiceManager,
times(1)).newSingleThreadScheduledExecutor(any(), anyString());
+ verify(executorServiceManager, times(1)).shutdownNow(executor);
+ verify(renewalClient).close();
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void aFailedRenewalIsRetriedByTheNextRun(boolean callThrows) throws
Exception {
+ useMockedExecutor();
+ Instant t0 = Instant.now();
+ OffsetDateTime lockedUntil =
OffsetDateTime.ofInstant(t0.plusSeconds(18), ZoneOffset.UTC);
+ OffsetDateTime renewed = OffsetDateTime.ofInstant(t0.plusSeconds(60),
ZoneOffset.UTC);
+ when(message.getLockedUntil()).thenReturn(lockedUntil);
+ if (callThrows) {
+ // the call itself throws
+
when(renewalClient.renewMessageLock(any(ServiceBusReceivedMessage.class)))
+ .thenThrow(new IllegalStateException("receiver closed"))
+ .thenReturn(Mono.just(renewed));
+ } else {
+ // the renewal answers with a transient error, as the SDK reports
a busy server
+ ServiceBusException busy = new ServiceBusException(
+ new AmqpException(true,
AmqpErrorCondition.SERVER_BUSY_ERROR, "server busy", null),
+ ServiceBusErrorSource.RENEW_LOCK);
+
when(renewalClient.renewMessageLock(any(ServiceBusReceivedMessage.class)))
+ .thenReturn(Mono.error(busy))
+ .thenReturn(Mono.just(renewed));
+ }
+
+ try (ServiceBusConsumer consumer = new ServiceBusConsumer(endpoint,
processor)) {
+ consumer.doStart();
+ processMessageCaptor.getValue().accept(messageContext);
+
+ consumer.runLockRenewer(t0);
+ verify(renewalClient, times(1)).renewMessageLock(message);
+ // the entry is kept (CAMEL-26969)
+
assertThat(consumer.lockRenewerLockedUntil("exchange-1")).isEqualTo(lockedUntil);
+
+ // the failed renewal is no longer in flight: the next run renews
again, before the 10 seconds after which
+ // a renewal that has not answered is sent again
+ consumer.runLockRenewer(t0.plusSeconds(5));
+ verify(renewalClient, times(2)).renewMessageLock(message);
+
assertThat(consumer.lockRenewerLockedUntil("exchange-1")).isEqualTo(renewed);
+ }
+ }
+
+ @Test
+ void aRunThatThrowsDoesNotEndTheLaterRuns() throws Exception {
+ ScheduledExecutorService executor = useMockedExecutor();
+ when(uuidGenerator.generateExchangeUuid()).thenReturn("exchange-1",
"exchange-2");
+
when(renewalClient.renewMessageLock(any(ServiceBusReceivedMessage.class)))
+
.thenReturn(Mono.just(OffsetDateTime.now(ZoneOffset.UTC).plusSeconds(60)));
+
+ try (ServiceBusConsumer consumer = new ServiceBusConsumer(endpoint,
processor)) {
+ consumer.doStart();
+ ArgumentCaptor<Runnable> task = ArgumentCaptor.captor();
+ verify(executor).scheduleWithFixedDelay(task.capture(), anyLong(),
anyLong(), any());
+
+ // a message without a lock expiry makes the run throw (a
NullPointerException): it stands for anything
+ // thrown in a run, which would end a task of a
ScheduledExecutorService, and with it every later renewal
+ when(message.getLockedUntil()).thenReturn(null);
+ processMessageCaptor.getValue().accept(messageContext);
+ ArgumentCaptor<Exchange> exchange = ArgumentCaptor.captor();
+ verify(processor).process(exchange.capture(),
any(AsyncCallback.class));
+ assertThatCode(task.getValue()::run).doesNotThrowAnyException();
+
+ // that exchange completes; a later message is renewed by the next
run
+ Exchange first = exchange.getValue();
+ for (Synchronization sync :
first.getExchangeExtension().handoverCompletions()) {
+ sync.onComplete(first);
+ }
+ ServiceBusReceivedMessageContext secondContext = mock();
+ ServiceBusReceivedMessage second = mock();
+ when(secondContext.getMessage()).thenReturn(second);
+
when(second.getApplicationProperties()).thenReturn(Collections.emptyMap());
+
when(second.getLockedUntil()).thenReturn(OffsetDateTime.now(ZoneOffset.UTC).plusSeconds(15));
+ processMessageCaptor.getValue().accept(secondContext);
+
+ assertThatCode(task.getValue()::run).doesNotThrowAnyException();
+ verify(renewalClient, times(1)).renewMessageLock(second);
+ }
+ }
+}
diff --git
a/components/camel-azure/camel-azure-servicebus/src/test/java/org/apache/camel/component/azure/servicebus/ServiceBusConsumerTest.java
b/components/camel-azure/camel-azure-servicebus/src/test/java/org/apache/camel/component/azure/servicebus/ServiceBusConsumerTest.java
index cf0d3a614d5c..9c50edcda0c9 100644
---
a/components/camel-azure/camel-azure-servicebus/src/test/java/org/apache/camel/component/azure/servicebus/ServiceBusConsumerTest.java
+++
b/components/camel-azure/camel-azure-servicebus/src/test/java/org/apache/camel/component/azure/servicebus/ServiceBusConsumerTest.java
@@ -20,6 +20,7 @@ import java.time.Duration;
import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.Map;
+import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
@@ -37,8 +38,8 @@ import org.apache.camel.*;
import
org.apache.camel.component.azure.servicebus.client.ServiceBusClientFactory;
import org.apache.camel.spi.ExceptionHandler;
import org.apache.camel.spi.ExchangeFactory;
+import org.apache.camel.spi.ExecutorServiceManager;
import org.apache.camel.spi.HeaderFilterStrategy;
-import org.apache.camel.spi.PeriodTaskScheduler;
import org.apache.camel.spi.Synchronization;
import org.apache.camel.spi.UuidGenerator;
import org.apache.camel.support.DefaultExchange;
@@ -98,7 +99,8 @@ public class ServiceBusConsumerTest {
private final ExchangeFactory ef = mock();
private final HeaderFilterStrategy headerFilterStrategy = mock();
private final ExceptionHandler exceptionHandler = mock();
- private final PeriodTaskScheduler periodTaskScheduler = mock();
+ private final ExecutorServiceManager executorServiceManager = mock();
+ private final ScheduledExecutorService lockRenewerExecutor = mock();
private final UuidGenerator uuidGenerator = mock();
private final ServiceBusReceiverAsyncClient renewalClient = mock();
private final ArgumentCaptor<Consumer<ServiceBusReceivedMessageContext>>
processMessageCaptor = ArgumentCaptor.captor();
@@ -125,7 +127,8 @@ public class ServiceBusConsumerTest {
when(processor.process(exchangeCaptor.capture(),
asyncCallbackCaptor.capture())).thenReturn(true);
when(configuration.getHeaderFilterStrategy()).thenReturn(headerFilterStrategy);
when(configuration.getTopicOrQueueName()).thenReturn(TOPIC_OR_QUEUE_NAME);
-
when(ecc.getContextPlugin(PeriodTaskScheduler.class)).thenReturn(periodTaskScheduler);
+
when(context.getExecutorServiceManager()).thenReturn(executorServiceManager);
+ when(executorServiceManager.newSingleThreadScheduledExecutor(any(),
anyString())).thenReturn(lockRenewerExecutor);
when(context.getUuidGenerator()).thenReturn(uuidGenerator);
when(uuidGenerator.generateExchangeUuid()).thenReturn("test-exchange-id");
when(clientFactory.createServiceBusReceiverAsyncClient(any())).thenReturn(renewalClient);
@@ -630,7 +633,7 @@ public class ServiceBusConsumerTest {
try (ServiceBusConsumer consumer = new ServiceBusConsumer(endpoint,
processor)) {
consumer.doStart();
verify(clientFactory).createServiceBusReceiverAsyncClient(any());
- verify(periodTaskScheduler).schedulePeriodTask(any(), anyLong());
+ verify(lockRenewerExecutor).scheduleWithFixedDelay(any(),
anyLong(), anyLong(), any());
}
}
@@ -687,9 +690,9 @@ public class ServiceBusConsumerTest {
try (ServiceBusConsumer consumer = new ServiceBusConsumer(endpoint,
processor)) {
consumer.doStart();
- // capture the lock renewer task scheduled with PeriodTaskScheduler
+ // capture the lock renewer task scheduled on its executor
ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.captor();
-
verify(periodTaskScheduler).schedulePeriodTask(taskCaptor.capture(), anyLong());
+
verify(lockRenewerExecutor).scheduleWithFixedDelay(taskCaptor.capture(),
anyLong(), anyLong(), any());
Runnable lockRenewerTask = taskCaptor.getValue();
processMessageCaptor.getValue().accept(messageContext);
@@ -718,7 +721,8 @@ public class ServiceBusConsumerTest {
ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.captor();
ArgumentCaptor<Long> periodCaptor = ArgumentCaptor.captor();
-
verify(periodTaskScheduler).schedulePeriodTask(taskCaptor.capture(),
periodCaptor.capture());
+
verify(lockRenewerExecutor).scheduleWithFixedDelay(taskCaptor.capture(),
anyLong(), periodCaptor.capture(),
+ eq(TimeUnit.MILLISECONDS));
long periodMillis = periodCaptor.getValue();
// the lock expires 2 seconds after the earliest moment the
scheduler runs the renewer again
@@ -727,8 +731,8 @@ public class ServiceBusConsumerTest {
taskCaptor.getValue().run();
- // the next run comes at least periodMillis later (the period task
scheduler ticks once per second), the
- // renewal itself is a call to Service Bus: waiting for that run
leaves at most 2 seconds, or none at all
+ // the next run comes periodMillis after the end of this one, the
renewal itself is a call to Service Bus:
+ // waiting for that run leaves at most 2 seconds, or none at all
verify(renewalClient).renewMessageLock(message);
}
}
@@ -750,9 +754,10 @@ public class ServiceBusConsumerTest {
ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.captor();
ArgumentCaptor<Long> periodCaptor = ArgumentCaptor.captor();
-
verify(periodTaskScheduler).schedulePeriodTask(taskCaptor.capture(),
periodCaptor.capture());
- // two runs are at most the period plus a second apart (the period
task scheduler ticks once per second).
- // A lock that expires 2 seconds after two such gaps must be
renewed now: left to the next run, its first
+
verify(lockRenewerExecutor).scheduleWithFixedDelay(taskCaptor.capture(),
anyLong(), periodCaptor.capture(),
+ eq(TimeUnit.MILLISECONDS));
+ // two runs are the period apart, plus the time of a run (a second
here, more than a run takes). A lock
+ // that expires 2 seconds after two such gaps must be renewed now:
left to the next run, its first
// renewal could come with one gap and 2 seconds left, and a
transient failure of it would be retried with
// about 2 seconds left, too little for the call to Service Bus
long maxGapMillis = periodCaptor.getValue() + 1000;
@@ -788,7 +793,7 @@ public class ServiceBusConsumerTest {
consumer.doStart();
ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.captor();
-
verify(periodTaskScheduler).schedulePeriodTask(taskCaptor.capture(), anyLong());
+
verify(lockRenewerExecutor).scheduleWithFixedDelay(taskCaptor.capture(),
anyLong(), anyLong(), any());
processMessageCaptor.getValue().accept(messageContext);
taskCaptor.getValue().run();
@@ -809,7 +814,7 @@ public class ServiceBusConsumerTest {
consumer.doStart();
ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.captor();
-
verify(periodTaskScheduler).schedulePeriodTask(taskCaptor.capture(), anyLong());
+
verify(lockRenewerExecutor).scheduleWithFixedDelay(taskCaptor.capture(),
anyLong(), anyLong(), any());
processMessageCaptor.getValue().accept(messageContext);
taskCaptor.getValue().run();
@@ -851,10 +856,14 @@ public class ServiceBusConsumerTest {
consumer.doStart();
verify(clientFactory,
times(2)).createServiceBusReceiverAsyncClient(any());
- verify(periodTaskScheduler, times(2)).schedulePeriodTask(any(),
anyLong());
+ // an executor per start, the one of the first start was shut down by
the stop
+ verify(executorServiceManager,
times(2)).newSingleThreadScheduledExecutor(any(), anyString());
+ verify(executorServiceManager,
times(1)).shutdownNow(lockRenewerExecutor);
+ verify(lockRenewerExecutor, times(2)).scheduleWithFixedDelay(any(),
anyLong(), anyLong(), any());
consumer.doShutdown();
verify(renewalClient2).close();
+ verify(executorServiceManager,
times(2)).shutdownNow(lockRenewerExecutor);
}
@Test
diff --git
a/components/camel-azure/camel-azure-servicebus/src/test/java/org/apache/camel/component/azure/servicebus/dst/ServiceBusWorld.java
b/components/camel-azure/camel-azure-servicebus/src/test/java/org/apache/camel/component/azure/servicebus/dst/ServiceBusWorld.java
index 543e3fb45cf4..97c252efef20 100644
---
a/components/camel-azure/camel-azure-servicebus/src/test/java/org/apache/camel/component/azure/servicebus/dst/ServiceBusWorld.java
+++
b/components/camel-azure/camel-azure-servicebus/src/test/java/org/apache/camel/component/azure/servicebus/dst/ServiceBusWorld.java
@@ -58,25 +58,27 @@ import static org.mockito.Mockito.when;
* fail or take long, settlements fail.
* <p>
* The route is asynchronous, so processMessage returns at once and the lock
of a routed message is kept only by the
- * lock renewer of the consumer (maxAutoLockRenewDuration), which renews every
message whose lock expires before the run
- * after the next one of its period task (every 10 seconds, or a second
later). A message the consumer holds in
- * processMessage without routing it keeps its lock through the renewal of the
processor client while the call runs (see
- * FakeServiceBus [A]); the invariants count only the routed deliveries as
held by the consumer. The seed picks the lock
- * duration of the queue, the max delivery count, maxConcurrentCalls (with the
asynchronous route it bounds only the
- * concurrent processMessage calls), maxAutoLockRenewDuration (60 or 300
seconds), enableDeadLettering, the latency of
- * the renewals and the fault rates.
+ * lock renewer of the consumer (maxAutoLockRenewDuration), which renews every
message whose lock expires within 20
+ * seconds, on a thread of its own every 5 seconds. The fake answers a renewal
when it is called (its latency only moves
+ * the new expiry), so a renewal is never in flight across runs here: the rule
of the renewer for a renewal in flight is
+ * tested in ServiceBusConsumerLockRenewerTest, not in this world. A message
the consumer holds in processMessage
+ * without routing it keeps its lock through the renewal of the processor
client while the call runs (see FakeServiceBus
+ * [A]); the invariants count only the routed deliveries as held by the
consumer. The seed picks the lock duration of
+ * the queue, the max delivery count, maxConcurrentCalls (with the
asynchronous route it bounds only the concurrent
+ * processMessage calls), maxAutoLockRenewDuration (60 or 300 seconds),
enableDeadLettering, the latency of the renewals
+ * and the fault rates.
* <p>
* Properties: no lock is lost, and no message is delivered again, while the
consumer holds the message, unless an
* injected renewal of its lock failed less than one run of the lock renewer
before the lock expired, the route was
* stopped while it was processed (once a stop timed out the consumer stops
renewing, and the exchange goes on), or
* maxAutoLockRenewDuration passed. The consumer renews a lock again after a
transient renewal error (CAMEL-26969), but
- * only at its next run (CAMEL-27066): the lock renewer runs every 10 seconds
or a second later, so a transient renewal
- * error in the last 11 seconds of a lock (plus the latency of the renewal)
can still lose it. An earlier failed renewal
- * is no excuse, so a renewer that gave up after one error would fail. {@code
-Ddst.servicebus.strictRenew=true} does
- * not excuse a failed renewal at all, and still fails on some seeds until
CAMEL-27066 is fixed. The message of a
- * completed exchange is completed, unless its settlement failed, found its
lock lost under one of those excuses, or
- * came after the close() of a stop that timed out while the exchange was in
flight (by design); a graceful stop keeps
- * the processor client open for the exchanges in flight (the V2 processor of
the SDK closes its receiver on stop(), see
+ * only at its next run (CAMEL-27066): the lock renewer runs every 5 seconds,
so a transient renewal error late in a
+ * lock (within RENEWER_RUN_MILLIS plus the latency of the renewal) can still
lose it. An earlier failed renewal is no
+ * excuse, so a renewer that gave up after one error would fail. {@code
-Ddst.servicebus.strictRenew=true} does not
+ * excuse a failed renewal at all, and still fails on some seeds until
CAMEL-27066 is fixed. The message of a completed
+ * exchange is completed, unless its settlement failed, found its lock lost
under one of those excuses, or came after
+ * the close() of a stop that timed out while the exchange was in flight (by
design); a graceful stop keeps the
+ * processor client open for the exchanges in flight (the V2 processor of the
SDK closes its receiver on stop(), see
* FakeServiceBus; CAMEL-26970), so a settlement inside the graceful wait must
find it open; a message is completed only
* after its exchange completed, and abandoned or dead-lettered only after it
failed (or was in flight when a stop timed
* out, see below); once the faults cleared every message is completed or
dead-lettered; the consumer settles each
@@ -123,7 +125,10 @@ final class ServiceBusWorld {
* fixed.
*/
static final boolean STRICT_RENEW =
Boolean.getBoolean("dst.servicebus.strictRenew");
- /** The longest time between two runs of the lock renewer of the consumer:
every 10 seconds, or a second later. */
+ /**
+ * A bound on the time from a failed renewal to the next one: the lock
renewer of the consumer runs every 5 seconds
+ * and waits for a renewal in flight up to 10 seconds; the bound is kept
loose.
+ */
static final long RENEWER_RUN_MILLIS = 11_000;
private final Dst dst;
@@ -359,8 +364,8 @@ final class ServiceBusWorld {
/**
* An injected renewal failure excuses the loss of the lock only when the
next run of the lock renewer comes too
- * late to renew it: the renewer runs every 10 seconds or a second later
(the period task scheduler ticks every
- * second), and the renewal itself takes up to renewLatencyMaxMillis.
+ * late to renew it: the renewer runs again within RENEWER_RUN_MILLIS (on
a thread of its own), and the renewal
+ * itself takes up to renewLatencyMaxMillis.
*/
private void renewFault(String delivery, long lockedUntil) {
if (lockedUntil < 0) {
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 5dc182e93920..f8857a8e1a20 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
@@ -7900,6 +7900,17 @@ in full and rejected by the broker.
A settlement request the broker rejects is now reported through the consumer's
exception handler.
+=== camel-azure-servicebus - the Camel lock renewer runs on a thread of its own
+
+A consumer in peek-lock mode with `maxAutoLockRenewDuration` above 0 (the
default) and without sessions now renews the
+locks of its messages on a thread of its own, named
`ServiceBusLockRenewer[<topic or queue name>]`. The thread comes
+from the thread pool settings of the CamelContext, starts with the consumer
and ends when the consumer stops. Before,
+the renewer was a task of the period task scheduler of the CamelContext, on
one thread shared with the other periodic
+tasks (such as the secret refresh tasks of the vaults): a slow task there
could hold up the renewals until a lock
+expired, and every start of the consumer left one more task registered until
the CamelContext stopped. There is now one
+more thread per such consumer in thread dumps and in the thread pools listed
over JMX, and the renewer is no longer
+listed among the period tasks. Routes need no change.
+
=== camel-azure-key-vault - the body after deleteSecret, and a Map or a POJO
given to createSecret
The `deleteSecret` operation now sets the `DeletedSecret` of the Azure SDK as
the message body, with the recovery id and