mirror of
https://github.com/darksaid98/HuskHomes.git
synced 2026-12-02 14:38:52 +00:00
networking/refactor: Rename messages to requests, use builder class
This commit is contained in:
1 parent
10a3eebc55
commit
0c1ad832ea
16 files changed
+429
-342
No files matched your search
@@ -0,0 +1,229 @@
|
||||
package net.william278.huskhomes.network;
|
||||
|
||||
import net.william278.huskhomes.HuskHomes;
|
||||
import net.william278.huskhomes.player.OnlineUser;
|
||||
import net.william278.huskhomes.position.Server;
|
||||
import net.william278.huskhomes.teleport.Teleport;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.logging.Level;
|
||||
|
||||
public abstract class Messenger implements AutoCloseable {
|
||||
|
||||
/**
|
||||
* Name of the network message channel for HuskHomes messages
|
||||
*/
|
||||
public static final String NETWORK_MESSAGE_CHANNEL = "huskhomes:main";
|
||||
|
||||
/**
|
||||
* Map of message UUIDs to messages being processed
|
||||
*/
|
||||
protected HashMap<UUID, CompletableFuture<Request>> processingMessages;
|
||||
|
||||
/**
|
||||
* List of pending futures for processing {@link #fetchServerName(OnlineUser)} requests
|
||||
*/
|
||||
protected List<CompletableFuture<String>> serverNameRequests;
|
||||
|
||||
/**
|
||||
* List of pending futures for processing {@link #getOnlinePlayerNames(OnlineUser)} requests
|
||||
*/
|
||||
protected List<CompletableFuture<String[]>> onlinePlayerNamesRequests;
|
||||
|
||||
/**
|
||||
* List of pending futures for processing {@link #fetchOnlineServerList(OnlineUser)} requests
|
||||
*/
|
||||
protected List<CompletableFuture<String[]>> onlineServersRequests;
|
||||
|
||||
/**
|
||||
* ID of the HuskHomes network cluster this server is on
|
||||
*/
|
||||
protected String clusterId;
|
||||
|
||||
/**
|
||||
* The implementing HuskHomes plugin instance
|
||||
*/
|
||||
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
|
||||
*
|
||||
* @param implementor Instance of the implementing plugin
|
||||
*/
|
||||
public void initialize(@NotNull HuskHomes implementor) {
|
||||
this.processingMessages = new HashMap<>();
|
||||
this.serverNameRequests = new ArrayList<>();
|
||||
this.onlinePlayerNamesRequests = new ArrayList<>();
|
||||
this.onlineServersRequests = new ArrayList<>();
|
||||
this.clusterId = implementor.getSettings().clusterId;
|
||||
this.plugin = implementor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a list of online player usernames from the proxy
|
||||
*
|
||||
* @param requester {@link OnlineUser} to send the request
|
||||
* @return Future returning a {@link List} of usernames of players on the proxy network
|
||||
*/
|
||||
public abstract CompletableFuture<String[]> getOnlinePlayerNames(@NotNull OnlineUser requester);
|
||||
|
||||
/**
|
||||
* Find a player on the proxy network by username to validate if they exist.
|
||||
*
|
||||
* @param requester {@link OnlineUser} to send the request
|
||||
* @param playerName Approximate name of the player to find. If an exact match is not found,
|
||||
* this will attempt to return the closest match
|
||||
* @return Future returning an {@link Optional} of the player's canonical username if found;
|
||||
* otherwise an empty {@link Optional}
|
||||
*/
|
||||
public final CompletableFuture<Optional<String>> findPlayer(@NotNull OnlineUser requester, @NotNull String playerName) {
|
||||
return getOnlinePlayerNames(requester).thenApply(networkedPlayers ->
|
||||
Arrays.stream(networkedPlayers)
|
||||
.filter(user -> user.equalsIgnoreCase(playerName))
|
||||
.findFirst()
|
||||
.or(() -> Arrays.stream(networkedPlayers)
|
||||
.filter(user -> user.toLowerCase().startsWith(playerName))
|
||||
.findFirst()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the name of this server on the proxy network
|
||||
*
|
||||
* @param requester {@link OnlineUser} to send the request
|
||||
* @return Future returning the name of this server on the network
|
||||
*/
|
||||
public abstract CompletableFuture<String> fetchServerName(@NotNull OnlineUser requester);
|
||||
|
||||
/**
|
||||
* Fetch a list of online server names proxy
|
||||
*
|
||||
* @param requester {@link OnlineUser} to send the request
|
||||
* @return Future returning a {@link List} of online servers connected to the proxy network
|
||||
*/
|
||||
public abstract CompletableFuture<String[]> fetchOnlineServerList(@NotNull OnlineUser requester);
|
||||
|
||||
/**
|
||||
* Send a {@link OnlineUser} to a target {@link Server} on the proxy network
|
||||
*
|
||||
* @param server The {@link Server} to send the {@link OnlineUser} to
|
||||
* @return A future, returning {@code true} if the player was sent.<p>
|
||||
* If the player could not be sent (i.e. the server was offline), this will return {@code false}
|
||||
*/
|
||||
public abstract CompletableFuture<Boolean> sendPlayer(@NotNull OnlineUser onlineUser, @NotNull Server server);
|
||||
|
||||
/**
|
||||
* Send a network message
|
||||
*
|
||||
* @param sender {@link OnlineUser} sending the message
|
||||
* @param request {@link Request} to send
|
||||
* @return Future returning the {@link Request} sent, that will time out after
|
||||
* @apiNote This method invokes {@link #dispatchMessage(OnlineUser, Request)}, applying a time-to-live timeOut
|
||||
*/
|
||||
protected final CompletableFuture<Optional<Request>> sendMessage(@NotNull OnlineUser sender, @NotNull Request request) {
|
||||
return dispatchMessage(sender, request)
|
||||
.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(request.getUuid());
|
||||
return Optional.ofNullable(result);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch a {@link Request} via the appropriate handler
|
||||
*
|
||||
* @param sender The {@link OnlineUser} that sent the {@link Request}
|
||||
* @param request The {@link Request} to dispatch
|
||||
* @return A future containing a reply to the {@link Request} that was sent
|
||||
*/
|
||||
protected abstract CompletableFuture<Request> dispatchMessage(@NotNull OnlineUser sender, @NotNull Request request);
|
||||
|
||||
/**
|
||||
* Send a reply to a received {@link Request}
|
||||
*
|
||||
* @param reply The reply {@link Request} to send
|
||||
*/
|
||||
protected abstract void sendReply(@NotNull OnlineUser replier, @NotNull Request reply);
|
||||
|
||||
/**
|
||||
* Handle and action received network {@link Request}s
|
||||
*
|
||||
* @param receiver The online {@link OnlineUser} receiving the message
|
||||
* @param request The received {@link Request}
|
||||
*/
|
||||
protected final void handleMessage(@NotNull OnlineUser receiver, @NotNull Request request) {
|
||||
switch (request.getRelayType()) {
|
||||
// Handle a message and send reply
|
||||
case MESSAGE -> handleRequest(receiver, request);
|
||||
// Handle a reply message
|
||||
case REPLY -> {
|
||||
if (processingMessages.containsKey(request.getUuid())) {
|
||||
final Request finalRequest = request;
|
||||
processingMessages.get(request.getUuid()).completeAsync(() -> finalRequest);
|
||||
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 request The received {@link Request}
|
||||
*/
|
||||
private void handleRequest(@NotNull OnlineUser receiver, @NotNull Request request) {
|
||||
switch (request.getType()) {
|
||||
case TELEPORT_TO_POSITION_REQUEST -> {
|
||||
if (request.getPayload().position != null) {
|
||||
Teleport.builder(plugin, receiver)
|
||||
.setTarget(request.getPayload().position).toTeleport()
|
||||
.thenAccept(teleport -> teleport.execute()
|
||||
.thenAccept(result -> request.reply(receiver,
|
||||
Payload.withTeleportResult(result.getState()), plugin)));
|
||||
return;
|
||||
}
|
||||
request.reply(receiver, Payload.empty(), plugin);
|
||||
}
|
||||
case POSITION_REQUEST -> request.reply(receiver, Payload.withPosition(receiver.getPosition()), plugin);
|
||||
case TELEPORT_REQUEST -> {
|
||||
if (request.getPayload().teleportRequest != null) {
|
||||
request.reply(receiver, plugin.getRequestManager()
|
||||
.sendLocalTeleportRequest(request.getPayload().teleportRequest, receiver)
|
||||
.map(Payload::withTeleportRequest)
|
||||
.orElse(Payload.empty()), plugin);
|
||||
return;
|
||||
}
|
||||
request.reply(receiver, Payload.empty(), plugin);
|
||||
}
|
||||
case TELEPORT_REQUEST_RESPONSE -> {
|
||||
if (request.getPayload().teleportRequest != null) {
|
||||
plugin.getRequestManager().handleLocalRequestResponse(receiver, request.getPayload().teleportRequest);
|
||||
request.reply(receiver, plugin);
|
||||
return;
|
||||
}
|
||||
request.reply(receiver, Payload.empty(), plugin);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the network messenger
|
||||
*/
|
||||
@Override
|
||||
public abstract void close();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package net.william278.huskhomes.network;
|
||||
|
||||
import com.google.gson.annotations.SerializedName;
|
||||
import net.william278.huskhomes.position.Position;
|
||||
import net.william278.huskhomes.request.TeleportRequest;
|
||||
import net.william278.huskhomes.teleport.TeleportResult;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Represents a payload sent in a cross-server {@link Request}
|
||||
*/
|
||||
public class Payload {
|
||||
|
||||
/**
|
||||
* A position field
|
||||
*/
|
||||
@Nullable
|
||||
public Position position;
|
||||
|
||||
/**
|
||||
* A teleport result field
|
||||
*/
|
||||
@Nullable
|
||||
@SerializedName("teleport_result")
|
||||
public TeleportResult resultState;
|
||||
|
||||
/**
|
||||
* A teleport request field
|
||||
*/
|
||||
@Nullable
|
||||
@SerializedName("teleport_request")
|
||||
public TeleportRequest teleportRequest;
|
||||
|
||||
/**
|
||||
* Returns an empty cross-server message payload
|
||||
*
|
||||
* @return an empty payload
|
||||
*/
|
||||
@NotNull
|
||||
public static Payload empty() {
|
||||
return new Payload();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a payload containing a {@link Position}
|
||||
*
|
||||
* @param position the position to send
|
||||
* @return a payload containing the position
|
||||
*/
|
||||
@NotNull
|
||||
public static Payload withPosition(@NotNull Position position) {
|
||||
final Payload payload = new Payload();
|
||||
payload.position = position;
|
||||
return payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a payload containing a {@link TeleportResult}
|
||||
*
|
||||
* @param resultState the teleport to send
|
||||
* @return a payload containing the teleport result
|
||||
*/
|
||||
@NotNull
|
||||
public static Payload withTeleportResult(@NotNull TeleportResult resultState) {
|
||||
final Payload payload = new Payload();
|
||||
payload.resultState = resultState;
|
||||
return payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a payload containing a {@link TeleportRequest}
|
||||
*
|
||||
* @param teleportRequest the teleport to send
|
||||
* @return a payload containing the teleport request
|
||||
*/
|
||||
@NotNull
|
||||
public static Payload withTeleportRequest(@NotNull TeleportRequest teleportRequest) {
|
||||
final Payload payload = new Payload();
|
||||
payload.teleportRequest = teleportRequest;
|
||||
return payload;
|
||||
}
|
||||
|
||||
private Payload() {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package net.william278.huskhomes.network;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.google.gson.annotations.Expose;
|
||||
import com.google.gson.annotations.SerializedName;
|
||||
import net.william278.huskhomes.HuskHomes;
|
||||
import net.william278.huskhomes.player.OnlineUser;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
* A message sent cross-proxy to a player
|
||||
*/
|
||||
public class Request {
|
||||
|
||||
/**
|
||||
* A unique ID representing this message
|
||||
*/
|
||||
@NotNull
|
||||
@Expose
|
||||
private UUID uuid;
|
||||
|
||||
/**
|
||||
* The type of the message
|
||||
*/
|
||||
@NotNull
|
||||
@Expose
|
||||
private MessageType type;
|
||||
|
||||
/**
|
||||
* Represents the context under which this message is being relayed; an outbound {@link RelayType#MESSAGE} or a {@link RelayType#REPLY} to one.
|
||||
*/
|
||||
@SerializedName("relay_type")
|
||||
@NotNull
|
||||
@Expose
|
||||
private RelayType relayType;
|
||||
|
||||
/**
|
||||
* Username of the target player the message is bound for
|
||||
*/
|
||||
@SerializedName("target_player")
|
||||
@NotNull
|
||||
@Expose
|
||||
private String targetPlayer;
|
||||
|
||||
/**
|
||||
* ID of the cluster this message is for
|
||||
*/
|
||||
@SerializedName("cluster_id")
|
||||
@NotNull
|
||||
@Expose
|
||||
private String clusterId;
|
||||
|
||||
/**
|
||||
* Data to send in the message
|
||||
*/
|
||||
@NotNull
|
||||
@Expose
|
||||
private Payload payload;
|
||||
|
||||
/**
|
||||
* Username of the sender of the message
|
||||
*/
|
||||
@NotNull
|
||||
@Expose
|
||||
private String sender;
|
||||
|
||||
protected Request(@NotNull MessageType type, @NotNull String targetPlayer, @NotNull Payload payload,
|
||||
@NotNull Request.RelayType relayType) {
|
||||
this.type = type;
|
||||
this.targetPlayer = targetPlayer;
|
||||
this.payload = payload;
|
||||
this.relayType = relayType;
|
||||
this.uuid = UUID.randomUUID();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private Request() {
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static RequestBuilder builder() {
|
||||
return new RequestBuilder();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String toJson() {
|
||||
return new GsonBuilder().create().toJson(this);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static Request fromJson(@NotNull String json) {
|
||||
return new GsonBuilder().create().fromJson(json, Request.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Identifies the type of message or reply
|
||||
*/
|
||||
public enum MessageType {
|
||||
TELEPORT_TO_POSITION_REQUEST,
|
||||
POSITION_REQUEST,
|
||||
TELEPORT_REQUEST,
|
||||
TELEPORT_REQUEST_RESPONSE
|
||||
}
|
||||
|
||||
/**
|
||||
* Identifies the source of the message being relayed - a {@link RelayType#MESSAGE} or a {@link RelayType#REPLY} to a message.
|
||||
*/
|
||||
public enum RelayType {
|
||||
/**
|
||||
* An outbound message to/from a server
|
||||
*/
|
||||
MESSAGE,
|
||||
/**
|
||||
* A reply to an outbound message
|
||||
*/
|
||||
REPLY
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public UUID getUuid() {
|
||||
return uuid;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public MessageType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public RelayType getRelayType() {
|
||||
return relayType;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getTargetPlayer() {
|
||||
return targetPlayer;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getSender() {
|
||||
return sender;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getClusterId() {
|
||||
return clusterId;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Payload getPayload() {
|
||||
return payload;
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<Request>> send(@NotNull OnlineUser sender, @NotNull HuskHomes plugin) {
|
||||
this.sender = sender.username;
|
||||
this.clusterId = plugin.getSettings().clusterId;
|
||||
return plugin.getMessenger().sendMessage(sender, this);
|
||||
}
|
||||
|
||||
public void reply(@NotNull OnlineUser sender, @NotNull Payload payload, @NotNull HuskHomes plugin) {
|
||||
this.targetPlayer = this.sender;
|
||||
this.sender = sender.username;
|
||||
this.clusterId = plugin.getSettings().clusterId;
|
||||
this.payload = payload;
|
||||
this.relayType = RelayType.REPLY;
|
||||
plugin.getMessenger().sendReply(sender, this);
|
||||
}
|
||||
|
||||
public void reply(@NotNull OnlineUser sender, @NotNull HuskHomes plugin) {
|
||||
this.reply(sender, this.payload, plugin);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(@NotNull Object other) {
|
||||
if (other instanceof Request request) {
|
||||
return request.uuid.equals(this.uuid);
|
||||
}
|
||||
return super.equals(other);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package net.william278.huskhomes.network;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class RequestBuilder {
|
||||
|
||||
private Request.MessageType type;
|
||||
|
||||
private String targetPlayer;
|
||||
|
||||
@NotNull
|
||||
private Payload payload = Payload.empty();
|
||||
|
||||
protected RequestBuilder() {
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public RequestBuilder withType(Request.MessageType type) {
|
||||
this.type = type;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public RequestBuilder withTargetPlayer(String targetPlayer) {
|
||||
this.targetPlayer = targetPlayer;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public RequestBuilder withPayload(Payload payload) {
|
||||
this.payload = payload;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Request build() {
|
||||
return new Request(type, targetPlayer, payload, Request.RelayType.MESSAGE);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user