Refactor #getServer() to be pre-cached from a CachedServer yaml file, no longer require fetcher, add #fetchServer(requester)

This commit is contained in:
William committed 2022-08-31 11:55:47 +01:00
1 parent 800bffbbf2
commit 74cb268426
11 files changed
+105 -45

No files matched your search

@@ -7,9 +7,10 @@ import net.william278.huskhomes.command.BukkitCommand;
import net.william278.huskhomes.command.BukkitCommandType; import net.william278.huskhomes.command.BukkitCommandType;
import net.william278.huskhomes.command.CommandBase; import net.william278.huskhomes.command.CommandBase;
import net.william278.huskhomes.command.DisabledCommand; import net.william278.huskhomes.command.DisabledCommand;
import net.william278.huskhomes.config.CachedServer;
import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.config.Spawn; import net.william278.huskhomes.config.CachedSpawn;
import net.william278.huskhomes.database.Database; import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.database.MySqlDatabase; import net.william278.huskhomes.database.MySqlDatabase;
import net.william278.huskhomes.database.SqLiteDatabase; import net.william278.huskhomes.database.SqLiteDatabase;
@@ -69,7 +70,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
private SavedPositionManager savedPositionManager; private SavedPositionManager savedPositionManager;
private EventListener eventListener; private EventListener eventListener;
private RandomTeleportEngine randomTeleportEngine; private RandomTeleportEngine randomTeleportEngine;
private Spawn serverSpawn; private CachedSpawn serverSpawn;
private EventDispatcher eventDispatcher; private EventDispatcher eventDispatcher;
private Set<PluginHook> pluginHooks; private Set<PluginHook> pluginHooks;
private List<CommandBase> registeredCommands; private List<CommandBase> registeredCommands;
@@ -386,13 +387,13 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
} }
@Override @Override
public Optional<Spawn> getServerSpawn() { public Optional<CachedSpawn> getServerSpawn() {
return Optional.ofNullable(serverSpawn); return Optional.ofNullable(serverSpawn);
} }
@Override @Override
public void setServerSpawn(@NotNull Location location) { public void setServerSpawn(@NotNull Location location) {
final Spawn newSpawn = new Spawn(location); final CachedSpawn newSpawn = new CachedSpawn(location);
this.serverSpawn = newSpawn; this.serverSpawn = newSpawn;
Annotaml.save(newSpawn, new File(getDataFolder(), "spawn.yml")); Annotaml.save(newSpawn, new File(getDataFolder(), "spawn.yml"));
@@ -441,25 +442,31 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
return registeredCommands; return registeredCommands;
} }
/**
* Returns the {@link Server} the plugin is on
*
* @return The {@link Server} object
*/
@Override @Override
@NotNull @NotNull
public Server getServer(@NotNull OnlineUser requester) { public Server getPluginServer() throws HuskHomesException {
if (server != null) { if (server == null) {
return server; throw new HuskHomesException("Attempted to access server when it was not initialized");
}
if (getSettings().crossServer) {
server = getNetworkMessenger().getServerName(requester).thenApply(Server::new).join();
} else {
server = new Server("server");
} }
return server; return server;
} }
public CompletableFuture<Void> fetchServer(@NotNull OnlineUser requester) {
if (!getSettings().crossServer) {
return CompletableFuture.completedFuture(null);
}
if (server == null) {
return getNetworkMessenger().getServerName(requester).thenAccept(serverName -> {
// Set the server name
this.server = new Server(serverName);
// Cache the server to the server.yml file
Annotaml.save(new CachedServer(serverName), new File(getDataFolder(), "server.yml"));
});
}
return CompletableFuture.completedFuture(null);
}
@Override @Override
public @NotNull List<World> getWorlds() { public @NotNull List<World> getWorlds() {
return getServer().getWorlds().stream().filter(world -> BukkitAdapter.adaptWorld(world).isPresent()) return getServer().getWorlds().stream().filter(world -> BukkitAdapter.adaptWorld(world).isPresent())
@@ -476,10 +483,20 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
Objects.requireNonNull(resourceReader.getResource("locales/" + settings.language + ".yml")), Objects.requireNonNull(resourceReader.getResource("locales/" + settings.language + ".yml")),
Locales.class, Annotaml.LoaderOptions.builder().copyDefaults(true)); Locales.class, Annotaml.LoaderOptions.builder().copyDefaults(true));
// Load cached server from file
if (settings.crossServer) {
final File serverFile = new File(getDataFolder(), "server.yml");
if (serverFile.exists()) {
this.server = Annotaml.load(serverFile, CachedServer.class).getServer();
}
} else {
this.server = new Server("server");
}
// Load spawn location from file // Load spawn location from file
final File spawnFile = new File(getDataFolder(), "spawn.yml"); final File spawnFile = new File(getDataFolder(), "spawn.yml");
if (spawnFile.exists()) { if (spawnFile.exists()) {
this.serverSpawn = Annotaml.load(spawnFile, Spawn.class); this.serverSpawn = Annotaml.load(spawnFile, CachedSpawn.class);
} }
return true; return true;
}).exceptionally(throwable -> { }).exceptionally(throwable -> {
@@ -107,14 +107,14 @@ public class HuskHomesAPI extends BaseHuskHomesAPI {
} }
/** /**
* Get this {@link Server}. * Get the {@link Server}, containing the ID of the server the plugin is running on
* *
* @param requester a player; needed to send a plugin message requesting the server if it has not been cached
* @return the {@link Server} * @return the {@link Server}
* @since 3.0
*/ */
@NotNull @NotNull
public Server getServer(@NotNull OnlineUser requester) { public Server getServer() {
return plugin.getServer(requester); return plugin.getPluginServer();
} }
} }
@@ -58,7 +58,7 @@ public class BukkitEventListener extends EventListener implements Listener {
CompletableFuture.runAsync(() -> { CompletableFuture.runAsync(() -> {
final BukkitPlayer bukkitPlayer = BukkitPlayer.adapt(player); final BukkitPlayer bukkitPlayer = BukkitPlayer.adapt(player);
BukkitAdapter.adaptLocation(event.getFrom()).ifPresent(sourceLocation -> BukkitAdapter.adaptLocation(event.getFrom()).ifPresent(sourceLocation ->
handlePlayerTeleport(bukkitPlayer, new Position(sourceLocation, plugin.getServer(bukkitPlayer)))); handlePlayerTeleport(bukkitPlayer, new Position(sourceLocation, plugin.getPluginServer())));
}); });
} }
@@ -80,7 +80,7 @@ public class BukkitEventListener extends EventListener implements Listener {
super.handlePlayerUpdateSpawnPoint(onlineUser, new Position( super.handlePlayerUpdateSpawnPoint(onlineUser, new Position(
adaptedLocation.x, adaptedLocation.y, adaptedLocation.z, adaptedLocation.x, adaptedLocation.y, adaptedLocation.z,
adaptedLocation.yaw, adaptedLocation.pitch, adaptedLocation.yaw, adaptedLocation.pitch,
adaptedLocation.world, plugin.getServer(onlineUser))); adaptedLocation.world, plugin.getPluginServer()));
})); }));
} }
@@ -65,14 +65,14 @@ public class BukkitPlayer extends OnlineUser {
public Position getPosition() { public Position getPosition() {
return new Position(BukkitAdapter.adaptLocation(player.getLocation()) return new Position(BukkitAdapter.adaptLocation(player.getLocation())
.orElseThrow(() -> new HuskHomesException("Failed to get the position of a BukkitPlayer (null)")), .orElseThrow(() -> new HuskHomesException("Failed to get the position of a BukkitPlayer (null)")),
BukkitHuskHomes.getInstance().getServer(this)); BukkitHuskHomes.getInstance().getPluginServer());
} }
@Override @Override
public Optional<Position> getBedSpawnPosition() { public Optional<Position> getBedSpawnPosition() {
return Optional.ofNullable(player.getBedSpawnLocation()).flatMap(BukkitAdapter::adaptLocation) return Optional.ofNullable(player.getBedSpawnLocation()).flatMap(BukkitAdapter::adaptLocation)
.map(location -> new Position(location, BukkitHuskHomes.getInstance().getServer(this))); .map(location -> new Position(location, BukkitHuskHomes.getInstance().getPluginServer()));
} }
@Override @Override
@@ -5,7 +5,7 @@ import net.william278.desertwell.Version;
import net.william278.huskhomes.command.CommandBase; import net.william278.huskhomes.command.CommandBase;
import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.config.Spawn; import net.william278.huskhomes.config.CachedSpawn;
import net.william278.huskhomes.database.Database; import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.event.EventDispatcher; import net.william278.huskhomes.event.EventDispatcher;
import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.hook.EconomyHook;
@@ -165,11 +165,11 @@ public interface HuskHomes {
List<Migrator> getMigrators(); List<Migrator> getMigrators();
/** /**
* The {@link Spawn} location of this server * The {@link CachedSpawn} location of this server
* *
* @return the {@link Spawn} location data * @return the {@link CachedSpawn} location data
*/ */
Optional<Spawn> getServerSpawn(); Optional<CachedSpawn> getServerSpawn();
/** /**
* Returns a future returning the latest plugin {@link Version} if the plugin is out-of-date * Returns a future returning the latest plugin {@link Version} if the plugin is out-of-date
@@ -188,9 +188,9 @@ public interface HuskHomes {
} }
/** /**
* Update the {@link Spawn} position to a location on the server * Update the {@link CachedSpawn} position to a location on the server
* *
* @param location the new {@link Spawn} location * @param location the new {@link CachedSpawn} location
*/ */
void setServerSpawn(@NotNull Location location); void setServerSpawn(@NotNull Location location);
@@ -270,12 +270,23 @@ public interface HuskHomes {
CompletableFuture<Optional<Location>> getSafeGroundLocation(@NotNull Location location); CompletableFuture<Optional<Location>> getSafeGroundLocation(@NotNull Location location);
/** /**
* Get the {@link Server} this server is on * Returns the {@link Server} the plugin is on
* *
* @return The server * @return The {@link Server} object
* @throws HuskHomesException If the server has not been initialized
*/ */
@NotNull @NotNull
Server getServer(@NotNull OnlineUser requester); 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);
/** /**
* Returns a resource read from the plugin resources folder * Returns a resource read from the plugin resources folder
@@ -26,7 +26,7 @@ public class SpawnCommand extends CommandBase {
CompletableFuture.runAsync(() -> { CompletableFuture.runAsync(() -> {
final Optional<? extends Position> position = (plugin.getSettings().crossServer && plugin.getSettings().globalSpawn final Optional<? extends Position> position = (plugin.getSettings().crossServer && plugin.getSettings().globalSpawn
? plugin.getDatabase().getWarp(plugin.getSettings().globalSpawnName).join() ? plugin.getDatabase().getWarp(plugin.getSettings().globalSpawnName).join()
: plugin.getServerSpawn().flatMap(spawn -> spawn.getLocation(plugin.getServer(onlineUser)))); : plugin.getServerSpawn().flatMap(spawn -> spawn.getLocation(plugin.getPluginServer())));
if (position.isEmpty()) { if (position.isEmpty()) {
plugin.getLocales().getLocale("error_spawn_not_set").ifPresent(onlineUser::sendMessage); plugin.getLocales().getLocale("error_spawn_not_set").ifPresent(onlineUser::sendMessage);
return; return;
@@ -173,7 +173,7 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
Double.parseDouble(args[3]), Double.parseDouble(args[3]),
0f, 0f, 0f, 0f,
args.length >= 5 ? new World(args[4], UUID.randomUUID()) : plugin.getWorlds().get(0), args.length >= 5 ? new World(args[4], UUID.randomUUID()) : plugin.getWorlds().get(0),
args.length == 6 ? new Server(args[5]) : plugin.getServer(playerToTeleport))); args.length == 6 ? new Server(args[5]) : plugin.getPluginServer()));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
plugin.getLoggingAdapter().log(Level.WARNING, "Invalid syntax. Usage: tp <player> <x> <y> <z> [world] [server]"); plugin.getLoggingAdapter().log(Level.WARNING, "Invalid syntax. Usage: tp <player> <x> <y> <z> [world] [server]");
return; return;
@@ -0,0 +1,32 @@
package net.william278.huskhomes.config;
import net.william278.annotaml.YamlFile;
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)
*/
public String serverName;
public CachedServer(@NotNull String serverName) {
this.serverName = serverName;
}
@SuppressWarnings("unused")
public CachedServer() {
}
@NotNull
public Server getServer() {
return new Server(serverName);
}
}
@@ -15,10 +15,10 @@ import java.util.UUID;
*/ */
@YamlFile(header = """ @YamlFile(header = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Server /spawn location ┃ ┃ Server /spawn location cache ┃
┃ Edit in-game using /setspawn ┃ ┃ Edit in-game using /setspawn ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛""") ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛""")
public class Spawn { public class CachedSpawn {
public double x; public double x;
public double y; public double y;
@@ -47,7 +47,7 @@ public class Spawn {
* *
* @param location The {@link Location} of the spawn * @param location The {@link Location} of the spawn
*/ */
public Spawn(@NotNull Location location) { public CachedSpawn(@NotNull Location location) {
this.x = location.x; this.x = location.x;
this.y = location.y; this.y = location.y;
this.z = location.z; this.z = location.z;
@@ -58,6 +58,6 @@ public class Spawn {
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")
public Spawn() { public CachedSpawn() {
} }
} }
@@ -38,8 +38,8 @@ public class EventListener {
// Handle the first player joining the server // Handle the first player joining the server
CompletableFuture.runAsync(() -> { CompletableFuture.runAsync(() -> {
if (firstUser) { if (firstUser) {
plugin.getServer(onlineUser);
firstUser = false; firstUser = false;
plugin.fetchServer(onlineUser).join();
} }
}).thenRun(() -> { }).thenRun(() -> {
// Ensure the player is present on the database first // Ensure the player is present on the database first
@@ -52,7 +52,7 @@ public class EventListener {
if (activeTeleport.type == TeleportType.RESPAWN) { if (activeTeleport.type == TeleportType.RESPAWN) {
final Optional<Position> bedPosition = onlineUser.getBedSpawnPosition(); final Optional<Position> bedPosition = onlineUser.getBedSpawnPosition();
if (bedPosition.isEmpty()) { if (bedPosition.isEmpty()) {
plugin.getServerSpawn().flatMap(spawn -> spawn.getLocation(plugin.getServer(onlineUser))) plugin.getServerSpawn().flatMap(spawn -> spawn.getLocation(plugin.getPluginServer()))
.ifPresent(position -> onlineUser.teleport(position, plugin.getSettings().asynchronousTeleports)); .ifPresent(position -> onlineUser.teleport(position, plugin.getSettings().asynchronousTeleports));
onlineUser.sendMinecraftMessage("block.minecraft.spawn.not_valid"); onlineUser.sendMinecraftMessage("block.minecraft.spawn.not_valid");
} else { } else {
@@ -155,7 +155,7 @@ public class EventListener {
// Respawn the player cross-server if needed // Respawn the player cross-server if needed
if (plugin.getSettings().crossServer && plugin.getSettings().globalRespawning) { if (plugin.getSettings().crossServer && plugin.getSettings().globalRespawning) {
plugin.getDatabase().getRespawnPosition(onlineUser).thenAccept(position -> position.ifPresent(respawnPosition -> { plugin.getDatabase().getRespawnPosition(onlineUser).thenAccept(position -> position.ifPresent(respawnPosition -> {
if (!respawnPosition.server.equals(plugin.getServer(onlineUser))) { if (!respawnPosition.server.equals(plugin.getPluginServer())) {
plugin.getTeleportManager().teleport(onlineUser, respawnPosition, TeleportType.RESPAWN).thenAccept( plugin.getTeleportManager().teleport(onlineUser, respawnPosition, TeleportType.RESPAWN).thenAccept(
result -> plugin.getTeleportManager().finishTeleport(onlineUser, result)); result -> plugin.getTeleportManager().finishTeleport(onlineUser, result));
} }
@@ -354,7 +354,7 @@ public class TeleportManager {
} }
// Teleport player locally, or across server depending on need // Teleport player locally, or across server depending on need
if (position.server.equals(plugin.getServer(onlineUser))) { if (position.server.equals(plugin.getPluginServer())) {
return onlineUser.teleport(teleport.target, plugin.getSettings().asynchronousTeleports); return onlineUser.teleport(teleport.target, plugin.getSettings().asynchronousTeleports);
} else { } else {
return teleportCrossServer(onlineUser, teleport); return teleportCrossServer(onlineUser, teleport);