Skip to content

Commit 77f6280

Browse files
fix: prevent concurrent disconnect and push operations (#15767) (#15821)
* fix: prevent concurrent disconnect and push operations Disconnecting an AtmospherePushConnection while it is sending a message may result in a NullPointerException if AtmosphereResource is nullified before the message is sent. This change synchronizes operations, so that disconnect will wait until current push finishes, or push waits for disconnect to complete so that the isConnected() method reflects correctly current state. Fixes #15571 * fixed test Co-authored-by: Marco Collovati <marco@vaadin.com>
1 parent be693e9 commit 77f6280

2 files changed

Lines changed: 132 additions & 52 deletions

File tree

‎flow-server/src/main/java/com/vaadin/flow/server/communication/AtmospherePushConnection.java‎

Lines changed: 54 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@ public class AtmospherePushConnection implements PushConnection {
5454
private transient FragmentedMessage incomingMessage;
5555
private transient Future<Object> outgoingMessage;
5656

57+
private transient Object lock = new Object();
58+
5759
/**
5860
* Represents a message that can arrive as multiple fragments.
5961
*/
@@ -185,19 +187,21 @@ public void push() {
185187
* false if it is a response to a client request.
186188
*/
187189
public void push(boolean async) {
188-
if (!isConnected()) {
189-
if (async && state != State.RESPONSE_PENDING) {
190-
state = State.PUSH_PENDING;
190+
synchronized (lock) {
191+
if (!isConnected()) {
192+
if (async && state != State.RESPONSE_PENDING) {
193+
state = State.PUSH_PENDING;
194+
} else {
195+
state = State.RESPONSE_PENDING;
196+
}
191197
} else {
192-
state = State.RESPONSE_PENDING;
193-
}
194-
} else {
195-
try {
196-
JsonObject response = new UidlWriter().createUidl(getUI(),
197-
async);
198-
sendMessage("for(;;);[" + response.toJson() + "]");
199-
} catch (Exception e) {
200-
throw new RuntimeException("Push failed", e);
198+
try {
199+
JsonObject response = new UidlWriter().createUidl(getUI(),
200+
async);
201+
sendMessage("for(;;);[" + response.toJson() + "]");
202+
} catch (Exception e) {
203+
throw new RuntimeException("Push failed", e);
204+
}
201205
}
202206
}
203207
}
@@ -307,46 +311,46 @@ protected AtmosphereResource getResource() {
307311

308312
@Override
309313
public void disconnect() {
310-
assert isConnected();
311-
312-
if (resource == null) {
313-
// Already disconnected. Should not happen but if it does, we don't
314-
// want to cause NPEs
315-
getLogger().debug(
316-
"AtmospherePushConnection.disconnect() called twice, this should not happen");
317-
return;
318-
}
319-
if (resource.isResumed()) {
320-
// This can happen for long polling because of
321-
// http://dev.vaadin.com/ticket/16919
322-
// Once that is fixed, this should never happen
323-
connectionLost();
324-
return;
325-
}
326-
327-
if (outgoingMessage != null) {
328-
// Wait for the last message to be sent before closing the
329-
// connection (assumes that futures are completed in order)
314+
synchronized (lock) {
315+
assert isConnected();
316+
if (resource == null) {
317+
// Already disconnected. Should not happen but if it does, we
318+
// don't
319+
// want to cause NPEs
320+
getLogger().debug(
321+
"AtmospherePushConnection.disconnect() called twice, this should not happen");
322+
return;
323+
}
324+
if (resource.isResumed()) {
325+
// This can happen for long polling because of
326+
// http://dev.vaadin.com/ticket/16919
327+
// Once that is fixed, this should never happen
328+
connectionLost();
329+
return;
330+
}
331+
if (outgoingMessage != null) {
332+
// Wait for the last message to be sent before closing the
333+
// connection (assumes that futures are completed in order)
334+
try {
335+
outgoingMessage.get(1000, TimeUnit.MILLISECONDS);
336+
} catch (TimeoutException e) {
337+
getLogger().info(
338+
"Timeout waiting for messages to be sent to client before disconnect",
339+
e);
340+
} catch (Exception e) {
341+
getLogger().info(
342+
"Error waiting for messages to be sent to client before disconnect",
343+
e);
344+
}
345+
outgoingMessage = null;
346+
}
330347
try {
331-
outgoingMessage.get(1000, TimeUnit.MILLISECONDS);
332-
} catch (TimeoutException e) {
333-
getLogger().info(
334-
"Timeout waiting for messages to be sent to client before disconnect",
335-
e);
336-
} catch (Exception e) {
337-
getLogger().info(
338-
"Error waiting for messages to be sent to client before disconnect",
339-
e);
348+
resource.close();
349+
} catch (IOException e) {
350+
getLogger().info("Error when closing push connection", e);
340351
}
341-
outgoingMessage = null;
342-
}
343-
344-
try {
345-
resource.close();
346-
} catch (IOException e) {
347-
getLogger().info("Error when closing push connection", e);
352+
connectionLost();
348353
}
349-
connectionLost();
350354
}
351355

352356
/**
@@ -389,6 +393,7 @@ private void readObject(ObjectInputStream stream)
389393
throws IOException, ClassNotFoundException {
390394
stream.defaultReadObject();
391395
state = State.DISCONNECTED;
396+
lock = new Object();
392397
}
393398

394399
private static Logger getLogger() {

‎flow-server/src/test/java/com/vaadin/flow/server/communication/AtmospherePushConnectionTest.java‎

Lines changed: 78 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,21 @@
1919
import java.io.ByteArrayOutputStream;
2020
import java.io.ObjectInputStream;
2121
import java.io.ObjectOutputStream;
22-
23-
import com.vaadin.flow.component.UI;
24-
import com.vaadin.flow.server.communication.AtmospherePushConnection.State;
22+
import java.util.concurrent.CompletableFuture;
23+
import java.util.concurrent.CountDownLatch;
24+
import java.util.concurrent.TimeUnit;
2525

2626
import org.atmosphere.cpr.AtmosphereResource;
27+
import org.atmosphere.cpr.Broadcaster;
2728
import org.junit.Assert;
2829
import org.junit.Test;
30+
import org.mockito.ArgumentMatchers;
2931
import org.mockito.Mockito;
3032

33+
import com.vaadin.flow.component.UI;
34+
import com.vaadin.flow.server.MockVaadinSession;
35+
import com.vaadin.flow.server.communication.AtmospherePushConnection.State;
36+
3137
/**
3238
* @author Vaadin Ltd
3339
* @since 1.0
@@ -53,4 +59,73 @@ public void testSerialization() throws Exception {
5359

5460
Assert.assertEquals(State.DISCONNECTED, connection.getState());
5561
}
62+
63+
@Test
64+
public void pushWhileDisconnect_disconnectedWithoutSendingMessage()
65+
throws Exception {
66+
67+
UI ui = Mockito.spy(new UI());
68+
MockVaadinSession vaadinSession = new MockVaadinSession();
69+
Mockito.when(ui.getSession()).thenReturn(vaadinSession);
70+
Broadcaster broadcaster = Mockito.mock(Broadcaster.class);
71+
AtmosphereResource resource = Mockito.mock(AtmosphereResource.class);
72+
Mockito.when(resource.getBroadcaster()).thenReturn(broadcaster);
73+
74+
AtmospherePushConnection connection = new AtmospherePushConnection(ui);
75+
connection.connect(resource);
76+
77+
CountDownLatch latch = new CountDownLatch(1);
78+
CompletableFuture.runAsync(() -> {
79+
try {
80+
vaadinSession.runWithLock(() -> {
81+
connection.push();
82+
return null;
83+
});
84+
} catch (Exception ex) {
85+
throw new RuntimeException(ex);
86+
} finally {
87+
latch.countDown();
88+
}
89+
});
90+
connection.disconnect();
91+
Assert.assertTrue("AtmospherePushConnection not disconnected",
92+
latch.await(2, TimeUnit.SECONDS));
93+
Assert.assertEquals(State.PUSH_PENDING, connection.getState());
94+
Mockito.verifyNoInteractions(broadcaster);
95+
}
96+
97+
@Test
98+
public void disconnectWhilePush_messageSentAndThenDisconnected()
99+
throws Exception {
100+
101+
UI ui = Mockito.spy(new UI());
102+
MockVaadinSession vaadinSession = new MockVaadinSession();
103+
Mockito.when(ui.getSession()).thenReturn(vaadinSession);
104+
Broadcaster broadcaster = Mockito.mock(Broadcaster.class);
105+
AtmosphereResource resource = Mockito.mock(AtmosphereResource.class);
106+
Mockito.when(resource.getBroadcaster()).thenReturn(broadcaster);
107+
108+
AtmospherePushConnection connection = new AtmospherePushConnection(ui);
109+
connection.connect(resource);
110+
111+
CountDownLatch latch = new CountDownLatch(1);
112+
CompletableFuture.runAsync(() -> {
113+
try {
114+
vaadinSession.runWithLock(() -> {
115+
CompletableFuture.runAsync(connection::disconnect);
116+
connection.push();
117+
return null;
118+
});
119+
} catch (Throwable ex) {
120+
throw new RuntimeException(ex);
121+
} finally {
122+
latch.countDown();
123+
}
124+
});
125+
Assert.assertTrue("Push not completed",
126+
latch.await(2, TimeUnit.SECONDS));
127+
Mockito.verify(broadcaster).broadcast(ArgumentMatchers.any(),
128+
ArgumentMatchers.eq(resource));
129+
}
130+
56131
}

0 commit comments

Comments
 (0)