feat(sessions): complete native health and fantasy defeat
CI / build (push) Failing after 4m43s
Release / release (push) Failing after 4m45s

This commit is contained in:
dmg committed 2026-09-19 12:37:20 -04:00
1 parent 6f42082383
commit 6ac4c4bfde
21 files changed
+1010 -46

No files matched your search

@@ -101,7 +101,8 @@ class CharacterAnvilNamesNativeTest {
assertEquals("Tail of Mira of Dawn — 雪", book.getTitle());
var text = net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText();
assertTrue(text.serialize(book.customName()).contains("Mira of Dawn — 雪"));
assertTrue(book.pages().stream().map(text::serialize).anyMatch(page -> page.contains("Mira of Dawn — 雪")));
assertTrue(book.pages().stream().map(text::serialize).collect(java.util.stream.Collectors.joining())
.replace("\n", "").contains("Mira of Dawn — 雪"), "Readable wrapping must retain the full acknowledged name");
assertTrue(problems.isEmpty());
// Actor rejects all XP/cursor/inventory mutation calls and all worker-side player access.
}
@@ -111,7 +111,7 @@ class CharacterBookNativeTest {
}
}
@Test void valuesBeyondOneNativeBookRemainCompleteThroughBoundedSingleUseNavigation() throws Exception {
@Test void largeRecordsRemainCompleteThroughBoundedSingleUseNavigation() throws Exception {
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
f.plugin.setEnabled(true);
var a = new FantasyStickLifecycleNativeTest.Actor(data);
@@ -131,7 +131,7 @@ class CharacterBookNativeTest {
while (true) {
var content = org.bukkit.craftbukkit.inventory.CraftItemStack.asNMSCopy(a.books.getLast())
.get(net.minecraft.core.component.DataComponents.WRITTEN_BOOK_CONTENT);
assertNotNull(content); assertTrue(content.pages().size() <= 100, "Never exceed the native book page limit");
assertNotNull(content); assertTrue(content.pages().size() <= 100, "Keep the chosen per-view payload bound (not a signed-book codec page limit)");
for (var page : content.pages()) if (!hasClick(page.raw())) all.append(page.raw().getString().replace("\n", ""));
if (!text(a.books.getLast()).contains("[Next pages]")) break;
assertTrue(++volumes < 10, "Navigation must terminate, not repeat a truncated volume");
@@ -1685,6 +1685,8 @@ class EquipmentSessionsNativeTest {
org.bukkit.GameMode gameMode = org.bukkit.GameMode.SURVIVAL;
Runnable beforeMode = () -> {};
double health = 20;
Runnable beforeHealth = () -> {};
Runnable healthMutation = () -> {};
float attackStrength = 1;
ItemStack activeItem = new ItemStack(Material.AIR);
int useStarts;
@@ -1729,7 +1731,7 @@ class EquipmentSessionsNativeTest {
useStarts++; activeItem = inventory.getItemInMainHand().clone(); startUse.run(); yield null;
}
case "clearActiveItem" -> { useClears++; activeItem = new ItemStack(Material.AIR); clearUse.run(); yield null; }
case "setHealth" -> { health = (Double) args[0]; yield null; }
case "setHealth" -> { beforeHealth.run(); health = (Double) args[0]; healthMutation.run(); yield null; }
case "getAttribute" -> { assertEquals(org.bukkit.attribute.Attribute.MAX_HEALTH, args[0]); yield maximum; }
case "teleport" -> {
teleports++; teleported = ((org.bukkit.Location) args[0]).clone(); teleport.run();
@@ -0,0 +1,384 @@
package games.dmg.fantasystick;
import static org.junit.jupiter.api.Assertions.*;
import games.dmg.fantasystick.persistence.CharacterStorage;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
import org.bukkit.attribute.Attribute;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class FantasyHealthNativeTest {
@TempDir Path data;
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
@Test void nativeMaximumIgnoresBonusesPenaltiesAndHealthBoostWhileTheirOrdinaryOwnershipAndExpiryRemainIntact() throws Exception {
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
f.plugin.setEnabled(true);
var a = new FantasyStickLifecycleNativeTest.Actor(data);
f.players.put(a.core.id, a.player);
var bonus = modifier("bonus", 5, net.minecraft.world.entity.ai.attributes.AttributeModifier.Operation.ADD_VALUE);
var penalty = modifier("penalty", -0.5, net.minecraft.world.entity.ai.attributes.AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL);
a.maximumHealth.addTransientModifier(bonus); a.maximumHealth.addTransientModifier(penalty);
var boost = net.minecraft.world.effect.MobEffects.HEALTH_BOOST.value();
boost.addAttributeModifiers(a.healthAttributes, 1);
a.player.setHealth(12); a.player.setFoodLevel(7); a.player.setSaturation(2); a.player.setExhaustion(3);
f.activate(a);
assertEquals(10, a.maximumHealth.getValue());
a.player.setHealth(6);
a.maximumHealth.setBaseValue(30); // A later legitimate ordinary base change must survive exit.
var later = modifier("later", 4, net.minecraft.world.entity.ai.attributes.AttributeModifier.Operation.ADD_VALUE);
a.maximumHealth.addPermanentModifier(later);
boost.addAttributeModifiers(a.healthAttributes, 2);
assertEquals(10, a.maximumHealth.getValue(), "New native potion modifiers cannot change fantasy maximum");
boost.removeAttributeModifiers(a.healthAttributes);
a.maximumHealth.removeModifier(bonus); a.maximumHealth.removeModifier(penalty);
var zero = modifier("zero", -1, net.minecraft.world.entity.ai.attributes.AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL);
a.maximumHealth.addTransientModifier(zero);
assertEquals(10, a.maximumHealth.getValue(), "Even a zero multiplier cannot bypass the native effective-value lease");
a.maximumHealth.removeModifier(zero);
assertEquals(6, a.player.getHealth());
var serialized = a.maximumHealth.pack();
assertEquals(30, serialized.baseValue()); assertEquals(java.util.List.of(later), serialized.modifiers());
var loaded = new net.minecraft.world.entity.ai.attributes.AttributeInstance(net.minecraft.world.entity.ai.attributes.Attributes.MAX_HEALTH, ignored -> {});
loaded.apply(serialized); assertEquals(34, loaded.getValue(), "Player saves retain ordinary attribute ownership, not the fantasy maximum");
a.player.setFoodLevel(2); a.player.setSaturation(0); a.player.setExhaustion(1);
a.core.inventory.setItemInOffHand(null); f.changed(a);
assertEquals(34, a.maximumHealth.getValue()); assertEquals(12, a.player.getHealth());
assertEquals(java.util.Set.of(later), a.maximumHealth.getModifiers(), "Expired/removed modifiers are not replayed from a snapshot");
assertEquals(7, a.player.getFoodLevel()); assertEquals(2, a.player.getSaturation()); assertEquals(3, a.player.getExhaustion());
assertFalse(a.player.isHealthScaled()); assertEquals(20, a.player.getHealthScale());
}
}
@Test void activeCharacterBookShowsCurrentNativeDamageRatherThanTheLastSavedHealth() throws Exception {
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
f.plugin.setEnabled(true);
var a = new FantasyStickLifecycleNativeTest.Actor(data);
f.players.put(a.core.id, a.player); f.activate(a);
a.player.setHealth(4);
PartyBookNativeTest.open(f, a);
assertTrue(PartyBookNativeTest.text(a).contains("Health: 4/10"));
}
}
@Test void activeBlueMistAndOneRedDefeatBurstUseWorldLocationsAndStopWithTheSession() throws Exception {
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
f.plugin.setEnabled(true);
var a = new FantasyStickLifecycleNativeTest.Actor(data);
var ordinary = new FantasyStickLifecycleNativeTest.Actor(data); ordinary.core.inventory.setItemInOffHand(null);
f.players.put(a.core.id, a.player); f.players.put(ordinary.core.id, ordinary.player);
var entry = a.player.getLocation(); f.activate(a);
f.pulses.forEach(Runnable::run);
assertTrue(dust(a, org.bukkit.Color.BLUE) > 0, "Active fantasy mode must have visible public blue particles");
assertEquals(0, dust(ordinary, org.bukkit.Color.BLUE));
a.core.location.add(20, 0, 20);
var defeatLocation = a.player.getLocation().add(0, 1, 0);
var source = new org.bukkit.craftbukkit.damage.CraftDamageSource(new net.minecraft.world.damagesource.DamageSource(
org.bukkit.craftbukkit.damage.CraftDamageType.bukkitToMinecraftHolder(org.bukkit.damage.DamageType.OUT_OF_WORLD)));
var death = new org.bukkit.event.entity.PlayerDeathEvent(a.player, source, new java.util.ArrayList<>(), 0,
net.kyori.adventure.text.Component.empty(), true);
f.dispatcher.accept(death); assertTrue(death.isCancelled());
PartyBookNativeTest.drain(f);
assertEquals(1, dust(a, org.bukkit.Color.RED));
assertTrue(org.mockito.Mockito.mockingDetails(a.world).getInvocations().stream().anyMatch(call ->
call.getMethod().getName().equals("spawnParticle") && java.util.Arrays.asList(call.getArguments()).contains(defeatLocation)));
assertEquals(entry, a.player.getLocation()); assertEquals(28, a.player.getHealth());
var tail = a.core.inventory.getItemInOffHand().clone();
assertEquals(org.bukkit.Material.WRITTEN_BOOK, tail.getType()); assertEquals(1, tail.getAmount());
long blue = dust(a, org.bukkit.Color.BLUE);
f.pulses.forEach(Runnable::run); f.dispatcher.accept(death);
assertEquals(blue, dust(a, org.bukkit.Color.BLUE)); assertEquals(1, dust(a, org.bukkit.Color.RED));
assertEquals(tail, a.core.inventory.getItemInOffHand());
f.plugin.setEnabled(false); f.awaitWorkers();
f.pulses.forEach(Runnable::run);
assertEquals(blue, dust(a, org.bukkit.Color.BLUE), "Retired timers cannot emit fantasy effects");
}
}
@Test void uncappedConstitutionEntersAtTheNativeCeilingAndPersistsOnlyBoundedRemainingHealth() throws Exception {
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
f.plugin.setEnabled(true);
var a = new FantasyStickLifecycleNativeTest.Actor(data);
f.players.put(a.core.id, a.player);
var old = a.core.record;
var con = java.math.BigInteger.TEN.pow(1000);
var stats = new java.util.EnumMap<games.dmg.fantasystick.progression.Stat, java.math.BigInteger>(games.dmg.fantasystick.progression.Stat.class);
stats.putAll(old.stats()); stats.put(games.dmg.fantasystick.progression.Stat.CON, con);
var saved = new games.dmg.fantasystick.persistence.CharacterRecord(old.id(), old.name(), old.revision().add(java.math.BigInteger.ONE),
stats, old.level(), old.experience(), old.unspentPoints(), new java.math.BigDecimal(con.add(java.math.BigInteger.TEN)),
old.learned(), old.loadout(), old.cooldowns(), false, null, null);
new games.dmg.fantasystick.persistence.YamlCharacterRepository(data).replace(saved, old.revision());
var ceiling = games.dmg.fantasystick.session.NativeHealthLimit.read();
f.activate(a);
assertEquals(ceiling.doubleValue(), a.maximumHealth.getValue()); assertEquals(ceiling.doubleValue(), a.player.getHealth());
a.player.setHealth(3.25);
a.core.inventory.setItemInOffHand(null); f.changed(a);
var characters = (CharacterStorage) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "characters");
var suspended = characters.find(old.id()).get(5, TimeUnit.SECONDS).orElseThrow();
assertEquals(con, suspended.stats().get(games.dmg.fantasystick.progression.Stat.CON));
assertEquals(0, suspended.health().compareTo(new java.math.BigDecimal("3.25")));
assertEquals(ceiling, games.dmg.fantasystick.session.NativeHealthLimit.read(), "Never mutate global attribute limits");
}
}
@Test void serializedInterruptedSessionRecoversOrdinaryVitalsAndRemainingHealthWithoutReplayingExpiredModifiers() throws Exception {
FantasyStickLifecycleNativeTest.Actor a;
byte[] nativeProof, characterFile, receiptFile;
byte[][] items;
net.minecraft.world.entity.ai.attributes.AttributeInstance.Packed ordinaryAttributes;
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
f.plugin.setEnabled(true);
a = new FantasyStickLifecycleNativeTest.Actor(data); f.players.put(a.core.id, a.player);
a.player.setHealth(12); a.player.setFoodLevel(7); a.player.setSaturation(2); a.player.setExhaustion(3);
net.minecraft.world.effect.MobEffects.HEALTH_BOOST.value().addAttributeModifiers(a.healthAttributes, 1);
f.activate(a); a.player.setHealth(4); a.player.setFoodLevel(2);
nativeProof = a.core.pdc.serializeToBytes();
items = java.util.Arrays.stream(a.core.snapshot()).map(item -> item == null ? null : item.serializeAsBytes()).toArray(byte[][]::new);
ordinaryAttributes = a.maximumHealth.pack();
characterFile = java.nio.file.Files.readAllBytes(data.resolve("characters").resolve(a.core.record.id() + ".yml"));
receiptFile = java.nio.file.Files.readAllBytes(data.resolve("sessions").resolve(a.core.id + ".yml"));
}
// Recreate one concrete crash window from native item/PDC/attribute and YAML saves.
// Orderly fixture disposal above is not mistaken for an actual server crash.
java.nio.file.Files.write(data.resolve("characters").resolve(a.core.record.id() + ".yml"), characterFile);
java.nio.file.Files.write(data.resolve("sessions").resolve(a.core.id + ".yml"), receiptFile);
a.core.inventory.setContents(java.util.Arrays.stream(items).map(bytes -> bytes == null ? null : org.bukkit.inventory.ItemStack.deserializeBytes(bytes))
.toArray(org.bukkit.inventory.ItemStack[]::new));
a.core.pdc.readFromBytes(nativeProof, true);
a.maximumHealth.removeModifiers(); a.maximumHealth.apply(ordinaryAttributes);
// Native potion attributes use permanent storage. Exercise the real expiry/removal
// hook after load; plugin recovery must not reintroduce that removed modifier.
net.minecraft.world.effect.MobEffects.HEALTH_BOOST.value().removeAttributeModifiers(a.healthAttributes);
a.core.health = 4; a.food.setFoodLevel(2); a.healthScaled = true; a.healthScale = 10;
a.core.gameMode = org.bukkit.GameMode.ADVENTURE;
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
f.players.put(a.core.id, a.player); f.plugin.setEnabled(true); f.tick();
PartyBookNativeTest.drain(f);
var receipt = f.receipts().find(a.core.id).toCompletableFuture().get(5, TimeUnit.SECONDS).orElseThrow();
assertNull(receipt.pending());
assertEquals(org.bukkit.Material.DIAMOND_SWORD, a.core.inventory.getItem(0).getType());
assertEquals(28, a.maximumHealth.getValue()); assertTrue(a.maximumHealth.getModifiers().isEmpty());
assertEquals(12, a.player.getHealth()); assertEquals(7, a.player.getFoodLevel());
assertEquals(2, a.player.getSaturation()); assertEquals(3, a.player.getExhaustion());
assertFalse(a.player.isHealthScaled()); assertEquals(0, a.core.teleports);
var characters = (CharacterStorage) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "characters");
assertEquals(0, characters.find(a.core.record.id()).get(5, TimeUnit.SECONDS).orElseThrow().health().compareTo(java.math.BigDecimal.valueOf(4)));
// An unrelated later ordinary change cannot be overwritten by a repeated recovery.
a.player.setHealth(5); a.player.setFoodLevel(9);
((games.dmg.fantasystick.session.EquipmentSessions) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "sessions")).recover(a.player);
f.tick(); assertEquals(5, a.player.getHealth()); assertEquals(9, a.player.getFoodLevel());
}
}
@Test void failedEntrySettersAndMissingExitProofNeverLeaveTheNativeMaximumOverridden() throws Exception {
for (int route = 0; route < 6; route++) try (var f = new FantasyStickLifecycleNativeTest.Fixture(data.resolve("failure-" + route))) {
f.plugin.setEnabled(true);
var a = new FantasyStickLifecycleNativeTest.Actor(data.resolve("failure-" + route));
f.players.put(a.core.id, a.player);
Runnable fail = () -> { a.core.beforeHealth = () -> {}; a.core.healthMutation = () -> {}; throw new IllegalStateException("Native health setter failed"); };
if (route == 0) a.core.beforeHealth = fail;
if (route == 1) a.core.healthMutation = fail;
if (route == 5) a.core.sync = () -> {
a.core.sync = () -> {}; a.player.setHealth(3);
throw new IllegalStateException("Activation client synchronization failed after native damage");
};
f.activate(a);
if (route >= 2 && route < 5) {
a.player.setHealth(4); a.player.setFoodLevel(2);
if (route == 2) a.core.pdc.remove(new org.bukkit.NamespacedKey("fantasystick", "vitals_session"));
else if (route == 3) org.mockito.Mockito.doThrow(new IllegalStateException("Native equipment update failed")).when(a.nativePlayer).detectEquipmentUpdates();
else a.core.beforeMutation = () -> { throw new IllegalStateException("Equipment restoration write failed"); };
a.core.inventory.setItemInOffHand(null); f.changed(a);
if (route < 4) {
assertEquals(4, a.player.getHealth(), "Missing/uncertain proof cannot authorize a stale ordinary-health replay");
assertEquals(2, a.player.getFoodLevel());
}
}
var sessions = (games.dmg.fantasystick.session.EquipmentSessions) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "sessions");
assertTrue(sessions.active(a.core.id).isEmpty());
assertEquals(28, a.maximumHealth.getValue(), "Only the owned maximum hook is safe to remove despite an uncertain setter/proof");
assertNotNull(f.receipts().find(a.core.id).toCompletableFuture().get(5, TimeUnit.SECONDS).orElseThrow().pending());
if (route < 2) {
assertEquals(route == 0 ? 20 : 10, a.player.getHealth(), "Do not blindly heal an uncertain native write");
assertFalse(a.player.isHealthScaled()); assertEquals(20, a.player.getHealthScale());
}
if (route >= 4) {
assertEquals(20, a.player.getHealth(), "Proven vitals cleanup is independent of uncertain equipment/client state");
var characters = (CharacterStorage) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "characters");
assertEquals(0, characters.find(a.core.record.id()).get(5, TimeUnit.SECONDS).orElseThrow().health()
.compareTo(java.math.BigDecimal.valueOf(route == 4 ? 4 : 3)));
}
}
}
@Test void failedHealthWriteRestoresOrdinaryGearButRetainsTheReceiptAndCannotResumeStaleHealth() throws Exception {
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
f.plugin.setEnabled(true);
var a = new FantasyStickLifecycleNativeTest.Actor(data); f.players.put(a.core.id, a.player); f.activate(a);
var sheet = a.core.inventory.getItemInOffHand().clone(); a.player.setHealth(4);
var path = data.resolve("characters").resolve(a.core.record.id() + ".yml");
byte[] acknowledged = java.nio.file.Files.readAllBytes(path);
try (var channel = java.nio.channels.FileChannel.open(data.resolve("characters/.records.lock"), java.nio.file.StandardOpenOption.WRITE);
var lock = channel.lock()) {
assertTrue(lock.isValid());
a.core.inventory.setItemInOffHand(null); f.changed(a); PartyBookNativeTest.drain(f);
assertNotNull(f.receipts().find(a.core.id).toCompletableFuture().get(5, TimeUnit.SECONDS).orElseThrow().pending());
assertArrayEquals(acknowledged, java.nio.file.Files.readAllBytes(path));
}
assertEquals(org.bukkit.Material.DIAMOND_SWORD, a.core.inventory.getItem(0).getType());
assertEquals(28, a.maximumHealth.getValue()); assertEquals(20, a.player.getHealth());
a.core.inventory.setItemInOffHand(sheet); f.changed(a); f.tick();
var sessions = (games.dmg.fantasystick.session.EquipmentSessions) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "sessions");
assertTrue(sessions.active(a.core.id).isEmpty(), "An unacknowledged health save cannot become a free heal on reentry");
assertArrayEquals(acknowledged, java.nio.file.Files.readAllBytes(path));
assertTrue(a.messages.stream().anyMatch(message -> message.contains("persistence or recovery is pending")));
}
}
@Test void delayedRecoveryReadCannotRecreateOwnershipAfterTheHealthSaveAndExitAlreadyCompleted() throws Exception {
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
f.plugin.setEnabled(true);
var a = new FantasyStickLifecycleNativeTest.Actor(data); f.players.put(a.core.id, a.player); f.activate(a);
var sheet = a.core.inventory.getItemInOffHand().clone(); a.player.setHealth(4);
var characters = (CharacterStorage) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "characters");
var worker = (java.util.concurrent.ExecutorService) FantasyStickLifecycleNativeTest.Fixture.field(characters, "worker");
var entered = new java.util.concurrent.CountDownLatch(1); var release = new java.util.concurrent.CountDownLatch(1);
var gate = worker.submit(() -> {
entered.countDown();
try { assertTrue(release.await(5, TimeUnit.SECONDS)); }
catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new AssertionError(interrupted); }
});
try {
assertTrue(entered.await(5, TimeUnit.SECONDS));
a.core.inventory.setItemInOffHand(null); f.changed(a);
assertNotNull(f.receipts().find(a.core.id).toCompletableFuture().get(5, TimeUnit.SECONDS).orElseThrow().pending());
var sessions = (games.dmg.fantasystick.session.EquipmentSessions) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "sessions");
sessions.recover(a.player);
var stale = f.tasks.poll(5, TimeUnit.SECONDS); assertNotNull(stale);
release.countDown(); gate.get(5, TimeUnit.SECONDS);
characters.find(a.core.record.id()).get(5, TimeUnit.SECONDS);
assertNull(f.receipts().find(a.core.id).toCompletableFuture().get(5, TimeUnit.SECONDS).orElseThrow().pending());
stale.run();
a.core.inventory.setItemInOffHand(sheet); f.changed(a); f.tick();
assertFalse(a.messages.stream().anyMatch(message -> message.contains("persistence or recovery is pending")),
"A delayed old receipt must not manufacture a new ownership blocker after acknowledged exit");
f.tick(); f.tick(); assertTrue(sessions.active(a.core.id).isPresent()); assertEquals(4, a.player.getHealth());
} finally { release.countDown(); }
}
}
@Test void nativeHealthChangesDuringClientScaleDeliveryAreNotOverwrittenByInitialActivation() throws Exception {
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
f.plugin.setEnabled(true);
var a = new FantasyStickLifecycleNativeTest.Actor(data); f.players.put(a.core.id, a.player);
a.scaleMutation = () -> {
a.scaleMutation = () -> {};
a.player.setHealth(Math.min(a.player.getHealth(), a.maximumHealth.getValue()) - 1);
};
f.activate(a);
assertEquals(9, a.player.getHealth(), "Native damage during a reentrant client update must not be replaced with another full-health initialization");
}
}
@Test void quitAndDisablePersistDamageAndRestoreOnlyOwnedOrdinaryVitalsAndDisplay() throws Exception {
for (boolean quit : new boolean[]{true, false}) try (var f = new FantasyStickLifecycleNativeTest.Fixture(data.resolve("lifecycle-" + quit))) {
f.plugin.setEnabled(true);
var a = new FantasyStickLifecycleNativeTest.Actor(data.resolve("lifecycle-" + quit)); f.players.put(a.core.id, a.player);
a.player.setHealth(12); a.player.setFoodLevel(7); a.player.setSaturation(2); a.player.setExhaustion(3);
f.activate(a); a.player.setHealth(4); a.player.setFoodLevel(1);
a.maximumHealth.setBaseValue(8); // A legitimate later ordinary maximum, below the pre-entry health.
a.player.setHealthScale(44); // A later display owner's value is not ours to undo.
if (quit) {
a.core.online = false;
f.dispatcher.accept(new org.bukkit.event.player.PlayerQuitEvent(a.player, net.kyori.adventure.text.Component.empty()));
PartyBookNativeTest.drain(f);
f.receipts().find(a.core.id).toCompletableFuture().get(5, TimeUnit.SECONDS);
} else { f.plugin.setEnabled(false); f.awaitWorkers(); }
assertEquals(8, a.maximumHealth.getValue()); assertEquals(8, a.player.getHealth());
assertEquals(7, a.player.getFoodLevel()); assertEquals(2, a.player.getSaturation()); assertEquals(3, a.player.getExhaustion());
assertEquals(44, a.player.getHealthScale()); assertTrue(a.player.isHealthScaled());
assertEquals(org.bukkit.Material.DIAMOND_SWORD, a.core.inventory.getItem(0).getType());
var saved = new games.dmg.fantasystick.persistence.YamlCharacterRepository(data.resolve("lifecycle-" + quit)).load(a.core.record.id()).orElseThrow();
assertFalse(saved.dead()); assertEquals(0, saved.health().compareTo(java.math.BigDecimal.valueOf(4))); assertEquals(0, a.core.teleports);
}
}
@Test void aDamagedTransferredCharacterNeverTransfersItsFormerHoldersOrdinaryVitals() throws Exception {
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
f.plugin.setEnabled(true);
var a = new FantasyStickLifecycleNativeTest.Actor(data); var b = new FantasyStickLifecycleNativeTest.Actor(data);
f.players.put(a.core.id, a.player); f.players.put(b.core.id, b.player);
a.player.setHealth(12); a.player.setFoodLevel(7);
b.player.setHealth(19); b.player.setFoodLevel(3);
var sheet = a.core.inventory.getItemInOffHand().clone(); f.activate(a); a.player.setHealth(3);
a.core.inventory.setItemInOffHand(null); f.changed(a); PartyBookNativeTest.drain(f);
f.receipts().find(a.core.id).toCompletableFuture().get(5, TimeUnit.SECONDS);
b.core.inventory.setItemInOffHand(sheet); f.activate(b);
assertEquals(3, b.player.getHealth()); assertEquals(12, a.player.getHealth()); assertEquals(7, a.player.getFoodLevel());
b.player.setHealth(2); b.core.inventory.setItemInOffHand(null); f.changed(b); PartyBookNativeTest.drain(f);
assertEquals(19, b.player.getHealth()); assertEquals(3, b.player.getFoodLevel());
var characters = (CharacterStorage) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "characters");
assertEquals(0, characters.find(a.core.record.id()).get(5, TimeUnit.SECONDS).orElseThrow().health().compareTo(java.math.BigDecimal.valueOf(2)));
assertEquals(b.core.record, characters.find(b.core.record.id()).get(5, TimeUnit.SECONDS).orElseThrow());
}
}
@Test void shuttingDownMaximumHooksContinuesAfterAnOriginalNativeObserverThrows() throws Exception {
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
f.plugin.setEnabled(true);
var throwNow = new java.util.concurrent.atomic.AtomicBoolean();
var attributes = new java.util.ArrayList<net.minecraft.world.entity.ai.attributes.AttributeInstance>();
for (int i = 0; i < 2; i++) {
var a = new FantasyStickLifecycleNativeTest.Actor(data); f.players.put(a.core.id, a.player);
var attribute = new net.minecraft.world.entity.ai.attributes.AttributeInstance(net.minecraft.world.entity.ai.attributes.Attributes.MAX_HEALTH,
ignored -> { if (throwNow.get()) throw new IllegalStateException("Native dirty observer failed during cleanup"); });
attributes.add(attribute);
org.mockito.Mockito.when(a.nativePlayer.getAttribute(net.minecraft.world.entity.ai.attributes.Attributes.MAX_HEALTH)).thenReturn(attribute);
f.activate(a); assertEquals(10, attribute.getValue());
}
throwNow.set(true);
var vitals = (games.dmg.fantasystick.session.SessionVitals) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "vitals");
var failure = assertThrows(IllegalStateException.class, vitals::close);
assertEquals(2, failure.getSuppressed().length);
for (var attribute : attributes) assertEquals(20, attribute.getValue(), "Every player's hook must be retired despite another cleanup failure");
}
}
private static long dust(FantasyStickLifecycleNativeTest.Actor a, org.bukkit.Color color) {
return org.mockito.Mockito.mockingDetails(a.world).getInvocations().stream().filter(call ->
call.getMethod().getName().equals("spawnParticle") && java.util.Arrays.stream(call.getArguments())
.anyMatch(argument -> argument instanceof org.bukkit.Particle.DustOptions dust && dust.getColor().equals(color))).count();
}
private static net.minecraft.world.entity.ai.attributes.AttributeModifier modifier(String name, double amount,
net.minecraft.world.entity.ai.attributes.AttributeModifier.Operation operation) {
return new net.minecraft.world.entity.ai.attributes.AttributeModifier(net.minecraft.resources.Identifier.fromNamespaceAndPath("test", name), amount, operation);
}
@Test void actualOffhandEntryAppliesFantasyHealthAndExitRestoresOrdinaryHealthWithoutHealingTheCharacter() throws Exception {
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
f.plugin.setEnabled(true);
var a = new FantasyStickLifecycleNativeTest.Actor(data);
f.players.put(a.core.id, a.player);
double ordinaryHealth = a.player.getHealth();
double ordinaryMaximum = a.player.getAttribute(Attribute.MAX_HEALTH).getValue();
var sheet = a.core.inventory.getItemInOffHand().clone();
f.activate(a);
assertEquals(10, a.player.getAttribute(Attribute.MAX_HEALTH).getValue());
assertEquals(10, a.player.getHealth(), "A fresh character starts full, independently of ordinary health");
a.player.setHealth(4);
a.core.inventory.setItemInOffHand(null); f.changed(a);
assertEquals(ordinaryMaximum, a.player.getAttribute(Attribute.MAX_HEALTH).getValue());
assertEquals(ordinaryHealth, a.player.getHealth());
var characters = (CharacterStorage) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "characters");
var saved = characters.find(a.core.record.id()).get(5, TimeUnit.SECONDS).orElseThrow();
assertEquals(0, saved.health().compareTo(java.math.BigDecimal.valueOf(4)));
f.receipts().find(a.core.id).toCompletableFuture().get(5, TimeUnit.SECONDS);
a.core.inventory.setItemInOffHand(sheet); f.activate(a);
assertEquals(4, a.player.getHealth(), "Resuming does not replay a first-activation heal");
}
}
}
@@ -60,7 +60,7 @@ class FantasyStickLifecycleNativeTest {
assertTrue(fixture.order.indexOf("CharacterChatNames") >= 0);
assertTrue(fixture.order.indexOf("CharacterChatNames") < recipe);
assertNotNull(fixture.packetListener);
assertEquals(2, fixture.timers.size(), "Presentation and bounded combat-provenance cleanup");
assertEquals(3, fixture.timers.size(), "Presentation, combat-provenance cleanup and session particles");
assertTrue(fixture.order.indexOf("PartyCombat") >= 0);
assertTrue(fixture.order.indexOf("PartyCombat") < recipe);
assertNotNull(fixture.command);
@@ -874,6 +874,14 @@ class FantasyStickLifecycleNativeTest {
var oldSessions = (games.dmg.fantasystick.session.EquipmentSessions) Fixture.field(f.plugin, "sessions");
var worker = (java.util.concurrent.ExecutorService) Fixture.field(oldCharacters, "worker");
var receiptWorker = (java.util.concurrent.ExecutorService) Fixture.field(f.receipts(), "worker");
// Finish owned health/receipt durability before deliberately overlapping ONLY a
// rename with a new plugin lifetime. A pending health save now correctly retains
// the character claim; it is not safe authority to start a replacement session.
var transferredSheet = a.core.inventory.getItemInOffHand().clone();
a.core.inventory.setItemInOffHand(null); f.changed(a);
oldCharacters.find(a.core.record.id()).get(5, java.util.concurrent.TimeUnit.SECONDS);
f.receipts().find(a.core.id).toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS);
a.core.inventory.setItemInOffHand(transferredSheet);
var entered = new java.util.concurrent.CountDownLatch(1); var release = new java.util.concurrent.CountDownLatch(1);
var gate = worker.submit(() -> {
entered.countDown();
@@ -1178,6 +1186,14 @@ class FantasyStickLifecycleNativeTest {
final List<String> messages = new ArrayList<>();
final List<org.bukkit.inventory.ItemStack> books = new ArrayList<>();
final List<Integer> particles = new ArrayList<>();
final net.minecraft.world.entity.ai.attributes.AttributeMap healthAttributes = new net.minecraft.world.entity.ai.attributes.AttributeMap(
net.minecraft.world.entity.ai.attributes.AttributeSupplier.builder().add(net.minecraft.world.entity.ai.attributes.Attributes.MAX_HEALTH).build());
final net.minecraft.world.entity.ai.attributes.AttributeInstance maximumHealth = java.util.Objects.requireNonNull(
healthAttributes.getInstance(net.minecraft.world.entity.ai.attributes.Attributes.MAX_HEALTH));
final net.minecraft.world.food.FoodData food = new net.minecraft.world.food.FoodData();
boolean healthScaled;
double healthScale = 20;
Runnable scaleMutation = () -> {};
java.util.function.Consumer<org.bukkit.event.player.PlayerGameModeChangeEvent> modeEvents = ignored -> { };
final org.bukkit.craftbukkit.entity.CraftPlayer player;
final net.minecraft.server.level.ServerPlayer nativePlayer = mock(net.minecraft.server.level.ServerPlayer.class);
@@ -1205,6 +1221,21 @@ class FantasyStickLifecycleNativeTest {
case "getHeight" -> 1.8;
case "getTrackedBy" -> tracked;
case "canSee" -> true;
case "getAttribute" -> {
assertEquals(org.bukkit.attribute.Attribute.MAX_HEALTH, args[0]);
yield new org.bukkit.craftbukkit.attribute.CraftAttributeInstance(maximumHealth, org.bukkit.attribute.Attribute.MAX_HEALTH);
}
case "getMaxHealth" -> maximumHealth.getValue();
case "getFoodLevel" -> food.getFoodLevel();
case "setFoodLevel" -> { food.setFoodLevel((Integer) args[0]); yield null; }
case "getSaturation" -> food.getSaturationLevel();
case "setSaturation" -> { food.setSaturation((Float) args[0]); yield null; }
case "getExhaustion" -> food.exhaustionLevel;
case "setExhaustion" -> { food.exhaustionLevel = (Float) args[0]; yield null; }
case "isHealthScaled" -> healthScaled;
case "getHealthScale" -> healthScale;
case "setHealthScale" -> { healthScale = (Double) args[0]; healthScaled = true; scaleMutation.run(); yield null; }
case "setHealthScaled" -> { healthScaled = (Boolean) args[0]; yield null; }
case "getGameMode" -> core.gameMode;
case "setGameMode" -> {
var event = new org.bukkit.event.player.PlayerGameModeChangeEvent((org.bukkit.entity.Player) call.getMock(), (org.bukkit.GameMode) args[0]);
@@ -1224,6 +1255,9 @@ class FantasyStickLifecycleNativeTest {
when(nativePlayer.getId()).thenReturn(42);
when(nativePlayer.getUUID()).thenReturn(core.id);
when(nativePlayer.getTabListDisplayName()).thenReturn(net.minecraft.network.chat.Component.literal("Ordinary tab"));
maximumHealth.setBaseValue(core.normalMaximum);
when(nativePlayer.getAttributes()).thenReturn(healthAttributes);
when(nativePlayer.getAttribute(net.minecraft.world.entity.ai.attributes.Attributes.MAX_HEALTH)).thenReturn(maximumHealth);
distance.setBaseValue(64);
when(nativePlayer.getAttribute(net.minecraft.world.entity.ai.attributes.Attributes.NAME_TAG_DISTANCE)).thenReturn(distance);
var level = mock(net.minecraft.server.level.ServerLevel.class);
@@ -0,0 +1,57 @@
package games.dmg.fantasystick;
import static org.junit.jupiter.api.Assertions.*;
import games.dmg.fantasystick.session.NativeMaximumHealth;
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
import net.minecraft.world.entity.ai.attributes.Attributes;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class NativeMaximumHealthNativeTest {
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
@Test void startupProbeExercisesPinnedInternalsWithoutChangingTheGlobalRangeOrOrdinaryInstances() {
var maximum = games.dmg.fantasystick.session.NativeHealthLimit.read();
var ordinary = new AttributeInstance(Attributes.MAX_HEALTH, ignored -> {});
double before = ordinary.getValue();
NativeMaximumHealth.prepare();
assertEquals(maximum, games.dmg.fantasystick.session.NativeHealthLimit.read());
assertEquals(before, ordinary.getValue()); assertTrue(ordinary.getModifiers().isEmpty());
}
@Test void nativePlayerHealthClampingAndClientAttributeSnapshotsUseTheLeasedMaximum() {
var attributes = new net.minecraft.world.entity.ai.attributes.AttributeMap(
net.minecraft.world.entity.ai.attributes.AttributeSupplier.builder().add(Attributes.MAX_HEALTH).build());
var maximum = java.util.Objects.requireNonNull(attributes.getInstance(Attributes.MAX_HEALTH));
var player = org.mockito.Mockito.mock(org.bukkit.craftbukkit.entity.CraftPlayer.class, org.mockito.Mockito.CALLS_REAL_METHODS);
var nativePlayer = org.mockito.Mockito.mock(net.minecraft.server.level.ServerPlayer.class, org.mockito.Mockito.CALLS_REAL_METHODS);
org.mockito.Mockito.doReturn(attributes).when(nativePlayer).getAttributes();
org.mockito.Mockito.doReturn(player).when(nativePlayer).getBukkitEntity();
org.mockito.Mockito.doReturn(nativePlayer).when(player).getHandle();
// Network/entity-data delivery is the boundary; run the actual native health methods.
org.mockito.Mockito.doNothing().when(player).updateScaledHealth();
org.mockito.Mockito.doNothing().when(player).updateScaledHealth(org.mockito.ArgumentMatchers.anyBoolean());
try (var lease = new NativeMaximumHealth(maximum, 10)) {
assertNotNull(lease);
player.setHealthScale(10);
nativePlayer.setHealth(100);
assertEquals(10, nativePlayer.getMaxHealth()); assertEquals(10, nativePlayer.getHealth());
nativePlayer.setHealth(6.25f); assertEquals(6.25, player.getHealth());
var packet = new net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket(42, java.util.List.of(player.getScaledMaxHealth()));
assertEquals(10, packet.getValues().getFirst().base()); assertTrue(packet.getValues().getFirst().modifiers().isEmpty());
assertEquals(20, maximum.getBaseValue(), "Ordinary attribute data is not replaced by the client presentation snapshot");
}
assertEquals(20, nativePlayer.getMaxHealth());
assertEquals(6.25, nativePlayer.getHealth(), "Removing the maximum lease does not itself heal");
}
@Test void failingOriginalNativeDirtyCallbackCannotLeaveAnUnownedMaximumOverride() {
var attribute = new AttributeInstance(Attributes.MAX_HEALTH, ignored -> { throw new IllegalStateException("Native observer failed"); });
assertEquals(20, attribute.getValue());
assertThrows(IllegalStateException.class, () -> new NativeMaximumHealth(attribute, 10));
assertEquals(20, attribute.getValue(), "Failed construction must not leave an unreachable effective-value lease");
assertThrows(IllegalStateException.class, () -> attribute.setBaseValue(24));
assertEquals(24, attribute.getValue(), "Subsequent legitimate native writes must not call a leaked lease");
}
}
@@ -390,8 +390,8 @@ class PartyCombatNativeTest {
static void exit(FantasyStickLifecycleNativeTest.Fixture f, FantasyStickLifecycleNativeTest.Actor a) throws Exception {
a.core.inventory.setItemInOffHand(null); f.changed(a);
PartyBookNativeTest.drain(f); // Health acknowledgment precedes clearing the equipment receipt.
f.receipts().find(a.core.id).toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS);
PartyBookNativeTest.drain(f);
}
private FantasyStickLifecycleNativeTest.Actor actor(FantasyStickLifecycleNativeTest.Fixture f) throws Exception {
@@ -54,7 +54,34 @@ class TailBooksNativeTest {
assertTrue(meta.getTitle().length() <= 32);
assertFalse(Character.isHighSurrogate(meta.getTitle().charAt(meta.getTitle().length() - 1)));
assertEquals(Component.text("Tail of " + name), meta.displayName());
assertTrue(meta.pages().contains(Component.text("Tail of " + name)));
String text = meta.pages().stream().map(net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText()::serialize)
.collect(java.util.stream.Collectors.joining()).replace("\n", "");
assertTrue(text.contains("Tail of " + name), "Readable wrapping must retain every character of the full name");
}
@Test void giantStatsRemainReadableInOneSignedKeepsakeThroughTheActualNativeCodec() {
var old = fallen();
var stats = new EnumMap<Stat, BigInteger>(Stat.class); stats.putAll(old.stats());
String digits = "1234567890".repeat(4000);
stats.put(Stat.STR, new BigInteger(digits));
var saved = new CharacterRecord(old.id(), "雪🐈".repeat(80), old.revision(), stats, old.level(), old.experience(),
old.unspentPoints(), old.health(), old.learned(), old.loadout(), old.cooldowns(), true, old.deathId(), old.diedAt());
var book = new TailBooks().create(saved);
var ops = RegistryOps.create(NbtOps.INSTANCE, CraftRegistry.getMinecraftRegistry());
var encoded = net.minecraft.world.item.ItemStack.CODEC.encodeStart(ops, CraftItemStack.asNMSCopy(book)).getOrThrow();
var decoded = net.minecraft.world.item.ItemStack.CODEC.parse(ops, encoded).getOrThrow();
var content = decoded.get(DataComponents.WRITTEN_BOOK_CONTENT); assertNotNull(content);
assertTrue(content.pages().size() > 100, "Signed books are not subject to the writable-book 100-page cap");
var text = new StringBuilder();
for (var page : content.pages()) {
String value = page.raw().getString();
assertTrue(value.split("\\n", -1).length <= 13);
for (String line : value.split("\\n", -1)) assertTrue(line.codePoints().map(cp -> cp < 128 ? 6 : 9).sum() <= 108);
text.append(value.replace("\n", ""));
}
assertTrue(text.toString().contains(saved.name())); assertTrue(text.toString().contains(digits));
assertEquals(1, book.getAmount());
assertEquals(new TailBooks.Identity(saved.id(), saved.deathId()), new TailBooks().identify(CraftItemStack.asBukkitCopy(decoded)).orElseThrow());
}
@Test