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 02d02ab96d93 CAMEL-27320: camel-file - the idempotent read locks 
release the key they acquired (#30574)
02d02ab96d93 is described below

commit 02d02ab96d93e24cc264ef851e4eb6418c24ba56
Author: allthingssecurity <[email protected]>
AuthorDate: Sun Nov 22 19:09:28 2026 +0530

    CAMEL-27320: camel-file - the idempotent read locks release the key they 
acquired (#30574)
    
    With readLock=idempotent, idempotent-changed or idempotent-rename and an
    idempotentKey, the read lock evaluated the idempotentKey again at commit,
    rollback and abort, on a copy of the routed exchange's headers. A route that
    sets CamelFileName (as it does before a file producer) then released another
    key: a rolled back file was never picked up again (its key stayed in the
    repository), and with readLockRemoveOnCommit=true the commit could remove 
the
    key of a file another node was processing.
    
    The key computed at acquire is now kept on the exchange and released.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 ...dempotentChangedRepositoryReadLockStrategy.java |  20 +++-
 ...IdempotentRenameRepositoryReadLockStrategy.java |  20 +++-
 .../FileIdempotentRepositoryReadLockStrategy.java  |  20 +++-
 .../FileIdempotentReadLockRoutedFileNameTest.java  | 129 +++++++++++++++++++++
 4 files changed, 180 insertions(+), 9 deletions(-)

diff --git 
a/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentChangedRepositoryReadLockStrategy.java
 
b/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentChangedRepositoryReadLockStrategy.java
index fe83b09c7bbb..b99e03bbd2e1 100644
--- 
a/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentChangedRepositoryReadLockStrategy.java
+++ 
b/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentChangedRepositoryReadLockStrategy.java
@@ -46,6 +46,9 @@ public class FileIdempotentChangedRepositoryReadLockStrategy 
extends ServiceSupp
         implements GenericFileExclusiveReadLockStrategy<File>, 
CamelContextAware {
 
     private static final Logger LOG = 
LoggerFactory.getLogger(FileIdempotentChangedRepositoryReadLockStrategy.class);
+    // exchange property (per file, see asReadLockKey) holding the key that 
acquireExclusiveReadLock added, so the
+    // release removes or confirms that same key whatever the route did to the 
headers the idempotentKey reads
+    private static final String READ_LOCK_IDEMPOTENT_KEY = 
"CamelFileLockIdempotentKey";
 
     private final FileChangedExclusiveReadLockStrategy changed;
     private GenericFileEndpoint<File> endpoint;
@@ -87,6 +90,7 @@ public class FileIdempotentChangedRepositoryReadLockStrategy 
extends ServiceSupp
 
         // check if we can begin on this file
         String key = asKey(exchange, file);
+        exchange.setProperty(asReadLockKey(file, READ_LOCK_IDEMPOTENT_KEY), 
key);
         boolean answer = false;
         try {
             answer = idempotentRepository.add(exchange, key);
@@ -126,7 +130,7 @@ public class 
FileIdempotentChangedRepositoryReadLockStrategy extends ServiceSupp
         boolean acquired
                 = exchange.getProperty(asReadLockKey(file, 
Exchange.FILE_LOCK_IDEMPOTENT_ACQUIRED), false, Boolean.class);
         if (acquired) {
-            String key = asKey(exchange, file);
+            String key = asAcquiredKey(exchange, file);
             idempotentRepository.remove(exchange, key);
         }
         changed.releaseExclusiveReadLockOnAbort(operations, file, exchange);
@@ -136,7 +140,7 @@ public class 
FileIdempotentChangedRepositoryReadLockStrategy extends ServiceSupp
     public void releaseExclusiveReadLockOnRollback(
             GenericFileOperations<File> operations, GenericFile<File> file, 
Exchange exchange)
             throws Exception {
-        String key = asKey(exchange, file);
+        String key = asAcquiredKey(exchange, file);
         Runnable r = () -> {
             if (removeOnRollback) {
                 idempotentRepository.remove(exchange, key);
@@ -173,7 +177,7 @@ public class 
FileIdempotentChangedRepositoryReadLockStrategy extends ServiceSupp
     public void releaseExclusiveReadLockOnCommit(
             GenericFileOperations<File> operations, GenericFile<File> file, 
Exchange exchange)
             throws Exception {
-        String key = asKey(exchange, file);
+        String key = asAcquiredKey(exchange, file);
         Runnable r = () -> {
             if (removeOnCommit) {
                 idempotentRepository.remove(exchange, key);
@@ -340,6 +344,16 @@ public class 
FileIdempotentChangedRepositoryReadLockStrategy extends ServiceSupp
         return key;
     }
 
+    /**
+     * The key to release: the one that {@link #acquireExclusiveReadLock} 
added to the idempotent repository. The
+     * idempotentKey expression is not evaluated again, as the route may have 
changed the headers it reads (such as
+     * {@link Exchange#FILE_NAME}), which would release another key.
+     */
+    protected String asAcquiredKey(Exchange exchange, GenericFile<File> file) {
+        String key = exchange.getProperty(asReadLockKey(file, 
READ_LOCK_IDEMPOTENT_KEY), String.class);
+        return key != null ? key : asKey(exchange, file);
+    }
+
     private static String asReadLockKey(GenericFile<File> file, String key) {
         // use the copy from absolute path as that was the original path of the
         // file when the lock was acquired; e.g. if the file consumer uses 
preMove
diff --git 
a/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentRenameRepositoryReadLockStrategy.java
 
b/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentRenameRepositoryReadLockStrategy.java
index 0f205dc20bf8..b22bb772ce0f 100644
--- 
a/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentRenameRepositoryReadLockStrategy.java
+++ 
b/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentRenameRepositoryReadLockStrategy.java
@@ -44,6 +44,9 @@ public class FileIdempotentRenameRepositoryReadLockStrategy 
extends ServiceSuppo
         implements GenericFileExclusiveReadLockStrategy<File>, 
CamelContextAware {
 
     private static final Logger LOG = 
LoggerFactory.getLogger(FileIdempotentRenameRepositoryReadLockStrategy.class);
+    // exchange property (per file, see asReadLockKey) holding the key that 
acquireExclusiveReadLock added, so the
+    // release removes or confirms that same key whatever the route did to the 
headers the idempotentKey reads
+    private static final String READ_LOCK_IDEMPOTENT_KEY = 
"CamelFileLockIdempotentKey";
     private final FileRenameExclusiveReadLockStrategy rename;
     private GenericFileEndpoint<File> endpoint;
     private LoggingLevel readLockLoggingLevel = LoggingLevel.DEBUG;
@@ -79,6 +82,7 @@ public class FileIdempotentRenameRepositoryReadLockStrategy 
extends ServiceSuppo
 
         // check if we can begin on this file
         String key = asKey(exchange, file);
+        exchange.setProperty(asReadLockKey(file, READ_LOCK_IDEMPOTENT_KEY), 
key);
         boolean answer = false;
         try {
             answer = idempotentRepository.add(exchange, key);
@@ -118,7 +122,7 @@ public class FileIdempotentRenameRepositoryReadLockStrategy 
extends ServiceSuppo
         boolean acquired
                 = exchange.getProperty(asReadLockKey(file, 
Exchange.FILE_LOCK_IDEMPOTENT_ACQUIRED), false, Boolean.class);
         if (acquired) {
-            String key = asKey(exchange, file);
+            String key = asAcquiredKey(exchange, file);
             idempotentRepository.remove(exchange, key);
         }
         rename.releaseExclusiveReadLockOnAbort(operations, file, exchange);
@@ -128,7 +132,7 @@ public class FileIdempotentRenameRepositoryReadLockStrategy 
extends ServiceSuppo
     public void releaseExclusiveReadLockOnRollback(
             GenericFileOperations<File> operations, GenericFile<File> file, 
Exchange exchange)
             throws Exception {
-        String key = asKey(exchange, file);
+        String key = asAcquiredKey(exchange, file);
         if (removeOnRollback) {
             idempotentRepository.remove(exchange, key);
         } else {
@@ -143,7 +147,7 @@ public class FileIdempotentRenameRepositoryReadLockStrategy 
extends ServiceSuppo
     public void releaseExclusiveReadLockOnCommit(
             GenericFileOperations<File> operations, GenericFile<File> file, 
Exchange exchange)
             throws Exception {
-        String key = asKey(exchange, file);
+        String key = asAcquiredKey(exchange, file);
         if (removeOnCommit) {
             idempotentRepository.remove(exchange, key);
         } else {
@@ -254,6 +258,16 @@ public class 
FileIdempotentRenameRepositoryReadLockStrategy extends ServiceSuppo
         return key;
     }
 
+    /**
+     * The key to release: the one that {@link #acquireExclusiveReadLock} 
added to the idempotent repository. The
+     * idempotentKey expression is not evaluated again, as the route may have 
changed the headers it reads (such as
+     * {@link Exchange#FILE_NAME}), which would release another key.
+     */
+    protected String asAcquiredKey(Exchange exchange, GenericFile<File> file) {
+        String key = exchange.getProperty(asReadLockKey(file, 
READ_LOCK_IDEMPOTENT_KEY), String.class);
+        return key != null ? key : asKey(exchange, file);
+    }
+
     private static String asReadLockKey(GenericFile<File> file, String key) {
         // use the copy from absolute path as that was the original path of the
         // file when the lock was acquired; e.g. if the file consumer uses 
preMove
diff --git 
a/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentRepositoryReadLockStrategy.java
 
b/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentRepositoryReadLockStrategy.java
index 07c02e5df063..c7169bc60cd4 100644
--- 
a/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentRepositoryReadLockStrategy.java
+++ 
b/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentRepositoryReadLockStrategy.java
@@ -46,6 +46,9 @@ public class FileIdempotentRepositoryReadLockStrategy extends 
ServiceSupport
         implements GenericFileExclusiveReadLockStrategy<File>, 
CamelContextAware {
 
     private static final Logger LOG = 
LoggerFactory.getLogger(FileIdempotentRepositoryReadLockStrategy.class);
+    // exchange property (per file, see asReadLockKey) holding the key that 
acquireExclusiveReadLock added, so the
+    // release removes or confirms that same key whatever the route did to the 
headers the idempotentKey reads
+    private static final String READ_LOCK_IDEMPOTENT_KEY = 
"CamelFileLockIdempotentKey";
     private GenericFileEndpoint<File> endpoint;
     private LoggingLevel readLockLoggingLevel = LoggingLevel.DEBUG;
     private CamelContext camelContext;
@@ -76,6 +79,7 @@ public class FileIdempotentRepositoryReadLockStrategy extends 
ServiceSupport
 
         // check if we can begin on this file
         String key = asKey(exchange, file);
+        exchange.setProperty(asReadLockKey(file, READ_LOCK_IDEMPOTENT_KEY), 
key);
         boolean answer = false;
         try {
             answer = idempotentRepository.add(exchange, key);
@@ -105,7 +109,7 @@ public class FileIdempotentRepositoryReadLockStrategy 
extends ServiceSupport
         boolean acquired
                 = exchange.getProperty(asReadLockKey(file, 
Exchange.FILE_LOCK_IDEMPOTENT_ACQUIRED), false, Boolean.class);
         if (acquired) {
-            String key = asKey(exchange, file);
+            String key = asAcquiredKey(exchange, file);
             idempotentRepository.remove(exchange, key);
         }
     }
@@ -114,7 +118,7 @@ public class FileIdempotentRepositoryReadLockStrategy 
extends ServiceSupport
     public void releaseExclusiveReadLockOnRollback(
             GenericFileOperations<File> operations, GenericFile<File> file, 
Exchange exchange)
             throws Exception {
-        String key = asKey(exchange, file);
+        String key = asAcquiredKey(exchange, file);
         Runnable r = () -> {
             if (removeOnRollback) {
                 idempotentRepository.remove(exchange, key);
@@ -131,7 +135,7 @@ public class FileIdempotentRepositoryReadLockStrategy 
extends ServiceSupport
     public void releaseExclusiveReadLockOnCommit(
             GenericFileOperations<File> operations, GenericFile<File> file, 
Exchange exchange)
             throws Exception {
-        String key = asKey(exchange, file);
+        String key = asAcquiredKey(exchange, file);
         Runnable r = () -> {
             if (removeOnCommit) {
                 idempotentRepository.remove(exchange, key);
@@ -301,6 +305,16 @@ public class FileIdempotentRepositoryReadLockStrategy 
extends ServiceSupport
         return key;
     }
 
+    /**
+     * The key to release: the one that {@link #acquireExclusiveReadLock} 
added to the idempotent repository. The
+     * idempotentKey expression is not evaluated again, as the route may have 
changed the headers it reads (such as
+     * {@link Exchange#FILE_NAME}), which would release another key.
+     */
+    protected String asAcquiredKey(Exchange exchange, GenericFile<File> file) {
+        String key = exchange.getProperty(asReadLockKey(file, 
READ_LOCK_IDEMPOTENT_KEY), String.class);
+        return key != null ? key : asKey(exchange, file);
+    }
+
     private static String asReadLockKey(GenericFile<File> file, String key) {
         // use the copy from absolute path as that was the original path of the
         // file when the lock was acquired; e.g. if the file consumer uses 
preMove
diff --git 
a/core/camel-core/src/test/java/org/apache/camel/component/file/strategy/FileIdempotentReadLockRoutedFileNameTest.java
 
b/core/camel-core/src/test/java/org/apache/camel/component/file/strategy/FileIdempotentReadLockRoutedFileNameTest.java
new file mode 100644
index 000000000000..5adc0d0af895
--- /dev/null
+++ 
b/core/camel-core/src/test/java/org/apache/camel/component/file/strategy/FileIdempotentReadLockRoutedFileNameTest.java
@@ -0,0 +1,129 @@
+/*
+ * 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.file.strategy;
+
+import java.nio.file.Files;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.spi.Registry;
+import 
org.apache.camel.support.processor.idempotent.MemoryIdempotentRepository;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+
+/**
+ * The idempotent read locks release the key they acquired, also when the 
route changes the headers that the
+ * idempotentKey expression reads (here CamelFileName, as a route does before 
it writes to a file endpoint).
+ */
+class FileIdempotentReadLockRoutedFileNameTest extends ContextTestSupport {
+
+    private final MemoryIdempotentRepository myRepo = new 
MemoryIdempotentRepository();
+
+    @Override
+    protected Registry createCamelRegistry() throws Exception {
+        Registry jndi = super.createCamelRegistry();
+        jndi.bind("myRepo", myRepo);
+        return jndi;
+    }
+
+    @Override
+    public boolean isUseRouteBuilder() {
+        return false;
+    }
+
+    private String consumerUri(String readLock, String options) {
+        return 
fileUri("?initialDelay=0&delay=10&readLockCheckInterval=100&readLock=" + 
readLock
+                       + 
"&idempotentRepository=#myRepo&idempotentKey=${file:name}" + options);
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = { "idempotent", "idempotent-changed", 
"idempotent-rename" })
+    void rolledBackFileIsPickedUpAgain(String readLock) throws Exception {
+        AtomicInteger attempts = new AtomicInteger();
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                errorHandler(noErrorHandler());
+
+                from(consumerUri(readLock, ""))
+                        // the name of the file to write, as a route does 
before a file producer
+                        .setHeader(Exchange.FILE_NAME, 
simple("out-${file:name}"))
+                        .process(e -> {
+                            if (attempts.incrementAndGet() == 1) {
+                                throw new IllegalStateException("Forced 
failure");
+                            }
+                        })
+                        .to("mock:done");
+            }
+        });
+        context.start();
+
+        MockEndpoint done = getMockEndpoint("mock:done");
+        done.expectedMessageCount(1);
+        done.setResultWaitTime(10000);
+
+        template.sendBodyAndHeader(fileUri(), "Hello World", 
Exchange.FILE_NAME, "hello.txt");
+
+        // the first attempt fails and is rolled back: the read lock must 
remove the key it added for hello.txt,
+        // so the file is picked up again and the second attempt completes
+        done.assertIsSatisfied();
+        assertThat(attempts.get()).isEqualTo(2);
+        await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> {
+            assertThat(Files.exists(testFile("hello.txt"))).as("file moved out 
of the inbox").isFalse();
+            assertThat(myRepo.contains("hello.txt")).as("key confirmed on 
commit").isTrue();
+            assertThat(myRepo.getCacheSize()).isEqualTo(1);
+        });
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = { "idempotent", "idempotent-changed", 
"idempotent-rename" })
+    void commitRemovesOnlyItsOwnKey(String readLock) throws Exception {
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from(consumerUri(readLock, 
"&readLockRemoveOnCommit=true&include=a.txt"))
+                        .setHeader(Exchange.FILE_NAME, constant("b.txt"))
+                        .to("mock:a");
+            }
+        });
+        context.start();
+
+        // another node holds the read lock of b.txt (it is processing that 
file right now)
+        myRepo.add("b.txt");
+
+        MockEndpoint a = getMockEndpoint("mock:a");
+        a.expectedMessageCount(1);
+        a.setResultWaitTime(10000);
+
+        template.sendBodyAndHeader(fileUri(), "A", Exchange.FILE_NAME, 
"a.txt");
+
+        a.assertIsSatisfied();
+        // the commit must remove the key a.txt (its own) and leave b.txt to 
the node that holds it
+        await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> {
+            assertThat(Files.exists(testFile("a.txt"))).as("file moved out of 
the inbox").isFalse();
+            assertThat(myRepo.contains("a.txt")).as("own key removed on 
commit").isFalse();
+            assertThat(myRepo.contains("b.txt")).as("key of the other node 
kept").isTrue();
+        });
+    }
+}

Reply via email to