Skip to content

Commit

Permalink
fix: complete client websocket future on open (#20587)
Browse files Browse the repository at this point in the history
* fix: complete client websocket future on open

Completing the websocket future in onOpen event prevents the connection to hang
indefintely when application run on low resources.

Fixes #20586

* apply review suggestions
  • Loading branch information
mcollovati authored Dec 10, 2024
1 parent 5b95429 commit 39e640c
Showing 1 changed file with 10 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public class ViteWebsocketConnection implements Listener {

private final Consumer<String> onMessage;
private final Runnable onClose;
private final CompletableFuture<WebSocket> clientWebsocket;
private final CompletableFuture<WebSocket> clientWebsocket = new CompletableFuture<>();
private final List<CharSequence> parts = new ArrayList<>();

private static Logger getLogger() {
Expand Down Expand Up @@ -72,15 +72,20 @@ public ViteWebsocketConnection(int port, String path, String subProtocol,
this.onClose = onClose;
String wsHost = ViteHandler.DEV_SERVER_HOST.replace("http://", "ws://");
URI uri = URI.create(wsHost + ":" + port + path);
clientWebsocket = HttpClient.newHttpClient().newWebSocketBuilder()
HttpClient.newHttpClient().newWebSocketBuilder()
.subprotocols(subProtocol).buildAsync(uri, this)
.whenComplete(((webSocket, failure) -> {
if (failure == null) {
getLogger().debug(
"Connection to {} using the {} protocol established",
uri, webSocket.getSubprotocol());
if (clientWebsocket.complete(webSocket)) {
getLogger().trace(
"Websocket future completed in client build completion");
}
} else {
getLogger().debug("Failed to connect to {}", uri);
clientWebsocket.completeExceptionally(failure);
onConnectionFailure.accept(failure);
}
}));
Expand All @@ -90,6 +95,9 @@ public ViteWebsocketConnection(int port, String path, String subProtocol,
public void onOpen(WebSocket webSocket) {
getLogger().debug("Connected using the {} protocol",
webSocket.getSubprotocol());
if (clientWebsocket.complete(webSocket)) {
getLogger().trace("Websocket future completed in onOpen");
}
Listener.super.onOpen(webSocket);
}

Expand Down

0 comments on commit 39e640c

Please # to comment.