fix(revival): preserve Tail authority and native custody
This commit is contained in:
1 parent
831c0ff3f6
commit
6dc706b6ff
15 files changed
+1206
-133
No files matched your search
@@ -563,7 +563,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
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));
|
||||
problem -> getLogger().log(Level.WARNING, "Revive transition failed", problem), getServer()::getPlayer);
|
||||
revive.attachDowned(downedController,downedSettings::protection);
|
||||
abilityRegistry.register(fireball.definition());
|
||||
abilityRegistry.register(frostShard.definition());
|
||||
@@ -638,7 +638,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
adminReviveSettings = new games.dmg.fantasystick.persistence.AdminReviveSettings(getDataFolder().toPath(), adminReviveTimeout);
|
||||
adminRevival = new games.dmg.fantasystick.session.AdminRevival(characters, revivals, Clock.systemUTC(), nextTick,
|
||||
abilityScheduler::later, (size, title) -> getServer().createInventory(null, size, title),
|
||||
problem -> getLogger().log(Level.WARNING, "Admin revival failed", problem));
|
||||
problem -> getLogger().log(Level.WARNING, "Admin revival failed", problem), getServer()::getPlayer);
|
||||
abilityEngine = new games.dmg.fantasystick.ability.AbilityEngine(abilityRegistry, characters, sessions, parties,
|
||||
Clock.systemUTC(), nextTick, abilityScheduler, report -> {var current=dungeonController;if(current!=null)current.accept(report);}, combatFeedback, trainingDummyController,
|
||||
problem -> getLogger().log(Level.WARNING, "Ability engine failed for character " + problem.character()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package games.dmg.fantasystick.ability;
|
||||
|
||||
import games.dmg.fantasystick.items.CharacterSheets;
|
||||
import games.dmg.fantasystick.items.TailBooks;
|
||||
import games.dmg.fantasystick.items.TailRevivalDelivery;
|
||||
import games.dmg.fantasystick.persistence.CharacterRecord;
|
||||
import games.dmg.fantasystick.persistence.CharacterStorage;
|
||||
import games.dmg.fantasystick.persistence.RevivalStore;
|
||||
@@ -48,8 +48,8 @@ public final class Revive implements AbilityEffect, Listener, AutoCloseable {
|
||||
private final Consumer<Runnable> nextTick;
|
||||
private final PopupFactory popups;
|
||||
private final Consumer<Throwable> failures;
|
||||
private final java.util.function.Function<UUID, Player> players;
|
||||
private final TailBooks tails = new TailBooks();
|
||||
private final CharacterSheets sheets = new CharacterSheets();
|
||||
private games.dmg.fantasystick.session.DownedController downed;
|
||||
private games.dmg.fantasystick.events.DownedEventBridge downedEvents;
|
||||
private games.dmg.fantasystick.events.ReviveEventBridge reviveEvents;
|
||||
@@ -73,31 +73,36 @@ public final class Revive implements AbilityEffect, Listener, AutoCloseable {
|
||||
}
|
||||
void resolve(String outcome,String stage){if(cast!=null&&!eventResolved){eventResolved=true;reviveEvents.resolved(cast,outcome,stage);}}
|
||||
void fail(String reason){if(cast!=null&&!eventResolved){eventResolved=true;reviveEvents.failed(cast,reason);}}
|
||||
void revived(RevivalStore.Reservation reservation,CharacterRecord dead,CharacterRecord restored){if(cast!=null&&!eventResolved){eventResolved=true;reviveEvents.revived(cast,reservation,dead,restored,target);}}
|
||||
void revived(RevivalStore.Reservation reservation,CharacterRecord dead,CharacterRecord restored,games.dmg.fantasystick.events.ReviveEventBridge.Carrier carrier){if(cast!=null&&!eventResolved){eventResolved=true;reviveEvents.revived(cast,reservation,dead,restored,carrier);}}
|
||||
@Override public void close() {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
inventories.remove(inventory, this); targets.remove(target.getUniqueId(), this);
|
||||
inventory.clear();
|
||||
if(!selecting)resolve("cancelled_or_expired","tail_selection_closed");
|
||||
try { target.closeInventory(); } catch (RuntimeException failure) { report(failure); }
|
||||
try { if (!selecting) target.closeInventory(); } catch (RuntimeException failure) { report(failure); }
|
||||
}
|
||||
}
|
||||
|
||||
public Revive(CharacterStorage characters, RevivalStore reservations, Clock clock, Consumer<Runnable> nextTick,
|
||||
PopupFactory popups, Consumer<Throwable> failures) {
|
||||
PopupFactory popups, Consumer<Throwable> failures, java.util.function.Function<UUID, Player> players) {
|
||||
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);
|
||||
this.players = Objects.requireNonNull(players);
|
||||
}
|
||||
|
||||
public void attachDowned(games.dmg.fantasystick.session.DownedController controller,java.util.function.Supplier<Duration> protection){if(closed||downed!=null)throw new IllegalStateException("Downed Revive already attached or closed");downed=Objects.requireNonNull(controller);downedProtection=Objects.requireNonNull(protection);}
|
||||
public void attachDownedEvents(games.dmg.fantasystick.events.DownedEventBridge events){if(closed||downedEvents!=null)throw new IllegalStateException("Downed Revive events already attached or closed");downedEvents=Objects.requireNonNull(events);}
|
||||
public void attachEvents(games.dmg.fantasystick.events.ReviveEventBridge events){if(closed||reviveEvents!=null)throw new IllegalStateException("Revive events already attached or closed");reviveEvents=Objects.requireNonNull(events);}
|
||||
public void attachAdminRevivalEvents(games.dmg.fantasystick.events.AdminRevivalEventBridge events){if(closed||adminRevivalEvents!=null)throw new IllegalStateException("Admin revival events already attached or closed");adminRevivalEvents=Objects.requireNonNull(events);}
|
||||
private void recoveryEvent(RevivalStore.Reservation reservation,CharacterRecord restored,Player target){
|
||||
if(reservation.administrative()){if(adminRevivalEvents!=null)adminRevivalEvents.recovered(reservation,restored,target);}
|
||||
else if(reviveEvents!=null)reviveEvents.recovered(reservation,restored,target);
|
||||
private Runnable recoveryAcknowledgment(RevivalStore.Reservation reservation, CharacterRecord restored, Player target) {
|
||||
if (reservation.administrative()) {
|
||||
var snapshot = adminRevivalEvents == null ? null : adminRevivalEvents.snapshot(target);
|
||||
return () -> { if (snapshot != null) adminRevivalEvents.recovered(reservation, restored, snapshot); };
|
||||
}
|
||||
var snapshot = reviveEvents == null ? null : reviveEvents.snapshot(target);
|
||||
return () -> { if (snapshot != null) reviveEvents.recovered(reservation, restored, snapshot); };
|
||||
}
|
||||
|
||||
public AbilityDefinition definition() {
|
||||
@@ -216,7 +221,7 @@ public final class Revive implements AbilityEffect, Listener, AutoCloseable {
|
||||
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.selecting = true; inventories.remove(view.inventory, view); // Keep the selected operation under quit/close ownership.
|
||||
view.inventory.clear(); view.target.closeInventory();
|
||||
confirm(view, choice);
|
||||
}
|
||||
@@ -236,7 +241,7 @@ public final class Revive implements AbilityEffect, Listener, AutoCloseable {
|
||||
@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())) {
|
||||
for (var view : List.copyOf(targets.values())) {
|
||||
if (view.execution.input().player() == event.getPlayer()) view.execution.finish();
|
||||
}
|
||||
}
|
||||
@@ -269,15 +274,24 @@ public final class Revive implements AbilityEffect, Listener, AutoCloseable {
|
||||
}
|
||||
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);
|
||||
candidate.slot(), source.getAmount(), destination, false, dead.sheetGeneration());
|
||||
reservations.reserve(reservation).whenComplete((reserved, failure) -> schedule(() -> {
|
||||
if (failure != null) {view.fail("reservation_save_failed"); 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)) {
|
||||
|| !unchanged(view.target, candidate)
|
||||
|| !games.dmg.fantasystick.items.TailRevivalDelivery.destinationAvailable(view.target, reservation)) {
|
||||
if (reserved.isPresent()) reservations.cancelReserved(reservation)
|
||||
.exceptionally(error -> { report(error); return false; });
|
||||
view.resolve("stale","tail_reservation");view.execution.input().player().sendMessage("Revive selection became stale after reservation; no Tail was changed.");
|
||||
view.execution.finish(); return;
|
||||
}
|
||||
deliver(view, dead, reservation);
|
||||
reservations.beginDelivery(reservation).whenComplete((begun, beginFailure) -> schedule(() -> {
|
||||
if (beginFailure != null || begun.isEmpty()) {
|
||||
if (beginFailure != null) report(beginFailure);
|
||||
view.fail("delivery_fence_unavailable"); view.execution.finish(); return;
|
||||
}
|
||||
deliver(view, candidate, dead, begun.orElseThrow());
|
||||
}));
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -290,58 +304,45 @@ public final class Revive implements AbilityEffect, Listener, AutoCloseable {
|
||||
return -1;
|
||||
}
|
||||
|
||||
private void deliver(View view, CharacterRecord dead, RevivalStore.Reservation reservation) {
|
||||
private boolean current(View view) {
|
||||
return !closed && !view.finished && view.execution.stillCurrent()
|
||||
&& TailRevivalDelivery.currentRecipient(view.target, players);
|
||||
}
|
||||
|
||||
private void uncertain(View view) {
|
||||
view.fail("tail_custody_uncertain");
|
||||
view.target.sendMessage("Revive could not acknowledge delivery safely; any pending custody proof is retained.");
|
||||
view.execution.finish();
|
||||
}
|
||||
|
||||
private void deliver(View view, Candidate candidate, 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.passives(), dead.cooldowns(), dead.restrictedKills(),
|
||||
false, dead.deathId(), dead.diedAt(), dead.sheetGeneration());
|
||||
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);
|
||||
if (!TailRevivalDelivery.deliver(view.target, candidate.captured(), dead, reservation, players, () -> current(view))) {
|
||||
uncertain(view); return;
|
||||
}
|
||||
view.target.updateInventory();
|
||||
} catch (RuntimeException uncertain) {
|
||||
view.fail("native_tail_delivery_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)
|
||||
} catch (RuntimeException failure) { report(failure); uncertain(view); return; }
|
||||
characters.restoreDeathRecord(reservation.character(), reservation.death(),
|
||||
games.dmg.fantasystick.session.NativeHealthLimit.read(), reservation.sheetGeneration())
|
||||
.whenComplete((restored, failure) -> schedule(() -> {
|
||||
if (failure != null || restored.isEmpty()) {
|
||||
view.fail(failure!=null?"character_restore_failed":"character_restore_unavailable");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 (failure != null) report(failure);
|
||||
uncertain(view); return;
|
||||
}
|
||||
if (installFinalSheet(view.target, restored.orElseThrow())) {
|
||||
view.revived(reservation,dead,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.fail("restored_but_sheet_custody_ambiguous");view.target.sendMessage("Character restoration was saved, but sheet custody is ambiguous; retained proof requires recovery.");}
|
||||
view.execution.finish();
|
||||
TailRevivalDelivery.complete(characters, reservations, nextTick, this::report, view.target, reservation, players,
|
||||
() -> current(view), record -> {
|
||||
var carrier = reviveEvents == null ? null : reviveEvents.snapshot(view.target);
|
||||
return () -> {
|
||||
view.revived(reservation, dead, record, carrier);
|
||||
if (current(view)) {
|
||||
view.target.sendMessage("Restored character sheet: " + record.name() + ".");
|
||||
view.execution.input().player().sendMessage("Revive restored " + record.name() + ".");
|
||||
}
|
||||
view.execution.finish();
|
||||
};
|
||||
}, () -> uncertain(view));
|
||||
}));
|
||||
}
|
||||
|
||||
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) -> {
|
||||
@@ -355,36 +356,30 @@ public final class Revive implements AbilityEffect, Listener, AutoCloseable {
|
||||
}
|
||||
|
||||
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)) {
|
||||
recoveryEvent(reservation,record,target);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();
|
||||
(reservation.administrative()
|
||||
? characters.restoreDeathRecordAdministratively(reservation.character(), reservation.death(), nativeLimit)
|
||||
: characters.restoreDeathRecord(reservation.character(), reservation.death(), nativeLimit))
|
||||
.whenComplete((restored, failure) -> schedule(() -> {
|
||||
if (failure != null) { report(failure); return; }
|
||||
if (restored.isPresent() && installFinalSheet(target, restored.orElseThrow())) {
|
||||
recoveryEvent(reservation,restored.orElseThrow(),target);reservations.clear(reservation.character(), reservation.id());
|
||||
}
|
||||
}));
|
||||
if (!TailRevivalDelivery.currentRecipient(target, players) || !TailRevivalDelivery.matchesRecord(record, reservation)) return;
|
||||
if (reservation.phase() == RevivalStore.DeliveryPhase.RESERVED) {
|
||||
if (record.dead() && TailRevivalDelivery.provablyUnperformed(target, reservation))
|
||||
reservations.cancelReserved(reservation).exceptionally(error -> { report(error); return false; });
|
||||
return;
|
||||
}
|
||||
if (reservation.phase() != RevivalStore.DeliveryPhase.DELIVERY_STARTED
|
||||
|| TailRevivalDelivery.uniqueProofSlot(target, reservation) < 0
|
||||
|| !TailRevivalDelivery.consumedTail(target, reservation)) return;
|
||||
if (!record.dead()) { completeRecovery(target, reservation); return; }
|
||||
var nativeLimit = games.dmg.fantasystick.session.NativeHealthLimit.read();
|
||||
(reservation.administrative()
|
||||
? characters.restoreDeathRecordAdministratively(reservation.character(), reservation.death(), nativeLimit, reservation.sheetGeneration())
|
||||
: characters.restoreDeathRecord(reservation.character(), reservation.death(), nativeLimit, reservation.sheetGeneration()))
|
||||
.whenComplete((restored, failure) -> schedule(() -> {
|
||||
if (failure != null) { report(failure); return; }
|
||||
if (restored.isPresent()) completeRecovery(target, reservation);
|
||||
}));
|
||||
}
|
||||
|
||||
private void completeRecovery(Player target, RevivalStore.Reservation reservation) {
|
||||
TailRevivalDelivery.complete(characters, reservations, nextTick, this::report, target, reservation, players,
|
||||
() -> !closed && TailRevivalDelivery.currentRecipient(target, players),
|
||||
record -> recoveryAcknowledgment(reservation, record, target), () -> {});
|
||||
}
|
||||
|
||||
private void schedule(Runnable action) {
|
||||
@@ -394,7 +389,7 @@ public final class Revive implements AbilityEffect, Listener, AutoCloseable {
|
||||
|
||||
@Override public void close() {
|
||||
if (closed) return; closed = true;
|
||||
for (var view : List.copyOf(inventories.values())) view.execution.finish();
|
||||
for (var view : List.copyOf(targets.values())) view.execution.finish();
|
||||
inventories.clear(); targets.clear();
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,12 @@ public final class AdminRevivalEventBridge implements AutoCloseable {
|
||||
EventInput.Location targetLocation,
|
||||
games.dmg.fantasystick.session.EquipmentSessions.Active targetSession) { }
|
||||
|
||||
public record Target(String name, EventInput.Location location,
|
||||
games.dmg.fantasystick.session.EquipmentSessions.Active session) { }
|
||||
public Target snapshot(Player target) {
|
||||
return new Target(target.getName(), safeLocation(target), sessions.active(target.getUniqueId()).orElse(null));
|
||||
}
|
||||
|
||||
private final Function<EventInput, CompletionStage<LocalEventLog.Delivery>> sink;
|
||||
private final FeatureEventOutbox outbox;
|
||||
private final Clock clock;
|
||||
@@ -63,9 +69,14 @@ public final class AdminRevivalEventBridge implements AutoCloseable {
|
||||
|
||||
public void revived(Selection selection, RevivalStore.Reservation reservation,
|
||||
CharacterRecord dead, CharacterRecord restored, Player target) {
|
||||
revived(selection, reservation, dead, restored, target.getName());
|
||||
}
|
||||
|
||||
public void revived(Selection selection, RevivalStore.Reservation reservation,
|
||||
CharacterRecord dead, CharacterRecord restored, String targetName) {
|
||||
if (selection == null || selection.actor() == null) return;
|
||||
try {
|
||||
var data = revivalData(reservation, restored, target);
|
||||
var data = revivalData(reservation, restored, targetName);
|
||||
data.put("revision_before", dead.revision().toString());
|
||||
data.put("death_time", dead.diedAt().toString());
|
||||
data.put("death_age_seconds", Long.toString(Math.max(0, Duration.between(dead.diedAt(), clock.instant()).getSeconds())));
|
||||
@@ -82,9 +93,13 @@ public final class AdminRevivalEventBridge implements AutoCloseable {
|
||||
|
||||
/** Reconciliation has the reservation's exact admin UUID, but never invents its old location or name. */
|
||||
public void recovered(RevivalStore.Reservation reservation, CharacterRecord restored, Player target) {
|
||||
recovered(reservation, restored, snapshot(target));
|
||||
}
|
||||
|
||||
public void recovered(RevivalStore.Reservation reservation, CharacterRecord restored, Target target) {
|
||||
if (!reservation.administrative()) return;
|
||||
try {
|
||||
var data = revivalData(reservation, restored, target);
|
||||
var data = revivalData(reservation, restored, target.name());
|
||||
data.put("actor_kind", "system");
|
||||
data.put("admin_player_id", reservation.casterCharacter().toString());
|
||||
data.put("admin_name_status", "unavailable");
|
||||
@@ -94,18 +109,18 @@ public final class AdminRevivalEventBridge implements AutoCloseable {
|
||||
data.put("death_age_seconds", Long.toString(Math.max(0,
|
||||
Duration.between(restored.diedAt(), reservation.createdAt()).getSeconds())));
|
||||
data.put("recovery_reconciliation", true);
|
||||
location(data, "target_location", safeLocation(target));
|
||||
targetSession(data, sessions.active(target.getUniqueId()).orElse(null));
|
||||
location(data, "target_location", target.location());
|
||||
targetSession(data, target.session());
|
||||
durable("character.revived", reservation.id(), null, data);
|
||||
} catch (RuntimeException ignored) { }
|
||||
}
|
||||
|
||||
private Map<String, Object> revivalData(RevivalStore.Reservation reservation, CharacterRecord restored, Player target) {
|
||||
private Map<String, Object> revivalData(RevivalStore.Reservation reservation, CharacterRecord restored, String targetName) {
|
||||
var data = new LinkedHashMap<String, Object>();
|
||||
data.put("revival_kind", "admin_tail");
|
||||
data.put("revival_operation_id", reservation.id().toString());
|
||||
data.put("target_player_id", reservation.targetPlayer().toString());
|
||||
data.put("target_player_name", target.getName());
|
||||
data.put("target_player_name", targetName);
|
||||
data.put("character_id", restored.id().toString());
|
||||
data.put("character_name", restored.name());
|
||||
data.put("death_id", reservation.death().toString());
|
||||
|
||||
@@ -21,15 +21,23 @@ public final class ReviveEventBridge {
|
||||
Instant castAt,Instant cooldownUntil,double range){
|
||||
public Cast{Objects.requireNonNull(actionId);Objects.requireNonNull(caster);Objects.requireNonNull(casterCharacter);Objects.requireNonNull(casterCharacterName);Objects.requireNonNull(targetPlayer);Objects.requireNonNull(targetPlayerName);Objects.requireNonNull(targetLocation);Objects.requireNonNull(castAt);Objects.requireNonNull(cooldownUntil);}
|
||||
}
|
||||
public record Carrier(UUID id, String name, EventInput.Location location, Map<String,Object> locationData) { }
|
||||
public Carrier snapshot(Player carrier) {
|
||||
var location = carrier.getLocation();
|
||||
return new Carrier(carrier.getUniqueId(), carrier.getName(), location(location),
|
||||
locationData(location, clock.instant()));
|
||||
}
|
||||
private final Consumer<EventInput> sink;private final Clock clock;
|
||||
public ReviveEventBridge(Consumer<EventInput> sink,Clock clock){this.sink=Objects.requireNonNull(sink);this.clock=Objects.requireNonNull(clock);}
|
||||
public Cast cast(AbilityExecution execution,Player target){var input=execution.input();var caster=execution.character();var now=clock.instant();var action=new Cast(UUID.randomUUID(),context(input.player(),input.session(),caster.name()),caster.id(),caster.name(),target.getUniqueId(),target.getName(),locationData(target.getLocation(),now),now,caster.cooldowns().get("revive"),input.player().getLocation().distance(target.getLocation()));emitAbility("ability.cast",action,"accepted","cooldown_committed",null);return action;}
|
||||
public void resolved(Cast cast,String outcome,String stage){emitAbility("ability.resolved",cast,outcome,stage,null);}
|
||||
public void failed(Cast cast,String reason){emitAbility("ability.resolved",cast,"failed","tail_restoration",reason);}
|
||||
public void revived(Cast cast,RevivalStore.Reservation reservation,CharacterRecord dead,CharacterRecord restored,Player carrier){revived(cast,reservation,dead,restored,carrier,false);}
|
||||
public void recovered(RevivalStore.Reservation reservation,CharacterRecord restored,Player carrier){if(reservation.administrative())return;revived(null,reservation,null,restored,carrier,true);}
|
||||
public void revived(Cast cast,RevivalStore.Reservation reservation,CharacterRecord dead,CharacterRecord restored,Player carrier){revived(cast,reservation,dead,restored,snapshot(carrier),false);}
|
||||
public void revived(Cast cast,RevivalStore.Reservation reservation,CharacterRecord dead,CharacterRecord restored,Carrier carrier){revived(cast,reservation,dead,restored,carrier,false);}
|
||||
public void recovered(RevivalStore.Reservation reservation,CharacterRecord restored,Player carrier){recovered(reservation,restored,snapshot(carrier));}
|
||||
public void recovered(RevivalStore.Reservation reservation,CharacterRecord restored,Carrier carrier){if(reservation.administrative())return;revived(null,reservation,null,restored,carrier,true);}
|
||||
|
||||
private void revived(Cast cast,RevivalStore.Reservation reservation,CharacterRecord dead,CharacterRecord restored,Player carrier,boolean recovery){var data=new LinkedHashMap<String,Object>();data.put("revival_kind","learned_tail");data.put("selected_branch","tail");data.put("reservation_id",reservation.id().toString());data.put("death_id",reservation.death().toString());data.put("tail_id",reservation.death().toString());data.put("caster_character_id",reservation.casterCharacter().toString());if(cast!=null){data.put("caster_player_id",cast.caster().playerId().toString());data.put("caster_player_name",cast.caster().playerName());data.put("cast_action_id",cast.actionId().toString());}data.put("carrier_player_id",carrier.getUniqueId().toString());data.put("carrier_player_name",carrier.getName());data.put("source_slot",reservation.sourceSlot());data.put("destination_slot",reservation.sourceAmount()==1?reservation.sourceSlot():reservation.destinationSlot());data.put("source_quantity_before",Integer.toString(reservation.sourceAmount()));data.put("source_quantity_after",Integer.toString(reservation.sourceAmount()-1));data.put("consumed_quantity","1");data.put("restored_character_id",restored.id().toString());data.put("restored_character_name",restored.name());data.put("restored_revision",restored.revision().toString());data.put("restored_health",restored.health().toPlainString());data.put("maximum_health",restored.maximumHealth().toPlainString());data.put("no_auto_entry",true);data.put("recovery_reconciliation",recovery);data.put("outcome","acknowledged");data.put("carrier_location",locationData(carrier.getLocation(),clock.instant()));var context=new EventInput.Context(carrier.getUniqueId(),carrier.getName(),null,null,null,location(carrier.getLocation()));emit(id(reservation.id(),"character-revived"),reservation.id(),reservation.createdAt(),"character.revived",context,data);if(cast!=null)emitAbility("ability.resolved",cast,"restored","tail_restoration_acknowledged",null,Map.of("reservation_id",reservation.id().toString(),"death_id",reservation.death().toString(),"restored_character_id",restored.id().toString()));}
|
||||
private void revived(Cast cast,RevivalStore.Reservation reservation,CharacterRecord dead,CharacterRecord restored,Carrier carrier,boolean recovery){var data=new LinkedHashMap<String,Object>();data.put("revival_kind","learned_tail");data.put("selected_branch","tail");data.put("reservation_id",reservation.id().toString());data.put("death_id",reservation.death().toString());data.put("tail_id",reservation.death().toString());data.put("caster_character_id",reservation.casterCharacter().toString());if(cast!=null){data.put("caster_player_id",cast.caster().playerId().toString());data.put("caster_player_name",cast.caster().playerName());data.put("cast_action_id",cast.actionId().toString());}data.put("carrier_player_id",carrier.id().toString());data.put("carrier_player_name",carrier.name());data.put("source_slot",reservation.sourceSlot());data.put("destination_slot",reservation.sourceAmount()==1?reservation.sourceSlot():reservation.destinationSlot());data.put("source_quantity_before",Integer.toString(reservation.sourceAmount()));data.put("source_quantity_after",Integer.toString(reservation.sourceAmount()-1));data.put("consumed_quantity","1");data.put("restored_character_id",restored.id().toString());data.put("restored_character_name",restored.name());data.put("restored_revision",restored.revision().toString());data.put("restored_health",restored.health().toPlainString());data.put("maximum_health",restored.maximumHealth().toPlainString());data.put("no_auto_entry",true);data.put("recovery_reconciliation",recovery);data.put("outcome","acknowledged");data.put("carrier_location",carrier.locationData());var context=new EventInput.Context(carrier.id(),carrier.name(),null,null,null,carrier.location());emit(id(reservation.id(),"character-revived"),reservation.id(),reservation.createdAt(),"character.revived",context,data);if(cast!=null)emitAbility("ability.resolved",cast,"restored","tail_restoration_acknowledged",null,Map.of("reservation_id",reservation.id().toString(),"death_id",reservation.death().toString(),"restored_character_id",restored.id().toString()));}
|
||||
private void emitAbility(String type,Cast cast,String outcome,String stage,String reason){emitAbility(type,cast,outcome,stage,reason,Map.of());}
|
||||
private void emitAbility(String type,Cast cast,String outcome,String stage,String reason,Map<String,Object> extra){var data=new LinkedHashMap<String,Object>();data.put("ability_id","revive");data.put("selected_branch","tail");data.put("stage",stage);data.put("outcome",outcome);data.put("cooldown_until",cast.cooldownUntil());data.put("caster_character_id",cast.casterCharacter().toString());data.put("target_player_id",cast.targetPlayer().toString());data.put("target_player_name",cast.targetPlayerName());data.put("target_location",cast.targetLocation());data.put("final_range",Double.toString(cast.range()));data.put("line_of_sight",true);if(reason!=null)data.put("reason",reason);data.putAll(extra);emit(id(cast.actionId(),type),cast.actionId(),cast.castAt(),type,cast.caster(),data);}
|
||||
private EventInput.Context context(Player player,games.dmg.fantasystick.session.EquipmentSessions.Active active,String name){return new EventInput.Context(player.getUniqueId(),player.getName(),active.character(),name,active.session(),location(player.getLocation()));}
|
||||
|
||||
@@ -19,6 +19,7 @@ public final class CharacterSheets {
|
||||
private static final NamespacedKey VERSION = new NamespacedKey("fantasystick", "sheet_version");
|
||||
private static final NamespacedKey CHARACTER = new NamespacedKey("fantasystick", "character_id");
|
||||
private static final NamespacedKey GENERATION = new NamespacedKey("fantasystick", "sheet_generation");
|
||||
private static final NamespacedKey REVIVAL = new NamespacedKey("fantasystick", "tail_revival_operation");
|
||||
private static final NamespacedKey RECOVERY = new NamespacedKey("fantasystick", "boss_recovery_operation");
|
||||
private static final List<Component> INSTRUCTION = List.of(Component.text("Character sheet:"),
|
||||
Component.text("Place in off hand"), Component.text("to enter fantasy world."));
|
||||
@@ -58,6 +59,25 @@ public final class CharacterSheets {
|
||||
public boolean hasRecovery(ItemStack item,UUID operation){if(identify(item).isEmpty())return false;return operation.toString().equals(item.getItemMeta().getPersistentDataContainer().get(RECOVERY,PersistentDataType.STRING));}
|
||||
public void clearRecovery(ItemStack item){if(item==null||!item.hasItemMeta())return;var meta=item.getItemMeta();meta.getPersistentDataContainer().remove(RECOVERY);item.setItemMeta(meta);}
|
||||
|
||||
public void markRevival(ItemStack item, UUID operation) {
|
||||
if (identity(item).filter(value -> !value.legacy()).isEmpty())
|
||||
throw new IllegalArgumentException("Not an explicitly generated character sheet");
|
||||
var meta = item.getItemMeta();
|
||||
meta.getPersistentDataContainer().set(REVIVAL, PersistentDataType.STRING, operation.toString());
|
||||
item.setItemMeta(meta);
|
||||
}
|
||||
|
||||
public boolean hasRevival(ItemStack item, UUID operation) {
|
||||
return identify(item).isPresent() && operation.toString().equals(
|
||||
item.getItemMeta().getPersistentDataContainer().get(REVIVAL, PersistentDataType.STRING));
|
||||
}
|
||||
|
||||
public void clearRevival(ItemStack item) {
|
||||
if (item == null || !item.hasItemMeta()) return;
|
||||
var meta = item.getItemMeta();
|
||||
meta.getPersistentDataContainer().remove(REVIVAL); item.setItemMeta(meta);
|
||||
}
|
||||
|
||||
/** Adds only the cosmetic model association to an already authentic sheet. */
|
||||
public boolean applyModel(ItemStack item) {
|
||||
if (identify(item).isEmpty()) return false;
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
package games.dmg.fantasystick.items;
|
||||
|
||||
import games.dmg.fantasystick.persistence.CharacterRecord;
|
||||
import games.dmg.fantasystick.persistence.CharacterStorage;
|
||||
import games.dmg.fantasystick.persistence.RevivalStore;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.function.Consumer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
/** Feature-scoped native custody proof shared by the existing learned and admin Tail routes. */
|
||||
public final class TailRevivalDelivery {
|
||||
private static final CharacterSheets SHEETS = new CharacterSheets();
|
||||
private static final TailBooks TAILS = new TailBooks();
|
||||
private TailRevivalDelivery() { }
|
||||
|
||||
public static boolean currentRecipient(Player target, java.util.function.Function<java.util.UUID, Player> players) {
|
||||
return target.isOnline() && players.apply(target.getUniqueId()) == target;
|
||||
}
|
||||
|
||||
public static boolean destinationAvailable(Player target, RevivalStore.Reservation reservation) {
|
||||
if (reservation.sourceAmount() == 1) return reservation.destinationSlot() == -1;
|
||||
var item = target.getInventory().getItem(reservation.destinationSlot());
|
||||
return item == null || item.isEmpty();
|
||||
}
|
||||
|
||||
public static boolean matchesRecord(CharacterRecord record, RevivalStore.Reservation reservation) {
|
||||
return reservation.sheetGeneration() != null && record.id().equals(reservation.character())
|
||||
&& record.sheetGeneration().equals(reservation.sheetGeneration())
|
||||
&& reservation.death().equals(record.deathId());
|
||||
}
|
||||
|
||||
public static ItemStack provisional(CharacterRecord dead, RevivalStore.Reservation reservation) {
|
||||
if (!dead.dead() || !matchesRecord(dead, reservation)
|
||||
|| reservation.phase() != RevivalStore.DeliveryPhase.DELIVERY_STARTED)
|
||||
throw new IllegalArgumentException("Unbound Tail revival");
|
||||
var living = new CharacterRecord(dead.id(), dead.name(), dead.revision(), dead.stats(), dead.level(),
|
||||
dead.experience(), dead.unspentPoints(), dead.maximumHealth(), dead.learned(), dead.loadout(),
|
||||
dead.passives(), dead.cooldowns(), dead.restrictedKills(), false, dead.deathId(), dead.diedAt(),
|
||||
// Death-only escrow remains in the saved dead record until restore commits; a living
|
||||
// reference projection must satisfy the same zero-escrow invariant as saved restoration.
|
||||
dead.coins(), dead.coinsInitialized(), dead.rewardReceipts(), java.math.BigInteger.ZERO, dead.gear(),
|
||||
dead.sheetGeneration());
|
||||
var sheet = SHEETS.create(living); SHEETS.markRevival(sheet, reservation.id()); return sheet;
|
||||
}
|
||||
|
||||
public static boolean proves(ItemStack item, RevivalStore.Reservation reservation) {
|
||||
return reservation.phase() == RevivalStore.DeliveryPhase.DELIVERY_STARTED
|
||||
&& SHEETS.identity(item).filter(value -> !value.legacy()
|
||||
&& value.character().equals(reservation.character())
|
||||
&& value.generation().equals(reservation.sheetGeneration())).isPresent()
|
||||
&& SHEETS.hasRevival(item, reservation.id());
|
||||
}
|
||||
|
||||
/** Count marked units, not UUID references. Revoked/unrelated same-character sheets stay untouched. */
|
||||
public static int uniqueProofSlot(Player target, RevivalStore.Reservation reservation) {
|
||||
int found = -1;
|
||||
for (int slot = 0; slot <= 40; slot++) {
|
||||
if (slot > 35 && slot != 40) continue;
|
||||
var item = target.getInventory().getItem(slot);
|
||||
if (!proves(item, reservation)) continue;
|
||||
if (found >= 0 || item.getAmount() != 1) return -2;
|
||||
found = slot;
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
public static boolean unchangedTail(Player target, RevivalStore.Reservation reservation) {
|
||||
var source = target.getInventory().getItem(reservation.sourceSlot());
|
||||
return source != null && source.getAmount() == reservation.sourceAmount() && matchingTail(source, reservation);
|
||||
}
|
||||
|
||||
public static boolean consumedTail(Player target, RevivalStore.Reservation reservation) {
|
||||
var source = target.getInventory().getItem(reservation.sourceSlot());
|
||||
if (reservation.sourceAmount() == 1) return !matchingTail(source, reservation);
|
||||
return source != null && source.getAmount() == reservation.sourceAmount() - 1 && matchingTail(source, reservation);
|
||||
}
|
||||
|
||||
private static boolean matchingTail(ItemStack item, RevivalStore.Reservation reservation) {
|
||||
return TAILS.identify(item).filter(value -> value.characterId().equals(reservation.character())
|
||||
&& value.deathId().equals(reservation.death())).isPresent();
|
||||
}
|
||||
|
||||
/** A RESERVED journal proves no writes began; item absence alone never proves non-delivery. */
|
||||
public static boolean provablyUnperformed(Player target, RevivalStore.Reservation reservation) {
|
||||
if (reservation.phase() != RevivalStore.DeliveryPhase.RESERVED || !unchangedTail(target, reservation)) return false;
|
||||
for (int slot = 0; slot <= 40; slot++) {
|
||||
if (slot > 35 && slot != 40) continue;
|
||||
if (SHEETS.hasRevival(target.getInventory().getItem(slot), reservation.id())) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** All native access runs on the caller's server thread, including reentrant setter postconditions. */
|
||||
public static boolean deliver(Player target, ItemStack captured, CharacterRecord dead,
|
||||
RevivalStore.Reservation reservation, java.util.function.Function<java.util.UUID, Player> players, BooleanSupplier current) {
|
||||
if (!current.getAsBoolean() || !currentRecipient(target, players)
|
||||
|| !captured.equals(target.getInventory().getItem(reservation.sourceSlot()))
|
||||
|| !destinationAvailable(target, reservation)) return false;
|
||||
var sheet = provisional(dead, reservation);
|
||||
if (reservation.sourceAmount() == 1) target.getInventory().setItem(reservation.sourceSlot(), sheet);
|
||||
else {
|
||||
target.getInventory().setItem(reservation.destinationSlot(), sheet);
|
||||
// A setter may reenter plugin/native code. Never overwrite a changed source after it returns.
|
||||
if (!current.getAsBoolean() || !currentRecipient(target, players)
|
||||
|| !captured.equals(target.getInventory().getItem(reservation.sourceSlot()))
|
||||
|| !sheet.equals(target.getInventory().getItem(reservation.destinationSlot()))) return false;
|
||||
var remaining = captured.clone(); remaining.setAmount(reservation.sourceAmount() - 1);
|
||||
target.getInventory().setItem(reservation.sourceSlot(), remaining);
|
||||
}
|
||||
target.updateInventory();
|
||||
return current.getAsBoolean() && currentRecipient(target, players) && consumedTail(target, reservation)
|
||||
&& uniqueProofSlot(target, reservation) >= 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reload both durable authorities before acknowledgment. The provisional reference already is the
|
||||
* current-generation sheet: finalization does not mint/upgrade/replace another item. Only the
|
||||
* conditional-clear winner may report success. The issued marker remains harmless final provenance.
|
||||
* Later ordinary inventory movement is not an atomic part of the saved completion acknowledgment.
|
||||
*/
|
||||
public static void complete(CharacterStorage characters, RevivalStore reservations, Consumer<Runnable> nextTick,
|
||||
Consumer<Throwable> failures, Player target, RevivalStore.Reservation reservation, java.util.function.Function<java.util.UUID, Player> players,
|
||||
BooleanSupplier current, java.util.function.Function<CharacterRecord, Runnable> acknowledgment, Runnable uncertain) {
|
||||
reservations.find(reservation.character()).whenComplete((saved, saveFailure) -> {
|
||||
if (saveFailure != null || saved.isEmpty() || !saved.orElseThrow().equals(reservation)) {
|
||||
schedule(nextTick, failures, () -> { if (saveFailure != null) failures.accept(saveFailure); uncertain.run(); });
|
||||
return;
|
||||
}
|
||||
characters.find(reservation.character()).whenComplete((found, loadFailure) -> schedule(nextTick, failures, () -> {
|
||||
if (loadFailure != null) { failures.accept(loadFailure); uncertain.run(); return; }
|
||||
if (!current.getAsBoolean() || !currentRecipient(target, players) || found.isEmpty()) { uncertain.run(); return; }
|
||||
var record = found.orElseThrow();
|
||||
int slot = uniqueProofSlot(target, reservation);
|
||||
if (record.dead() || !matchesRecord(record, reservation) || slot < 0
|
||||
|| !consumedTail(target, reservation)
|
||||
|| !SHEETS.authorizes(target.getInventory().getItem(slot), record)) { uncertain.run(); return; }
|
||||
final Runnable acknowledged;
|
||||
try { acknowledged = java.util.Objects.requireNonNull(acknowledgment.apply(record)); }
|
||||
catch (RuntimeException captureFailure) { failures.accept(captureFailure); uncertain.run(); return; }
|
||||
reservations.clear(reservation).whenComplete((cleared, clearFailure) ->
|
||||
schedule(nextTick, failures, () -> {
|
||||
if (clearFailure != null) { failures.accept(clearFailure); uncertain.run(); return; }
|
||||
// Successful clearance commits already proved historical completion. Later quit/expiry
|
||||
// cannot turn it into unresolved custody after deleting its proof. Feedback is gated
|
||||
// by each route; audit facts were captured above, while the native context was valid.
|
||||
if (Boolean.TRUE.equals(cleared)) acknowledged.run();
|
||||
else uncertain.run();
|
||||
}));
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
private static void schedule(Consumer<Runnable> nextTick, Consumer<Throwable> failures, Runnable action) {
|
||||
try { nextTick.accept(action); } catch (RuntimeException rejected) { failures.accept(rejected); }
|
||||
}
|
||||
}
|
||||
@@ -1017,17 +1017,27 @@ public final class CharacterStorage implements AutoCloseable {
|
||||
/** 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) {
|
||||
return restore(characterId, deathId, nativeLimit, true);
|
||||
return restore(characterId, deathId, nativeLimit, true, null);
|
||||
}
|
||||
|
||||
/** Administrator revival retains death identity/consume-once checks but deliberately ignores death age. */
|
||||
public CompletableFuture<Optional<CharacterRecord>> restoreDeathRecordAdministratively(
|
||||
UUID characterId, UUID deathId, java.math.BigDecimal nativeLimit) {
|
||||
return restore(characterId, deathId, nativeLimit, false);
|
||||
return restore(characterId, deathId, nativeLimit, false, null);
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<CharacterRecord>> restoreDeathRecord(UUID characterId, UUID deathId,
|
||||
java.math.BigDecimal nativeLimit, BigInteger expectedGeneration) {
|
||||
return restore(characterId, deathId, nativeLimit, true, Objects.requireNonNull(expectedGeneration));
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<CharacterRecord>> restoreDeathRecordAdministratively(UUID characterId,
|
||||
UUID deathId, java.math.BigDecimal nativeLimit, BigInteger expectedGeneration) {
|
||||
return restore(characterId, deathId, nativeLimit, false, Objects.requireNonNull(expectedGeneration));
|
||||
}
|
||||
|
||||
private CompletableFuture<Optional<CharacterRecord>> restore(UUID characterId, UUID deathId,
|
||||
java.math.BigDecimal nativeLimit, boolean ageLimited) {
|
||||
java.math.BigDecimal nativeLimit, boolean ageLimited, BigInteger expectedGeneration) {
|
||||
Objects.requireNonNull(characterId); Objects.requireNonNull(deathId);
|
||||
if (nativeLimit != null && nativeLimit.signum() <= 0) throw new IllegalArgumentException("Invalid revival health limit");
|
||||
Instant selectedAt = clock.instant();
|
||||
@@ -1037,6 +1047,7 @@ public final class CharacterStorage implements AutoCloseable {
|
||||
CharacterRecord old = found.orElseThrow();
|
||||
Duration age = Duration.between(old.diedAt(), selectedAt);
|
||||
if (!deathId.equals(old.deathId()) || age.isNegative()
|
||||
|| expectedGeneration != null && !expectedGeneration.equals(old.sheetGeneration())
|
||||
|| ageLimited && 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(),
|
||||
|
||||
@@ -33,8 +33,30 @@ public final class RevivalStore implements AutoCloseable {
|
||||
"target-player-id", "character-id", "death-id", "created-at", "source-slot", "source-amount", "destination-slot");
|
||||
private static final Set<String> KEYS_V2 = java.util.stream.Stream.concat(KEYS_V1.stream(), java.util.stream.Stream.of("administrative"))
|
||||
.collect(java.util.stream.Collectors.toUnmodifiableSet());
|
||||
private static final Set<String> KEYS_V3 = java.util.stream.Stream.concat(KEYS_V2.stream(),
|
||||
java.util.stream.Stream.of("sheet-generation", "delivery-phase"))
|
||||
.collect(java.util.stream.Collectors.toUnmodifiableSet());
|
||||
public enum DeliveryPhase { LEGACY, RESERVED, DELIVERY_STARTED }
|
||||
public record Reservation(UUID id, UUID casterCharacter, UUID targetPlayer, UUID character, UUID death,
|
||||
Instant createdAt, int sourceSlot, int sourceAmount, int destinationSlot, boolean administrative) {
|
||||
Instant createdAt, int sourceSlot, int sourceAmount, int destinationSlot,
|
||||
boolean administrative, java.math.BigInteger sheetGeneration, DeliveryPhase phase) {
|
||||
/** Old reservations deliberately carry no inferred generation or delivery authority. */
|
||||
public Reservation(UUID id, UUID casterCharacter, UUID targetPlayer, UUID character, UUID death,
|
||||
Instant createdAt, int sourceSlot, int sourceAmount, int destinationSlot, boolean administrative) {
|
||||
this(id, casterCharacter, targetPlayer, character, death, createdAt, sourceSlot, sourceAmount,
|
||||
destinationSlot, administrative, null, DeliveryPhase.LEGACY);
|
||||
}
|
||||
public Reservation(UUID id, UUID casterCharacter, UUID targetPlayer, UUID character, UUID death,
|
||||
Instant createdAt, int sourceSlot, int sourceAmount, int destinationSlot,
|
||||
boolean administrative, java.math.BigInteger sheetGeneration) {
|
||||
this(id, casterCharacter, targetPlayer, character, death, createdAt, sourceSlot, sourceAmount,
|
||||
destinationSlot, administrative, Objects.requireNonNull(sheetGeneration), DeliveryPhase.RESERVED);
|
||||
}
|
||||
public Reservation deliveryStarted() {
|
||||
if (phase != DeliveryPhase.RESERVED) throw new IllegalStateException("Delivery is not reserved");
|
||||
return new Reservation(id, casterCharacter, targetPlayer, character, death, createdAt, sourceSlot,
|
||||
sourceAmount, destinationSlot, administrative, sheetGeneration, DeliveryPhase.DELIVERY_STARTED);
|
||||
}
|
||||
public Reservation(UUID id, UUID casterCharacter, UUID targetPlayer, UUID character, UUID death,
|
||||
Instant createdAt, int sourceSlot, int sourceAmount, int destinationSlot) {
|
||||
this(id, casterCharacter, targetPlayer, character, death, createdAt, sourceSlot, sourceAmount, destinationSlot, false);
|
||||
@@ -42,6 +64,11 @@ public final class RevivalStore implements AutoCloseable {
|
||||
public Reservation {
|
||||
Objects.requireNonNull(id); Objects.requireNonNull(casterCharacter); Objects.requireNonNull(targetPlayer);
|
||||
Objects.requireNonNull(character); Objects.requireNonNull(death); Objects.requireNonNull(createdAt);
|
||||
Objects.requireNonNull(phase);
|
||||
if ((sheetGeneration == null) != (phase == DeliveryPhase.LEGACY)
|
||||
|| sheetGeneration != null && (sheetGeneration.signum() < 0
|
||||
|| (sourceAmount == 1 ? destinationSlot != -1 : destinationSlot < 0)))
|
||||
throw new IllegalArgumentException("Invalid revival authority");
|
||||
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) {
|
||||
@@ -74,6 +101,25 @@ public final class RevivalStore implements AutoCloseable {
|
||||
});
|
||||
}
|
||||
|
||||
/** Durable attempted-delivery fence precedes every native write; stale/legacy work cannot begin. */
|
||||
public CompletableFuture<Optional<Reservation>> beginDelivery(Reservation expected) {
|
||||
Objects.requireNonNull(expected);
|
||||
return submit(() -> {
|
||||
var found = load(file(expected.character()));
|
||||
if (expected.phase() != DeliveryPhase.RESERVED || found.isEmpty()
|
||||
|| !found.orElseThrow().equals(expected)) return Optional.empty();
|
||||
var started = expected.deliveryStarted();
|
||||
Path temporary = directory.resolve("." + expected.character() + "." + UUID.randomUUID() + ".tmp");
|
||||
try {
|
||||
Files.writeString(temporary, encode(started), StandardCharsets.UTF_8,
|
||||
StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
|
||||
Files.move(temporary, file(expected.character()), StandardCopyOption.ATOMIC_MOVE,
|
||||
StandardCopyOption.REPLACE_EXISTING);
|
||||
} finally { Files.deleteIfExists(temporary); }
|
||||
return Optional.of(started);
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<Reservation>> find(UUID character) {
|
||||
Objects.requireNonNull(character);
|
||||
return submit(() -> load(file(character)));
|
||||
@@ -99,6 +145,23 @@ public final class RevivalStore implements AutoCloseable {
|
||||
});
|
||||
}
|
||||
|
||||
/** A stale RESERVED callback cannot retire a later attempted-delivery phase of the same operation. */
|
||||
public CompletableFuture<Boolean> cancelReserved(Reservation expected) {
|
||||
Objects.requireNonNull(expected);
|
||||
if (expected.phase() != DeliveryPhase.RESERVED) return CompletableFuture.completedFuture(false);
|
||||
return clear(expected);
|
||||
}
|
||||
|
||||
/** Completion/cancellation must match the full captured authority, not merely an operation UUID. */
|
||||
public CompletableFuture<Boolean> clear(Reservation expected) {
|
||||
Objects.requireNonNull(expected);
|
||||
return submit(() -> {
|
||||
var found = load(file(expected.character()));
|
||||
if (found.isEmpty() || !found.orElseThrow().equals(expected)) return false;
|
||||
return Files.deleteIfExists(file(expected.character()));
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> clear(UUID character, UUID reservation) {
|
||||
Objects.requireNonNull(character); Objects.requireNonNull(reservation);
|
||||
return submit(() -> {
|
||||
@@ -127,13 +190,15 @@ public final class RevivalStore implements AutoCloseable {
|
||||
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_V1) || raw.keySet().equals(KEYS_V2))) throw new IOException("Invalid revival reservation keys");
|
||||
if (!(decoded instanceof Map<?, ?> raw) || !(raw.keySet().equals(KEYS_V1) || raw.keySet().equals(KEYS_V2) || raw.keySet().equals(KEYS_V3))) throw new IOException("Invalid revival reservation keys");
|
||||
try {
|
||||
String schema=text(raw,"schema-version");if(!(schema.equals("1")&&raw.keySet().equals(KEYS_V1)||schema.equals("2")&&raw.keySet().equals(KEYS_V2)))throw new IllegalArgumentException("schema");
|
||||
String schema=text(raw,"schema-version");if(!(schema.equals("1")&&raw.keySet().equals(KEYS_V1)||schema.equals("2")&&raw.keySet().equals(KEYS_V2)||schema.equals("3")&&raw.keySet().equals(KEYS_V3)))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"), schema.equals("2") && bool(raw,"administrative"));
|
||||
integer(raw, "destination-slot"), !schema.equals("1") && bool(raw,"administrative"),
|
||||
schema.equals("3") ? new java.math.BigInteger(text(raw,"sheet-generation")) : null,
|
||||
schema.equals("3") ? DeliveryPhase.valueOf(text(raw,"delivery-phase")) : DeliveryPhase.LEGACY);
|
||||
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); }
|
||||
@@ -141,12 +206,16 @@ public final class RevivalStore implements AutoCloseable {
|
||||
|
||||
private static String encode(Reservation value) {
|
||||
var map = new LinkedHashMap<String, Object>();
|
||||
map.put("schema-version", "2"); map.put("reservation-id", value.id().toString());
|
||||
map.put("schema-version", value.phase() == DeliveryPhase.LEGACY ? "2" : "3"); 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()));
|
||||
map.put("administrative", Boolean.toString(value.administrative()));
|
||||
if (value.phase() != DeliveryPhase.LEGACY) {
|
||||
map.put("sheet-generation", value.sheetGeneration().toString());
|
||||
map.put("delivery-phase", value.phase().name());
|
||||
}
|
||||
return new Yaml().dump(map);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package games.dmg.fantasystick.session;
|
||||
|
||||
import games.dmg.fantasystick.events.AdminActionEventBridge;
|
||||
import games.dmg.fantasystick.items.CharacterSheets;
|
||||
import games.dmg.fantasystick.items.TailBooks;
|
||||
import games.dmg.fantasystick.items.TailRevivalDelivery;
|
||||
import games.dmg.fantasystick.persistence.CharacterRecord;
|
||||
import games.dmg.fantasystick.persistence.CharacterStorage;
|
||||
import games.dmg.fantasystick.persistence.RevivalStore;
|
||||
@@ -35,8 +35,11 @@ public final class AdminRevival implements Listener, AutoCloseable {
|
||||
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 Scheduler scheduler; 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> views=new IdentityHashMap<>();private boolean closed;
|
||||
private final Consumer<Throwable> failures; private final TailBooks tails=new TailBooks();
|
||||
private final java.util.function.Function<UUID,Player> players;
|
||||
private final Map<Inventory,View> views=new IdentityHashMap<>();
|
||||
private final java.util.Set<View> activeViews=java.util.Collections.newSetFromMap(new IdentityHashMap<>());
|
||||
private boolean closed;
|
||||
private games.dmg.fantasystick.events.AdminRevivalEventBridge auditEvents;
|
||||
private AdminActionEventBridge adminAudit;
|
||||
|
||||
@@ -58,29 +61,65 @@ public final class AdminRevival implements Listener, AutoCloseable {
|
||||
private final class View implements AutoCloseable {
|
||||
final Player admin,target;final Inventory inventory;final Map<Integer,Choice> choices;final Instant deadline;final AutoCloseable expiry;final AdminActionEventBridge.Action action;boolean selecting,finished;
|
||||
View(Player admin,Player target,Inventory inventory,Map<Integer,Choice> choices,Instant deadline,AdminActionEventBridge.Action action){this.admin=admin;this.target=target;this.inventory=inventory;this.choices=choices;this.deadline=deadline;this.action=action;this.expiry=scheduler.later(Duration.between(clock.instant(),deadline),this::close);}
|
||||
boolean current(){return !closed&&!finished&&admin.isOnline()&&admin.hasPermission(EquipmentAdminCommand.PERMISSION)&&target.isOnline()&&clock.instant().isBefore(deadline);}
|
||||
@Override public void close(){if(finished)return;finished=true;views.remove(inventory,this);inventory.clear();try{expiry.close();}catch(Exception e){report(e);}try{admin.closeInventory();}catch(RuntimeException e){report(e);}}
|
||||
boolean current(){return !closed&&!finished&&TailRevivalDelivery.currentRecipient(admin,players)&&admin.hasPermission(EquipmentAdminCommand.PERMISSION)&&TailRevivalDelivery.currentRecipient(target,players)&&clock.instant().isBefore(deadline);}
|
||||
@Override public void close(){if(finished)return;finished=true;views.remove(inventory,this);activeViews.remove(this);inventory.clear();try{expiry.close();}catch(Exception e){report(e);}try{if(!selecting)admin.closeInventory();}catch(RuntimeException e){report(e);}}
|
||||
}
|
||||
|
||||
public AdminRevival(CharacterStorage characters,RevivalStore reservations,Clock clock,Consumer<Runnable> nextTick,Scheduler scheduler,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.scheduler=Objects.requireNonNull(scheduler);this.popups=Objects.requireNonNull(popups);this.failures=Objects.requireNonNull(failures);}
|
||||
public AdminRevival(CharacterStorage characters,RevivalStore reservations,Clock clock,Consumer<Runnable> nextTick,Scheduler scheduler,PopupFactory popups,Consumer<Throwable> failures,java.util.function.Function<UUID,Player> players){this.characters=Objects.requireNonNull(characters);this.reservations=Objects.requireNonNull(reservations);this.clock=Objects.requireNonNull(clock);this.nextTick=Objects.requireNonNull(nextTick);this.scheduler=Objects.requireNonNull(scheduler);this.popups=Objects.requireNonNull(popups);this.failures=Objects.requireNonNull(failures);this.players=Objects.requireNonNull(players);}
|
||||
|
||||
public void open(Player admin,Player target,Duration timeout){Objects.requireNonNull(admin);Objects.requireNonNull(target);if(closed||!admin.isOnline()||!admin.hasPermission(EquipmentAdminCommand.PERMISSION)||!target.isOnline()){admin.sendMessage("Admin revival refused: authorization or target is no longer available.");return;}var candidates=candidates(target);if(candidates.isEmpty()){admin.sendMessage("That player has no authentic direct-inventory Tails.");return;}var action=adminAudit==null?null:adminAudit.current();var loads=candidates.stream().map(c->characters.find(c.identity.characterId())).toList();CompletableFuture.allOf(loads.toArray(CompletableFuture[]::new)).whenComplete((ignored,failure)->schedule(()->{if(failure!=null){report(failure);admin.sendMessage("Admin revival could not inspect those Tails safely.");return;}if(closed||!admin.isOnline()||!admin.hasPermission(EquipmentAdminCommand.PERMISSION)||!target.isOnline())return;var choices=new ArrayList<Choice>();for(int i=0;i<candidates.size();i++){var found=loads.get(i).join();if(found.isPresent()&&eligible(found.orElseThrow(),candidates.get(i).identity)&&unchanged(target,candidates.get(i)))choices.add(new Choice(candidates.get(i),found.orElseThrow()));}if(choices.isEmpty()){admin.sendMessage("That player has no current unconsumed Tail.");return;}show(admin,target,choices,timeout,action);}));}
|
||||
private List<Candidate> candidates(Player target){var result=new ArrayList<Candidate>();for(int slot=0;slot<=40;slot++){if(slot>35&&slot!=40)continue;var 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 id){return record.dead()&&record.id().equals(id.characterId())&&Objects.equals(record.deathId(),id.deathId())&&!record.diedAt().isAfter(clock.instant());}
|
||||
private static boolean unchanged(Player target,Candidate candidate){var item=target.getInventory().getItem(candidate.slot);return item!=null&&item.equals(candidate.item);}
|
||||
private void show(Player admin,Player target,List<Choice> eligible,Duration timeout,AdminActionEventBridge.Action action){int size=Math.min(54,Math.max(9,((eligible.size()+8)/9)*9));var inventory=popups.create(size,Component.text("Choose a Tail for "+target.getName()));var choices=new LinkedHashMap<Integer,Choice>();for(int i=0;i<eligible.size()&&i<size;i++){var choice=eligible.get(i);var item=choice.candidate.item.clone();item.setAmount(1);var meta=item.getItemMeta();meta.lore(List.of(Component.text("Character: "+choice.record.name()),Component.text("Level "+choice.record.level()+" · target slot "+choice.candidate.slot),Component.text("Click to restore this exact death")));item.setItemMeta(meta);inventory.setItem(i,item);choices.put(i,choice);}var view=new View(admin,target,inventory,Map.copyOf(choices),clock.instant().plus(timeout),action);views.put(inventory,view);admin.openInventory(inventory);}
|
||||
private void show(Player admin,Player target,List<Choice> eligible,Duration timeout,AdminActionEventBridge.Action action){int size=Math.min(54,Math.max(9,((eligible.size()+8)/9)*9));var inventory=popups.create(size,Component.text("Choose a Tail for "+target.getName()));var choices=new LinkedHashMap<Integer,Choice>();for(int i=0;i<eligible.size()&&i<size;i++){var choice=eligible.get(i);var item=choice.candidate.item.clone();item.setAmount(1);var meta=item.getItemMeta();meta.lore(List.of(Component.text("Character: "+choice.record.name()),Component.text("Level "+choice.record.level()+" · target slot "+choice.candidate.slot),Component.text("Click to restore this exact death")));item.setItemMeta(meta);inventory.setItem(i,item);choices.put(i,choice);}var view=new View(admin,target,inventory,Map.copyOf(choices),clock.instant().plus(timeout),action);views.put(inventory,view);activeViews.add(view);admin.openInventory(inventory);}
|
||||
|
||||
@EventHandler(priority=EventPriority.HIGHEST) public void click(org.bukkit.event.inventory.InventoryClickEvent event){var view=views.get(event.getView().getTopInventory());if(view==null)return;event.setCancelled(true);if(event.getWhoClicked()!=view.admin||event.getRawSlot()<0||event.getRawSlot()>=view.inventory.getSize())return;var choice=view.choices.get(event.getRawSlot());if(choice==null||view.selecting)return;view.selecting=true;views.remove(view.inventory,view);if(adminAudit!=null)adminAudit.confirmation(view.action,view.admin.isOnline()&&view.admin.hasPermission(EquipmentAdminCommand.PERMISSION),"inventory_confirmation",null);view.inventory.clear();view.admin.closeInventory();confirm(view,choice);}
|
||||
@EventHandler(priority=EventPriority.HIGHEST) public void drag(org.bukkit.event.inventory.InventoryDragEvent event){var view=views.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=views.get(event.getView().getTopInventory());if(view!=null&&!view.selecting)view.close();}
|
||||
@EventHandler(priority=EventPriority.MONITOR) public void quit(org.bukkit.event.player.PlayerQuitEvent event){for(var view:List.copyOf(views.values()))if(view.admin==event.getPlayer()||view.target==event.getPlayer())view.close();}
|
||||
@EventHandler(priority=EventPriority.MONITOR) public void quit(org.bukkit.event.player.PlayerQuitEvent event){for(var view:List.copyOf(activeViews))if(view.admin==event.getPlayer()||view.target==event.getPlayer())view.close();}
|
||||
|
||||
private void confirm(View view,Choice choice){if(!view.current()||!unchanged(view.target,choice.candidate)){outcome(view.action,AdminActionEventBridge.Outcome.REFUSED,"stale",Map.of());view.close();return;}characters.find(choice.record.id()).whenComplete((found,failure)->schedule(()->{if(failure!=null){report(failure);outcome(view.action,AdminActionEventBridge.Outcome.FAILED,"operation_failed",Map.of());view.admin.sendMessage("Admin revival could not recheck that Tail; no item changed.");view.close();return;}if(!view.current()||found.isEmpty()||!eligible(found.orElseThrow(),choice.candidate.identity)||!unchanged(view.target,choice.candidate)){outcome(view.action,AdminActionEventBridge.Outcome.REFUSED,"stale",Map.of());view.admin.sendMessage("That Tail selection is stale; no item changed.");view.close();return;}reserve(view,choice.candidate,found.orElseThrow());}));}
|
||||
private void reserve(View view,Candidate candidate,CharacterRecord dead){var source=view.target.getInventory().getItem(candidate.slot);int destination=source.getAmount()==1?-1:emptySlot(view.target,candidate.slot);if(source.getAmount()>1&&destination<0){outcome(view.action,AdminActionEventBridge.Outcome.REFUSED,"owner_refused",Map.of());view.admin.sendMessage("Admin revival needs one empty direct inventory slot to preserve copied Tails.");view.close();return;}var reservation=new RevivalStore.Reservation(UUID.randomUUID(),view.admin.getUniqueId(),view.target.getUniqueId(),dead.id(),dead.deathId(),clock.instant().truncatedTo(ChronoUnit.SECONDS),candidate.slot,source.getAmount(),destination,true);var audit=auditEvents==null?null:auditEvents.selection(view.admin,view.target);reservations.reserve(reservation).whenComplete((saved,failure)->schedule(()->{if(failure!=null){report(failure);outcome(view.action,AdminActionEventBridge.Outcome.UNCERTAIN,"operation_uncertain",Map.of("domain_operation_id",reservation.id()));view.admin.sendMessage("Admin revival reservation failed; no item changed.");view.close();return;}if(saved.isEmpty()||!view.current()||!unchanged(view.target,candidate)){outcome(view.action,saved.isEmpty()?AdminActionEventBridge.Outcome.REFUSED:AdminActionEventBridge.Outcome.UNCERTAIN,saved.isEmpty()?"stale":"operation_uncertain",saved.isEmpty()?Map.of():Map.of("domain_operation_id",reservation.id()));view.admin.sendMessage("Admin revival became stale after reservation; no item changed.");view.close();return;}deliver(view,dead,reservation,audit);}));}
|
||||
private void reserve(View view,Candidate candidate,CharacterRecord dead){var source=view.target.getInventory().getItem(candidate.slot);int destination=source.getAmount()==1?-1:emptySlot(view.target,candidate.slot);if(source.getAmount()>1&&destination<0){outcome(view.action,AdminActionEventBridge.Outcome.REFUSED,"owner_refused",Map.of());view.admin.sendMessage("Admin revival needs one empty direct inventory slot to preserve copied Tails.");view.close();return;}var reservation=new RevivalStore.Reservation(UUID.randomUUID(),view.admin.getUniqueId(),view.target.getUniqueId(),dead.id(),dead.deathId(),clock.instant().truncatedTo(ChronoUnit.SECONDS),candidate.slot,source.getAmount(),destination,true,dead.sheetGeneration());var audit=auditEvents==null?null:auditEvents.selection(view.admin,view.target);reservations.reserve(reservation).whenComplete((saved,failure)->schedule(()->{if(failure!=null){report(failure);outcome(view.action,AdminActionEventBridge.Outcome.UNCERTAIN,"operation_uncertain",Map.of("domain_operation_id",reservation.id()));view.admin.sendMessage("Admin revival reservation failed; no item changed.");view.close();return;}if(saved.isEmpty()||!view.current()||!unchanged(view.target,candidate)||!games.dmg.fantasystick.items.TailRevivalDelivery.destinationAvailable(view.target,reservation)){if(saved.isPresent())reservations.cancelReserved(reservation).exceptionally(error->{report(error);return false;});outcome(view.action,saved.isEmpty()?AdminActionEventBridge.Outcome.REFUSED:AdminActionEventBridge.Outcome.UNCERTAIN,saved.isEmpty()?"stale":"operation_uncertain",saved.isEmpty()?Map.of():Map.of("domain_operation_id",reservation.id()));view.admin.sendMessage("Admin revival became stale after reservation; no item changed.");view.close();return;}reservations.beginDelivery(reservation).whenComplete((begun,beginFailure)->schedule(()->{if(beginFailure!=null||begun.isEmpty()){if(beginFailure!=null)report(beginFailure);uncertain(view,reservation);return;}deliver(view,candidate,dead,begun.orElseThrow(),audit);}));}));}
|
||||
private static int emptySlot(Player target,int source){for(int slot=0;slot<=40;slot++){if(slot>35&&slot!=40||slot==source)continue;var item=target.getInventory().getItem(slot);if(item==null||item.isEmpty())return slot;}return-1;}
|
||||
private void deliver(View view,CharacterRecord dead,RevivalStore.Reservation reservation,games.dmg.fantasystick.events.AdminRevivalEventBridge.Selection audit){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.passives(),dead.cooldowns(),dead.restrictedKills(),false,dead.deathId(),dead.diedAt(),dead.sheetGeneration());var sheet=sheets.create(provisional);var 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);outcome(view.action,AdminActionEventBridge.Outcome.UNCERTAIN,"operation_uncertain",Map.of("domain_operation_id",reservation.id()));view.admin.sendMessage("Admin revival delivery is uncertain; retained proof requires recovery.");view.close();return;}characters.restoreDeathRecordAdministratively(reservation.character(),reservation.death(),NativeHealthLimit.read()).whenComplete((restored,failure)->schedule(()->{if(failure!=null||restored.isEmpty()){if(failure!=null)report(failure);outcome(view.action,AdminActionEventBridge.Outcome.UNCERTAIN,"operation_uncertain",Map.of("domain_operation_id",reservation.id()));view.admin.sendMessage("The Tail changed, but restoration is pending proof-based recovery.");view.close();return;}boolean installed;try{installed=installFinal(view.target,restored.orElseThrow());}catch(RuntimeException uncertain){report(uncertain);outcome(view.action,AdminActionEventBridge.Outcome.UNCERTAIN,"operation_uncertain",Map.of("domain_operation_id",reservation.id()));view.admin.sendMessage("Character restoration was saved, but sheet custody is ambiguous; retained proof requires recovery.");view.close();return;}if(installed){if(auditEvents!=null)auditEvents.revived(audit,reservation,dead,restored.orElseThrow(),view.target);reservations.clear(reservation.character(),reservation.id()).exceptionally(error->{report(error);return false;});outcome(view.action,AdminActionEventBridge.Outcome.COMPLETED,"acknowledged",Map.of("domain_operation_id",reservation.id(),"subject_id",dead.id(),"target_id",view.target.getUniqueId()));view.admin.sendMessage("Administratively restored "+restored.orElseThrow().name()+" for "+view.target.getName()+".");view.target.sendMessage("An administrator restored character sheet: "+restored.orElseThrow().name()+".");}else{outcome(view.action,AdminActionEventBridge.Outcome.UNCERTAIN,"operation_uncertain",Map.of("domain_operation_id",reservation.id()));view.admin.sendMessage("Character restoration was saved, but sheet custody is ambiguous; retained proof requires recovery.");}view.close();}));}
|
||||
private boolean installFinal(Player target,CharacterRecord record){int found=-1;for(int slot=0;slot<=40;slot++){if(slot>35&&slot!=40)continue;if(sheets.identify(target.getInventory().getItem(slot)).filter(record.id()::equals).isEmpty())continue;if(found>=0)return false;found=slot;}if(found<0)return false;target.getInventory().setItem(found,sheets.create(record));target.updateInventory();return sheets.authorizes(target.getInventory().getItem(found),record);}
|
||||
private void uncertain(View view, RevivalStore.Reservation reservation) {
|
||||
outcome(view.action, AdminActionEventBridge.Outcome.UNCERTAIN, "operation_uncertain",
|
||||
Map.of("domain_operation_id", reservation.id()));
|
||||
view.admin.sendMessage("Admin revival could not acknowledge delivery safely; any pending custody proof is retained.");
|
||||
view.close();
|
||||
}
|
||||
|
||||
private void deliver(View view, Candidate candidate, CharacterRecord dead, RevivalStore.Reservation reservation,
|
||||
games.dmg.fantasystick.events.AdminRevivalEventBridge.Selection audit) {
|
||||
try {
|
||||
if (!TailRevivalDelivery.deliver(view.target, candidate.item, dead, reservation, players, view::current)) {
|
||||
uncertain(view, reservation); return;
|
||||
}
|
||||
} catch (RuntimeException failure) { report(failure); uncertain(view, reservation); return; }
|
||||
characters.restoreDeathRecordAdministratively(reservation.character(), reservation.death(),
|
||||
NativeHealthLimit.read(), reservation.sheetGeneration()).whenComplete((restored, failure) -> schedule(() -> {
|
||||
if (failure != null || restored.isEmpty()) {
|
||||
if (failure != null) report(failure);
|
||||
uncertain(view, reservation); return;
|
||||
}
|
||||
TailRevivalDelivery.complete(characters, reservations, nextTick, this::report, view.target, reservation, players,
|
||||
view::current, record -> {
|
||||
var targetName = view.target.getName();
|
||||
return () -> {
|
||||
if (auditEvents != null) auditEvents.revived(audit, reservation, dead, record, targetName);
|
||||
outcome(view.action, AdminActionEventBridge.Outcome.COMPLETED, "acknowledged",
|
||||
Map.of("domain_operation_id", reservation.id(), "subject_id", dead.id(),
|
||||
"target_id", reservation.targetPlayer()));
|
||||
if (view.current()) {
|
||||
view.admin.sendMessage("Administratively restored " + record.name() + " for " + targetName + ".");
|
||||
view.target.sendMessage("An administrator restored character sheet: " + record.name() + ".");
|
||||
}
|
||||
view.close();
|
||||
};
|
||||
}, () -> uncertain(view, reservation));
|
||||
}));
|
||||
}
|
||||
|
||||
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(views.values()))view.close();views.clear();}
|
||||
@Override public void close(){if(closed)return;closed=true;for(var view:List.copyOf(activeViews))view.close();views.clear();activeViews.clear();}
|
||||
}
|
||||
Reference in new issue
Block a user