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 eaff5dc78598 CAMEL-27569: camel-undertow - a WebSocket message not
sent within sendTimeout fails the exchange, also for text messages (#30868)
eaff5dc78598 is described below
commit eaff5dc785982a6a284f44ff65ba0740aa1adaca
Author: Claus Ibsen <[email protected]>
AuthorDate: Thu Nov 26 17:15:47 2026 +0100
CAMEL-27569: camel-undertow - a WebSocket message not sent within
sendTimeout fails the exchange, also for text messages (#30868)
The sendTimeout of a WebSocket producer applied only to byte[] and
InputStream
bodies, so a String or Reader message to a peer that stopped reading stayed
in flight, with its exchange, forever.
Undertow's own timeout closes the frame of a message that is not written in
time and then reports it as complete, so a timed-out binary message was
dropped while the exchange succeeded. Camel now runs the send timeout itself
for every message type: a message not sent within sendTimeout fails the
exchange with a TimeoutException, and the connection to the stalled peer is
closed, which releases the messages that wait for it.
With sendToAll or several connection keys, the same body object was handed
to
every peer, so the first peer consumed a Reader or InputStream body and the
other peers got an empty message. Without stream caching, a Reader was also
closed by the first peer and the exchange failed with "Stream closed".
Now the body is read once and its content is sent to every peer.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Claus Ibsen <[email protected]>
---
.../apache/camel/catalog/components/undertow.json | 2 +-
.../apache/camel/component/undertow/undertow.json | 2 +-
.../camel/component/undertow/UndertowEndpoint.java | 4 +-
.../undertow/handlers/CamelWebSocketHandler.java | 129 +++++++++++---
.../ws/UndertowWsProducerSendTimeoutTest.java | 188 +++++++++++++++++++++
.../ws/UndertowWsProducerSendToAllStreamTest.java | 97 +++++++++++
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 11 ++
.../dsl/UndertowEndpointBuilderFactory.java | 8 +-
8 files changed, 413 insertions(+), 28 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/undertow.json
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/undertow.json
index 39a54bdff92d..857a3a969595 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/undertow.json
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/undertow.json
@@ -90,7 +90,7 @@
"securityProvider": { "index": 26, "kind": "parameter", "displayName":
"Security Provider", "group": "security", "label": "security", "required":
false, "type": "object", "javaType":
"org.apache.camel.component.undertow.spi.UndertowSecurityProvider",
"deprecated": false, "autowired": false, "secret": false, "description":
"Security provider allows plug in the provider, which will be used to secure
requests. SPI approach could be used too (endpoint then finds security provider
using S [...]
"sslContextParameters": { "index": 27, "kind": "parameter", "displayName":
"Ssl Context Parameters", "group": "security", "label": "security", "required":
false, "type": "object", "javaType":
"org.apache.camel.support.jsse.SSLContextParameters", "deprecated": false,
"autowired": false, "secret": false, "description": "To configure security
using SSLContextParameters" },
"fireWebSocketChannelEvents": { "index": 28, "kind": "parameter",
"displayName": "Fire Web Socket Channel Events", "group": "websocket", "label":
"consumer,websocket", "required": false, "type": "boolean", "javaType":
"boolean", "deprecated": false, "autowired": false, "secret": false,
"defaultValue": false, "description": "if true, the consumer will post
notifications to the route when a new WebSocket peer connects, disconnects,
etc. See UndertowConstants.EVENT_TYPE and EventType." },
- "sendTimeout": { "index": 29, "kind": "parameter", "displayName": "Send
Timeout", "group": "websocket", "label": "producer,websocket", "required":
false, "type": "integer", "javaType": "java.lang.Integer", "deprecated": false,
"autowired": false, "secret": false, "defaultValue": 30000, "description":
"Timeout in milliseconds when sending to a websocket channel. The default
timeout is 30000 (30 seconds)." },
+ "sendTimeout": { "index": 29, "kind": "parameter", "displayName": "Send
Timeout", "group": "websocket", "label": "producer,websocket", "required":
false, "type": "integer", "javaType": "java.lang.Integer", "deprecated": false,
"autowired": false, "secret": false, "defaultValue": 30000, "description":
"Timeout in milliseconds when sending to a websocket channel. The default
timeout is 30000 (30 seconds). A message that is not sent to a peer within the
timeout fails the exchange, and t [...]
"sendToAll": { "index": 30, "kind": "parameter", "displayName": "Send To
All", "group": "websocket", "label": "producer,websocket", "required": false,
"type": "boolean", "javaType": "java.lang.Boolean", "deprecated": false,
"autowired": false, "secret": false, "defaultValue": false, "description": "To
send to all websocket subscribers. Can be used to configure on endpoint level,
instead of having to use the UndertowConstants.SEND_TO_ALL header on the
message." }
}
}
diff --git
a/components/camel-undertow/src/generated/resources/META-INF/org/apache/camel/component/undertow/undertow.json
b/components/camel-undertow/src/generated/resources/META-INF/org/apache/camel/component/undertow/undertow.json
index 39a54bdff92d..857a3a969595 100644
---
a/components/camel-undertow/src/generated/resources/META-INF/org/apache/camel/component/undertow/undertow.json
+++
b/components/camel-undertow/src/generated/resources/META-INF/org/apache/camel/component/undertow/undertow.json
@@ -90,7 +90,7 @@
"securityProvider": { "index": 26, "kind": "parameter", "displayName":
"Security Provider", "group": "security", "label": "security", "required":
false, "type": "object", "javaType":
"org.apache.camel.component.undertow.spi.UndertowSecurityProvider",
"deprecated": false, "autowired": false, "secret": false, "description":
"Security provider allows plug in the provider, which will be used to secure
requests. SPI approach could be used too (endpoint then finds security provider
using S [...]
"sslContextParameters": { "index": 27, "kind": "parameter", "displayName":
"Ssl Context Parameters", "group": "security", "label": "security", "required":
false, "type": "object", "javaType":
"org.apache.camel.support.jsse.SSLContextParameters", "deprecated": false,
"autowired": false, "secret": false, "description": "To configure security
using SSLContextParameters" },
"fireWebSocketChannelEvents": { "index": 28, "kind": "parameter",
"displayName": "Fire Web Socket Channel Events", "group": "websocket", "label":
"consumer,websocket", "required": false, "type": "boolean", "javaType":
"boolean", "deprecated": false, "autowired": false, "secret": false,
"defaultValue": false, "description": "if true, the consumer will post
notifications to the route when a new WebSocket peer connects, disconnects,
etc. See UndertowConstants.EVENT_TYPE and EventType." },
- "sendTimeout": { "index": 29, "kind": "parameter", "displayName": "Send
Timeout", "group": "websocket", "label": "producer,websocket", "required":
false, "type": "integer", "javaType": "java.lang.Integer", "deprecated": false,
"autowired": false, "secret": false, "defaultValue": 30000, "description":
"Timeout in milliseconds when sending to a websocket channel. The default
timeout is 30000 (30 seconds)." },
+ "sendTimeout": { "index": 29, "kind": "parameter", "displayName": "Send
Timeout", "group": "websocket", "label": "producer,websocket", "required":
false, "type": "integer", "javaType": "java.lang.Integer", "deprecated": false,
"autowired": false, "secret": false, "defaultValue": 30000, "description":
"Timeout in milliseconds when sending to a websocket channel. The default
timeout is 30000 (30 seconds). A message that is not sent to a peer within the
timeout fails the exchange, and t [...]
"sendToAll": { "index": 30, "kind": "parameter", "displayName": "Send To
All", "group": "websocket", "label": "producer,websocket", "required": false,
"type": "boolean", "javaType": "java.lang.Boolean", "deprecated": false,
"autowired": false, "secret": false, "defaultValue": false, "description": "To
send to all websocket subscribers. Can be used to configure on endpoint level,
instead of having to use the UndertowConstants.SEND_TO_ALL header on the
message." }
}
}
diff --git
a/components/camel-undertow/src/main/java/org/apache/camel/component/undertow/UndertowEndpoint.java
b/components/camel-undertow/src/main/java/org/apache/camel/component/undertow/UndertowEndpoint.java
index ef9258de93b3..7c67a106ccad 100644
---
a/components/camel-undertow/src/main/java/org/apache/camel/component/undertow/UndertowEndpoint.java
+++
b/components/camel-undertow/src/main/java/org/apache/camel/component/undertow/UndertowEndpoint.java
@@ -456,7 +456,9 @@ public class UndertowEndpoint extends DefaultEndpoint
}
/**
- * Timeout in milliseconds when sending to a websocket channel. The
default timeout is 30000 (30 seconds).
+ * Timeout in milliseconds when sending to a websocket channel. The
default timeout is 30000 (30 seconds). A message
+ * that is not sent to a peer within the timeout fails the exchange, and
the connection to that peer is closed. Use
+ * 0 for no timeout.
*/
public void setSendTimeout(Integer sendTimeout) {
this.sendTimeout = sendTimeout;
diff --git
a/components/camel-undertow/src/main/java/org/apache/camel/component/undertow/handlers/CamelWebSocketHandler.java
b/components/camel-undertow/src/main/java/org/apache/camel/component/undertow/handlers/CamelWebSocketHandler.java
index 18a161e808a7..0856e6813baa 100644
---
a/components/camel-undertow/src/main/java/org/apache/camel/component/undertow/handlers/CamelWebSocketHandler.java
+++
b/components/camel-undertow/src/main/java/org/apache/camel/component/undertow/handlers/CamelWebSocketHandler.java
@@ -35,6 +35,9 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Predicate;
@@ -49,12 +52,14 @@ import io.undertow.util.HeaderValues;
import io.undertow.util.Headers;
import io.undertow.util.MimeMappings;
import io.undertow.util.StatusCodes;
+import io.undertow.util.WorkerUtils;
import io.undertow.websockets.WebSocketConnectionCallback;
import io.undertow.websockets.WebSocketProtocolHandshakeHandler;
import io.undertow.websockets.core.AbstractReceiveListener;
import io.undertow.websockets.core.BufferedBinaryMessage;
import io.undertow.websockets.core.BufferedTextMessage;
import io.undertow.websockets.core.CloseMessage;
+import io.undertow.websockets.core.WebSocketCallback;
import io.undertow.websockets.core.WebSocketChannel;
import io.undertow.websockets.core.WebSockets;
import io.undertow.websockets.spi.WebSocketHttpExchange;
@@ -75,7 +80,9 @@ import org.apache.camel.spi.OAuthTokenValidationResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xnio.ChannelListener;
+import org.xnio.IoUtils;
import org.xnio.Pooled;
+import org.xnio.XnioExecutor;
/**
* An {@link HttpHandler} that delegates to {@link
WebSocketProtocolHandshakeHandler} and provides some wiring to
@@ -136,39 +143,52 @@ public class CamelWebSocketHandler implements HttpHandler
{
* Send the given {@code message} to the given {@code channel} and report
the outcome to the given {@code callback}
* within the given {@code timeoutMillis}.
*
- * @param channel the channel to send the {@code message} to
- * @param message the message to send
- * @param callback where to report the outcome
- * @param timeoutMillis the timeout in milliseconds
- * @throws IOException
+ * @param channel the channel to send the {@code message} to
+ * @param message the message to send, a {@code String} or a {@code
byte[]}
+ * @param callback where to report the outcome
+ * @param timeoutMillis the timeout in milliseconds, none if zero or
negative
*/
private static void send(
WebSocketChannel channel, Object message,
ExtendedWebSocketCallback callback,
- long timeoutMillis)
- throws IOException {
+ long timeoutMillis) {
if (channel.isOpen()) {
+ WebSocketCallback<Void> sendCallback = callback;
+ if (timeoutMillis > 0) {
+ SendTimeoutCallback timeoutCallback = new
SendTimeoutCallback(channel, callback, timeoutMillis);
+ timeoutCallback.start();
+ sendCallback = timeoutCallback;
+ }
if (message instanceof String) {
- WebSockets.sendText((String) message, channel, callback);
- } else if (message instanceof byte[]) {
- ByteBuffer buffer = ByteBuffer.wrap((byte[]) message);
- WebSockets.sendBinary(buffer, channel, callback,
timeoutMillis);
- } else if (message instanceof Reader) {
- Reader r = (Reader) message;
- WebSockets.sendText(IOConverter.toString(r), channel,
callback);
- } else if (message instanceof InputStream) {
- InputStream in = (InputStream) message;
- ByteBuffer buffer = ByteBuffer.wrap(IOConverter.toBytes(in));
- WebSockets.sendBinary(buffer, channel, callback,
timeoutMillis);
+ WebSockets.sendText((String) message, channel, sendCallback);
} else {
- throw new RuntimeCamelException(
- "Unexpected type of message " +
message.getClass().getName() + "; expected String, byte[], "
- + Reader.class.getName() + "
or " + InputStream.class.getName());
+ // a buffer of its own per peer, as sending moves its position
+ WebSockets.sendBinary(ByteBuffer.wrap((byte[]) message),
channel, sendCallback);
}
} else {
callback.closedBeforeSent(channel);
}
}
+ /**
+ * Reads a {@code Reader} or {@code InputStream} message, so that every
peer is sent the same text or bytes rather
+ * than what the previous peer left of the stream.
+ *
+ * @return the message as a {@code String} or a {@code byte[]}
+ */
+ private static Object readOnce(Object message) throws IOException {
+ if (message instanceof String || message instanceof byte[]) {
+ return message;
+ } else if (message instanceof Reader) {
+ return IOConverter.toString((Reader) message);
+ } else if (message instanceof InputStream) {
+ return IOConverter.toBytes((InputStream) message);
+ } else {
+ throw new RuntimeCamelException(
+ "Unexpected type of message " +
message.getClass().getName() + "; expected String, byte[], "
+ + Reader.class.getName() + " or "
+ InputStream.class.getName());
+ }
+ }
+
/**
* {@inheritDoc}
*/
@@ -384,9 +404,10 @@ public class CamelWebSocketHandler implements HttpHandler {
return true;
} else {
/* There are some peers to send the message to */
+ Object payload = readOnce(message);
MultiCallback wsCallback = new MultiCallback(targetPeers,
camelCallback, camelExchange);
for (WebSocketChannel peer : targetPeers) {
- send(peer, message, wsCallback, timeout);
+ send(peer, payload, wsCallback, timeout);
}
return false;
}
@@ -504,6 +525,68 @@ public class CamelWebSocketHandler implements HttpHandler {
}
}
+ /**
+ * Applies the send timeout to the message sent to one peer. Undertow's
own timeout closes the frame of a message
+ * that is not written in time and then reports that frame as complete, so
a message dropped that way would look as
+ * sent. Instead, a message that is not written within the timeout fails,
and the connection to the peer, which
+ * stopped reading, is closed, which also releases the messages that wait
for it. Only the first outcome is
+ * reported: the timeout, or the completion or failure of the write.
+ */
+ static final class SendTimeoutCallback implements WebSocketCallback<Void>,
Runnable {
+ private final WebSocketChannel channel;
+ private final ExtendedWebSocketCallback delegate;
+ private final long timeoutMillis;
+ private final AtomicBoolean done = new AtomicBoolean();
+ private volatile XnioExecutor.Key timer;
+
+ SendTimeoutCallback(WebSocketChannel channel,
ExtendedWebSocketCallback delegate, long timeoutMillis) {
+ this.channel = channel;
+ this.delegate = delegate;
+ this.timeoutMillis = timeoutMillis;
+ }
+
+ /**
+ * Starts the timer, before the message is sent, as the write can
complete while it is sent.
+ */
+ void start() {
+ timer = WorkerUtils.executeAfter(channel.getIoThread(), this,
timeoutMillis, TimeUnit.MILLISECONDS);
+ }
+
+ @Override
+ public void run() {
+ if (done.compareAndSet(false, true)) {
+ LOG.debug("Closing WebSocket channel {} as a message was not
sent within the send timeout of {} millis",
+ channel, timeoutMillis);
+ delegate.onError(channel, null,
+ new TimeoutException("Not sent within the send timeout
of " + timeoutMillis + " millis"));
+ IoUtils.safeClose(channel);
+ }
+ }
+
+ @Override
+ public void complete(WebSocketChannel channel, Void context) {
+ if (done.compareAndSet(false, true)) {
+ cancelTimer();
+ delegate.complete(channel, context);
+ }
+ }
+
+ @Override
+ public void onError(WebSocketChannel channel, Void context, Throwable
throwable) {
+ if (done.compareAndSet(false, true)) {
+ cancelTimer();
+ delegate.onError(channel, context, throwable);
+ }
+ }
+
+ private void cancelTimer() {
+ XnioExecutor.Key key = timer;
+ if (key != null) {
+ key.remove();
+ }
+ }
+ }
+
/**
* A {@link ExtendedWebSocketCallback} able to track sending one message
to multiple peers.
*/
@@ -567,7 +650,7 @@ public class CamelWebSocketHandler implements HttpHandler {
final StringBuilder msg = new StringBuilder(
"Delivery to the following WebSocket peer channels
has failed: ");
for (Entry<String, Throwable> en : errors.entrySet()) {
- msg.append("\n
").append(en.getKey()).append(en.getValue().getMessage());
+ msg.append("\n ").append(en.getKey()).append(":
").append(en.getValue().getMessage());
}
camelExchange.setException(new
CamelExchangeException(msg.toString(), camelExchange));
}
diff --git
a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/ws/UndertowWsProducerSendTimeoutTest.java
b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/ws/UndertowWsProducerSendTimeoutTest.java
new file mode 100644
index 000000000000..72933d2c691f
--- /dev/null
+++
b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/ws/UndertowWsProducerSendTimeoutTest.java
@@ -0,0 +1,188 @@
+/*
+ * 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.undertow.ws;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.StringReader;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.net.SocketException;
+import java.net.SocketTimeoutException;
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.stream.Stream;
+
+import org.apache.camel.CamelExchangeException;
+import org.apache.camel.Exchange;
+import org.apache.camel.Produce;
+import org.apache.camel.ProducerTemplate;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.undertow.BaseUndertowTest;
+import org.apache.camel.component.undertow.UndertowConstants;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The {@code sendTimeout} of a WebSocket producer applies to every type of
message: a message to a peer that stops
+ * reading fails the exchange, and the connection to that peer is closed,
instead of keeping the exchange and the
+ * message in flight forever.
+ */
+public class UndertowWsProducerSendTimeoutTest extends BaseUndertowTest {
+
+ /**
+ * Much more than the socket buffers of the server and of the stalled peer
can hold, so the write cannot complete.
+ */
+ private static final int MESSAGE_SIZE = 64 * 1024 * 1024;
+
+ private static final String PROBE = "probe";
+
+ @Produce("direct:send")
+ private ProducerTemplate producer;
+
+ static Stream<Arguments> messages() {
+ String text = "x".repeat(MESSAGE_SIZE);
+ byte[] bytes = text.getBytes(StandardCharsets.US_ASCII);
+ return Stream.of(
+ Arguments.of("String", text),
+ Arguments.of("Reader", new StringReader(text)),
+ Arguments.of("byte[]", bytes),
+ Arguments.of("InputStream", new ByteArrayInputStream(bytes)));
+ }
+
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("messages")
+ public void sendToStalledPeerTimesOut(String type, Object body) throws
Exception {
+ try (Socket peer = connectStalledPeer()) {
+ CompletableFuture<Exchange> future =
producer.asyncSend("direct:send", exchange -> {
+ exchange.getIn().setBody(body);
+ exchange.getIn().setHeader(UndertowConstants.SEND_TO_ALL,
true);
+ });
+
+ // the send timeout is 1 second; without it the exchange would
never complete
+ Exchange exchange = future.get(30, TimeUnit.SECONDS);
+
+ CamelExchangeException failure =
assertInstanceOf(CamelExchangeException.class, exchange.getException(),
+ "A " + type + " message that is not sent within the send
timeout should fail the exchange");
+ assertInstanceOf(TimeoutException.class, failure.getCause(),
failure.getMessage());
+
+ assertTrue(isClosedByServer(peer), "The connection to the stalled
peer should be closed");
+ }
+ }
+
+ /**
+ * Reads what the server wrote before it closed the connection.
+ */
+ private static boolean isClosedByServer(Socket peer) throws IOException {
+ peer.setSoTimeout(20000);
+ InputStream in = peer.getInputStream();
+ byte[] buffer = new byte[64 * 1024];
+ try {
+ while (in.read(buffer) >= 0) {
+ // drain
+ }
+ return true;
+ } catch (SocketTimeoutException e) {
+ return false;
+ } catch (SocketException e) {
+ // reset by the server
+ return true;
+ }
+ }
+
+ /**
+ * Opens a WebSocket connection to the producer path and then never reads
from it, as a stalled peer does.
+ */
+ private Socket connectStalledPeer() throws IOException {
+ Socket socket = new Socket();
+ // a small window, so that the server soon has to wait for the peer to
read
+ socket.setReceiveBufferSize(4096);
+ socket.connect(new InetSocketAddress("localhost", getPort()), 10000);
+ socket.setSoTimeout(10000);
+
+ String key =
Base64.getEncoder().encodeToString("camel-27569-test".getBytes(StandardCharsets.US_ASCII));
+ String request = "GET /slow HTTP/1.1\r\n"
+ + "Host: localhost:" + getPort() + "\r\n"
+ + "Upgrade: websocket\r\n"
+ + "Connection: Upgrade\r\n"
+ + "Sec-WebSocket-Key: " + key + "\r\n"
+ + "Sec-WebSocket-Version: 13\r\n"
+ + "\r\n";
+ OutputStream out = socket.getOutputStream();
+ out.write(request.getBytes(StandardCharsets.US_ASCII));
+ out.flush();
+
+ // read the handshake response, and nothing after it
+ InputStream in = socket.getInputStream();
+ ByteArrayOutputStream response = new ByteArrayOutputStream();
+ while
(!response.toString(StandardCharsets.US_ASCII).endsWith("\r\n\r\n")) {
+ int b = in.read();
+ if (b < 0) {
+ throw new IOException("Connection closed during the handshake:
" + response);
+ }
+ response.write(b);
+ }
+ String status =
response.toString(StandardCharsets.US_ASCII).lines().findFirst().orElse("");
+ assertEquals("HTTP/1.1 101 Switching Protocols", status);
+
+ // Undertow registers the peer only after it has sent the handshake
response, so send small probes until one
+ // arrives; from then on the peer reads nothing more
+ socket.setSoTimeout(200);
+ await().atMost(20, TimeUnit.SECONDS).until(() -> {
+ producer.sendBodyAndHeader("direct:send", PROBE,
UndertowConstants.SEND_TO_ALL, true);
+ return readProbe(in);
+ });
+ return socket;
+ }
+
+ private static boolean readProbe(InputStream in) throws IOException {
+ // an unmasked text frame whose payload is shorter than 126 bytes: FIN
+ opcode, length, payload
+ byte[] expected = new byte[2 + PROBE.length()];
+ expected[0] = (byte) 0x81;
+ expected[1] = (byte) PROBE.length();
+ System.arraycopy(PROBE.getBytes(StandardCharsets.US_ASCII), 0,
expected, 2, PROBE.length());
+ try {
+ assertArrayEquals(expected, in.readNBytes(expected.length));
+ return true;
+ } catch (SocketTimeoutException e) {
+ return false;
+ }
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ public void configure() {
+ from("direct:send")
+ .to("undertow:ws://localhost:" + getPort() +
"/slow?sendTimeout=1000");
+ }
+ };
+ }
+}
diff --git
a/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/ws/UndertowWsProducerSendToAllStreamTest.java
b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/ws/UndertowWsProducerSendToAllStreamTest.java
new file mode 100644
index 000000000000..7ab62a1c56da
--- /dev/null
+++
b/components/camel-undertow/src/test/java/org/apache/camel/component/undertow/ws/UndertowWsProducerSendToAllStreamTest.java
@@ -0,0 +1,97 @@
+/*
+ * 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.undertow.ws;
+
+import java.io.ByteArrayInputStream;
+import java.io.StringReader;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.undertow.BaseUndertowTest;
+import org.apache.camel.component.undertow.UndertowConstants;
+import org.apache.camel.test.infra.common.http.WebsocketTestClient;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A {@code Reader} or {@code InputStream} body sent to several peers is read
once, so that every peer receives the
+ * whole message, whether the route caches streams or not.
+ */
+public class UndertowWsProducerSendToAllStreamTest extends BaseUndertowTest {
+
+ private static final String MESSAGE = "Beer on stock at Apache Mall";
+
+ static Stream<Arguments> bodies() {
+ return Stream.of("direct:cached", "direct:uncached").flatMap(route ->
Stream.of(
+ Arguments.of(route, "Reader"),
+ Arguments.of(route, "InputStream")));
+ }
+
+ @ParameterizedTest(name = "{0} {1}")
+ @MethodSource("bodies")
+ public void everyPeerReceivesTheWholeMessage(String route, String type)
throws Exception {
+ WebsocketTestClient first = new WebsocketTestClient("ws://localhost:"
+ getPort() + "/shop");
+ WebsocketTestClient second = new WebsocketTestClient("ws://localhost:"
+ getPort() + "/shop");
+ first.connect();
+ second.connect();
+ try {
+ // Undertow registers a peer after the handshake, so send probes
until both peers receive them
+ await().atMost(20, TimeUnit.SECONDS).until(() -> {
+ template.sendBodyAndHeader("direct:uncached", "probe",
UndertowConstants.SEND_TO_ALL, true);
+ return !first.getReceived().isEmpty() &&
!second.getReceived().isEmpty();
+ });
+
+ Object body = "Reader".equals(type)
+ ? new StringReader(MESSAGE)
+ : new
ByteArrayInputStream(MESSAGE.getBytes(StandardCharsets.UTF_8));
+ template.sendBodyAndHeader(route, body,
UndertowConstants.SEND_TO_ALL, true);
+
+ await().atMost(20, TimeUnit.SECONDS)
+ .until(() -> received(first).contains(MESSAGE) &&
received(second).contains(MESSAGE));
+ assertTrue(received(first).stream().noneMatch(String::isEmpty),
"first peer: " + received(first));
+ assertTrue(received(second).stream().noneMatch(String::isEmpty),
"second peer: " + received(second));
+ } finally {
+ first.close();
+ second.close();
+ }
+ }
+
+ private static List<String> received(WebsocketTestClient client) {
+ return client.getReceived().stream()
+ .map(o -> o instanceof byte[] ? new String((byte[]) o,
StandardCharsets.UTF_8) : String.valueOf(o))
+ .toList();
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ public void configure() {
+ from("direct:cached").streamCache("true")
+ .to("undertow:ws://localhost:" + getPort() + "/shop");
+ from("direct:uncached").streamCache("false")
+ .to("undertow:ws://localhost:" + getPort() + "/shop");
+ }
+ };
+ }
+}
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 38b8b68c3feb..6195e29cb3ce 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
@@ -6702,6 +6702,17 @@ first ran is no longer served: its messages no longer
reach the route and it no
sends, and the connection is closed. Clients that open a connection in this
window must reconnect after the consumer
has started.
+=== camel-undertow - a WebSocket message not sent within sendTimeout fails the
exchange
+
+The `sendTimeout` option of a WebSocket producer (30 seconds by default) now
applies to text messages, that is a
+`String` or `Reader` body, and to bodies converted to `String`. Before, it
applied only to `byte[]` and `InputStream`
+bodies, so a text message to a peer that stopped reading stayed in flight,
with its exchange, until the peer read it
+or the connection closed.
+
+A message that is not sent to a peer within `sendTimeout` now fails the
exchange with a `CamelExchangeException`
+caused by a `TimeoutException`, and the connection to that peer is closed.
Before, the timeout of a binary message
+only dropped the message, and the exchange completed as if it was sent. Set
`sendTimeout` to `0` for no timeout.
+
=== camel-undertow, camel-vertx-http - CamelHttpPath with a query in the
endpoint uri
When the endpoint uri of an undertow or vertx-http producer has a query, the
`CamelHttpPath` header now goes before
diff --git
a/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/UndertowEndpointBuilderFactory.java
b/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/UndertowEndpointBuilderFactory.java
index 1a455280cd64..b9a1811384cc 100644
---
a/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/UndertowEndpointBuilderFactory.java
+++
b/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/UndertowEndpointBuilderFactory.java
@@ -1101,7 +1101,9 @@ public interface UndertowEndpointBuilderFactory {
}
/**
* Timeout in milliseconds when sending to a websocket channel. The
- * default timeout is 30000 (30 seconds).
+ * default timeout is 30000 (30 seconds). A message that is not sent to
+ * a peer within the timeout fails the exchange, and the connection to
+ * that peer is closed. Use 0 for no timeout.
*
* The option is a: <code>java.lang.Integer</code> type.
*
@@ -1117,7 +1119,9 @@ public interface UndertowEndpointBuilderFactory {
}
/**
* Timeout in milliseconds when sending to a websocket channel. The
- * default timeout is 30000 (30 seconds).
+ * default timeout is 30000 (30 seconds). A message that is not sent to
+ * a peer within the timeout fails the exchange, and the connection to
+ * that peer is closed. Use 0 for no timeout.
*
* The option will be converted to a <code>java.lang.Integer</code>
* type.