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 db3d393aae03 CAMEL-27264: camel-file - a file polled by pollEnrich 
stays in progress when the poll also delivered a bridged error (#30470)
db3d393aae03 is described below

commit db3d393aae03687ce7618b912788801af1c5e619
Author: Adriano Machado <[email protected]>
AuthorDate: Fri Nov 20 14:19:16 2026 -0500

    CAMEL-27264: camel-file - a file polled by pollEnrich stays in progress 
when the poll also delivered a bridged error (#30470)
    
    With bridgeErrorHandler, a read lock that fails (such as with "Pipe closed"
    when another thread closed the sftp channel) delivers a bridged error
    exchange to the receive call of pollEnrich, and the file is not started.
    As no file was polled, the receive call polled again within its timeout,
    found the file, and put its exchange on the queue of the polling consumer,
    as it already returned the error. Nothing takes exchanges from that queue,
    so the on completion of the file never ran: the file stayed in the
    in-progress repository and every later poll skipped it until a restart.
    
    The receive call now stops polling once the poll delivered an exchange to
    it, and a poll strategy retry is skipped as well. An exchange that arrives
    while the receive call of the same thread already has the exchange it
    returns is completed as failed, and its file, which no route started, is
    aborted (removed from the in-progress repository and polled again) rather
    than rolled back, so moveFailed does not move it.
    
    _Claude Code on behalf of Adriano Machado (@ammachado)_
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
    Co-authored-by: Claude Sonnet 5.5 <[email protected]>
---
 .../component/file/GenericFileOnCompletion.java    |  28 +++
 .../component/file/GenericFilePollingConsumer.java |  61 +++++-
 .../FileNotReturnedByPollingConsumerAbortTest.java |  79 ++++++++
 ...PollEnrichBridgeErrorHandlerInProgressTest.java | 204 +++++++++++++++++++++
 4 files changed, 370 insertions(+), 2 deletions(-)

diff --git 
a/components/camel-file/src/main/java/org/apache/camel/component/file/GenericFileOnCompletion.java
 
b/components/camel-file/src/main/java/org/apache/camel/component/file/GenericFileOnCompletion.java
index 82f3cdfd1fd9..9a8bd1531466 100644
--- 
a/components/camel-file/src/main/java/org/apache/camel/component/file/GenericFileOnCompletion.java
+++ 
b/components/camel-file/src/main/java/org/apache/camel/component/file/GenericFileOnCompletion.java
@@ -111,6 +111,34 @@ public class GenericFileOnCompletion<T> implements 
Synchronization {
         }
     }
 
+    /**
+     * The file was polled, but cannot be handed to anyone, so it was never 
started: abort it, and make it available to
+     * be polled again, as {@link GenericFileConsumer} does for a file it 
cannot begin to process. Unlike a rollback, a
+     * file is not moved by the moveFailed option.
+     *
+     * @param exchange the exchange of the file
+     */
+    void abort(Exchange exchange) {
+        LOG.debug("Aborting file: {} that was not started, using exchange: 
{}", file, exchange);
+        try {
+            processStrategy.abort(operations, endpoint, exchange, file);
+        } catch (Exception e) {
+            handleException("Error during abort", exchange, e);
+        } finally {
+            endpoint.getInProgressRepository().remove(absoluteFileName);
+            if (Boolean.TRUE.equals(endpoint.isIdempotent()) && 
endpoint.isIdempotentEager()
+                    && endpoint.getIdempotentRepository() != null) {
+                String key = absoluteFileName;
+                if (endpoint.getIdempotentKey() != null) {
+                    key = exchange.getProperty(Exchange.FILE_IDEMPOTENT_KEY, 
absoluteFileName, String.class);
+                }
+                if (key != null) {
+                    endpoint.getIdempotentRepository().remove(key);
+                }
+            }
+        }
+    }
+
     /**
      * Strategy when the file was processed and a commit should be executed.
      *
diff --git 
a/components/camel-file/src/main/java/org/apache/camel/component/file/GenericFilePollingConsumer.java
 
b/components/camel-file/src/main/java/org/apache/camel/component/file/GenericFilePollingConsumer.java
index 4cd03b0a37ca..62712382af7d 100644
--- 
a/components/camel-file/src/main/java/org/apache/camel/component/file/GenericFilePollingConsumer.java
+++ 
b/components/camel-file/src/main/java/org/apache/camel/component/file/GenericFilePollingConsumer.java
@@ -16,13 +16,19 @@
  */
 package org.apache.camel.component.file;
 
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.camel.CamelExchangeException;
 import org.apache.camel.Consumer;
 import org.apache.camel.DynamicPollingConsumer;
 import org.apache.camel.Exchange;
 import org.apache.camel.PooledExchange;
 import org.apache.camel.RuntimeCamelException;
 import org.apache.camel.spi.PollingConsumerPollStrategy;
+import org.apache.camel.spi.Synchronization;
 import org.apache.camel.support.EventDrivenPollingConsumer;
+import org.apache.camel.support.UnitOfWorkHelper;
 import org.apache.camel.support.service.ServiceHelper;
 import org.apache.camel.util.StopWatch;
 import org.slf4j.Logger;
@@ -162,7 +168,12 @@ public class GenericFilePollingConsumer extends 
EventDrivenPollingConsumer imple
                         polledMessages = getConsumer().poll(exchange);
                         LOG.trace("Polled {} messages", polledMessages);
 
-                        if (polledMessages == 0 && sendEmptyMessageWhenIdle) {
+                        if (polledMessages == 0 && 
isExchangeTakenByThisCall()) {
+                            // no file was polled, but the poll delivered an 
exchange to this call, such as an error
+                            // bridged to the error handler: return it, and do 
not poll again, as a file found by
+                            // that poll could not be returned as well 
(CAMEL-27264)
+                            LOG.trace("Not polling again as the poll delivered 
an exchange");
+                        } else if (polledMessages == 0 && 
sendEmptyMessageWhenIdle) {
                             // send an "empty" exchange
                             processEmptyMessage();
                             // set polledMessages=1 since the empty message is 
queued
@@ -183,7 +194,7 @@ public class GenericFilePollingConsumer extends 
EventDrivenPollingConsumer imple
             } catch (Exception e) {
                 try {
                     boolean retry = pollStrategy.rollback(getConsumer(), 
getEndpoint(), retryCounter, e);
-                    if (retry) {
+                    if (retry && !isExchangeTakenByThisCall()) {
                         // do not set cause as we retry
                         done = false;
                     } else {
@@ -233,9 +244,55 @@ public class GenericFilePollingConsumer extends 
EventDrivenPollingConsumer imple
             slot[0] = isCopy() || exchange instanceof PooledExchange ? 
prepareCopy(exchange, true) : exchange;
             return;
         }
+        if (slot != null) {
+            // the receive call on this thread already returns another 
exchange, and nothing takes this one from the
+            // queue, which would keep its file in the in-progress repository, 
skipped by every later poll (CAMEL-27264)
+            rollbackNotReturned(exchange, slot[0]);
+            return;
+        }
         super.process(exchange);
     }
 
+    /**
+     * Completes an exchange that the receive call cannot return as failed, 
and aborts its polled file, which was never
+     * started, so it is removed from the in-progress repository and polled 
again, and is not moved by moveFailed.
+     *
+     * @param exchange the exchange that cannot be returned and will be 
completed as failed
+     * @param returned the exchange already taken by the receive call
+     */
+    static void rollbackNotReturned(Exchange exchange, Exchange returned) {
+        if (exchange.getException() == null) {
+            exchange.setException(new CamelExchangeException(
+                    "Rolled back as the receive call already returns exchange: 
" + returned.getExchangeId(), exchange));
+        } else {
+            LOG.warn(
+                    "Cannot return exchange: {} as the receive call already 
returns exchange: {}. Its exception is not returned to the caller: {}",
+                    exchange.getExchangeId(), returned.getExchangeId(), 
exchange.getException().getMessage());
+        }
+        List<Synchronization> completions = 
exchange.getExchangeExtension().handoverCompletions();
+        if (completions == null) {
+            // no on-completions of its own, such as a second bridged error 
whose completions are on its own UoW
+            return;
+        }
+        List<Synchronization> others = new ArrayList<>();
+        for (Synchronization onCompletion : completions) {
+            if (onCompletion instanceof GenericFileOnCompletion<?> 
fileCompletion) {
+                fileCompletion.abort(exchange);
+            } else {
+                others.add(onCompletion);
+            }
+        }
+        UnitOfWorkHelper.doneSynchronizations(exchange, others);
+    }
+
+    /**
+     * Whether a receive call on this thread is polling and has already been 
given the exchange it returns.
+     */
+    private boolean isExchangeTakenByThisCall() {
+        Exchange[] slot = polledByThisThread.get();
+        return slot != null && slot[0] != null;
+    }
+
     /**
      * No messages to poll so send an empty message instead.
      *
diff --git 
a/core/camel-core/src/test/java/org/apache/camel/component/file/FileNotReturnedByPollingConsumerAbortTest.java
 
b/core/camel-core/src/test/java/org/apache/camel/component/file/FileNotReturnedByPollingConsumerAbortTest.java
new file mode 100644
index 000000000000..03b3bcf185d8
--- /dev/null
+++ 
b/core/camel-core/src/test/java/org/apache/camel/component/file/FileNotReturnedByPollingConsumerAbortTest.java
@@ -0,0 +1,79 @@
+/*
+ * 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;
+
+import java.io.File;
+
+import org.apache.camel.CamelExchangeException;
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Exchange;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertSame;
+
+/**
+ * CAMEL-27264: a file exchange that the receive call of the polling consumer 
cannot return was never started by any
+ * route, so its file is aborted, and made available to be polled again. It 
must not be rolled back, as the rollback
+ * moves the file with the moveFailed option.
+ */
+public class FileNotReturnedByPollingConsumerAbortTest extends 
ContextTestSupport {
+
+    @Test
+    public void testFileIsAbortedAndNotMovedByMoveFailed() throws Exception {
+        template.sendBodyAndHeader(fileUri(), "Hello World", 
Exchange.FILE_NAME, "hello.txt");
+
+        FileEndpoint endpoint = 
context.getEndpoint(fileUri("?moveFailed=error"), FileEndpoint.class);
+        FileConsumer consumer = (FileConsumer) 
endpoint.createConsumer(exchange -> {
+        });
+
+        File file = testFile("hello.txt").toFile();
+        GenericFile<File> genericFile
+                = 
FileConsumer.asGenericFile(endpoint.getConfiguration().getDirectory(), file, 
null, false);
+        String absoluteFileName = genericFile.getAbsoluteFilePath();
+
+        // the file is polled, so it is in progress, and its completion is 
registered on the exchange
+        Exchange notReturned = endpoint.createExchange(genericFile);
+        endpoint.getInProgressRepository().add(absoluteFileName);
+        notReturned.getExchangeExtension().addOnCompletion(
+                new GenericFileOnCompletion<>(
+                        endpoint, consumer.operations, 
consumer.processStrategy, genericFile, absoluteFileName));
+        Exchange returned = endpoint.createExchange();
+
+        GenericFilePollingConsumer.rollbackNotReturned(notReturned, returned);
+
+        assertInstanceOf(CamelExchangeException.class, 
notReturned.getException());
+        assertEquals(false, 
endpoint.getInProgressRepository().contains(absoluteFileName),
+                "the file must not be left in the in-progress repository");
+        assertFileExists(testFile("hello.txt"));
+        assertFileNotExists(testFile("error/hello.txt"));
+    }
+
+    @Test
+    public void testExchangeWithoutOnCompletionsDoesNotFail() {
+        Exchange notReturned = context.getEndpoint(fileUri(), 
FileEndpoint.class).createExchange();
+        IllegalStateException cause = new IllegalStateException("Forced");
+        notReturned.setException(cause);
+        Exchange returned = context.getEndpoint(fileUri(), 
FileEndpoint.class).createExchange();
+
+        assertDoesNotThrow(() -> 
GenericFilePollingConsumer.rollbackNotReturned(notReturned, returned));
+
+        assertSame(cause, notReturned.getException(), "the existing exception 
must be preserved");
+    }
+}
diff --git 
a/core/camel-core/src/test/java/org/apache/camel/component/file/FilePollEnrichBridgeErrorHandlerInProgressTest.java
 
b/core/camel-core/src/test/java/org/apache/camel/component/file/FilePollEnrichBridgeErrorHandlerInProgressTest.java
new file mode 100644
index 000000000000..025a5bac1476
--- /dev/null
+++ 
b/core/camel-core/src/test/java/org/apache/camel/component/file/FilePollEnrichBridgeErrorHandlerInProgressTest.java
@@ -0,0 +1,204 @@
+/*
+ * 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;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.CamelExecutionException;
+import org.apache.camel.Consumer;
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Endpoint;
+import org.apache.camel.Exchange;
+import org.apache.camel.LoggingLevel;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.spi.PollingConsumerPollStrategy;
+import org.apache.camel.spi.Registry;
+import 
org.apache.camel.support.processor.idempotent.MemoryIdempotentRepository;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * CAMEL-27264: with bridgeErrorHandler, a poll of pollEnrich whose read lock 
fails delivers a bridged error exchange.
+ * The file must then not be polled again by the same receive call, as that 
exchange cannot be returned and its file
+ * would stay in the in-progress repository, skipped by every later poll. A 
poll is not retried once it delivered an
+ * exchange to the receive call, as a retried poll could only find exchanges 
it cannot return.
+ */
+public class FilePollEnrichBridgeErrorHandlerInProgressTest extends 
ContextTestSupport {
+
+    private final MemoryIdempotentRepository inProgress = new 
MemoryIdempotentRepository();
+    private final FailOnceReadLockStrategy readLock = new 
FailOnceReadLockStrategy();
+    private final MemoryIdempotentRepository skipRetryInProgress = new 
MemoryIdempotentRepository();
+    private final FailOnceReadLockStrategy skipRetryReadLock = new 
FailOnceReadLockStrategy();
+
+    @Test
+    public void testFileIsReleasedWhenReadLockFailsOnce() {
+        template.sendBodyAndHeader(fileUri(), "Hello World", 
Exchange.FILE_NAME, "hello.txt");
+
+        // the first read lock attempt fails, and pollEnrich returns the 
bridged error
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.requestBody("direct:start", "Start", 
String.class));
+        IOException cause = assertInstanceOf(IOException.class, e.getCause());
+        assertEquals("Forced to simulate a lost connection", 
cause.getMessage());
+
+        // the receive call returned the error, so it must not have taken the 
file as well: an exchange it cannot return
+        // would keep the file in the in-progress repository, and every later 
poll would skip the file
+        assertEquals(0, inProgress.getCacheSize(), "the file must not be left 
in the in-progress repository");
+        assertEquals(1, readLock.attempts.get(), "the file should not be 
polled again after the error was delivered");
+
+        // the next pollEnrich gets the file, which is then committed (moved 
to .camel)
+        String out = template.requestBody("direct:start", "Start", 
String.class);
+        assertEquals("Hello World", out);
+        assertFileExists(testFile(".camel/hello.txt"));
+        assertEquals(0, inProgress.getCacheSize());
+    }
+
+    @Test
+    public void testPollIsNotRetriedWhenErrorWasDelivered() {
+        template.sendBodyAndHeader(fileUri("skipretry"), "Hello World", 
Exchange.FILE_NAME, "hello.txt");
+
+        // the commit of the poll fails after the bridged error was delivered, 
and the poll strategy asks to retry,
+        // but a retried poll could only find exchanges the receive call 
cannot return
+        assertThrows(CamelExecutionException.class, () -> 
template.requestBody("direct:skipRetry", "Start", String.class));
+        assertEquals(1, skipRetryReadLock.attempts.get(), "the poll should not 
be retried");
+        assertEquals(0, skipRetryInProgress.getCacheSize(), "the file must not 
be left in the in-progress repository");
+        assertFileExists(testFile("skipretry/hello.txt"));
+    }
+
+    @Override
+    protected Registry createCamelRegistry() throws Exception {
+        Registry registry = super.createCamelRegistry();
+        registry.bind("failOnceReadLock", readLock);
+        registry.bind("inProgress", inProgress);
+        registry.bind("skipRetryReadLock", skipRetryReadLock);
+        registry.bind("skipRetryInProgress", skipRetryInProgress);
+        registry.bind("retryOncePollStrategy", new RetryOncePollStrategy());
+        return registry;
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("direct:start")
+                        
.pollEnrich(fileUri("?exclusiveReadLockStrategy=#failOnceReadLock&bridgeErrorHandler=true"
+                                            + 
"&inProgressRepository=#inProgress&initialDelay=0&delay=10"),
+                                2000)
+                        .convertBodyTo(String.class);
+
+                from("direct:skipRetry")
+                        
.pollEnrich(fileUri("skipretry?exclusiveReadLockStrategy=#skipRetryReadLock"
+                                            + 
"&bridgeErrorHandler=true&inProgressRepository=#skipRetryInProgress"
+                                            + 
"&pollStrategy=#retryOncePollStrategy&initialDelay=0&delay=10"),
+                                2000)
+                        .convertBodyTo(String.class);
+            }
+        };
+    }
+
+    // simulates a read lock that fails on the first attempt, such as when the 
connection is lost (Pipe closed)
+    private static class FailOnceReadLockStrategy implements 
GenericFileExclusiveReadLockStrategy<File> {
+
+        private final AtomicInteger attempts = new AtomicInteger();
+
+        @Override
+        public void prepareOnStartup(GenericFileOperations<File> operations, 
GenericFileEndpoint<File> endpoint) {
+            // noop
+        }
+
+        @Override
+        public boolean acquireExclusiveReadLock(
+                GenericFileOperations<File> operations, GenericFile<File> 
file, Exchange exchange)
+                throws Exception {
+            if (attempts.incrementAndGet() == 1) {
+                throw new IOException("Forced to simulate a lost connection");
+            }
+            return true;
+        }
+
+        @Override
+        public void releaseExclusiveReadLockOnAbort(
+                GenericFileOperations<File> operations, GenericFile<File> 
file, Exchange exchange) {
+            // noop
+        }
+
+        @Override
+        public void releaseExclusiveReadLockOnRollback(
+                GenericFileOperations<File> operations, GenericFile<File> 
file, Exchange exchange) {
+            // noop
+        }
+
+        @Override
+        public void releaseExclusiveReadLockOnCommit(
+                GenericFileOperations<File> operations, GenericFile<File> 
file, Exchange exchange) {
+            // noop
+        }
+
+        @Override
+        public void setTimeout(long timeout) {
+            // noop
+        }
+
+        @Override
+        public void setCheckInterval(long checkInterval) {
+            // noop
+        }
+
+        @Override
+        public void setReadLockLoggingLevel(LoggingLevel readLockLoggingLevel) 
{
+            // noop
+        }
+
+        @Override
+        public void setMarkerFiler(boolean markerFile) {
+            // noop
+        }
+
+        @Override
+        public void setDeleteOrphanLockFiles(boolean deleteOrphanLockFiles) {
+            // noop
+        }
+    }
+
+    // fails the commit of the first poll, and retries it, as a poll strategy 
can do after a failed poll
+    private static class RetryOncePollStrategy implements 
PollingConsumerPollStrategy {
+
+        private final AtomicInteger commits = new AtomicInteger();
+
+        @Override
+        public boolean begin(Consumer consumer, Endpoint endpoint) {
+            return true;
+        }
+
+        @Override
+        public void commit(Consumer consumer, Endpoint endpoint, int 
polledMessages) {
+            if (commits.incrementAndGet() == 1) {
+                throw new IllegalStateException("Forced to retry the poll");
+            }
+        }
+
+        @Override
+        public boolean rollback(Consumer consumer, Endpoint endpoint, int 
retryCounter, Exception cause) {
+            return retryCounter < 1;
+        }
+    }
+}

Reply via email to