Skip to content

Acquire HubConnectionStateLock before Send/Invoke/Stream #12078

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jul 15, 2019
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ public class HubConnection {
private Map<String, Observable> streamMap = new ConcurrentHashMap<>();
private TransportEnum transportEnum = TransportEnum.ALL;
private String connectionId;
private final Lock connectionStateLock = new ReentrantLock();
private final Logger logger = LoggerFactory.getLogger(HubConnection.class);

/**
Expand Down Expand Up @@ -505,9 +506,15 @@ private void stopConnection(String errorMessage) {
exception = new RuntimeException(errorMessage);
logger.error("HubConnection disconnected with an error {}.", errorMessage);
}
if (connectionState != null) {
connectionState.cancelOutstandingInvocations(exception);
connectionState = null;

connectionStateLock.lock();
try {
if (connectionState != null) {
connectionState.cancelOutstandingInvocations(exception);
connectionState = null;
}
} finally {
connectionStateLock.unlock();
}

logger.info("HubConnection stopped.");
Expand Down Expand Up @@ -537,8 +544,13 @@ private void stopConnection(String errorMessage) {
* @param args The arguments to be passed to the method.
*/
public void send(String method, Object... args) {
if (hubConnectionState != HubConnectionState.CONNECTED) {
throw new RuntimeException("The 'send' method cannot be called if the connection is not active.");
hubConnectionStateLock.lock();
try {
if (hubConnectionState != HubConnectionState.CONNECTED) {
throw new RuntimeException("The 'send' method cannot be called if the connection is not active.");
}
} finally {
hubConnectionStateLock.unlock();
}

sendInvocationMessage(method, args);
Expand Down Expand Up @@ -638,15 +650,23 @@ public Completable invoke(String method, Object... args) {
*/
@SuppressWarnings("unchecked")
public <T> Single<T> invoke(Class<T> returnType, String method, Object... args) {
if (hubConnectionState != HubConnectionState.CONNECTED) {
throw new RuntimeException("The 'invoke' method cannot be called if the connection is not active.");
}
ConnectionState localConnectionState;
InvocationRequest irq;
String id;
hubConnectionStateLock.lock();
try {
if (hubConnectionState != HubConnectionState.CONNECTED) {
throw new RuntimeException("The 'invoke' method cannot be called if the connection is not active.");
}

String id = connectionState.getNextInvocationId();
id = connectionState.getNextInvocationId();
irq = new InvocationRequest(returnType, id);
connectionState.addInvocation(irq);
} finally {
hubConnectionStateLock.unlock();
}

SingleSubject<T> subject = SingleSubject.create();
InvocationRequest irq = new InvocationRequest(returnType, id);
connectionState.addInvocation(irq);

// forward the invocation result or error to the user
// run continuations on a separate thread
Expand Down Expand Up @@ -677,12 +697,23 @@ public <T> Single<T> invoke(Class<T> returnType, String method, Object... args)
*/
@SuppressWarnings("unchecked")
public <T> Observable<T> stream(Class<T> returnType, String method, Object ... args) {
String invocationId = connectionState.getNextInvocationId();
String invocationId;
InvocationRequest irq;
hubConnectionStateLock.lock();
try {
if (hubConnectionState != HubConnectionState.CONNECTED) {
throw new RuntimeException("The 'stream' method cannot be called if the connection is not active.");
}

invocationId = connectionState.getNextInvocationId();
irq = new InvocationRequest(returnType, invocationId);
connectionState.addInvocation(irq);
} finally {
hubConnectionStateLock.unlock();
}

AtomicInteger subscriptionCount = new AtomicInteger();
InvocationRequest irq = new InvocationRequest(returnType, invocationId);
connectionState.addInvocation(irq);
ReplaySubject<T> subject = ReplaySubject.create();

Subject<Object> pendingCall = irq.getPendingCall();
pendingCall.subscribe(result -> {
// Primitive types can't be cast with the Class cast function
Expand All @@ -700,7 +731,14 @@ public <T> Observable<T> stream(Class<T> returnType, String method, Object ... a
if (subscriptionCount.decrementAndGet() == 0) {
CancelInvocationMessage cancelInvocationMessage = new CancelInvocationMessage(invocationId);
sendHubMessage(cancelInvocationMessage);
connectionState.tryRemoveInvocation(invocationId);
connectionStateLock.lock();
try {
if (connectionState != null) {
connectionState.tryRemoveInvocation(invocationId);
}
} finally {
connectionStateLock.unlock();
}
subject.onComplete();
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1608,6 +1608,15 @@ public void cannotInvokeBeforeStart() {
assertEquals("The 'invoke' method cannot be called if the connection is not active.", exception.getMessage());
}

@Test
public void cannotStreamBeforeStart() {
HubConnection hubConnection = TestUtils.createHubConnection("http://example.com");
assertEquals(HubConnectionState.DISCONNECTED, hubConnection.getConnectionState());

Throwable exception = assertThrows(RuntimeException.class, () -> hubConnection.stream(String.class, "inc", "arg1"));
assertEquals("The 'stream' method cannot be called if the connection is not active.", exception.getMessage());
}

@Test
public void doesNotErrorWhenReceivingInvokeWithIncorrectArgumentLength() {
MockTransport mockTransport = new MockTransport();
Expand Down Expand Up @@ -2036,7 +2045,7 @@ public void authorizationHeaderFromNegotiateGetsSetToNewValue() {

TestHttpClient client = new TestHttpClient()
.on("POST", "http://example.com/negotiate", (req) -> {
if(redirectCount.get() == 0){
if (redirectCount.get() == 0) {
redirectCount.incrementAndGet();
redirectToken.set(req.getHeaders().get("Authorization"));
return Single.just(new HttpResponse(200, "", "{\"url\":\"http://testexample.com/\",\"accessToken\":\"firstRedirectToken\"}"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import java.util.HashMap;
import java.util.stream.Stream;

import io.reactivex.Single;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,6 @@ public static void main(String[] args) {
hubConnection.send("Send", message);
}

hubConnection.stop();
hubConnection.stop().blockingAwait();
}
}