Skip to content

Commit 63291fb

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

10 files changed

Lines changed: 595 additions & 0 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;
@@ -993,6 +998,45 @@ private static void clearAllPreservedChains(UI ui) {
993998
}
994999
}
9951000

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

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@
6363
import com.vaadin.flow.internal.UsageStatistics;
6464
import com.vaadin.flow.router.RouteData;
6565
import com.vaadin.flow.router.Router;
66+
import com.vaadin.flow.router.internal.AbstractNavigationStateRenderer;
6667
import com.vaadin.flow.server.HandlerHelper.RequestType;
6768
import com.vaadin.flow.server.communication.AtmospherePushConnection;
6869
import com.vaadin.flow.server.communication.HeartbeatHandler;
@@ -1347,6 +1348,8 @@ private void closeInactiveUIs(VaadinSession session) {
13471348
getLogger().debug("Closing inactive UI #{} in session {}",
13481349
ui.getUIId(), sessionId);
13491350
ui.close();
1351+
AbstractNavigationStateRenderer
1352+
.purgeInactiveUIPreservedChainCache(ui);
13501353
});
13511354
}
13521355
}

‎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;
@@ -67,6 +68,7 @@
6768
import com.vaadin.flow.server.MockVaadinSession;
6869
import com.vaadin.flow.server.RouteRegistry;
6970
import com.vaadin.flow.server.ServiceException;
71+
import com.vaadin.flow.server.WrappedSession;
7072
import com.vaadin.flow.server.startup.ApplicationRouteRegistry;
7173
import com.vaadin.tests.util.AlwaysLockedVaadinSession;
7274
import com.vaadin.tests.util.MockDeploymentConfiguration;
@@ -743,4 +745,66 @@ public Page getPage() {
743745
"No pushState invocation is expected when navigating to the current location.",
744746
pushStateCalled.get());
745747
}
748+
749+
@Test
750+
public void purgeInactiveUIPreservedChainCache_activeUI_throws() {
751+
MockVaadinServletService service = createMockServiceWithInstantiator();
752+
MockVaadinSession session = new AlwaysLockedVaadinSession(service);
753+
754+
MockUI activeUI = new MockUI(session);
755+
Component attachedToActiveUI = new PreservedView();
756+
activeUI.add(attachedToActiveUI);
757+
758+
Assert.assertThrows(IllegalStateException.class,
759+
() -> AbstractNavigationStateRenderer
760+
.purgeInactiveUIPreservedChainCache(activeUI));
761+
762+
}
763+
764+
@Test
765+
public void purgeInactiveUIPreservedChainCache_inactiveUI_clearsCache() {
766+
MockVaadinServletService service = createMockServiceWithInstantiator();
767+
WrappedSession wrappedSession = Mockito.mock(WrappedSession.class);
768+
Mockito.when(wrappedSession.getId()).thenReturn("A-SESSION-ID");
769+
MockVaadinSession session = new AlwaysLockedVaadinSession(service) {
770+
@Override
771+
public WrappedSession getSession() {
772+
return wrappedSession;
773+
}
774+
};
775+
776+
MockUI activeUI = new MockUI(session);
777+
Component attachedToActiveUI = new PreservedView();
778+
activeUI.add(attachedToActiveUI);
779+
780+
MockUI inActiveUI = new MockUI(session);
781+
Component attachedToInactiveUI = new PreservedView();
782+
inActiveUI.add(attachedToInactiveUI);
783+
inActiveUI.close();
784+
785+
// Simulate two tabs on the same view, but one has been closed
786+
Location location = new Location("preserved");
787+
AbstractNavigationStateRenderer.setPreservedChain(session, "ACTIVE",
788+
location,
789+
new ArrayList<>(Collections.singletonList(attachedToActiveUI)));
790+
AbstractNavigationStateRenderer.setPreservedChain(session, "INACTIVE",
791+
location, new ArrayList<>(
792+
Collections.singletonList(attachedToInactiveUI)));
793+
794+
AbstractNavigationStateRenderer
795+
.purgeInactiveUIPreservedChainCache(inActiveUI);
796+
797+
Optional<ArrayList<HasElement>> active = AbstractNavigationStateRenderer
798+
.getPreservedChain(session, "ACTIVE", location);
799+
Assert.assertTrue(
800+
"Expected preserved chain for active window to be present",
801+
active.isPresent());
802+
803+
Optional<ArrayList<HasElement>> inactive = AbstractNavigationStateRenderer
804+
.getPreservedChain(session, "INACTIVE", location);
805+
Assert.assertFalse(
806+
"Expected preserved chain for inactive window to be removed",
807+
inactive.isPresent());
808+
809+
}
746810
}

‎flow-tests/test-misc/pom.xml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,12 @@
1717
<artifactId>flow-test-resources</artifactId>
1818
<version>${project.version}</version>
1919
</dependency>
20+
<dependency>
21+
<groupId>com.vaadin</groupId>
22+
<artifactId>flow-html-components-testbench</artifactId>
23+
<version>${project.version}</version>
24+
<scope>test</scope>
25+
</dependency>
2026
</dependencies>
2127

2228
<build>
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
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 -> {
60+
Div div = new Div();
61+
div.setText("GC Collected UI: " + uiId);
62+
gcCollectedUIs.add(div);
63+
});
64+
}
65+
66+
private void listUIs(UI currentUI, Div uis) {
67+
uis.removeAll();
68+
currentUI.getSession().getUIs().stream().filter(ui -> ui != currentUI)
69+
.map(ui -> {
70+
Div div = new Div();
71+
div.setText("UI: " + ui.getUIId() + ", Path: " + ui
72+
.getInternals().getActiveViewLocation().getPath());
73+
return div;
74+
}).forEach(uis::add);
75+
}
76+
77+
}
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 javax.servlet.annotation.WebInitParam;
20+
import javax.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+
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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.UI;
20+
import com.vaadin.flow.component.html.Div;
21+
import com.vaadin.flow.component.html.H1;
22+
import com.vaadin.flow.component.html.H3;
23+
import com.vaadin.flow.component.html.NativeButton;
24+
import com.vaadin.flow.router.AfterNavigationEvent;
25+
import com.vaadin.flow.router.AfterNavigationObserver;
26+
import com.vaadin.flow.router.PreserveOnRefresh;
27+
import com.vaadin.flow.router.Route;
28+
29+
@PreserveOnRefresh
30+
@Route("preserve")
31+
public class PreserveOnRefreshView extends Div
32+
implements AfterNavigationObserver {
33+
34+
private final Div uiId;
35+
36+
public PreserveOnRefreshView() {
37+
38+
uiId = new Div();
39+
uiId.setId("uiId");
40+
NativeButton reloadButton = new NativeButton("Reload page",
41+
ev -> UI.getCurrent().getPage().reload());
42+
reloadButton.setId("reload");
43+
add(new H1("This view is preserved on refresh"));
44+
add(new H3("Initial UI: " + UI.getCurrent().getUIId()));
45+
add(uiId, reloadButton);
46+
}
47+
48+
@Override
49+
public void afterNavigation(AfterNavigationEvent event) {
50+
uiId.setText("UI: " + UI.getCurrent().getUIId());
51+
}
52+
}

0 commit comments

Comments
 (0)