This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch dev
in repository https://gitbox.apache.org/repos/asf/seatunnel.git
The following commit(s) were added to refs/heads/dev by this push:
new bbeb327127 [Fix][Connector-V2] Clear the stale websocket fatal error
when a reconnect succeeds (#12716)
bbeb327127 is described below
commit bbeb327127fd174962f6560b4ff7d8ed1418bc54
Author: Jast <[email protected]>
AuthorDate: Wed Nov 25 14:38:43 2026 +0000
[Fix][Connector-V2] Clear the stale websocket fatal error when a reconnect
succeeds (#12716)
Co-authored-by: jast <[email protected]>
Co-authored-by: Claude Code <[email protected]>
---
.../websocket/source/WebSocketSourceClient.java | 51 +++++-
.../WebSocketSourceClientFatalErrorTest.java | 181 +++++++++++++++++++++
.../source/WebSocketSourceReaderTest.java | 45 +++++
3 files changed, 271 insertions(+), 6 deletions(-)
diff --git
a/seatunnel-connectors-v2/connector-websocket/src/main/java/org/apache/seatunnel/connectors/seatunnel/websocket/source/WebSocketSourceClient.java
b/seatunnel-connectors-v2/connector-websocket/src/main/java/org/apache/seatunnel/connectors/seatunnel/websocket/source/WebSocketSourceClient.java
index ef251df288..af3e34f69e 100644
---
a/seatunnel-connectors-v2/connector-websocket/src/main/java/org/apache/seatunnel/connectors/seatunnel/websocket/source/WebSocketSourceClient.java
+++
b/seatunnel-connectors-v2/connector-websocket/src/main/java/org/apache/seatunnel/connectors/seatunnel/websocket/source/WebSocketSourceClient.java
@@ -67,6 +67,15 @@ public class WebSocketSourceClient {
private volatile boolean closed;
private volatile long connectedTimestamp;
+ /**
+ * The open-message send rejected by a dying connection, see {@link
+ * SourceWebSocketListener#onOpen}. Not fatal on its own: the reconnect
replaces the connection
+ * that recorded it. Only kept so that the terminal error reported after
the reconnect budget is
+ * exhausted still names the send failure instead of only the transport
error that broke the
+ * camel's back.
+ */
+ private volatile WebSocketConnectorException openMessageSendFailure;
+
public WebSocketSourceClient(WebSocketSourceConfig config) {
this.config = config;
this.messageQueue = new
ArrayBlockingQueue<>(config.getQueueCapacity());
@@ -177,7 +186,7 @@ public class WebSocketSourceClient {
return;
}
if (!config.isEnableReconnect()) {
- fatalError = cause;
+ fatalError = asTerminalError(cause);
return;
}
if (reconnectTimes.get() >= config.getMaxReconnectTimes()) {
@@ -185,7 +194,7 @@ public class WebSocketSourceClient {
"Reconnect to websocket server [{}] gave up after [{}]
attempts",
config.getMaskedUrl(),
reconnectTimes.get());
- fatalError = cause;
+ fatalError = asTerminalError(cause);
return;
}
log.warn(
@@ -205,6 +214,23 @@ public class WebSocketSourceClient {
}
}
+ /**
+ * The error that ends the task once the connection is given up on. When
the connection was
+ * dying because it rejected an open-message send, that recorded send
failure is the
+ * closer-to-root cause of the loss, so the terminal error reports it and
keeps the transport
+ * error that finally broke the camel's back as its cause. Without this, a
reconnect budget
+ * exhausted by such connections would only report the cancellation
triggered by the client
+ * itself, which tells the operator nothing about the actual problem.
+ */
+ private Throwable asTerminalError(Throwable cause) {
+ WebSocketConnectorException sendFailure = openMessageSendFailure;
+ if (sendFailure == null) {
+ return cause;
+ }
+ return new WebSocketConnectorException(
+ sendFailure.getSeaTunnelErrorCode(), sendFailure.getMessage(),
cause);
+ }
+
/**
* Buffers a received frame, making the callback thread wait while the
queue is full so that the
* server is back-pressured instead of the heap growing without limit.
@@ -237,11 +263,16 @@ public class WebSocketSourceClient {
}
}
- private class SourceWebSocketListener extends WebSocketListener {
+ // package-private so tests can drive the callbacks against stub sockets
without a live server
+ class SourceWebSocketListener extends WebSocketListener {
@Override
public void onOpen(WebSocket webSocket, Response response) {
reconnectTimes.set(0);
+ // a re-established connection invalidates any failure recorded
for the dead one,
+ // otherwise rethrowFatalIfNeeded() would kill the recovered task
with a stale error
+ fatalError = null;
+ openMessageSendFailure = null;
connectedTimestamp = System.currentTimeMillis();
log.info("Websocket connection to [{}] is established",
config.getMaskedUrl());
List<String> openMessages = config.getOpenMessages();
@@ -251,14 +282,22 @@ public class WebSocketSourceClient {
for (int i = 0; i < openMessages.size(); i++) {
// never log the payload itself, it usually carries credentials
if (!webSocket.send(openMessages.get(i))) {
- // throwing here would only be swallowed by the callback
thread, record the
- // failure so that the reader can fail the task on its
next poll
- fatalError =
+ // a rejected send only means the connection is already
dying. Recording it as
+ // a fatal error would fail the task on the reader's next
poll, which happens
+ // within poll_timeout_ms (1000ms by default) - long
before the reconnect
+ // scheduled reconnect_interval_ms (3000ms by default)
later, so a transient
+ // disconnect right after the handshake would still kill
the task, see
+ // https://github.com/apache/seatunnel/issues/12713. Treat
it as a connection
+ // failure instead: cancel the dying socket so the regular
onFailure ->
+ // onDisconnected path schedules the reconnect, and
remember the send failure
+ // so the terminal error still names it once the budget is
exhausted.
+ openMessageSendFailure =
new WebSocketConnectorException(
WebSocketConnectorErrorCode.SEND_MESSAGE_FAILED,
String.format(
"Failed to send open message at
index [%s] to websocket server [%s]",
i, config.getMaskedUrl()));
+ webSocket.cancel();
return;
}
}
diff --git
a/seatunnel-connectors-v2/connector-websocket/src/test/java/org/apache/seatunnel/connectors/seatunnel/websocket/source/WebSocketSourceClientFatalErrorTest.java
b/seatunnel-connectors-v2/connector-websocket/src/test/java/org/apache/seatunnel/connectors/seatunnel/websocket/source/WebSocketSourceClientFatalErrorTest.java
new file mode 100644
index 0000000000..4f5cfd4f60
--- /dev/null
+++
b/seatunnel-connectors-v2/connector-websocket/src/test/java/org/apache/seatunnel/connectors/seatunnel/websocket/source/WebSocketSourceClientFatalErrorTest.java
@@ -0,0 +1,181 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.websocket.source;
+
+import org.apache.seatunnel.api.configuration.ReadonlyConfig;
+import
org.apache.seatunnel.connectors.seatunnel.websocket.config.WebSocketSourceConfig;
+import
org.apache.seatunnel.connectors.seatunnel.websocket.config.WebSocketSourceOptions;
+import
org.apache.seatunnel.connectors.seatunnel.websocket.exception.WebSocketConnectorErrorCode;
+import
org.apache.seatunnel.connectors.seatunnel.websocket.exception.WebSocketConnectorException;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import okhttp3.Protocol;
+import okhttp3.Request;
+import okhttp3.Response;
+import okhttp3.WebSocket;
+import okio.ByteString;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * A connection that rejects the open-message send while it is dying must not
fail the task while a
+ * reconnect can still replace it, see <a
+ * href="https://github.com/apache/seatunnel/issues/12713">#12713</a>. The
reader rethrows a
+ * terminal error within {@code poll_timeout_ms} (1000ms by default), while
the reconnect only fires
+ * after {@code reconnect_interval_ms} (3000ms by default), so recording the
send failure as fatal
+ * would kill the task before the recovery the PR promises. Only an exhausted
reconnect budget (or
+ * reconnect disabled) may turn it into the task's terminal error.
+ */
+class WebSocketSourceClientFatalErrorTest {
+
+ private static Response upgradeResponse() {
+ return new Response.Builder()
+ .request(new
Request.Builder().url("https://seatunnel.invalid/").build())
+ .protocol(Protocol.HTTP_1_1)
+ .code(101)
+ .message("Switching Protocols")
+ .build();
+ }
+
+ /** A socket that behaves like one that is already closing: every send is
rejected. */
+ private static WebSocket refusingSocket() {
+ return new StubWebSocket(false);
+ }
+
+ /** A socket that behaves like the healthy replacement connection: every
send succeeds. */
+ private static WebSocket acceptingSocket() {
+ return new StubWebSocket(true);
+ }
+
+ /**
+ * The scenario of #12713: the send of the open message is rejected
because the connection is
+ * dying. The rejected send must not become a terminal error on its own,
otherwise the reader
+ * fails the task on its next poll, about two seconds before the scheduled
reconnect runs.
+ */
+ @Test
+ void shouldNotFailTheTaskWhenAnOpenMessageSendIsRejected() {
+ WebSocketSourceClient client = new WebSocketSourceClient(config(true));
+ WebSocketSourceClient.SourceWebSocketListener listener =
+ client.new SourceWebSocketListener();
+
+ listener.onOpen(refusingSocket(), upgradeResponse());
+
+ Assertions.assertDoesNotThrow(
+ client::rethrowFatalIfNeeded,
+ "a rejected open-message send must not fail the task while a
reconnect can still"
+ + " replace the dying connection");
+ }
+
+ /**
+ * Cancellation of the dying socket leads to the regular onFailure ->
onDisconnected path. Once
+ * no reconnect is allowed to follow, the task must fail with an error
that names the rejected
+ * send instead of only the cancellation the client triggered itself.
+ */
+ @Test
+ void shouldFailNamingTheSendFailureWhenNoReconnectMayFollow() {
+ WebSocketSourceClient client = new
WebSocketSourceClient(config(false));
+ WebSocketSourceClient.SourceWebSocketListener listener =
+ client.new SourceWebSocketListener();
+
+ WebSocket dyingSocket = refusingSocket();
+ listener.onOpen(dyingSocket, upgradeResponse());
+ listener.onFailure(dyingSocket, new IOException("canceled"), null);
+
+ WebSocketConnectorException exception =
+ Assertions.assertThrows(
+ WebSocketConnectorException.class,
client::rethrowFatalIfNeeded);
+ Assertions.assertEquals(
+ WebSocketConnectorErrorCode.SEND_MESSAGE_FAILED,
exception.getSeaTunnelErrorCode());
+ Assertions.assertTrue(
+ exception.getMessage().contains("Failed to send open message"),
+ "the terminal error must name the rejected send: " +
exception.getMessage());
+ Assertions.assertNotNull(exception.getCause(), "the transport error
must be kept as cause");
+ }
+
+ /**
+ * A re-established connection invalidates any failure recorded for the
dead one: after a
+ * successful reconnect the recovered task must not be killed by a stale
error.
+ */
+ @Test
+ void shouldNotFailTheRecoveredTaskAfterASuccessfulReconnect() {
+ WebSocketSourceClient client = new
WebSocketSourceClient(config(false));
+ WebSocketSourceClient.SourceWebSocketListener listener =
+ client.new SourceWebSocketListener();
+
+ listener.onOpen(refusingSocket(), upgradeResponse());
+ // the dying socket reports the failure the cancellation provoked
+ listener.onFailure(refusingSocket(), new IOException("canceled"),
null);
+ // the automatic reconnect establishes a healthy replacement connection
+ listener.onOpen(acceptingSocket(), upgradeResponse());
+
+ Assertions.assertDoesNotThrow(
+ client::rethrowFatalIfNeeded,
+ "a stale error recorded by the replaced connection must not
kill the recovered"
+ + " task");
+ }
+
+ private static WebSocketSourceConfig config(boolean enableReconnect) {
+ Map<String, Object> configMap = new HashMap<>();
+ configMap.put(WebSocketSourceOptions.URL.key(),
"ws://seatunnel.invalid/");
+ configMap.put(WebSocketSourceOptions.OPEN_MESSAGES.key(),
Collections.singletonList("x"));
+ configMap.put(WebSocketSourceOptions.ENABLE_RECONNECT.key(),
enableReconnect);
+ return new WebSocketSourceConfig(ReadonlyConfig.fromMap(configMap));
+ }
+
+ private static final class StubWebSocket implements WebSocket {
+
+ private final boolean acceptsSends;
+
+ private StubWebSocket(boolean acceptsSends) {
+ this.acceptsSends = acceptsSends;
+ }
+
+ @Override
+ public Request request() {
+ return new
Request.Builder().url("https://seatunnel.invalid/").build();
+ }
+
+ @Override
+ public long queueSize() {
+ return 0L;
+ }
+
+ @Override
+ public boolean send(String text) {
+ return acceptsSends;
+ }
+
+ @Override
+ public boolean send(ByteString bytes) {
+ return acceptsSends;
+ }
+
+ @Override
+ public boolean close(int code, String reason) {
+ return true;
+ }
+
+ @Override
+ public void cancel() {}
+ }
+}
diff --git
a/seatunnel-connectors-v2/connector-websocket/src/test/java/org/apache/seatunnel/connectors/seatunnel/websocket/source/WebSocketSourceReaderTest.java
b/seatunnel-connectors-v2/connector-websocket/src/test/java/org/apache/seatunnel/connectors/seatunnel/websocket/source/WebSocketSourceReaderTest.java
index 007e908e33..381cd6c35d 100644
---
a/seatunnel-connectors-v2/connector-websocket/src/test/java/org/apache/seatunnel/connectors/seatunnel/websocket/source/WebSocketSourceReaderTest.java
+++
b/seatunnel-connectors-v2/connector-websocket/src/test/java/org/apache/seatunnel/connectors/seatunnel/websocket/source/WebSocketSourceReaderTest.java
@@ -322,6 +322,51 @@ class WebSocketSourceReaderTest {
Assertions.assertEquals("alice", collector.rows.get(0).getField(1));
}
+ /**
+ * The scenario of <a
href="https://github.com/apache/seatunnel/issues/12713">#12713</a>: the
+ * first connection is dropped right after the handshake, so the
open-message send races with
+ * the dying socket. With the default {@code poll_timeout_ms} (1000ms) and
{@code
+ * reconnect_interval_ms} (3000ms) the reader re-checks for terminal
errors twice before the
+ * reconnect even fires, so the task only survives if the rejected send is
treated as a
+ * connection failure that the reconnect replaces, not as a terminal
error. The reader must keep
+ * polling through that window and emit the row the reconnected
subscription produces.
+ */
+ @Test
+ void
shouldSurviveADroppedFirstConnectionWithDefaultPollAndReconnectOptions() throws
Exception {
+ String url =
+ startServerWith(
+ connectionDroppingListener(),
+
subscriptionDrivenListener("{\"id\":1,\"name\":\"alice\"}"));
+ // deliberately not overriding poll_timeout_ms (1000) and
reconnect_interval_ms (3000):
+ // the bug only shows on the default timing, where the reader rethrows
long before the
+ // scheduled reconnect replaces the connection
+ Map<String, Object> configMap = new HashMap<>();
+ configMap.put(WebSocketSourceOptions.URL.key(), url);
+ configMap.put(ConnectorCommonOptions.SCHEMA.key(), jsonSchema());
+ configMap.put(
+ WebSocketSourceOptions.OPEN_MESSAGES.key(),
+ Collections.singletonList(SUBSCRIBE_MESSAGE));
+ configMap.put(WebSocketSourceOptions.ENABLE_RECONNECT.key(), true);
+ configMap.put(WebSocketSourceOptions.MAX_RECORDS.key(), 1);
+
+ SourceReader.Context context = mockContext(Boundedness.BOUNDED);
+ AtomicBoolean noMoreElement = trackNoMoreElement(context);
+ TestCollector collector = new TestCollector();
+ try (AbstractSingleSplitReader<SeaTunnelRow> reader =
createReader(configMap, context)) {
+ reader.open();
+ pollUntil(reader, collector, noMoreElement::get);
+ }
+
+ Assertions.assertTrue(
+ noMoreElement.get(), "The reconnected reader must reach the
end of the stream");
+ Assertions.assertEquals(
+ SUBSCRIBE_MESSAGE,
+ reconnectedServerReceived.poll(AWAIT_TIMEOUT_MS,
TimeUnit.MILLISECONDS),
+ "The subscription must be sent on the replacement connection");
+ Assertions.assertEquals(1, collector.rows.size());
+ Assertions.assertEquals("alice", collector.rows.get(0).getField(1));
+ }
+
/**
* Once the reconnect budget is exhausted the reader must fail the task
instead of waiting for
* messages that can never arrive. The failure message reaches job logs
and alerts, so it must