davsclaus commented on code in PR #2046:
URL: 
https://github.com/apache/camel-spring-boot/pull/2046#discussion_r4302943168


##########
core/camel-spring-boot/src/main/java/org/apache/camel/spring/boot/statestore/SpringCacheKeyValueRepositoryAutoConfiguration.java:
##########
@@ -0,0 +1,44 @@
+/*
+ * 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.spring.boot.statestore;
+
+import org.apache.camel.spi.KeyValueRepository;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
+import 
org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.cache.CacheManager;
+import org.springframework.context.annotation.Bean;
+
+@AutoConfiguration
+@ConditionalOnClass({ CacheManager.class, KeyValueRepository.class })
+@ConditionalOnProperty(prefix = "camel.spring.cache.state-store", name = 
"enabled", havingValue = "true")
+@AutoConfigureAfter(name = {
+    "org.springframework.boot.cache.autoconfigure.CacheAutoConfiguration",
+    "org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration"
+})

Review Comment:
   The Spring Boot 3 name never resolves on Spring Boot 4.1.1, so it can go. 
The other auto-configurations in this module declare their order on 
`@AutoConfiguration` itself; `CacheAutoConfiguration` does the same. The 
`AutoConfigureAfter` import goes away with it.
   
   ```suggestion
   @AutoConfiguration(afterName = 
"org.springframework.boot.cache.autoconfigure.CacheAutoConfiguration")
   @ConditionalOnClass({ CacheManager.class, KeyValueRepository.class })
   @ConditionalOnProperty(prefix = "camel.spring.cache.state-store", name = 
"enabled", havingValue = "true")
   ```



##########
core/camel-spring-boot/src/main/java/org/apache/camel/spring/boot/statestore/SpringCacheKeyValueRepositoryAutoConfiguration.java:
##########
@@ -0,0 +1,44 @@
+/*
+ * 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.spring.boot.statestore;
+
+import org.apache.camel.spi.KeyValueRepository;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
+import 
org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.cache.CacheManager;
+import org.springframework.context.annotation.Bean;
+
+@AutoConfiguration
+@ConditionalOnClass({ CacheManager.class, KeyValueRepository.class })
+@ConditionalOnProperty(prefix = "camel.spring.cache.state-store", name = 
"enabled", havingValue = "true")

Review Comment:
   Making this opt-in fixes the upgrade problem, thanks. The name and the docs 
still describe a state-store setting, though. Once it is set, 
`AggregateProcessor`, `IdempotentConsumerReifier` and `CacheReifier` also pick 
this bean up (`findSingleByType(KeyValueRepository.class)`) when they have no 
repository of their own. The review summary lists the effects: aggregators log 
a recovery WARN every 5 seconds (or do not start with `completionTimeout`), the 
Cache EIP `ttl` is ignored, and `state-store` `clear` empties the shared cache. 
Could the docs, and ideally the property name, say what turning it on does?



##########
core/camel-spring-boot/src/main/java/org/apache/camel/spring/boot/statestore/SpringCacheKeyValueRepository.java:
##########
@@ -0,0 +1,161 @@
+/*
+ * 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.spring.boot.statestore;
+
+import java.time.Duration;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.camel.spi.KeyValueRepository;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.cache.Cache;
+import org.springframework.cache.CacheManager;
+import org.springframework.util.Assert;
+
+/**
+ * An Apache Camel {@link KeyValueRepository} adapter backed by Spring's 
{@link CacheManager}[cite: 2].
+ *
+ * <h3>Design Constraints &amp; Backend Behavior:</h3>
+ * <ul>
+ *   <li><strong>TTL Support:</strong> Spring Cache has no standard per-entry 
TTL API[cite: 2]. Providing a TTL argument
+ *       triggers a single {@code WARN} log per repository instance and stores 
the entry without expiration[cite: 2].
+ *       Users requiring TTL must configure it at the underlying 
provider/CacheManager spec level (e.g., Caffeine spec)[cite: 2].</li>
+ *   <li><strong>Atomicity:</strong> Only {@code putIfAbsent} delegates 
directly to Spring Cache's {@code Cache.putIfAbsent()}
+ *       (with provider-dependent atomicity). Conditional operations like 
{@code replace} and conditional {@code delete}
+ *       rely on SPI default implementations (non-atomic check-then-act via 
{@code get} and {@code put}/{@code evict}).</li>
+ *   <li><strong>Enumeration:</strong> {@link #keys()} and {@link #size()} 
intentionally throw
+ *       {@link UnsupportedOperationException} as Spring Cache does not 
provide a portable key enumeration API[cite: 2].</li>

Review Comment:
   The `[cite: 2]` markers look like leftovers from the tool that drafted this 
text.
   
   ```suggestion
    * An Apache Camel {@link KeyValueRepository} adapter backed by Spring's 
{@link CacheManager}.
    *
    * <h3>Design Constraints &amp; Backend Behavior:</h3>
    * <ul>
    *   <li><strong>TTL Support:</strong> Spring Cache has no standard 
per-entry TTL API. Providing a TTL argument
    *       triggers a single {@code WARN} log per repository instance and 
stores the entry without expiration.
    *       Users requiring TTL must configure it at the underlying 
provider/CacheManager spec level (e.g., Caffeine spec).</li>
    *   <li><strong>Atomicity:</strong> Only {@code putIfAbsent} delegates 
directly to Spring Cache's {@code Cache.putIfAbsent()}
    *       (with provider-dependent atomicity). Conditional operations like 
{@code replace} and conditional {@code delete}
    *       rely on SPI default implementations (non-atomic check-then-act via 
{@code get} and {@code put}/{@code evict}).</li>
    *   <li><strong>Enumeration:</strong> {@link #keys()} and {@link #size()} 
intentionally throw
    *       {@link UnsupportedOperationException} as Spring Cache does not 
provide a portable key enumeration API.</li>
   ```



##########
core/camel-spring-boot/src/main/docs/spring-boot.adoc:
##########
@@ -755,4 +755,25 @@ If you encounter issues with virtual threads:
 1. **Check JDK Version**: Ensure you're running JDK 21 or later
 2. **Verify Property Setting**: Confirm `spring.threads.virtual.enabled=true` 
is set
 3. **Review Logs**: Check for virtual thread configuration messages in startup 
logs
-4. **Monitor Thread Usage**: Use JVM monitoring tools to observe virtual 
thread behavior
\ No newline at end of file
+4. **Monitor Thread Usage**: Use JVM monitoring tools to observe virtual 
thread behavior
+
+== Spring Cache State Store Support
+
+The `camel-spring-boot` module provides an auto-configured Apache Camel 
`KeyValueRepository` backed by Spring's `CacheManager` abstraction 
(`org.springframework.cache.CacheManager`).
+
+When a `CacheManager` bean is present in the Spring application context, no 
explicit `KeyValueRepository` bean is defined, and 
`camel.spring.cache.state-store.enabled=true` is set, a 
`SpringCacheKeyValueRepository` is automatically registered. This allows any 
caching backend supported by Spring Boot (such as Caffeine, Redis via Lettuce, 
Ehcache, Hazelcast, or JCache) to seamlessly function as an Apache Camel state 
store backend without requiring extra component-specific dependencies.
+
+=== Configuration Example
+
+[source,properties]
+----
+camel.spring.cache.state-store.enabled=true
+spring.cache.type=simple
+----

Review Comment:
   On its own, this example does not give `state-store` a Spring cache. Spring 
Boot 4.1.1 `CacheAutoConfiguration` is 
`@ConditionalOnBean(CacheAspectSupport.class)`, so it creates the 
`CacheManager` only when the application uses `@EnableCaching`. That's why 
`shouldAutoConfigureWithBootCacheAutoConfiguration` imports 
`ProxyCachingConfiguration`. Without it, 
`@ConditionalOnBean(CacheManager.class)` is false and `state-store` falls back 
to `MemoryKeyValueRepository` without a word. Could the section mention 
`@EnableCaching` (or a user-defined `CacheManager` bean)? It should also say 
that `spring.cache.cache-names`, when set, must include `camel-kvr`: the cache 
manager is then static, and every operation fails with `IllegalStateException`.



##########
core/camel-spring-boot/src/main/java/org/apache/camel/spring/boot/statestore/SpringCacheKeyValueRepository.java:
##########
@@ -0,0 +1,161 @@
+/*
+ * 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.spring.boot.statestore;
+
+import java.time.Duration;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.camel.spi.KeyValueRepository;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.cache.Cache;
+import org.springframework.cache.CacheManager;
+import org.springframework.util.Assert;
+
+/**
+ * An Apache Camel {@link KeyValueRepository} adapter backed by Spring's 
{@link CacheManager}[cite: 2].
+ *
+ * <h3>Design Constraints &amp; Backend Behavior:</h3>
+ * <ul>
+ *   <li><strong>TTL Support:</strong> Spring Cache has no standard per-entry 
TTL API[cite: 2]. Providing a TTL argument
+ *       triggers a single {@code WARN} log per repository instance and stores 
the entry without expiration[cite: 2].
+ *       Users requiring TTL must configure it at the underlying 
provider/CacheManager spec level (e.g., Caffeine spec)[cite: 2].</li>
+ *   <li><strong>Atomicity:</strong> Only {@code putIfAbsent} delegates 
directly to Spring Cache's {@code Cache.putIfAbsent()}
+ *       (with provider-dependent atomicity). Conditional operations like 
{@code replace} and conditional {@code delete}
+ *       rely on SPI default implementations (non-atomic check-then-act via 
{@code get} and {@code put}/{@code evict}).</li>
+ *   <li><strong>Enumeration:</strong> {@link #keys()} and {@link #size()} 
intentionally throw
+ *       {@link UnsupportedOperationException} as Spring Cache does not 
provide a portable key enumeration API[cite: 2].</li>
+ *   <li><strong>Scope &amp; Multi-Store:</strong> Bound to a specific cache 
name (defaulting to {@code camel-kvr}).
+ *       When auto-configured as a single singleton bean, the State Store 
component shares this repository instance
+ *       across endpoints, resulting in a shared cache unless separate 
instances are explicitly bound per endpoint via backend references.</li>
+ * </ul>
+ */
+public class SpringCacheKeyValueRepository implements KeyValueRepository {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(SpringCacheKeyValueRepository.class);
+    private static final String DEFAULT_CACHE_NAME = "camel-kvr";
+
+    private final CacheManager cacheManager;
+    private final String cacheName;
+    private final AtomicBoolean ttlWarningLogged = new AtomicBoolean(false);
+
+    public SpringCacheKeyValueRepository(CacheManager cacheManager) {
+        this(cacheManager, DEFAULT_CACHE_NAME);
+    }
+
+    public SpringCacheKeyValueRepository(CacheManager cacheManager, String 
cacheName) {
+        Assert.notNull(cacheManager, "CacheManager must not be null");
+        Assert.hasText(cacheName, "CacheName must not be empty");
+        this.cacheManager = cacheManager;
+        this.cacheName = cacheName;
+    }
+
+    public String getCacheName() {
+        return cacheName;
+    }
+
+    private Cache getCache() {
+        Cache cache = cacheManager.getCache(cacheName);
+        if (cache == null) {
+            throw new IllegalStateException(String.format("Spring Cache '%s' 
not found in CacheManager of type %s",
+                    cacheName, cacheManager.getClass().getName()));
+        }
+        return cache;
+    }
+
+    @Override
+    public void start() {
+        // Lifecycle start hook (managed externally by Spring CacheManager 
container)
+    }
+
+    @Override
+    public void stop() {
+        // Lifecycle stop hook (managed externally by Spring CacheManager 
container)
+    }
+
+    @Override
+    public Object get(String key) {
+        Cache.ValueWrapper wrapper = getCache().get(key);
+        return wrapper != null ? wrapper.get() : null;
+    }
+
+    @Override
+    public Object put(String key, Object value) {
+        return put(key, value, null);
+    }
+
+    @Override
+    public Object put(String key, Object value, Duration ttl) {
+        checkTtl(ttl);
+        Cache cache = getCache();
+        Cache.ValueWrapper oldWrapper = cache.get(key);
+        Object oldValue = oldWrapper != null ? oldWrapper.get() : null;
+        cache.put(key, value);
+        return oldValue;
+    }
+
+    @Override
+    public Object putIfAbsent(String key, Object value) {
+        return putIfAbsent(key, value, null);
+    }
+
+    @Override
+    public Object putIfAbsent(String key, Object value, Duration ttl) {
+        checkTtl(ttl);
+        Cache.ValueWrapper existing = getCache().putIfAbsent(key, value);
+        return existing != null ? existing.get() : null;
+    }
+
+    @Override
+    public Object delete(String key) {
+        Cache cache = getCache();
+        Cache.ValueWrapper oldWrapper = cache.get(key);
+        Object oldValue = oldWrapper != null ? oldWrapper.get() : null;
+        cache.evict(key);

Review Comment:
   Spring's `Cache.evict()` javadoc says eviction "may be performed in an 
asynchronous or deferred fashion, with subsequent lookups possibly still seeing 
the entry" (for example with transactional cache decorators), and points to 
`evictIfPresent` for guaranteed immediate removal. A state store, and the 
idempotent repository on top of it, needs the key gone right away.
   
   ```suggestion
           cache.evictIfPresent(key);
   ```



##########
core/camel-spring-boot/src/main/java/org/apache/camel/spring/boot/statestore/SpringCacheKeyValueRepository.java:
##########
@@ -0,0 +1,161 @@
+/*
+ * 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.spring.boot.statestore;
+
+import java.time.Duration;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.camel.spi.KeyValueRepository;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.cache.Cache;
+import org.springframework.cache.CacheManager;
+import org.springframework.util.Assert;
+
+/**
+ * An Apache Camel {@link KeyValueRepository} adapter backed by Spring's 
{@link CacheManager}[cite: 2].
+ *
+ * <h3>Design Constraints &amp; Backend Behavior:</h3>
+ * <ul>
+ *   <li><strong>TTL Support:</strong> Spring Cache has no standard per-entry 
TTL API[cite: 2]. Providing a TTL argument
+ *       triggers a single {@code WARN} log per repository instance and stores 
the entry without expiration[cite: 2].
+ *       Users requiring TTL must configure it at the underlying 
provider/CacheManager spec level (e.g., Caffeine spec)[cite: 2].</li>
+ *   <li><strong>Atomicity:</strong> Only {@code putIfAbsent} delegates 
directly to Spring Cache's {@code Cache.putIfAbsent()}
+ *       (with provider-dependent atomicity). Conditional operations like 
{@code replace} and conditional {@code delete}
+ *       rely on SPI default implementations (non-atomic check-then-act via 
{@code get} and {@code put}/{@code evict}).</li>
+ *   <li><strong>Enumeration:</strong> {@link #keys()} and {@link #size()} 
intentionally throw
+ *       {@link UnsupportedOperationException} as Spring Cache does not 
provide a portable key enumeration API[cite: 2].</li>
+ *   <li><strong>Scope &amp; Multi-Store:</strong> Bound to a specific cache 
name (defaulting to {@code camel-kvr}).
+ *       When auto-configured as a single singleton bean, the State Store 
component shares this repository instance
+ *       across endpoints, resulting in a shared cache unless separate 
instances are explicitly bound per endpoint via backend references.</li>
+ * </ul>
+ */
+public class SpringCacheKeyValueRepository implements KeyValueRepository {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(SpringCacheKeyValueRepository.class);
+    private static final String DEFAULT_CACHE_NAME = "camel-kvr";
+
+    private final CacheManager cacheManager;
+    private final String cacheName;
+    private final AtomicBoolean ttlWarningLogged = new AtomicBoolean(false);
+
+    public SpringCacheKeyValueRepository(CacheManager cacheManager) {
+        this(cacheManager, DEFAULT_CACHE_NAME);
+    }
+
+    public SpringCacheKeyValueRepository(CacheManager cacheManager, String 
cacheName) {
+        Assert.notNull(cacheManager, "CacheManager must not be null");
+        Assert.hasText(cacheName, "CacheName must not be empty");
+        this.cacheManager = cacheManager;
+        this.cacheName = cacheName;
+    }
+
+    public String getCacheName() {
+        return cacheName;
+    }
+
+    private Cache getCache() {
+        Cache cache = cacheManager.getCache(cacheName);
+        if (cache == null) {
+            throw new IllegalStateException(String.format("Spring Cache '%s' 
not found in CacheManager of type %s",
+                    cacheName, cacheManager.getClass().getName()));
+        }
+        return cache;
+    }
+
+    @Override
+    public void start() {
+        // Lifecycle start hook (managed externally by Spring CacheManager 
container)
+    }
+
+    @Override
+    public void stop() {
+        // Lifecycle stop hook (managed externally by Spring CacheManager 
container)
+    }
+
+    @Override
+    public Object get(String key) {
+        Cache.ValueWrapper wrapper = getCache().get(key);
+        return wrapper != null ? wrapper.get() : null;
+    }
+
+    @Override
+    public Object put(String key, Object value) {
+        return put(key, value, null);
+    }
+
+    @Override
+    public Object put(String key, Object value, Duration ttl) {
+        checkTtl(ttl);
+        Cache cache = getCache();
+        Cache.ValueWrapper oldWrapper = cache.get(key);
+        Object oldValue = oldWrapper != null ? oldWrapper.get() : null;
+        cache.put(key, value);
+        return oldValue;
+    }
+
+    @Override
+    public Object putIfAbsent(String key, Object value) {
+        return putIfAbsent(key, value, null);
+    }
+
+    @Override
+    public Object putIfAbsent(String key, Object value, Duration ttl) {
+        checkTtl(ttl);
+        Cache.ValueWrapper existing = getCache().putIfAbsent(key, value);
+        return existing != null ? existing.get() : null;
+    }
+
+    @Override
+    public Object delete(String key) {
+        Cache cache = getCache();
+        Cache.ValueWrapper oldWrapper = cache.get(key);
+        Object oldValue = oldWrapper != null ? oldWrapper.get() : null;
+        cache.evict(key);
+        return oldValue;
+    }
+
+    @Override
+    public boolean contains(String key) {
+        return getCache().get(key) != null;
+    }
+
+    @Override
+    public void clear() {
+        getCache().clear();

Review Comment:
   Same for `clear()`: the javadoc points to `invalidate()` for guaranteed 
immediate removal of entries.
   
   ```suggestion
           getCache().invalidate();
   ```



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