Compare commits

..
2 Commits
Author SHA1 Message Date
Mo Firouz eb55222866 Nakama Java 2.5.2 release. 2024-10-27 10:26:26 +00:00
Mo Firouz afc257b7b6 Add overloaded methods for async disconnect methods. (#83)
* Add overloaded methods for async disconnect methods.

* Keep socket reference until OnClose is invoked

* Correct session logout. Shutdown executor correctly.

* WebSocket client resources are released immediately after disconnection and are made ready again in case of reconnection.
2024-10-27 10:25:08 +00:00
15 changed files with 166 additions and 31 deletions

No files matched your search

+11
View File
@@ -4,6 +4,17 @@ All notable changes to this project are documented below.
The format is based on [keep a changelog](http://keepachangelog.com/) and this project uses [semantic versioning](http://semver.org/).
## [2.5.2] - 2024-10-27
### Changed
- WebSocketClient now closes the thread executor service if internal executor was used once the socket is closed.
- Improve client and socket disconnection process.
### Fixed
- Corrected Channel Type enum values to match the protocol.
- Session logout function no longer attempts to renew the token after logout.
- WebSocket client resources are released immediately after disconnection and are made ready again in case of reconnection.
## [2.5.1] - 2024-10-16
### Changed
+1 -1
View File
@@ -42,7 +42,7 @@ lombok {
}
group = 'com.github.heroiclabs'
version = '2.5.1'
version = '2.5.2'
sourceCompatibility = 1.8
targetCompatibility = 1.8
@@ -23,17 +23,17 @@ public enum ChannelType {
/**
* A chat room which can be created dynamically with a name.
*/
ROOM(0),
ROOM(1),
/**
* A private chat between two users.
*/
DIRECT_MESSAGE(1),
DIRECT_MESSAGE(2),
/**
* A chat within a group on the server.
*/
GROUP(2);
GROUP(3);
private final int value;
ChannelType(int value) {
@@ -37,6 +37,8 @@ public interface Client {
/**
* Disconnects the client. This function kills all outgoing exchanges immediately without waiting.
* @deprecated
* This method is deprecated. <p> Use {@link Client#disconnect(long, TimeUnit)} instead.
*/
void disconnect();
@@ -210,22 +210,22 @@ public class DefaultClient implements Client {
@Override
public SocketClient createSocket(final int port, final int socketTimeoutMs) {
return new WebSocketClient(host, port, ssl, socketTimeoutMs, WebSocketClient.DEFAULT_PING_MS, this.trace, Executors.newSingleThreadExecutor());
return new WebSocketClient(host, port, ssl, socketTimeoutMs, WebSocketClient.DEFAULT_PING_MS, this.trace, null);
}
@Override
public SocketClient createSocket(final String host, final int port, final boolean ssl) {
return new WebSocketClient(host, port, ssl, WebSocketClient.DEFAULT_TIMEOUT_MS, WebSocketClient.DEFAULT_PING_MS, this.trace, Executors.newSingleThreadExecutor());
return new WebSocketClient(host, port, ssl, WebSocketClient.DEFAULT_TIMEOUT_MS, WebSocketClient.DEFAULT_PING_MS, this.trace, null);
}
@Override
public SocketClient createSocket(final String host, final int port, final boolean ssl, final int socketTimeoutMs) {
return new WebSocketClient(host, port, ssl, socketTimeoutMs, WebSocketClient.DEFAULT_PING_MS, this.trace, Executors.newSingleThreadExecutor());
return new WebSocketClient(host, port, ssl, socketTimeoutMs, WebSocketClient.DEFAULT_PING_MS, this.trace, null);
}
@Override
public SocketClient createSocket(final String host, final int port, final boolean ssl, final int socketTimeoutMs, final int socketPingMs) {
return new WebSocketClient(host, port, ssl, socketTimeoutMs, socketPingMs, this.trace, Executors.newSingleThreadExecutor());
return new WebSocketClient(host, port, ssl, socketTimeoutMs, socketPingMs, this.trace, null);
}
@Override
@@ -1791,7 +1791,7 @@ public class DefaultClient implements Client {
@Override
public ListenableFuture<Empty> logoutSession(@NonNull final Session session) {
return autoRefreshSession(session, getStub(session).sessionLogout(SessionLogoutRequest.newBuilder().setToken(session.getAuthToken()).setRefreshToken(session.getRefreshToken()).build()));
return getStub(session).sessionLogout(SessionLogoutRequest.newBuilder().setToken(session.getAuthToken()).setRefreshToken(session.getRefreshToken()).build());
}
@Override
@@ -24,6 +24,7 @@ import lombok.NonNull;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* A socket connection to the server.
@@ -48,11 +49,18 @@ public interface SocketClient {
/**
* Close the connection with the server.
* @deprecated
* This method is deprecated. <p> Use {@link SocketClient#disconnectSocket()} instead.
*
* @return A close future.
*/
ListenableFuture<Boolean> disconnect();
/**
* Close the connection with the server. This is an asynchronous call, and you should subscribe to OnClose callback to act on this.
*/
void disconnectSocket();
/**
* Join a chat channel on the server.
*
@@ -27,9 +27,6 @@ import com.google.protobuf.Timestamp;
import com.google.type.Date;
import com.heroiclabs.nakama.api.NotificationList;
import com.heroiclabs.nakama.api.Rpc;
import com.heroiclabs.nakama.rtapi.PartyJoin;
import com.heroiclabs.nakama.rtapi.PartyJoinRequestList;
import com.heroiclabs.nakama.rtapi.PartyMatchmakerAdd;
import com.heroiclabs.nakama.rtapi.PartyMatchmakerTicket;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
@@ -43,6 +40,7 @@ import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
@@ -77,10 +75,11 @@ public class WebSocketClient implements SocketClient {
private final int port;
private final boolean ssl;
private final boolean trace;
private final OkHttpClient client;
private final Map<String, SettableFuture<?>> collationIds;
private final boolean shouldShutdownThreadExecService;
private final OkHttpClient.Builder clientBuilder;
private ExecutorService listenerThreadExec;
private WebSocket socket;
private final ExecutorService listenerThreadExec;
WebSocketClient(@NonNull final String host, final int port, final boolean ssl,
final int socketTimeoutMs, final int socketPingMs, final boolean trace, ExecutorService listenerThreadExec) {
@@ -89,14 +88,19 @@ public class WebSocketClient implements SocketClient {
this.ssl = ssl;
this.trace = trace;
this.collationIds = new ConcurrentHashMap<>();
this.listenerThreadExec = listenerThreadExec;
if (listenerThreadExec != null) {
this.listenerThreadExec = listenerThreadExec;
this.shouldShutdownThreadExecService = false;
} else {
this.listenerThreadExec = Executors.newSingleThreadExecutor();
this.shouldShutdownThreadExecService = true;
}
client = new OkHttpClient.Builder()
clientBuilder = new OkHttpClient.Builder()
.connectTimeout(socketTimeoutMs, TimeUnit.MILLISECONDS)
.readTimeout(socketTimeoutMs, TimeUnit.MILLISECONDS)
.writeTimeout(socketTimeoutMs, TimeUnit.MILLISECONDS)
.pingInterval(socketPingMs, TimeUnit.SECONDS)
.build();
.pingInterval(socketPingMs, TimeUnit.SECONDS);
}
@Override
@@ -107,7 +111,7 @@ public class WebSocketClient implements SocketClient {
@Override
public ListenableFuture<Session> connect(@NonNull final Session session, @NonNull final SocketListener listener, final boolean createStatus) {
if (socket != null) {
return Futures.immediateFailedFuture(new DefaultError("Client is already connected"));
return Futures.immediateFailedFuture(new DefaultError("Socket is already connected"));
}
final String url = new HttpUrl.Builder()
@@ -133,8 +137,14 @@ public class WebSocketClient implements SocketClient {
}
private ListenableFuture<Session> createWebsocket(@NonNull final Session session, @NonNull final SocketListener listener, @NonNull final Request request) {
if (this.listenerThreadExec == null || this.listenerThreadExec.isShutdown() || this.listenerThreadExec.isTerminated()) {
// in case of previously closed/failed socket.
this.listenerThreadExec = Executors.newSingleThreadExecutor();
}
final SettableFuture<Session> connectFuture = SettableFuture.create();
final Object lock = this;
final OkHttpClient client = clientBuilder.build();
socket = client.newWebSocket(request, new WebSocketListener() {
@Override
public void onOpen(final WebSocket webSocket, final Response response) {
@@ -146,7 +156,7 @@ public class WebSocketClient implements SocketClient {
@Override
public void onMessage(final WebSocket webSocket, final ByteString bytes) {
super.onMessage(webSocket, bytes);
// No text messages are expected.
// No binary messages are expected.
log.warn("Unexpected binary message from server: " + bytes.base64());
}
@@ -293,32 +303,54 @@ public class WebSocketClient implements SocketClient {
@Override
public void onClosed(final WebSocket webSocket, final int code, final String reason) {
super.onClosed(webSocket, code, reason);
listener.onDisconnect(null);
// Graceful socket disconnect is complete, clean up.
synchronized (lock) {
socket.cancel();
socket = null;
collationIds.clear();
if (!connectFuture.isCancelled() && !connectFuture.isDone()) {
connectFuture.setException(new Throwable("Socket closed."));
}
if (shouldShutdownThreadExecService) {
listenerThreadExec.shutdown();
}
// clean up OkHttp Websocket resources.
client.connectionPool().evictAll();
client.dispatcher().executorService().shutdown();
// setup new executor service in case of reconnections.
clientBuilder.setDispatcher$okhttp(new Dispatcher());
}
listener.onDisconnect(null);
}
@Override
public void onFailure(final WebSocket webSocket, final Throwable t, final Response response) {
super.onFailure(webSocket, t, response);
listener.onDisconnect(t);
// Socket has failed and is no longer connected, clean up.
synchronized (lock) {
socket.cancel();
socket = null;
collationIds.clear();
if (!connectFuture.isCancelled() && !connectFuture.isDone()) {
connectFuture.setException(t);
}
}
listener.onDisconnect(t);
if (shouldShutdownThreadExecService) {
listenerThreadExec.shutdown();
}
// clean up OkHttp Websocket resources.
client.connectionPool().evictAll();
client.dispatcher().executorService().shutdown();
// setup new executor service in case of reconnections.
clientBuilder.setDispatcher$okhttp(new Dispatcher());
}
}
});
return connectFuture;
@@ -330,12 +362,23 @@ public class WebSocketClient implements SocketClient {
// Returns true if a shutdown was initiated, false if already shutting down or disconnected.
// Either result is acceptable here.
// Socket reference will be set to null when disconnect is completed.
// Don't nullify the socket at this stage as we'll need to have the OnClose called.
socket.close(1000, null);
socket = null;
}
return Futures.immediateFuture(true);
}
@Override
public synchronized void disconnectSocket() {
if (socket != null) {
// Returns true if a shutdown was initiated, false if already shutting down or disconnected.
// Either result is acceptable here.
// Socket reference will be set to null when disconnect is completed.
// Don't nullify the socket at this stage as we'll need to have the OnClose called.
socket.close(1000, null);
}
}
@Override
public ListenableFuture<Channel> joinChat(@NonNull final String target, @NonNull final ChannelType type) {
final ChannelJoinMessage msg = new ChannelJoinMessage(target, type.getValue());
@@ -42,7 +42,7 @@ public class ChannelTest {
@After
public void shutdown() throws Exception {
socket.disconnect();
socket.disconnectSocket();
client.disconnect(5000, TimeUnit.MILLISECONDS);
}
@@ -56,7 +56,7 @@ public class ChannelTest {
Assert.assertNotNull(channel.getSelf());
Assert.assertEquals(session.getUserId(), channel.getSelf().getUserId());
socket.leaveChat(channel.getId()).get();
socket.disconnect();
socket.disconnectSocket();
}
@Test
@@ -43,7 +43,7 @@ public class MatchTest {
@After
public void shutdown() throws Exception {
socket.disconnect();
socket.disconnectSocket();
client.disconnect(5000, TimeUnit.MILLISECONDS);
}
@@ -45,6 +45,8 @@ public class MatchmakerTest {
@After
public void shutdown() throws Exception {
socket.disconnectSocket();
socket2.disconnectSocket();
client.disconnect(5000, TimeUnit.MILLISECONDS);
}
@@ -45,7 +45,7 @@ public class NotificationTest {
@After
public void shutdown() throws Exception {
socket.disconnect();
socket.disconnectSocket();
client.disconnect(5000, TimeUnit.MILLISECONDS);
}
@@ -40,7 +40,7 @@ public class RpcTest {
@After
public void shutdown() throws Exception {
socket.disconnect();
socket.disconnectSocket();
client.disconnect(5000, TimeUnit.MILLISECONDS);
}
@@ -22,6 +22,7 @@ import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@@ -54,5 +55,13 @@ public class SessionTest {
Assert.assertNotEquals(0, session.getCreateTime());
Assert.assertNotEquals(0, session.getExpireTime());
// let's make sure that we terminate all threads correctly.
for (Thread thread: Thread.getAllStackTraces().keySet()) {
// System.out.printf("%s: %s %s\n", thread.getName(), thread.getState(), thread.isDaemon() ? "(daemon)" : "");
if (!thread.getName().equalsIgnoreCase("main")) {
Assert.assertTrue(thread.isDaemon());
}
}
}
}
@@ -16,12 +16,17 @@
package com.heroiclabs.nakama;
import com.heroiclabs.nakama.api.ChannelMessage;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
@@ -42,7 +47,7 @@ public class SocketTest {
@After
public void shutdown() throws Exception {
socket.disconnect();
socket.disconnectSocket();
}
@Test(expected = Error.class)
@@ -112,4 +117,59 @@ public class SocketTest {
Assert.assertTrue("Success callback was not dispatched.", connectCallback.successDispatched);
}
@Test
public void testMultiConnectAndThreadCount() throws Exception {
final List<Boolean> callbacks = new ArrayList<Boolean>();
final CountDownLatch latch = new CountDownLatch(4);
final String content = "{\"message\":\"Hello world\"}";
socket.connect(session, new AbstractSocketListener() {
@Override public void onDisconnect(final Throwable t) {
callbacks.add(true);
latch.countDown();
}
});
socket.disconnectSocket();
Thread.sleep(1000);
socket.connect(session, new AbstractSocketListener() {
@Override
public void onChannelMessage(final ChannelMessage message) {
super.onChannelMessage(message);
callbacks.add(true);
latch.countDown();
}
@Override
public void onChannelPresence(final ChannelPresenceEvent presence) {
super.onChannelPresence(presence);
callbacks.add(true);
latch.countDown();
}
@Override public void onDisconnect(final Throwable t) {
callbacks.add(true);
latch.countDown();
}
});
final Channel channel = socket.joinChat("myroom2", ChannelType.ROOM).get();
Assert.assertNotNull(channel);
final ChannelMessageAck ack = socket.writeChatMessage(channel.getId(), content).get();
Assert.assertNotNull(ack);
socket.disconnectSocket();
Thread.sleep(1000);
latch.await(10, TimeUnit.SECONDS);
// let's make sure that we terminate all threads correctly.
for (Thread thread: Thread.getAllStackTraces().keySet()) {
// System.out.printf("%s: %s %s\n", thread.getName(), thread.getState(), thread.isDaemon() ? "(daemon)" : "");
if (!thread.getName().equalsIgnoreCase("main")) {
Assert.assertTrue(thread.isDaemon());
}
}
Assert.assertEquals(4, callbacks.size());
}
}
@@ -41,7 +41,7 @@ public class StreamTest {
@After
public void shutdown() throws Exception {
socket.disconnect();
socket.disconnectSocket();
client.disconnect(5000, TimeUnit.MILLISECONDS);
}