Remove server auto-fetching due to instability

This commit is contained in:
William278 committed 2023-02-11 13:12:35 +00:00
1 parent d928ee6ade
commit eb4652d6ff
17 files changed
+43 -161

No files matched your search

@@ -8,7 +8,6 @@ import net.william278.huskhomes.command.BukkitCommand;
import net.william278.huskhomes.command.BukkitCommandType;
import net.william278.huskhomes.command.CommandBase;
import net.william278.huskhomes.command.DisabledCommand;
import net.william278.huskhomes.config.CachedServer;
import net.william278.huskhomes.config.CachedSpawn;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.config.Settings;
@@ -55,7 +54,6 @@ import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.stream.Collectors;
@@ -81,13 +79,11 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
private Set<PluginHook> pluginHooks;
private List<CommandBase> registeredCommands;
private List<Migrator> migrators;
private Server server;
@Nullable
private Messenger messenger;
@Nullable
private Server server;
// Adventure audience
private BukkitAudiences audiences;
@@ -464,35 +460,10 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
@Override
@NotNull
public Server getPluginServer() throws HuskHomesException {
if (server == null) {
throw new HuskHomesException("Attempted to access server when it was not initialized");
}
public Server getServerName() {
return server;
}
@Override
public CompletableFuture<Void> fetchServer(@NotNull OnlineUser requester) {
if (!getSettings().crossServer || this.server != null) {
return CompletableFuture.completedFuture(null);
}
return getMessenger().fetchServerName(requester).orTimeout(5, TimeUnit.SECONDS).exceptionally(throwable -> null).thenAccept(serverName -> {
if (serverName == null) {
throw new HuskHomesException("GetServer plugin message call operation timed out");
}
try {
this.server = new Server(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) {
throw new HuskHomesException("Failed to write cached server name to disk", e);
}
}).exceptionally(throwable -> {
getLoggingAdapter().log(Level.SEVERE, "Failed to fetch and cache server name", throwable);
return null;
});
}
@Override
@NotNull
public List<World> getWorlds() {
@@ -509,14 +480,11 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
final Locales languagePresets = Annotaml.create(Locales.class, Objects.requireNonNull(getResource("locales/" + settings.language + ".yml"))).get();
this.locales = Annotaml.create(new File(getDataFolder(), "messages_" + settings.language + ".yml"), languagePresets).get();
// Load cached server from file
// Load server from file
if (settings.crossServer) {
final File serverFile = new File(getDataFolder(), "server.yml");
if (serverFile.exists()) {
this.server = Annotaml.create(serverFile, CachedServer.class).get().getServer();
}
this.server = Annotaml.create(new File(getDataFolder(), "server.yml"), Server.DEFAULT).get();
} else {
this.server = new Server("server");
this.server = Server.DEFAULT;
}
// Load spawn location from file
@@ -114,7 +114,7 @@ public class HuskHomesAPI extends BaseHuskHomesAPI {
*/
@NotNull
public Server getServer() {
return plugin.getPluginServer();
return plugin.getServerName();
}
}
@@ -17,8 +17,6 @@ import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.*;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.CompletableFuture;
public class BukkitEventListener extends EventListener implements Listener {
public BukkitEventListener(@NotNull BukkitHuskHomes huskHomes) {
@@ -57,7 +55,7 @@ public class BukkitEventListener extends EventListener implements Listener {
final BukkitPlayer bukkitPlayer = BukkitPlayer.adapt(player);
BukkitAdapter.adaptLocation(event.getFrom()).ifPresent(sourceLocation ->
handlePlayerTeleport(bukkitPlayer, new Position(sourceLocation, plugin.getPluginServer())));
handlePlayerTeleport(bukkitPlayer, new Position(sourceLocation, plugin.getServerName())));
}
//todo When defining paper-plugin.yml files gets merged, use the PlayerSetSpawnEvent in the paper module
@@ -78,7 +76,7 @@ public class BukkitEventListener extends EventListener implements Listener {
super.handlePlayerUpdateSpawnPoint(onlineUser, new Position(
adaptedLocation.x, adaptedLocation.y, adaptedLocation.z,
adaptedLocation.yaw, adaptedLocation.pitch,
adaptedLocation.world, plugin.getPluginServer()));
adaptedLocation.world, plugin.getServerName()));
});
}
@@ -59,18 +59,6 @@ public class PluginMessenger extends Messenger implements PluginMessageListener
return future;
}
@Override
@SuppressWarnings("UnstableApiUsage")
public CompletableFuture<String> fetchServerName(@NotNull OnlineUser requester) {
final CompletableFuture<String> future = new CompletableFuture<>();
final BukkitPlayer dispatcher = ((BukkitPlayer) requester);
serverNameRequests.add(future);
final ByteArrayDataOutput messageWriter = ByteStreams.newDataOutput();
messageWriter.writeUTF("GetServer");
dispatcher.sendPluginMessage(BUNGEE_PLUGIN_CHANNEL_NAME, messageWriter.toByteArray());
return future;
}
@Override
@SuppressWarnings("UnstableApiUsage")
public CompletableFuture<String[]> fetchOnlineServerList(@NotNull OnlineUser requester) {
@@ -151,7 +139,7 @@ public class PluginMessenger extends Messenger implements PluginMessageListener
}
@Override
@SuppressWarnings({"UnstableApiUsage", "ForLoopReplaceableByForEach"})
@SuppressWarnings({"UnstableApiUsage"})
public void onPluginMessageReceived(@NotNull String channel, @NotNull org.bukkit.entity.Player player,
final byte[] messageBytes) {
if (!channel.equals(BUNGEE_PLUGIN_CHANNEL_NAME)) {
@@ -180,14 +168,6 @@ public class PluginMessenger extends Messenger implements PluginMessageListener
"Failed to read an inbound plugin message", e);
}
}
case "GetServer" -> {
final String serverName = pluginMessage.readUTF();
for (int i = 0; i < serverNameRequests.size(); i++) {
final CompletableFuture<String> future = serverNameRequests.get(i);
future.complete(serverName);
}
serverNameRequests.clear();
}
case "PlayerList" -> {
pluginMessage.readUTF(); // Read the server name (unused)
handleArrayPluginMessage(pluginMessage, onlinePlayerNamesRequests);
@@ -74,14 +74,14 @@ public class BukkitPlayer extends OnlineUser {
public Position getPosition() {
return new Position(BukkitAdapter.adaptLocation(player.getLocation())
.orElseThrow(() -> new HuskHomesException("Failed to get the position of a BukkitPlayer (null)")),
plugin.getPluginServer());
plugin.getServerName());
}
@Override
public Optional<Position> getBedSpawnPosition() {
return Optional.ofNullable(player.getBedSpawnLocation()).flatMap(BukkitAdapter::adaptLocation)
.map(location -> new Position(location, plugin.getPluginServer()));
.map(location -> new Position(location, plugin.getServerName()));
}
@Override
@@ -192,7 +192,7 @@ public interface HuskHomes {
default CompletableFuture<Optional<? extends Position>> getSpawn() {
return CompletableFuture.supplyAsync(() -> getSettings().crossServer && getSettings().globalSpawn
? getDatabase().getWarp(getSettings().globalSpawnName).join()
: getLocalCachedSpawn().flatMap(spawn -> spawn.getPosition(getPluginServer())));
: getLocalCachedSpawn().flatMap(spawn -> spawn.getPosition(getServerName())));
}
/**
@@ -314,20 +314,9 @@ public interface HuskHomes {
* Returns the {@link Server} the plugin is on
*
* @return The {@link Server} object
* @throws HuskHomesException If the server has not been initialized
*/
@NotNull
Server getPluginServer() throws HuskHomesException;
/**
* Fetches the name of this server if {@link Server} is {@code null} by querying the proxy
*
* @param requester The {@link OnlineUser} to carry out the proxy request
* @return a future completing when the server has been fetched
* @implNote If cross-server mode is disabled, or the server has already been pulled from the server.yml cache file,
* the future will return immediately
*/
CompletableFuture<Void> fetchServer(@NotNull OnlineUser requester);
Server getServerName();
/**
* Returns a resource read from the plugin resources folder
@@ -179,7 +179,7 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
Double.parseDouble(args[3]),
0f, 0f,
args.length >= 5 ? new World(args[4], UUID.randomUUID()) : plugin.getWorlds().get(0),
args.length == 6 ? new Server(args[5]) : plugin.getPluginServer()));
args.length == 6 ? new Server(args[5]) : plugin.getServerName()));
} catch (NumberFormatException e) {
plugin.getLoggingAdapter().log(Level.WARNING, "Invalid syntax. Usage: tp <player> <x> <y> <z> [world] [server]");
return;
@@ -1,34 +0,0 @@
package net.william278.huskhomes.config;
import net.william278.annotaml.YamlFile;
import net.william278.annotaml.YamlKey;
import net.william278.huskhomes.position.Server;
import org.jetbrains.annotations.NotNull;
@YamlFile(header = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Server ID cache. Must match ┃
┃ server name in proxy config. ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛""")
public class CachedServer {
/**
* Name of the server (must match proxy config ID)
*/
@YamlKey("server_name")
public String serverName;
public CachedServer(@NotNull String serverName) {
this.serverName = serverName;
}
@SuppressWarnings("unused")
public CachedServer() {
}
@NotNull
public Server getServer() {
return new Server(serverName);
}
}
@@ -270,7 +270,7 @@ public abstract class Database {
*/
public final CompletableFuture<List<Warp>> getLocalWarps(@NotNull HuskHomes plugin) {
try {
final Server server = plugin.getPluginServer();
final Server server = plugin.getServerName();
return getWarps().thenApplyAsync(warps -> warps.stream()
.filter(warp -> warp.server.equals(server))
.collect(Collectors.toList()));
@@ -297,7 +297,7 @@ public abstract class Database {
*/
public final CompletableFuture<List<Home>> getLocalPublicHomes(@NotNull HuskHomes plugin) {
try {
final Server server = plugin.getPluginServer();
final Server server = plugin.getServerName();
return getPublicHomes().thenApplyAsync(homes -> homes.stream()
.filter(home -> home.server.equals(server))
.collect(Collectors.toList()));
@@ -103,7 +103,7 @@ public abstract class MapHook extends PluginHook {
if (position instanceof Home && !plugin.getSettings().publicHomesOnMap) return false;
try {
return position.server.equals(plugin.getPluginServer());
return position.server.equals(plugin.getServerName());
} catch (HuskHomesException e) {
return plugin.getWorlds().stream()
.map(world -> world.uuid)
@@ -22,9 +22,6 @@ public class EventListener {
@NotNull
protected final HuskHomes plugin;
// Indicates if the first user has joined yet
private boolean firstUser = true;
protected EventListener(@NotNull HuskHomes implementor) {
this.plugin = implementor;
}
@@ -36,7 +33,7 @@ public class EventListener {
*/
protected final void handlePlayerJoin(@NotNull OnlineUser onlineUser) {
// Handle the first player joining the server
cacheServer(onlineUser).thenRun(() -> plugin.getDatabase().ensureUser(onlineUser)
plugin.getDatabase().ensureUser(onlineUser)
// Handle cross-server checks
.thenRun(() -> handleInboundTeleport(onlineUser).thenRun(() -> {
// Update the cached player list
@@ -63,21 +60,7 @@ public class EventListener {
.map(home -> home.meta.name)
.collect(Collectors.toList())));
});
})));
}
/**
* Ensure the server data has been cached locally
*
* @param onlineUser user to handle the checks for
* @return a future returning void when done
*/
private CompletableFuture<Void> cacheServer(@NotNull OnlineUser onlineUser) {
if (plugin.getSettings().crossServer && firstUser) {
firstUser = false;
return plugin.fetchServer(onlineUser);
}
return CompletableFuture.completedFuture(null);
}));
}
/**
@@ -98,7 +81,7 @@ public class EventListener {
if (teleport.get().type == TeleportType.RESPAWN) {
final Optional<Position> bedPosition = onlineUser.getBedSpawnPosition();
if (bedPosition.isEmpty()) {
plugin.getLocalCachedSpawn().flatMap(spawn -> spawn.getPosition(plugin.getPluginServer()))
plugin.getLocalCachedSpawn().flatMap(spawn -> spawn.getPosition(plugin.getServerName()))
.ifPresent(position -> onlineUser.teleportLocally(position, plugin.getSettings().asynchronousTeleports));
onlineUser.sendTranslatableMessage("block.minecraft.spawn.not_valid");
} else {
@@ -173,7 +156,7 @@ public class EventListener {
// Respawn the player cross-server if needed
if (plugin.getSettings().crossServer && plugin.getSettings().globalRespawning) {
plugin.getDatabase().getRespawnPosition(onlineUser).thenAccept(position -> position.ifPresent(respawnPosition -> {
if (!respawnPosition.server.equals(plugin.getPluginServer())) {
if (!respawnPosition.server.equals(plugin.getServerName())) {
Teleport.builder(plugin, onlineUser)
.setType(TeleportType.RESPAWN)
.setTarget(respawnPosition)
@@ -23,11 +23,6 @@ public abstract class Messenger implements AutoCloseable {
*/
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
*/
@@ -60,7 +55,6 @@ public abstract class Messenger implements AutoCloseable {
*/
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;
@@ -94,14 +88,6 @@ public abstract class Messenger implements AutoCloseable {
.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
*
@@ -1,24 +1,36 @@
package net.william278.huskhomes.position;
import net.william278.annotaml.YamlFile;
import net.william278.annotaml.YamlKey;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Represents a server on a proxied network
*/
@YamlFile(header = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Server ID cache. Must match ┃
┃ server name in proxy config. ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛""")
public class Server {
/**
* Default (unknown) server identifier
*/
public static final Server DEFAULT = new Server();
/**
* Proxy-defined name of this server
*/
public String name;
@YamlKey("server_name")
public String name = "server";
public Server(@Nullable String name) {
this.name = (name != null ? name : "server");
public Server(@NotNull String name) {
this.name = name;
}
@SuppressWarnings("unused")
public Server() {
private Server() {
}
@Override
@@ -94,6 +94,6 @@ public class NormalDistributionEngine extends RandomTeleportEngine {
return Optional.empty();
}
}
return location.map(resolved -> new Position(resolved, plugin.getPluginServer()));
return location.map(resolved -> new Position(resolved, plugin.getServerName()));
}
}
@@ -50,10 +50,10 @@ public abstract class RandomTeleportEngine {
if (!spawn.worldUuid.equals(world.uuid.toString())) {
return Optional.empty();
}
return spawn.getPosition(plugin.getPluginServer());
return spawn.getPosition(plugin.getServerName());
})
.orElse(new Position(0d, 128d, 0d, 0f, 0f,
world, plugin.getPluginServer()));
world, plugin.getServerName()));
}
/**
@@ -178,7 +178,7 @@ public class Teleport {
}
// If the target position is local, finalize economy transactions and teleport the player
if (!plugin.getSettings().crossServer || target.server.equals(plugin.getPluginServer())) {
if (!plugin.getSettings().crossServer || target.server.equals(plugin.getServerName())) {
return teleporter.teleportLocally(target, plugin.getSettings().asynchronousTeleports);
}
@@ -118,7 +118,7 @@ public class TeleportBuilder {
* @return The {@link TeleportBuilder} instance
*/
public TeleportBuilder setTarget(@NotNull Location location) {
this.target = CompletableFuture.completedFuture(new Position(location, plugin.getPluginServer()));
this.target = CompletableFuture.completedFuture(new Position(location, plugin.getServerName()));
return this;
}