Skip to content

Commit

Permalink
fix: support serialization of Vaadin scoped beans (#20394) (#20430)
Browse files Browse the repository at this point in the history
Makes sure that VaadinSession and UI thread locals are available during
both serialization and deserialization, to allow other libraries to
perform inspection and injection of Vaadin scoped beans.

Also refactors VaadinRouteScope to be independent from VaadinService
when fetching RouteScopeOwner annotation for the bean, and replaces
VaadinSession.unlock() calls with direct access to the lock instance
to prevent unwanted push during bean lookup.

Fixes #19967
Part of vaadin/kubernetes-kit#140

Co-authored-by: Mikhail Shabarov <[email protected]>
  • Loading branch information
mcollovati and mshabarov authored Nov 12, 2024
1 parent ce7a71b commit 9ae1e5f
Show file tree
Hide file tree
Showing 10 changed files with 320 additions and 73 deletions.
40 changes: 40 additions & 0 deletions flow-server/src/main/java/com/vaadin/flow/component/Component.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,15 @@
*/
package com.vaadin.flow.component;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serial;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;
import java.util.stream.Stream.Builder;
Expand All @@ -32,6 +37,7 @@
import com.vaadin.flow.dom.ShadowRoot;
import com.vaadin.flow.i18n.I18NProvider;
import com.vaadin.flow.internal.AnnotationReader;
import com.vaadin.flow.internal.CurrentInstance;
import com.vaadin.flow.internal.LocaleUtil;
import com.vaadin.flow.internal.nodefeature.ElementData;
import com.vaadin.flow.server.Attributes;
Expand Down Expand Up @@ -820,4 +826,38 @@ public void removeFromParent() {
getElement().removeFromParent();
}

@Serial
private void writeObject(ObjectOutputStream out) throws IOException {
if (this instanceof UI ui) {
Map<Class<?>, CurrentInstance> instances = CurrentInstance
.setCurrent(ui);
try {
out.defaultWriteObject();
} finally {
CurrentInstance.restoreInstances(instances);
}
} else {
out.defaultWriteObject();
}
}

@Serial
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
if (this instanceof UI ui) {
Map<Class<?>, CurrentInstance> instances = CurrentInstance
.getInstances();
// Cannot use CurrentInstance.setCurrent(this) because it will try
// to get VaadinSession from UI.internals that is not yet available
CurrentInstance.set(UI.class, ui);
try {
in.defaultReadObject();
} finally {
CurrentInstance.restoreInstances(instances);
}
} else {
in.defaultReadObject();
}
}

}
60 changes: 37 additions & 23 deletions flow-server/src/main/java/com/vaadin/flow/server/VaadinSession.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@

package com.vaadin.flow.server;

import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.HttpSessionBindingEvent;
import jakarta.servlet.http.HttpSessionBindingListener;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
Expand Down Expand Up @@ -52,10 +56,6 @@
import com.vaadin.flow.shared.Registration;
import com.vaadin.flow.shared.communication.PushMode;

import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.HttpSessionBindingEvent;
import jakarta.servlet.http.HttpSessionBindingListener;

