Skip to content

Commit a7e41f6

Browse files
authored
fix: clear preseved chain cache for inactive UI (#19360)
Prevents potential memory leaks caused by UIs being retained by the preserve on refresh cache when the browser page is closed.
1 parent 2f9bfc6 commit a7e41f6

9 files changed

Lines changed: 586 additions & 34 deletions

File tree

‎flow-server/src/main/java/com/vaadin/flow/router/internal/AbstractNavigationStateRenderer.java‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,14 @@
2323
import java.util.HashMap;
2424
import java.util.HashSet;
2525
import java.util.List;
26+
import java.util.Map;
2627
import java.util.Objects;
2728
import java.util.Optional;
2829
import java.util.Set;
2930
import java.util.function.Supplier;
31+
import java.util.stream.Collectors;
32+
33+
import org.slf4j.LoggerFactory;
3034

3135
import com.vaadin.flow.component.Component;
3236
import com.vaadin.flow.component.HasElement;
@@ -36,6 +40,7 @@
3640
import com.vaadin.flow.dom.Element;
3741
import com.vaadin.flow.function.DeploymentConfiguration;
3842
import com.vaadin.flow.internal.Pair;
43+
import com.vaadin.flow.internal.StateNode;
3944
import com.vaadin.flow.router.AfterNavigationEvent;
4045
import com.vaadin.flow.router.BeforeEnterEvent;
4146
import com.vaadin.flow.router.BeforeEnterObserver;
@@ -986,6 +991,45 @@ private static void clearAllPreservedChains(UI ui) {
986991
}
987992
}
988993

994+
/**
995+
* Removes preserved component cache for an inactive UI.
996+
*
997+
* @param inactiveUI
998+
* the inactive UI
999+
* @throws IllegalStateException
1000+
* if the UI is not in closing state
1001+
*/
1002+
public static void purgeInactiveUIPreservedChainCache(UI inactiveUI) {
1003+
if (!inactiveUI.isClosing()) {
1004+
throw new IllegalStateException(
1005+
"Cannot purge preserved chain cache for an active UI");
1006+
}
1007+
final VaadinSession session = inactiveUI.getSession();
1008+
final PreservedComponentCache cache = session
1009+
.getAttribute(PreservedComponentCache.class);
1010+
if (cache != null && !cache.isEmpty()) {
1011+
StateNode uiNode = inactiveUI.getElement().getNode();
1012+
Set<String> inactiveWindows = cache.entrySet().stream()
1013+
.filter(e -> {
1014+
ArrayList<HasElement> chain = e.getValue().getSecond();
1015+
// chain is never empty
1016+
StateNode chainNode = chain.get(0).getElement()
1017+
.getNode();
1018+
while (chainNode.getParent() != null) {
1019+
chainNode = chainNode.getParent();
1020+
}
1021+
return uiNode == chainNode;
1022+
}).map(Map.Entry::getKey).collect(Collectors.toSet());
1023+
if (!inactiveWindows.isEmpty()) {
1024+
LoggerFactory.getLogger(AbstractNavigationStateRenderer.class)
1025+
.debug("Removing preserved chain cache for inactive UI {} on VaadinSession {} (windows: {})",
1026+
inactiveUI.getUIId(),
1027+
session.getSession().getId(), inactiveWindows);
1028+
}
1029+
inactiveWindows.forEach(cache::remove);
1030+
}
1031+
}
1032+
9891033
private static void warnAboutPreserveOnRefreshAndLiveReloadCombo(UI ui) {
9901034
// Show a warning that live-reload may work counter-intuitively
9911035
DeploymentConfiguration configuration = ui.getSession()

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

Lines changed: 40 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,41 @@
1616

1717
package com.vaadin.flow.server;
1818

19+
import java.io.BufferedWriter;
20+
import java.io.IOException;
21+
import java.io.InputStream;
22+
import java.io.OutputStream;
23+
import java.io.OutputStreamWriter;
24+
import java.io.PrintWriter;
25+
import java.io.Serializable;
26+
import java.lang.reflect.Constructor;
27+
import java.net.URL;
28+
import java.nio.charset.StandardCharsets;
29+
import java.security.MessageDigest;
30+
import java.util.ArrayList;
31+
import java.util.Collection;
32+
import java.util.Collections;
33+
import java.util.HashMap;
34+
import java.util.List;
35+
import java.util.Locale;
36+
import java.util.Map;
37+
import java.util.Map.Entry;
38+
import java.util.Optional;
39+
import java.util.ServiceLoader;
40+
import java.util.Set;
41+
import java.util.concurrent.CancellationException;
42+
import java.util.concurrent.ConcurrentHashMap;
43+
import java.util.concurrent.CopyOnWriteArrayList;
44+
import java.util.concurrent.Future;
45+
import java.util.concurrent.TimeUnit;
46+
import java.util.concurrent.locks.Lock;
47+
import java.util.concurrent.locks.ReentrantLock;
48+
import java.util.stream.Collectors;
49+
import java.util.stream.StreamSupport;
50+
51+
import org.slf4j.Logger;
52+
import org.slf4j.LoggerFactory;
53+
1954
import com.vaadin.flow.component.UI;
2055
import com.vaadin.flow.di.DefaultInstantiator;
2156
import com.vaadin.flow.di.Instantiator;
@@ -29,6 +64,7 @@
2964
import com.vaadin.flow.internal.UsageStatistics;
3065
import com.vaadin.flow.router.RouteData;
3166
import com.vaadin.flow.router.Router;
67+
import com.vaadin.flow.router.internal.AbstractNavigationStateRenderer;
3268
import com.vaadin.flow.server.HandlerHelper.RequestType;
3369
import com.vaadin.flow.server.communication.AtmospherePushConnection;
3470
import com.vaadin.flow.server.communication.HeartbeatHandler;
@@ -45,44 +81,11 @@
4581
import com.vaadin.flow.shared.JsonConstants;
4682
import com.vaadin.flow.shared.Registration;
4783
import com.vaadin.flow.shared.communication.PushMode;
84+
4885
import elemental.json.Json;
4986
import elemental.json.JsonException;
5087
import elemental.json.JsonObject;
5188
import elemental.json.impl.JsonUtil;
52-
import org.slf4j.Logger;
53-
import org.slf4j.LoggerFactory;
54-
55-
import java.io.BufferedWriter;
56-
import java.io.IOException;
57-
import java.io.InputStream;
58-
import java.io.OutputStream;
59-
import java.io.OutputStreamWriter;
60-
import java.io.PrintWriter;
61-
import java.io.Serializable;
62-
import java.lang.reflect.Constructor;
63-
import java.net.URL;
64-
import java.nio.charset.StandardCharsets;
65-
import java.security.MessageDigest;
66-
import java.util.ArrayList;
67-
import java.util.Collection;
68-
import java.util.Collections;
69-
import java.util.HashMap;
70-
import java.util.List;
71-
import java.util.Locale;
72-
import java.util.Map;
73-
import java.util.Map.Entry;
74-
import java.util.Optional;
75-
import java.util.ServiceLoader;
76-
import java.util.Set;
77-
import java.util.concurrent.CancellationException;
78-
import java.util.concurrent.ConcurrentHashMap;
79-
import java.util.concurrent.CopyOnWriteArrayList;
80-
import java.util.concurrent.Future;
81-
import java.util.concurrent.TimeUnit;
82-
import java.util.concurrent.locks.Lock;
83-
import java.util.concurrent.locks.ReentrantLock;
84-
import java.util.stream.Collectors;
85-
import java.util.stream.StreamSupport;
8689

8790
import static java.nio.charset.StandardCharsets.UTF_8;
8891

@@ -1345,9 +1348,12 @@ private void closeInactiveUIs(VaadinSession session) {
13451348
getLogger().debug("Closing inactive UI #{} in session {}",
13461349
ui.getUIId(), sessionId);
13471350
ui.close();
1351+
AbstractNavigationStateRenderer
1352+
.purgeInactiveUIPreservedChainCache(ui);
13481353
});
13491354
}
13501355
}
1356+
13511357
}
13521358

