gnodet-bot commented on code in PR #31133:
URL: https://github.com/apache/camel/pull/31133#discussion_r4743518993
##########
components/camel-azure/camel-azure-servicebus/src/main/java/org/apache/camel/component/azure/servicebus/ServiceBusConsumer.java:
##########
@@ -80,8 +81,11 @@ public class ServiceBusConsumer extends DefaultConsumer
implements ShutdownAware
private ServiceBusProcessorClient client;
private boolean clientCloseable;
private ServiceBusReceiverAsyncClient renewalClient;
+ private ServiceBusSessionReceiverAsyncClient sessionRenewalClient;
private volatile LockRenewer lockRenewer;
private ScheduledExecutorService lockRenewerExecutor;
+ private SessionLockRenewer sessionLockRenewer;
Review Comment:
⚠️ **Missing `volatile`:** The adjacent `lockRenewer` field on line 85 is
`volatile` for a reason — it is written by `doStart()` on the Camel lifecycle
thread and read by `processMessage()` on the Service Bus processor callback
thread. `sessionLockRenewer` is accessed the same way and must carry the same
`volatile` guarantee; without it the processor thread is not guaranteed to
observe the assignment and may silently skip session lock renewal.
```suggestion
private volatile SessionLockRenewer sessionLockRenewer;
```
##########
components/camel-azure/camel-azure-servicebus/src/main/java/org/apache/camel/component/azure/servicebus/ServiceBusConsumer.java:
##########
@@ -531,6 +579,204 @@ private record LockRenewerEntry(
}
}
+ /**
+ * Renews the session lock for session-enabled consumers in PEEK_LOCK mode
with async routes. Session-enabled queues
+ * and subscriptions lock the session rather than individual messages, so
{@link LockRenewer} does not apply. This
+ * renewer accepts a session-bound {@link ServiceBusReceiverAsyncClient}
for each active session and calls
+ * {@code renewSessionLock()} on it periodically until all exchanges of
that session complete or
+ * {@code maxAutoLockRenewDuration} elapses.
+ */
+ private class SessionLockRenewer implements Runnable {
+
+ private final ServiceBusSessionReceiverAsyncClient
sessionReceiverClient;
+ private final Duration maxRenewDuration;
+ private final AtomicBoolean run = new AtomicBoolean(true);
+ /**
+ * One entry per active session. The session-bound receiver is shared
by all in-flight exchanges of the same
+ * session (the session processor delivers at most maxConcurrentCalls
messages per session at a time, but they
+ * all belong to the same session so one receiver suffices for session
lock renewal).
+ */
+ private final Map<String, SessionRenewerEntry> sessions = new
ConcurrentHashMap<>();
+ /** Exchange-to-sessionId mapping so the completion callback can
decrement the reference count. */
+ private final Map<String, String> exchangeSession = new
ConcurrentHashMap<>();
+
+ SessionLockRenewer(ServiceBusSessionReceiverAsyncClient
sessionReceiverClient, Duration maxRenewDuration) {
+ this.sessionReceiverClient = sessionReceiverClient;
+ this.maxRenewDuration = maxRenewDuration;
+ }
+
+ public void add(Exchange exchange, ServiceBusReceivedMessage message) {
+ String sessionId = message.getSessionId();
+ if (sessionId == null) {
+ LOG.warn(
+ "Session-enabled consumer received a message without a
session ID; skipping session lock renewal");
+ return;
+ }
+
+ exchangeSession.put(exchange.getExchangeId(), sessionId);
+ exchange.getExchangeExtension().addOnCompletion(new
SynchronizationAdapter() {
+ @Override
+ public void onComplete(Exchange exchange) {
+ remove(exchange);
+ }
+
+ @Override
+ public void onFailure(Exchange exchange) {
+ remove(exchange);
+ }
+
+ private void remove(Exchange exchange) {
+ String sid =
exchangeSession.remove(exchange.getExchangeId());
+ if (sid != null) {
+ // decrement and remove atomically inside
computeIfPresent, so a concurrent add() on the same
+ // key (which increments inside compute()) cannot
observe a zero refCount and a live entry at
+ // the same time, nor hold a reference to a receiver
that has just been closed
+ final boolean[] closed = { false };
+ sessions.computeIfPresent(sid, (k, entry) -> {
+ int remaining = entry.refCount.decrementAndGet();
+ LOG.trace(
+ "Removing exchangeId {} from
SessionLockRenewer for session {}, {} exchanges left",
+ exchange.getExchangeId(), sid, remaining);
+ if (remaining <= 0) {
+ // no more in-flight exchanges for this
session: release the receiver
+ closed[0] = true;
+ entry.receiver.close();
+ return null;
+ }
+ return entry;
+ });
+ if (closed[0]) {
+ LOG.debug("Closed session receiver for session
{}", sid);
+ }
+ }
+ }
+ });
+
+ sessions.compute(sessionId, (sid, existing) -> {
+ if (existing != null) {
+ // another exchange for the same session is already
tracked: share the receiver
+ existing.refCount.incrementAndGet();
+ LOG.trace("Sharing session receiver for session {}
(refCount={})", sid,
+ existing.refCount.get());
+ return existing;
+ }
+ // first exchange for this session: accept a session-bound
receiver
+ try {
+ ServiceBusReceiverAsyncClient receiver =
sessionReceiverClient.acceptSession(sid).block();
+ LOG.debug("Accepted session receiver for session {}", sid);
+ return new SessionRenewerEntry(receiver,
message.getLockedUntil(), Instant.now());
+ } catch (Exception e) {
+ // If we cannot accept the session (e.g. it was already
claimed), log a warning and skip
+ // renewal for this session. The message processing
continues; the session lock may expire.
+ LOG.warn(
+ "Cannot accept session {} for lock renewal;
session lock renewal will not run: {}",
+ sid, e.getMessage());
+ exchangeSession.remove(exchange.getExchangeId());
+ return null;
+ }
+ });
+ }
+
+ public void cancel() {
+ run.set(false);
+ // close all open session receivers
+ for (Map.Entry<String, SessionRenewerEntry> e :
sessions.entrySet()) {
+ try {
+ e.getValue().receiver.close();
+ } catch (Exception ex) {
+ LOG.debug("Error closing session receiver for session {}:
{}", e.getKey(), ex.getMessage());
+ }
+ }
+ sessions.clear();
+ exchangeSession.clear();
+ }
+
+ @Override
+ public void run() {
+ if (!run.get()) {
+ return;
+ }
+
+ Instant now = Instant.now();
+ for (Map.Entry<String, SessionRenewerEntry> mapEntry :
sessions.entrySet()) {
+ String sessionId = mapEntry.getKey();
+ SessionRenewerEntry entry = mapEntry.getValue();
+
+ // skip if max renewal duration exceeded (measured from when
the first exchange arrived)
+ Duration elapsed = Duration.between(entry.startTime, now);
+ if (elapsed.compareTo(maxRenewDuration) >= 0) {
+ LOG.debug("Max session lock renewal duration exceeded for
session {}, stopping renewal",
+ sessionId);
+ // do not remove the entry here — the exchange completion
callbacks will close the receiver
+ continue;
+ }
+
+ // renew if the session lock expires within
LOCK_RENEW_BEFORE_EXPIRY_SECONDS
+ Instant lockExpiry = entry.sessionLockedUntil.toInstant();
+ if
(now.plusSeconds(LOCK_RENEW_BEFORE_EXPIRY_SECONDS).isAfter(lockExpiry)) {
+ entry.receiver.renewSessionLock()
+ .subscribe(
+ newLockedUntil -> {
+ LOG.trace("Renewed session lock for
session {}, new expiry: {}",
+ sessionId, newLockedUntil);
+ sessions.computeIfPresent(sessionId,
+ (k, e) -> new
SessionRenewerEntry(
+ e.receiver,
newLockedUntil,
+ e.startTime,
e.refCount));
+ },
+ error -> {
+ if (isTransient(error)) {
+ LOG.warn(
+ "Failed to renew session
lock for session {}, will try again: {}",
+ sessionId,
error.getMessage());
+ } else {
+ LOG.warn("Failed to renew session
lock for session {}: {}",
+ sessionId,
error.getMessage());
+ // non-transient: stop renewing
(the session lock is lost);
+ // remove the entry and close the
receiver here — the exchange
+ // completion callback tolerates
an absent sessions entry
+ SessionRenewerEntry removed =
sessions.remove(sessionId);
+ if (removed != null) {
+ removed.receiver.close();
Review Comment:
⚠️ **Same atomicity gap as the `computeIfPresent` fix on the completion
path.** The comment on the completion callback explains the invariant clearly —
the decrement and removal must happen atomically inside `computeIfPresent` to
prevent a concurrent `add()` from observing a zero refCount and a live entry at
the same time, or holding a reference to a receiver that is about to be closed.
This error handler breaks the same invariant with a bare `sessions.remove()` +
`receiver.close()`.
```suggestion
sessions.computeIfPresent(sessionId, (k, entry) -> {
entry.receiver.close();
return null;
});
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]