/**
* Contains everything that Vaadin needs to store for a specific user. This is
* typically stored in a {@link HttpSession}, but others storage mechanisms
Expand Down Expand Up @@ -1098,6 +1098,14 @@ private void readObject(ObjectInputStream stream)
Map<Class<?>, CurrentInstance> old = CurrentInstance.setCurrent(this);
try {
stream.defaultReadObject();
// Add-ons may have Listener classes that nullify themselves during
// serialization (e.g. Collaboration Kit) and restore instances in
// some custom way later on.
// Removing null elements prevents application to fail if restore
// actions are not applied eagerly
requestHandlers.remove(null);
destroyListeners.remove(null);

uIs = (Map<Integer, UI>) stream.readObject();
resourceRegistry = (StreamResourceRegistry) stream.readObject();
pendingAccessQueue = new ConcurrentLinkedQueue<>();
Expand All @@ -1108,27 +1116,33 @@ private void readObject(ObjectInputStream stream)

private void writeObject(java.io.ObjectOutputStream stream)
throws IOException {
boolean serializeUIs = true;

// If service is null it has just been deserialized and should be
// serialized in
// the same way again
if (getService() != null) {
ApplicationConfiguration appConfiguration = ApplicationConfiguration
.get(getService().getContext());
if (!appConfiguration.isProductionMode() && !appConfiguration
.isDevModeSessionSerializationEnabled()) {
serializeUIs = false;
Map<Class<?>, CurrentInstance> instanceMap = CurrentInstance
.setCurrent(this);
try {
boolean serializeUIs = true;

// If service is null it has just been deserialized and should be
// serialized in
// the same way again
if (getService() != null) {
ApplicationConfiguration appConfiguration = ApplicationConfiguration
.get(getService().getContext());
if (!appConfiguration.isProductionMode() && !appConfiguration
.isDevModeSessionSerializationEnabled()) {
serializeUIs = false;
}
}
}

stream.defaultWriteObject();
if (serializeUIs) {
stream.writeObject(uIs);
stream.writeObject(resourceRegistry);
} else {
stream.writeObject(new HashMap<>());
stream.writeObject(new StreamResourceRegistry(this));
stream.defaultWriteObject();
if (serializeUIs) {
stream.writeObject(uIs);
stream.writeObject(resourceRegistry);
} else {
stream.writeObject(new HashMap<>());
stream.writeObject(new StreamResourceRegistry(this));
}
} finally {
CurrentInstance.restoreInstances(instanceMap);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,29 @@
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serial;
import java.io.Serializable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.Tag;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.function.DeploymentConfiguration;
import com.vaadin.flow.server.RequestHandler;
import com.vaadin.flow.server.StreamRegistration;
import com.vaadin.flow.server.StreamResource;
import com.vaadin.flow.server.VaadinContext;
import com.vaadin.flow.server.VaadinRequest;
import com.vaadin.flow.server.VaadinResponse;
import com.vaadin.flow.server.VaadinService;
import com.vaadin.flow.server.VaadinServletService;
import com.vaadin.flow.server.VaadinSession;
Expand All @@ -29,6 +39,30 @@

public class SerializationTest {

Runnable cleaner;

@Before
public void enabledSerializationDebugInfo() {
String extendedDebugInfo = System
.getProperty("sun.io.serialization.extendedDebugInfo");
System.setProperty("sun.io.serialization.extendedDebugInfo", "true");
cleaner = () -> {
if (extendedDebugInfo != null) {
System.setProperty("sun.io.serialization.extendedDebugInfo",
extendedDebugInfo);
} else {
System.clearProperty("sun.io.serialization.extendedDebugInfo");
}
};
}

@After
public void restore() {
if (cleaner != null) {
cleaner.run();
}
}

@Test
public void testSerializeVaadinSession_accessQueueIsRecreated()
throws Exception {
Expand Down Expand Up @@ -123,8 +157,119 @@ public void testSerializeVaadinSession_notProductionMode_canSerializeWithoutTran
Assert.assertNull(againSerializedAndDeserializedSession.getService());
}

@Test
// Covers serialization of UI scoped beans, e.g. in Kubernetes Kit
// https://github.com/vaadin/flow/issues/19967
// https://github.com/vaadin/kubernetes-kit/issues/140
public void serializeUI_currentUI_availableDuringSerialization()
throws Exception {
VaadinSession deserializeSession = serializeAndDeserializeWithUI(true,
true, ui -> ui.add(new MyComponent()));
MyComponent deserializedComponent = deserializeSession.getUIs()
.iterator().next().getChildren()
.filter(MyComponent.class::isInstance)
.map(MyComponent.class::cast).findFirst()
.orElseThrow(() -> new AssertionError(
"Custom component has not been deserialized"));

deserializedComponent.checker.assertInstancesAvailable();
}

@Test
// Covers serialization of UI scoped beans, e.g. in Kubernetes Kit
// https://github.com/vaadin/flow/issues/19967
// https://github.com/vaadin/kubernetes-kit/issues/140
public void serializeUI_currentVaadinSession_availableDuringSerialization()
throws Exception {
VaadinSession deserializeSession = serializeAndDeserializeWithUI(true,
true,
ui -> ui.getSession().addRequestHandler(new MyListener()));

MyListener deserializedListener = deserializeSession
.getRequestHandlers().stream()
.filter(MyListener.class::isInstance)
.map(MyListener.class::cast).findFirst()
.orElseThrow(() -> new AssertionError(
"Session request listener has not been deserialized"));

deserializedListener.checker.assertSessionAvailable();
}

private static class SerializationInstancesChecker implements Serializable {
private boolean uiAvailableOnRead = false;
private boolean sessionAvailableOnRead = false;
private boolean uiAvailableOnWrite = false;
private boolean sessionAvailableOnWrite = false;

@Serial
private void writeObject(ObjectOutputStream out) throws IOException {
uiAvailableOnWrite = UI.getCurrent() != null;
sessionAvailableOnWrite = VaadinSession.getCurrent() != null;
out.defaultWriteObject();
}

@Serial
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject();
uiAvailableOnRead = UI.getCurrent() != null;
sessionAvailableOnRead = VaadinSession.getCurrent() != null;
}

void assertInstancesAvailable() {
assertUIAvailable();
assertSessionAvailable();
}

void assertUIAvailable() {
Assert.assertTrue(
"Expecting serialization hook to be called with UI thread local set",
uiAvailableOnWrite);
Assert.assertTrue(
"Expecting deserialization hook to be called with UI thread local set",
uiAvailableOnRead);
}

void assertSessionAvailable() {
Assert.assertTrue(
"Expecting serialization hook to be called with VaadinSession thread local set",
sessionAvailableOnWrite);
Assert.assertTrue(
"Expecting deserialization hook to be called with VaadinSession thread local set",
sessionAvailableOnRead);
}

}

@Tag("my-component")
private static class MyComponent extends Component {

private final SerializationInstancesChecker checker = new SerializationInstancesChecker();

}

private static class MyListener implements RequestHandler {

private final SerializationInstancesChecker checker = new SerializationInstancesChecker();

@Override
public boolean handleRequest(VaadinSession session,
VaadinRequest request, VaadinResponse response)
throws IOException {
return false;
}
}

private static VaadinSession serializeAndDeserializeWithUI(
boolean serializeUI) throws Exception {
return serializeAndDeserializeWithUI(serializeUI, false, ui -> {
});
}

private static VaadinSession serializeAndDeserializeWithUI(
boolean serializeUI) throws IOException, ClassNotFoundException {
boolean serializeUI, boolean background, Consumer<UI> uiConsumer)
throws Exception {

VaadinService vaadinService = new MockVaadinService(false, serializeUI);
VaadinSession session = new VaadinSession(vaadinService);
// This is done only for test purpose to init the session lock,
Expand All @@ -136,13 +281,25 @@ private static VaadinSession serializeAndDeserializeWithUI(
MockUI ui = new MockUI(session);
ui.doInit(null, 42);
session.addUI(ui);

session = serializeAndDeserialize(session);
uiConsumer.accept(ui);

VaadinSession deserializedSession;
if (background) {
deserializedSession = CompletableFuture.supplyAsync(() -> {
try {
return serializeAndDeserialize(session);
} catch (Exception e) {
throw new RuntimeException(e);
}
}).get();
} else {
deserializedSession = serializeAndDeserialize(session);
}
// This is done only for test purpose to refresh the session lock,
// should be called by Flow internally as soon as the session has
// been retrieved from http session.
session.refreshTransients(null, vaadinService);
return session;
deserializedSession.refreshTransients(null, vaadinService);
return deserializedSession;
}

private static <S extends Serializable> S serializeAndDeserialize(S s)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,11 +149,11 @@ private <T> T execute(Supplier<T> supplier) {
if (session.hasLock()) {
return supplier.get();
} else {
session.lock();
session.getLockInstance().lock();
try {
return supplier.get();
} finally {
session.unlock();
session.getLockInstance().unlock();
}
}
}
Expand Down
Loading

0 comments on commit 9ae1e5f

Please sign in to comment.