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 5a885da3e27f CAMEL-27209: camel-stream - a scanning stream:http 
consumer opens the stream again after it could not be opened or read (#30465)
5a885da3e27f is described below

commit 5a885da3e27f9d1e8bf2c97bfa2ef66e74787df7
Author: allthingssecurity <[email protected]>
AuthorDate: Fri Nov 20 18:19:11 2026 +0530

    CAMEL-27209: camel-stream - a scanning stream:http consumer opens the 
stream again after it could not be opened or read (#30465)
    
    With scanStream=true the consumer reads in one task that loops while the
    consumer runs, and with retry=true it opens the stream again at its end.
    For stream:http an IOException ended that task: the URL could not be
    opened (server not reachable, or an error status such as 503) at the
    start or when the stream was opened again, or a line could not be read
    (connection lost). The consumer stayed started without reading anything
    until the route was restarted.
    
    - In scan mode a stream that cannot be opened is reported and treated as
      not there yet (as a missing file already is), and a line that cannot be
      read ends the stream; with retry=true the stream is opened again.
    - The first failure in a row goes to the exception handler, the next ones
      are logged at DEBUG; after a failure the scan waits at least one second
      before the next attempt.
    - The consumer that does not scan is unchanged.
    - StreamHttpScanRetryTest: server not available when the stream is opened
      again, when the consumer starts, connection reset while reading, and the
      raw mode.
    
    CAMEL-27209: camel-stream - reset the scan failure count only when data is 
read, and wait before opening the stream again
    
    Review follow-up (davsclaus):
    - The failures in a row are reset when a line is read (a non-empty read in
      raw mode), not when the stream opens. A server that answers and then drops
      the connection before any data, every time, is reported once, the next
      failures at DEBUG, and the scan waits at least one second before each new
      request.
    - After a failure (also when the stream cannot be opened at the start) the
      stream is opened again only after the wait, not in the same loop
      iteration: no second request right after the failed one.
    - Raw mode: a read that fails is reported and ends the stream, as in line
      mode (it was ignored, and the stream opened again right away).
    - Without retry a failed stream is not opened again, and the scan keeps
      waiting at least one second per round instead of looping without a wait.
    - StreamHttpScanRetryTest: a 200 whose connection is reset before the body
      on every request (line and raw mode), and a line then a reset on every
      request; the start test checks the wait before the second request. The
      context is stopped before the server is closed.
    - stream-component.adoc (and its catalog copy): one paragraph about a
      scanned stream that cannot be opened or read; upgrade guide entry.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../camel/catalog/docs/stream-component.adoc       |   4 +
 .../src/main/docs/stream-component.adoc            |   4 +
 .../camel/component/stream/StreamConsumer.java     | 134 ++++++++--
 .../component/stream/StreamHttpScanRetryTest.java  | 284 +++++++++++++++++++++
 .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc    |   9 +
 5 files changed, 412 insertions(+), 23 deletions(-)

diff --git 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/stream-component.adoc
 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/stream-component.adoc
index 0aa67edeb8fe..5ff54ffa104d 100644
--- 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/stream-component.adoc
+++ 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/stream-component.adoc
@@ -194,6 +194,10 @@ YAML::
 ----
 ====
 
+When a scanned stream cannot be opened or read (such as a `stream:http` server 
that is down, or a lost connection),
+the first failure in a row goes to the exception handler and the next ones are 
logged at DEBUG until data is read
+again, and with `retry` the stream is opened again, at least one second after 
the failure.
+
 === Reading HTTP server side streaming
 
 The camel-stream component has basic support for connecting to a remote HTTP 
server and read streaming data
diff --git a/components/camel-stream/src/main/docs/stream-component.adoc 
b/components/camel-stream/src/main/docs/stream-component.adoc
index 0aa67edeb8fe..5ff54ffa104d 100644
--- a/components/camel-stream/src/main/docs/stream-component.adoc
+++ b/components/camel-stream/src/main/docs/stream-component.adoc
@@ -194,6 +194,10 @@ YAML::
 ----
 ====
 
+When a scanned stream cannot be opened or read (such as a `stream:http` server 
that is down, or a lost connection),
+the first failure in a row goes to the exception handler and the next ones are 
logged at DEBUG until data is read
+again, and with `retry` the stream is opened again, at least one second after 
the failure.
+
 === Reading HTTP server side streaming
 
 The camel-stream component has basic support for connecting to a remote HTTP 
server and read streaming data
diff --git 
a/components/camel-stream/src/main/java/org/apache/camel/component/stream/StreamConsumer.java
 
b/components/camel-stream/src/main/java/org/apache/camel/component/stream/StreamConsumer.java
index 683c668ba7bf..54605dca16fc 100644
--- 
a/components/camel-stream/src/main/java/org/apache/camel/component/stream/StreamConsumer.java
+++ 
b/components/camel-stream/src/main/java/org/apache/camel/component/stream/StreamConsumer.java
@@ -54,6 +54,8 @@ public class StreamConsumer extends DefaultConsumer 
implements Runnable {
     private static final String TYPES = "in,file,http";
     private static final String INVALID_URI = "Invalid uri, valid form: 
'stream:{" + TYPES + "}'";
     private static final List<String> TYPES_LIST = 
Arrays.asList(TYPES.split(","));
+    // the least time to wait before the stream is opened again after it could 
not be opened or read when scanning
+    private static final long SCAN_FAILURE_DELAY = 1000;
     private ExecutorService executor;
     private FileWatcherStrategy fileWatcher;
     private volatile boolean watchFileChanged;
@@ -66,6 +68,10 @@ public class StreamConsumer extends DefaultConsumer 
implements Runnable {
     private volatile boolean initialPromptDone;
     private volatile boolean streamOpenedOnStart;
     private final List<String> lines = new CopyOnWriteArrayList<>();
+    // the failures in a row to open or read a scanned stream (reset once data 
is read again), and whether the scan
+    // must wait before it opens the stream again, only used by the thread 
that reads
+    private int scanFailures;
+    private boolean scanFailedBeforeSleep;
 
     public StreamConsumer(StreamEndpoint endpoint, Processor processor, String 
uri) throws Exception {
         super(endpoint, processor);
@@ -101,6 +107,8 @@ public class StreamConsumer extends DefaultConsumer 
implements Runnable {
             streamOpenedOnStart = true;
         }
 
+        scanFailures = 0;
+        scanFailedBeforeSleep = false;
         executor = 
endpoint.getCamelContext().getExecutorServiceManager().newSingleThreadExecutor(this,
                 endpoint.getEndpointUri());
         executor.execute(this);
@@ -193,9 +201,9 @@ public class StreamConsumer extends DefaultConsumer 
implements Runnable {
 
     private void readFromStreamRawMode() throws Exception {
         long index = 0;
-        InputStream is = initializeStreamRawMode();
 
         if (endpoint.isScanStream()) {
+            InputStream is = openScannedStream(this::initializeStreamRawMode);
             // repeat scanning from stream
             while (isRunAllowed()) {
 
@@ -204,22 +212,28 @@ public class StreamConsumer extends DefaultConsumer 
implements Runnable {
                     try {
                         data = is.readAllBytes();
                     } catch (IOException e) {
-                        // ignore
+                        // such as an HTTP connection that is lost: the stream 
ends here, and is opened again (retry)
+                        scanFailed("Cannot read from the stream", e);
+                        is = null;
                     }
                 }
                 boolean eos = data == null || data.length == 0;
+                if (!eos) {
+                    scanRecovered();
+                }
 
                 if (!eos && isRunAllowed()) {
                     // a scanned stream is never complete
                     index = processRaw(data, index, false);
-                } else if (eos && isRunAllowed() && endpoint.isRetry()) {
+                } else if (eos && isRunAllowed() && endpoint.isRetry() && 
!scanFailedBeforeSleep) {
+                    // not right after a failure: then the stream is opened 
again after the sleep below
                     boolean reOpen = true;
                     if (endpoint.isFileWatcher()) {
                         reOpen = watchFileChanged;
                     }
                     if (reOpen) {
                         LOG.debug("File: {} changed/rollover, re-reading file 
from beginning", file);
-                        is = initializeStreamRawMode();
+                        is = openScannedStream(this::initializeStreamRawMode);
                         // we have re-initialized the stream so lower changed 
flag
                         if (endpoint.isFileWatcher()) {
                             watchFileChanged = false;
@@ -230,16 +244,12 @@ public class StreamConsumer extends DefaultConsumer 
implements Runnable {
                 }
 
                 // sleep only if there is no input
-                if (eos) {
-                    try {
-                        Thread.sleep(endpoint.getScanStreamDelay());
-                    } catch (InterruptedException e) {
-                        Thread.currentThread().interrupt();
-                        break;
-                    }
+                if (eos && !sleepBeforeNextScan()) {
+                    break;
                 }
             }
         } else {
+            InputStream is = initializeStreamRawMode();
             // regular read stream once until end of stream
             boolean eos = false;
             while (!eos && isRunAllowed()) {
@@ -264,28 +274,39 @@ public class StreamConsumer extends DefaultConsumer 
implements Runnable {
     private void readFromStreamLineMode() throws Exception {
         long index = 0;
         String line;
-        BufferedReader br = initializeStreamLineMode();
 
         if (endpoint.isScanStream()) {
+            BufferedReader br = 
openScannedStream(this::initializeStreamLineMode);
             // repeat scanning from stream
             while (isRunAllowed()) {
                 if (br != null) {
-                    line = br.readLine();
-                    LOG.trace("Read line: {}", line);
+                    try {
+                        line = br.readLine();
+                        LOG.trace("Read line: {}", line);
+                        if (line != null) {
+                            scanRecovered();
+                        }
+                    } catch (IOException e) {
+                        // such as an HTTP connection that is lost: the stream 
ends here, and is opened again (retry)
+                        scanFailed("Cannot read from the stream", e);
+                        br = null;
+                        line = null;
+                    }
                 } else {
                     line = null;
                 }
                 boolean eos = line == null;
                 if (!eos && isRunAllowed()) {
                     index = processLine(line, false, index);
-                } else if (eos && isRunAllowed() && endpoint.isRetry()) {
+                } else if (eos && isRunAllowed() && endpoint.isRetry() && 
!scanFailedBeforeSleep) {
+                    // not right after a failure: then the stream is opened 
again after the sleep below
                     boolean reOpen = true;
                     if (endpoint.isFileWatcher()) {
                         reOpen = watchFileChanged;
                     }
                     if (reOpen) {
                         LOG.debug("File: {} changed/rollover, re-reading file 
from beginning", file);
-                        br = initializeStreamLineMode();
+                        br = openScannedStream(this::initializeStreamLineMode);
                         // we have re-initialized the stream so lower changed 
flag
                         if (endpoint.isFileWatcher()) {
                             watchFileChanged = false;
@@ -296,16 +317,12 @@ public class StreamConsumer extends DefaultConsumer 
implements Runnable {
                 }
 
                 // sleep only if there is no input
-                if (eos) {
-                    try {
-                        Thread.sleep(endpoint.getScanStreamDelay());
-                    } catch (InterruptedException e) {
-                        Thread.currentThread().interrupt();
-                        break;
-                    }
+                if (eos && !sleepBeforeNextScan()) {
+                    break;
                 }
             }
         } else {
+            BufferedReader br = initializeStreamLineMode();
             // regular read stream once until end of stream
             boolean eos = false;
             String line2 = null;
@@ -335,6 +352,77 @@ public class StreamConsumer extends DefaultConsumer 
implements Runnable {
         // important: do not close the reader as it will close the standard 
system.in etc.
     }
 
+    /**
+     * Opens the scanned stream. A stream that cannot be opened (such as an 
HTTP server that cannot be reached) is
+     * reported and gives null, as a file that does not exist yet does: the 
scan opens it again later (retry) instead of
+     * ending, which would leave the consumer started without reading anything.
+     */
+    private <T> T openScannedStream(ScannedStreamOpener<T> opener) throws 
InterruptedException {
+        try {
+            return opener.open();
+        } catch (InterruptedException e) {
+            throw e;
+        } catch (Exception e) {
+            scanFailed("Cannot open the stream", e);
+            return null;
+        }
+    }
+
+    private void scanFailed(String message, Exception cause) {
+        if (!isRunAllowed()) {
+            // stopping: the stream was closed by the stop
+            return;
+        }
+        scanFailures++;
+        scanFailedBeforeSleep = true;
+        // the stream is opened again only with the retry option, as at the 
end of the stream
+        String next = endpoint.isRetry() ? ", it is opened again" : ", set the 
retry option to open it again";
+        if (scanFailures == 1) {
+            getExceptionHandler().handleException(message + " of " + endpoint 
+ next, cause);
+        } else {
+            LOG.debug("{} of {} ({} times in a row){}", message, endpoint, 
scanFailures, next, cause);
+        }
+    }
+
+    /**
+     * Data was read from the scanned stream: a failure after this is the 
first one in a row again. The counter is not
+     * reset when the stream is opened, as a server that answers and then 
drops the connection before any data every
+     * time would otherwise report every failure to the exception handler.
+     */
+    private void scanRecovered() {
+        if (scanFailures > 0) {
+            LOG.info("Reading from the stream of {} again after {} failed 
attempts", endpoint, scanFailures);
+            scanFailures = 0;
+        }
+    }
+
+    /**
+     * Waits before the next scan of the stream: the scan stream delay, and at 
least one second after the stream could
+     * not be opened or read, so that a server that is down is not asked in a 
loop. Without retry a stream that failed
+     * is not opened again, and the scan keeps waiting at least one second 
until it is stopped.
+     *
+     * @return false if interrupted (the consumer is stopping)
+     */
+    private boolean sleepBeforeNextScan() {
+        long delay = endpoint.getScanStreamDelay();
+        if (scanFailedBeforeSleep || scanFailures > 0 && !endpoint.isRetry()) {
+            delay = Math.max(delay, SCAN_FAILURE_DELAY);
+            scanFailedBeforeSleep = false;
+        }
+        try {
+            Thread.sleep(delay);
+            return true;
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+            return false;
+        }
+    }
+
+    @FunctionalInterface
+    private interface ScannedStreamOpener<T> {
+        T open() throws Exception;
+    }
+
     /**
      * Strategy method for processing the line
      */
diff --git 
a/components/camel-stream/src/test/java/org/apache/camel/component/stream/StreamHttpScanRetryTest.java
 
b/components/camel-stream/src/test/java/org/apache/camel/component/stream/StreamHttpScanRetryTest.java
new file mode 100644
index 000000000000..a3659b958e1e
--- /dev/null
+++ 
b/components/camel-stream/src/test/java/org/apache/camel/component/stream/StreamHttpScanRetryTest.java
@@ -0,0 +1,284 @@
+/*
+ * 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.stream;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.SocketTimeoutException;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.spi.ExceptionHandler;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A stream:http consumer with scanStream and retry keeps reading when the 
HTTP server cannot be reached or the
+ * connection is lost for a while, instead of ending its reading thread while 
the route stays started.
+ */
+class StreamHttpScanRetryTest extends CamelTestSupport {
+
+    // the least time between two requests when the one before failed, a bit 
less than the 1 s the consumer waits
+    private static final long FAILURE_DELAY_MILLIS = 900;
+
+    private final AtomicInteger requests = new AtomicInteger();
+    private final List<Long> requestTimes = new CopyOnWriteArrayList<>();
+    private final AtomicInteger handledFailures = new AtomicInteger();
+    private final ExecutorService serverThread = 
Executors.newSingleThreadExecutor();
+    private ServerSocket server;
+
+    @AfterEach
+    void stopServer() throws Exception {
+        // stop the consumer first, so that it does not find the server gone 
while it is still running
+        context.stop();
+        if (server != null) {
+            server.close();
+        }
+        serverThread.shutdownNow();
+    }
+
+    @Override
+    public boolean isUseRouteBuilder() {
+        return false;
+    }
+
+    @Test
+    void testServerNotAvailableWhenReopened() throws Exception {
+        // the first request is answered, the second fails (the server is 
down), the next ones are answered again
+        serve(List.of("a\n", "", "b\n"));
+        MockEndpoint mock = expectFirstBodies("a", "b");
+
+        startRoute("");
+
+        mock.assertIsSatisfied();
+        assertFirstBodies(mock, "a", "b");
+    }
+
+    @Test
+    void testServerNotAvailableWhenStarted() throws Exception {
+        serve(List.of("", "a\n"));
+        MockEndpoint mock = expectFirstBodies("a");
+
+        startRoute("");
+
+        mock.assertIsSatisfied();
+        assertFirstBodies(mock, "a");
+        // the stream that could not be opened at the start is not asked again 
right away
+        assertWaitedAfterFailures(2);
+    }
+
+    @Test
+    void testConnectionLostWhileReading() throws Exception {
+        // the connection of the first answer is reset before the length it 
announced was sent: reading it fails
+        serve(List.of("a\n|cut", "b\n"));
+        MockEndpoint answeredAgain = getMockEndpoint("mock:b");
+        answeredAgain.expectedMinimumMessageCount(1);
+
+        startRoute("");
+
+        answeredAgain.assertIsSatisfied();
+    }
+
+    @Test
+    void testConnectionLostOnEveryRequest() throws Exception {
+        // every answer is a 200 whose connection is reset before any of the 
body was sent: every open succeeds and
+        // every read fails, and the scan does not end up in a loop of 
requests, each one reported
+        serve(List.of("|cut"));
+
+        startRoute("");
+
+        awaitRequests(4);
+        // the first failure in a row goes to the exception handler, the next 
ones are logged at DEBUG
+        assertEquals(1, handledFailures.get());
+        assertEquals(0, getMockEndpoint("mock:result").getReceivedCounter());
+        assertWaitedAfterFailures(4);
+    }
+
+    @Test
+    void testConnectionLostOnEveryRequestRawMode() throws Exception {
+        // in raw mode the whole body is read at once: the line sent before 
the reset is lost with it
+        serve(List.of("a\n|cut"));
+
+        startRoute("&readLine=false");
+
+        awaitRequests(4);
+        assertEquals(1, handledFailures.get());
+        assertEquals(0, getMockEndpoint("mock:result").getReceivedCounter());
+        assertWaitedAfterFailures(4);
+    }
+
+    @Test
+    void testConnectionLostAfterDataOnEveryRequest() throws Exception {
+        // every answer sends a line before its connection is reset: each line 
is routed, and the scan still waits
+        // after each failure (as a line was read, the failure after it is 
reported again)
+        serve(List.of("a\n|cut"));
+        MockEndpoint mock = expectFirstBodies("a", "a", "a");
+
+        startRoute("");
+
+        assertWaitedAfterFailures(4);
+        mock.assertIsSatisfied();
+        assertFirstBodies(mock, "a", "a", "a");
+    }
+
+    @Test
+    void testServerNotAvailableWhenReopenedRawMode() throws Exception {
+        serve(List.of("a\n", "", "b\n"));
+        MockEndpoint mock = expectFirstBodies("a\n", "b\n");
+
+        startRoute("&readLine=false");
+
+        mock.assertIsSatisfied();
+        assertFirstBodies(mock, "a\n", "b\n");
+    }
+
+    /**
+     * An HTTP server that answers the requests with the given answers in 
turn, the last one for all the requests after,
+     * and closes each connection after its answer: an empty answer is the 
status 503 (opening the stream fails), and an
+     * answer that ends with "|cut" announces a longer body than it sends 
before the connection is reset (the connection
+     * is lost while reading).
+     */
+    private void serve(List<String> answers) throws IOException {
+        server = new ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"));
+        serverThread.execute(() -> {
+            while (!server.isClosed()) {
+                try (Socket socket = server.accept()) {
+                    readRequest(socket.getInputStream());
+                    requestTimes.add(System.nanoTime());
+                    String answer = 
answers.get(Math.min(requests.getAndIncrement(), answers.size() - 1));
+                    socket.getOutputStream().write(response(answer));
+                    socket.getOutputStream().flush();
+                    if (answer.endsWith("|cut")) {
+                        // give the client a moment to read what was sent (it 
sends nothing more, so the read times
+                        // out), then reset the connection (lost, not ended)
+                        socket.setSoTimeout(200);
+                        try {
+                            socket.getInputStream().read();
+                        } catch (SocketTimeoutException e) {
+                            // the client is waiting for the rest of the body
+                        }
+                        socket.setSoLinger(true, 0);
+                    }
+                } catch (IOException e) {
+                    // closed by the test
+                }
+            }
+        });
+    }
+
+    private static void readRequest(InputStream in) throws IOException {
+        // up to the empty line that ends the request head (a GET has no body)
+        int matched = 0;
+        int b;
+        while (matched < 4 && (b = in.read()) != -1) {
+            matched = b == "\r\n\r\n".charAt(matched) ? matched + 1 : (b == 
'\r' ? 1 : 0);
+        }
+    }
+
+    private static byte[] response(String answer) {
+        if (answer.isEmpty()) {
+            return "HTTP/1.1 503 Service Unavailable\r\nContent-Length: 
0\r\nConnection: close\r\n\r\n"
+                    .getBytes(StandardCharsets.US_ASCII);
+        }
+        boolean cut = answer.endsWith("|cut");
+        String body = answer.replace("|cut", "");
+        int length = body.length() + (cut ? 100 : 0);
+        return ("HTTP/1.1 200 OK\r\nContent-Length: " + length + 
"\r\nConnection: close\r\n\r\n" + body)
+                .getBytes(StandardCharsets.US_ASCII);
+    }
+
+    private MockEndpoint expectFirstBodies(String... bodies) {
+        MockEndpoint mock = getMockEndpoint("mock:result");
+        // with retry, the stream is opened again at its end, and the last 
answer is read again and again
+        mock.expectedMinimumMessageCount(bodies.length);
+        return mock;
+    }
+
+    private static void assertFirstBodies(MockEndpoint mock, String... bodies) 
{
+        for (int i = 0; i < bodies.length; i++) {
+            assertEquals(bodies[i], 
mock.getExchanges().get(i).getIn().getBody(String.class));
+        }
+    }
+
+    /**
+     * Waits for the given number of requests, each one after a request that 
failed, and checks that the consumer waited
+     * about a second before each of them instead of asking the server again 
right away.
+     */
+    private void assertWaitedAfterFailures(int count) {
+        awaitRequests(count);
+        for (int i = 1; i < count; i++) {
+            long millis = TimeUnit.NANOSECONDS.toMillis(requestTimes.get(i) - 
requestTimes.get(i - 1));
+            assertTrue(millis >= FAILURE_DELAY_MILLIS, "request " + (i + 1) + 
" came " + millis + " ms after the one before");
+        }
+    }
+
+    private void awaitRequests(int count) {
+        await().atMost(20, TimeUnit.SECONDS).until(() -> requestTimes.size() 
>= count);
+    }
+
+    private void startRoute(String options) throws Exception {
+        String url = "http://127.0.0.1:"; + server.getLocalPort() + "/data.txt";
+        context.getRegistry().bind("countingExceptionHandler", new 
CountingExceptionHandler());
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                
from("stream:http?scanStream=true&retry=true&scanStreamDelay=50&httpUrl=" + url 
+ options
+                     + "&exceptionHandler=#countingExceptionHandler")
+                        .to("mock:result")
+                        .filter(body().isEqualTo("b")).to("mock:b");
+            }
+        });
+        context.start();
+    }
+
+    /**
+     * Counts the failures the consumer reports to its exception handler.
+     */
+    private class CountingExceptionHandler implements ExceptionHandler {
+
+        @Override
+        public void handleException(Throwable exception) {
+            handledFailures.incrementAndGet();
+        }
+
+        @Override
+        public void handleException(String message, Throwable exception) {
+            handledFailures.incrementAndGet();
+        }
+
+        @Override
+        public void handleException(String message, Exchange exchange, 
Throwable exception) {
+            handledFailures.incrementAndGet();
+        }
+    }
+}
diff --git 
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc 
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index 42eb192a0e55..96026a408d5b 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -3097,6 +3097,15 @@ default). It fails with a 
`java.util.concurrent.TimeoutException` when RabbitMQ
 and with an `org.springframework.amqp.AmqpTimeoutException` when RabbitMQ does 
not confirm it within `confirmTimeout`.
 Set `confirm=disabled` to send without waiting, as before.
 
+=== camel-stream - a scanning consumer keeps going after the stream cannot be 
opened or read
+
+A `stream` consumer with `scanStream=true` no longer ends its reading thread 
when the stream cannot be opened (for
+example a `stream:http` server that is down or answers 503) or a read fails 
(the connection is lost). Before, the route
+stayed started but read nothing until it was restarted. Now the first failure 
in a row goes to the exception handler of
+the consumer (a WARN by default) and the next ones are logged at DEBUG, until 
data is read again. With `retry=true` the
+stream is opened again, at least one second after the failure (or after 
`scanStreamDelay`, if longer). In raw mode
+(`readLine=false`) a read that fails is reported in the same way; before, it 
was ignored.
+
 === camel-cyberark-vault - verifySsl and certificatePath are applied, and 
getSecret no longer sets the CamelCyberArkVaultSecretValue header
 
 The `verifySsl` and `certificatePath` options of the `cyberark-vault` 
endpoint, and the

Reply via email to