Tweak network message logic, consolidate timeout handling

This commit is contained in:
William committed 2022-11-23 00:26:47 +00:00
1 parent 9a34ecdee6
commit b4e95b13d0
7 files changed
+116 -75

No files matched your search

@@ -54,7 +54,6 @@ import java.util.*;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -468,34 +467,29 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
return server; return server;
} }
@Override
public CompletableFuture<Void> fetchServer(@NotNull OnlineUser requester) { public CompletableFuture<Void> fetchServer(@NotNull OnlineUser requester) {
if (!getSettings().crossServer || server != null) { if (!getSettings().crossServer || this.server != null) {
return CompletableFuture.completedFuture(null); return CompletableFuture.completedFuture(null);
} }
assert networkMessenger != null; return getNetworkMessenger()
getLoggingAdapter().log(Level.INFO, "Fetching server information from the proxy..."); .fetchServerName(requester)
final AtomicInteger attempts = new AtomicInteger(0); .orTimeout(5, TimeUnit.SECONDS)
return CompletableFuture.runAsync(() -> { .exceptionally(throwable -> null)
String serverName = null; .thenAccept(serverName -> {
while (serverName == null) { if (serverName == null) {
attempts.getAndIncrement(); throw new HuskHomesException("GetServer plugin message call operation timed out");
serverName = networkMessenger.getServerName(requester)
.orTimeout(1, TimeUnit.SECONDS)
.exceptionally(throwable -> null).join();
} }
getLoggingAdapter().log(Level.INFO, "Successfully fetched server information from the proxy (name: "
+ serverName + ", attempts: " + attempts.get() + ")");
server = new Server(serverName);
try { try {
this.server = new Server(serverName);
Annotaml.create(new File(getDataFolder(), "server.yml"), new CachedServer(serverName)); Annotaml.create(new File(getDataFolder(), "server.yml"), new CachedServer(serverName));
getLoggingAdapter().log(Level.INFO, "Successfully cached server name to disk (" + serverName + ")");
} catch (IOException e) { } catch (IOException e) {
throw new HuskHomesException("Failed to save server information", e); throw new HuskHomesException("Failed to write cached server name to disk", e);
} }
}) })
.orTimeout(5, TimeUnit.SECONDS)
.exceptionally(throwable -> { .exceptionally(throwable -> {
getLoggingAdapter().log(Level.SEVERE, "Failed to fetch server name from the proxy (attempts: " getLoggingAdapter().log(Level.SEVERE, "Failed to fetch and cache server name", throwable);
+ attempts.get() + ") - Is your proxy server online?", throwable);
return null; return null;
}); });
} }
@@ -71,7 +71,7 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi
@Override @Override
@SuppressWarnings("UnstableApiUsage") @SuppressWarnings("UnstableApiUsage")
public CompletableFuture<String> getServerName(@NotNull OnlineUser requester) { public CompletableFuture<String> fetchServerName(@NotNull OnlineUser requester) {
final BukkitHuskHomes plugin = (BukkitHuskHomes) this.plugin; final BukkitHuskHomes plugin = (BukkitHuskHomes) this.plugin;
final CompletableFuture<String> future = new CompletableFuture<>(); final CompletableFuture<String> future = new CompletableFuture<>();
serverNameRequests.add(future); serverNameRequests.add(future);
@@ -87,7 +87,7 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi
@Override @Override
@SuppressWarnings("UnstableApiUsage") @SuppressWarnings("UnstableApiUsage")
public CompletableFuture<String[]> getOnlineServers(@NotNull OnlineUser requester) { public CompletableFuture<String[]> fetchOnlineServerList(@NotNull OnlineUser requester) {
final BukkitHuskHomes plugin = (BukkitHuskHomes) this.plugin; final BukkitHuskHomes plugin = (BukkitHuskHomes) this.plugin;
final CompletableFuture<String[]> future = new CompletableFuture<>(); final CompletableFuture<String[]> future = new CompletableFuture<>();
onlineServersRequests.add(future); onlineServersRequests.add(future);
@@ -105,7 +105,7 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi
@SuppressWarnings("UnstableApiUsage") @SuppressWarnings("UnstableApiUsage")
public CompletableFuture<Boolean> sendPlayer(@NotNull OnlineUser onlineUser, @NotNull Server server) { public CompletableFuture<Boolean> sendPlayer(@NotNull OnlineUser onlineUser, @NotNull Server server) {
final BukkitHuskHomes plugin = (BukkitHuskHomes) this.plugin; final BukkitHuskHomes plugin = (BukkitHuskHomes) this.plugin;
return getOnlineServers(onlineUser).thenApplyAsync(onlineServers -> { return fetchOnlineServerList(onlineUser).thenApplyAsync(onlineServers -> {
final Optional<String> targetServer = Arrays.stream(onlineServers) final Optional<String> targetServer = Arrays.stream(onlineServers)
.filter(serverName -> serverName.equals(server.name)) .filter(serverName -> serverName.equals(server.name))
.findFirst(); .findFirst();
@@ -126,7 +126,7 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi
} }
@Override @Override
public CompletableFuture<Message> sendMessage(@NotNull OnlineUser sender, @NotNull Message message) { public CompletableFuture<Message> dispatchMessage(@NotNull OnlineUser sender, @NotNull Message message) {
final CompletableFuture<Message> repliedMessage = new CompletableFuture<>(); final CompletableFuture<Message> repliedMessage = new CompletableFuture<>();
processingMessages.put(message.uuid, repliedMessage); processingMessages.put(message.uuid, repliedMessage);
sendPluginMessage((BukkitPlayer) sender, message); sendPluginMessage((BukkitPlayer) sender, message);
@@ -53,7 +53,7 @@ public class RedisMessenger extends PluginMessenger {
} }
@Override @Override
public CompletableFuture<Message> sendMessage(@NotNull OnlineUser sender, @NotNull Message message) { public CompletableFuture<Message> dispatchMessage(@NotNull OnlineUser sender, @NotNull Message message) {
final CompletableFuture<Message> repliedMessage = new CompletableFuture<>(); final CompletableFuture<Message> repliedMessage = new CompletableFuture<>();
processingMessages.put(message.uuid, repliedMessage); processingMessages.put(message.uuid, repliedMessage);
redisWorker.sendMessage(message); redisWorker.sendMessage(message);
@@ -8,6 +8,8 @@ import org.jetbrains.annotations.NotNull;
import java.util.*; import java.util.*;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
public abstract class NetworkMessenger { public abstract class NetworkMessenger {
@@ -22,7 +24,7 @@ public abstract class NetworkMessenger {
protected HashMap<UUID, CompletableFuture<Message>> processingMessages; protected HashMap<UUID, CompletableFuture<Message>> processingMessages;
/** /**
* List of pending futures for processing {@link #getServerName(OnlineUser)} requests * List of pending futures for processing {@link #fetchServerName(OnlineUser)} requests
*/ */
protected List<CompletableFuture<String>> serverNameRequests; protected List<CompletableFuture<String>> serverNameRequests;
@@ -32,7 +34,7 @@ public abstract class NetworkMessenger {
protected List<CompletableFuture<String[]>> onlinePlayerNamesRequests; protected List<CompletableFuture<String[]>> onlinePlayerNamesRequests;
/** /**
* List of pending futures for processing {@link #getOnlineServers(OnlineUser)} requests * List of pending futures for processing {@link #fetchOnlineServerList(OnlineUser)} requests
*/ */
protected List<CompletableFuture<String[]>> onlineServersRequests; protected List<CompletableFuture<String[]>> onlineServersRequests;
@@ -46,6 +48,11 @@ public abstract class NetworkMessenger {
*/ */
protected HuskHomes plugin; protected HuskHomes plugin;
/**
* The time-to-live of a message before it expires and the {@link CompletableFuture} is cancelled
*/
private final long MESSAGE_TIME_OUT = 5L;
/** /**
* Initialize the network messenger * Initialize the network messenger
* *
@@ -93,7 +100,7 @@ public abstract class NetworkMessenger {
* @param requester {@link OnlineUser} to send the request * @param requester {@link OnlineUser} to send the request
* @return Future returning the name of this server on the network * @return Future returning the name of this server on the network
*/ */
public abstract CompletableFuture<String> getServerName(@NotNull OnlineUser requester); public abstract CompletableFuture<String> fetchServerName(@NotNull OnlineUser requester);
/** /**
* Fetch a list of online server names proxy * Fetch a list of online server names proxy
@@ -101,7 +108,7 @@ public abstract class NetworkMessenger {
* @param requester {@link OnlineUser} to send the request * @param requester {@link OnlineUser} to send the request
* @return Future returning a {@link List} of online servers connected to the proxy network * @return Future returning a {@link List} of online servers connected to the proxy network
*/ */
public abstract CompletableFuture<String[]> getOnlineServers(@NotNull OnlineUser requester); public abstract CompletableFuture<String[]> fetchOnlineServerList(@NotNull OnlineUser requester);
/** /**
* Send a {@link OnlineUser} to a target {@link Server} on the proxy network * Send a {@link OnlineUser} to a target {@link Server} on the proxy network
@@ -113,12 +120,34 @@ public abstract class NetworkMessenger {
public abstract CompletableFuture<Boolean> sendPlayer(@NotNull OnlineUser onlineUser, @NotNull Server server); public abstract CompletableFuture<Boolean> sendPlayer(@NotNull OnlineUser onlineUser, @NotNull Server server);
/** /**
* Send a network {@link Message} to a target player on the proxy * Send a network message
* *
* @param message The {@link Message} to send * @param sender {@link OnlineUser} sending the message
* @param message {@link Message} to send
* @return Future returning the {@link Message} sent, that will time out after
* @apiNote This method invokes {@link #dispatchMessage(OnlineUser, Message)}, applying a time-to-live timeOut
*/
public final CompletableFuture<Optional<Message>> sendMessage(@NotNull OnlineUser sender, @NotNull Message message) {
return dispatchMessage(sender, message)
.orTimeout(MESSAGE_TIME_OUT, TimeUnit.SECONDS)
.exceptionally(e -> {
plugin.getLoggingAdapter().log(Level.WARNING, "Message dispatch after " + MESSAGE_TIME_OUT + " seconds", e);
return null;
})
.thenApply(result -> {
processingMessages.remove(message.uuid);
return Optional.ofNullable(result);
});
}
/**
* Dispatch a {@link Message} via the appropriate handler
*
* @param sender The {@link OnlineUser} that sent the {@link Message}
* @param message The {@link Message} to dispatch
* @return A future containing a reply to the {@link Message} that was sent * @return A future containing a reply to the {@link Message} that was sent
*/ */
public abstract CompletableFuture<Message> sendMessage(@NotNull OnlineUser sender, @NotNull Message message); protected abstract CompletableFuture<Message> dispatchMessage(@NotNull OnlineUser sender, @NotNull Message message);
/** /**
* Send a reply to a received {@link Message} * Send a reply to a received {@link Message}
@@ -142,14 +171,23 @@ public abstract class NetworkMessenger {
if (processingMessages.containsKey(message.uuid)) { if (processingMessages.containsKey(message.uuid)) {
final Message finalMessage = message; final Message finalMessage = message;
processingMessages.get(message.uuid).completeAsync(() -> finalMessage); processingMessages.get(message.uuid).completeAsync(() -> finalMessage);
return;
} }
plugin.getLoggingAdapter().log(Level.WARNING, "Received a reply to a message that was not sent by this server");
} }
} }
} }
/**
* Handle different message types, executed needed operations and dispatches a reply message
* to the sender
*
* @param receiver The {@link OnlineUser} receiving the message
* @param message The received {@link Message}
* @return A future containing the reply {@link Message}
*/
private CompletableFuture<Message> prepareReply(@NotNull final OnlineUser receiver, @NotNull final Message message) { private CompletableFuture<Message> prepareReply(@NotNull final OnlineUser receiver, @NotNull final Message message) {
return CompletableFuture.supplyAsync(() -> { return CompletableFuture.supplyAsync(() -> {
// Handle different message types and apply changes for reply message
switch (message.type) { switch (message.type) {
case TELEPORT_TO_POSITION_REQUEST -> { case TELEPORT_TO_POSITION_REQUEST -> {
if (message.payload.position != null) { if (message.payload.position != null) {
@@ -176,15 +214,29 @@ public abstract class NetworkMessenger {
} }
} }
} }
// Prepare reply message
message.targetPlayer = message.sender;
message.sender = receiver.username;
message.relayType = Message.RelayType.REPLY;
return message; return message;
}).exceptionally(exception -> {
plugin.getLoggingAdapter().log(Level.WARNING, "Failed to prepare message reply", exception);
message.payload = MessagePayload.empty();
return message;
}).thenApply(reply -> {
formatReplyMessage(message, receiver);
return reply;
}); });
} }
/**
* Prepare a {@link Message} to be sent as a reply to a received {@link Message}
*
* @param message The received {@link Message}
* @param receiver The {@link OnlineUser} receiving the message
*/
private void formatReplyMessage(@NotNull Message message, @NotNull OnlineUser receiver) {
message.targetPlayer = message.sender;
message.sender = receiver.username;
message.relayType = Message.RelayType.REPLY;
}
/** /**
* Close the network messenger * Close the network messenger
*/ */
@@ -12,7 +12,6 @@ import org.jetbrains.annotations.NotNull;
import java.time.Instant; import java.time.Instant;
import java.util.*; import java.util.*;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
/** /**
* Manages {@link TeleportRequest}s between players * Manages {@link TeleportRequest}s between players
@@ -148,26 +147,25 @@ public class RequestManager {
// Use the network messenger to send the request // Use the network messenger to send the request
request.recipientName = networkedTarget.get(); request.recipientName = networkedTarget.get();
return Optional.ofNullable(plugin.getNetworkMessenger().sendMessage(requester, return plugin.getNetworkMessenger()
new Message(Message.MessageType.TELEPORT_REQUEST, .sendMessage(requester, new Message(Message.MessageType.TELEPORT_REQUEST,
requester.username, requester.username,
networkedTarget.get(), networkedTarget.get(),
MessagePayload.withTeleportRequest(request), MessagePayload.withTeleportRequest(request),
Message.RelayType.MESSAGE, Message.RelayType.MESSAGE,
plugin.getSettings().clusterId)) plugin.getSettings().clusterId))
.orTimeout(3, TimeUnit.SECONDS)
.exceptionally(throwable -> null)
.thenApply(reply -> { .thenApply(reply -> {
if (reply == null || reply.payload.teleportRequest == null) { if (reply.isPresent()) {
return null; final TeleportRequest result = reply.get().payload.teleportRequest;
} if (result == null || result.status == TeleportRequest.RequestStatus.IGNORED) {
return null;
// If the message was ignored by the recipient, return false }
if (reply.payload.teleportRequest.status == TeleportRequest.RequestStatus.PENDING) { return result;
return request;
} }
return null; return null;
}).join()); })
.thenApply(Optional::ofNullable)
.join();
}); });
} }
return CompletableFuture.completedFuture(Optional.empty()); return CompletableFuture.completedFuture(Optional.empty());
@@ -294,16 +292,15 @@ public class RequestManager {
return false; return false;
} }
return plugin.getNetworkMessenger().sendMessage(recipient, return plugin.getNetworkMessenger()
new Message(Message.MessageType.TELEPORT_REQUEST_RESPONSE, .sendMessage(recipient, new Message(Message.MessageType.TELEPORT_REQUEST_RESPONSE,
recipient.username, recipient.username,
networkedTarget.get(), networkedTarget.get(),
MessagePayload.withTeleportRequest(request), MessagePayload.withTeleportRequest(request),
Message.RelayType.MESSAGE, Message.RelayType.MESSAGE,
plugin.getSettings().clusterId)) plugin.getSettings().clusterId))
.thenApply(reply -> true) .thenApply(Optional::isPresent)
.orTimeout(3, TimeUnit.SECONDS) .join();
.exceptionally(throwable -> false).join();
}) })
.thenAccept(online -> { .thenAccept(online -> {
if (!online) { if (!online) {
@@ -223,13 +223,14 @@ public class Teleport {
MessagePayload.withPosition(target), MessagePayload.withPosition(target),
Message.RelayType.MESSAGE, Message.RelayType.MESSAGE,
plugin.getSettings().clusterId)) plugin.getSettings().clusterId))
.orTimeout(3, TimeUnit.SECONDS)
.exceptionally(throwable -> null)
.thenApply(result -> { .thenApply(result -> {
if (result == null || result.payload.resultState == null) { if (result.isPresent()) {
return TeleportResult.FAILED_TELEPORTER_NOT_RESOLVED; final Message reply = result.get();
if (reply.payload.resultState != null) {
return reply.payload.resultState;
}
} }
return result.payload.resultState; return TeleportResult.FAILED_TELEPORTER_NOT_RESOLVED;
}); });
} }
@@ -12,7 +12,6 @@ import org.jetbrains.annotations.NotNull;
import java.util.*; import java.util.*;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level; import java.util.logging.Level;
/** /**
@@ -237,7 +236,7 @@ public class TeleportBuilder {
if (plugin.getSettings().crossServer) { if (plugin.getSettings().crossServer) {
return plugin.getNetworkMessenger() return plugin.getNetworkMessenger()
.findPlayer(executor, playerName) .findPlayer(executor, playerName)
.thenApply(foundPlayer -> { .thenApplyAsync(foundPlayer -> {
if (foundPlayer.isEmpty()) { if (foundPlayer.isEmpty()) {
return Optional.empty(); return Optional.empty();
} }
@@ -245,9 +244,7 @@ public class TeleportBuilder {
.sendMessage(executor, new Message(Message.MessageType.POSITION_REQUEST, .sendMessage(executor, new Message(Message.MessageType.POSITION_REQUEST,
executor.username, playerName, MessagePayload.empty(), executor.username, playerName, MessagePayload.empty(),
Message.RelayType.MESSAGE, plugin.getSettings().clusterId)) Message.RelayType.MESSAGE, plugin.getSettings().clusterId))
.orTimeout(3, TimeUnit.SECONDS) .thenApply(reply -> reply.map(message -> message.payload.position)).join();
.exceptionally(throwable -> null)
.thenApply(reply -> Optional.ofNullable(reply == null ? null : reply.payload.position)).join();
}); });
} }
return CompletableFuture.supplyAsync(Optional::empty); return CompletableFuture.supplyAsync(Optional::empty);