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

   # Description
   
   [CAMEL-27534](https://issues.apache.org/jira/browse/CAMEL-27534)
   
   With `asyncStartListener=true`, `JmsConsumer.doStart` submits a task that 
initializes and starts the listener container later. Since CAMEL-26536 that 
task checks that the consumer still owns the container, so a stop while it is 
pending is handled. A suspend or a resume while it is pending was not, and 
neither was a suspend and resume after the task failed:
   
   - **A route suspended while the start was pending kept consuming.** 
`doSuspend` stopped a container that was not started yet, and then the task 
started it. The route and the consumer were Suspended, the listener container 
ran, and a message sent to the queue reached the suspended route.
   - **A route resumed while the start was pending got doubled consumers.** 
`doResume` saw `initialized=false` and called `doStart` again. The endpoint 
counted the same container twice (`onListenerContainerStarting`), and a second 
start task was submitted. Both tasks called `afterPropertiesSet()`, and 
Spring's `DefaultMessageListenerContainer` schedules another 
`concurrentConsumers` invokers on every initialization (`doInitialize` has no 
"already initialized" check, checked with javap in spring-jms 7.0.9 and 7.1.0). 
With `concurrentConsumers=1` the container ran 2 consumers: on a topic without 
a shared subscription each message was processed twice, and on a queue two 
messages could be processed at the same time. The extra count stayed after the 
route was stopped, so `JmsEndpoint.stop()` and `shutdown()` never stopped the 
endpoint.
   - **Suspend and resume after a failed async start did the same.** With 
`testConnectionOnStartup=true` and the broker unreachable, the task had already 
initialized the container when the connection test failed; it only logs the 
error. A suspend and resume then ran `doStart` again: the container was counted 
twice and initialized twice.
   
   The route controller, JMX and route policies all suspend and resume routes, 
and the start window is long exactly when `asyncStartListener` is useful: a 
slow or unreachable broker.
   
   The three are in one PR because they are one gap in one place: the async 
start task and `doSuspend`/`doResume` did not coordinate. The fix is the same 
state, guarded by the same `containerLock` that CAMEL-26536 added, and the 
failed-start case uses the same "start the same container again, without 
counting it" path as the resume-while-pending case.
   
   ## The change
   
   All in `JmsConsumer`:
   
   - Two fields guarded by `containerLock`: whether `doStart` counted the 
current listener container on the endpoint, and whether its asynchronous start 
task has not checked the consumer status yet. `detachListenerContainer()` 
clears both with the container.
   - The start task initializes the container only when it is not active yet 
(`isActive()`), so a container is never initialized twice.
   - Then the task checks the status once, under `containerLock`: it marks the 
consumer initialized, clears the pending flag, and starts the container only 
when the consumer is not suspending or suspended. A consumer suspended before 
this check is started by its resume.
   - After `start()` the task checks once more under the lock: if the consumer 
was suspended in the meantime it stops the container (a `doSuspend` that ran 
before `start()` could not). The task calls `start()` at most once and has no 
loop.
   - `doResume`:
     - the task has not checked the status yet: it only lets the status change; 
the task starts the container, as the consumer is no longer suspended;
     - `initialized=false` and the container was counted (its start failed, the 
`testConnectionOnStartup` case): it starts the same container again, 
asynchronously with `asyncStartListener=true`, without counting it again, and 
logs one INFO line;
     - `initialized=false` otherwise (never started): it calls `doStart` as 
before;
     - `initialized=true`: it starts the container as before. This now also 
covers a resume while the task is still in `start()`: a suspend in that window 
may have stopped the container after the task started it, and the resume starts 
it again.
   - `doSuspend` is unchanged.
   
   Why the order holds without a lock in `doSuspend`: `BaseService` sets 
SUSPENDING before `doSuspend` and STARTING before `doResume`, and runs suspend, 
resume and stop one at a time. If the task's last check sees the consumer 
suspended, it stops the container under the lock; a resume that comes next 
reads `initialized` under the same lock, so it starts the container only after 
that stop. If the check sees the consumer not suspended, the last suspend (if 
any) has finished its stop and the resume that followed started the container 
after it.
   
   A container can still run for a moment while the consumer is suspended: the 
status check and `start()` are not atomic, and the task's check after `start()` 
stops it. Calling `start()` under the lock would close that window, but a stop 
or suspend would then wait for a slow broker connect, so I left it out.
   
   With `asyncStartListener=false` the same code runs on the lifecycle thread, 
under `BaseService`'s lock, so no suspend or resume runs at the same time: the 
status check always finds the consumer starting, and the check after `start()` 
never stops the container. What changes there: `afterPropertiesSet()` is 
skipped when the container is already active (only possible when 
`prepareAndStartListenerContainer()` is called again on the same container), 
and `initialized` is set before `start()` and reset when the start throws, so 
the state after a failed start is the same as before.
   
   ## Tests
   
   New `JmsAsyncStartListenerSuspendResumeTest` (package-private, JUnit 
assertions as in the module, embedded Artemis broker from the module's test 
infra, no sleeps). It reuses the held executor of 
`JmsAsyncStopListenerRestartTest`: the consumer's start and stop tasks are kept 
and run by the test, so each interleaving is deterministic. A connection 
factory wrapper can fail every connection, as if the broker were down. Some 
tests use a listener container that runs a hook when it is initialized, or 
before or after it starts, to suspend or resume the route while the task runs, 
and check that the hook ran. The CamelContext creates the consumers, with their 
listener containers, when it starts, so each test first stops both routes: it 
then starts its route with a new listener container made from its own 
configuration, and does not depend on the tests that ran before it.
   
   - `testSuspendWhileAsyncStartIsPending`: start, suspend, then the start task 
runs. The listener container is not running, and a message sent while suspended 
is not consumed (1 s assert period). After the resume that message is consumed, 
the container runs `concurrentConsumers` invokers and is counted once.
   - `testSuspendWhileAsyncStartIsStartingTheListenerContainer`: the route is 
suspended after the task's status check and before the container starts. The 
task's check after `start()` stops it; the same checks as above follow.
   - `testSuspendAndResumeWhileAsyncStartIsStartingTheListenerContainer`: the 
route is suspended and resumed after the container started and before the 
task's second check. The resume starts the stopped container again; no second 
task, one set of invokers, counted once, consumes, nothing counted after the 
stop.
   - `testResumeWhileAsyncStartIsPending`: start, suspend, resume before the 
task runs. One task is pending (not two), the container runs 
`concurrentConsumers` invokers, it is counted once, it consumes, and after the 
route is stopped nothing is counted.
   - `testResumeWhileAsyncStartIsInitializingTheListenerContainer`: start, 
suspend, and the route is resumed while the task initializes the container, 
before its status check. No second task is submitted, and the task starts the 
container.
   - `testResumeWhileAsyncStartIsPendingOnTopicProcessesEachMessageOnce`: the 
same as the pending resume on a topic route with `concurrentConsumers=1` and no 
shared subscription. Each published message is processed once (checked for 1 s 
after the last one), and one set of invokers runs.
   - `testSuspendAndResumeAfterFailedAsyncStart`: 
`testConnectionOnStartup=true` and every connection fails while the first start 
task runs, so it only logs. After a suspend and resume, one new start task 
runs, the container runs `concurrentConsumers` invokers, is counted once, 
consumes, and nothing is counted after the stop.
   - `testAsyncStartWhileCamelContextIsStoppingStartsTheListenerContainerOnce`: 
the start task runs while the CamelContext is stopping, with 
`shutdownRoute(Defer)` on the JMS route and an inflight exchange on another 
route, so the consumer is not suspended yet. Camel's listener container does 
not run while the context is stopping (`runningAllowed()` is false). The task 
must call `start()` once.
   - 
`testSynchronousStartWhileEndpointIsNotStartedStartsTheListenerContainerOnce`: 
`asyncStartListener=false`, a consumer started while its endpoint is not 
started (`runningAllowed()` false again). `start()` returns, the consumer is 
Started, and the container was started once.
   - `testSuspendAndResumeWithSynchronousStart`: a control with 
`asyncStartListener=false`, which also passes on main.
   
   In the two "starts once" tests the listener container counts its starts and 
throws on a second one, so a start that repeats fails fast instead of hanging. 
A variant of this fix that checks `container.isRunning()` after `start()` and 
starts again while it is false loops without end in both cases, because the 
container's `isRunning()` includes `runningAllowed()`: with that variant both 
tests fail (2 starts) and the other 8 pass.
   
   On main, 7 of the 10 fail: the suspended container runs and consumes, two 
start tasks, two sets of invokers, and on the topic every message processed 
twice; the synchronous control and the two "starts once" tests pass. The same 7 
fail when each test runs alone, in its own JVM, and the variant above fails the 
same two "starts once" tests alone. Negative controls, each taking one part out 
of the fix: initializing the container even when it is active fails the 
failed-start test (2 sets of invokers); no stop after `start()` when suspended 
fails `testSuspendWhileAsyncStartIsStarting...`; marking the consumer 
initialized only after `start()` (so a resume during `start()` leaves the start 
to the task) fails `testSuspendAndResumeWhileAsyncStartIsStarting...` (no 
running container).
   
   With the change: the new class 20 times in one JVM: 200/200; each of its 10 
tests alone, in its own JVM: 10/10; the related ones 
(`JmsAsyncStopListenerRestartTest`, `JmsSuspendResumeTest`, 
`JmsAsyncStartListenerTest`, `JmsLifecycleIssueTest`): 9/9. camel-jms unit 
tests: 561 run, 11 skipped, 0 failures. The formatter and import-sort plugins 
made no changes.
   
   camel-sjms has the same `asyncStartListener` option but not this problem: 
its `doResume` never calls `doStart`, and its start task suspends the listener 
container when the consumer was suspended meanwhile.
   
   Model: found with a TLA+ model of the consumer lifecycle (start, stop, 
suspend and resume on the lifecycle thread, against the asynchronous start and 
stop tasks, with failed connection tests). The model abstracts the container's 
`isRunning()` as "started", so it could not see the repeated start above; this 
version does not ask the container whether it runs. I did not run the model 
checker on this version.
   
   Not changed:
   
   - A failed async start still leaves a started route without a running 
listener; the `asyncStartListener` option documents this ("You can then restart 
the route to retry"). A suspend and resume now also retries it, on the same 
listener container, without counting or initializing it again.
   - The short window above, and the one after a stop that CAMEL-26536 handles 
the same way.
   - The task's check after `start()` holds `containerLock` while it stops the 
container. With `consumerType=Simple` and a JMS client whose 
`Connection.stop()` waits for running `onMessage` calls (as the JMS 
specification asks), a listener thread that resumes its own route at that 
moment (a route policy) would wait for the lock in `doResume` while the stop 
waits for that listener: a deadlock. It needs a suspend within the start 
window, a message already in flight, and a resume from that message's thread 
during the stop. With the Artemis client it does not happen: in a test of 
exactly this, `stop()` returned at once while `onMessage` was still running, 
the resume took the lock right after, and the route ended Started with a 
running container. Another JMS client could still block there. Stopping outside 
the lock would let a resume start the container before the stop.
   - `doSuspend`, and `doResume` with `initialized=true`, stop and start the 
container as before.
   - No upgrade guide entry: nothing changes for a route that is not suspended 
or resumed during an asynchronous start, and in that case a suspended route no 
longer consumes and a resumed one runs the configured number of consumers.
   
   Backport: this change builds on CAMEL-26536 (`containerLock` and the 
ownership check of the start task), which is on main only. On camel-4.22.x, 
camel-4.18.x and camel-4.14.x, `doResume` also calls `doStart` when 
`initialized` is false and the start task does not look at a suspend, so they 
have the same problem; a backport needs CAMEL-26536 first.
   
   # 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-27534](https://issues.apache.org/jira/browse/CAMEL-27534).
   
   # 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 and tested the affected module, including the formatter and 
import-sort plugins. I did not run the full root build.)
   
   # 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