Skip to content

Commit 73f26e8

Browse files
authored
fix: Use the servlet host and port for the Vite websocket connection (#15689)
* Update checker plugin so it uses the correct WS url
1 parent cf5b032 commit 73f26e8

12 files changed

Lines changed: 447 additions & 37 deletions

File tree

‎flow-server/src/main/java/com/vaadin/flow/server/VaadinServlet.java‎

Lines changed: 41 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,6 @@
1515
*/
1616
package com.vaadin.flow.server;
1717

18-
import jakarta.servlet.ServletConfig;
19-
import jakarta.servlet.ServletContext;
20-
import jakarta.servlet.ServletException;
21-
import jakarta.servlet.ServletRegistration;
22-
import jakarta.servlet.http.HttpServlet;
23-
import jakarta.servlet.http.HttpServletRequest;
24-
import jakarta.servlet.http.HttpServletResponse;
25-
26-
import org.slf4j.Logger;
27-
import org.slf4j.LoggerFactory;
28-
2918
import java.io.IOException;
3019
import java.net.MalformedURLException;
3120
import java.net.URL;
@@ -35,6 +24,10 @@
3524
import java.util.List;
3625
import java.util.Map;
3726
import java.util.Properties;
27+
import java.util.function.Consumer;
28+
29+
import org.slf4j.Logger;
30+
import org.slf4j.LoggerFactory;
3831

3932
import com.vaadin.flow.component.UI;
4033
import com.vaadin.flow.di.Lookup;
@@ -46,6 +39,14 @@
4639
import com.vaadin.flow.server.startup.ApplicationConfiguration;
4740
import com.vaadin.flow.shared.JsonConstants;
4841

42+
import jakarta.servlet.ServletConfig;
43+
import jakarta.servlet.ServletContext;
44+
import jakarta.servlet.ServletException;
45+
import jakarta.servlet.ServletRegistration;
46+
import jakarta.servlet.http.HttpServlet;
47+
import jakarta.servlet.http.HttpServletRequest;
48+
import jakarta.servlet.http.HttpServletResponse;
49+
4950
/**
5051
* The main servlet, which handles all incoming requests to the application.
5152
* <p>
@@ -70,6 +71,8 @@ public class VaadinServlet extends HttpServlet {
7071
private volatile boolean isServletInitialized;
7172
private static String frontendMapping = null;
7273

74+
private static List<Runnable> whenFrontendMappingAvailable = new ArrayList<>();
75+
7376
/**
7477
* Called by the servlet container to indicate to a servlet that the servlet
7578
* is being placed into service.
@@ -162,6 +165,7 @@ private void detectFrontendMapping() {
162165
if (definedPath != null) {
163166
// Use the path define in a property
164167
frontendMapping = definedPath;
168+
invokeWhenFrontendMappingAvailable();
165169
return;
166170
}
167171

@@ -194,6 +198,32 @@ private void detectFrontendMapping() {
194198
getLogger().debug("Using mapping " + frontendMapping
195199
+ " from servlet " + getClass().getSimpleName()
196200
+ " as the frontend servlet because this was the first deployed VaadinServlet");
201+
invokeWhenFrontendMappingAvailable();
202+
}
203+
}
204+
}
205+
206+
private void invokeWhenFrontendMappingAvailable() {
207+
synchronized (VaadinServlet.class) {
208+
for (Runnable consumer : whenFrontendMappingAvailable) {
209+
consumer.run();
210+
}
211+
whenFrontendMappingAvailable.clear();
212+
}
213+
}
214+
215+
/**
216+
* Runs the given runnable when frontend mapping is available.
217+
*
218+
* @param runnable
219+
* the runnable to run
220+
*/
221+
public static void whenFrontendMappingAvailable(Runnable runnable) {
222+
synchronized (VaadinServlet.class) {
223+
if (frontendMapping != null) {
224+
runnable.run();
225+
} else {
226+
whenFrontendMappingAvailable.add(runnable);
197227
}
198228
}
199229
}

‎flow-server/src/main/resources/com/vaadin/flow/server/frontend/dependencies/vite/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
"@rollup/plugin-replace": "5.0.2",
1515
"@rollup/pluginutils": "5.0.2",
1616
"rollup-plugin-brotli": "3.1.0",
17-
"vite-plugin-checker": "0.5.2",
17+
"vite-plugin-checker": "0.5.3",
1818
"mkdirp": "1.0.4",
1919
"workbox-build": "6.5.4",
2020
"transform-ast": "2.4.4"

‎flow-server/src/main/resources/vite.generated.ts‎

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -513,18 +513,6 @@ const allowedFrontendFolders = [
513513
nodeModulesFolder
514514
];
515515

516-
function setHmrPortToServerPort(): PluginOption {
517-
return {
518-
name: 'set-hmr-port-to-server-port',
519-
configResolved(config) {
520-
if (config.server.strictPort && config.server.hmr !== false) {
521-
if (config.server.hmr === true) config.server.hmr = {};
522-
config.server.hmr = config.server.hmr || {};
523-
config.server.hmr.clientPort = config.server.port;
524-
}
525-
}
526-
};
527-
}
528516
function showRecompileReason(): PluginOption {
529517
return {
530518
name: 'vaadin:why-you-compile',
@@ -596,7 +584,6 @@ export const vaadinConfig: UserConfigFn = (env) => {
596584
plugins: [
597585
!devMode && brotli(),
598586
devMode && vaadinBundlesPlugin(),
599-
devMode && setHmrPortToServerPort(),
600587
devMode && showRecompileReason(),
601588
settings.offlineEnabled && buildSWPlugin({ devMode }),
602589
!devMode && statsExtracterPlugin(),

‎flow-test-generic/src/main/java/com/vaadin/flow/testutil/ClassesSerializableTest.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ protected Stream<String> getExcludedPatterns() {
7070
"com\\.vaadin\\.flow\\.osgi\\.support\\..*",
7171
"com\\.vaadin\\.flow\\.server\\.osgi\\..*",
7272
"com\\.vaadin\\.base\\.devserver\\.DevServerOutputTracker.*",
73+
"com\\.vaadin\\.base\\.devserver\\.viteproxy\\..*",
7374
"com\\.vaadin\\.base\\.devserver\\.stats..*",
7475
"com\\.vaadin\\.flow\\.internal\\.VaadinContextInitializer",
7576
"com\\.vaadin\\.flow\\.internal\\.ApplicationClassLoaderAccess",

‎vaadin-dev-server/pom.xml‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
<?xml version="1.0" encoding="UTF-8"?>
22
<project xmlns="http://maven.apache.org/POM/4.0.0"
3-
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
45
<modelVersion>4.0.0</modelVersion>
56
<parent>
67
<groupId>com.vaadin</groupId>
@@ -41,6 +42,21 @@
4142
<artifactId>jakarta.servlet-api</artifactId>
4243
<scope>provided</scope>
4344
</dependency>
45+
<dependency>
46+
<groupId>jakarta.websocket</groupId>
47+
<artifactId>jakarta.websocket-api</artifactId>
48+
<version>2.1.0</version>
49+
</dependency>
50+
<dependency>
51+
<groupId>jakarta.websocket</groupId>
52+
<artifactId>jakarta.websocket-api</artifactId>
53+
<version>2.1.0</version>
54+
</dependency>
55+
<dependency>
56+
<groupId>jakarta.websocket</groupId>
57+
<artifactId>jakarta.websocket-client-api</artifactId>
58+
<version>2.1.0</version>
59+
</dependency>
4460

4561
<!-- Test dependencies -->
4662

‎vaadin-dev-server/src/main/java/com/vaadin/base/devserver/AbstractDevServerRunner.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ public abstract class AbstractDevServerRunner implements DevModeHandler {
7878

7979
private static final String START_FAILURE = "Couldn't start dev server because";
8080

81-
private static final String DEV_SERVER_HOST = "http://127.0.0.1";
81+
public static final String DEV_SERVER_HOST = "http://127.0.0.1";
8282

8383
private static final String FAILED_MSG = "\n------------------ Frontend compilation failed. ------------------\n\n";
8484
private static final String SUCCEED_MSG = "\n----------------- Frontend compiled successfully. -----------------\n\n";

‎vaadin-dev-server/src/main/java/com/vaadin/base/devserver/ViteHandler.java‎

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,11 @@
1515
*/
1616
package com.vaadin.base.devserver;
1717

18+
import static com.vaadin.flow.server.Constants.VAADIN_MAPPING;
19+
import static com.vaadin.flow.server.frontend.FrontendUtils.INDEX_HTML;
20+
import static com.vaadin.flow.server.frontend.FrontendUtils.SERVICE_WORKER_SRC_JS;
21+
import static com.vaadin.flow.server.frontend.FrontendUtils.WEB_COMPONENT_HTML;
22+
1823
import java.io.File;
1924
import java.io.IOException;
2025
import java.net.HttpURLConnection;
@@ -33,11 +38,6 @@
3338
import com.vaadin.flow.server.frontend.FrontendTools;
3439
import com.vaadin.flow.server.frontend.FrontendUtils;
3540

36-
import static com.vaadin.flow.server.Constants.VAADIN_MAPPING;
37-
import static com.vaadin.flow.server.frontend.FrontendUtils.INDEX_HTML;
38-
import static com.vaadin.flow.server.frontend.FrontendUtils.SERVICE_WORKER_SRC_JS;
39-
import static com.vaadin.flow.server.frontend.FrontendUtils.WEB_COMPONENT_HTML;
40-
4141
/**
4242
* Handles communication with a Vite server.
4343
* <p>
@@ -153,11 +153,23 @@ public HttpURLConnection prepareConnection(String path, String method)
153153
return super.prepareConnection(vitePath, method);
154154
}
155155

156+
/**
157+
* Gets the url path to the /VAADIN folder.
158+
*
159+
* @return the url path to the /VAADIN folder, relative to the host root
160+
*/
156161
private String getPathToVaadin() {
157-
return getContextPath()
158-
+ FrontendUtils.getFrontendServletPath(
159-
getServletContext().getContext())
160-
+ "/" + VAADIN_MAPPING;
162+
return getContextPath() + getPathToVaadinInContext();
163+
}
164+
165+
/**
166+
* Gets the url path to the /VAADIN folder inside the context root.
167+
*
168+
* @return the url path to the /VAADIN folder, relative to the context root
169+
*/
170+
public String getPathToVaadinInContext() {
171+
return FrontendUtils.getFrontendServletPath(
172+
getServletContext().getContext()) + "/" + VAADIN_MAPPING;
161173
}
162174

163175
private String getContextPath() {
@@ -169,4 +181,5 @@ private VaadinServletContext getServletContext() {
169181
return (VaadinServletContext) getApplicationConfiguration()
170182
.getContext();
171183
}
184+
172185
}

‎vaadin-dev-server/src/main/java/com/vaadin/base/devserver/startup/DevModeInitializer.java‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@
7070
import com.vaadin.base.devserver.stats.DevModeUsageStatistics;
7171
import com.vaadin.base.devserver.stats.StatisticsSender;
7272
import com.vaadin.base.devserver.stats.StatisticsStorage;
73+
import com.vaadin.base.devserver.viteproxy.ViteWebsocketEndpoint;
7374
import com.vaadin.experimental.FeatureFlags;
7475
import com.vaadin.flow.di.Lookup;
7576
import com.vaadin.flow.internal.DevModeHandler;
@@ -365,8 +366,11 @@ public static DevModeHandler initDevModeHandler(Set<Class<?>> classes,
365366
nodeTasksFuture.join();
366367
return null;
367368
} else {
368-
return new ViteHandler(devServerLookup, port,
369+
ViteHandler handler = new ViteHandler(devServerLookup, port,
369370
options.getNpmFolder(), nodeTasksFuture);
371+
VaadinServlet.whenFrontendMappingAvailable(
372+
() -> ViteWebsocketEndpoint.init(context, handler));
373+
return handler;
370374
}
371375
}
372376

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
/*
2+
* Copyright 2000-2022 Vaadin Ltd.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
5+
* use this file except in compliance with the License. You may obtain a copy of
6+
* the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations under
14+
* the License.
15+
*/
16+
package com.vaadin.base.devserver.viteproxy;
17+
18+
import java.net.URI;
19+
import java.net.http.HttpClient;
20+
import java.net.http.WebSocket;
21+
import java.net.http.WebSocket.Listener;
22+
import java.util.concurrent.CompletableFuture;
23+
import java.util.concurrent.CompletionStage;
24+
import java.util.concurrent.ExecutionException;
25+
import java.util.function.Consumer;
26+
27+
import org.slf4j.Logger;
28+
import org.slf4j.LoggerFactory;
29+
30+
import com.vaadin.base.devserver.ViteHandler;
31+
32+
import jakarta.websocket.CloseReason.CloseCodes;
33+
34+
/**
35+
* Communicates with a Vite server through a websocket connection.
36+
*/
37+
public class ViteWebsocketConnection implements Listener {
38+
39+
private final Consumer<String> onMessage;
40+
private final WebSocket clientWebSocket;
41+
private final Runnable onClose;
42+
43+
private Logger getLogger() {
44+
return LoggerFactory.getLogger(getClass());
45+
}
46+
47+
/**
48+
* Established a connection with a Vite server running on the given port,
49+
* using the given sub protocol.
50+
*
51+
* @param port
52+
* the port Vite is running on
53+
* @param subProtocol
54+
* the sub protocol to use
55+
* @param onMessage
56+
* a callback to invoke when a message arrives.
57+
* @param onClose
58+
* a callback to invoke if the connection to Vite is closed
59+
*
60+
* @throws InterruptedException
61+
* if there is a problem with the connection
62+
* @throws ExecutionException
63+
* if there is a problem with the connection
64+
*/
65+
public ViteWebsocketConnection(int port, String subProtocol,
66+
Consumer<String> onMessage, Runnable onClose)
67+
throws InterruptedException, ExecutionException {
68+
this.onMessage = onMessage;
69+
this.onClose = onClose;
70+
String wsHost = ViteHandler.DEV_SERVER_HOST.replace("http://", "ws://");
71+
URI uri = URI.create(wsHost + ":" + port + "/VAADIN/");
72+
clientWebSocket = HttpClient.newHttpClient().newWebSocketBuilder()
73+
.subprotocols(subProtocol).buildAsync(uri, this).get();
74+
getLogger().debug("Connecting to {} using the {} protocol", uri,
75+
clientWebSocket.getSubprotocol());
76+
}
77+
78+
@Override
79+
public void onOpen(WebSocket webSocket) {
80+
getLogger().debug("Connected using the {} protocol",
81+
webSocket.getSubprotocol());
82+
83+
Listener.super.onOpen(webSocket);
84+
}
85+
86+
@Override
87+
public CompletionStage<?> onClose(WebSocket webSocket, int statusCode,
88+
String reason) {
89+
onClose.run();
90+
return Listener.super.onClose(webSocket, statusCode, reason);
91+
}
92+
93+
@Override
94+
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data,
95+
boolean last) {
96+
// Message from Vite
97+
String msg = data.toString();
98+
getLogger().debug("Message from Vite: {}", msg);
99+
onMessage.accept(msg);
100+
return Listener.super.onText(webSocket, data, last);
101+
}
102+
103+
/**
104+
* Sends the given message to the Vite server.
105+
*
106+
* @param message
107+
* the message to send
108+
* @throws InterruptedException
109+
* if there is a problem with the connection
110+
* @throws ExecutionException
111+
* if there is a problem with the connection
112+
*/
113+
public void send(String message)
114+
throws InterruptedException, ExecutionException {
115+
CompletableFuture<WebSocket> send = clientWebSocket.sendText(message,
116+
false);
117+
send.get();
118+
}
119+
120+
/**
121+
* Closes the connection.
122+
*
123+
* @throws ExecutionException
124+
* if there is a problem with the connection
125+
* @throws InterruptedException
126+
* if there is a problem with the connection
127+
*/
128+
public void close() throws InterruptedException, ExecutionException {
129+
getLogger().debug("Closing the connection");
130+
CompletableFuture<WebSocket> closeRequest = clientWebSocket
131+
.sendClose(CloseCodes.NORMAL_CLOSURE.getCode(), "");
132+
closeRequest.get();
133+
}
134+
}

0 commit comments

Comments
 (0)