feat(abilities): add Revive
Release / release (push) Successful in 6m27s

This commit is contained in:
dmg committed 2026-09-20 06:19:56 -04:00
1 parent 624deb938d
commit 27f38818ae
11 files changed
+1059 -7

No files matched your search

@@ -49,6 +49,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
private games.dmg.fantasystick.ability.AbilityRegistry abilityRegistry;
private games.dmg.fantasystick.ability.AbilityEngine abilityEngine;
private games.dmg.fantasystick.ability.Fireball fireball;
private games.dmg.fantasystick.ability.Revive revive;
private games.dmg.fantasystick.persistence.RevivalStore revivals;
private games.dmg.fantasystick.session.NutritionPolicy nutritionPolicy;
private java.util.concurrent.CompletionStage<Void> configurationDrain = java.util.concurrent.CompletableFuture.completedStage(null);
@@ -116,7 +118,12 @@ public final class FantasyStickPlugin extends JavaPlugin {
notice -> notifyPlayer(generation, notice), diagnostics, presentation, adventureSettings::enabled, gameModes);
abilityRegistry = new games.dmg.fantasystick.ability.AbilityRegistry();
fireball = new games.dmg.fantasystick.ability.Fireball(fireballSettings);
revivals = new games.dmg.fantasystick.persistence.RevivalStore(getDataFolder().toPath());
revive = new games.dmg.fantasystick.ability.Revive(characters, revivals, Clock.systemUTC(), nextTick,
(size, title) -> getServer().createInventory(null, size, title),
problem -> getLogger().log(Level.WARNING, "Revive transition failed", problem));
abilityRegistry.register(fireball.definition());
abilityRegistry.register(revive.definition());
sessions.attachAbilityRegistry(abilityRegistry);
vitals = new games.dmg.fantasystick.session.SessionVitals();
sessions.attachVitals(vitals);
@@ -172,6 +179,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
getServer().getPluginManager().registerEvents(combatExperience, this);
combatExperience.install(this);
getServer().getPluginManager().registerEvents(fireball, this);
getServer().getPluginManager().registerEvents(revive, this);
getServer().getPluginManager().registerEvents(localBasicAttack, this);
getServer().getPluginManager().registerEvents(nutritionPolicy, this);
getServer().getPluginManager().registerEvents(books, this);
@@ -181,7 +189,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
sessionVisuals.install(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);
for (var player : getServer().getOnlinePlayers()) { sessions.arrive(player); revive.reconcile(player); }
} catch (RuntimeException | LinkageError failure) {
try { onDisable(); }
catch (RuntimeException | LinkageError cleanupFailure) { failure.addSuppressed(cleanupFailure); }
@@ -215,6 +223,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
var closingCombatExperience = combatExperience; combatExperience = null;
var closingAbilityEngine = abilityEngine; abilityEngine = null;
var closingFireball = fireball; fireball = null;
var closingRevive = revive; revive = null;
var closingRevivals = revivals; revivals = null;
abilityRegistry = null;
var closingNutrition = nutritionPolicy; nutritionPolicy = null;
// Retire client resources independently of successful ordinary-equipment restoration.
@@ -229,6 +239,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
if (closingBasicAttack != null) cleanup("basic attack", closingBasicAttack::close);
if (closingCombatExperience != null) cleanup("combat experience", closingCombatExperience::close);
if (closingFireball != null) cleanup("Fireball", closingFireball::close);
if (closingRevive != null) cleanup("Revive", closingRevive::close);
if (closingAbilityEngine != null) cleanup("ability engine", closingAbilityEngine::close);
if (closingNutrition != null) cleanup("nutrition policy", closingNutrition::close);
if (closingVisuals != null) cleanup("session particles", closingVisuals::close);
@@ -244,6 +255,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
unregister(closingPartyCombat);
unregister(closingCombatExperience);
unregister(closingFireball);
unregister(closingRevive);
unregister(closingBasicAttack);
unregister(closingNutrition);
unregister(closingBooks);
@@ -256,6 +268,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
recipeRegistered = false; // Retain ownership for a later retry if removal failed.
});
if (closingCharacters != null) cleanup("character storage", closingCharacters::close);
if (closingRevivals != null) cleanup("revival storage", closingRevivals::close);
// Never await IO on the server thread or close receipts ahead of accepted preparations.
if (closingReceipts != null) cleanup("equipment receipt drain", () -> {
if (closingSessions == null) closingReceipts.close();
@@ -17,7 +17,8 @@ public record AbilityDefinition(String id, String name, Material icon, List<Stri
ControlInput.Gesture gesture, Duration cooldown, Map<String, BigDecimal> parameters,
TargetPolicy targetPolicy, AbilityEffect effect) {
public enum Activation { IMMEDIATE, DELAYED, PROJECTILE, AREA, SELECTION }
public enum TargetPolicy { SELF, HOSTILE, PROJECTILE_HOSTILE, ALLY, PARTY, AREA, SELECTION, EXCEPTIONAL_NONCOMBAT }
public enum TargetPolicy { SELF, HOSTILE, PROJECTILE_HOSTILE, ALLY, PARTY, AREA, SELECTION, EXCEPTIONAL_NONCOMBAT,
EXCEPTIONAL_NONCOMBAT_SELECTION }
private static final Pattern ID = Pattern.compile("[a-z][a-z0-9_]{0,63}");
private static final Pattern PARAMETER = Pattern.compile("[a-z][a-z0-9_-]{0,63}");
@@ -3,5 +3,7 @@ package games.dmg.fantasystick.ability;
/** Focused native effect invoked only after shared persistence, cooldown and target authorization. */
@FunctionalInterface
public interface AbilityEffect {
/** Effect-specific initial eligibility checked before the shared cooldown commit. */
default boolean accepts(games.dmg.fantasystick.session.ControlInput input) { return true; }
void activate(AbilityExecution execution);
}
@@ -138,7 +138,13 @@ public final class AbilityEngine implements Consumer<ControlInput>, AutoCloseabl
input.player().sendMessage("" + definition.name() + " is ready in "
+ Math.max(1, Duration.between(now, existing).toSeconds()) + " seconds."); return;
}
if (!eligible(definition.targetPolicy(), input, input.target())) {
boolean accepted;
try { accepted = eligible(definition.targetPolicy(), input, input.target()) && definition.effect().accepts(input); }
catch (RuntimeException invalid) {
report(input.session().character(), definition.id(), invalid);
input.player().sendMessage("That target could not be validated for " + definition.name() + "."); return;
}
if (!accepted) {
input.player().sendMessage("That target is not eligible for " + definition.name() + "."); return;
}
var key = new Key(input.session().character(), definition.id());
@@ -235,6 +241,7 @@ public final class AbilityEngine implements Consumer<ControlInput>, AutoCloseabl
case AREA -> target == null || target instanceof LivingEntity && (!(target instanceof Player player) || fantasy(player));
case SELECTION -> target == null || target instanceof LivingEntity && (!(target instanceof Player player) || fantasy(player));
case EXCEPTIONAL_NONCOMBAT -> target instanceof Player && target != input.player();
case EXCEPTIONAL_NONCOMBAT_SELECTION -> target == null || target instanceof Player && target != input.player();
};
}
@@ -320,6 +327,7 @@ public final class AbilityEngine implements Consumer<ControlInput>, AutoCloseabl
}
@Override public void report(AbilityReport.Type type, Entity target, java.math.BigDecimal amount) {
if (!stillCurrent() || definition.targetPolicy() == AbilityDefinition.TargetPolicy.EXCEPTIONAL_NONCOMBAT
|| definition.targetPolicy() == AbilityDefinition.TargetPolicy.EXCEPTIONAL_NONCOMBAT_SELECTION
|| target == null || !AbilityEngine.this.eligible(definition.targetPolicy(), input, target)) return;
reports.accept(new AbilityReport(type, key.character(), input.session().session(), target.getUniqueId(), amount, clock.instant()));
}
@@ -0,0 +1,374 @@
package games.dmg.fantasystick.ability;
import games.dmg.fantasystick.items.CharacterSheets;
import games.dmg.fantasystick.items.TailBooks;
import games.dmg.fantasystick.persistence.CharacterRecord;
import games.dmg.fantasystick.persistence.CharacterStorage;
import games.dmg.fantasystick.persistence.RevivalStore;
import games.dmg.fantasystick.progression.Stat;
import games.dmg.fantasystick.session.ControlInput;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import net.kyori.adventure.text.Component;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
/** Revive target selection, contained popup and proof-based Tail conversion. */
public final class Revive implements AbilityEffect, Listener, AutoCloseable {
public interface PopupFactory { Inventory create(int size, Component title); }
private static final Duration DEATH_AGE = Duration.ofHours(24);
private static final Duration VIEW_TIME = Duration.ofMinutes(5);
private static final double RANGE = 12;
private record Candidate(int slot, ItemStack captured, TailBooks.Identity identity) { }
private record Choice(Candidate candidate, CharacterRecord record) { }
private final CharacterStorage characters;
private final RevivalStore reservations;
private final Clock clock;
private final Consumer<Runnable> nextTick;
private final PopupFactory popups;
private final Consumer<Throwable> failures;
private final TailBooks tails = new TailBooks();
private final CharacterSheets sheets = new CharacterSheets();
private final Map<Inventory, View> inventories = new IdentityHashMap<>();
private final Map<UUID, View> targets = new LinkedHashMap<>();
private boolean closed;
private final class View implements AutoCloseable {
final AbilityExecution execution;
final Player target;
final Inventory inventory;
final Map<Integer, Choice> choices;
boolean selecting;
boolean finished;
View(AbilityExecution execution, Player target, Inventory inventory, Map<Integer, Choice> choices) {
this.execution = execution; this.target = target; this.inventory = inventory; this.choices = choices;
}
@Override public void close() {
if (finished) return;
finished = true;
inventories.remove(inventory, this); targets.remove(target.getUniqueId(), this);
inventory.clear();
try { target.closeInventory(); } catch (RuntimeException failure) { report(failure); }
}
}
public Revive(CharacterStorage characters, RevivalStore reservations, Clock clock, Consumer<Runnable> nextTick,
PopupFactory popups, Consumer<Throwable> failures) {
this.characters = Objects.requireNonNull(characters); this.reservations = Objects.requireNonNull(reservations);
this.clock = Objects.requireNonNull(clock); this.nextTick = Objects.requireNonNull(nextTick);
this.popups = Objects.requireNonNull(popups); this.failures = Objects.requireNonNull(failures);
}
public AbilityDefinition definition() {
return new AbilityDefinition("revive", "Revive", Material.ECHO_SHARD,
List.of("Let another player continue one fallen character.", "A valid cast spends the daily opportunity."),
"Use the equipped shard while aiming at another player within 12 blocks.",
Map.of(Stat.WIS, BigInteger.valueOf(30), Stat.CHR, BigInteger.valueOf(24), Stat.CON, BigInteger.valueOf(12)),
BigInteger.ONE, AbilityDefinition.Activation.SELECTION, ControlInput.Gesture.USE, Duration.ofHours(24),
Map.of("range", BigDecimal.valueOf(12), "selection-time", BigDecimal.valueOf(300),
"death-age", BigDecimal.valueOf(86400)),
AbilityDefinition.TargetPolicy.EXCEPTIONAL_NONCOMBAT_SELECTION, this);
}
@Override public boolean accepts(ControlInput input) { return !closed && target(input) != null; }
@Override public void activate(AbilityExecution execution) {
if (closed || !execution.stillCurrent()) { execution.finish(); return; }
Player target = target(execution.input());
if (target == null) {
execution.input().player().sendMessage("Revive found no eligible player within 12 blocks and line of sight.");
execution.finish(); return;
}
var captured = candidates(target);
if (captured.isEmpty()) {
execution.input().player().sendMessage("That player has no direct-inventory Tail eligible for Revive.");
execution.finish(); return;
}
var loads = captured.stream().map(candidate -> characters.find(candidate.identity().characterId())).toList();
CompletableFuture.allOf(loads.toArray(CompletableFuture[]::new)).whenComplete((ignored, failure) -> schedule(() -> {
if (failure != null) { report(failure); execution.input().player().sendMessage("Revive could not inspect those Tails safely."); execution.finish(); return; }
if (closed || !execution.stillCurrent() || !target.isOnline()) { execution.finish(); return; }
var eligible = new ArrayList<Choice>();
Instant now = clock.instant();
for (int index = 0; index < captured.size(); index++) {
var found = loads.get(index).join();
if (found.isEmpty()) continue;
var record = found.orElseThrow();
var candidate = captured.get(index);
if (eligible(record, candidate.identity(), now) && unchanged(target, candidate)) eligible.add(new Choice(candidate, record));
}
if (eligible.isEmpty()) {
execution.input().player().sendMessage("That player has no current Tail younger than 24 hours.");
execution.finish(); return;
}
open(execution, target, eligible, now);
}));
}
private Player target(ControlInput input) {
Player caster = input.player();
Entity supplied = input.target();
Player selected = supplied instanceof Player player ? player : null;
if (selected == null) {
Location eye = caster.getEyeLocation();
var hit = caster.getWorld().rayTraceEntities(eye, eye.getDirection(), RANGE,
entity -> entity instanceof Player && entity != caster);
if (hit != null && hit.getHitEntity() instanceof Player player) selected = player;
}
if (selected == null || selected == caster || !selected.isOnline() || selected.getWorld() != caster.getWorld()
|| selected.getLocation().distanceSquared(caster.getLocation()) > RANGE * RANGE
|| !caster.hasLineOfSight(selected)) return null;
return selected;
}
private List<Candidate> candidates(Player target) {
var result = new ArrayList<Candidate>();
for (int slot = 0; slot <= 40; slot++) {
if (slot > 35 && slot != 40) continue;
ItemStack item = target.getInventory().getItem(slot);
if (item == null || item.isEmpty()) continue;
var identity = tails.identify(item);
if (identity.isPresent()) result.add(new Candidate(slot, item.clone(), identity.orElseThrow()));
}
return List.copyOf(result);
}
private boolean eligible(CharacterRecord record, TailBooks.Identity identity, Instant now) {
if (!record.dead() || !record.id().equals(identity.characterId()) || !Objects.equals(record.deathId(), identity.deathId())) return false;
Duration age = Duration.between(record.diedAt(), now);
return !age.isNegative() && age.compareTo(DEATH_AGE) < 0;
}
private boolean unchanged(Player target, Candidate candidate) {
ItemStack current = target.getInventory().getItem(candidate.slot());
return current != null && current.equals(candidate.captured());
}
private void open(AbilityExecution execution, Player target, List<Choice> eligible, Instant now) {
View old = targets.get(target.getUniqueId()); if (old != null) old.execution.finish();
int size = Math.min(54, Math.max(9, ((eligible.size() + 8) / 9) * 9));
Inventory inventory = popups.create(size, Component.text("Choose a Tail to Revive"));
var choices = new LinkedHashMap<Integer, Choice>();
for (int index = 0; index < eligible.size() && index < size; index++) {
Choice choice = eligible.get(index); ItemStack display = choice.candidate().captured().clone(); display.setAmount(1);
var meta = display.getItemMeta();
long seconds = Math.max(0, Duration.between(now, choice.record().diedAt().plus(DEATH_AGE)).toSeconds());
meta.lore(List.of(Component.text("Level " + choice.record().level()),
Component.text("Eligible for " + seconds + " more seconds"), Component.text("Click to continue this character")));
display.setItemMeta(meta); inventory.setItem(index, display); choices.put(index, choice);
}
var view = new View(execution, target, inventory, Map.copyOf(choices));
inventories.put(inventory, view); targets.put(target.getUniqueId(), view); execution.own(view);
target.openInventory(inventory);
execution.later(VIEW_TIME, execution::finish);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void click(org.bukkit.event.inventory.InventoryClickEvent event) {
var view = inventories.get(event.getView().getTopInventory());
if (view == null) return;
event.setCancelled(true);
if (event.getWhoClicked() != view.target || event.getRawSlot() < 0 || event.getRawSlot() >= view.inventory.getSize()) return;
Choice choice = view.choices.get(event.getRawSlot());
if (choice == null || view.selecting) return;
view.selecting = true; inventories.remove(view.inventory, view); targets.remove(view.target.getUniqueId(), view);
view.inventory.clear(); view.target.closeInventory();
confirm(view, choice);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void drag(org.bukkit.event.inventory.InventoryDragEvent event) {
var view = inventories.get(event.getView().getTopInventory());
if (view != null && event.getRawSlots().stream().anyMatch(slot -> slot < view.inventory.getSize())) event.setCancelled(true);
}
@EventHandler(priority = EventPriority.MONITOR)
public void close(org.bukkit.event.inventory.InventoryCloseEvent event) {
var view = inventories.get(event.getView().getTopInventory());
if (view != null && !view.selecting) view.execution.finish();
}
@EventHandler(priority = EventPriority.MONITOR)
public void quit(org.bukkit.event.player.PlayerQuitEvent event) {
var targetView = targets.get(event.getPlayer().getUniqueId()); if (targetView != null) targetView.execution.finish();
for (var view : List.copyOf(inventories.values())) {
if (view.execution.input().player() == event.getPlayer()) view.execution.finish();
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void join(org.bukkit.event.player.PlayerJoinEvent event) { reconcile(event.getPlayer()); }
private void confirm(View view, Choice choice) {
if (closed || !view.execution.stillCurrent() || !view.target.isOnline() || !unchanged(view.target, choice.candidate())) {
view.execution.finish(); return;
}
characters.find(choice.record().id()).whenComplete((found, failure) -> schedule(() -> {
if (failure != null) { report(failure); view.execution.input().player().sendMessage("Revive could not recheck that Tail; no item changed."); view.execution.finish(); return; }
if (closed || !view.execution.stillCurrent() || !view.target.isOnline() || found.isEmpty()
|| !eligible(found.orElseThrow(), choice.candidate().identity(), clock.instant())
|| !unchanged(view.target, choice.candidate())) {
view.execution.input().player().sendMessage("That Tail is no longer eligible; no item changed.");
view.execution.finish(); return;
}
reserve(view, choice.candidate(), found.orElseThrow());
}));
}
private void reserve(View view, Candidate candidate, CharacterRecord dead) {
ItemStack source = view.target.getInventory().getItem(candidate.slot());
int destination = source.getAmount() == 1 ? -1 : emptyDirectSlot(view.target, candidate.slot());
if (source.getAmount() > 1 && destination < 0) {
view.target.sendMessage("Revive needs one empty direct inventory slot to preserve the copied Tails.");
view.execution.finish(); return;
}
var reservation = new RevivalStore.Reservation(UUID.randomUUID(), view.execution.character().id(),
view.target.getUniqueId(), dead.id(), dead.deathId(), clock.instant().truncatedTo(ChronoUnit.SECONDS),
candidate.slot(), source.getAmount(), destination);
reservations.reserve(reservation).whenComplete((reserved, failure) -> schedule(() -> {
if (failure != null) { report(failure); view.execution.input().player().sendMessage("Revive reservation could not be saved; no Tail changed."); view.execution.finish(); return; }
if (reserved.isEmpty() || closed || !view.execution.stillCurrent() || !view.target.isOnline()
|| !unchanged(view.target, candidate)) {
view.execution.input().player().sendMessage("Revive selection became stale after reservation; no Tail was changed.");
view.execution.finish(); return;
}
deliver(view, dead, reservation);
}));
}
private int emptyDirectSlot(Player target, int source) {
for (int slot = 0; slot <= 40; slot++) {
if (slot > 35 && slot != 40 || slot == source) continue;
ItemStack item = target.getInventory().getItem(slot);
if (item == null || item.isEmpty()) return slot;
}
return -1;
}
private void deliver(View view, CharacterRecord dead, RevivalStore.Reservation reservation) {
try {
var provisional = new CharacterRecord(dead.id(), dead.name(), dead.revision(), dead.stats(), dead.level(), dead.experience(),
dead.unspentPoints(), dead.maximumHealth(), dead.learned(), dead.loadout(), dead.cooldowns(), dead.restrictedKills(),
false, dead.deathId(), dead.diedAt());
ItemStack sheet = sheets.create(provisional);
ItemStack source = view.target.getInventory().getItem(reservation.sourceSlot());
if (reservation.sourceAmount() == 1) view.target.getInventory().setItem(reservation.sourceSlot(), sheet);
else {
view.target.getInventory().setItem(reservation.destinationSlot(), sheet);
var remaining = source.clone(); remaining.setAmount(reservation.sourceAmount() - 1);
view.target.getInventory().setItem(reservation.sourceSlot(), remaining);
}
view.target.updateInventory();
} catch (RuntimeException uncertain) {
report(uncertain); view.target.sendMessage("Revive item delivery is uncertain; retained proof requires recovery.");
view.execution.finish(); return;
}
var nativeLimit = games.dmg.fantasystick.session.NativeHealthLimit.read();
characters.restoreDeathRecord(reservation.character(), reservation.death(), nativeLimit)
.whenComplete((restored, failure) -> schedule(() -> {
if (failure != null || restored.isEmpty()) {
if (failure != null) report(failure);
view.target.sendMessage("The Tail changed, but character restoration is pending recovery; do not move the sheet.");
view.execution.finish(); return;
}
if (installFinalSheet(view.target, restored.orElseThrow())) {
reservations.clear(reservation.character(), reservation.id()).exceptionally(failure2 -> { report(failure2); return false; });
view.target.sendMessage("Restored character sheet: " + restored.orElseThrow().name() + ".");
view.execution.input().player().sendMessage("Revive restored " + restored.orElseThrow().name() + ".");
} else view.target.sendMessage("Character restoration was saved, but sheet custody is ambiguous; retained proof requires recovery.");
view.execution.finish();
}));
}
private boolean installFinalSheet(Player target, CharacterRecord record) {
int slot = uniqueSheetSlot(target, record.id());
if (slot < 0) return false;
target.getInventory().setItem(slot, sheets.create(record)); target.updateInventory(); return true;
}
private int uniqueSheetSlot(Player target, UUID character) {
int found = -1;
for (int slot = 0; slot <= 40; slot++) {
if (slot > 35 && slot != 40) continue;
if (sheets.identify(target.getInventory().getItem(slot)).filter(character::equals).isEmpty()) continue;
if (found >= 0) return -2;
found = slot;
}
return found;
}
public void reconcile(Player target) {
if (closed || !target.isOnline()) return;
reservations.target(target.getUniqueId()).whenComplete((found, failure) -> {
if (failure != null) { report(failure); return; }
for (var reservation : found) characters.find(reservation.character()).whenComplete((record, loadFailure) -> schedule(() -> {
if (loadFailure != null) { report(loadFailure); return; }
if (closed || !target.isOnline() || record.isEmpty()) return;
reconcile(target, reservation, record.orElseThrow());
}));
});
}
private void reconcile(Player target, RevivalStore.Reservation reservation, CharacterRecord record) {
int foundSheet = uniqueSheetSlot(target, reservation.character());
boolean hasSheet = foundSheet >= 0;
ItemStack source = target.getInventory().getItem(reservation.sourceSlot());
boolean unchangedTail = source != null && source.getAmount() == reservation.sourceAmount()
&& tails.identify(source).filter(id -> id.characterId().equals(reservation.character()) && id.deathId().equals(reservation.death())).isPresent();
boolean consumedTail = reservation.sourceAmount() == 1 ? hasSheet
: source != null && source.getAmount() == reservation.sourceAmount() - 1
&& tails.identify(source).filter(id -> id.deathId().equals(reservation.death())).isPresent();
if (!record.dead() && hasSheet && installFinalSheet(target, record)) {
reservations.clear(reservation.character(), reservation.id()); return;
}
if (record.dead() && unchangedTail && !hasSheet) {
reservations.clear(reservation.character(), reservation.id()); return;
}
if (record.dead() && hasSheet && (consumedTail || unchangedTail && reservation.sourceAmount() > 1)) {
if (unchangedTail && reservation.sourceAmount() > 1) {
var remaining = source.clone(); remaining.setAmount(source.getAmount() - 1);
target.getInventory().setItem(reservation.sourceSlot(), remaining); target.updateInventory();
}
var nativeLimit = games.dmg.fantasystick.session.NativeHealthLimit.read();
characters.restoreDeathRecord(reservation.character(), reservation.death(), nativeLimit)
.whenComplete((restored, failure) -> schedule(() -> {
if (failure != null) { report(failure); return; }
if (restored.isPresent() && installFinalSheet(target, restored.orElseThrow())) {
reservations.clear(reservation.character(), reservation.id());
}
}));
}
}
private void schedule(Runnable action) {
try { nextTick.accept(action); } catch (RuntimeException rejected) { report(rejected); }
}
private void report(Throwable failure) { try { failures.accept(failure); } catch (RuntimeException ignored) { } }
@Override public void close() {
if (closed) return; closed = true;
for (var view : List.copyOf(inventories.values())) view.execution.finish();
inventories.clear(); targets.clear();
}
}
@@ -489,8 +489,15 @@ public final class CharacterStorage implements AutoCloseable {
}
public CompletableFuture<Optional<CharacterRecord>> restoreDeathRecord(UUID characterId, UUID deathId) {
return restoreDeathRecord(characterId, deathId, null);
}
/** Native Revive supplies the current plugin-controlled health ceiling captured on the server thread. */
public CompletableFuture<Optional<CharacterRecord>> restoreDeathRecord(UUID characterId, UUID deathId,
java.math.BigDecimal nativeLimit) {
Objects.requireNonNull(characterId);
Objects.requireNonNull(deathId);
if (nativeLimit != null && nativeLimit.signum() <= 0) throw new IllegalArgumentException("Invalid revival health limit");
Instant selectedAt = clock.instant();
return submit(() -> {
Optional<CharacterRecord> found = repository.load(characterId);
@@ -500,9 +507,10 @@ public final class CharacterStorage implements AutoCloseable {
if (!deathId.equals(old.deathId()) || age.isNegative() || age.compareTo(Duration.ofHours(24)) >= 0) {
return Optional.empty();
}
var health = nativeLimit == null ? old.maximumHealth() : old.maximumHealth().min(nativeLimit);
var restored = new CharacterRecord(old.id(), old.name(), old.revision().add(BigInteger.ONE), old.stats(),
old.level(), old.experience(), old.unspentPoints(), old.maximumHealth(), old.learned(),
old.loadout(), old.cooldowns(), old.restrictedKills(), false, old.deathId(), old.diedAt());
old.level(), old.experience(), old.unspentPoints(), health, old.learned(), old.loadout(), old.cooldowns(),
old.restrictedKills(), false, old.deathId(), old.diedAt());
repository.replace(restored, old.revision());
return Optional.of(restored);
});
@@ -0,0 +1,159 @@
package games.dmg.fantasystick.persistence;
import java.io.IOException;
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.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
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;
/** Feature-scoped Revive interruption proof; never authority to guess or mint an item. */
public final class RevivalStore implements AutoCloseable {
private static final int MAX_FILE_BYTES = 32_768;
private static final int MAX_FILES = 4096;
private static final Set<String> KEYS = Set.of("schema-version", "reservation-id", "caster-character-id",
"target-player-id", "character-id", "death-id", "created-at", "source-slot", "source-amount", "destination-slot");
public record Reservation(UUID id, UUID casterCharacter, UUID targetPlayer, UUID character, UUID death,
Instant createdAt, int sourceSlot, int sourceAmount, int destinationSlot) {
public Reservation {
Objects.requireNonNull(id); Objects.requireNonNull(casterCharacter); Objects.requireNonNull(targetPlayer);
Objects.requireNonNull(character); Objects.requireNonNull(death); Objects.requireNonNull(createdAt);
if (createdAt.getNano() != 0 || sourceSlot < 0 || sourceSlot > 40 || sourceSlot > 35 && sourceSlot != 40
|| sourceAmount < 1 || sourceAmount > 99 || destinationSlot < -1 || destinationSlot > 40
|| destinationSlot > 35 && destinationSlot != 40 || destinationSlot == sourceSlot) {
throw new IllegalArgumentException("Invalid revival reservation");
}
}
}
private final Path directory;
private final ExecutorService worker = Executors.newSingleThreadExecutor(
task -> new Thread(task, "fantasy-revival-persistence"));
public RevivalStore(Path pluginDataDirectory) {
directory = Objects.requireNonNull(pluginDataDirectory).resolve("revivals").toAbsolutePath();
}
public CompletableFuture<Optional<Reservation>> reserve(Reservation reservation) {
Objects.requireNonNull(reservation);
return submit(() -> {
Path file = file(reservation.character());
if (Files.exists(file, LinkOption.NOFOLLOW_LINKS)) return Optional.empty();
safeDirectory();
Path temporary = directory.resolve("." + reservation.character() + "." + UUID.randomUUID() + ".tmp");
try {
Files.writeString(temporary, encode(reservation), StandardCharsets.UTF_8,
StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
Files.move(temporary, file, StandardCopyOption.ATOMIC_MOVE);
} finally { Files.deleteIfExists(temporary); }
return Optional.of(reservation);
});
}
public CompletableFuture<Optional<Reservation>> find(UUID character) {
Objects.requireNonNull(character);
return submit(() -> load(file(character)));
}
public CompletableFuture<List<Reservation>> target(UUID player) {
Objects.requireNonNull(player);
return submit(() -> {
if (!Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) return List.of();
if (Files.isSymbolicLink(directory) || !Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) {
throw new IOException("Unsafe revival directory");
}
var result = new ArrayList<Reservation>();
try (var files = Files.list(directory)) {
for (var path : files.limit(MAX_FILES + 1).toList()) {
if (result.size() >= MAX_FILES) throw new IOException("Too many revival reservations");
if (!path.getFileName().toString().endsWith(".yml")) continue;
var reservation = load(path).orElseThrow(() -> new IOException("Missing revival reservation"));
if (reservation.targetPlayer().equals(player)) result.add(reservation);
}
}
return List.copyOf(result);
});
}
public CompletableFuture<Boolean> clear(UUID character, UUID reservation) {
Objects.requireNonNull(character); Objects.requireNonNull(reservation);
return submit(() -> {
var found = load(file(character));
if (found.isEmpty() || !found.orElseThrow().id().equals(reservation)) return false;
return Files.deleteIfExists(file(character));
});
}
private void safeDirectory() throws IOException {
if (Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) {
if (Files.isSymbolicLink(directory) || !Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) {
throw new IOException("Unsafe revival directory");
}
} else Files.createDirectories(directory);
}
private Path file(UUID character) { return directory.resolve(character + ".yml"); }
private Optional<Reservation> load(Path file) throws IOException {
if (!Files.exists(file, LinkOption.NOFOLLOW_LINKS)) return Optional.empty();
if (Files.isSymbolicLink(file) || !Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)
|| Files.size(file) > MAX_FILE_BYTES) throw new IOException("Unsafe revival reservation");
Object decoded;
try {
var options = new LoaderOptions(); options.setAllowDuplicateKeys(false); options.setMaxAliasesForCollections(0);
decoded = new Yaml(new SafeConstructor(options)).load(Files.readString(file, StandardCharsets.UTF_8));
} catch (RuntimeException invalid) { throw new IOException("Invalid revival reservation", invalid); }
if (!(decoded instanceof Map<?, ?> raw) || !raw.keySet().equals(KEYS)) throw new IOException("Invalid revival reservation keys");
try {
if (!"1".equals(text(raw, "schema-version"))) throw new IllegalArgumentException("schema");
var value = new Reservation(uuid(raw, "reservation-id"), uuid(raw, "caster-character-id"),
uuid(raw, "target-player-id"), uuid(raw, "character-id"), uuid(raw, "death-id"),
Instant.parse(text(raw, "created-at")), integer(raw, "source-slot"), integer(raw, "source-amount"),
integer(raw, "destination-slot"));
if (!file.getFileName().toString().equals(value.character() + ".yml")) throw new IllegalArgumentException("identity");
return Optional.of(value);
} catch (RuntimeException invalid) { throw new IOException("Invalid revival reservation", invalid); }
}
private static String encode(Reservation value) {
var map = new LinkedHashMap<String, Object>();
map.put("schema-version", "1"); map.put("reservation-id", value.id().toString());
map.put("caster-character-id", value.casterCharacter().toString()); map.put("target-player-id", value.targetPlayer().toString());
map.put("character-id", value.character().toString()); map.put("death-id", value.death().toString());
map.put("created-at", value.createdAt().toString()); map.put("source-slot", Integer.toString(value.sourceSlot()));
map.put("source-amount", Integer.toString(value.sourceAmount())); map.put("destination-slot", Integer.toString(value.destinationSlot()));
return new Yaml().dump(map);
}
private static String text(Map<?, ?> map, String key) {
Object value = map.get(key); if (!(value instanceof String text) || text.isBlank()) throw new IllegalArgumentException(key); return text;
}
private static UUID uuid(Map<?, ?> map, String key) { var value = UUID.fromString(text(map, key)); if (!value.toString().equals(text(map, key))) throw new IllegalArgumentException(key); return value; }
private static int integer(Map<?, ?> map, String key) { return Integer.parseInt(text(map, key)); }
@FunctionalInterface private interface Work<T> { T run() throws IOException; }
private <T> CompletableFuture<T> submit(Work<T> work) {
try {
return CompletableFuture.supplyAsync(() -> { try { return work.run(); } catch (IOException error) { throw new CompletionException(error); } }, worker);
} catch (RejectedExecutionException rejected) { return CompletableFuture.failedFuture(rejected); }
}
@Override public void close() { worker.shutdown(); }
}