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 42f115442095 CAMEL-27265: camel-netty-http - chunked requests get a
response on the shared HTTP server (#30526)
42f115442095 is described below
commit 42f1154420955862d5f6ea53b5f5be856b15a5e8
Author: allthingssecurity <[email protected]>
AuthorDate: Sat Nov 21 14:38:21 2026 +0530
CAMEL-27265: camel-netty-http - chunked requests get a response on the
shared HTTP server (#30526)
A request with a chunked body got no response on the shared HTTP server:
its pipeline streamed the body through a pipe that the I/O thread, which
also runs the routes, both wrote and read. This also held the other
connections of that I/O thread, also when the route did not read the
body or no route matched the path. With chunked=false the shared server
had no aggregator, and every request failed.
The shared server now always aggregates the request and keeps the
outbound streamer, so chunked=false works like the default (the chunked
option is no longer used).
With disableStreamCache=true the server of an endpoint streams a chunked
request only when the route runs on the executor service; with
usingExecutorService=false the request is aggregated.
HttpInboundStreamHandler no longer uses a pipe: each message gets its own
stream, the I/O thread never waits for the reader (the connection is not
read while 64 KB wait to be read), the consumer closes the stream when
the exchange is done and the rest of the body is discarded, a connection
closed before the end fails the stream, and reading it on the I/O thread
of its connection fails instead of waiting for ever. A body that the
route does not read, a request to an unknown path, and a second chunked
request on the same connection now get a response.
A streamed reply may read the request stream after the exchange is done
(a route that sends the body back, or wraps it in another stream), so the
consumer passes a streamed reply on in a small subclass that closes the
request stream once the outbound streamer has written or failed the
reply, or the connection is closed. The outbound streamer closes the
connection when the body of a streamed message fails to be read or
written, as its headers are sent already.
Docs and the 4.24 upgrade guide are updated; the guide also notes that an
aggregated chunked request is limited by chunkedMaxContentLength, and
that a large body the route does not read can wait for a large streamed
reply.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-authored-by: Claus Ibsen <[email protected]>
---
.../camel/catalog/docs/netty-http-component.adoc | 9 +
.../src/main/docs/netty-http-component.adoc | 9 +
.../netty/http/HttpServerInitializerFactory.java | 4 +-
.../http/HttpServerSharedInitializerFactory.java | 10 +-
...ettySharedHttpServerBootstrapConfiguration.java | 4 +
.../netty/http/OutboundStreamHttpResponse.java | 8 +
.../http/handlers/HttpInboundStreamHandler.java | 209 +++++++++++++++++---
.../http/handlers/HttpOutboundStreamHandler.java | 4 +
.../http/handlers/HttpServerChannelHandler.java | 76 ++++++-
...tyHttpChunkedRequestDisableStreamCacheTest.java | 219 +++++++++++++++++++++
.../NettySharedHttpServerChunkedRequestTest.java | 145 ++++++++++++++
.../http/NettySharedHttpServerNotChunkedTest.java | 28 +++
.../camel/component/netty/http/RawHttpClient.java | 159 +++++++++++++++
.../handlers/HttpInboundStreamHandlerTest.java | 134 +++++++++++++
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 38 ++++
15 files changed, 1025 insertions(+), 31 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/netty-http-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/netty-http-component.adoc
index 3e0cedfb7afc..600302cc6600 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/netty-http-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/netty-http-component.adoc
@@ -30,6 +30,13 @@ for a chunked message), which you can only read *once*. If
you find a situation
message body then appears to be empty, or you need to access the data multiple
times (eg: doing
multicasting, or redelivery error handling), convert the message body to a
`String` or a `byte[]`
which is safe to be re-read multiple times.
+
+On the consumer, the body of a chunked request is an `InputStream` only when
the route runs on the executor
+service (`usingExecutorService=true`, the default), as the body cannot be
received while the route waits for it
+on the I/O thread; otherwise the request is aggregated as any other. The
stream is closed when the exchange is done,
+and the part of the body that the route did not read is discarded. When the
reply is streamed (its body is an
+`InputStream`), the stream is closed once the reply is written instead, as the
reply may read it (the request body sent
+back, as it is or in another stream); such a reply reads it on the I/O thread,
so the body must be received already.
====
Maven users will need to add the following dependency to their `pom.xml`
@@ -708,6 +715,8 @@ or the xref:platform-http-component.adoc[Platform HTTP]
component, which uses th
A `DefaultNettySharedHttpServer` is a Netty HTTP server that is configured
with a
`NettySharedHttpServerBootstrapConfiguration` and started on its own. The
consumers that refer to it with the
`nettySharedHttpServer` option use its port and its pipeline, instead of the
server that the component creates.
+The routes run on the I/O threads of the shared server, so it aggregates each
request, also a chunked one, before
+the route is called (the `chunked` option of
`NettySharedHttpServerBootstrapConfiguration` is not used).
=== Implementing a reverse proxy
diff --git
a/components/camel-netty-http/src/main/docs/netty-http-component.adoc
b/components/camel-netty-http/src/main/docs/netty-http-component.adoc
index 3e0cedfb7afc..600302cc6600 100644
--- a/components/camel-netty-http/src/main/docs/netty-http-component.adoc
+++ b/components/camel-netty-http/src/main/docs/netty-http-component.adoc
@@ -30,6 +30,13 @@ for a chunked message), which you can only read *once*. If
you find a situation
message body then appears to be empty, or you need to access the data multiple
times (eg: doing
multicasting, or redelivery error handling), convert the message body to a
`String` or a `byte[]`
which is safe to be re-read multiple times.
+
+On the consumer, the body of a chunked request is an `InputStream` only when
the route runs on the executor
+service (`usingExecutorService=true`, the default), as the body cannot be
received while the route waits for it
+on the I/O thread; otherwise the request is aggregated as any other. The
stream is closed when the exchange is done,
+and the part of the body that the route did not read is discarded. When the
reply is streamed (its body is an
+`InputStream`), the stream is closed once the reply is written instead, as the
reply may read it (the request body sent
+back, as it is or in another stream); such a reply reads it on the I/O thread,
so the body must be received already.
====
Maven users will need to add the following dependency to their `pom.xml`
@@ -708,6 +715,8 @@ or the xref:platform-http-component.adoc[Platform HTTP]
component, which uses th
A `DefaultNettySharedHttpServer` is a Netty HTTP server that is configured
with a
`NettySharedHttpServerBootstrapConfiguration` and started on its own. The
consumers that refer to it with the
`nettySharedHttpServer` option use its port and its pipeline, instead of the
server that the component creates.
+The routes run on the I/O threads of the shared server, so it aggregates each
request, also a chunked one, before
+the route is called (the `chunked` option of
`NettySharedHttpServerBootstrapConfiguration` is not used).
=== Implementing a reverse proxy
diff --git
a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/HttpServerInitializerFactory.java
b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/HttpServerInitializerFactory.java
index e42b50a5cf44..40ccc0a532ca 100644
---
a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/HttpServerInitializerFactory.java
+++
b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/HttpServerInitializerFactory.java
@@ -114,7 +114,9 @@ public class HttpServerInitializerFactory extends
ServerInitializerFactory {
}
pipeline.addLast("encoder-" + x, encoder);
}
- if (configuration.isDisableStreamCache()) {
+ // a chunked request is streamed to the route only when the route runs
on the executor service, as the body
+ // is received by the I/O thread, which cannot wait for the route to
read it
+ if (configuration.isDisableStreamCache() &&
consumer.getConfiguration().isUsingExecutorService()) {
pipeline.addLast("inbound-streamer", new
HttpInboundStreamHandler());
}
pipeline.addLast("aggregator", new
HttpObjectAggregator(configuration.getChunkedMaxContentLength()));
diff --git
a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/HttpServerSharedInitializerFactory.java
b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/HttpServerSharedInitializerFactory.java
index 417ffdbcc03b..b7fe651b6f33 100644
---
a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/HttpServerSharedInitializerFactory.java
+++
b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/HttpServerSharedInitializerFactory.java
@@ -30,7 +30,6 @@ import org.apache.camel.CamelContext;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.component.netty.NettyConsumer;
import org.apache.camel.component.netty.ServerInitializerFactory;
-import org.apache.camel.component.netty.http.handlers.HttpInboundStreamHandler;
import
org.apache.camel.component.netty.http.handlers.HttpOutboundStreamHandler;
import org.apache.camel.component.netty.ssl.SSLEngineFactory;
import org.slf4j.Logger;
@@ -92,11 +91,10 @@ public class HttpServerSharedInitializerFactory extends
HttpServerInitializerFac
pipeline.addLast("decoder", new HttpRequestDecoder(
configuration.getMaxInitialLineLength(),
configuration.getMaxHeaderSize(), configuration.getMaxChunkSize()));
pipeline.addLast("encoder", new HttpResponseEncoder());
- if (configuration.isChunked()) {
- pipeline.addLast("inbound-streamer", new
HttpInboundStreamHandler());
- pipeline.addLast("aggregator", new
HttpObjectAggregator(configuration.getChunkedMaxContentLength()));
- pipeline.addLast("outbound-streamer", new
HttpOutboundStreamHandler());
- }
+ // the routes run on the I/O thread that receives the request, which
cannot wait for a route to read the body,
+ // so each request, also a chunked one, is aggregated before it is
passed on to the route
+ pipeline.addLast("aggregator", new
HttpObjectAggregator(configuration.getChunkedMaxContentLength()));
+ pipeline.addLast("outbound-streamer", new HttpOutboundStreamHandler());
if (configuration.isCompression()) {
pipeline.addLast("deflater", new HttpContentCompressor());
}
diff --git
a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/NettySharedHttpServerBootstrapConfiguration.java
b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/NettySharedHttpServerBootstrapConfiguration.java
index ce3d8bbf4297..883218102d20 100644
---
a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/NettySharedHttpServerBootstrapConfiguration.java
+++
b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/NettySharedHttpServerBootstrapConfiguration.java
@@ -39,6 +39,10 @@ public class NettySharedHttpServerBootstrapConfiguration
extends NettyServerBoot
return chunked;
}
+ /**
+ * Not used: the server aggregates each request, also a chunked one,
before it is passed on to the route, as the
+ * server of a netty-http endpoint does. The size of the body is limited
by chunkedMaxContentLength.
+ */
public void setChunked(boolean chunked) {
this.chunked = chunked;
}
diff --git
a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/OutboundStreamHttpResponse.java
b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/OutboundStreamHttpResponse.java
index d3b5b57a88a1..b9e684f2c4e6 100644
---
a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/OutboundStreamHttpResponse.java
+++
b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/OutboundStreamHttpResponse.java
@@ -35,6 +35,14 @@ public class OutboundStreamHttpResponse extends
DefaultHttpResponse implements C
this.input = new HttpChunkedInput(new ChunkedStream(in));
}
+ /**
+ * A response with the status, headers and body stream of the given
response, such as to add behaviour to it.
+ */
+ protected OutboundStreamHttpResponse(OutboundStreamHttpResponse response) {
+ super(response.protocolVersion(), response.status(),
response.headers());
+ this.input = response.input;
+ }
+
public DefaultHttpResponse getResponse() {
return new DefaultHttpResponse(this.protocolVersion(), this.status(),
this.headers());
}
diff --git
a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpInboundStreamHandler.java
b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpInboundStreamHandler.java
index 0170cbd6cb71..c6b9903594dc 100644
---
a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpInboundStreamHandler.java
+++
b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpInboundStreamHandler.java
@@ -14,14 +14,19 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.camel.component.netty.http.handlers;
-import java.io.PipedInputStream;
-import java.io.PipedOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InterruptedIOException;
+import java.util.ArrayDeque;
+import java.util.Deque;
import java.util.List;
+import java.util.Objects;
import io.netty.buffer.ByteBuf;
+import io.netty.buffer.ByteBufUtil;
+import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.HttpContent;
@@ -37,24 +42,41 @@ import
org.apache.camel.component.netty.http.InboundStreamHttpResponse;
import static io.netty.handler.codec.http.HttpHeaderNames.TRANSFER_ENCODING;
import static io.netty.handler.codec.http.HttpHeaderValues.CHUNKED;
+/**
+ * Passes a chunked HTTP message on as soon as its headers are received, with
an {@link InputStream} of its body, which
+ * gets the chunks as they are received.
+ * <p/>
+ * The I/O thread of the connection never waits for the reader of the body:
when {@link #HIGH_WATER_MARK} bytes of the
+ * body are waiting to be read, the handler stops reading from the connection,
and reads again when the reader has
+ * caught up. The body must therefore be read by another thread than the I/O
thread of the connection; reading it on
+ * that thread fails rather than waiting for data that cannot be received.
Closing the stream discards the rest of the
+ * body. Each message gets its own stream.
+ */
public class HttpInboundStreamHandler extends
MessageToMessageDecoder<HttpObject> {
- private PipedInputStream is;
- private PipedOutputStream os;
+
+ /**
+ * The number of bytes of the body that can wait to be read before the
handler stops reading from the connection.
+ */
+ static final int HIGH_WATER_MARK = 64 * 1024;
+
+ /**
+ * The number of bytes of the body waiting to be read below which the
handler reads from the connection again.
+ */
+ static final int LOW_WATER_MARK = HIGH_WATER_MARK / 2;
+
+ private InboundStream stream;
private boolean isChunked;
@Override
- public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
- super.handlerAdded(ctx);
- os = new PipedOutputStream();
- is = new PipedInputStream(os);
- isChunked = false;
+ public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
+ super.handlerRemoved(ctx);
+ failStream();
}
@Override
- public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
- super.handlerRemoved(ctx);
- os.close();
- is.close();
+ public void channelInactive(ChannelHandlerContext ctx) throws Exception {
+ failStream();
+ super.channelInactive(ctx);
}
@Override
@@ -73,24 +95,165 @@ public class HttpInboundStreamHandler extends
MessageToMessageDecoder<HttpObject
@Override
protected void decode(ChannelHandlerContext ctx, HttpObject msg,
List<Object> out) throws Exception {
+ if (msg instanceof HttpMessage) {
+ failStream();
+ stream = new InboundStream(ctx.channel());
+ }
+
if (msg instanceof HttpRequest httpRequest) {
- InboundStreamHttpRequest request = new
InboundStreamHttpRequest(httpRequest, is);
- out.add(request);
+ out.add(new InboundStreamHttpRequest(httpRequest, stream));
}
if (msg instanceof HttpResponse httpResponse) {
- InboundStreamHttpResponse response = new
InboundStreamHttpResponse(httpResponse, is);
- out.add(response);
+ out.add(new InboundStreamHttpResponse(httpResponse, stream));
}
- if (msg instanceof HttpContent httpContent) {
- ByteBuf body = httpContent.content();
- if (body.readableBytes() > 0) {
- body.readBytes(os, body.readableBytes());
+ if (msg instanceof HttpContent httpContent && stream != null) {
+ if (httpContent.decoderResult().isFailure()) {
+ stream.fail(new IOException(
+ "Invalid chunked body: " +
httpContent.decoderResult().cause().getMessage(),
+ httpContent.decoderResult().cause()));
+ stream = null;
+ return;
}
+ stream.offer(httpContent.content());
+
if (msg instanceof LastHttpContent) {
- os.close();
+ stream.end();
+ stream = null;
+ }
+ }
+ }
+
+ private void failStream() {
+ if (stream != null) {
+ stream.fail(new IOException("The connection was closed before the
whole body was received"));
+ stream = null;
+ }
+ }
+
+ /**
+ * The body of a chunked message: the I/O thread adds the chunks, and
another thread reads them.
+ */
+ private static final class InboundStream extends InputStream {
+ private final Channel channel;
+ private final Deque<byte[]> chunks = new ArrayDeque<>();
+ // the position in the first chunk
+ private int position;
+ // the number of bytes waiting to be read
+ private int waiting;
+ private boolean ended;
+ private boolean closed;
+ private boolean suspended;
+ private IOException failure;
+
+ InboundStream(Channel channel) {
+ this.channel = channel;
+ }
+
+ synchronized void offer(ByteBuf content) {
+ if (closed || !content.isReadable()) {
+ return;
+ }
+ byte[] chunk = ByteBufUtil.getBytes(content);
+ chunks.add(chunk);
+ waiting += chunk.length;
+ if (waiting >= HIGH_WATER_MARK && !suspended) {
+ suspended = true;
+ channel.config().setAutoRead(false);
+ }
+ notifyAll();
+ }
+
+ synchronized void end() {
+ ended = true;
+ notifyAll();
+ }
+
+ synchronized void fail(IOException cause) {
+ if (!ended) {
+ failure = cause;
+ ended = true;
+ resume();
+ notifyAll();
+ }
+ }
+
+ @Override
+ public int read() throws IOException {
+ byte[] b = new byte[1];
+ int n = read(b, 0, 1);
+ return n == -1 ? -1 : b[0] & 0xff;
+ }
+
+ @Override
+ public synchronized int read(byte[] b, int off, int len) throws
IOException {
+ Objects.checkFromIndexSize(off, len, b.length);
+ if (len == 0) {
+ return 0;
+ }
+ while (!closed && chunks.isEmpty() && !ended) {
+ if (channel.eventLoop().inEventLoop()) {
+ throw new IOException(
+ "Cannot wait for the body on the I/O thread of the
connection that receives it");
+ }
+ try {
+ wait();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new InterruptedIOException("Interrupted while
waiting for the body");
+ }
+ }
+ if (closed) {
+ throw new IOException("Stream closed");
+ }
+ if (chunks.isEmpty()) {
+ if (failure != null) {
+ throw new IOException(failure.getMessage(), failure);
+ }
+ return -1;
+ }
+
+ int n = 0;
+ while (n < len && !chunks.isEmpty()) {
+ byte[] chunk = chunks.peek();
+ int count = Math.min(len - n, chunk.length - position);
+ System.arraycopy(chunk, position, b, off + n, count);
+ n += count;
+ position += count;
+ if (position == chunk.length) {
+ chunks.poll();
+ position = 0;
+ }
+ }
+ waiting -= n;
+ if (waiting <= LOW_WATER_MARK) {
+ resume();
+ }
+ return n;
+ }
+
+ @Override
+ public synchronized int available() {
+ return waiting;
+ }
+
+ @Override
+ public synchronized void close() {
+ if (!closed) {
+ closed = true;
+ chunks.clear();
+ waiting = 0;
+ resume();
+ notifyAll();
+ }
+ }
+
+ private void resume() {
+ if (suspended) {
+ suspended = false;
+ channel.config().setAutoRead(true);
}
}
}
diff --git
a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpOutboundStreamHandler.java
b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpOutboundStreamHandler.java
index 186c5bd7041a..8ec8e0129eb0 100644
---
a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpOutboundStreamHandler.java
+++
b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpOutboundStreamHandler.java
@@ -16,6 +16,7 @@
*/
package org.apache.camel.component.netty.http.handlers;
+import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.DefaultChannelPromise;
@@ -38,6 +39,9 @@ public class HttpOutboundStreamHandler extends
ChunkedWriteHandler {
if (needNewPromise) {
promise = new DefaultChannelPromise(ctx.channel());
+ // the headers are sent before the body, so a body that fails to
be read or written leaves the message
+ // incomplete: close the connection, otherwise the peer waits for
the rest of the body
+ promise.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
}
super.write(ctx, msg, promise);
diff --git
a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpServerChannelHandler.java
b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpServerChannelHandler.java
index 44b77b33b659..f744215c4abb 100644
---
a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpServerChannelHandler.java
+++
b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpServerChannelHandler.java
@@ -16,6 +16,7 @@
*/
package org.apache.camel.component.netty.http.handlers;
+import java.io.InputStream;
import java.net.URI;
import java.nio.channels.ClosedChannelException;
import java.nio.charset.StandardCharsets;
@@ -54,13 +55,16 @@ import
org.apache.camel.component.netty.http.NettyHttpConstants;
import org.apache.camel.component.netty.http.NettyHttpConsumer;
import org.apache.camel.component.netty.http.NettyHttpHelper;
import org.apache.camel.component.netty.http.NettyHttpSecurityConfiguration;
+import org.apache.camel.component.netty.http.OutboundStreamHttpResponse;
import org.apache.camel.component.netty.http.SecurityAuthenticator;
import org.apache.camel.http.base.OAuthHttpSecuritySupport;
import org.apache.camel.http.base.OAuthHttpSecuritySupport.Validation;
import org.apache.camel.spi.CamelLogger;
import org.apache.camel.support.ExceptionHelper;
import org.apache.camel.support.ObjectHelper;
+import org.apache.camel.support.SynchronizationAdapter;
import org.apache.camel.support.TlsPeerCertificateSupport;
+import org.apache.camel.util.IOHelper;
import org.apache.camel.util.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -80,6 +84,10 @@ public class HttpServerChannelHandler extends
ServerChannelHandler {
private static final Logger LOG =
LoggerFactory.getLogger(HttpServerChannelHandler.class);
+ // internal exchange property: the reply that is streamed by the outbound
streamer, which reads it after the exchange
+ // is done
+ private static final String REPLY_STREAM = "CamelNettyHttpReplyStream";
+
// whether the basic auth credential of the request being read has been
checked by Camel, so that beforeProcess
// (called by channelRead0 of the super class on the same thread) removes
the Authorization header from the message
private static final AttributeKey<Boolean> BASIC_AUTH_CHECKED
@@ -495,8 +503,16 @@ public class HttpServerChannelHandler extends
ServerChannelHandler {
@Override
protected Object getResponseBody(Exchange exchange) throws Exception {
try {
- return
consumer.getEndpoint().getNettyHttpBinding().toNettyResponse(exchange.getMessage(),
+ HttpResponse response =
consumer.getEndpoint().getNettyHttpBinding().toNettyResponse(exchange.getMessage(),
consumer.getConfiguration());
+ if (response instanceof OutboundStreamHttpResponse reply) {
+ // the outbound streamer writes the body of the reply after
the exchange is done, and may read the body
+ // stream of the request (sent back, as it is or in another
stream), which is then closed with the reply
+ StreamedReply streamedReply = new StreamedReply(reply);
+ exchange.setProperty(REPLY_STREAM, streamedReply);
+ return streamedReply;
+ }
+ return response;
} catch (Exception e) {
// no response can be built from the message, so answer with a
500, otherwise the client gets no response
// and waits for one forever (if not timing out)
@@ -539,6 +555,22 @@ public class HttpServerChannelHandler extends
ServerChannelHandler {
} else {
InboundStreamHttpRequest request = (InboundStreamHttpRequest)
message;
in =
consumer.getEndpoint().getNettyHttpBinding().toCamelMessage(request, exchange,
consumer.getConfiguration());
+ // close the body stream when the exchange is done, so the part of
the body that the route did not read is
+ // discarded, and the connection is read again
+ InputStream body = request.getInputStream();
+ exchange.getExchangeExtension().addOnCompletion(new
SynchronizationAdapter() {
+ @Override
+ public void onDone(Exchange exchange) {
+ // unless the reply is streamed: the outbound streamer
writes it after the exchange is done, and it may
+ // read the body, so the body stream is closed with the
reply
+ StreamedReply reply = exchange.getProperty(REPLY_STREAM,
StreamedReply.class);
+ if (reply != null) {
+ reply.closeWith(body);
+ } else {
+ IOHelper.close(body);
+ }
+ }
+ });
}
exchange.setIn(in);
@@ -555,4 +587,46 @@ public class HttpServerChannelHandler extends
ServerChannelHandler {
return exchange;
}
+
+ /**
+ * A streamed reply that closes the body stream of the request with it.
The outbound streamer closes the reply once
+ * it is written, when the write fails, or when the connection is closed.
Everything else is the reply as built by
+ * the binding.
+ */
+ private static final class StreamedReply extends
OutboundStreamHttpResponse {
+ private boolean closed;
+ private InputStream requestStream;
+
+ StreamedReply(OutboundStreamHttpResponse reply) {
+ super(reply);
+ }
+
+ /**
+ * Closes the body stream of the request when the reply is closed, or
now if the reply is closed already.
+ */
+ void closeWith(InputStream stream) {
+ synchronized (this) {
+ if (!closed) {
+ requestStream = stream;
+ return;
+ }
+ }
+ IOHelper.close(stream);
+ }
+
+ @Override
+ public void close() throws Exception {
+ InputStream stream;
+ synchronized (this) {
+ closed = true;
+ stream = requestStream;
+ requestStream = null;
+ }
+ try {
+ super.close();
+ } finally {
+ IOHelper.close(stream);
+ }
+ }
+ }
}
diff --git
a/components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettyHttpChunkedRequestDisableStreamCacheTest.java
b/components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettyHttpChunkedRequestDisableStreamCacheTest.java
new file mode 100644
index 000000000000..8d8d549a389f
--- /dev/null
+++
b/components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettyHttpChunkedRequestDisableStreamCacheTest.java
@@ -0,0 +1,219 @@
+/*
+ * 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.netty.http;
+
+import java.io.BufferedInputStream;
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.StreamCache;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.component.netty.http.RawHttpClient.Response;
+import org.apache.camel.test.AvailablePortFinder;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import static org.apache.camel.component.netty.http.RawHttpClient.chunkedPost;
+import static org.apache.camel.component.netty.http.RawHttpClient.get;
+import static org.apache.camel.component.netty.http.RawHttpClient.send;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * With disableStreamCache=true, the server of a netty-http endpoint streams
the body of a chunked request to the route.
+ * The request is answered whether the route reads the body or not, and
whether a route matches or not, and the
+ * connection can be used for the next request. The server has one I/O thread,
so a request that is not answered would
+ * also hold the requests after it.
+ */
+@Timeout(value = 60, unit = TimeUnit.SECONDS)
+class NettyHttpChunkedRequestDisableStreamCacheTest extends
BaseNettyTestSupport {
+
+ // 200 chunks of 1000 bytes: more than the server keeps waiting to be read
+ private static final int CHUNKS = 200;
+
+ @RegisterExtension
+ AvailablePortFinder.Port port2 = AvailablePortFinder.find();
+
+ @Test
+ void testChunkedRequestRouteReadsBody() throws Exception {
+ MockEndpoint mock = getMockEndpoint("mock:read");
+ mock.expectedMessageCount(2);
+ mock.allMessages().header("streamed").isEqualTo(true);
+
+ try (RawHttpClient client = new RawHttpClient(getPort())) {
+ // two requests on the same connection
+ for (int i = 0; i < 2; i++) {
+ Response response = client.send(chunkedPost("/read", CHUNKS));
+ assertEquals("HTTP/1.1 200 OK", response.status());
+ assertEquals(String.valueOf(CHUNKS * 1000), response.body());
+ }
+ }
+
+ MockEndpoint.assertIsSatisfied(context);
+ }
+
+ @Test
+ void testChunkedRequestRouteDoesNotReadBody() throws Exception {
+ try (RawHttpClient client = new RawHttpClient(getPort())) {
+ Response response = client.send(chunkedPost("/noread", CHUNKS));
+ assertEquals("HTTP/1.1 200 OK", response.status());
+ assertEquals("ok", response.body());
+
+ // the rest of the body is discarded, and the next request on the
connection is answered
+ assertEquals("HTTP/1.1 200 OK",
client.send(get("/hello")).status());
+ }
+
+ assertEquals("HTTP/1.1 200 OK", send(getPort(),
get("/hello")).status());
+ }
+
+ @Test
+ void testChunkedRequestBodySentBack() throws Exception {
+ try (RawHttpClient client = new RawHttpClient(getPort())) {
+ // two requests on the same connection
+ for (int i = 0; i < 2; i++) {
+ Response response = client.send(chunkedPost("/echo", "Hello ",
"World"));
+ assertEquals("HTTP/1.1 200 OK", response.status());
+ assertEquals("Hello World", response.body());
+ }
+ }
+ }
+
+ @Test
+ void testChunkedRequestBodySentBackInAnotherStream() throws Exception {
+ try (RawHttpClient client = new RawHttpClient(getPort())) {
+ // two requests on the same connection
+ for (int i = 0; i < 2; i++) {
+ Response response = client.send(chunkedPost("/wrap", "Hello ",
"World"));
+ assertEquals("HTTP/1.1 200 OK", response.status());
+ assertEquals("Hello World", response.body());
+ }
+ }
+ }
+
+ @Test
+ void testChunkedRequestStreamedReplyWithoutReadingBody() throws Exception {
+ try (RawHttpClient client = new RawHttpClient(getPort())) {
+ Response response = client.send(chunkedPost("/stream", CHUNKS));
+ assertEquals("HTTP/1.1 200 OK", response.status());
+ assertEquals("streamed", response.body());
+
+ // the rest of the body is discarded once the reply is written,
and the next request on the connection is
+ // answered
+ assertEquals("HTTP/1.1 200 OK",
client.send(get("/hello")).status());
+ }
+ }
+
+ @Test
+ void testChunkedRequestBodySentBackBeforeReceived() throws Exception {
+ try (RawHttpClient client = new RawHttpClient(getPort())) {
+ // only the first chunk is sent: the reply cannot wait for the
rest of the body on the I/O thread that
+ // receives it, so the reply fails, and the connection is closed
instead of waiting for the rest
+ assertTrue(client.sendAndAwaitClose(
+ "POST /echo HTTP/1.1\r\nHost:
localhost\r\nTransfer-Encoding: chunked\r\n\r\n6\r\nHello \r\n"));
+ }
+
+ assertEquals("HTTP/1.1 200 OK", send(getPort(),
get("/hello")).status());
+ }
+
+ @Test
+ void testChunkedRequestRouteFailsWithoutReadingBody() throws Exception {
+ try (RawHttpClient client = new RawHttpClient(getPort())) {
+ assertEquals("HTTP/1.1 500 Internal Server Error",
client.send(chunkedPost("/fail", CHUNKS)).status());
+
+ // the rest of the body is discarded, and the next request on the
connection is answered
+ assertEquals("HTTP/1.1 200 OK",
client.send(get("/hello")).status());
+ }
+ }
+
+ @Test
+ void testChunkedRequestUnknownPath() throws Exception {
+ assertEquals("HTTP/1.1 404 Not Found", send(getPort(),
chunkedPost("/unknown", 4)).status());
+
+ assertEquals("HTTP/1.1 200 OK", send(getPort(),
get("/hello")).status());
+ }
+
+ @Test
+ void testChunkedRequestWithoutExecutorService() throws Exception {
+ Response response = send(port2.getPort(), chunkedPost("/read", 4));
+ assertEquals("HTTP/1.1 200 OK", response.status());
+ assertEquals("4000", response.body());
+
+ assertEquals("HTTP/1.1 200 OK", send(port2.getPort(),
get("/hello")).status());
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ String options = "?disableStreamCache=true&workerCount=1";
+
+ // the routes do not use stream caching, which would read the
body before the route
+ from("netty-http:http://localhost:" + getPort() + "/read" +
options)
+ .noStreamCaching()
+ .process(e -> e.getMessage().setHeader("streamed",
+ e.getMessage().getBody() instanceof InputStream
+ && !(e.getMessage().getBody()
instanceof StreamCache)))
+ .to("mock:read")
+ .convertBodyTo(String.class)
+ .setBody(simple("${body.length()}"));
+
+ from("netty-http:http://localhost:" + getPort() + "/noread" +
options)
+ .noStreamCaching()
+ .transform().constant("ok");
+
+ // the reply sends the body back as it was received
+ from("netty-http:http://localhost:" + getPort() + "/echo" +
options)
+ .noStreamCaching()
+ .log("Sending the body back");
+
+ // the reply sends the body back in another stream
+ from("netty-http:http://localhost:" + getPort() + "/wrap" +
options)
+ .noStreamCaching()
+ .process(e -> e.getMessage().setBody(
+ new
BufferedInputStream(e.getMessage().getBody(InputStream.class))));
+
+ // the reply is streamed, and the route does not read the body
+ from("netty-http:http://localhost:" + getPort() + "/stream" +
options)
+ .noStreamCaching()
+ .process(e -> e.getMessage().setBody(
+ new
ByteArrayInputStream("streamed".getBytes(StandardCharsets.UTF_8))));
+
+ from("netty-http:http://localhost:" + getPort() + "/fail" +
options)
+ .noStreamCaching()
+ .throwException(new IllegalStateException("Forced"));
+
+ from("netty-http:http://localhost:" + getPort() + "/hello" +
options)
+ .transform().constant("hello");
+
+ // the routes run on the I/O thread
+ String noExecutor = options + "&usingExecutorService=false";
+
+ from("netty-http:http://localhost:" + port2.getPort() +
"/read" + noExecutor)
+ .convertBodyTo(String.class)
+ .setBody(simple("${body.length()}"));
+
+ from("netty-http:http://localhost:" + port2.getPort() +
"/hello" + noExecutor)
+ .transform().constant("hello");
+ }
+ };
+ }
+}
diff --git
a/components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettySharedHttpServerChunkedRequestTest.java
b/components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettySharedHttpServerChunkedRequestTest.java
new file mode 100644
index 000000000000..a00bf6669f2b
--- /dev/null
+++
b/components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettySharedHttpServerChunkedRequestTest.java
@@ -0,0 +1,145 @@
+/*
+ * 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.netty.http;
+
+import java.io.ByteArrayInputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.BindToRegistry;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.component.netty.http.RawHttpClient.Response;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+
+import static org.apache.camel.component.netty.http.RawHttpClient.chunkedPost;
+import static org.apache.camel.component.netty.http.RawHttpClient.get;
+import static org.apache.camel.component.netty.http.RawHttpClient.post;
+import static org.apache.camel.component.netty.http.RawHttpClient.send;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * A request with a chunked body (Transfer-Encoding: chunked, as sent by HTTP
clients for a body of unknown length) to a
+ * shared Netty HTTP server is answered, whether the route reads the body or
not, and whether a route matches or not.
+ * The server has one I/O thread, so a request that is not answered would also
hold the requests after it.
+ */
+@Timeout(value = 60, unit = TimeUnit.SECONDS)
+class NettySharedHttpServerChunkedRequestTest extends BaseNettyTestSupport {
+
+ private NettySharedHttpServer nettySharedHttpServer;
+
+ @BindToRegistry("myNettyServer")
+ public NettySharedHttpServer createServer() {
+ nettySharedHttpServer = new DefaultNettySharedHttpServer();
+ nettySharedHttpServer.setCamelContext(context);
+
+ NettySharedHttpServerBootstrapConfiguration configuration = new
NettySharedHttpServerBootstrapConfiguration();
+ configuration.setPort(getPort());
+ configuration.setHost("localhost");
+ configuration.setWorkerCount(1);
+ configureServer(configuration);
+
nettySharedHttpServer.setNettyServerBootstrapConfiguration(configuration);
+
+ nettySharedHttpServer.start();
+
+ return nettySharedHttpServer;
+ }
+
+ protected void configureServer(NettySharedHttpServerBootstrapConfiguration
configuration) {
+ // the default configuration (chunked = true)
+ }
+
+ @Override
+ public void doPostTearDown() {
+ nettySharedHttpServer.stop();
+ }
+
+ @Test
+ void testChunkedRequestRouteReadsBody() throws Exception {
+ getMockEndpoint("mock:read").expectedBodiesReceived("Hello World");
+
+ Response response = send(getPort(), chunkedPost("/read", "Hello ",
"World"));
+ assertEquals("HTTP/1.1 200 OK", response.status());
+ assertEquals("Bye World", response.body());
+
+ assertEquals("HTTP/1.1 200 OK", send(getPort(),
get("/hello")).status());
+ MockEndpoint.assertIsSatisfied(context);
+ }
+
+ @Test
+ void testChunkedRequestRouteDoesNotReadBody() throws Exception {
+ Response response = send(getPort(), chunkedPost("/noread", 4));
+ assertEquals("HTTP/1.1 200 OK", response.status());
+ assertEquals("ok", response.body());
+
+ assertEquals("HTTP/1.1 200 OK", send(getPort(),
get("/hello")).status());
+ }
+
+ @Test
+ void testChunkedRequestUnknownPath() throws Exception {
+ assertEquals("HTTP/1.1 404 Not Found", send(getPort(),
chunkedPost("/unknown", 4)).status());
+
+ assertEquals("HTTP/1.1 200 OK", send(getPort(),
get("/hello")).status());
+ }
+
+ @Test
+ void testRequestWithContentLength() throws Exception {
+ getMockEndpoint("mock:read").expectedBodiesReceived("Hello World");
+
+ Response response = send(getPort(), post("/read", "Hello World"));
+ assertEquals("HTTP/1.1 200 OK", response.status());
+ assertEquals("Bye World", response.body());
+
+ Response hello = send(getPort(), get("/hello"));
+ assertEquals("HTTP/1.1 200 OK", hello.status());
+ assertEquals("hello", hello.body());
+ MockEndpoint.assertIsSatisfied(context);
+ }
+
+ @Test
+ void testStreamedResponse() throws Exception {
+ Response response = send(getPort(), get("/stream"));
+ assertEquals("HTTP/1.1 200 OK", response.status());
+ assertEquals("chunked", response.headers().get("transfer-encoding"));
+ assertEquals("x".repeat(20000), response.body());
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+
from("netty-http:http://localhost/read?nettySharedHttpServer=#myNettyServer")
+ .convertBodyTo(String.class)
+ .to("mock:read")
+ .transform().constant("Bye World");
+
+
from("netty-http:http://localhost/noread?nettySharedHttpServer=#myNettyServer")
+ .noStreamCaching()
+ .transform().constant("ok");
+
+
from("netty-http:http://localhost/hello?nettySharedHttpServer=#myNettyServer")
+ .transform().constant("hello");
+
+
from("netty-http:http://localhost/stream?nettySharedHttpServer=#myNettyServer&disableStreamCache=true")
+ .process(e -> e.getMessage().setBody(
+ new
ByteArrayInputStream("x".repeat(20000).getBytes(StandardCharsets.US_ASCII))));
+ }
+ };
+ }
+}
diff --git
a/components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettySharedHttpServerNotChunkedTest.java
b/components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettySharedHttpServerNotChunkedTest.java
new file mode 100644
index 000000000000..a8d20cfa1853
--- /dev/null
+++
b/components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettySharedHttpServerNotChunkedTest.java
@@ -0,0 +1,28 @@
+/*
+ * 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.netty.http;
+
+/**
+ * A shared Netty HTTP server with chunked = false answers requests, as with
the default configuration.
+ */
+class NettySharedHttpServerNotChunkedTest extends
NettySharedHttpServerChunkedRequestTest {
+
+ @Override
+ protected void configureServer(NettySharedHttpServerBootstrapConfiguration
configuration) {
+ configuration.setChunked(false);
+ }
+}
diff --git
a/components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/RawHttpClient.java
b/components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/RawHttpClient.java
new file mode 100644
index 000000000000..667bce27045e
--- /dev/null
+++
b/components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/RawHttpClient.java
@@ -0,0 +1,159 @@
+/*
+ * 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.netty.http;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.Socket;
+import java.net.SocketException;
+import java.net.SocketTimeoutException;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+
+/**
+ * Sends HTTP requests on a socket as written, so a test controls the chunks
of a request and the connection it uses,
+ * and reads the responses with a timeout.
+ */
+final class RawHttpClient implements AutoCloseable {
+
+ static final int TIMEOUT = 5000;
+
+ private final Socket socket;
+ private final InputStream in;
+
+ RawHttpClient(int port) throws IOException {
+ socket = new Socket("localhost", port);
+ socket.setSoTimeout(TIMEOUT);
+ in = socket.getInputStream();
+ }
+
+ /**
+ * Sends the request and reads the response. The status is NO-RESPONSE
when no response is received within the
+ * timeout, and CLOSED when the connection is closed without a response.
+ */
+ Response send(String request) throws IOException {
+ OutputStream out = socket.getOutputStream();
+ out.write(request.getBytes(StandardCharsets.US_ASCII));
+ out.flush();
+ try {
+ return readResponse();
+ } catch (SocketTimeoutException e) {
+ return new Response("NO-RESPONSE", Map.of(), "");
+ }
+ }
+
+ /**
+ * Sends the request and reads until the connection is closed. Returns
false when the connection is not closed
+ * within the timeout.
+ */
+ boolean sendAndAwaitClose(String request) throws IOException {
+ OutputStream out = socket.getOutputStream();
+ out.write(request.getBytes(StandardCharsets.US_ASCII));
+ out.flush();
+ try {
+ in.readAllBytes();
+ return true;
+ } catch (SocketTimeoutException e) {
+ return false;
+ } catch (SocketException e) {
+ // the connection was reset
+ return true;
+ }
+ }
+
+ static Response send(int port, String request) throws IOException {
+ try (RawHttpClient client = new RawHttpClient(port)) {
+ return client.send(request);
+ }
+ }
+
+ static String get(String path) {
+ return "GET " + path + " HTTP/1.1\r\nHost: localhost\r\n\r\n";
+ }
+
+ static String post(String path, String body) {
+ return "POST " + path + " HTTP/1.1\r\nHost:
localhost\r\nContent-Length: " + body.length() + "\r\n\r\n" + body;
+ }
+
+ static String chunkedPost(String path, String... chunks) {
+ StringBuilder sb
+ = new StringBuilder("POST " + path + " HTTP/1.1\r\nHost:
localhost\r\nTransfer-Encoding: chunked\r\n\r\n");
+ for (String chunk : chunks) {
+
sb.append(Integer.toHexString(chunk.length())).append("\r\n").append(chunk).append("\r\n");
+ }
+ return sb.append("0\r\n\r\n").toString();
+ }
+
+ /**
+ * A chunked request with a body of the given number of chunks of 1000
bytes each.
+ */
+ static String chunkedPost(String path, int chunks) {
+ String[] body = new String[chunks];
+ for (int i = 0; i < chunks; i++) {
+ body[i] = String.valueOf((char) ('a' + i % 26)).repeat(1000);
+ }
+ return chunkedPost(path, body);
+ }
+
+ private Response readResponse() throws IOException {
+ String status = readLine();
+ if (status == null) {
+ return new Response("CLOSED", Map.of(), "");
+ }
+ Map<String, String> headers = new HashMap<>();
+ for (String line = readLine(); line != null && !line.isEmpty(); line =
readLine()) {
+ int idx = line.indexOf(':');
+ headers.put(line.substring(0,
idx).trim().toLowerCase(Locale.ENGLISH), line.substring(idx + 1).trim());
+ }
+ ByteArrayOutputStream body = new ByteArrayOutputStream();
+ if ("chunked".equalsIgnoreCase(headers.get("transfer-encoding"))) {
+ for (int size = Integer.parseInt(readLine().trim(), 16); size > 0;
size = Integer.parseInt(readLine().trim(), 16)) {
+ body.write(in.readNBytes(size));
+ readLine();
+ }
+ readLine();
+ } else if (headers.containsKey("content-length")) {
+
body.write(in.readNBytes(Integer.parseInt(headers.get("content-length"))));
+ }
+ return new Response(status, headers,
body.toString(StandardCharsets.UTF_8));
+ }
+
+ private String readLine() throws IOException {
+ StringBuilder sb = new StringBuilder();
+ int c;
+ while ((c = in.read()) != -1) {
+ if (c == '\n') {
+ int len = sb.length();
+ return len > 0 && sb.charAt(len - 1) == '\r' ? sb.substring(0,
len - 1) : sb.toString();
+ }
+ sb.append((char) c);
+ }
+ return sb.isEmpty() ? null : sb.toString();
+ }
+
+ @Override
+ public void close() throws IOException {
+ socket.close();
+ }
+
+ record Response(String status, Map<String, String> headers, String body) {
+ }
+}
diff --git
a/components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/handlers/HttpInboundStreamHandlerTest.java
b/components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/handlers/HttpInboundStreamHandlerTest.java
new file mode 100644
index 000000000000..ffa7a86547a1
--- /dev/null
+++
b/components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/handlers/HttpInboundStreamHandlerTest.java
@@ -0,0 +1,134 @@
+/*
+ * 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.netty.http.handlers;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.TimeUnit;
+
+import io.netty.buffer.Unpooled;
+import io.netty.channel.embedded.EmbeddedChannel;
+import io.netty.handler.codec.http.DefaultHttpContent;
+import io.netty.handler.codec.http.DefaultHttpRequest;
+import io.netty.handler.codec.http.DefaultLastHttpContent;
+import io.netty.handler.codec.http.HttpHeaderNames;
+import io.netty.handler.codec.http.HttpHeaderValues;
+import io.netty.handler.codec.http.HttpMethod;
+import io.netty.handler.codec.http.HttpRequest;
+import io.netty.handler.codec.http.HttpVersion;
+import org.apache.camel.component.netty.http.InboundStreamHttpRequest;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The stream of the body of a chunked request never makes the I/O thread
wait: it stops reading from the connection
+ * while too much of the body waits to be read, discards the rest of the body
once closed, and fails rather than waits
+ * when it is read on the I/O thread (an embedded channel runs everything on
the I/O thread).
+ */
+@Timeout(value = 30, unit = TimeUnit.SECONDS)
+class HttpInboundStreamHandlerTest {
+
+ private final EmbeddedChannel channel = new EmbeddedChannel(new
HttpInboundStreamHandler());
+
+ @AfterEach
+ void close() {
+ channel.finishAndReleaseAll();
+ }
+
+ @Test
+ void testBodyIsStreamed() throws Exception {
+ InputStream body = sendRequest();
+ channel.writeInbound(content("Hello "));
+ channel.writeInbound(new
DefaultLastHttpContent(Unpooled.copiedBuffer("World",
StandardCharsets.US_ASCII)));
+
+ assertEquals("Hello World", new String(body.readAllBytes(),
StandardCharsets.US_ASCII));
+ }
+
+ @Test
+ void testStopsReadingWhileTheBodyWaitsToBeRead() throws Exception {
+ InputStream body = sendRequest();
+ byte[] chunk = new byte[1000];
+ int chunks = HttpInboundStreamHandler.HIGH_WATER_MARK / chunk.length +
1;
+ for (int i = 0; i < chunks; i++) {
+ channel.writeInbound(new
DefaultHttpContent(Unpooled.wrappedBuffer(chunk)));
+ }
+ assertFalse(channel.config().isAutoRead(), "the connection is not read
while the body waits to be read");
+
+ byte[] read = body.readNBytes(chunks * chunk.length -
HttpInboundStreamHandler.LOW_WATER_MARK);
+ assertArrayEquals(new byte[read.length], read);
+ assertTrue(channel.config().isAutoRead(), "the connection is read
again once the body is read");
+ }
+
+ @Test
+ void testCloseDiscardsTheRestOfTheBody() throws Exception {
+ InputStream body = sendRequest();
+ byte[] chunk = new byte[1000];
+ for (int i = 0; i <= HttpInboundStreamHandler.HIGH_WATER_MARK /
chunk.length; i++) {
+ channel.writeInbound(new
DefaultHttpContent(Unpooled.wrappedBuffer(chunk)));
+ }
+ assertFalse(channel.config().isAutoRead());
+
+ body.close();
+ assertTrue(channel.config().isAutoRead(), "the connection is read
again once the body is closed");
+ channel.writeInbound(new
DefaultLastHttpContent(Unpooled.wrappedBuffer(chunk)));
+ assertThrows(IOException.class, body::read);
+
+ // the next request on the connection has a body of its own
+ InputStream next = sendRequest();
+ channel.writeInbound(new
DefaultLastHttpContent(Unpooled.copiedBuffer("next",
StandardCharsets.US_ASCII)));
+ assertEquals("next", new String(next.readAllBytes(),
StandardCharsets.US_ASCII));
+ }
+
+ @Test
+ void testReadOnTheIoThreadFailsInsteadOfWaiting() throws Exception {
+ InputStream body = sendRequest();
+ channel.writeInbound(content("Hello"));
+
+ assertEquals("Hello", new String(body.readNBytes(5),
StandardCharsets.US_ASCII));
+ assertThrows(IOException.class, body::read);
+ }
+
+ @Test
+ void testConnectionClosedBeforeTheEndOfTheBody() throws Exception {
+ InputStream body = sendRequest();
+ channel.writeInbound(content("Hello"));
+ channel.close();
+
+ assertEquals("Hello", new String(body.readNBytes(5),
StandardCharsets.US_ASCII));
+ assertThrows(IOException.class, body::read);
+ }
+
+ private InputStream sendRequest() {
+ HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1,
HttpMethod.POST, "/foo");
+ request.headers().set(HttpHeaderNames.TRANSFER_ENCODING,
HttpHeaderValues.CHUNKED);
+ channel.writeInbound(request);
+ InboundStreamHttpRequest received = channel.readInbound();
+ return received.getInputStream();
+ }
+
+ private static DefaultHttpContent content(String text) {
+ return new DefaultHttpContent(Unpooled.copiedBuffer(text,
StandardCharsets.US_ASCII));
+ }
+}
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 ab02cb5282cb..6322076c50ab 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
@@ -6856,6 +6856,44 @@ It was added for OSGi/Karaf, so that several
applications (bundles) in one JVM c
Spring Boot and Quarkus applications run one application per JVM: use a
`netty-http` consumer per port, where several
routes can use the same port, or the `platform-http` component.
+=== camel-netty-http - chunked requests on the shared HTTP server and with
disableStreamCache
+
+A request with a chunked body (`Transfer-Encoding: chunked`) to a consumer on
a shared HTTP server
+(`nettySharedHttpServer`) is now aggregated before the route is called, as on
the server of an endpoint: the body is
+the stream cache, or the Netty `ByteBuf` with `disableStreamCache=true`,
instead of an `InputStream`. Before, such a
+request got no response, and the I/O thread that received it no longer served
its other connections. The `chunked`
+option of `NettySharedHttpServerBootstrapConfiguration` is no longer used;
before, `chunked=false` made every request
+fail. The aggregated body is limited by its `chunkedMaxContentLength` (1 MB by
default); a larger request gets the
+response `413 Request Entity Too Large`.
+
+With `disableStreamCache=true` on a consumer, the body of a chunked request is
still an `InputStream`, with these
+changes:
+
+* When the route runs on the I/O thread (`usingExecutorService=false`), the
request is aggregated, and the body is the
+ Netty `ByteBuf`, as for a request with a `Content-Length`. Before, the route
waited for ever when it read the body.
+ The aggregated body is limited by the `chunkedMaxContentLength` option (1 MB
by default); a larger request gets
+ the response `413 Request Entity Too Large`.
+* The stream is closed when the exchange is done, and the part of the body
that the route did not read is discarded.
+ Before, a body of more than 1 KB that the route did not read held the I/O
thread, so the next requests on it got no
+ response. A route that hands the stream to another thread must read it
before the exchange is done.
+ When the reply is streamed (its body is an `InputStream`), the stream is
closed once the reply is written instead,
+ as the reply may read it (a route that sends the request body back, as it is
or in another stream). Such a reply
+ reads the stream on the I/O thread of the connection, so it can only
+ send back a body that is received already: when a part of the body, as of a
large body, is still to be received,
+ the stream fails with an `IOException`, and the connection is closed without
a complete reply. Before, the I/O
+ thread waited for ever.
+ As the rest of the body is read only once such a reply is written, when a
route does not read a large body and
+ replies with a stream of its own that is larger than what the connection
buffers, the reply and a client that sends
+ the whole body before it reads the response wait for each other for ever. In
that case close the body stream in the
+ route (for example `exchange.getIn().getBody(InputStream.class).close()`),
or reply with a body that is not a
+ stream. Before, such a request got no response once the body was larger than
1 KB.
+* The stream fails with an `IOException` when the connection is closed before
the whole body is received. Before, it
+ ended as if the body was complete.
+
+The same stream is used for a chunked response on a producer with
`disableStreamCache=true`: it fails with an
+`IOException` when it is read on the I/O thread of the connection with no data
received yet, instead of waiting for
+ever, so read it after the producer with `synchronous=true`, or on another
thread.
+
=== camel-alibaba-eventbridge - endpoint is marked as required instead of
region
The `endpoint` option of `alibaba-eventbridge` is now marked as required, and
the `region` option no longer is. The