diff --git a/src/main/java/games/dmg/fantasystick/FantasyStickPlugin.java b/src/main/java/games/dmg/fantasystick/FantasyStickPlugin.java index d157b24..17c9a48 100644 --- a/src/main/java/games/dmg/fantasystick/FantasyStickPlugin.java +++ b/src/main/java/games/dmg/fantasystick/FantasyStickPlugin.java @@ -73,6 +73,7 @@ public final class FantasyStickPlugin extends JavaPlugin { private games.dmg.fantasystick.persistence.RevivalStore revivals; private games.dmg.fantasystick.session.AdminRevival adminRevival; private games.dmg.fantasystick.persistence.AdminReviveSettings adminReviveSettings; + private games.dmg.fantasystick.persistence.SwitchDelaySettings switchDelaySettings; private games.dmg.fantasystick.session.NutritionPolicy nutritionPolicy; private java.util.concurrent.CompletionStage configurationDrain = java.util.concurrent.CompletableFuture.completedStage(null); @@ -96,7 +97,8 @@ public final class FantasyStickPlugin extends JavaPlugin { 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 switchDelay = games.dmg.fantasystick.persistence.SwitchDelaySettings.parse( + getConfig().get(games.dmg.fantasystick.persistence.SwitchDelaySettings.KEY)); var rules = progressionRules(); var rewardRules = combatRewardRules(); var fireballSettings = fireballSettings(); @@ -155,8 +157,10 @@ public final class FantasyStickPlugin extends JavaPlugin { getLogger().log(Level.WARNING, "Equipment transition/recovery for player " + problem.player() + "; session " + problem.session(), problem.cause()); gameModes = new games.dmg.fantasystick.session.AdventureModeLease(); + switchDelaySettings = new games.dmg.fantasystick.persistence.SwitchDelaySettings(getDataFolder().toPath(), switchDelay); sessions = new EquipmentSessions(characters, receipts, switchDelay, Clock.systemUTC(), nextTick, notice -> notifyPlayer(generation, notice), diagnostics, presentation, adventureSettings::enabled, gameModes); + sessions.attachSwitchDelay(switchDelaySettings::delay); parties = new games.dmg.fantasystick.party.PartyRoster(Clock.systemUTC(), id -> { var player = getServer().getPlayer(id); return player != null && player.isOnline(); @@ -256,6 +260,7 @@ public final class FantasyStickPlugin extends JavaPlugin { stoneSkinSettings, stoneSkin, shieldBashSettings, shieldBash, hexSettings, hex, inspireSettings, inspire, abilityRegistry); admin.attachAdminRevival(adminRevival, adminReviveSettings); + admin.attachSwitchDelay(switchDelaySettings); admin.attachCharacterIssuer(new games.dmg.fantasystick.session.AdminCharacterIssuer(characters, () -> factory.create(rules), nextTick, problem -> getLogger().log(Level.WARNING, "Admin character issue " + problem.operation() + " for player " + problem.player() @@ -341,6 +346,7 @@ public final class FantasyStickPlugin extends JavaPlugin { var closingInspireSettings = inspireSettings; inspireSettings = null; var closingAdminRevival = adminRevival; adminRevival = null; var closingAdminReviveSettings = adminReviveSettings; adminReviveSettings = null; + var closingSwitchDelaySettings = switchDelaySettings; switchDelaySettings = null; var closingTemporaryHealth = temporaryHealth; temporaryHealth = null; var closingHexSettings = hexSettings; hexSettings = null; var closingOutgoingDamageMitigation = outgoingDamageMitigation; outgoingDamageMitigation = null; @@ -367,6 +373,7 @@ public final class FantasyStickPlugin extends JavaPlugin { if (closingHexSettings != null) cleanup("Hex configuration", closingHexSettings::close); if (closingInspireSettings != null) cleanup("Inspire configuration", closingInspireSettings::close); if (closingAdminReviveSettings != null) cleanup("admin revival configuration", closingAdminReviveSettings::close); + if (closingSwitchDelaySettings != null) cleanup("switch delay configuration", closingSwitchDelaySettings::close); configurationDrain = java.util.concurrent.CompletableFuture.allOf( closingSettings == null ? java.util.concurrent.CompletableFuture.completedFuture(null) : closingSettings.drained().toCompletableFuture(), @@ -387,7 +394,9 @@ public final class FantasyStickPlugin extends JavaPlugin { closingInspireSettings == null ? java.util.concurrent.CompletableFuture.completedFuture(null) : closingInspireSettings.drained().toCompletableFuture(), closingAdminReviveSettings == null ? java.util.concurrent.CompletableFuture.completedFuture(null) - : closingAdminReviveSettings.drained().toCompletableFuture()); + : closingAdminReviveSettings.drained().toCompletableFuture(), + closingSwitchDelaySettings == null ? java.util.concurrent.CompletableFuture.completedFuture(null) + : closingSwitchDelaySettings.drained().toCompletableFuture()); if (closingBooks != null) cleanup("character book", closingBooks::close); if (closingAdminRevival != null) cleanup("admin revival", closingAdminRevival::close); if (closingBasicAttack != null) cleanup("basic attack", closingBasicAttack::close); @@ -589,24 +598,6 @@ public final class FantasyStickPlugin extends JavaPlugin { } } - private java.time.Duration switchDelay() { - Object configured = getConfig().get("character-swap-cooldown-seconds", 900); - String value = String.valueOf(configured); - if (!value.matches("[0-9]+")) { - throw new IllegalArgumentException("character-swap-cooldown-seconds must be a nonnegative integer"); - } - try { - var delay = java.time.Duration.ofSeconds(new java.math.BigInteger(value).longValueExact()); - var deadline = java.time.Instant.now().plus(delay); - if (deadline.atOffset(java.time.ZoneOffset.UTC).getYear() > 9999) { - throw new IllegalArgumentException("character-swap-cooldown-seconds exceeds the persisted UTC timestamp range"); - } - return delay; - } catch (ArithmeticException | java.time.DateTimeException invalid) { - throw new IllegalArgumentException("character-swap-cooldown-seconds exceeds the supported duration range", invalid); - } - } - private void notifyPlayer(Object generation, EquipmentSessions.Notice notice) { Runnable delivery = () -> { if (lifetime != generation) return; diff --git a/src/main/java/games/dmg/fantasystick/persistence/SwitchDelaySettings.java b/src/main/java/games/dmg/fantasystick/persistence/SwitchDelaySettings.java new file mode 100644 index 0000000..df6e342 --- /dev/null +++ b/src/main/java/games/dmg/fantasystick/persistence/SwitchDelaySettings.java @@ -0,0 +1,42 @@ +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.time.Duration; +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; + +/** Durable save-before-publish policy for character-switch delay checks and later exits. */ +public final class SwitchDelaySettings implements AutoCloseable { + public static final String KEY="character-swap-cooldown-seconds";public static final String DEFAULT="900"; + private static final int MAX_BYTES=1_048_576; + @FunctionalInterface interface Replacement{void move(Path from,Path to)throws IOException;} + public record Update(String value,Duration delay,long sequence){} + private final Path directory;private final Replacement replacement;private final java.util.concurrent.ExecutorService worker=Executors.newSingleThreadExecutor(task->new Thread(task,"fantasy-switch-delay-configuration")); + private volatile Duration effective;private long persistedSequence,publishedSequence;private boolean closed;private int pending;private final CompletableFuture drained=new CompletableFuture<>(); + public SwitchDelaySettings(Path directory,Duration initial){this(directory,initial,(from,to)->Files.move(from,to,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING));} + SwitchDelaySettings(Path directory,Duration initial,Replacement replacement){this.directory=Objects.requireNonNull(directory).toAbsolutePath();this.replacement=Objects.requireNonNull(replacement);effective=validate(initial);} + public static Duration parse(Object value){if(value==null)return Duration.ofSeconds(900);try{return validate(Duration.ofSeconds(value instanceof Number n?new java.math.BigDecimal(n.toString()).longValueExact():Long.parseLong(value.toString())));}catch(ArithmeticException|NumberFormatException invalid){throw new IllegalArgumentException(KEY+" must be nonnegative whole seconds",invalid);}} + private static Duration validate(Duration value){if(value.isNegative()||value.getNano()!=0)throw new IllegalArgumentException(KEY+" must be nonnegative whole seconds");try{var deadline=java.time.Instant.now().plus(value);if(deadline.atOffset(java.time.ZoneOffset.UTC).getYear()>9999)throw new IllegalArgumentException(KEY+" exceeds the persisted timestamp range");return value;}catch(java.time.DateTimeException|ArithmeticException invalid){throw new IllegalArgumentException(KEY+" exceeds the persisted timestamp range",invalid);}} + public Duration delay(){return effective;}public String value(){return Long.toString(effective.toSeconds());} + public CompletionStage set(String raw){Duration accepted=parse(raw);synchronized(this){if(closed)return CompletableFuture.failedStage(new IOException("Configuration store is closed"));pending++;}try{return CompletableFuture.supplyAsync(()->{try{save(accepted);return new Update(Long.toString(accepted.toSeconds()),accepted,++persistedSequence);}catch(IOException|RuntimeException failure){throw new java.util.concurrent.CompletionException(new IOException("Character switch 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"));}} + public synchronized void publish(Update update){if(update.sequence()<=publishedSequence)return;effective=validate(update.delay());publishedSequence=update.sequence();} + private void save(Duration 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 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(KEY,Long.toString(value.toSeconds()));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 drained(){return drained.minimalCompletionStage();}@Override public synchronized void close(){closed=true;worker.shutdown();if(pending==0)drained.complete(null);} +} diff --git a/src/main/java/games/dmg/fantasystick/session/EquipmentAdminCommand.java b/src/main/java/games/dmg/fantasystick/session/EquipmentAdminCommand.java index 5b7ef6f..021c791 100644 --- a/src/main/java/games/dmg/fantasystick/session/EquipmentAdminCommand.java +++ b/src/main/java/games/dmg/fantasystick/session/EquipmentAdminCommand.java @@ -41,6 +41,7 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable { private AdminCharacterIssuer characterIssuer; private AdminRevival adminRevival; private games.dmg.fantasystick.persistence.AdminReviveSettings adminReviveSettings; + private games.dmg.fantasystick.persistence.SwitchDelaySettings switchDelaySettings; public EquipmentAdminCommand(EquipmentSessionStore receipts, EquipmentSessions sessions, Server server, Consumer nextTick, Consumer diagnostics) { @@ -210,6 +211,8 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable { this.inspireSettings=Objects.requireNonNull(inspireSettings);this.inspire=Objects.requireNonNull(inspire); } + public void attachSwitchDelay(games.dmg.fantasystick.persistence.SwitchDelaySettings settings){if(closed||switchDelaySettings!=null)throw new IllegalStateException("Switch delay already attached or command closed");switchDelaySettings=Objects.requireNonNull(settings);} + public void attachAdminRevival(AdminRevival revival, games.dmg.fantasystick.persistence.AdminReviveSettings settings) { if (closed || adminRevival != null) throw new IllegalStateException("Admin revival already attached or command closed"); adminRevival=Objects.requireNonNull(revival);adminReviveSettings=Objects.requireNonNull(settings); @@ -326,6 +329,7 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable { private void configuration(CommandSender sender, String[] args) { if (args.length < 2 || args.length > 3) { configurationUsage(sender); return; } if (args[1].equals("adventure-mode")) { adventureConfiguration(sender, args); return; } + if (args[1].equals(games.dmg.fantasystick.persistence.SwitchDelaySettings.KEY)) { switchDelayConfiguration(sender,args); return; } if (args[1].equals(games.dmg.fantasystick.persistence.AdminReviveSettings.KEY)) { adminReviveConfiguration(sender,args); return; } if (longbowSettings != null && games.dmg.fantasystick.persistence.LongbowSettings.keys().contains(args[1])) { longbowConfiguration(sender, args); return; @@ -537,6 +541,8 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable { }); } + private void switchDelayConfiguration(CommandSender sender,String[] args){if(switchDelaySettings==null){configurationUsage(sender);return;}if(args.length==2){sender.sendMessage(games.dmg.fantasystick.persistence.SwitchDelaySettings.KEY+"="+switchDelaySettings.value()+" (new exits use this delay; existing deadlines are unchanged)");return;}java.util.concurrent.CompletionStage operation;try{operation=switchDelaySettings.set(args[2]);}catch(IllegalArgumentException invalid){sender.sendMessage("Character switch delay is invalid; the effective value is unchanged.");return;}operation.whenComplete((saved,failure)->{if(failure!=null)report(null,"config-switch-delay",failure);if(closed)return;try{nextTick.accept(()->{if(closed)return;if(failure==null)switchDelaySettings.publish(saved);if(!sender.hasPermission(PERMISSION)||sender instanceof org.bukkit.entity.Player player&&!player.isOnline())return;sender.sendMessage(failure==null?"Saved "+games.dmg.fantasystick.persistence.SwitchDelaySettings.KEY+"="+saved.value()+"; new exits use it and existing deadlines are unchanged.":"Character switch delay save failed; the effective value is unchanged.");});}catch(RuntimeException rejected){report(null,"config-response",rejected);}});} + private void adminReviveConfiguration(CommandSender sender,String[] args){if(adminReviveSettings==null){configurationUsage(sender);return;}if(args.length==2){sender.sendMessage(games.dmg.fantasystick.persistence.AdminReviveSettings.KEY+"="+adminReviveSettings.value()+" (applies to later admin revival selections only)");return;}java.util.concurrent.CompletionStage operation;try{operation=adminReviveSettings.set(args[2]);}catch(IllegalArgumentException invalid){sender.sendMessage("Admin revival timeout is invalid; the effective value is unchanged.");return;}operation.whenComplete((saved,failure)->{if(failure!=null)report(null,"config-admin-revive",failure);if(closed)return;try{nextTick.accept(()->{if(closed)return;if(failure==null)adminReviveSettings.publish(saved);if(!sender.hasPermission(PERMISSION)||sender instanceof org.bukkit.entity.Player player&&!player.isOnline())return;sender.sendMessage(failure==null?"Saved "+games.dmg.fantasystick.persistence.AdminReviveSettings.KEY+"="+saved.value()+" for later selections; open selections retain their deadline.":"Admin revival configuration save failed; the effective setting is unchanged.");});}catch(RuntimeException rejected){report(null,"config-response",rejected);}});} private void adventureConfiguration(CommandSender sender, String[] args) { @@ -579,7 +585,7 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable { if (args.length == 2 && (args[0].equals("give") || args[0].equals("revive") && sender instanceof org.bukkit.entity.Player)) return matching(server.getOnlinePlayers().stream() .filter(org.bukkit.entity.Player::isOnline).map(org.bukkit.entity.Player::getName).toList(), args[1]); if (args.length == 2 && args[0].equals("config")) { - var keys = new java.util.ArrayList(); keys.add("adventure-mode");keys.add(games.dmg.fantasystick.persistence.AdminReviveSettings.KEY); + var keys = new java.util.ArrayList(); keys.add("adventure-mode");keys.add(games.dmg.fantasystick.persistence.AdminReviveSettings.KEY);keys.add(games.dmg.fantasystick.persistence.SwitchDelaySettings.KEY); keys.addAll(games.dmg.fantasystick.persistence.FrostShardSettings.keys()); keys.addAll(games.dmg.fantasystick.persistence.LongbowSettings.keys()); keys.addAll(games.dmg.fantasystick.persistence.QuickstepSettings.keys()); @@ -593,6 +599,7 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable { if (args.length == 3 && args[0].equals("config")) { if (args[1].equals("adventure-mode")) return matching(List.of("false", "true"), args[2]); if(args[1].equals(games.dmg.fantasystick.persistence.AdminReviveSettings.KEY)&&adminReviveSettings!=null){String current=adminReviveSettings.value();return matching(current.equals(games.dmg.fantasystick.persistence.AdminReviveSettings.DEFAULT)?List.of(current):List.of(current,games.dmg.fantasystick.persistence.AdminReviveSettings.DEFAULT),args[2]);} + if(args[1].equals(games.dmg.fantasystick.persistence.SwitchDelaySettings.KEY)&&switchDelaySettings!=null){String current=switchDelaySettings.value();return matching(current.equals(games.dmg.fantasystick.persistence.SwitchDelaySettings.DEFAULT)?List.of(current):List.of(current,games.dmg.fantasystick.persistence.SwitchDelaySettings.DEFAULT),args[2]);} if (frostSettings != null && games.dmg.fantasystick.persistence.FrostShardSettings.keys().contains(args[1])) { String current = frostSettings.value(args[1]); String defaults = games.dmg.fantasystick.persistence.FrostShardSettings.defaultValue(args[1]); diff --git a/src/main/java/games/dmg/fantasystick/session/EquipmentSessions.java b/src/main/java/games/dmg/fantasystick/session/EquipmentSessions.java index b246288..90c7584 100644 --- a/src/main/java/games/dmg/fantasystick/session/EquipmentSessions.java +++ b/src/main/java/games/dmg/fantasystick/session/EquipmentSessions.java @@ -38,7 +38,7 @@ public final class EquipmentSessions implements AutoCloseable { private final CharacterStorage characters; private final EquipmentSessionStore receipts; - private final Duration switchDelay; + private Supplier switchDelay; private final Clock clock; private final Consumer nextTick; private final Consumer notices; @@ -91,6 +91,7 @@ public final class EquipmentSessions implements AutoCloseable { boolean uncertainSave; boolean nativeUncertain; boolean exitRequested; + Duration exitDelay; boolean arrival; Attempt recoveryOwner; org.bukkit.Location entryLocation; @@ -118,7 +119,8 @@ public final class EquipmentSessions implements AutoCloseable { Consumer nextTick, Consumer notices, Consumer diagnostics) { this.characters = Objects.requireNonNull(characters); this.receipts = Objects.requireNonNull(receipts); - this.switchDelay = Objects.requireNonNull(switchDelay); + var initialSwitchDelay = Objects.requireNonNull(switchDelay); + this.switchDelay = () -> initialSwitchDelay; this.clock = Objects.requireNonNull(clock); if (switchDelay.isNegative()) throw new IllegalArgumentException("Negative switch delay"); this.nextTick = Objects.requireNonNull(nextTick); @@ -142,6 +144,13 @@ public final class EquipmentSessions implements AutoCloseable { this.gameModes = Objects.requireNonNull(gameModes); } + /** Install before exposing entry so later checks/exits capture the acknowledged live policy. */ + public synchronized void attachSwitchDelay(Supplier policy) { + if (!owned.isEmpty()) throw new IllegalStateException("Sessions already started"); + switchDelay = Objects.requireNonNull(policy); + if (switchDelay.get().isNegative()) throw new IllegalArgumentException("Negative switch delay"); + } + /** Install before exposing entry so registered definitions drive delivered control metadata. */ public synchronized void attachAbilityRegistry(games.dmg.fantasystick.ability.AbilityRegistry registry) { if (!owned.isEmpty()) throw new IllegalStateException("Sessions already started"); @@ -337,7 +346,7 @@ public final class EquipmentSessions implements AutoCloseable { refuse(attempt, "RECOVERY_REQUIRED", "An unresolved equipment receipt requires validated recovery."); return; } Instant now = clock.instant(); - if (!state.canEnter(attempt.character, switchDelay, now)) { + if (!state.canEnter(attempt.character, switchDelay.get(), now)) { Duration remaining = Duration.between(now, state.lastExit().deadline()); long seconds = remaining.getSeconds() + (remaining.getNano() == 0 ? 0 : 1); refuse(attempt, "COOLDOWN", "Wait " + seconds + " seconds to switch characters (until " @@ -454,6 +463,7 @@ public final class EquipmentSessions implements AutoCloseable { UUID owner = player.getUniqueId(); var transition = transitioning.get(owner); if (transition != null) { + captureExitDelay(transition); active.remove(owner, transition); withdrawPresentation(transition); transition.exitRequested = true; @@ -463,6 +473,7 @@ public final class EquipmentSessions implements AutoCloseable { cancelEntry(owner); var attempt = active.remove(owner); if (attempt == null) { invalidateCursor(owner); return EquipmentStorage.RestoreResult.NOT_FOUND; } + captureExitDelay(attempt); return restoreExit(attempt); } @@ -607,6 +618,7 @@ public final class EquipmentSessions implements AutoCloseable { } private EquipmentStorage.RestoreResult restoreExit(Attempt attempt) { + captureExitDelay(attempt); active.remove(attempt.owner, attempt); withdrawPresentation(attempt); boolean reserved = transitioning.putIfAbsent(attempt.owner, attempt) == null; @@ -703,13 +715,21 @@ public final class EquipmentSessions implements AutoCloseable { return false; } + private void captureExitDelay(Attempt attempt) { + if (attempt.exitDelay != null) return; + var delay = Objects.requireNonNull(switchDelay.get()); + if (delay.isNegative()) throw new IllegalStateException("Negative switch delay policy"); + attempt.exitDelay = delay; + } + private void persistExit(Attempt attempt, boolean restored) { + captureExitDelay(attempt); // Recovery attempts have no process-local exit request to capture earlier. attempt.nativeRestored = restored; boolean complete = restored && (attempt.healthAcknowledged || attempt.defeated); attempt.saving = true; persist(() -> complete - ? receipts.completeExit(attempt.owner, attempt.session, switchDelay) - : receipts.recordExit(attempt.owner, attempt.session, switchDelay), (state, failure) -> { + ? receipts.completeExit(attempt.owner, attempt.session, attempt.exitDelay) + : receipts.recordExit(attempt.owner, attempt.session, attempt.exitDelay), (state, failure) -> { attempt.saving = false; if (failure != null) diagnostic(attempt, failure); else if (complete) { attempt.gearAcknowledged = true; release(attempt); } diff --git a/src/nativeTest/java/games/dmg/fantasystick/SwitchDelayAdminNativeTest.java b/src/nativeTest/java/games/dmg/fantasystick/SwitchDelayAdminNativeTest.java new file mode 100644 index 0000000..6858488 --- /dev/null +++ b/src/nativeTest/java/games/dmg/fantasystick/SwitchDelayAdminNativeTest.java @@ -0,0 +1,9 @@ +package games.dmg.fantasystick; +import static org.junit.jupiter.api.Assertions.*;import java.nio.file.Path;import java.time.Duration;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.io.TempDir; +class SwitchDelayAdminNativeTest{@TempDir Path data;@BeforeAll static void bootstrap()throws Exception{NativeRuntime.bootstrap();} + @Test void registeredCommandDurablyChangesActualExitAndEntryPolicyWithoutRewritingDeadlines()throws Exception{try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var sender=new EquipmentAdminCommandNativeTest.Sender();assertEquals(java.util.List.of("character-swap-cooldown-seconds"),f.command.tabComplete(sender.port,"fantasystick",new String[]{"config","character-s"}));assertEquals(java.util.List.of("900"),f.command.tabComplete(sender.port,"fantasystick",new String[]{"config","character-swap-cooldown-seconds",""}));f.command.execute(sender.port,"fantasystick",new String[]{"config","character-swap-cooldown-seconds"});assertTrue(sender.messages.getLast().contains("=900"));sender.allowed=false;assertTrue(f.command.tabComplete(sender.port,"fantasystick",new String[]{"config","character"}).isEmpty());f.command.execute(sender.port,"fantasystick",new String[]{"config","character-swap-cooldown-seconds","37"});assertTrue(sender.messages.getLast().contains("Permission denied"));sender.allowed=true;for(String bad:java.util.List.of("-1","1.5","bad","9223372036854775807")){f.command.execute(sender.port,"fantasystick",new String[]{"config","character-swap-cooldown-seconds",bad});assertTrue(sender.messages.getLast().contains("invalid"),bad+" -> "+sender.messages);}f.command.execute(sender.port,"fantasystick",new String[]{"config","character-swap-cooldown-seconds","37","extra"});assertTrue(sender.messages.getLast().contains("Usage"));save(f,sender,"37"); + var sessions=(games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"sessions");var a=new FantasyStickLifecycleNativeTest.Actor(data);var b=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(a.core.id,a.player);f.players.put(b.core.id,b.player);f.activate(a);f.activate(b);sessions.exit(a.player);sessions.exit(b.player);f.awaitCharacterAndReceipt(a);f.awaitCharacterAndReceipt(b);var aExit=f.receipts().find(a.core.id).toCompletableFuture().get().orElseThrow().lastExit();var bExit=f.receipts().find(b.core.id).toCompletableFuture().get().orElseThrow().lastExit();assertEquals(Duration.ofSeconds(37),Duration.between(aExit.exitedAt(),aExit.deadline()));assertEquals(Duration.ofSeconds(37),Duration.between(bExit.exitedAt(),bExit.deadline()));var otherA=new FantasyStickLifecycleNativeTest.Actor(data);var otherB=new FantasyStickLifecycleNativeTest.Actor(data);a.core.inventory.setItemInOffHand(otherA.core.inventory.getItemInOffHand().clone());b.core.inventory.setItemInOffHand(otherB.core.inventory.getItemInOffHand().clone());save(f,sender,"0");f.activate(a);assertEquals(otherA.core.record.id(),sessions.active(a.core.id).orElseThrow().character());assertEquals(aExit,f.receipts().find(a.core.id).toCompletableFuture().get().orElseThrow().lastExit());save(f,sender,"900");var policy=(games.dmg.fantasystick.persistence.SwitchDelaySettings)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"switchDelaySettings");assertEquals(Duration.ofSeconds(900),policy.delay());assertFalse(f.receipts().find(b.core.id).toCompletableFuture().get().orElseThrow().canEnter(otherB.core.record.id(),policy.delay(),java.time.Instant.now()));assertTrue(sessions.active(b.core.id).isEmpty(),"B remained active after exit");f.changed(b);f.receipts().find(b.core.id).toCompletableFuture().get();PartyBookNativeTest.drain(f);assertTrue(sessions.active(b.core.id).isEmpty(),b.messages::toString);assertEquals(bExit,f.receipts().find(b.core.id).toCompletableFuture().get().orElseThrow().lastExit());sessions.exit(a.player);f.awaitCharacterAndReceipt(a);var newExit=f.receipts().find(a.core.id).toCompletableFuture().get().orElseThrow().lastExit();assertEquals(Duration.ofSeconds(900),Duration.between(newExit.exitedAt(),newExit.deadline()));f.plugin.setEnabled(false);f.plugin.setEnabled(true);f.command.execute(sender.port,"fantasystick",new String[]{"config","character-swap-cooldown-seconds"});assertTrue(sender.messages.getLast().contains("=900"));}} + @Test void exitRetainsPolicyCapturedWhenItsNativeTransitionStarts()throws Exception{try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var sender=new EquipmentAdminCommandNativeTest.Sender();save(f,sender,"37");var a=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(a.core.id,a.player);f.activate(a);var characters=(games.dmg.fantasystick.persistence.CharacterStorage)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"characters");var worker=(java.util.concurrent.ExecutorService)FantasyStickLifecycleNativeTest.Fixture.field(characters,"worker");var entered=new java.util.concurrent.CountDownLatch(1);var release=new java.util.concurrent.CountDownLatch(1);worker.execute(()->{entered.countDown();try{release.await();}catch(InterruptedException interrupted){Thread.currentThread().interrupt();}});assertTrue(entered.await(5,java.util.concurrent.TimeUnit.SECONDS));var sessions=(games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"sessions");sessions.exit(a.player);save(f,sender,"0");release.countDown();f.awaitCharacterAndReceipt(a);var exit=f.receipts().find(a.core.id).toCompletableFuture().get().orElseThrow().lastExit();assertEquals(Duration.ofSeconds(37),Duration.between(exit.exitedAt(),exit.deadline()));}} + @Test void failedRegisteredWriteLeavesEffectivePolicyAndUnrelatedStateUntouched()throws Exception{try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);java.nio.file.Files.createDirectory(data.resolve("config.yml"));var sender=new EquipmentAdminCommandNativeTest.Sender();f.command.execute(sender.port,"fantasystick",new String[]{"config","character-swap-cooldown-seconds","0"});var task=f.tasks.poll(5,java.util.concurrent.TimeUnit.SECONDS);assertNotNull(task);task.run();assertTrue(sender.messages.getLast().contains("save failed"));f.command.execute(sender.port,"fantasystick",new String[]{"config","character-swap-cooldown-seconds"});assertTrue(sender.messages.getLast().contains("=900"));}} + static void save(FantasyStickLifecycleNativeTest.Fixture f,EquipmentAdminCommandNativeTest.Sender sender,String value)throws Exception{int before=sender.messages.size();f.command.execute(sender.port,"fantasystick",new String[]{"config","character-swap-cooldown-seconds",value});assertEquals(before,sender.messages.size());var task=f.tasks.poll(5,java.util.concurrent.TimeUnit.SECONDS);assertNotNull(task);task.run();assertTrue(sender.messages.getLast().contains("="+value));} +} diff --git a/src/test/java/games/dmg/fantasystick/persistence/SwitchDelaySettingsTest.java b/src/test/java/games/dmg/fantasystick/persistence/SwitchDelaySettingsTest.java new file mode 100644 index 0000000..d38cda4 --- /dev/null +++ b/src/test/java/games/dmg/fantasystick/persistence/SwitchDelaySettingsTest.java @@ -0,0 +1,7 @@ +package games.dmg.fantasystick.persistence; +import static org.junit.jupiter.api.Assertions.*;import java.nio.file.*;import java.time.Duration;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.io.TempDir; +class SwitchDelaySettingsTest{@TempDir Path data; + @Test void validatesZeroPersistsPreservesUnrelatedAndPublishesAfterAcknowledgment()throws Exception{assertEquals(Duration.ofSeconds(900),SwitchDelaySettings.parse(null));assertEquals(Duration.ZERO,SwitchDelaySettings.parse("0"));for(Object bad:new Object[]{-1,"1.5","bad","9223372036854775807","253402300800"})assertThrows(IllegalArgumentException.class,()->SwitchDelaySettings.parse(bad));Files.writeString(data.resolve("config.yml"),"unrelated: keep\ncharacter-swap-cooldown-seconds: 900\n");try(var settings=new SwitchDelaySettings(data,Duration.ofSeconds(900))){var update=settings.set("37").toCompletableFuture().get();assertEquals("900",settings.value());assertTrue(Files.readString(data.resolve("config.yml")).contains("unrelated: keep"));settings.publish(update);assertEquals("37",settings.value());assertEquals(Duration.ofSeconds(37),settings.delay());}} + @Test void concurrentWritesSerializeAndStalePublicationCannotRollBackNewerPolicy()throws Exception{try(var settings=new SwitchDelaySettings(data,Duration.ofSeconds(900))){var one=settings.set("1").toCompletableFuture();var two=settings.set("2").toCompletableFuture();var first=one.get();var second=two.get();settings.publish(second);settings.publish(first);assertEquals("2",settings.value());assertTrue(Files.readString(data.resolve("config.yml")).contains("character-swap-cooldown-seconds: '2'"));}} + @Test void failedWriteRetainsEffectiveValue()throws Exception{try(var settings=new SwitchDelaySettings(data,Duration.ofSeconds(900))){Files.createDirectory(data.resolve("config.yml"));assertThrows(Exception.class,()->settings.set("0").toCompletableFuture().get());assertEquals("900",settings.value());}} +}