feat(sessions): add configurable Adventure-mode sessions
This commit is contained in:
1 parent
b493cfe192
commit
40e41d6b7a
15 files changed
+967
-28
No files matched your search
@@ -36,11 +36,30 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
private CharacterPresentation presentation;
|
||||
private ProtocolPresentation protocolPresentation;
|
||||
private CharacterChatNames chatNames;
|
||||
private games.dmg.fantasystick.persistence.AdventureSettings adventureSettings;
|
||||
private games.dmg.fantasystick.session.AdventureModeLease gameModes;
|
||||
private java.util.concurrent.CompletionStage<Void> configurationDrain = java.util.concurrent.CompletableFuture.completedStage(null);
|
||||
|
||||
@Override public void onEnable() {
|
||||
try {
|
||||
Object generation = new Object();
|
||||
lifetime = generation;
|
||||
if (!configurationDrain.toCompletableFuture().isDone()) {
|
||||
configurationDrain.whenComplete((ignored, failure) -> {
|
||||
if (lifetime != generation) return;
|
||||
try {
|
||||
getServer().getScheduler().runTask(this, () -> {
|
||||
if (lifetime == generation && isEnabled()) onEnable();
|
||||
});
|
||||
} catch (RuntimeException rejected) {
|
||||
getLogger().log(Level.WARNING, "Configuration startup continuation unavailable", rejected);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
reloadConfig();
|
||||
var adventure = games.dmg.fantasystick.persistence.AdventureSettings.validate(getConfig().get("adventure-mode"));
|
||||
adventureSettings = new games.dmg.fantasystick.persistence.AdventureSettings(getDataFolder().toPath(), adventure);
|
||||
var switchDelay = switchDelay();
|
||||
var defaults = ProgressionRules.defaults();
|
||||
var rules = new ProgressionRules(new java.math.BigInteger(getConfig().getString("starting-points", "40")),
|
||||
@@ -80,12 +99,13 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
java.util.function.Consumer<EquipmentSessions.Failure> diagnostics = problem ->
|
||||
getLogger().log(Level.WARNING, "Equipment transition/recovery for player " + problem.player()
|
||||
+ "; session " + problem.session(), problem.cause());
|
||||
gameModes = new games.dmg.fantasystick.session.AdventureModeLease();
|
||||
sessions = new EquipmentSessions(characters, receipts, switchDelay, Clock.systemUTC(), nextTick,
|
||||
notice -> notifyPlayer(generation, notice), diagnostics, presentation);
|
||||
notice -> notifyPlayer(generation, notice), diagnostics, presentation, adventureSettings::enabled, gameModes);
|
||||
sessionEvents = new EquipmentSessionEvents(sessions, nextTick, diagnostics);
|
||||
admin = new EquipmentAdminCommand(receipts, sessions, getServer(), nextTick,
|
||||
problem -> getLogger().log(Level.WARNING, "Equipment admin " + problem.operation()
|
||||
+ " for player " + problem.player(), problem.cause()));
|
||||
+ " for player " + problem.player(), problem.cause()), adventureSettings);
|
||||
var command = java.util.Objects.requireNonNull(getCommand("fantasystick"), "Missing packaged fantasystick command");
|
||||
command.setExecutor(admin);
|
||||
command.setTabCompleter(admin);
|
||||
@@ -94,6 +114,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
getServer().getPluginManager().registerEvents(anvilNames, this);
|
||||
getServer().getPluginManager().registerEvents(sessionEvents, this);
|
||||
getServer().getPluginManager().registerEvents(chatNames, this);
|
||||
getServer().getPluginManager().registerEvents(gameModes, this);
|
||||
recipeRegistered = getServer().addRecipe(new CharacterSheets().recipe());
|
||||
if (!recipeRegistered) throw new IllegalStateException("Character-sheet recipe key is already registered");
|
||||
for (var player : getServer().getOnlinePlayers()) sessions.arrive(player);
|
||||
@@ -118,13 +139,20 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
var closingSessions = sessions; sessions = null;
|
||||
var closingReceipts = receipts; receipts = null;
|
||||
var closingCharacters = characters; characters = null;
|
||||
var closingSettings = adventureSettings; adventureSettings = null;
|
||||
var closingModes = gameModes; gameModes = null;
|
||||
// Retire client resources independently of successful ordinary-equipment restoration.
|
||||
if (closingPresentation != null) cleanup("presentation", closingPresentation::close);
|
||||
if (closingProtocol != null) cleanup("protocol presentation", closingProtocol::close);
|
||||
if (closingAdmin != null) cleanup("admin command", closingAdmin::close);
|
||||
if (closingSettings != null) {
|
||||
configurationDrain = closingSettings.drained();
|
||||
cleanup("configuration", closingSettings::close);
|
||||
}
|
||||
if (closingEvents != null) cleanup("session events", closingEvents::close);
|
||||
if (closingCrafting != null) cleanup("craft attempts", closingCrafting::close);
|
||||
if (closingSessions != null) cleanup("equipment sessions", closingSessions::close);
|
||||
unregister(closingModes);
|
||||
unregister(closingChat);
|
||||
unregister(closingEvents);
|
||||
unregister(closingCrafting);
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
package games.dmg.fantasystick.persistence;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.OverlappingFileLockException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import org.yaml.snakeyaml.LoaderOptions;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||
|
||||
/** Worker-owned config writes; publish a new-session policy only after durable file acknowledgment. */
|
||||
public final class AdventureSettings implements AutoCloseable {
|
||||
private static final int MAX_BYTES = 1_048_576;
|
||||
@FunctionalInterface interface Replacement { void move(Path from, Path to) throws IOException; }
|
||||
private final Path directory;
|
||||
private final Replacement replacement;
|
||||
private final java.util.concurrent.ExecutorService worker = Executors.newSingleThreadExecutor(
|
||||
task -> new Thread(task, "fantasy-configuration-persistence"));
|
||||
private volatile boolean enabled;
|
||||
private boolean closed;
|
||||
private int pending;
|
||||
private final CompletableFuture<Void> drained = new CompletableFuture<>();
|
||||
|
||||
public AdventureSettings(Path directory, boolean initial) {
|
||||
this(directory, initial, (from, to) -> Files.move(from, to,
|
||||
StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING));
|
||||
}
|
||||
|
||||
AdventureSettings(Path directory, boolean initial, Replacement replacement) {
|
||||
this.directory = Objects.requireNonNull(directory).toAbsolutePath();
|
||||
this.replacement = Objects.requireNonNull(replacement);
|
||||
enabled = initial;
|
||||
}
|
||||
|
||||
public static boolean validate(Object configured) {
|
||||
if (configured == null) return true;
|
||||
if (configured instanceof Boolean value) return value;
|
||||
throw new IllegalArgumentException("adventure-mode must be true or false");
|
||||
}
|
||||
|
||||
public boolean enabled() { return enabled; }
|
||||
|
||||
public synchronized CompletionStage<Boolean> set(boolean value) {
|
||||
if (closed) return CompletableFuture.failedStage(new IOException("Configuration store is closed"));
|
||||
pending++;
|
||||
try {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try { save(value); enabled = value; return value; }
|
||||
catch (IOException | RuntimeException failure) {
|
||||
// No parser contents, filesystem paths or configuration values in diagnostics.
|
||||
throw new java.util.concurrent.CompletionException(new IOException(
|
||||
"Adventure configuration save refused or failed; effective setting unchanged"));
|
||||
} finally { finished(); }
|
||||
}, worker).minimalCompletionStage();
|
||||
} catch (RejectedExecutionException rejected) {
|
||||
finished();
|
||||
return CompletableFuture.failedStage(new IOException("Configuration store is closed"));
|
||||
}
|
||||
}
|
||||
|
||||
private void save(boolean value) throws IOException {
|
||||
Files.createDirectories(directory);
|
||||
if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe directory");
|
||||
var file = directory.resolve("config.yml");
|
||||
var lockFile = directory.resolve(".config.lock");
|
||||
if (Files.exists(lockFile, LinkOption.NOFOLLOW_LINKS)
|
||||
&& !Files.isRegularFile(lockFile, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe lock");
|
||||
try (var channel = FileChannel.open(lockFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS);
|
||||
var lock = channel.tryLock()) {
|
||||
if (lock == null) throw new IOException("Configuration busy");
|
||||
var options = new LoaderOptions();
|
||||
options.setAllowDuplicateKeys(false);
|
||||
options.setMaxAliasesForCollections(20);
|
||||
options.setCodePointLimit(MAX_BYTES);
|
||||
var yaml = new Yaml(new SafeConstructor(options));
|
||||
Map<String, Object> values = new LinkedHashMap<>();
|
||||
if (Files.exists(file, LinkOption.NOFOLLOW_LINKS)) {
|
||||
if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe configuration");
|
||||
byte[] bytes;
|
||||
try (var input = Files.newInputStream(file, LinkOption.NOFOLLOW_LINKS)) { bytes = input.readNBytes(MAX_BYTES + 1); }
|
||||
if (bytes.length > MAX_BYTES) throw new IOException("Configuration too large");
|
||||
Object loaded = yaml.load(StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString());
|
||||
if (loaded != null) {
|
||||
if (!(loaded instanceof Map<?, ?> map)) throw new IOException("Invalid configuration root");
|
||||
for (var entry : map.entrySet()) {
|
||||
if (!(entry.getKey() instanceof String key)) throw new IOException("Invalid configuration key");
|
||||
values.put(key, entry.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
values.put("adventure-mode", value);
|
||||
byte[] bytes = yaml.dump(values).getBytes(StandardCharsets.UTF_8);
|
||||
if (bytes.length > MAX_BYTES) throw new IOException("Configuration too large");
|
||||
Path temporary = Files.createTempFile(directory, ".config-", ".tmp");
|
||||
try {
|
||||
try (var output = FileChannel.open(temporary, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS)) {
|
||||
var buffer = ByteBuffer.wrap(bytes);
|
||||
while (buffer.hasRemaining()) output.write(buffer);
|
||||
output.force(true);
|
||||
}
|
||||
replacement.move(temporary, file);
|
||||
} finally { Files.deleteIfExists(temporary); }
|
||||
} catch (OverlappingFileLockException busy) { throw new IOException("Configuration busy"); }
|
||||
}
|
||||
|
||||
private synchronized void finished() {
|
||||
pending--;
|
||||
if (closed && pending == 0) drained.complete(null);
|
||||
}
|
||||
|
||||
public CompletionStage<Void> drained() { return drained.minimalCompletionStage(); }
|
||||
|
||||
/** Drain accepted writes without waiting on the server thread. */
|
||||
@Override public synchronized void close() {
|
||||
closed = true;
|
||||
worker.shutdown();
|
||||
if (pending == 0) drained.complete(null);
|
||||
}
|
||||
}
|
||||
@@ -48,11 +48,15 @@ public final class EquipmentSessionStore implements AutoCloseable {
|
||||
private final ExecutorService worker = Executors.newSingleThreadExecutor(
|
||||
task -> new Thread(task, "fantasy-equipment-session-persistence"));
|
||||
|
||||
public record Receipt(UUID sessionId, UUID characterId, Instant preparedAt) {
|
||||
public record Receipt(UUID sessionId, UUID characterId, Instant preparedAt, String previousGameMode) {
|
||||
public Receipt(UUID sessionId, UUID characterId, Instant preparedAt) { this(sessionId, characterId, preparedAt, null); }
|
||||
public Receipt {
|
||||
Objects.requireNonNull(sessionId);
|
||||
Objects.requireNonNull(characterId);
|
||||
timestamp(preparedAt);
|
||||
if (previousGameMode != null && !Set.of("SURVIVAL", "CREATIVE", "ADVENTURE", "SPECTATOR").contains(previousGameMode)) {
|
||||
throw new IllegalArgumentException("Invalid previous game mode");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,16 +110,21 @@ public final class EquipmentSessionStore implements AutoCloseable {
|
||||
return submit(() -> withLock(() -> load(player)));
|
||||
}
|
||||
|
||||
/** A receipt acknowledgment is a prerequisite for packing, not evidence that packing happened. */
|
||||
public CompletionStage<State> prepare(UUID player, UUID session, UUID character) {
|
||||
return prepare(player, session, character, null);
|
||||
}
|
||||
|
||||
/** A receipt acknowledgment precedes mode/gear mutation; it is not proof either happened. */
|
||||
public CompletionStage<State> prepare(UUID player, UUID session, UUID character, String previousGameMode) {
|
||||
Objects.requireNonNull(player);
|
||||
var receipt = new Receipt(session, character, clock.instant());
|
||||
var receipt = new Receipt(session, character, clock.instant(), previousGameMode);
|
||||
return submit(() -> withLock(() -> {
|
||||
var found = load(player);
|
||||
if (found.isPresent()) {
|
||||
var old = found.orElseThrow();
|
||||
if (old.pending() != null) {
|
||||
if (session.equals(old.pending().sessionId()) && character.equals(old.pending().characterId())) {
|
||||
if (session.equals(old.pending().sessionId()) && character.equals(old.pending().characterId())
|
||||
&& Objects.equals(previousGameMode, old.pending().previousGameMode())) {
|
||||
return old;
|
||||
}
|
||||
throw new IOException("Conflicting pending equipment session");
|
||||
@@ -282,8 +291,12 @@ public final class EquipmentSessionStore implements AutoCloseable {
|
||||
root.put("revision", state.revision().toString());
|
||||
if (state.pending() != null) {
|
||||
var receipt = state.pending();
|
||||
root.put("pending", Map.of("session-id", receipt.sessionId().toString(),
|
||||
"character-id", receipt.characterId().toString(), "prepared-at", receipt.preparedAt().toString()));
|
||||
var pending = new LinkedHashMap<String, Object>();
|
||||
pending.put("session-id", receipt.sessionId().toString());
|
||||
pending.put("character-id", receipt.characterId().toString());
|
||||
pending.put("prepared-at", receipt.preparedAt().toString());
|
||||
if (receipt.previousGameMode() != null) pending.put("previous-game-mode", receipt.previousGameMode());
|
||||
root.put("pending", pending);
|
||||
}
|
||||
if (state.lastExit() != null) {
|
||||
var exit = state.lastExit();
|
||||
@@ -304,8 +317,13 @@ public final class EquipmentSessionStore implements AutoCloseable {
|
||||
Exit exit = null;
|
||||
if (root.containsKey("pending")) {
|
||||
var keys = Set.of("session-id", "character-id", "prepared-at");
|
||||
var row = mapping(root.get("pending"), keys, keys);
|
||||
pending = new Receipt(id(row.get("session-id")), id(row.get("character-id")), instant(row.get("prepared-at")));
|
||||
var row = mapping(root.get("pending"), keys, Set.of("session-id", "character-id", "prepared-at", "previous-game-mode"));
|
||||
String previousMode = null;
|
||||
if (row.containsKey("previous-game-mode")) {
|
||||
if (!(row.get("previous-game-mode") instanceof String value)) throw new IllegalArgumentException("Invalid previous mode");
|
||||
previousMode = value;
|
||||
}
|
||||
pending = new Receipt(id(row.get("session-id")), id(row.get("character-id")), instant(row.get("prepared-at")), previousMode);
|
||||
}
|
||||
if (root.containsKey("last-exit")) {
|
||||
var keys = Set.of("session-id", "character-id", "exited-at", "deadline");
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package games.dmg.fantasystick.session;
|
||||
|
||||
import java.util.UUID;
|
||||
import org.bukkit.GameMode;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
|
||||
/** Main-thread holder/session proof for optional Adventure mode; the receipt must already be saved. */
|
||||
public final class AdventureModeLease implements org.bukkit.event.Listener {
|
||||
@org.bukkit.event.EventHandler(priority = org.bukkit.event.EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void changed(org.bukkit.event.player.PlayerGameModeChangeEvent event) {
|
||||
if (event.isCancelled()) return;
|
||||
var player = event.getPlayer();
|
||||
var mark = read(player);
|
||||
// Events precede the write. A currently non-Adventure mode proves a previous
|
||||
// external change already happened, even when this new request returns to Adventure.
|
||||
// A lone external change is also detected directly by restore(). Never infer success
|
||||
// from this event's requested value, which a later listener may still cancel.
|
||||
if (mark != null && mark.phase() == Phase.APPLIED && player.getGameMode() != GameMode.ADVENTURE) {
|
||||
write(player, new Mark(mark.session(), mark.previous(), Phase.RELEASED));
|
||||
}
|
||||
}
|
||||
private static final NamespacedKey KEY = new NamespacedKey("fantasystick", "adventure_session");
|
||||
private enum Phase { APPLYING, APPLIED, RESTORING, RELEASED }
|
||||
private record Mark(UUID session, String previous, Phase phase) {
|
||||
boolean matches(UUID expected, String original) { return session.equals(expected) && previous.equals(original); }
|
||||
}
|
||||
|
||||
public boolean available(Player player) {
|
||||
var mark = read(player);
|
||||
return !player.getPersistentDataContainer().has(KEY) || mark != null && mark.phase() == Phase.RELEASED;
|
||||
}
|
||||
|
||||
public boolean enter(Player player, UUID session, String previous) {
|
||||
if (previous == null) return true;
|
||||
var existing = read(player);
|
||||
if (player.getPersistentDataContainer().has(KEY) && (existing == null || existing.phase() != Phase.RELEASED)) {
|
||||
return existing != null && existing.matches(session, previous) && existing.phase() == Phase.APPLIED
|
||||
&& player.getGameMode() == GameMode.ADVENTURE;
|
||||
}
|
||||
if (player.getGameMode() != GameMode.valueOf(previous)) return false;
|
||||
write(player, new Mark(session, previous, Phase.APPLYING));
|
||||
player.setGameMode(GameMode.ADVENTURE);
|
||||
if (player.getGameMode() != GameMode.ADVENTURE) {
|
||||
write(player, new Mark(session, previous, Phase.RELEASED));
|
||||
return false;
|
||||
}
|
||||
write(player, new Mark(session, previous, Phase.APPLIED));
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean restore(Player player, UUID session, String previous) {
|
||||
if (previous == null) return true;
|
||||
var mark = read(player);
|
||||
if (mark == null || !mark.matches(session, previous)) return false;
|
||||
if (mark.phase() == Phase.RELEASED) return true;
|
||||
if (mark.phase() != Phase.APPLIED) return false; // Interrupted setter is not restoration proof.
|
||||
if (player.getGameMode() != GameMode.ADVENTURE) {
|
||||
write(player, new Mark(session, previous, Phase.RELEASED));
|
||||
return true; // A later external/admin change is not ours to undo.
|
||||
}
|
||||
write(player, new Mark(session, previous, Phase.RESTORING));
|
||||
player.setGameMode(GameMode.valueOf(previous));
|
||||
if (player.getGameMode() == GameMode.ADVENTURE && !previous.equals("ADVENTURE")) {
|
||||
write(player, new Mark(session, previous, Phase.APPLIED));
|
||||
return false; // Native veto: unchanged and still owned, not successful restoration.
|
||||
}
|
||||
write(player, new Mark(session, previous, Phase.RELEASED));
|
||||
return true;
|
||||
}
|
||||
|
||||
private static Mark read(Player player) {
|
||||
var data = player.getPersistentDataContainer();
|
||||
if (!data.has(KEY, PersistentDataType.STRING)) return null;
|
||||
try {
|
||||
String[] fields = data.get(KEY, PersistentDataType.STRING).split("\\|", -1);
|
||||
if (fields.length != 4 || !fields[0].equals("1")) return null;
|
||||
var session = UUID.fromString(fields[1]);
|
||||
if (!session.toString().equals(fields[1])) return null;
|
||||
GameMode.valueOf(fields[2]);
|
||||
return new Mark(session, fields[2], Phase.valueOf(fields[3]));
|
||||
} catch (IllegalArgumentException invalid) { return null; }
|
||||
}
|
||||
|
||||
private static void write(Player player, Mark mark) {
|
||||
player.getPersistentDataContainer().set(KEY, PersistentDataType.STRING,
|
||||
"1|" + mark.session() + "|" + mark.previous() + "|" + mark.phase());
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
private final Consumer<Runnable> nextTick;
|
||||
private final Consumer<Failure> diagnostics;
|
||||
private volatile boolean closed;
|
||||
private games.dmg.fantasystick.persistence.AdventureSettings settings;
|
||||
|
||||
public EquipmentAdminCommand(EquipmentSessionStore receipts, EquipmentSessions sessions, Server server,
|
||||
Consumer<Runnable> nextTick, Consumer<Failure> diagnostics) {
|
||||
@@ -30,10 +31,21 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
this.diagnostics = Objects.requireNonNull(diagnostics);
|
||||
}
|
||||
|
||||
public EquipmentAdminCommand(EquipmentSessionStore receipts, EquipmentSessions sessions, Server server,
|
||||
Consumer<Runnable> nextTick, Consumer<Failure> diagnostics,
|
||||
games.dmg.fantasystick.persistence.AdventureSettings settings) {
|
||||
this(receipts, sessions, server, nextTick, diagnostics);
|
||||
this.settings = Objects.requireNonNull(settings);
|
||||
}
|
||||
|
||||
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (closed) return true;
|
||||
if (!sender.hasPermission(PERMISSION)) {
|
||||
sender.sendMessage("You need fantasystick.admin to inspect or recover equipment sessions.");
|
||||
sender.sendMessage("You need fantasystick.admin to administer Fantasy Stick.");
|
||||
return true;
|
||||
}
|
||||
if (args.length > 0 && args[0].equals("config")) {
|
||||
configuration(sender, args);
|
||||
return true;
|
||||
}
|
||||
UUID owner;
|
||||
@@ -96,6 +108,32 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
return true;
|
||||
}
|
||||
|
||||
private void configuration(CommandSender sender, String[] args) {
|
||||
if (args.length < 2 || args.length > 3 || !args[1].equals("adventure-mode")
|
||||
|| args.length == 3 && !args[2].equals("true") && !args[2].equals("false")) {
|
||||
sender.sendMessage("Usage: /fantasystick config adventure-mode [true|false]");
|
||||
return;
|
||||
}
|
||||
if (settings == null) { sender.sendMessage("Adventure configuration is unavailable."); return; }
|
||||
if (args.length == 2) {
|
||||
sender.sendMessage("adventure-mode=" + settings.enabled() + " (applies to new sessions only)");
|
||||
return;
|
||||
}
|
||||
settings.set(Boolean.parseBoolean(args[2])).whenComplete((saved, failure) -> {
|
||||
if (failure != null) report(null, "config-adventure-mode", failure);
|
||||
if (closed) return;
|
||||
try {
|
||||
nextTick.accept(() -> {
|
||||
if (closed || !sender.hasPermission(PERMISSION)
|
||||
|| sender instanceof org.bukkit.entity.Player player && !player.isOnline()) return;
|
||||
sender.sendMessage(failure == null
|
||||
? "Saved adventure-mode=" + saved + " for new sessions only; active sessions are unchanged."
|
||||
: "Adventure configuration save failed; the effective setting is unchanged.");
|
||||
});
|
||||
} catch (RuntimeException rejected) { report(null, "config-response", rejected); }
|
||||
});
|
||||
}
|
||||
|
||||
private void report(UUID owner, String operation, Throwable cause) {
|
||||
try { diagnostics.accept(new Failure(owner, operation, cause)); }
|
||||
catch (RuntimeException ignored) { /* Diagnostics cannot authorize recovery. */ }
|
||||
|
||||
@@ -54,6 +54,8 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
private Consumer<UUID> cursorCustody = ignored -> { };
|
||||
private boolean cursorCustodyAttached;
|
||||
private boolean closed;
|
||||
private java.util.function.BooleanSupplier adventureMode = () -> false;
|
||||
private AdventureModeLease gameModes = new AdventureModeLease();
|
||||
private boolean closeSweepFinished;
|
||||
private int persistenceOperations;
|
||||
private final CompletableFuture<Void> drained = new CompletableFuture<>();
|
||||
@@ -71,6 +73,9 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
boolean acknowledged;
|
||||
boolean saving;
|
||||
boolean effectsStarted;
|
||||
String previousGameMode;
|
||||
boolean modeStarted;
|
||||
boolean gearRestoredForModeRecovery;
|
||||
boolean presentationInstalled;
|
||||
boolean cleaning;
|
||||
boolean cleanupAttempted;
|
||||
@@ -118,6 +123,15 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
this.presentation = Objects.requireNonNull(presentation);
|
||||
}
|
||||
|
||||
public EquipmentSessions(CharacterStorage characters, EquipmentSessionStore receipts, Duration switchDelay, Clock clock,
|
||||
Consumer<Runnable> nextTick, Consumer<Notice> notices, Consumer<Failure> diagnostics,
|
||||
games.dmg.fantasystick.presentation.SessionPresentation presentation,
|
||||
java.util.function.BooleanSupplier adventureMode, AdventureModeLease gameModes) {
|
||||
this(characters, receipts, switchDelay, clock, nextTick, notices, diagnostics, presentation);
|
||||
this.adventureMode = Objects.requireNonNull(adventureMode);
|
||||
this.gameModes = Objects.requireNonNull(gameModes);
|
||||
}
|
||||
|
||||
/** One server-thread custody bridge per coordinator; never called by persistence workers. */
|
||||
synchronized void attachCursorCustody(Consumer<UUID> invalidate) {
|
||||
if (cursorCustodyAttached) throw new IllegalStateException("Cursor custody already attached");
|
||||
@@ -182,6 +196,9 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
return;
|
||||
}
|
||||
var attempt = new Attempt(player, owner, character.orElseThrow());
|
||||
if (adventureMode.getAsBoolean() && player.getGameMode() != org.bukkit.GameMode.ADVENTURE) {
|
||||
attempt.previousGameMode = player.getGameMode().name();
|
||||
}
|
||||
attempt.snapshot = snapshot(player);
|
||||
attempt.cursor = copy(player.getItemOnCursor());
|
||||
pending.put(owner, attempt);
|
||||
@@ -192,7 +209,7 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
private record Loaded(Optional<CharacterRecord> character, Optional<EquipmentSessionStore.State> state) { }
|
||||
|
||||
private boolean entryNativeSafe(Attempt attempt, EquipmentSessionStore.State state) {
|
||||
if (hasRemnants(attempt.player)) return false;
|
||||
if (hasRemnants(attempt.player) || !gameModes.available(attempt.player)) return false;
|
||||
var marker = EquipmentSessionMarker.read(attempt.player).orElse(null);
|
||||
if (EquipmentSessionMarker.present(attempt.player)) {
|
||||
// A terminal marker is resolved only by its matching completed file acknowledgment.
|
||||
@@ -257,7 +274,7 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
owned.put(attempt.owner, attempt);
|
||||
controls.create(record, attempt.owner, attempt.session); // Validate all nine controls before preparation/packing.
|
||||
attempt.saving = true;
|
||||
persist(() -> receipts.prepare(attempt.owner, attempt.session, attempt.character), (saved, error) -> {
|
||||
persist(() -> receipts.prepare(attempt.owner, attempt.session, attempt.character, attempt.previousGameMode), (saved, error) -> {
|
||||
attempt.saving = false;
|
||||
if (error != null) { attempt.uncertainSave = true; fail(attempt, error); return; }
|
||||
attempt.acknowledged = true;
|
||||
@@ -281,6 +298,12 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
try {
|
||||
var items = controls.create(record, attempt.owner, attempt.session);
|
||||
attempt.entryLocation = attempt.player.getLocation().clone(); // Server thread, before activation.
|
||||
attempt.modeStarted = attempt.previousGameMode != null;
|
||||
if (!gameModes.enter(attempt.player, attempt.session, attempt.previousGameMode)) {
|
||||
attempt.modeStarted = false; // Returned refusal is not an uncertain setter exception.
|
||||
refuse(attempt, "GAME_MODE_REFUSED", "Adventure mode was refused; entry did not pack equipment."); return;
|
||||
}
|
||||
if (!entryCurrent(attempt) || attempt.exitRequested) return;
|
||||
attempt.effectsStarted = true;
|
||||
mark(attempt, EquipmentSessionMarker.Phase.PACKING);
|
||||
var result = equipment.pack(attempt.player.getInventory(), attempt.owner, attempt.session);
|
||||
@@ -308,6 +331,11 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
fail(attempt, error); // Effects may have started: never roll back or replay them.
|
||||
notice(attempt.owner, "NATIVE_UNCERTAIN", "Equipment mutation failed; items and receipt require inspection.");
|
||||
} finally {
|
||||
if (!active.containsKey(attempt.owner) && attempt.modeStarted) {
|
||||
restoreGameMode(attempt);
|
||||
if (!attempt.effectsStarted && attempt.exitRequested) pending.remove(attempt.owner, attempt);
|
||||
if (!attempt.effectsStarted && !current(attempt)) abandon(attempt);
|
||||
}
|
||||
transitioning.remove(attempt.owner, attempt);
|
||||
// The deferred exit must reserve persistence before drain can be signalled.
|
||||
try {
|
||||
@@ -471,11 +499,25 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
catch (RuntimeException | LinkageError failure) { diagnostic(attempt, failure); }
|
||||
}
|
||||
|
||||
private boolean restoreGameMode(Attempt attempt) {
|
||||
if (attempt.previousGameMode == null) return true;
|
||||
try {
|
||||
if (gameModes.restore(attempt.player, attempt.session, attempt.previousGameMode)) {
|
||||
attempt.modeStarted = false;
|
||||
return true;
|
||||
}
|
||||
} catch (RuntimeException failure) { diagnostic(attempt, failure); }
|
||||
notice(attempt.owner, "GAME_MODE_RECOVERY", "Game-mode restoration was refused or ambiguous; retained receipt requires inspection.");
|
||||
return false;
|
||||
}
|
||||
|
||||
private EquipmentStorage.RestoreResult restoreExit(Attempt attempt) {
|
||||
active.remove(attempt.owner, attempt);
|
||||
withdrawPresentation(attempt);
|
||||
boolean reserved = transitioning.putIfAbsent(attempt.owner, attempt) == null;
|
||||
try {
|
||||
invalidateCursor(attempt.owner);
|
||||
boolean modeRestored = restoreGameMode(attempt);
|
||||
EquipmentStorage.RestoreResult result;
|
||||
try {
|
||||
result = restoreMarked(attempt);
|
||||
@@ -486,7 +528,8 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
notice(attempt.owner, "NATIVE_UNCERTAIN", "Restoration failed; items and receipt require inspection.");
|
||||
return EquipmentStorage.RestoreResult.INVALID_BOX;
|
||||
}
|
||||
persistExit(attempt, result == EquipmentStorage.RestoreResult.RESTORED);
|
||||
if (result == EquipmentStorage.RestoreResult.RESTORED && !modeRestored) attempt.gearRestoredForModeRecovery = true;
|
||||
persistExit(attempt, result == EquipmentStorage.RestoreResult.RESTORED && modeRestored);
|
||||
if (result != EquipmentStorage.RestoreResult.RESTORED) {
|
||||
notice(attempt.owner, result.name(), "Equipment recovery refused: " + result);
|
||||
} else sync(attempt);
|
||||
@@ -504,6 +547,13 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
private EquipmentStorage.RestoreResult restoreMarked(Attempt attempt) {
|
||||
invalidateCursor(attempt.owner);
|
||||
var marker = EquipmentSessionMarker.read(attempt.player);
|
||||
// Only a successful restoration observed by this process for this exact Player
|
||||
// permits finishing a mode-only retry. Serialized RESTORED alone proves nothing.
|
||||
if (attempt.gearRestoredForModeRecovery && !hasRemnants(attempt.player)
|
||||
&& marker.filter(token -> token.matches(attempt.session, attempt.character)
|
||||
&& token.phase() == EquipmentSessionMarker.Phase.RESTORED).isPresent()) {
|
||||
return EquipmentStorage.RestoreResult.RESTORED;
|
||||
}
|
||||
if (marker.filter(token -> token.matches(attempt.session, attempt.character)
|
||||
&& token.phase() == EquipmentSessionMarker.Phase.PACKED).isEmpty()) {
|
||||
notice(attempt.owner, "NATIVE_MARKER", "Missing, malformed, mismatched or ambiguous native equipment marker; "
|
||||
@@ -544,7 +594,7 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
}
|
||||
|
||||
private void abandon(Attempt attempt) {
|
||||
if (attempt.effectsStarted || attempt.cleanupAttempted || attempt.uncertainSave) return;
|
||||
if (attempt.modeStarted || attempt.effectsStarted || attempt.cleanupAttempted || attempt.uncertainSave) return;
|
||||
if (attempt.acknowledged) {
|
||||
attempt.cleaning = true;
|
||||
attempt.cleanupAttempted = true;
|
||||
@@ -564,6 +614,8 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
private boolean entryCurrent(Attempt attempt) {
|
||||
if (!current(attempt)) { abandon(attempt); return false; }
|
||||
if (!attempt.player.isOnline()
|
||||
|| attempt.previousGameMode != null && !attempt.modeStarted
|
||||
&& !attempt.player.getGameMode().name().equals(attempt.previousGameMode)
|
||||
|| attempt.markerValidated && (EquipmentSessionMarker.present(attempt.player) != (attempt.entryMarker != null)
|
||||
|| !Objects.equals(attempt.entryMarker, EquipmentSessionMarker.read(attempt.player).orElse(null)))
|
||||
|| !Arrays.equals(attempt.snapshot, snapshot(attempt.player))
|
||||
@@ -666,6 +718,8 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
}
|
||||
attempt.character = receipt.characterId();
|
||||
attempt.session = receipt.sessionId();
|
||||
attempt.previousGameMode = receipt.previousGameMode();
|
||||
attempt.modeStarted = attempt.previousGameMode != null;
|
||||
var previous = owned.get(attempt.owner);
|
||||
if (previous != null && !attempt.session.equals(previous.session)) {
|
||||
notice(attempt.owner, "SESSION_MISMATCH", "Saved and process-local sessions disagree; items were left unchanged."); return;
|
||||
@@ -678,13 +732,18 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
restoreExit(previous);
|
||||
return;
|
||||
}
|
||||
if (previous != null) attempt.claim = previous.claim;
|
||||
if (previous != null) {
|
||||
attempt.claim = previous.claim;
|
||||
attempt.gearRestoredForModeRecovery = previous.player == attempt.player && previous.gearRestoredForModeRecovery;
|
||||
}
|
||||
owned.put(attempt.owner, attempt);
|
||||
transitioning.put(attempt.owner, attempt);
|
||||
try {
|
||||
boolean modeRestored = restoreGameMode(attempt);
|
||||
var result = restoreMarked(attempt);
|
||||
if (result == EquipmentStorage.RestoreResult.RESTORED) {
|
||||
persistExit(attempt, true);
|
||||
if (!modeRestored) attempt.gearRestoredForModeRecovery = true;
|
||||
persistExit(attempt, modeRestored);
|
||||
sync(attempt);
|
||||
} else notice(attempt.owner, result.name(), "Equipment recovery refused: " + result + "; receipt and items retained.");
|
||||
} catch (RuntimeException error) {
|
||||
|
||||
Reference in new issue
Block a user