Author SHA1 Message Date
Ronan 74cd1145e0 Merge master into PR 268 while preserving startup fixes 2026-11-23 16:11:39 +01:00
RonanCraft a9e821497c Online editor (#267)
* web editor

* editor command help

* editor sync cmd

* removed same user restriction

* removed player executed restriction

* no server identifier sent to server

* editor url updated

* config harsher verification + send world names to editor api

* no more session controls

* addons editor commands

* moved rtp to /betterrtp-core to create a better env for maven compiling

* bettersync lib

* Own core and addon editor schemas with BetterSync validation

* Simplify editor metadata and publish core and addon schemas on release

* Release core and addons together using their Maven versions

* Exclude unavailable ProtocolLib executor snapshot from Addons build

* betterrtp compiling

* log upload commands fixed - upload to mclo.gs website

* Fix deferred player lookups retaining disconnected sessions (#265)

* Fix RTP operation retention on cancellation and failure (#266)
2026-11-23 10:07:25 -05:00
Ronan 606510754e start up fix 2026-11-20 22:23:43 +01:00
RonanCraft 36289b31af Fix RTP operation retention on cancellation and failure 2026-11-18 16:58:31 -05:00
RonanCraft 76fc1ffe9b Fix deferred player lookups retaining disconnected sessions (#265) 2026-11-18 16:37:14 -05:00
RonanCraft c8c5a04a59 Online editor + auto deployment/releases (#264)
* web editor

* editor command help

* editor sync cmd

* removed same user restriction

* removed player executed restriction

* no server identifier sent to server

* editor url updated

* config harsher verification + send world names to editor api

* no more session controls

* addons editor commands

* moved rtp to /betterrtp-core to create a better env for maven compiling

* bettersync lib

* Own core and addon editor schemas with BetterSync validation

* Simplify editor metadata and publish core and addon schemas on release

* Release core and addons together using their Maven versions

* Exclude unavailable ProtocolLib executor snapshot from Addons build

* betterrtp compiling
2026-11-12 14:17:03 -05:00
35 changed files with 1251 additions and 218 deletions

No files matched your search

+2 -2
View File
@@ -1,7 +1,7 @@
name: Release BetterRTP Maven version name: Release BetterRTP Maven version
on: on:
push: push:
branches: [online-editor] branches: [master]
workflow_dispatch: workflow_dispatch:
permissions: permissions:
contents: write contents: write
@@ -10,7 +10,7 @@ concurrency:
cancel-in-progress: false cancel-in-progress: false
jobs: jobs:
release: release:
if: github.ref == 'refs/heads/online-editor' if: github.ref == 'refs/heads/master'
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
+3 -1
View File
@@ -18,4 +18,6 @@ jobs:
run: cp settings.xml $HOME/.m2/settings.xml run: cp settings.xml $HOME/.m2/settings.xml
- name: Build and test with Maven - name: Build and test with Maven
run: mvn -B -pl :BetterRTP test run: |
mvn -B -pl :BetterRTP verify
mvn -B -f tests/editor/pom.xml verify
+4 -1
View File
@@ -7,7 +7,7 @@
<groupId>me.SuperRonanCraft</groupId> <groupId>me.SuperRonanCraft</groupId>
<artifactId>BetterRTP</artifactId> <artifactId>BetterRTP</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<version>3.6.13</version> <version>3.6.15</version>
<!-- Upload patches to https://repo.ronanplugins.com/#/ --> <!-- Upload patches to https://repo.ronanplugins.com/#/ -->
@@ -212,6 +212,9 @@
</repository> </repository>
</repositories> </repositories>
<dependencies> <dependencies>
<dependency>
<groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope>
</dependency>
<!-- Download the tagged GitHub library through JitPack; bundled by Shade. --> <!-- Download the tagged GitHub library through JitPack; bundled by Shade. -->
<dependency> <dependency>
<groupId>com.github.RonanPlugins</groupId> <groupId>com.github.RonanPlugins</groupId>
@@ -76,6 +76,8 @@ public class BetterRTP extends JavaPlugin {
@Override @Override
public void onDisable() { public void onDisable() {
RTP.getOperations().clear();
playerDataManager.clear();
if (editorBridge != null) editorBridge.close(); if (editorBridge != null) editorBridge.close();
invs.closeAll(); invs.closeAll();
queue.unload(); queue.unload();
@@ -110,8 +112,11 @@ public class BetterRTP extends JavaPlugin {
//(Re)Load all plugin systems/files/cache //(Re)Load all plugin systems/files/cache
private void loadAll() { private void loadAll() {
RTP.getOperations().clear();
foliaHandler.load(); foliaHandler.load();
playerDataManager.clear(); playerDataManager.clear();
for (org.bukkit.entity.Player player : Bukkit.getOnlinePlayers())
playerDataManager.startSession(player);
files.loadAll(); files.loadAll();
settings.load(); settings.load();
cooldowns.load(); cooldowns.load();
@@ -16,7 +16,7 @@ public class PlayerInfo {
@Getter private final HashMap<Player, World> invWorld = new HashMap<>(); @Getter private final HashMap<Player, World> invWorld = new HashMap<>();
@Getter private final HashMap<Player, RTP_INV_SETTINGS> invNextInv = new HashMap<>(); @Getter private final HashMap<Player, RTP_INV_SETTINGS> invNextInv = new HashMap<>();
//private final HashMap<Player, CooldownData> cooldown = new HashMap<>(); //private final HashMap<Player, CooldownData> cooldown = new HashMap<>();
@Getter private final HashMap<Player, Boolean> rtping = new HashMap<>();
//private final HashMap<Player, List<Location>> previousLocations = new HashMap<>(); //private final HashMap<Player, List<Location>> previousLocations = new HashMap<>();
//private final HashMap<Player, RTP_TYPE> rtpType = new HashMap<>(); //private final HashMap<Player, RTP_TYPE> rtpType = new HashMap<>();
@@ -48,14 +48,14 @@ public class PlayerInfo {
invWorld.clear(); invWorld.clear();
invNextInv.clear(); invNextInv.clear();
//cooldown.clear(); //cooldown.clear();
rtping.clear();
//previousLocations.clear(); //previousLocations.clear();
} }
private void unload(Player p) { private void unload(Player p) {
clearInvs(p); clearInvs(p);
//cooldown.remove(p); //cooldown.remove(p);
rtping.remove(p);
//previousLocations.remove(p); //previousLocations.remove(p);
} }
@@ -21,6 +21,7 @@ public class Click {
try { try {
Player p = (Player) e.getWhoClicked(); Player p = (Player) e.getWhoClicked();
PlayerData data = HelperPlayer.getData(p); PlayerData data = HelperPlayer.getData(p);
if (data == null) return;
RTPInventories menu = BetterRTP.getInstance().getInvs(); RTPInventories menu = BetterRTP.getInstance().getInvs();
menu.getInv(data.getMenu().getInvType()).clickEvent(e); menu.getInv(data.getMenu().getInvType()).clickEvent(e);
} catch (NullPointerException ex) { } catch (NullPointerException ex) {
@@ -38,6 +39,7 @@ public class Click {
else if (e.getWhoClicked() instanceof Player) { else if (e.getWhoClicked() instanceof Player) {
// Clicks the inventory // Clicks the inventory
PlayerData data = HelperPlayer.getData((Player) e.getWhoClicked()); PlayerData data = HelperPlayer.getData((Player) e.getWhoClicked());
if (data == null) return false;
if (!e.getInventory().equals(data.getMenu().getInv())) if (!e.getInventory().equals(data.getMenu().getInv()))
return false; return false;
// Clicks their own inventory // Clicks their own inventory
@@ -1,6 +1,7 @@
package me.SuperRonanCraft.BetterRTP.player.events; package me.SuperRonanCraft.BetterRTP.player.events;
import me.SuperRonanCraft.BetterRTP.references.player.HelperPlayer; import me.SuperRonanCraft.BetterRTP.references.player.HelperPlayer;
import me.SuperRonanCraft.BetterRTP.references.player.playerdata.PlayerData;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent;
@@ -11,7 +12,8 @@ public class Damage {
} }
static boolean isInInvincibleMode(Player player) { static boolean isInInvincibleMode(Player player) {
return HelperPlayer.getData(player).getInvincibleEndTime() > System.currentTimeMillis(); PlayerData data = HelperPlayer.getData(player);
return data != null && data.getInvincibleEndTime() > System.currentTimeMillis();
} }
static void onEntityDamage(EntityDamageEvent event) { static void onEntityDamage(EntityDamageEvent event) {
@@ -8,7 +8,6 @@ import me.SuperRonanCraft.BetterRTP.references.messages.Message_RTP;
import me.SuperRonanCraft.BetterRTP.references.messages.MessagesCore; import me.SuperRonanCraft.BetterRTP.references.messages.MessagesCore;
import me.SuperRonanCraft.BetterRTP.references.web.Updater; import me.SuperRonanCraft.BetterRTP.references.web.Updater;
import me.SuperRonanCraft.BetterRTP.references.helpers.HelperRTP; import me.SuperRonanCraft.BetterRTP.references.helpers.HelperRTP;
import me.SuperRonanCraft.BetterRTP.versions.AsyncHandler;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
@@ -19,8 +18,9 @@ public class Join {
static void event(PlayerJoinEvent e) { static void event(PlayerJoinEvent e) {
Player p = e.getPlayer(); Player p = e.getPlayer();
getPl().getPlayerDataManager().startSession(p);
updater(p); updater(p);
AsyncHandler.async(() -> getPl().getCooldowns().loadPlayer(p)); getPl().getCooldowns().loadPlayer(p);
rtpOnFirstJoin(p); rtpOnFirstJoin(p);
} }
@@ -1,6 +1,7 @@
package me.SuperRonanCraft.BetterRTP.player.events; package me.SuperRonanCraft.BetterRTP.player.events;
import me.SuperRonanCraft.BetterRTP.references.player.HelperPlayer; import me.SuperRonanCraft.BetterRTP.references.player.HelperPlayer;
import me.SuperRonanCraft.BetterRTP.BetterRTP;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
@@ -8,6 +9,10 @@ class Leave {
static void event(PlayerQuitEvent e) { static void event(PlayerQuitEvent e) {
Player p = e.getPlayer(); Player p = e.getPlayer();
HelperPlayer.unload(p); try {
BetterRTP.getInstance().getRTP().getOperations().cancel(p.getUniqueId(), p);
} finally {
HelperPlayer.unload(p);
}
} }
} }
@@ -22,6 +22,7 @@ import me.SuperRonanCraft.BetterRTP.references.rtpinfo.worlds.WorldPlayer;
public class RTP { public class RTP {
@Getter final RTPTeleport teleport = new RTPTeleport(); @Getter final RTPTeleport teleport = new RTPTeleport();
@Getter private final RTPOperationTracker operations = new RTPOperationTracker();
//Cache //Cache
public final HashMap<String, String> overriden = new HashMap<>(); public final HashMap<String, String> overriden = new HashMap<>();
@Getter List<String> disabledWorlds, blockList; @Getter List<String> disabledWorlds, blockList;
@@ -82,16 +83,19 @@ public class RTP {
private void rtp(CommandSender sendi, WorldPlayer pWorld, RTP_TYPE type) { private void rtp(CommandSender sendi, WorldPlayer pWorld, RTP_TYPE type) {
//Cooldown //Cooldown
Player p = pWorld.getPlayer(); Player p = pWorld.getPlayer();
getPl().getPInfo().getRtping().put(p, true); //Cache player so they cant run '/rtp' again while rtp'ing if (!p.isOnline()) return;
RTPOperationTracker.Operation operation = operations.start(p.getUniqueId(), p);
if (operation == null) return;
//Setup player rtp methods //Setup player rtp methods
RTPPlayer rtpPlayer = new RTPPlayer(p, this, pWorld, type); RTPPlayer rtpPlayer = new RTPPlayer(p, this, pWorld, type, operation);
// Delaying? Else, just go rtpPlayer.runSafely(() -> {
if (pWorld.getPlayerInfo().applyDelay && HelperRTP_Check.applyDelay(pWorld.getPlayer())) { if (pWorld.getPlayerInfo().applyDelay && HelperRTP_Check.applyDelay(p)) {
new RTPDelay(sendi, rtpPlayer, delayTime, cancelOnMove, cancelOnDamage); new RTPDelay(sendi, rtpPlayer, delayTime, cancelOnMove, cancelOnDamage);
} else { } else {
if (!teleport.beforeTeleportInstant(sendi, p)) rtpPlayer.afterPreEvent(teleport.beforeTeleportInstant(sendi, p),
rtpPlayer.randomlyTeleport(sendi); () -> rtpPlayer.randomlyTeleport(sendi));
} }
});
} }
private BetterRTP getPl() { private BetterRTP getPl() {
@@ -22,15 +22,17 @@ class RTPDelay implements Listener {
this.cancelOnMove = cancelOnMove; this.cancelOnMove = cancelOnMove;
this.cancelOnDamage = cancelOnDamage; this.cancelOnDamage = cancelOnDamage;
this.rtp = rtp; this.rtp = rtp;
rtp.getOperation().onFinish(this::dispose);
delay(sendi, delay); delay(sendi, delay);
} }
private void delay(CommandSender sendi, int delay) { private void delay(CommandSender sendi, int delay) {
if (!getPl().getRTP().getTeleport().beforeTeleportDelay(rtp.getPlayer(), delay)) { rtp.afterPreEvent(getPl().getRTP().getTeleport().beforeTeleportDelay(rtp.getPlayer(), delay), () -> {
task = AsyncHandler.syncLater(run(sendi, this), delay * 20L); task = AsyncHandler.syncLater(run(sendi, this), delay * 20L);
if (cancelOnMove || cancelOnDamage) if (cancelOnMove || cancelOnDamage)
Bukkit.getPluginManager().registerEvents(this, BetterRTP.getInstance()); Bukkit.getPluginManager().registerEvents(this, BetterRTP.getInstance());
} if (!rtp.isActive()) dispose();
});
} }
@EventHandler @EventHandler
@@ -57,23 +59,35 @@ class RTPDelay implements Listener {
} }
} }
private void dispose() {
dispose(task, this);
}
static void dispose(WrappedTask task, Listener listener) {
try {
if (task != null) task.cancel();
} finally {
HandlerList.unregisterAll(listener);
}
}
private void cancel() { private void cancel() {
if (task != null) rtp.runSafely(() -> {
task.cancel(); try {
HandlerList.unregisterAll(this); getPl().getRTP().getTeleport().cancelledTeleport(rtp.getPlayer());
getPl().getRTP().getTeleport().cancelledTeleport(rtp.getPlayer()); getPl().getCooldowns().removeCooldown(rtp.getPlayer(), rtp.worldPlayer.getWorld());
//getPl().getEco().unCharge(rtp.getPlayer(), rtp.pWorld); } finally {
getPl().getCooldowns().removeCooldown(rtp.getPlayer(), rtp.worldPlayer.getWorld()); rtp.getOperation().finish();
getPl().getPInfo().getRtping().remove(rtp.getPlayer()); }
Bukkit.getServer().getPluginManager().callEvent(new RTP_CancelledEvent(rtp.getPlayer())); Bukkit.getServer().getPluginManager().callEvent(new RTP_CancelledEvent(rtp.getPlayer()));
});
} }
private Runnable run(final CommandSender sendi, final RTPDelay cls) { private Runnable run(final CommandSender sendi, final RTPDelay cls) {
return () -> { return () -> rtp.runSafely(() -> {
HandlerList.unregisterAll(cls); HandlerList.unregisterAll(cls);
if (getPl().getPInfo().getRtping().containsKey(rtp.getPlayer())) rtp.randomlyTeleport(sendi);
rtp.randomlyTeleport(sendi); });
};
} }
private BetterRTP getPl() { private BetterRTP getPl() {
@@ -0,0 +1,95 @@
package me.SuperRonanCraft.BetterRTP.player.rtp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
/** Owns active requests. Identity checks prevent old callbacks from ending a newer request. */
public final class RTPOperationTracker {
private final Map<UUID, Operation> active = new HashMap<>();
public synchronized Operation start(UUID uuid, Object session) {
if (active.containsKey(uuid)) return null;
Operation operation = new Operation(uuid, session);
active.put(uuid, operation);
return operation;
}
public synchronized boolean contains(UUID uuid) { return active.containsKey(uuid); }
public void cancel(UUID uuid, Object session) {
Operation operation;
synchronized (this) { operation = active.get(uuid); }
if (operation != null && operation.session == session) operation.finish();
}
public void clear() {
List<Operation> operations;
synchronized (this) {
operations = new ArrayList<>(active.values());
active.clear();
}
RuntimeException failure = null;
for (Operation operation : operations) {
try { operation.finish(); } catch (RuntimeException ex) { failure = ex; }
}
if (failure != null) throw failure;
}
public final class Operation {
private final UUID uuid;
private final Object session;
private final List<Runnable> cleanup = new ArrayList<>();
private boolean finished;
private Operation(UUID uuid, Object session) { this.uuid = uuid; this.session = session; }
public boolean isActive() {
synchronized (RTPOperationTracker.this) { return active.get(uuid) == this; }
}
public void onFinish(Runnable action) {
synchronized (this) {
if (!finished) { cleanup.add(action); return; }
}
action.run();
}
public void finish() {
List<Runnable> actions;
synchronized (this) {
if (finished) return;
finished = true;
actions = new ArrayList<>(cleanup);
cleanup.clear();
}
synchronized (RTPOperationTracker.this) { active.remove(uuid, this); }
RuntimeException failure = null;
for (Runnable action : actions) {
try { action.run(); } catch (RuntimeException ex) { failure = ex; }
}
if (failure != null) throw failure;
}
/** Terminal future: cleanup also runs when result handling throws. */
public void complete(CompletableFuture<Boolean> future, Runnable success, Runnable failure,
Consumer<Throwable> errors) {
future.whenComplete((result, error) -> {
try {
if (!isActive()) return;
if (error != null) errors.accept(error);
else if (Boolean.TRUE.equals(result)) success.run();
else failure.run();
} catch (Throwable ex) {
errors.accept(ex);
} finally {
finish();
}
});
}
}
}
@@ -23,20 +23,56 @@ import me.SuperRonanCraft.BetterRTP.versions.AsyncHandler;
public class RTPPlayer { public class RTPPlayer {
@Getter private final Player player; @Getter private final Player player;
@Getter private final RTPOperationTracker.Operation operation;
private final RTP settings; private final RTP settings;
@Getter WorldPlayer worldPlayer; @Getter WorldPlayer worldPlayer;
@Getter RTP_TYPE type; @Getter RTP_TYPE type;
@Getter int attempts; @Getter int attempts;
//List<Location> attemptedLocations = new ArrayList<>(); //List<Location> attemptedLocations = new ArrayList<>();
RTPPlayer(Player player, RTP settings, WorldPlayer worldPlayer, RTP_TYPE type) { RTPPlayer(Player player, RTP settings, WorldPlayer worldPlayer, RTP_TYPE type, RTPOperationTracker.Operation operation) {
this.operation = operation;
this.player = player; this.player = player;
this.settings = settings; this.settings = settings;
this.worldPlayer = worldPlayer; this.worldPlayer = worldPlayer;
this.type = type; this.type = type;
} }
boolean isActive() {
if (!player.isOnline()) operation.finish();
return operation.isActive();
}
void logError(Throwable error) {
getPl().getLogger().log(java.util.logging.Level.WARNING, "RTP operation failed for " + player.getUniqueId(), error);
}
void runSafely(Runnable action) {
try {
if (isActive()) action.run();
} catch (Throwable error) {
try { operation.finish(); } finally { logError(error); }
}
}
void afterPreEvent(boolean cancelled, Runnable continuation) {
if (cancelled) operation.finish();
else runSafely(continuation);
}
void awaitChunk(CompletableFuture<Chunk> chunk, Runnable continuation) {
chunk.whenComplete((result, error) -> runSafely(() -> {
if (error != null) {
try { operation.finish(); } finally { logError(error); }
} else continuation.run();
}));
}
void randomlyTeleport(CommandSender sendi) { void randomlyTeleport(CommandSender sendi) {
runSafely(() -> search(sendi));
}
private void search(CommandSender sendi) {
if (attempts >= settings.maxAttempts) //Cancel out, too many tries if (attempts >= settings.maxAttempts) //Cancel out, too many tries
metMax(sendi, player); metMax(sendi, player);
else { //Try again to find a safe location else { //Try again to find a safe location
@@ -45,11 +81,11 @@ public class RTPPlayer {
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
//Async Location finder //Async Location finder
if (event.isCancelled()) { if (event.isCancelled()) {
randomlyTeleport(sendi);
attempts++; attempts++;
AsyncHandler.sync(() -> randomlyTeleport(sendi));
return; return;
} }
AsyncHandler.async(() -> { AsyncHandler.async(() -> runSafely(() -> {
Location loc; Location loc;
if (event.getLocation() != null) // && WorldPlayer.checkIsValid(event.getLocation(), pWorld)) if (event.getLocation() != null) // && WorldPlayer.checkIsValid(event.getLocation(), pWorld))
loc = event.getLocation(); loc = event.getLocation();
@@ -63,25 +99,21 @@ public class RTPPlayer {
} }
attempts++; //Add an attempt attempts++; //Add an attempt
//Load chunk and find out if safe location (asynchronously) //Load chunk and find out if safe location (asynchronously)
AsyncHandler.sync(() -> { AsyncHandler.sync(() -> runSafely(() -> {
try { //Prior to 1.12 this async chunk will NOT work try { //Prior to 1.12 this async chunk will NOT work
CompletableFuture<Chunk> chunk = PaperLib.getChunkAtAsync(loc); CompletableFuture<Chunk> chunk = PaperLib.getChunkAtAsync(loc);
chunk.thenAccept(result -> { awaitChunk(chunk, () -> attempt(sendi, loc));
//BetterRTP.debug("Checking location for " + p.getName());
attempt(sendi, loc);
});
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
//Legacy non-async support //Legacy non-async support
attempt(sendi, loc); attempt(sendi, loc);
} catch (Throwable ignored) {
} }
}); }));
}); }));
} }
} }
private void attempt(CommandSender sendi, Location loc) { private void attempt(CommandSender sendi, Location loc) {
if (!isActive()) return;
Location tpLoc; Location tpLoc;
tpLoc = RandomLocation.getSafeLocation(worldPlayer.getWorldtype(), worldPlayer.getWorld(), loc, worldPlayer.getMinY(), worldPlayer.getMaxY(), worldPlayer.getBiomes()); tpLoc = RandomLocation.getSafeLocation(worldPlayer.getWorldtype(), worldPlayer.getWorld(), loc, worldPlayer.getMinY(), worldPlayer.getMaxY(), worldPlayer.getBiomes());
//attemptedLocations.add(loc); //attemptedLocations.add(loc);
@@ -94,11 +126,11 @@ public class RTPPlayer {
getPl().getCooldowns().add(player, worldPlayer.getWorld()); getPl().getCooldowns().add(player, worldPlayer.getWorld());
tpLoc.setYaw(player.getLocation().getYaw()); tpLoc.setYaw(player.getLocation().getYaw());
tpLoc.setPitch(player.getLocation().getPitch()); tpLoc.setPitch(player.getLocation().getPitch());
AsyncHandler.sync(() -> settings.teleport.sendPlayer(sendi, player, tpLoc, worldPlayer, attempts, type)); AsyncHandler.sync(() -> runSafely(() -> settings.teleport.sendPlayer(sendi, this, tpLoc)));
} else { } else {
if (worldPlayer.getPlayerInfo().applyCooldown) if (worldPlayer.getPlayerInfo().applyCooldown)
getPl().getCooldowns().removeCooldown(player, worldPlayer.getWorld()); getPl().getCooldowns().removeCooldown(player, worldPlayer.getWorld());
getPl().getPInfo().getRtping().remove(player); operation.finish();
} }
} else { } else {
randomlyTeleport(sendi); randomlyTeleport(sendi);
@@ -110,7 +142,7 @@ public class RTPPlayer {
private void metMax(CommandSender sendi, Player p) { private void metMax(CommandSender sendi, Player p) {
settings.teleport.failedTeleport(p, sendi); settings.teleport.failedTeleport(p, sendi);
getPl().getCooldowns().removeCooldown(p, worldPlayer.getWorld()); getPl().getCooldowns().removeCooldown(p, worldPlayer.getWorld());
getPl().getPInfo().getRtping().remove(p); operation.finish();
//RTP Failed Event //RTP Failed Event
Bukkit.getServer().getPluginManager().callEvent(new RTP_FailedEvent(this)); Bukkit.getServer().getPluginManager().callEvent(new RTP_FailedEvent(this));
} }
@@ -5,7 +5,6 @@ import java.util.Arrays;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import io.papermc.lib.PaperLib; import io.papermc.lib.PaperLib;
import me.SuperRonanCraft.BetterRTP.BetterRTP; import me.SuperRonanCraft.BetterRTP.BetterRTP;
@@ -38,37 +37,25 @@ public class RTPTeleport {
// CompletableFuture.allOf(asyncChunks.toArray(new CompletableFuture[] {})).cancel(true); // CompletableFuture.allOf(asyncChunks.toArray(new CompletableFuture[] {})).cancel(true);
// } // }
void sendPlayer(final CommandSender sendi, final Player p, final Location location, final WorldPlayer wPlayer, void sendPlayer(CommandSender sendi, RTPPlayer request, Location location) {
final int attempts, RTP_TYPE type) throws NullPointerException { Player p = request.getPlayer();
WorldPlayer wPlayer = request.getWorldPlayer();
int attempts = request.getAttempts();
RTP_TYPE type = request.getType();
Location oldLoc = p.getLocation(); Location oldLoc = p.getLocation();
loadingTeleport(p, sendi); //Send loading message to player who requested loadingTeleport(p, sendi);
//List<CompletableFuture<Chunk>> asyncChunks = getChunks(location); //Get a list of chunks RTP_TeleportEvent event = new RTP_TeleportEvent(p, location, wPlayer.getWorldtype());
//playerLoads.put(p, asyncChunks); getPl().getServer().getPluginManager().callEvent(event);
/*CompletableFuture.allOf(asyncChunks.toArray(new CompletableFuture[] {})).thenRun(() -> { //Async chunk load if (!request.isActive()) return;
new BukkitRunnable() { //Run synchronously Location loc = event.getLocation();
@Override request.getOperation().complete(PaperLib.teleportAsync(p, loc), () -> {
public void run() {*/ if (!request.isActive()) return;
try { afterTeleport(p, loc, wPlayer, attempts, oldLoc, type);
RTP_TeleportEvent event = new RTP_TeleportEvent(p, location, wPlayer.getWorldtype()); if (sendi != p)
getPl().getServer().getPluginManager().callEvent(event); sendSuccessMsg(sendi, p.getName(), loc, wPlayer, false, attempts);
Location loc = event.getLocation(); if (type == RTP_TYPE.JOIN && getPl().getSettings().isRtpOnFirstJoin_SetAsRespawn())
PaperLib.teleportAsync(p, loc).thenRun(new BukkitRunnable() { //Async teleport p.setBedSpawnLocation(loc, true);
@Override }, () -> failedTeleport(p, sendi), request::logError);
public void run() {
afterTeleport(p, loc, wPlayer, attempts, oldLoc, type);
if (sendi != p) //Tell player who requested that the player rtp'd
sendSuccessMsg(sendi, p.getName(), loc, wPlayer, false, attempts);
getPl().getPInfo().getRtping().remove(p); //No longer rtp'ing
//Save respawn location if first join
if (type == RTP_TYPE.JOIN) //RTP Type was Join
if (BetterRTP.getInstance().getSettings().isRtpOnFirstJoin_SetAsRespawn()) //Save as respawn is enabled
p.setBedSpawnLocation(loc, true); //True means to force a respawn even without a valid bed
}
});
} catch (Exception e) {
getPl().getPInfo().getRtping().remove(p); //No longer rtp'ing (errored)
e.printStackTrace();
}
} }
//Effects //Effects
@@ -3,6 +3,7 @@ package me.SuperRonanCraft.BetterRTP.player.rtp.effects;
import me.SuperRonanCraft.BetterRTP.BetterRTP; import me.SuperRonanCraft.BetterRTP.BetterRTP;
import me.SuperRonanCraft.BetterRTP.references.file.FileOther; import me.SuperRonanCraft.BetterRTP.references.file.FileOther;
import me.SuperRonanCraft.BetterRTP.references.player.HelperPlayer; import me.SuperRonanCraft.BetterRTP.references.player.HelperPlayer;
import me.SuperRonanCraft.BetterRTP.references.player.playerdata.PlayerData;
import me.SuperRonanCraft.BetterRTP.versions.AsyncHandler; import me.SuperRonanCraft.BetterRTP.versions.AsyncHandler;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffect;
@@ -52,8 +53,10 @@ public class RTPEffect_Potions { //Potions AND Invincibility
public void giveEffects(Player p) { public void giveEffects(Player p) {
AsyncHandler.syncAtEntity(p, () -> { AsyncHandler.syncAtEntity(p, () -> {
PlayerData data = HelperPlayer.getData(p);
if (data == null) return;
if (invincibleEnabled) if (invincibleEnabled)
HelperPlayer.getData(p).setInvincibleEndTime(System.currentTimeMillis() + (invincibleTime * 1000L)); data.setInvincibleEndTime(System.currentTimeMillis() + (invincibleTime * 1000L));
if (potionEnabled) { if (potionEnabled) {
List<PotionEffect> effects = new ArrayList<>(); List<PotionEffect> effects = new ArrayList<>();
for (PotionEffectType e : potionEffects.keySet()) { for (PotionEffectType e : potionEffects.keySet()) {
@@ -6,7 +6,7 @@ import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.Future; import java.util.UUID;
import java.util.logging.Level; import java.util.logging.Level;
import me.SuperRonanCraft.BetterRTP.BetterRTP; import me.SuperRonanCraft.BetterRTP.BetterRTP;
@@ -41,56 +41,68 @@ public class DatabasePlayers extends SQLite {
} }
} }
public void setupData(PlayerData data) { /** Immutable persistence values; never retains a Bukkit player/session. */
if (data == null || data.player == null) { public static final class Snapshot {
return; public final UUID uuid;
} public final int count;
try { public final long cooldown;
Future<?> task = SQLiteExecutor.EXECUTOR.submit(() -> {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = getSQLConnection();
ps = conn.prepareStatement("SELECT * FROM " + tables.get(0) + " WHERE " + COLUMNS.UUID.name + " = ?");
ps.setString(1, data.player.getUniqueId().toString());
rs = ps.executeQuery(); public Snapshot(UUID uuid, int count, long cooldown) {
if (rs.next()) { this.uuid = uuid;
long count = rs.getLong(COLUMNS.COUNT.name); this.count = count;
long time = rs.getLong(COLUMNS.LAST_COOLDOWN_DATE.name); this.cooldown = cooldown;
data.setRtpCount(Math.toIntExact(count)); }
data.setGlobalCooldown(time);
public static Snapshot capture(PlayerData data) {
return new Snapshot(data.player.getUniqueId(), data.getRtpCount(), data.getGlobalCooldown());
}
}
/** Existing API: load into this session only while it is still current. */
public void setupData(PlayerData data) {
if (data == null) return;
Snapshot stored = loadData(data.player.getUniqueId());
if (stored != null)
BetterRTP.getInstance().getPlayerDataManager().applyIfCurrent(data, current -> {
current.setRtpCount(stored.count);
current.setGlobalCooldown(stored.cooldown);
});
}
public Snapshot loadData(UUID uuid) {
try {
return SQLiteExecutor.EXECUTOR.submit(() -> {
try (Connection conn = getSQLConnection();
PreparedStatement ps = conn.prepareStatement("SELECT * FROM " + tables.get(0) + " WHERE " + COLUMNS.UUID.name + " = ?")) {
ps.setString(1, uuid.toString());
try (ResultSet rs = ps.executeQuery()) {
if (rs.next())
return new Snapshot(uuid, Math.toIntExact(rs.getLong(COLUMNS.COUNT.name)),
rs.getLong(COLUMNS.LAST_COOLDOWN_DATE.name));
} }
} catch (SQLException ex) { } catch (SQLException ex) {
BetterRTP.getInstance().getLogger().log(Level.SEVERE, Errors.sqlConnectionExecute(), ex); BetterRTP.getInstance().getLogger().log(Level.SEVERE, Errors.sqlConnectionExecute(), ex);
} finally {
close(ps, rs, conn);
} }
}); return null;
task.get(); }).get();
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
return null;
} }
} }
//Set a player Cooldown /** Compatibility entry point: capture before deferring database work. */
public void setData(PlayerData data) { public void setData(PlayerData data) {
try { if (data != null) setData(Snapshot.capture(data));
SQLiteExecutor.EXECUTOR.submit(() -> { }
String sql = "INSERT OR REPLACE INTO " + tables.get(0) + " ("
+ COLUMNS.UUID.name + ", " public void setData(Snapshot data) {
+ COLUMNS.COUNT.name + ", " SQLiteExecutor.EXECUTOR.submit(() -> {
String sql = "INSERT OR REPLACE INTO " + tables.get(0) + " ("
+ COLUMNS.UUID.name + ", " + COLUMNS.COUNT.name + ", "
+ COLUMNS.LAST_COOLDOWN_DATE.name + ") VALUES(?, ?, ?)"; + COLUMNS.LAST_COOLDOWN_DATE.name + ") VALUES(?, ?, ?)";
List<Object> params = new ArrayList<Object>() {{ List<Object> params = java.util.Arrays.asList(data.uuid.toString(), data.count, data.cooldown);
add(data.player.getUniqueId().toString()); sqlUpdate(sql, params);
add(data.getRtpCount()); });
add(data.getGlobalCooldown());
}};
sqlUpdate(sql, params);
});
} catch (Exception ex) {
ex.printStackTrace();
}
} }
} }
@@ -39,6 +39,7 @@ public class DepPlaceholderAPI extends PlaceholderExpansion {
@Override @Override
public String onPlaceholderRequest(Player player, String request) { public String onPlaceholderRequest(Player player, String request) {
PlayerData data = HelperPlayer.getData(player); PlayerData data = HelperPlayer.getData(player);
if (data == null) return null;
if (request.equalsIgnoreCase("count")) { if (request.equalsIgnoreCase("count")) {
return String.valueOf(data.getRtpCount()); return String.valueOf(data.getRtpCount());
} else if (request.startsWith("cooldown")) { } else if (request.startsWith("cooldown")) {
@@ -37,7 +37,7 @@ public class HelperRTP_Check {
} }
private static boolean isRTPing(Player player) { private static boolean isRTPing(Player player) {
return getPl().getPInfo().getRtping().getOrDefault(player, false); return getPl().getRTP().getOperations().contains(player.getUniqueId());
} }
public static boolean isCoolingDown(Player player, WorldPlayer pWorld) { public static boolean isCoolingDown(Player player, WorldPlayer pWorld) {
@@ -37,6 +37,7 @@ public interface RTPInventory_Defaults {
default void cacheInv(Player p, Inventory inv, RTP_INV_SETTINGS type) { default void cacheInv(Player p, Inventory inv, RTP_INV_SETTINGS type) {
PlayerData info = HelperPlayer.getData(p); PlayerData info = HelperPlayer.getData(p);
if (info == null) return;
info.getMenu().setInv(inv); info.getMenu().setInv(inv);
info.getMenu().setInvType(type); info.getMenu().setInvType(type);
} }
@@ -6,6 +6,7 @@ import org.bukkit.entity.Player;
public class HelperPlayer { public class HelperPlayer {
@org.jetbrains.annotations.Nullable
public static PlayerData getData(Player p) { public static PlayerData getData(Player p) {
return getPl().getPlayerDataManager().getData(p); return getPl().getPlayerDataManager().getData(p);
} }
@@ -12,7 +12,8 @@ import me.SuperRonanCraft.BetterRTP.references.rtpinfo.CooldownData;
public class PlayerData { public class PlayerData {
public boolean loading; //Is this players data loading? public volatile boolean cooldownsLoaded;
public volatile boolean loading; //Is this players data loading?
public final Player player; public final Player player;
//Menus //Menus
@Getter final PlayerData_Menus menu = new PlayerData_Menus(); @Getter final PlayerData_Menus menu = new PlayerData_Menus();
@@ -6,14 +6,33 @@ import org.jetbrains.annotations.Nullable;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.function.Consumer;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
public class PlayerDataManager { public class PlayerDataManager {
private final Map<UUID, PlayerData> playerData = new ConcurrentHashMap<>(); private final Map<UUID, PlayerData> playerData = new ConcurrentHashMap<>();
public PlayerData getData(@NonNull Player p) { /** Called only by join/enable/reload lifecycle handling. */
return playerData.computeIfAbsent(p.getUniqueId(), uuid -> new PlayerData(p)); public PlayerData startSession(@NonNull Player p) {
PlayerData data = new PlayerData(p);
playerData.put(p.getUniqueId(), data);
return data;
}
/** Lookup only: a departed or replaced session must never be recreated. */
@Nullable
public PlayerData getData(Player p) {
if (p == null) return null;
PlayerData data = playerData.get(p.getUniqueId());
return data != null && data.player == p ? data : null;
}
public void applyIfCurrent(PlayerData session, Consumer<PlayerData> update) {
playerData.computeIfPresent(session.player.getUniqueId(), (id, current) -> {
if (current == session) update.accept(current);
return current;
});
} }
@Nullable @Nullable
@@ -26,6 +45,6 @@ public class PlayerDataManager {
} }
public void clear(Player p) { public void clear(Player p) {
playerData.remove(p.getUniqueId()); playerData.computeIfPresent(p.getUniqueId(), (id, data) -> data.player == p ? null : data);
} }
} }
@@ -2,7 +2,8 @@ package me.SuperRonanCraft.BetterRTP.references.rtpinfo;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.HashMap;
import java.util.UUID;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@@ -15,6 +16,7 @@ import lombok.Getter;
import me.SuperRonanCraft.BetterRTP.BetterRTP; import me.SuperRonanCraft.BetterRTP.BetterRTP;
import me.SuperRonanCraft.BetterRTP.references.database.DatabaseCooldowns; import me.SuperRonanCraft.BetterRTP.references.database.DatabaseCooldowns;
import me.SuperRonanCraft.BetterRTP.references.database.DatabaseHandler; import me.SuperRonanCraft.BetterRTP.references.database.DatabaseHandler;
import me.SuperRonanCraft.BetterRTP.references.database.DatabasePlayers;
import me.SuperRonanCraft.BetterRTP.references.file.FileOther; import me.SuperRonanCraft.BetterRTP.references.file.FileOther;
import me.SuperRonanCraft.BetterRTP.references.player.HelperPlayer; import me.SuperRonanCraft.BetterRTP.references.player.HelperPlayer;
import me.SuperRonanCraft.BetterRTP.references.player.playerdata.PlayerData; import me.SuperRonanCraft.BetterRTP.references.player.playerdata.PlayerData;
@@ -26,12 +28,11 @@ public class CooldownHandler {
@Getter boolean enabled, loaded, cooldownByWorld; @Getter boolean enabled, loaded, cooldownByWorld;
@Getter private int defaultCooldownTime; //Global Cooldown timer @Getter private int defaultCooldownTime; //Global Cooldown timer
private int lockedAfter; //Rtp's before being locked private int lockedAfter; //Rtp's before being locked
private final List<Player> downloading = new CopyOnWriteArrayList<>();
public void load() { public void load() {
FileOther.FILETYPE config = FileOther.FILETYPE.CONFIG; FileOther.FILETYPE config = FileOther.FILETYPE.CONFIG;
enabled = config.getBoolean("Settings.Cooldown.Enabled"); enabled = config.getBoolean("Settings.Cooldown.Enabled");
downloading.clear();
loaded = false; loaded = false;
if (enabled) { if (enabled) {
defaultCooldownTime = config.getInt("Settings.Cooldown.Time"); defaultCooldownTime = config.getInt("Settings.Cooldown.Time");
@@ -62,6 +63,7 @@ public class CooldownHandler {
public void add(Player player, World world) { public void add(Player player, World world) {
if (!enabled) return; if (!enabled) return;
PlayerData playerData = getData(player); PlayerData playerData = getData(player);
if (playerData == null) return;
if (cooldownByWorld) { if (cooldownByWorld) {
Map<World, CooldownData> cooldowns = playerData.getCooldowns(); Map<World, CooldownData> cooldowns = playerData.getCooldowns();
CooldownData data = cooldowns.getOrDefault(world, new CooldownData(player.getUniqueId(), 0L)); CooldownData data = cooldowns.getOrDefault(world, new CooldownData(player.getUniqueId(), 0L));
@@ -69,7 +71,7 @@ public class CooldownHandler {
data.setTime(System.currentTimeMillis()); data.setTime(System.currentTimeMillis());
playerData.setGlobalCooldown(data.getTime()); playerData.setGlobalCooldown(data.getTime());
cooldowns.put(world, data); cooldowns.put(world, data);
savePlayer(player, world, data, false); savePlayer(playerData, world, data, false);
} else } else
add(player); add(player);
} }
@@ -77,18 +79,19 @@ public class CooldownHandler {
private void add(Player player) { private void add(Player player) {
if (!enabled) return; if (!enabled) return;
PlayerData playerData = getData(player); PlayerData playerData = getData(player);
if (playerData == null) return;
playerData.setRtpCount(playerData.getRtpCount() + 1); playerData.setRtpCount(playerData.getRtpCount() + 1);
playerData.setGlobalCooldown(System.currentTimeMillis()); playerData.setGlobalCooldown(System.currentTimeMillis());
savePlayer(player, null, null, false); savePlayer(playerData, null, null, false);
} }
@Nullable @Nullable
public CooldownData get(Player p, World world) { public CooldownData get(Player p, World world) {
PlayerData data = getData(p); PlayerData data = getData(p);
if (data == null) return null;
if (cooldownByWorld) { if (cooldownByWorld) {
Map<World, CooldownData> cooldownData = getData(p).getCooldowns(); Map<World, CooldownData> cooldownData = data.getCooldowns();
if (data != null) return cooldownData.getOrDefault(world, null);
return cooldownData.getOrDefault(world, null);
} else if (data.getGlobalCooldown() > 0) { } else if (data.getGlobalCooldown() > 0) {
return new CooldownData(p.getUniqueId(), data.getGlobalCooldown()); return new CooldownData(p.getUniqueId(), data.getGlobalCooldown());
} }
@@ -102,73 +105,87 @@ public class CooldownHandler {
} }
public boolean locked(Player player) { public boolean locked(Player player) {
return lockedAfter > 0 && getData(player).getRtpCount() >= lockedAfter; PlayerData data = getData(player);
return lockedAfter > 0 && data != null && data.getRtpCount() >= lockedAfter;
} }
public void removeCooldown(Player player, World world) { public void removeCooldown(Player player, World world) {
if (!enabled) return; if (!enabled) return;
PlayerData playerData = getData(player); PlayerData playerData = getData(player);
if (playerData == null) return;
CooldownData cooldownData = playerData.getCooldowns().getOrDefault(world, null); CooldownData cooldownData = playerData.getCooldowns().getOrDefault(world, null);
if (cooldownData != null) { if (cooldownData != null) {
if (lockedAfter > 0) { if (lockedAfter > 0) {
if (playerData.getRtpCount() <= 0) { //Remove from file as well if (playerData.getRtpCount() <= 0) { //Remove from file as well
savePlayer(player, world, cooldownData, true); savePlayer(playerData, world, cooldownData, true);
getData(player).getCooldowns().put(world, null); playerData.getCooldowns().remove(world);
} else { //Keep the player cached } else { //Keep the player cached
savePlayer(player, world, cooldownData, false); savePlayer(playerData, world, cooldownData, false);
} }
} else { //Remove completely } else { //Remove completely
getData(player).getCooldowns().remove(world); playerData.getCooldowns().remove(world);
savePlayer(player, world, cooldownData, true); savePlayer(playerData, world, cooldownData, true);
} }
} else if (!cooldownByWorld) { } else if (!cooldownByWorld) {
getData(player).setGlobalCooldown(0); playerData.setGlobalCooldown(0);
savePlayer(player, null, null, true); savePlayer(playerData, null, null, true);
} }
} }
private void savePlayer(Player player, @Nullable World world, @Nullable CooldownData data, boolean remove) { private void savePlayer(PlayerData session, @Nullable World world, @Nullable CooldownData data, boolean remove) {
AsyncHandler.async(() -> { DatabasePlayers.Snapshot snapshot = DatabasePlayers.Snapshot.capture(session);
if (world != null && data != null && getDatabaseWorlds() != null) { //Per World enabled? CooldownData cooldown = data == null ? null : new CooldownData(data.getUuid(), data.getTime());
if (!remove) DatabaseCooldowns worlds = getDatabaseWorlds();
getDatabaseWorlds().setCooldown(world, data); // Submit player values now, preserving submission order and avoiding a later lookup.
else DatabaseHandler.getPlayers().setData(snapshot);
getDatabaseWorlds().removePlayer(data.getUuid(), world); if (world != null && cooldown != null && worlds != null) {
} AsyncHandler.async(() -> {
DatabaseHandler.getPlayers().setData(getData(player)); if (remove) worlds.removePlayer(cooldown.getUuid(), world);
else worlds.setCooldown(world, cooldown);
}); });
}
} }
/** Capture the session before scheduling; completion cannot affect a reconnect. */
public void loadPlayer(Player player) { public void loadPlayer(Player player) {
if (!isEnabled()) { if (!isEnabled()) return;
return; PlayerData session = getData(player);
if (session == null) return;
synchronized (session) {
if (session.loading || session.cooldownsLoaded) return;
session.loading = true;
} }
UUID uuid = player.getUniqueId();
PlayerData playerData = getData(player); List<World> worlds = Bukkit.getWorlds();
if (playerData == null) { DatabaseCooldowns databaseWorlds = getDatabaseWorlds();
return; AsyncHandler.async(() -> {
} try {
if (getData(player) != session) return;
downloading.add(player); Map<World, CooldownData> cooldowns = new HashMap<>();
if (databaseWorlds != null) {
try { for (World world : worlds) {
if (getDatabaseWorlds() != null) { //Per World enabled? CooldownData cooldown = databaseWorlds.getCooldown(uuid, world);
for (World world : Bukkit.getWorlds()) { if (cooldown != null) cooldowns.put(world, cooldown);
//Cooldowns }
CooldownData cooldown = getDatabaseWorlds().getCooldown(player.getUniqueId(), world);
if (cooldown != null)
playerData.getCooldowns().put(world, cooldown);
} }
DatabasePlayers.Snapshot stored = DatabaseHandler.getPlayers().loadData(uuid);
BetterRTP.getInstance().getPlayerDataManager().applyIfCurrent(session, current -> {
current.getCooldowns().putAll(cooldowns);
if (stored != null) {
current.setRtpCount(stored.count);
current.setGlobalCooldown(stored.cooldown);
}
current.cooldownsLoaded = true;
});
} finally {
session.loading = false;
} }
//Player Data });
DatabaseHandler.getPlayers().setupData(playerData);
} finally {
downloading.remove(player);
}
} }
public boolean loadedPlayer(Player player) { public boolean loadedPlayer(Player player) {
return !downloading.contains(player); PlayerData data = getData(player);
return data != null && !data.loading;
} }
@Nullable @Nullable
@@ -11,7 +11,6 @@ import org.jetbrains.annotations.Nullable;
import com.tcoded.folialib.wrapper.task.WrappedTask; import com.tcoded.folialib.wrapper.task.WrappedTask;
import io.papermc.lib.PaperLib;
import me.SuperRonanCraft.BetterRTP.BetterRTP; import me.SuperRonanCraft.BetterRTP.BetterRTP;
import me.SuperRonanCraft.BetterRTP.player.commands.RTP_SETUP_TYPE; import me.SuperRonanCraft.BetterRTP.player.commands.RTP_SETUP_TYPE;
import me.SuperRonanCraft.BetterRTP.player.rtp.RTP; import me.SuperRonanCraft.BetterRTP.player.rtp.RTP;
@@ -156,37 +155,38 @@ public class QueueGenerator {
private void addQueue(RTPWorld rtpWorld, String id, ReQueueData reQueueData) { private void addQueue(RTPWorld rtpWorld, String id, ReQueueData reQueueData) {
Location loc = RandomLocation.generateLocation(rtpWorld); Location loc = RandomLocation.generateLocation(rtpWorld);
if (loc != null) { if (loc != null) {
AsyncHandler.sync(() -> { AsyncHandler.atLoadedChunk(loc, () -> {
//BetterRTP.debug("Queued up a new position, attempts " + reQueueData.attempts); Location safeLoc = RandomLocation.getSafeLocation(
PaperLib.getChunkAtAsync(loc) HelperRTP.getWorldType(rtpWorld.getWorld()),
.thenAccept(v -> { loc.getWorld(),
Location safeLoc = RandomLocation.getSafeLocation( loc,
HelperRTP.getWorldType(rtpWorld.getWorld()), rtpWorld.getMinY(),
loc.getWorld(), rtpWorld.getMaxY(),
loc, rtpWorld.getBiomes());
rtpWorld.getMinY(), //data.setLocation(safeLoc);
rtpWorld.getMaxY(), if (safeLoc != null) {
rtpWorld.getBiomes()); AsyncHandler.async(() -> {
//data.setLocation(safeLoc); QueueData data = DatabaseHandler.getQueue().addQueue(safeLoc);
if (safeLoc != null) { if (data != null) {
AsyncHandler.async(() -> { //queueList.add(data);
QueueData data = DatabaseHandler.getQueue().addQueue(safeLoc); String _x = String.valueOf(data.getLocation().getBlockX());
if (data != null) { String _y = String.valueOf(data.getLocation().getBlockY());
//queueList.add(data); String _z = String.valueOf(data.getLocation().getBlockZ());
String _x = String.valueOf(data.getLocation().getBlockX()); String _world = data.getLocation().getWorld().getName();
String _y = String.valueOf(data.getLocation().getBlockY()); BetterRTP.debug("Queue position generated"
String _z = String.valueOf(data.getLocation().getBlockZ()); + ": id= " + id + ", database_ID= " + data.database_id
String _world = data.getLocation().getWorld().getName(); + ", location= x: " + _x + ", y: " + _y + ", z: " + _z + ", world: " + _world);
BetterRTP.debug("Queue position generated" } else
+ ": id= " + id + ", database_ID= " + data.database_id BetterRTP.debug("Database error occurred for a queue when trying to save: " + safeLoc);
+ ", location= x: " + _x + ", y: " + _y + ", z: " + _z + ", world: " + _world); queueGenerator(reQueueData);
} else });
BetterRTP.debug("Database error occurred for a queue when trying to save: " + safeLoc); } else
queueGenerator(reQueueData); queueGenerator(reQueueData);
}); }).exceptionally(error -> {
} else BetterRTP.getInstance().getLogger().log(java.util.logging.Level.WARNING,
queueGenerator(reQueueData); "Failed to generate queue position for " + id + " at " + loc, error);
}); queueGenerator(reQueueData);
return null;
}); });
} else { } else {
BetterRTP.debug("Queue position wasn't able to generate a location!"); BetterRTP.debug("Queue position wasn't able to generate a location!");
@@ -4,6 +4,12 @@ import com.tcoded.folialib.impl.ServerImplementation;
import com.tcoded.folialib.wrapper.task.WrappedTask; import com.tcoded.folialib.wrapper.task.WrappedTask;
import me.SuperRonanCraft.BetterRTP.BetterRTP; import me.SuperRonanCraft.BetterRTP.BetterRTP;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.Location;
import org.bukkit.Chunk;
import io.papermc.lib.PaperLib;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.Supplier;
public class AsyncHandler { public class AsyncHandler {
@@ -15,6 +21,47 @@ public class AsyncHandler {
getFolia().runNextTick(task -> runnable.run()); getFolia().runNextTick(task -> runnable.run());
} }
public static void syncAtLocation(Location location, Runnable runnable) {
getFolia().runAtLocation(location, task -> runnable.run());
}
/** Load and inspect a chunk on its owning region, including PaperLib's sync fallback. */
public static CompletableFuture<Void> atLoadedChunk(Location location, Runnable action) {
return atLoadedChunk(task -> syncAtLocation(location, task),
() -> PaperLib.getChunkAtAsync(location), action);
}
static CompletableFuture<Void> atLoadedChunk(Consumer<Runnable> scheduler,
Supplier<CompletableFuture<Chunk>> loader, Runnable action) {
CompletableFuture<Void> result = new CompletableFuture<>();
schedule(scheduler, () -> loader.get().whenComplete((chunk, error) -> {
if (error != null) {
result.completeExceptionally(error);
} else {
// Future completion alone does not guarantee ownership of the destination region.
schedule(scheduler, () -> {
action.run();
result.complete(null);
}, result);
}
}), result);
return result;
}
private static void schedule(Consumer<Runnable> scheduler, Runnable action, CompletableFuture<Void> result) {
try {
scheduler.accept(() -> {
try {
action.run();
} catch (Throwable error) {
result.completeExceptionally(error);
}
});
} catch (Throwable error) {
result.completeExceptionally(error);
}
}
public static void syncAtEntity(Entity entity, Runnable runnable) { public static void syncAtEntity(Entity entity, Runnable runnable) {
getFolia().runAtEntity(entity, task -> runnable.run()); getFolia().runAtEntity(entity, task -> runnable.run());
} }
@@ -0,0 +1,180 @@
package me.SuperRonanCraft.BetterRTP.player.rtp;
import org.bukkit.Chunk;
import org.bukkit.entity.Player;
import org.junit.Test;
import java.lang.reflect.Proxy;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.*;
public class RTPOperationTest {
private final RTPOperationTracker tracker = new RTPOperationTracker();
private final UUID uuid = UUID.randomUUID();
private final Object session = new Object();
private final AtomicReference<Throwable> error = new AtomicReference<>();
private RTPOperationTracker.Operation start() { return tracker.start(uuid, session); }
private Runnable unexpected() { return () -> fail("Unexpected continuation"); }
private RTPPlayer request(RTPOperationTracker.Operation operation) {
Player player = (Player) Proxy.newProxyInstance(Player.class.getClassLoader(), new Class<?>[]{Player.class},
(proxy, method, args) -> {
if (method.getName().equals("isOnline")) return true;
if (method.getName().equals("getUniqueId")) return uuid;
throw new UnsupportedOperationException(method.getName());
});
return new RTPPlayer(player, null, null, RTP_TYPE.JOIN, operation) {
@Override void logError(Throwable failure) { error.set(failure); }
};
}
@Test public void cancelledPreEventDoesNotStartInstantSearch() {
RTPOperationTracker.Operation operation = start();
request(operation).afterPreEvent(true, unexpected());
assertNull(error.get());
assertFalse(tracker.contains(uuid));
}
@Test public void cancelledPreEventDisposesDelayAndDoesNotSchedule() {
RTPOperationTracker.Operation operation = start();
AtomicInteger disposed = new AtomicInteger();
operation.onFinish(disposed::incrementAndGet);
request(operation).afterPreEvent(true, unexpected());
assertNull(error.get());
operation.finish();
assertEquals(1, disposed.get());
assertFalse(tracker.contains(uuid));
}
@Test public void exceptionalChunkFutureEndsOperation() {
RTPOperationTracker.Operation operation = start();
CompletableFuture<Chunk> future = new CompletableFuture<>();
request(operation).awaitChunk(future, unexpected());
RuntimeException failure = new RuntimeException("chunk load failed");
future.completeExceptionally(failure);
assertSame(failure, error.get());
assertFalse(tracker.contains(uuid));
}
@Test public void exceptionInChunkContinuationEndsOperation() {
RTPOperationTracker.Operation operation = start();
RuntimeException failure = new RuntimeException("location check failed");
request(operation).awaitChunk(CompletableFuture.completedFuture(null), () -> { throw failure; });
assertSame(failure, error.get());
assertFalse(tracker.contains(uuid));
}
@Test public void exceptionalTeleportFutureEndsOperation() {
RTPOperationTracker.Operation operation = start();
CompletableFuture<Boolean> future = new CompletableFuture<>();
operation.complete(future, unexpected(), unexpected(), error::set);
RuntimeException failure = new RuntimeException("teleport failed");
future.completeExceptionally(failure);
assertSame(failure, error.get());
assertFalse(tracker.contains(uuid));
}
@Test public void falseTeleportRunsFailureOnly() {
AtomicInteger failures = new AtomicInteger();
start().complete(CompletableFuture.completedFuture(false), unexpected(), failures::incrementAndGet, error::set);
assertEquals(1, failures.get());
assertNull(error.get());
assertFalse(tracker.contains(uuid));
}
@Test public void exceptionInPostTeleportEffectsStillCleansUp() {
RuntimeException failure = new RuntimeException("effect failed");
start().complete(CompletableFuture.completedFuture(true), () -> { throw failure; }, unexpected(), error::set);
assertSame(failure, error.get());
assertFalse(tracker.contains(uuid));
}
@Test public void successRunsOnceAndReleasesOperation() {
AtomicInteger successes = new AtomicInteger();
start().complete(CompletableFuture.completedFuture(true), successes::incrementAndGet, unexpected(), error::set);
assertEquals(1, successes.get());
assertFalse(tracker.contains(uuid));
}
@Test public void quitAndStaleCompletionCannotRemoveNewOperation() {
RTPOperationTracker.Operation old = start();
CompletableFuture<Boolean> future = new CompletableFuture<>();
old.complete(future, unexpected(), unexpected(), error::set);
tracker.cancel(uuid, session);
RTPOperationTracker.Operation current = tracker.start(uuid, new Object());
tracker.cancel(uuid, session);
future.complete(true);
old.finish();
assertTrue(current.isActive());
assertNull(error.get());
}
@Test public void reloadClearsAllAndRunsEachCleanupOnce() {
RTPOperationTracker.Operation first = start();
RTPOperationTracker.Operation second = tracker.start(UUID.randomUUID(), new Object());
AtomicInteger disposed = new AtomicInteger();
first.onFinish(disposed::incrementAndGet);
second.onFinish(disposed::incrementAndGet);
tracker.clear();
tracker.clear();
assertEquals(2, disposed.get());
assertFalse(first.isActive());
assertFalse(second.isActive());
first.onFinish(disposed::incrementAndGet);
assertEquals(3, disposed.get());
}
@Test public void cleanupFailureDoesNotRetainOtherOperations() {
RTPOperationTracker.Operation first = start();
RTPOperationTracker.Operation second = tracker.start(UUID.randomUUID(), new Object());
AtomicInteger disposed = new AtomicInteger();
first.onFinish(() -> { throw new IllegalStateException("task cancellation failed"); });
first.onFinish(disposed::incrementAndGet);
second.onFinish(disposed::incrementAndGet);
try { tracker.clear(); fail("Expected cleanup failure"); } catch (IllegalStateException expected) { }
assertEquals(2, disposed.get());
assertFalse(first.isActive());
assertFalse(second.isActive());
}
@Test public void duplicateRequestCannotReplaceActiveRequest() {
RTPOperationTracker.Operation first = start();
assertNull(start());
assertTrue(first.isActive());
}
@Test public void lifecycleCleanupUnregistersListenerEvenWhenTaskCancelThrows() {
org.bukkit.event.HandlerList handlers = new org.bukkit.event.HandlerList();
org.bukkit.event.Listener listener = new org.bukkit.event.Listener() {};
org.bukkit.plugin.Plugin plugin = (org.bukkit.plugin.Plugin) Proxy.newProxyInstance(
org.bukkit.plugin.Plugin.class.getClassLoader(), new Class<?>[]{org.bukkit.plugin.Plugin.class},
(proxy, method, args) -> {
if (method.getName().equals("isEnabled")) return true;
throw new UnsupportedOperationException(method.getName());
});
handlers.register(new org.bukkit.plugin.RegisteredListener(listener, (target, event) -> {},
org.bukkit.event.EventPriority.NORMAL, plugin, false));
AtomicInteger cancelled = new AtomicInteger();
com.tcoded.folialib.wrapper.task.WrappedTask task = new com.tcoded.folialib.wrapper.task.WrappedTask() {
public void cancel() { cancelled.incrementAndGet(); throw new IllegalStateException("cancel failed"); }
public boolean isCancelled() { return cancelled.get() > 0; }
public org.bukkit.plugin.Plugin getOwningPlugin() { return plugin; }
public boolean isAsync() { return false; }
};
RTPOperationTracker.Operation operation = start();
operation.onFinish(() -> RTPDelay.dispose(task, listener));
try {
assertEquals(1, handlers.getRegisteredListeners().length);
try { tracker.clear(); fail("Expected task cancellation failure"); }
catch (IllegalStateException expected) { }
assertEquals(0, handlers.getRegisteredListeners().length);
assertEquals(1, cancelled.get());
assertFalse(tracker.contains(uuid));
} finally {
handlers.unregister(listener);
}
}
}
@@ -0,0 +1,116 @@
package me.SuperRonanCraft.BetterRTP.references.player.playerdata;
import me.SuperRonanCraft.BetterRTP.references.database.DatabasePlayers;
import org.bukkit.entity.Player;
import org.junit.Test;
import java.lang.reflect.Proxy;
import java.util.UUID;
import static org.junit.Assert.*;
public class PlayerSessionTest {
private Player player(UUID id) {
return (Player) Proxy.newProxyInstance(Player.class.getClassLoader(), new Class<?>[]{Player.class},
(proxy, method, args) -> {
if (method.getName().equals("getUniqueId")) return id;
if (method.getName().equals("hashCode")) return System.identityHashCode(proxy);
if (method.getName().equals("equals")) return proxy == args[0];
throw new UnsupportedOperationException(method.getName());
});
}
@Test public void deferredLookupAndLoadCannotRestoreDepartedSession() {
PlayerDataManager manager = new PlayerDataManager();
Player player = player(UUID.randomUUID());
PlayerData session = manager.startSession(player);
manager.clear(player);
assertNull(manager.getData(player));
manager.applyIfCurrent(session, data -> fail("Departed session was updated"));
assertNull(manager.getData(player.getUniqueId()));
}
@Test public void oldCallbacksAndQuitCannotAffectReconnect() {
PlayerDataManager manager = new PlayerDataManager();
UUID id = UUID.randomUUID();
Player oldPlayer = player(id), newPlayer = player(id);
PlayerData old = manager.startSession(oldPlayer);
manager.clear(oldPlayer);
PlayerData current = manager.startSession(newPlayer);
manager.applyIfCurrent(old, data -> data.setRtpCount(99));
manager.clear(oldPlayer);
assertNull(manager.getData(oldPlayer));
assertSame(current, manager.getData(newPlayer));
assertSame(newPlayer, current.player);
assertEquals(0, current.getRtpCount());
}
@Test public void reloadInvalidatesOldLoadEvenForSamePlayerObject() {
PlayerDataManager manager = new PlayerDataManager();
Player player = player(UUID.randomUUID());
PlayerData old = manager.startSession(player);
manager.clear();
PlayerData current = manager.startSession(player);
manager.applyIfCurrent(old, data -> fail("Old reload generation was updated"));
manager.applyIfCurrent(current, data -> data.setRtpCount(7));
assertEquals(7, current.getRtpCount());
}
@Test public void pendingSaveKeepsCapturedValuesAfterMutationAndQuit() {
PlayerDataManager manager = new PlayerDataManager();
Player player = player(UUID.randomUUID());
PlayerData data = manager.startSession(player);
data.setRtpCount(12);
data.setGlobalCooldown(123456L);
DatabasePlayers.Snapshot pending = DatabasePlayers.Snapshot.capture(data);
data.setRtpCount(0);
data.setGlobalCooldown(0);
manager.clear(player);
assertEquals(player.getUniqueId(), pending.uuid);
assertEquals(12, pending.count);
assertEquals(123456L, pending.cooldown);
assertNull(manager.getData(player));
}
@Test public void deferredDatabaseWriterUsesSnapshotAfterQuit() throws Exception {
PlayerDataManager manager = new PlayerDataManager();
Player player = player(UUID.randomUUID());
PlayerData data = manager.startSession(player);
data.setRtpCount(23);
data.setGlobalCooldown(987654L);
java.util.concurrent.CountDownLatch release = new java.util.concurrent.CountDownLatch(1);
java.util.concurrent.atomic.AtomicReference<java.util.List<Object>> written =
new java.util.concurrent.atomic.AtomicReference<>();
DatabasePlayers database = new DatabasePlayers() {
@Override protected boolean sqlUpdate(String sql, java.util.List<Object> params) {
written.set(params);
return true;
}
};
// Table setup without starting Bukkit or opening a database connection.
java.lang.reflect.Field tables = database.getClass().getSuperclass().getSuperclass().getDeclaredField("tables");
tables.setAccessible(true);
tables.set(database, java.util.Collections.singletonList("Players"));
java.util.concurrent.ExecutorService executor =
me.SuperRonanCraft.BetterRTP.references.database.SQLiteExecutor.EXECUTOR;
executor.submit(() -> {
try { release.await(5, java.util.concurrent.TimeUnit.SECONDS); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
try {
database.setData(data);
data.setRtpCount(0);
data.setGlobalCooldown(0);
manager.clear(player);
} finally {
release.countDown();
}
executor.submit(() -> {}).get(5, java.util.concurrent.TimeUnit.SECONDS);
assertEquals(java.util.Arrays.asList(player.getUniqueId().toString(), 23, 987654L), written.get());
assertNull(manager.getData(player));
}
@Test public void lookupNeverCreatesSessionAndAcceptsNull() {
PlayerDataManager manager = new PlayerDataManager();
assertNull(manager.getData((Player) null));
assertNull(manager.getData(player(UUID.randomUUID())));
}
}
@@ -0,0 +1,81 @@
package me.SuperRonanCraft.BetterRTP.versions;
import org.bukkit.Chunk;
import org.junit.Test;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.Assert.*;
public class AsyncHandlerTest {
@Test public void synchronousFallbackLoadsOnlyOnRegionAndReschedulesInspection() {
Queue<Runnable> region = new ArrayDeque<>();
AtomicBoolean loaded = new AtomicBoolean();
AtomicBoolean checked = new AtomicBoolean();
CompletableFuture<Void> result = AsyncHandler.atLoadedChunk(region::add, () -> {
loaded.set(true);
return CompletableFuture.completedFuture(null);
}, () -> checked.set(true));
assertFalse(loaded.get());
region.remove().run();
assertTrue(loaded.get());
assertFalse(checked.get());
assertFalse(result.isDone());
region.remove().run();
assertTrue(checked.get());
result.join();
}
@Test public void asynchronousCompletionDoesNotInspectBlocksOnCompletingThread() {
Queue<Runnable> region = new ArrayDeque<>();
CompletableFuture<Chunk> chunk = new CompletableFuture<>();
AtomicBoolean checked = new AtomicBoolean();
CompletableFuture<Void> result = AsyncHandler.atLoadedChunk(region::add, () -> chunk,
() -> checked.set(true));
region.remove().run();
assertTrue(region.isEmpty());
chunk.complete(null);
assertFalse(checked.get());
region.remove().run();
assertTrue(checked.get());
result.join();
}
@Test public void synchronousLoadFailureIsReported() {
RuntimeException failure = new RuntimeException("load failed");
assertFailure(failure, AsyncHandler.atLoadedChunk(Runnable::run, () -> { throw failure; },
() -> fail("Must not inspect failed chunk")));
}
@Test public void asynchronousLoadFailureIsReported() {
RuntimeException failure = new RuntimeException("load failed");
CompletableFuture<Chunk> chunk = new CompletableFuture<>();
CompletableFuture<Void> result = AsyncHandler.atLoadedChunk(Runnable::run, () -> chunk,
() -> fail("Must not inspect failed chunk"));
chunk.completeExceptionally(failure);
assertFailure(failure, result);
}
@Test public void inspectionFailureIsReported() {
RuntimeException failure = new RuntimeException("inspection failed");
assertFailure(failure, AsyncHandler.atLoadedChunk(Runnable::run,
() -> CompletableFuture.completedFuture(null), () -> { throw failure; }));
}
@Test public void schedulingFailureIsReported() {
RuntimeException failure = new RuntimeException("scheduling failed");
assertFailure(failure, AsyncHandler.atLoadedChunk(task -> { throw failure; },
() -> { fail("Must not load without region ownership"); return null; }, () -> {}));
}
private static void assertFailure(Throwable expected, CompletableFuture<Void> result) {
try {
result.join();
fail("Expected failure");
} catch (CompletionException failure) {
assertSame(expected, failure.getCause());
}
}
}
+2 -2
View File
@@ -7,7 +7,7 @@
<groupId>me.SuperRonanCraft</groupId> <groupId>me.SuperRonanCraft</groupId>
<artifactId>BetterRTPAddons</artifactId> <artifactId>BetterRTPAddons</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<version>1.8.10</version> <version>1.8.11</version>
<properties> <properties>
<editor.website>https://www.minecentral.net</editor.website> <editor.website>https://www.minecentral.net</editor.website>
@@ -169,7 +169,7 @@
<dependency> <dependency>
<groupId>me.SuperRonanCraft</groupId> <groupId>me.SuperRonanCraft</groupId>
<artifactId>BetterRTP</artifactId> <artifactId>BetterRTP</artifactId>
<version>3.6.13</version> <version>3.6.15</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<!-- ProtocolLib --> <!-- ProtocolLib -->
@@ -35,9 +35,17 @@ public class AddonsHandler {
} }
public void unload() { public void unload() {
for (Addons addon : addons) try {
addon.disable(); for (Addons addon : addons)
addons.clear(); addon.disable();
} finally {
addons.clear();
// Core retains these command objects after this plugin's classloader closes.
BetterRTP core = BetterRTP.getInstance();
if (core != null && core.getCmd() != null)
core.getCmd().commands.removeIf(command ->
command.getClass().getClassLoader() == getClass().getClassLoader());
}
} }
public enum Addons { public enum Addons {
@@ -41,8 +41,11 @@ public class Main extends JavaPlugin {
@Override @Override
public void onDisable() { public void onDisable() {
if (editorBridge != null) editorBridge.close(); try {
addonsHandler.unload(); if (editorBridge != null) editorBridge.close();
} finally {
addonsHandler.unload();
}
} }
public void load() { public void load() {
+4 -4
View File
@@ -37,8 +37,8 @@ BetterRTP uses and is compiled with the following libraries:
From this directory, run `mvn clean package` to build BetterRTP followed by BetterRTP Addons. Maven resolves Addons against the BetterRTP built in the same run; a separate `install` step is unnecessary. From this directory, run `mvn clean package` to build BetterRTP followed by BetterRTP Addons. Maven resolves Addons against the BetterRTP built in the same run; a separate `install` step is unnecessary.
- BetterRTP JAR: `dist/BetterRTP-3.6.13.jar` - BetterRTP JAR: `dist/BetterRTP-3.6.15.jar`
- Addons JAR: `dist/BetterRTPAddons-1.8.10.jar` - Addons JAR: `dist/BetterRTPAddons-1.8.11.jar`
Both server-ready JARs are collected in `dist/`. `mvn clean` removes each selected plugin’s previous JARs from this folder; intermediate build files stay in `target/`. The `dev` profile still outputs directly to its configured server plugins folder. Both server-ready JARs are collected in `dist/`. `mvn clean` removes each selected plugin’s previous JARs from this folder; intermediate build files stay in `target/`. The `dev` profile still outputs directly to its configured server plugins folder.
@@ -95,10 +95,10 @@ Use the website's schema-version database migrations before deploying these clie
### Automatic Maven releases ### Automatic Maven releases
`.github/workflows/release.yml` runs on pushes to `online-editor` (or manually from `.github/workflows/release.yml` runs on pushes to `master` (or manually from
that branch). It reads only the Core POM version, builds and verifies BetterRTP Core, that branch). It reads only the Core POM version, builds and verifies BetterRTP Core,
runs the editor tests, and publishes a stable GitHub release with exactly one plugin runs the editor tests, and publishes a stable GitHub release with exactly one plugin
JAR. For the current Core POM the title is `BetterRTP 3.6.13` and the tag is `v3.6.13`. JAR. For the current Core POM the title is `BetterRTP 3.6.15` and the tag is `v3.6.15`.
This single-JAR release is compatible with the website's GitHub release importer. This single-JAR release is compatible with the website's GitHub release importer.
Both Core and Addons editor-schema JSON files remain attached for the website editor. Both Core and Addons editor-schema JSON files remain attached for the website editor.
+126
View File
@@ -0,0 +1,126 @@
# BetterRTP memory-retention analysis
Reviewed 2026-11-18 at commit `04309fb`; core POM version 3.6.13. Scope: BetterRTP-Core player lifecycle, cooldown persistence, RTP execution, menus, queues, scheduling, and shutdown. Addons were screened but are not covered by the conclusions below. This is source analysis plus an isolated Java reproduction, not a production heap diagnosis. No plugin behavior was changed.
All source references below are relative to `BetterRTP-Core/src/main/java/me/SuperRonanCraft/BetterRTP/`.
## Implementation status: deferred player lookups
Finding 1 has now been addressed in the working tree. The findings below describe the original reviewed commit; the other issues remain separate work.
- Sessions are created explicitly on join and for online players during enable/reload, and cleared on quit/disable. `getData(Player)` is now a nullable, non-creating lookup that rejects a different Player instance for the same UUID. External integrations using this API must handle absent sessions.
- Cooldown loads capture the session before scheduling, avoid duplicate loads, and apply results through an atomic current-session check. Old results cannot update a replacement session or repopulate the map.
- Player saves capture immutable UUID/count/timestamp values before executor submission. Per-world saves copy the cooldown timestamp before scheduling. Deferred writers do not look up or capture PlayerData/Player.
- Core placeholder, menu, damage, and effect callers handle absent session data.
- Validation: `mvn -o -q -f BetterRTP-Core/pom.xml test` passed six regression tests, including a blocked database executor released after session mutation/quit. Quit, reconnect, reload, and non-creating reads are covered. Live Paper/Folia integration has not been exercised.
## 1. High: deferred player lookups recreate cache entries after quit
Evidence: `references/player/playerdata/PlayerDataManager.java:15`, `PlayerData.java:16`, `references/player/HelperPlayer.java:13`, `player/events/Join.java:25`, `references/rtpinfo/CooldownHandler.java:130-166`.
`getData(Player)` is a creating operation: `computeIfAbsent` installs a PlayerData containing a strong, final Player reference. Neither this method nor loadPlayer checks whether that player session remains active. Quit only removes the UUID from this map.
Two concrete sequences:
1. Join schedules async loadPlayer(p); player quits and the cache is cleared; the async task starts and getData(p) creates a new entry for the departed player.
2. A cooldown change schedules savePlayer(p); player quits; the save callback calls `DatabaseHandler.getPlayers().setData(getData(player))`, recreating the cache entry.
The entry has no expiry or offline sweep. It remains until another explicit clear for that UUID or a plugin reload. A stream of different departing players can grow the map beyond the online population. Reference path: plugin -> PlayerDataManager -> map -> PlayerData -> Player. The exact retained bytes behind Player require heap inspection; this does not establish that every loaded chunk is retained by each player.
The save race also risks overwriting persisted count/global cooldown with defaults: the callback can obtain a newly created empty PlayerData instead of the state that originally triggered the save. If the player reconnects while the stale entry exists, getData(newPlayer) returns data whose final player field still refers to the previous session. UUID keys alone do not solve this.
Important distinction: when loadPlayer obtained PlayerData before quit, updating that detached object afterward does not itself reinsert it. The problematic insertion is the creating lookup after removal. ConcurrentHashMap makes map operations safe but does not make join/quit/callback ordering correct.
Validation: compiled the actual, unmodified PlayerDataManager and PlayerData sources with minimal Bukkit/annotation/menu stubs. Simulated 1,000 join -> clear -> deferred lookup sequences: 1,000 entries remained. Reconnecting with a different Player instance and the same UUID returned the old Player reference. This validates cache semantics, not real scheduler timing or production incidence. Reproduction is in `/tmp/betterrtp-retention-2sz2g7g5/Repro.java` for this workspace session.
Recommended correction: create session state explicitly on join; separate non-creating lookup from creation; invalidate the session on quit; carry a session token through callbacks. Save immutable UUID/count/timestamp snapshots captured before scheduling, without looking up PlayerData in the writer. Apply loaded results only if the original session is still current. An isOnline check alone still leaves check/remove/insert and reconnect races.
## Implementation status: RTP operation cleanup
Finding 2 is addressed on `fix/rtp-operation-cleanup`, based on the deferred-lookup fix. The original findings below remain as historical evidence.
- Replaced the Player-keyed boolean map with a synchronized UUID-keyed operation registry. Each request has its own identity and session owner; duplicate starts are rejected, and stale completion/quit cannot remove a newer operation.
- Both pre-teleport cancellation modes end the operation. Chunk-load failures, synchronous work exceptions, unsuccessful teleport results, and exceptions in success effects also release it. Unexpected errors are logged.
- Quit, reload, and disable end active operations. Delay cleanup cancels its task and unregisters its listener, including when task cancellation throws. Cleanup is idempotent and clears resource callbacks.
- Deferred search/delay callbacks check whether their request remains active. Cancelled location-event retries increment attempts before scheduling another retry, avoiding recursive stack growth.
- Compatibility: the mutable `PlayerInfo.getRtping()` API was removed. Integrations checking activity should use `getRTP().getOperations().contains(player.getUniqueId())`; they must not independently mutate tracking state.
- Validation: `mvn -o -q -f BetterRTP-Core/pom.xml test` passed 19 tests (13 operation tests plus the existing 6 session tests). These exercise shared pre-event cancellation handling, actual chunk continuation handling, terminal future outcomes, cleanup after effect exceptions, stale completions, lifecycle cleanup, and Bukkit listener unregistration even when task cancellation fails. Full plugin event/scheduler integration on Paper/Folia has not been exercised.
- Limits: no timeout policy was added for a future that never completes while its player remains online. Logical cancellation does not guarantee cancellation of underlying chunk IO or an already-started teleport. Other menu, executor, and queue-generation findings remain separate work.
## 2. High: RTP operation map has permanent retention paths
Evidence: `player/PlayerInfo.java:19,45-59`, `player/rtp/RTP.java:82-94`, `RTPDelay.java:31-36`, `RTPPlayer.java:64-76`, `RTPTeleport.java:55-71`, and `player/events/Leave.java:9-12`.
`PlayerInfo.rtping` is a HashMap keyed by Player. RTP inserts before firing the teleport pre-event. If another plugin cancels that event, both instant and delayed paths stop without removing the entry. This is a direct persistent retention path, even without a database race. Quit does not clear it; PlayerInfo.unload and unloadAll are private and never invoked.
Additional ways to strand the entry:
- The chunk-loading continuation has no exceptional completion handler. Its surrounding catch also silently discards Throwable without cleanup.
- teleportAsync uses thenRun, so exceptional completion skips cleanup. Errors thrown by afterTeleport also skip the later removal.
- A false Boolean teleport result still runs the success path because thenRun ignores the result; this is a correctness issue separate from retention.
Ordinary completion can remove an entry; this is not a claim that every RTP leaks. The cancellation and failure paths make retention possible without a later cleanup guarantee. Player keys can retain distinct disconnected session objects across reconnects.
Recommended correction: centralize idempotent operation completion and use it for success, cancellation, exceptions, quit, reload, and disable. Scope removal to the operation/session so an old callback cannot clear a newer request. Handle both exceptional completion and unsuccessful teleport results. Use thread-safe or correctly scheduler-confined state for supported Folia execution.
## 3. High/medium: RTP keeps searching after disconnect
Evidence: `player/rtp/RTPDelay.java:72-78`, `RTPPlayer.java:38-114`, `RTPTeleport.java:40-85`, and `player/rtp/effects/RTPEffect_Potions.java:56`.
Quit does not cancel a delay or in-progress search. The delay checks rtping, which quit does not clear. Search callbacks do not verify online/session/operation state before generating locations, loading chunks, charging, adding cooldowns, or teleporting. Later cooldown and effect lookups can recreate PlayerData as in finding 1.
Ordinary failed-location retries are limited by maxAttempts, so these callbacks alone are not necessarily a permanent leak. They are avoidable post-quit work and temporary Player retention that can feed permanent caches. An unresolved chunk future can prolong retention; no application timeout exists.
A separate retry bug exists at RTPPlayer.java:46-49: when the location event is cancelled, recursive randomlyTeleport runs before attempts is incremented. Repeated cancellation can cause stack overflow instead of reaching the attempt limit. Treat this as a control-flow/resource-exhaustion bug, not proof of a growing heap cache.
Recommended correction: cancel the logical operation on quit, check its token at every async boundary and before side effects, bound its lifetime, and guarantee terminal cleanup. Do not assume cancelling a future stops underlying chunk IO. Count attempts before retrying and schedule retries without recursive stack growth.
## 4. Medium: settings menu maps retain players
Evidence: `player/PlayerInfo.java:16-17,31-36,41-66`, `references/invs/types/RTPInvCoordinates.java:18-22`, `RTPInvWorlds.java:55`, `references/invs/RTPInventories.java:22-29`.
Menu navigation writes Player keys into invWorld and invNextInv. Quit does not clear these maps. The apparent reload cleanup is ineffective: closeAll gates cleanup on playerExists, which checks the legacy invs map; its only insertion method is commented out. Offline users would be skipped by closeAll's online-player loop anyway. No InventoryCloseEvent handler performs cleanup in the core listener.
This is a source-confirmed retention path for users who navigate those settings screens. It affects fewer players than the general cooldown race, but does not require async timing.
Recommended correction: consolidate menu state into session-owned data or explicitly remove all menu references on quit and clear them on reload/disable. Close inventory cleanup must use the active menu state, not the unused legacy map.
## 5. Medium: database backlog and executor lifecycle
Evidence: `references/database/SQLiteExecutor.java:7`, `DatabasePlayers.java:49-85`, `DatabaseQueue.java:63-95`, `BetterRTP.java:78-83`.
A static single-thread executor serves player and queue work, has an unbounded pending-task queue, and is never shut down by plugin code. Writes capture PlayerData, which holds Player. Several callers block on Future.get without an application timeout while holding their own captured Player/world state. Under sustained IO slowdown, queued tasks and waiting async callers can retain an increasing population of objects. This is a conditional backlog, not proof that normal successful queries permanently leak.
After first use, the executor also leaves a worker running across plugin disable. This is a lifecycle leak risk when unloading/replacing the plugin in-process; exact classloader roots should be verified in a heap dump. It is distinct from an ordinary `/rtp reload`, which does not create a fresh static executor.
Recommended correction: own the executor in the plugin lifecycle, define a bounded pending-work policy, snapshot primitive persistence data, expose queue depth/age, and drain/shut down explicitly. Avoid blocking worker threads waiting for other workers. Shutdown must coordinate pending saves before clearing session state.
## 6. Medium/conditional: queue generation can outlive reload
Evidence: `references/rtpinfo/QueueGenerator.java:33-66,165-204`, `QueueHandler.java:48-51`.
Only the latest queueGenerator delayed task is tracked. The initial generate delay is not retained; in-flight chunk/database continuations can call queueGenerator after unload. Concurrent low-queue requests can each enter generate before generating becomes true. Reload or demand bursts can therefore leave multiple chains active and make cancellation incomplete. A request can carry WorldPlayer via RTPWorld, retaining a player through that chain.
This is a lifecycle/concurrency risk, not a demonstrated indefinitely growing in-memory location cache. DatabaseQueue queries explicitly limit results to queueMax + 1 (33). Queue contents are persisted rather than held in an unlimited core list.
Recommended correction: use a generation token and atomic single-flight admission; invalidate the generation on reload/disable and check it before each continuation schedules more work.
## Other observations and limits
- PlaceholderAPI calls creating getData before validating the request and without a null/session guard (`DepPlaceholderAPI.java:40-41`). A stale Player passed by an integration can reproduce finding 1; a null player can throw. This method itself does not issue SQL, and the core contains no active getOfflinePlayer lookup. Do not attribute automatic offline placeholder polling to this plugin without tracing the caller.
- CooldownHandler.downloading removes entries in finally. Under normal completion it is not a permanent leak, although blocked database work prolongs retention. It also allows duplicate loads.
- Most query paths explicitly close JDBC resources. SQLite.close wraps all closes in a single try, so one close failure can prevent subsequent cleanup; use independent try-with-resources. This is exception-path hardening, not evidence that every query leaks connections.
- Metrics' timer cancels when it next notices the plugin disabled, so it can retain the old plugin until that scheduled check (up to roughly 30 minutes). It is not necessarily permanent.
- Logger setup closes the prior file handler. LogUploader bounds uploaded file content. Neither supplied a stronger explanation for offline Player retention.
- No production heap, live server, or user logs were available. No full plugin integration tests were run. External libraries, BetterSync internals, and addon-specific lifecycle bugs are outside this report's validated scope.
## Fix order and validation
1. Introduce explicit session ownership/non-creating reads and snapshot-based persistence.
2. Centralize RTP completion, cancel on quit, and cover cancellation/failure/timeout branches.
3. Remove legacy menu references on quit/reload/disable.
4. Bound and close database work; invalidate queue-generation continuations on reload.
Regression scenarios should deliberately control callback ordering: quit before join-load starts; quit before save starts; reconnect before an old callback finishes; cancelled pre-event in both delay modes; exceptional chunk/teleport futures; exception during post-teleport effects; quit during delay/search; menu use then quit; reload during queue generation; database backlog then shutdown.
For production confirmation, compare retained objects after equivalent join/RTP/quit cycles and after pending work drains. Inspect strong paths from BetterRTP to PlayerDataManager.playerData, PlayerInfo.rtping/invWorld/invNextInv, executor pending tasks, and RTP callback/listener instances. Count offline Player objects in those structures, oldest operation age, database queue depth, and outstanding generation chains. A rising heap before garbage collection alone is insufficient; distinguish live retained objects from allocation churn, ordinary loaded chunks, and work that eventually drains. Expected steady state: no departed session in player/menu/operation maps and no stale callback able to recreate it.
+266
View File
@@ -0,0 +1,266 @@
# BetterRTP multi-version compatibility execution plan
Status: proposed implementation plan; no platform migration has been performed.
Research date: 2026-11-19.
## Objective and constraints
Maintain one codebase with explicitly tested Bukkit/CraftBukkit, Spigot, Paper, and
Folia distributions. Target Minecraft 1.8.8 through the latest verified stable
release, limited to versions on which each platform actually exists. Future
releases become supported only after validation. A successful compile is not a
runtime compatibility guarantee.
Prefer public APIs and maintained upstream libraries. Shading and relocation are
allowed; maintaining our own forks is not the default. Keep BetterRTP free of
NMS/CraftBukkit internals and bytecode rewriting. Avoid scattered reflection and
version-string routing: any necessary capability detection belongs in a small,
tested compatibility boundary or an audited upstream library.
Retain Maven and existing configuration, database, commands, permissions, and
public events unless a separately documented migration is necessary.
Prefer a single user-facing JAR when isolated adapters and upstream libraries
can safely cover the supported runtimes. Use separate builds only when verified
API, bytecode, or dependency constraints justify them. Do not create a fork or permanent branch per Minecraft version.
Do not automatically create a module for every patch release.
## Patterns adopted from existing projects
| Reference | Observed structure | Pattern to adopt |
| --- | --- | --- |
| EssentialsX | BaseProviders, PaperProvider, legacy providers, and an NMSReflectionProvider | Small capability interfaces with isolated implementations; do not copy its NMS approach |
| LuckPerms | common, api, bukkit, bukkit-legacy, and platform loaders | Shared behavior and thin platform entry points; one repository and coordinated releases |
| TAB | shared, platform modules, API-specific submodules, jar assembly, and a compatibility/backport policy | Add build boundaries at demonstrated API changes and publish explicit compatibility ranges |
| SkinsRestorer | shared, multiver, platform modules, test, and universal assembly | Isolate version-sensitive implementation and integration code; centralize packaging and testing |
Borrow verified patterns, not entire implementations or their complexity. Their
use of internal APIs does not establish that BetterRTP needs internal APIs. Their development branches can differ from released artifacts.
Pin reviewed commits when using their implementation details during execution.
Do not copy their code without reviewing applicable licenses.
Sources reviewed:
- https://github.com/EssentialsX/Essentials/blob/2.x/settings.gradle.kts
- https://github.com/LuckPerms/LuckPerms/blob/master/settings.gradle
- https://github.com/NEZNAMY/TAB/blob/master/settings.gradle.kts
- https://github.com/NEZNAMY/TAB/wiki/Compatibility
- https://github.com/SkinsRestorer/SkinsRestorer/blob/dev/settings.gradle.kts
## Current baseline and known gaps
- Core compiles against Spigot 1.8.8 with a Java 8 release target.
- Core shades PaperLib, FoliaLib, BetterSync, and potentially other compile dependencies.
- QueueGenerator now schedules chunk loading and safety inspection at the destination.
This change is still uncommitted and must be preserved during implementation.
- RTPPlayer still routes chunk loading and player operations through global sync tasks.
- RTPTeleport still uses PaperLib teleportation. RandomLocation contains a PaperLib
chunk diagnostic. Commented-out calls must be distinguished from executable code.
- Effects, third-party hooks, database driver provisioning, and bundled dependencies
need inspection beyond the queue fix.
- Reflection exists in optional claim integrations, metrics, packet helpers, and
JDBC driver loading. Classify these uses; driver loading is not server API probing.
- Existing unit tests are useful, but no full real-server compatibility matrix is established.
## Proposed module boundaries
Keep BetterRTP-Core initially; extract modules incrementally instead of moving
all source files in one change.
- betterrtp-api: stable public events and integration contracts; preserve existing
package names and verify BetterRTPAddons consumers.
- betterrtp-core: request lifecycle, configuration, queue policy, location selection,
and orchestration. Initially allow the oldest supported Bukkit API as a baseline;
do not require a costly rewrite into a completely server-independent model.
- betterrtp-platform-api: scheduling, chunk readiness, teleportation, world-height,
and effect capabilities expressed without modern platform types.
- betterrtp-platform-bukkit: legacy public Bukkit implementation, Java 8 compatible.
- betterrtp-platform-paper-<baseline>: native asynchronous APIs compiled against
the earliest verified API in that compatible range.
- betterrtp-platform-folia-<baseline>: public region/entity scheduler implementation.
- betterrtp-integrations: separate optional hook modules where dependency versions
require isolation; classes must not load before their dependency is available.
- betterrtp-distributions: explicit bootstrap and plugin descriptors per build family.
- tests/compatibility: server harness, fixtures, test companion, and result collection.
Modern adapters can use newer toolchains while the shared/legacy modules retain
Java 8 bytecode and API compatibility. A legacy runtime must never load incompatible
classes or resolve unavailable APIs. If a universal artifact includes isolated modern
classes, prove safe class loading on the oldest runtime and verify server tooling
does not eagerly scan them. Otherwise split artifacts. Confirm real API boundaries
before assigning exact adapter ranges. The module list is conceptual: create only
the boundaries the implementation actually needs.
Keep implementation selection centralized and tested. Package first-party modules
and approved dependencies with Maven Shade as appropriate. Relocate private library
packages to avoid plugin conflicts; do not relocate public integration APIs or bundle
server APIs. Preserve licenses and required service descriptors. Avoid aggressive
JAR minimization unless runtime-loaded classes are covered by tests. Publish one JAR
if validated; otherwise use build-specific metadata and descriptive filenames such
as BetterRTP-<release>-<platform>-<verified-range>.jar.
## Execution work packages
### 1. Inventory and support manifest
Deliver a dependency inventory and a machine-readable support manifest containing:
platform, exact Minecraft version, server build identity/checksum, Java runtime,
adapter, artifact, integration set, and validation status.
Audit all scheduled tasks, future callbacks, world/player access, public events,
plugin lifecycle callbacks, effects, and addon API dependencies. Determine API
and runtime boundaries from actual dependency signatures and executable probes.
Inventory PaperLib, FoliaLib, BetterSync, particle libraries, ProtocolLib usage,
JDBC, metrics, and every optional hook. For each record whether it is provided,
bundled, replaceable with a public API, or requires a declared external plugin.
Keeping BetterSync shaded is allowed; verify its API and runtime compatibility.
Do not introduce an external plugin dependency merely to avoid shading.
For each retained library record upstream activity, supported runtimes, transitive
dependencies, required relocations, and upgrade tests. Prefer an upstream fix or a
maintained replacement over a private fork. Any unavoidable temporary fork needs
a pinned patch, owner, upstream issue, and explicit removal criteria.
If a feature needs an external dependency or a capability downgrade, document the
specific user-visible consequence before implementing that change.
Acceptance: every runtime dependency and compatibility-sensitive operation has
an owner; the initial matrix distinguishes planned, tested, and unsupported rows.
### 2. Establish reproducible real-server tests before refactoring
Create an isolated harness with temporary server directories, localhost-only
ports, pinned Java executables, pinned server builds, timeouts, graceful stop,
and archived logs/results. Obtain binaries through official downloads or official
build tooling as applicable. Handle required EULA acceptance explicitly; do not
silently accept terms or redistribute restricted server binaries.
Initial targets: Spigot 1.8.8, current stable Paper, and current stable Folia.
Add CraftBukkit and historical boundaries as the harness becomes reliable.
Use a small test companion plugin for server-side assertions and compatible test
clients for player flows. Do not assume one bot library supports the whole range.
Keep test-client tooling isolated from the production plugin.
Acceptance: startup and empty-queue scenarios run unattended; tests detect failed
queue generation and plugin enablement errors. A known broken build demonstrates
that the harness fails correctly. Player test tooling can execute and observe /rtp.
Record existing failures rather than declaring the baseline supported.
### 3. Introduce contracts around validated upstream implementations
Define explicit operations for global work, location-owned work, player-owned
work, background I/O, delayed tasks, cancellation, chunk readiness, and teleportation.
Specify callback ownership and completion semantics. A completed future alone
must never imply ownership of a region or player.
First evaluate the supported FoliaLib release against our real-server matrix.
Retain it behind our contracts if it correctly supplies scheduling and teleportation;
do not rewrite it solely to own the implementation. Provide native public API
adapters only for demonstrated gaps. Bukkit fallback operations use main-thread
scheduling and public synchronous chunk/teleport APIs. Define retired-player behavior and rejected scheduling so
requests complete or cancel instead of hanging. Use injectable interfaces in unit
tests; avoid static singleton dependencies in new orchestration code.
Acceptance: existing tests pass and Spigot 1.8.8 scenarios pass using the adapter.
### 4. Close adapter gaps and migrate the RTP flow
Use public async APIs for Paper, directly or through validated libraries.
Use location schedulers for Folia world
inspection, entity schedulers for player operations, and native async teleportation.
Never block a tick thread waiting for a future. Ensure a chunk remains usable
through the region-owned inspection; define ticket/lifetime behavior where needed.
Migrate in this order: QueueGenerator, RTPPlayer search and safety checks,
RTPTeleport, countdowns and post-teleport effects, diagnostics, then remaining tasks.
Capture required player state on its owner, inspect destinations on their owner,
then return to the player owner and revalidate the operation before charging and
teleporting. Define failure/refund and cooldown semantics explicitly.
Audit protection hooks for the thread required by their public APIs. Do not assume
that a destination-region callback makes every third-party integration safe.
Preserve event cancellation and event order while documenting execution context.
Use lifecycle generation tokens/cancellation tracking so reload, quit, disable,
and late completions cannot revive an old request or queue generator.
Acceptance: real RTP, cancellation, cross-region, and cross-world tests pass;
all scheduling/loading/teleport calls pass through tested compatibility contracts.
Replace PaperLib's broken version-dependent paths without creating a private PaperLib
fork by default. FoliaLib may remain as a shaded, pinned upstream dependency.
### 5. Complete dependency and integration separation
Remove superseded libraries only after their callers migrate; retain validated
upstream libraries and their required relocations. Replace version-sensitive
particles/sounds/titles with public API implementations where possible; explicitly
report unavailable optional capabilities instead of attempting internal access.
Resolve BetterSync delivery and JDBC provisioning from the inventory. Keep external
plugin dependencies declared and optional hooks isolated by supported API version.
Compile against API artifacts, removing the full Spigot server dependency if unused.
Acceptance: inspect final JAR contents and dependency trees to verify approved
bundling, relocations, service resources, licenses, and runtime compatibility; startup works with optional plugins absent, present, and unsupported.
No silent loss of protection/economy behavior is acceptable.
### 6. Expand the matrix and enforce architectural rules
Candidate boundary tests: 1.8.8, 1.12.2, 1.13.2, 1.16.5, 1.18.2, 1.19.4,
1.20.4, 1.20.6, and supported 1.21.x/26.x releases. These are starting probes,
not a claim that all intervening versions work. Folia rows exist only for released
Folia versions. Current endpoints and Java requirements must be verified during setup.
Every change: unit tests, all artifact builds, API/bytecode checks, and a small
real-server smoke matrix. Nightly/release: expanded exact-version manifest and
integration scenarios. Test each claimed release, or explicitly narrow the claim.
Enforce forbidden internal API references in BetterRTP, compatibility logic outside
its designated boundary, unapproved dependency bundling, missing required
relocations, modern API leakage into legacy modules, and unsupported bytecode/API
usage. Audit retained libraries for internal access and reflective behavior; document
necessary internals rather than assuming a library automatically meets our policy. Existing violations get explicit migration entries;
new violations fail immediately. Audit dependencies as well as our own source.
Acceptance: deliberately introducing a forbidden reference or wrong bytecode target
fails CI; each distribution has machine-readable test results.
### 7. Release and support policy
One coordinated version and changelog across distributions. Generate a download
compatibility table from the manifest, with exact tested versions and required Java.
Only tested combinations are supported. Add new stable Minecraft releases through
an API audit and matrix run; avoid automatically claiming future compatibility.
Keep a previous known-good artifact available for each supported family. Preserve
config/database compatibility where possible and test upgrade paths with copied
fixtures. Publish explicit migration notes if formats or external dependencies change.
Acceptance: a clean checkout produces all artifacts and reports, and a maintainer
can select the correct download without reading code.
## Required behavioral assertions
- Fresh startup: plugin enables and queue reaches its configured target in a bounded time.
- RTP: real player arrives within configured bounds with safe ground/headroom,
matching biome/world constraints; test queued and uncached destinations.
- World access: normal/Nether/End, negative coordinates, world-height boundaries,
loaded/unloaded/generated/ungenerated chunks, and cross-world teleportation.
- Failure: no safe location, cancelled events, chunk/teleport/database failure,
denied permission, insufficient funds, and unavailable optional dependencies.
- Lifecycle: movement cancellation, quit/rejoin, duplicate commands, config reload,
shutdown, and late future completion; no retained request or resurrected work.
- Folia: independent distant regions, simultaneous players, and player movement
between capture and completion; no wrong-thread access or cross-region deadlock.
- Integrations: protected destinations rejected, charges/refunds and cooldowns applied
exactly as documented, public events remain usable by BetterRTPAddons.
Logs are supporting evidence. Assert outcomes and resource cleanup, not merely the
absence of exceptions. Deterministic worlds/seeds and bounded retries reduce flakes.
Track stress-test performance separately from functional correctness.
## First implementation slice
Execute packages 1 and 2 first: inventory + pinned three-server baseline harness.
Resolve whether validated upstream libraries enable one artifact before committing
to multiple distributions. Then implement the minimal contracts needed for fresh-start queue generation and
one /rtp request. Complete that vertical slice on all three initial platforms before
moving optional effects and integrations. No broad source reorganization first.
The exact number of distributions, API boundaries, external dependency delivery,
and feasible client tooling remain research outcomes, not assumptions hidden in code.
+1 -1
View File
@@ -5,7 +5,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>me.SuperRonanCraft</groupId> <groupId>me.SuperRonanCraft</groupId>
<artifactId>BetterRTP-build</artifactId> <artifactId>BetterRTP-build</artifactId>
<version>3.6.13</version> <version>3.6.15</version>
<packaging>pom</packaging> <packaging>pom</packaging>
<modules> <modules>
<module>BetterRTP-Core</module> <module>BetterRTP-Core</module>