13531359
/**

‎flow-server/src/test/java/com/vaadin/flow/router/internal/NavigationStateRendererTest.java‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import java.util.Arrays;
2121
import java.util.Collections;
2222
import java.util.List;
23+
import java.util.Optional;
2324
import java.util.Set;
2425
import java.util.concurrent.atomic.AtomicBoolean;
2526
import java.util.concurrent.atomic.AtomicInteger;
@@ -71,6 +72,7 @@
7172
import com.vaadin.flow.server.MockVaadinSession;
7273
import com.vaadin.flow.server.RouteRegistry;
7374
import com.vaadin.flow.server.ServiceException;
75+
import com.vaadin.flow.server.WrappedSession;
7476
import com.vaadin.flow.server.startup.ApplicationRouteRegistry;
7577
import com.vaadin.tests.util.AlwaysLockedVaadinSession;
7678
import com.vaadin.tests.util.MockDeploymentConfiguration;
@@ -727,4 +729,66 @@ public Page getPage() {
727729
"No pushState invocation is expected when navigating to the current location.",
728730
pushStateCalled.get());
729731
}
732+
733+
@Test
734+
public void purgeInactiveUIPreservedChainCache_activeUI_throws() {
735+
MockVaadinServletService service = createMockServiceWithInstantiator();
736+
MockVaadinSession session = new AlwaysLockedVaadinSession(service);
737+
738+
MockUI activeUI = new MockUI(session);
739+
Component attachedToActiveUI = new PreservedView();
740+
activeUI.add(attachedToActiveUI);
741+
742+
Assert.assertThrows(IllegalStateException.class,
743+
() -> AbstractNavigationStateRenderer
744+
.purgeInactiveUIPreservedChainCache(activeUI));
745+
746+
}
747+
748+
@Test
749+
public void purgeInactiveUIPreservedChainCache_inactiveUI_clearsCache() {
750+
MockVaadinServletService service = createMockServiceWithInstantiator();
751+
WrappedSession wrappedSession = Mockito.mock(WrappedSession.class);
752+
Mockito.when(wrappedSession.getId()).thenReturn("A-SESSION-ID");
753+
MockVaadinSession session = new AlwaysLockedVaadinSession(service) {
754+
@Override
755+
public WrappedSession getSession() {
756+
return wrappedSession;
757+
}
758+
};
759+
760+
MockUI activeUI = new MockUI(session);
761+
Component attachedToActiveUI = new PreservedView();
762+
activeUI.add(attachedToActiveUI);
763+
764+
MockUI inActiveUI = new MockUI(session);
765+
Component attachedToInactiveUI = new PreservedView();
766+
inActiveUI.add(attachedToInactiveUI);
767+
inActiveUI.close();
768+
769+
// Simulate two tabs on the same view, but one has been closed
770+
Location location = new Location("preserved");
771+
AbstractNavigationStateRenderer.setPreservedChain(session, "ACTIVE",
772+
location,
773+
new ArrayList<>(Collections.singletonList(attachedToActiveUI)));
774+
AbstractNavigationStateRenderer.setPreservedChain(session, "INACTIVE",
775+
location, new ArrayList<>(
776+
Collections.singletonList(attachedToInactiveUI)));
777+
778+
AbstractNavigationStateRenderer
779+
.purgeInactiveUIPreservedChainCache(inActiveUI);
780+
781+
Optional<ArrayList<HasElement>> active = AbstractNavigationStateRenderer
782+
.getPreservedChain(session, "ACTIVE", location);
783+
Assert.assertTrue(
784+
"Expected preserved chain for active window to be present",
785+
active.isPresent());
786+
787+
Optional<ArrayList<HasElement>> inactive = AbstractNavigationStateRenderer
788+
.getPreservedChain(session, "INACTIVE", location);
789+
Assert.assertFalse(
790+
"Expected preserved chain for inactive window to be removed",
791+
inactive.isPresent());
792+
793+
}
730794
}
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/*
2+
* Copyright 2000-2024 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+
17+
package com.vaadin.flow.misc.ui;
18+
19+
import com.vaadin.flow.component.ComponentUtil;
20+
import com.vaadin.flow.component.UI;
21+
import com.vaadin.flow.component.html.Div;
22+
import com.vaadin.flow.component.html.H1;
23+
import com.vaadin.flow.component.html.NativeButton;
24+
import com.vaadin.flow.router.Route;
25+
26+
@Route("active-uis")
27+
public class ActiveUIsView extends Div {
28+
29+
public ActiveUIsView() {
30+
Div uis = new Div();
31+
uis.setId("uis");
32+
NativeButton listUIsButton = new NativeButton("List active UIs",
33+
event -> {
34+
UI current = UI.getCurrent();
35+
listUIs(current, uis);
36+
});
37+
listUIsButton.setId("list-uis");
38+
39+
Div gcCollectedUIs = new Div();
40+
gcCollectedUIs.setId("gcuis");
41+
NativeButton listGCCollectedUIsButton = new NativeButton(
42+
"List GC collected UIs", event -> {
43+
listGCCollectedUIs(gcCollectedUIs);
44+
});
45+
listGCCollectedUIsButton.setId("list-gc-collected-uis");
46+
NativeButton gcHintButton = new NativeButton("Run GC",
47+
event -> System.gc());
48+
gcHintButton.setId("gc-hint");
49+
50+
add(listUIsButton, new H1("Active UIs (excluding current)"), uis,
51+
listGCCollectedUIsButton, gcHintButton,
52+
new H1("GC collected UIs"), gcCollectedUIs);
53+
}
54+
55+
private void listGCCollectedUIs(Div gcCollectedUIs) {
56+
gcCollectedUIs.removeAll();
57+
UI ui = UI.getCurrent();
58+
ComponentUtil.getData(ui, UITrackerListener.UITracker.class)
59+
.getCollectedUIs(ui.getSession()).forEach(uiId -> gcCollectedUIs
60+
.add(new Div("GC Collected UI: " + uiId)));
61+
}
62+
63+
private void listUIs(UI currentUI, Div uis) {
64+
uis.removeAll();
65+
currentUI.getSession().getUIs().stream().filter(ui -> ui != currentUI)
66+
.map(ui -> new Div("UI: " + ui.getUIId() + ", Path: "
67+
+ ui.getActiveViewLocation().getPath()))
68+
.forEach(uis::add);
69+
}
70+
71+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/*
2+
* Copyright 2000-2024 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+
17+
package com.vaadin.flow.misc.ui;
18+
19+
import jakarta.servlet.annotation.WebInitParam;
20+
import jakarta.servlet.annotation.WebServlet;
21+
22+
import com.vaadin.flow.server.VaadinServlet;
23+
24+
@WebServlet(urlPatterns = "/*", asyncSupported = true, initParams = {
25+
@WebInitParam(name = "heartbeatInterval", value = "5") })
26+
public class CustomServlet extends VaadinServlet {
27+
public static long HEARTBEAT_INTERVAL = 5;
28+
}

0 commit comments

Comments
 (0)