mirror of
https://github.com/darksaid98/HuskHomes.git
synced 2026-12-02 22:17:17 +00:00
Networking rework, further refactoring
This commit is contained in:
1 parent
1cebdac9b8
commit
4c90e5498c
88 files changed
+1116
-1364
No files matched your search
@@ -0,0 +1,142 @@
|
||||
package net.william278.huskhomes.network;
|
||||
|
||||
import net.william278.huskhomes.HuskHomes;
|
||||
import net.william278.huskhomes.request.TeleportRequest;
|
||||
import net.william278.huskhomes.user.OnlineUser;
|
||||
import net.william278.huskhomes.teleport.Teleport;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public abstract class Broker {
|
||||
|
||||
protected final HuskHomes plugin;
|
||||
private final Map<UUID, CompletableFuture<Message>> outboundMessages = new HashMap<>();
|
||||
|
||||
/**
|
||||
* Create a new broker
|
||||
*
|
||||
* @param plugin the HuskTowns plugin instance
|
||||
*/
|
||||
protected Broker(@NotNull HuskHomes plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an inbound {@link Message}
|
||||
*
|
||||
* @param receiver The user who received the message, if a receiver exists
|
||||
* @param message The message
|
||||
*/
|
||||
protected void handle(@Nullable OnlineUser receiver, @NotNull Message message) {
|
||||
if (message.getSourceServer().equals(getServer()) || receiver == null) {
|
||||
return;
|
||||
}
|
||||
if (message.getDirection() == Message.Direction.INBOUND) {
|
||||
this.outboundMessages.getOrDefault(message.getUuid(), new CompletableFuture<>()).complete(message);
|
||||
this.outboundMessages.remove(message.getUuid());
|
||||
return;
|
||||
}
|
||||
switch (message.getType()) {
|
||||
case TELEPORT_TO_POSITION_REQUEST -> {
|
||||
if (message.getPayload().getPosition() != null) {
|
||||
Teleport.builder(plugin, receiver)
|
||||
.setTarget(message.getPayload().getPosition()).toTeleport()
|
||||
.thenAccept(teleport -> teleport.execute()
|
||||
.thenAccept(result -> message.reply(
|
||||
this,
|
||||
receiver,
|
||||
Payload.withTeleportResult(result.getState())
|
||||
)));
|
||||
return;
|
||||
}
|
||||
}
|
||||
case POSITION_REQUEST -> message.reply(this, receiver, Payload.withPosition(receiver.getPosition()));
|
||||
case TELEPORT_REQUEST -> {
|
||||
if (message.getPayload().getTeleportRequest() != null) {
|
||||
message.reply(this, receiver, plugin.getRequestManager()
|
||||
.sendLocalTeleportRequest(message.getPayload().getTeleportRequest(), receiver)
|
||||
.map(Payload::withTeleportRequest)
|
||||
.orElse(Payload.empty()));
|
||||
return;
|
||||
}
|
||||
message.reply(this, receiver, Payload.empty());
|
||||
}
|
||||
case TELEPORT_REQUEST_RESPONSE -> {
|
||||
if (message.getPayload().getTeleportRequest() != null) {
|
||||
final TeleportRequest request = message.getPayload().getTeleportRequest();
|
||||
plugin.getRequestManager().handleLocalRequestResponse(receiver, request);
|
||||
message.reply(this, receiver, Payload.withTeleportRequest(request));
|
||||
return;
|
||||
}
|
||||
message.reply(this, receiver, Payload.empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the message broker
|
||||
*
|
||||
* @throws RuntimeException if the broker fails to initialize
|
||||
*/
|
||||
public abstract void initialize() throws RuntimeException;
|
||||
|
||||
/**
|
||||
* Send a message to the broker
|
||||
*
|
||||
* @param message the message to send
|
||||
* @param sender the sender of the message
|
||||
*/
|
||||
protected abstract void send(@NotNull Message message, @NotNull OnlineUser sender);
|
||||
|
||||
/**
|
||||
* Move an {@link OnlineUser} to a new server on the proxy network
|
||||
*
|
||||
* @param user the user to move
|
||||
* @param server the server to move the user to
|
||||
*/
|
||||
public abstract void changeServer(@NotNull OnlineUser user, @NotNull String server);
|
||||
|
||||
@NotNull
|
||||
protected Map<UUID, CompletableFuture<Message>> getOutboundMessages() {
|
||||
return outboundMessages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Terminate the broker
|
||||
*/
|
||||
public abstract void close();
|
||||
|
||||
@NotNull
|
||||
protected String getSubChannelId() {
|
||||
final String version = plugin.getVersion().getMajor() + "." + plugin.getVersion().getMinor();
|
||||
return plugin.getKey(plugin.getSettings().getClusterId(), version).asString();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
protected String getServer() {
|
||||
return plugin.getServerName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Identifies types of message brokers
|
||||
*/
|
||||
public enum Type {
|
||||
PLUGIN_MESSAGE("Plugin Messages"),
|
||||
REDIS("Redis");
|
||||
@NotNull
|
||||
private final String displayName;
|
||||
|
||||
Type(@NotNull String displayName) {
|
||||
this.displayName = displayName;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package net.william278.huskhomes.network;
|
||||
|
||||
import com.google.gson.annotations.Expose;
|
||||
import net.william278.huskhomes.user.OnlineUser;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
* Represents a message sent by a {@link Broker} cross-server. See {@link #builder()} for
|
||||
* a builder to create a message.
|
||||
*/
|
||||
public class Message {
|
||||
|
||||
public static final String TARGET_ALL = "ALL";
|
||||
|
||||
@Expose
|
||||
private UUID id;
|
||||
@Expose
|
||||
private Type type;
|
||||
@Expose
|
||||
private String target;
|
||||
@Expose
|
||||
private Payload payload;
|
||||
@Expose
|
||||
private String sender;
|
||||
@Expose
|
||||
private String sourceServer;
|
||||
@Expose
|
||||
private Direction direction;
|
||||
|
||||
private Message(@NotNull Type type, @NotNull String target, @NotNull Payload payload) {
|
||||
this.type = type;
|
||||
this.target = target;
|
||||
this.payload = payload;
|
||||
this.id = UUID.randomUUID();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private Message() {
|
||||
}
|
||||
|
||||
public static Builder builder() {
|
||||
return new Builder();
|
||||
}
|
||||
|
||||
public CompletableFuture<Message> send(@NotNull Broker broker, @NotNull OnlineUser sender) {
|
||||
this.sender = sender.getUsername();
|
||||
this.sourceServer = broker.getServer();
|
||||
this.direction = Direction.OUTBOUND;
|
||||
final CompletableFuture<Message> future = new CompletableFuture<>();
|
||||
broker.getOutboundMessages().put(getUuid(), future);
|
||||
broker.send(this, sender);
|
||||
return future;
|
||||
}
|
||||
|
||||
public void reply(@NotNull Broker broker, @NotNull OnlineUser receiver, @NotNull Payload payload) {
|
||||
this.sender = receiver.getUsername();
|
||||
this.sourceServer = broker.getServer();
|
||||
this.direction = Direction.INBOUND;
|
||||
this.payload = payload;
|
||||
broker.send(this, receiver);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Type getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getTarget() {
|
||||
return target;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Payload getPayload() {
|
||||
return payload;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getSender() {
|
||||
return sender;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getSourceServer() {
|
||||
return sourceServer;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Direction getDirection() {
|
||||
return direction;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public UUID getUuid() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builder for {@link Message}s
|
||||
*/
|
||||
public static class Builder {
|
||||
private Type type;
|
||||
private Payload payload = Payload.empty();
|
||||
private String target;
|
||||
|
||||
private Builder() {
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Builder type(@NotNull Type type) {
|
||||
this.type = type;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Builder payload(@NotNull Payload payload) {
|
||||
this.payload = payload;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Builder target(@NotNull String target) {
|
||||
this.target = target;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Message build() {
|
||||
return new Message(type, target, payload);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Different types of cross-server messages
|
||||
*/
|
||||
public enum Type {
|
||||
TELEPORT_TO_POSITION_REQUEST,
|
||||
POSITION_REQUEST,
|
||||
TELEPORT_REQUEST,
|
||||
POSITION_RESPONSE, TELEPORT_REQUEST_RESPONSE
|
||||
}
|
||||
|
||||
public enum Direction {
|
||||
/**
|
||||
* The message is being sent from the sender to the target
|
||||
*/
|
||||
OUTBOUND,
|
||||
/**
|
||||
* The message is being sent from the target to the sender
|
||||
*/
|
||||
INBOUND
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,215 +0,0 @@
|
||||
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 #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.onlinePlayerNamesRequests = new ArrayList<>();
|
||||
this.onlineServersRequests = new ArrayList<>();
|
||||
this.clusterId = implementor.getSettings().getClusterId();
|
||||
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 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();
|
||||
|
||||
}
|
||||
@@ -12,25 +12,16 @@ import org.jetbrains.annotations.Nullable;
|
||||
*/
|
||||
public class Payload {
|
||||
|
||||
/**
|
||||
* A position field
|
||||
*/
|
||||
@Nullable
|
||||
public Position position;
|
||||
private Position position;
|
||||
|
||||
/**
|
||||
* A teleport result field
|
||||
*/
|
||||
@Nullable
|
||||
@SerializedName("teleport_result")
|
||||
public TeleportResult resultState;
|
||||
private TeleportResult resultState;
|
||||
|
||||
/**
|
||||
* A teleport request field
|
||||
*/
|
||||
@Nullable
|
||||
@SerializedName("teleport_request")
|
||||
public TeleportRequest teleportRequest;
|
||||
private TeleportRequest teleportRequest;
|
||||
|
||||
/**
|
||||
* Returns an empty cross-server message payload
|
||||
@@ -84,4 +75,27 @@ public class Payload {
|
||||
private Payload() {
|
||||
}
|
||||
|
||||
/**
|
||||
* A position field
|
||||
*/
|
||||
@Nullable
|
||||
public Position getPosition() {
|
||||
return position;
|
||||
}
|
||||
|
||||
/**
|
||||
* A teleport result field
|
||||
*/
|
||||
@Nullable
|
||||
public TeleportResult getResultState() {
|
||||
return resultState;
|
||||
}
|
||||
|
||||
/**
|
||||
* A teleport request field
|
||||
*/
|
||||
@Nullable
|
||||
public TeleportRequest getTeleportRequest() {
|
||||
return teleportRequest;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package net.william278.huskhomes.network;
|
||||
|
||||
import com.google.common.io.ByteArrayDataInput;
|
||||
import com.google.common.io.ByteArrayDataOutput;
|
||||
import com.google.common.io.ByteStreams;
|
||||
import net.william278.huskhomes.HuskHomes;
|
||||
import net.william278.huskhomes.user.OnlineUser;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
|
||||
/**
|
||||
* <a href="https://www.spigotmc.org/wiki/bukkit-bungee-plugin-messaging-channel/">Plugin Messaging channel</a> message
|
||||
* broker implementation
|
||||
*/
|
||||
public class PluginMessageBroker extends Broker {
|
||||
|
||||
/**
|
||||
* The name of BungeeCord's provided plugin channel.
|
||||
*
|
||||
* @implNote Technically, the effective identifier of this channel is {@code bungeecord:main}, but Spigot remaps
|
||||
* {@code BungeeCord} automatically to the new one (<a href="https://wiki.vg/Plugin_channels#bungeecord:main">source</a>).
|
||||
* Spigot's <a href="https://www.spigotmc.org/wiki/bukkit-bungee-plugin-messaging-channel/">official documentation</a>
|
||||
* still instructs usage of {@code BungeeCord} as the name to use, however. It's all a bit inconsistent, so just in case
|
||||
* it's best to leave it how it is for to maintain backwards compatibility.
|
||||
*/
|
||||
public static final String BUNGEE_CHANNEL_ID = "BungeeCord";
|
||||
|
||||
public PluginMessageBroker(@NotNull HuskHomes plugin) {
|
||||
super(plugin);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initialize() throws RuntimeException {
|
||||
plugin.initializePluginChannels();
|
||||
}
|
||||
|
||||
@SuppressWarnings("UnstableApiUsage")
|
||||
public final void onReceive(@NotNull String channel, @NotNull OnlineUser user, byte[] message) {
|
||||
if (!channel.equals(BUNGEE_CHANNEL_ID)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final ByteArrayDataInput inputStream = ByteStreams.newDataInput(message);
|
||||
final String subChannelId = inputStream.readUTF();
|
||||
if (!subChannelId.equals(getSubChannelId())) {
|
||||
return;
|
||||
}
|
||||
|
||||
short messageLength = inputStream.readShort();
|
||||
byte[] messageBody = new byte[messageLength];
|
||||
inputStream.readFully(messageBody);
|
||||
|
||||
try (final DataInputStream messageReader = new DataInputStream(new ByteArrayInputStream(messageBody))) {
|
||||
super.handle(user, plugin.getGson().fromJson(messageReader.readUTF(), Message.class));
|
||||
} catch (IOException e) {
|
||||
plugin.getLoggingAdapter().log(Level.SEVERE, "Failed to fully read plugin message", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("UnstableApiUsage")
|
||||
protected void send(@NotNull Message message, @NotNull OnlineUser sender) {
|
||||
final ByteArrayDataOutput messageWriter = ByteStreams.newDataOutput();
|
||||
messageWriter.writeUTF("ForwardToPlayer");
|
||||
messageWriter.writeUTF(message.getTarget());
|
||||
messageWriter.writeUTF(getSubChannelId());
|
||||
|
||||
// Write the plugin message
|
||||
try (final ByteArrayOutputStream messageByteStream = new ByteArrayOutputStream()) {
|
||||
try (DataOutputStream messageDataStream = new DataOutputStream(messageByteStream)) {
|
||||
messageDataStream.writeUTF(plugin.getGson().toJson(message));
|
||||
messageWriter.writeShort(messageByteStream.toByteArray().length);
|
||||
messageWriter.write(messageByteStream.toByteArray());
|
||||
}
|
||||
} catch (IOException e) {
|
||||
plugin.getLoggingAdapter().log(Level.SEVERE, "Exception dispatching plugin message", e);
|
||||
return;
|
||||
}
|
||||
|
||||
sender.sendPluginMessage(BUNGEE_CHANNEL_ID, messageWriter.toByteArray());
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("UnstableApiUsage")
|
||||
public void changeServer(@NotNull OnlineUser user, @NotNull String server) {
|
||||
final ByteArrayDataOutput outputStream = ByteStreams.newDataOutput();
|
||||
|
||||
outputStream.writeUTF("Connect");
|
||||
outputStream.writeUTF(server);
|
||||
|
||||
user.sendPluginMessage(BUNGEE_CHANNEL_ID, outputStream.toByteArray());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package net.william278.huskhomes.network;
|
||||
|
||||
import net.william278.huskhomes.HuskHomes;
|
||||
import net.william278.huskhomes.user.OnlineUser;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.JedisPool;
|
||||
import redis.clients.jedis.JedisPoolConfig;
|
||||
import redis.clients.jedis.JedisPubSub;
|
||||
|
||||
import java.util.logging.Level;
|
||||
|
||||
/**
|
||||
* Redis message broker implementation
|
||||
*/
|
||||
public class RedisBroker extends PluginMessageBroker {
|
||||
private JedisPool jedisPool;
|
||||
|
||||
public RedisBroker(@NotNull HuskHomes plugin) {
|
||||
super(plugin);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initialize() throws RuntimeException {
|
||||
super.initialize();
|
||||
|
||||
final String password = plugin.getSettings().getRedisPassword();
|
||||
final String host = plugin.getSettings().getRedisHost();
|
||||
final int port = plugin.getSettings().getRedisPort();
|
||||
final boolean useSSL = plugin.getSettings().useRedisSsl();
|
||||
|
||||
this.jedisPool = password.isEmpty() ? new JedisPool(new JedisPoolConfig(), host, port, 0, useSSL)
|
||||
: new JedisPool(new JedisPoolConfig(), host, port, 0, password, useSSL);
|
||||
|
||||
new Thread(getSubscriber(), plugin.getKey("redis_subscriber").toString()).start();
|
||||
|
||||
plugin.getLoggingAdapter().log(Level.INFO, "Initialized Redis connection pool");
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private Runnable getSubscriber() {
|
||||
return () -> {
|
||||
try (Jedis jedis = jedisPool.getResource()) {
|
||||
jedis.subscribe(new JedisPubSub() {
|
||||
@Override
|
||||
public void onMessage(@NotNull String channel, @NotNull String encodedMessage) {
|
||||
if (!channel.equals(getSubChannelId())) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Message message = plugin.getGson().fromJson(encodedMessage, Message.class);
|
||||
plugin.getOnlineUsers().stream()
|
||||
.filter(online -> online.getUsername().equalsIgnoreCase(message.getTarget()))
|
||||
.findFirst()
|
||||
.ifPresent(receiver -> handle(receiver, message));
|
||||
}
|
||||
}, getSubChannelId());
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void send(@NotNull Message message, @NotNull OnlineUser sender) {
|
||||
try (Jedis jedis = jedisPool.getResource()) {
|
||||
jedis.publish(getSubChannelId(), plugin.getGson().toJson(message));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
super.close();
|
||||
if (jedisPool != null) {
|
||||
jedisPool.close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,185 +0,0 @@
|
||||
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().getClusterId();
|
||||
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().getClusterId();
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
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