allthingssecurity opened a new pull request, #30831:
URL: https://github.com/apache/camel/pull/30831

   # Description
   
   [CAMEL-27510](https://issues.apache.org/jira/browse/CAMEL-27510)
   
   The Camel lock renewer of the Service Bus consumer (peek-lock mode, 
`maxAutoLockRenewDuration` above 0, no sessions: on by default) now runs on a 
thread of its own instead of the shared timer thread of the period task 
scheduler. This reverses a choice of CAMEL-27066, whose commit kept the renewer 
on that task with "no new thread, timer or Reactor delay" and noted that the 
margins are smaller when the shared timer thread is late. The shared timer 
thread turned out to be the cause of the two problems below, so the renewer 
gets its own thread.
   
   The renewer was a task of `PeriodTaskScheduler.schedulePeriodTask`. That 
scheduler calls all its tasks one after another on one thread (the 
`TimerListenerManager` of the CamelContext), and has no way to remove a task:
   
   - a periodic task that is slow on that thread 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. The periodic tasks there include the 
secret refresh tasks of the vaults, which make remote calls, and the context 
reload such a task starts on that same thread, which waits up to the shutdown 
timeout for the exchanges in flight;
   - `doStop` only set a flag, so every start of the consumer (route restart, 
supervised restart, context reload) left one more renewer task registered until 
the CamelContext stopped. Each kept the stopped consumer (and its endpoint) 
reachable and ran every 5 seconds for nothing.
   
   Change (`ServiceBusConsumer`):
   
   - the renewer runs on a single-thread scheduled executor of the consumer, 
from the `ExecutorServiceManager` of the CamelContext, named 
`ServiceBusLockRenewer[<topic or queue name>]`. It is created in `doStart` and 
shut down in `doStop` and `doShutdown` with `shutdownNow`: a run only 
subscribes renewals (their 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. A new executor per start, as nothing of the previous start waits on the 
old one.
   - the renewer is set up before `client.start()`: it was 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 the renewer and its 
executor down.
   - it runs 5 seconds after the end of its previous run, and still renews a 
lock that expires within 20 seconds (CAMEL-27066): the first renewal comes with 
about 15 seconds left, a retry after a transient error with about 10.
   - one thread per consumer rather than one shared per component or endpoint: 
the renewer then depends only on its own consumer and starts and stops with it, 
and the consumer already has the threads of its processor client.
   - an exception or an `Error` in a run is logged (one WARN line, the stack 
trace at DEBUG) 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.
   - 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, `amqpRetryOptions`), 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, the first renewal 
is sent with 10 to 15 seconds left and the retry of a hung one with 0 to 5 
seconds left, where main sent one more 5 seconds earlier (with 5 to 10 seconds 
left). Before, a slow broker got one more renewal of the same message on every 
run. The answer, a transient error, or a call that throws clears the mark at 
once, 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 to renew and the in-flight mark are taken in one 
`computeIfPresent`, so a callback or the completion of the exchange in between 
is not lost. A late answer still does not add a completed exchange 
(`computeIfPresent`, as before), and a transient error still keeps the entry 
(CAMEL-26969). The graceful stop of CAMEL-26970 is unchanged.
   - `processMessage` reads the `lockRenewer` field once (now volatile). It 
read it twice, so a stop between the two reads gave a `NullPointerException` 
(the message was then abandoned).
   - two package-private methods for the tests: one run of the renewer at a 
given time, and the lock expiry it holds for an exchange.
   
   Behaviour for users: one more thread per such consumer, visible in thread 
dumps and in the thread pools listed over JMX, and the renewer is no longer 
listed among the period tasks of the CamelContext. The upgrade guide for 4.24 
has an entry. Session consumers, receive-and-delete mode and a user-provided 
processor client have no Camel lock renewer and are unchanged. The other users 
of `schedulePeriodTask` are tasks of the CamelContext registered once (the 
vault refresh tasks, the Kamelet reloader), so no other consumer has the same 
leak.
   
   Not changed:
   - two transient renewal errors in a row late in a lock can still lose it: 
the second retry comes with about 5 seconds left minus the time of the call. 
This is the margin documented by CAMEL-27066. Service Bus asks for a back-off 
of about 10 seconds after a ServerBusy error, so it can happen under throttling.
   - a `VirtualMachineError` thrown by a task of the `TimerListenerManager` 
still ends that timer, which is deliberate there (CAMEL-26906). The renewer no 
longer depends on that timer; the same error in the renewer's own run ends its 
own task.
   
   Tests:
   
   - new `ServiceBusConsumerLockRenewerTest` (package-private, mocked Service 
Bus clients, a real `DefaultCamelContext` for the first two):
     - `stopEndsTheLockRenewerAndItsThread`: 5 stop/start cycles of one 
consumer and 3 more consumers started, stopped and shut down leave no renewer 
task on the period task scheduler and no renewer thread; a started consumer has 
one renewer thread, none after its stop.
     - `aBlockedSharedTimerDoesNotHoldUpTheRenewal`: another periodic task 
blocks the shared timer thread for the whole test; a lock with 15 seconds left 
is renewed before it expires (at the first run, 5 seconds after the start).
     - `slowBrokerGetsOneRenewalAtATimeAndALateAnswerDoesNotMoveTheExpiryBack`: 
runs at given times against a broker that answers only when the test says so: 
one renewal while it has not answered, one more after 10 seconds, answers 
newest first leave the later expiry, and the period task scheduler is not used.
     - `aMessageDeliveredAsTheClientStartsIsTracked`: the processor client 
delivers a message inside `start()`; the renewer tracks it and renews its lock.
     - `aFailedStartShutsTheLockRenewerDown`: `client.start()` throws; 
`consumer.start()` fails, and the stop it makes shuts the renewer's executor 
down and closes the renewal client.
     - `aFailedRenewalIsRetriedByTheNextRun` (a transient error answer, and a 
call that throws): the entry is kept (CAMEL-26969), the in-flight mark is 
cleared, and the next run, 5 seconds later, renews again.
     - `aRunThatThrowsDoesNotEndTheLaterRuns`: a run of the scheduled task that 
hits an exception returns normally, and the next run renews another message.
   - `ServiceBusConsumerTest` captures the renewer from the executor instead of 
the period task scheduler, and `stopStartCycleRecreatesLockRenewer` checks an 
executor per start that the stop and the shutdown shut down.
   - the comments of the DST world describe the new thread model, and say that 
the world does not exercise the in-flight rule (its fake Service Bus answers a 
renewal when it is called).
   
   The first 3 tests of the new class fail on main (checked by running them 
against the `ServiceBusConsumer` of main with only the two test methods added): 
8 renewer tasks left registered, no renewal within 14 seconds while the timer 
is blocked, and two renewals in flight. With only the forward-only store taken 
out, the third test fails on the lock expiry. Each of the other new tests fails 
when only the change it covers is taken out: with the renewer set up after 
`client.start()` again, the first two of the four above fail (the message is 
not tracked; no executor was created to shut down); without `stopLockRenewer()` 
in `doStop`, the failed start leaves the executor running; without clearing the 
in-flight mark on a failed renewal, both cases of 
`aFailedRenewalIsRetriedByTheNextRun` fail (no second renewal 5 seconds later); 
without the catch in the run, `aRunThatThrowsDoesNotEndTheLaterRuns` fails. 
With the change: the camel-azure-servicebus unit tests pass (89 run, 0 
failures); `Serv
 iceBusConsumerLockRenewerTest` and `ServiceBusConsumerTest` pass 20 of 20 runs 
(1040 tests). The DST test still passes 1000 seeds, which shows only that 
nothing else regressed: its fake Service Bus answers a renewal when it is 
called, so a renewal is never in flight across runs there, and the in-flight 
rule and the forward-only expiry are tested only by 
`ServiceBusConsumerLockRenewerTest`. The integration tests need a Service Bus 
emulator and were not run locally (CI runs them).
   
   Found with a TLA+ model of the renewer, the shared timer thread, stop/start 
and the reload that runs on that thread, and reproduced against the real 
consumer.
   
   # Target
   
   - [x] I checked that the commit is targeting the correct branch (Camel 4 
uses the `main` branch)
   
   # Tracking
   - [x] If this is a large change, bug fix, or code improvement, I checked 
there is a [JIRA issue](https://issues.apache.org/jira/browse/CAMEL) filed for 
the change (usually before you start working on it): 
[CAMEL-27510](https://issues.apache.org/jira/browse/CAMEL-27510).
   
   # Apache Camel coding standards and style
   
   - [x] I checked that each commit in the pull request has a meaningful 
subject line and body.
   - [ ] I have run `mvn clean install -DskipTests` locally from root folder 
and I have committed all auto-generated changes.
     (I built camel-azure-servicebus and the core modules offline with the 
formatter and import-sort plugins and ran the tests listed above. I did not run 
the full root build. No option or generated file changed.)
   
   # AI-assisted contributions
   
   - [x] If this PR includes AI-generated code, commits have proper 
co-authorship attribution (e.g., `Co-authored-by` trailers) and the PR 
description identifies the AI tool used.
     This PR was prepared with Claude Code (Claude Opus 5.5). The commit 
carries a `Co-Authored-By` trailer.
   
   _Claude Code on behalf of allthingssecurity_
   
   🤖 Generated with [Claude Code](https://claude.com/claude-code)
   


-- 
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]

Reply via email to