Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b493cfe192 | ||
|
|
3d045ff99b |
No files matched your search
@@ -1,14 +1,15 @@
|
||||
# Fantasy Stick
|
||||
|
||||
**Equipment packing/restoration (US-002) is complete with automated verification. The full RPG remains in development and is not deployment-ready.**
|
||||
**Transferable characters and standalone names (US-001), equipment restoration (US-002), and switch delay (US-023) have automated implementation coverage. The full RPG remains in development and is not deployment-ready.**
|
||||
|
||||
Fantasy Stick is the proposed transferable-character RPG plugin for Social Minecraft. Its approved design uses Paper character sheets, native equipment storage and a book/basic-stick/seven-ability hotbar. Crafting and equipment-only offhand sessions are assembled; fantasy health/nutrition, display identity, book UI, combat progression and spells remain incomplete. The server-independent progression core now tests initial stats/points, stat purchases, CON's equal maximum/current-health gain, capped XP and `MAX` presentation. YAML persistence, backend death/revival transitions and a native signed-book factory are also present. Saved-sheet crafting is wired; anvil-name persistence now observes native accepted takes; fantasy health, display and spell interactions remain incomplete.
|
||||
Fantasy Stick is the proposed transferable-character RPG plugin for Social Minecraft. Its approved design uses Paper character sheets, native equipment storage and a book/basic-stick/seven-ability hotbar. Crafting and equipment-only offhand sessions are assembled; fantasy health/nutrition, book UI, combat progression and spells remain incomplete. The server-independent progression core now tests initial stats/points, stat purchases, CON's equal maximum/current-health gain, capped XP and `MAX` presentation. YAML persistence, backend death/revival transitions and a native signed-book factory are also present. Saved-sheet crafting is wired; anvil-name persistence now observes native accepted takes; fantasy health and spell interactions remain incomplete.
|
||||
|
||||
## Build and verify
|
||||
|
||||
- Java 25 toolchain (Gradle can resolve it), Gradle wrapper 9.6.1.
|
||||
- Purpur API/runtime `26.2.build.2618-stable`; `plugin.yml` declares API `26.2`.
|
||||
- Node.js 20 or later and npm for the TypeScript release-tool tests.
|
||||
- ProtocolLib **5.4.0** is required at runtime and declared as a compile-only dependency; it is not bundled.
|
||||
|
||||
```sh
|
||||
./gradlew clean check jar
|
||||
@@ -99,7 +100,7 @@ Nine native lifecycle tests load the actual packaged entrypoint through a test c
|
||||
|
||||
Vanilla retains responsibility for item movement, XP charging and anvil damage. The inspected event fires at the start of native accepted-take processing, before that continuation; the observer does not make native completion contingent on YAML acknowledgment. Failure/crash may leave item presentation ahead of the saved name. The original saved progress is retained and captured IDs are logged; there is no automatic item/XP rollback, reissue or guaranteed retry.
|
||||
|
||||
Six backend tests, seven native observer tests and an added packaged-entrypoint registration test cover preservation, sequencing, failures, shutdown, preview/take separation, name fallbacks and later serialized sheet/Tail rendering. Native XP/damage execution and live clients are not exercised by these fixtures. Active overhead/chat/tab presentation and fantasy sessions remain incomplete. This slice passes 176 tests, clean/incremental packaging, three additional native-suite repeats, audit and static analysis. A controller test's leftover retry was explicitly drained before fixture reuse (12 focused stress runs pass); production shutdown remains nonblocking. Remote publication is tracked separately.
|
||||
Six backend tests, seven native observer tests and an added packaged-entrypoint registration test cover preservation, sequencing, failures, shutdown, preview/take separation, name fallbacks and later serialized sheet/Tail rendering. Native XP/damage execution and live clients are not exercised by these fixtures. Active overhead/chat/tab presentation now refreshes after acknowledged saves, including renaming a copied reference held by someone else; stale session/revision callbacks cannot rename a replacement holder. This slice passes 176 tests, clean/incremental packaging, three additional native-suite repeats, audit and static analysis. A controller test's leftover retry was explicitly drained before fixture reuse (12 focused stress runs pass); production shutdown remains nonblocking. Remote publication is tracked separately.
|
||||
|
||||
## Native health ceiling (activation still unwired)
|
||||
|
||||
@@ -121,7 +122,7 @@ Six unit tests cover exclusion, transfer/switch release, stale callbacks, invali
|
||||
|
||||
Version-1 box metadata uses `fantasystick:storage_version`, `storage_owner_id`, `storage_session_id` and `storage_slots`. Box positions 0–8 contain original hotbar slots 0–8; positions 9–12 contain boots, leggings, chest and head from player slots 36–39. These metadata fields are for identity/restoration, not the only copy of the items. Restoration searches main slots 9–35, so sorting relocation does not lose the box. Repeated requests, wrong identity, duplicate/malformed boxes, unexpected extra contents or occupied restoration slots do not overwrite/delete items. These are adapter error results, not a persistent administrator lock or completed recovery policy.
|
||||
|
||||
The coordinator supplies authenticated control ownership to the adapter, which validates all destinations before replacing controls. One new head stack uses the slot freed by removing the box, even with a full main inventory; there is no drop fallback. The equipment coordinator/event bridge now routes sheet/cursor events, emits entry warnings and registers equipment-only sessions. Fantasy-health, nutrition and display snapshots remain separate unfinished features. Native tests use real player-slot storage with only the absent network recipient stubbed; client packets and live gameplay remain unverified.
|
||||
The coordinator supplies authenticated control ownership to the adapter, which validates all destinations before replacing controls. One new head stack uses the slot freed by removing the box, even with a full main inventory; there is no drop fallback. The equipment coordinator/event bridge now routes sheet/cursor events, emits entry warnings and registers equipment-only sessions. Fantasy-health and nutrition overrides remain separate unfinished features; standalone display projection is implemented below. Native tests use real player-slot storage with only the absent network recipient stubbed; client packets and live gameplay remain unverified.
|
||||
|
||||
## Equipment sessions and safe box movement
|
||||
|
||||
@@ -140,6 +141,18 @@ Administration (permission `fantasystick.admin`, default operators):
|
||||
|
||||
Tests use actual native items, inventories, serialization, Paper event dispatch and menu-close behavior, with explicit scheduler/player/world ports. Drag continuation ordering includes a model based on pinned bytecode. The packaged lifecycle fixture isolates the entrypoint but delegates helpers parent-first. Live clients, production PluginClassLoader execution and arbitrary-plugin/crash atomicity are not claimed verified. No deployment or existing-data migration is authorized by story completion.
|
||||
|
||||
## Standalone character presentation
|
||||
|
||||
Saved character identity/progress transfers between holders; ordinary equipment, vitals, return location and switch deadline do not. Native reference/session tests cover live/dead/invalid/copied identities, concurrent exclusion, orderly switches and legitimate backend revival. The complete Revive spell remains unfinished.
|
||||
|
||||
ProtocolLib-backed presentation shows the full literal saved name above the player, in chat and in the player list, without changing the server account name/UUID/profile, scoreboard membership, ordinary display/list fields or authoritative name-tag-distance attribute. A detached client-only TextDisplay replaces the native overhead label; display-name-only player-info packets and the chat renderer's sender-name argument cover the other surfaces. No signed message-body or recipient rewrite is introduced.
|
||||
|
||||
Output resources belong to a player connection/session, not the sheet. Exit/defeat/lifecycle cleanup withdraws them independently of successful gear restoration, using current ordinary server state rather than replaying stale fantasy names. Renames refresh only after authoritative file acknowledgment; future sessions also reload saved names. Reconnect/restart discards client-only labels, not ordinary identity data.
|
||||
|
||||
**Cross-plugin display compatibility is unsupported**, as explicitly requested. There is no Stealth/Leaf/Ignis bridge or nickname/concealment guarantee. Native/platform visibility and ordinary cancellations are covered; supplemental presentation-owned packets bypass ProtocolLib filters to avoid recursive projection. Names can therefore conflict with other plugins' presentation or packet-only concealment. This does not disable ordinary protection or inventory safeguards.
|
||||
|
||||
Tests exercise actual native codecs, renderer inputs and ProtocolLib dispatch with explicit transport/server/player ports. They do not prove live-client appearance or client delivery acknowledgments. Unknown transport outcomes are reported without speculative spawn replay; cleanup remains best-effort. Label reconciliation is tick-driven; live-client/network-load observation remains a follow-up. Optional Adventure mode is approved separately but not implemented in this source yet.
|
||||
|
||||
## CI and publication
|
||||
|
||||
Gitea CI verifies pushes/PRs; main pushes run semantic-release and can publish immutable versioned JARs. Source checkout is anonymous from the public repository; external action revisions are pinned to full commit SHAs. CI and actual release publication must both be verified for the exact source commit before any deployment preparation. The operator has provisioned `RELEASE_TOKEN` and the bootstrap is pushed. Do not infer successful CI, publication or credential validity from the secret name alone; record actual exact-commit workflow and artifact results in the canonical wiki.
|
||||
|
||||
@@ -25,6 +25,8 @@ tasks.withType<JavaCompile>().configureEach {
|
||||
|
||||
dependencies {
|
||||
compileOnly("org.purpurmc.purpur:purpur-api:26.2.build.2618-stable")
|
||||
compileOnly("net.dmulloy2:ProtocolLib:5.4.0")
|
||||
testImplementation("net.dmulloy2:ProtocolLib:5.4.0")
|
||||
testImplementation("org.purpurmc.purpur:purpur-api:26.2.build.2618-stable")
|
||||
testImplementation(platform("org.junit:junit-bom:5.13.4"))
|
||||
testImplementation("org.junit.jupiter:junit-jupiter")
|
||||
@@ -71,6 +73,8 @@ val nativeTest = sourceSets.create("nativeTest")
|
||||
dependencies {
|
||||
add(nativeTest.implementationConfigurationName, platform("org.junit:junit-bom:5.13.4"))
|
||||
add(nativeTest.implementationConfigurationName, "org.junit.jupiter:junit-jupiter")
|
||||
add(nativeTest.implementationConfigurationName, "net.dmulloy2:ProtocolLib:5.4.0")
|
||||
add(nativeTest.implementationConfigurationName, "org.mockito:mockito-core:5.18.0")
|
||||
add(nativeTest.compileOnlyConfigurationName, "org.jetbrains:annotations:26.0.2")
|
||||
add(nativeTest.compileOnlyConfigurationName, "org.checkerframework:checker-qual:3.49.2")
|
||||
add(nativeTest.runtimeOnlyConfigurationName, "org.junit.platform:junit-platform-launcher")
|
||||
@@ -78,6 +82,8 @@ dependencies {
|
||||
val nativeRuntimeJars = files(fileTree(nativeRuntime) {
|
||||
include("versions/**/*.jar", "libraries/**/*.jar")
|
||||
}).builtBy(prepareNativeRuntime)
|
||||
// Pinned output-only packet codec; native classes remain provided by the server, never bundled.
|
||||
sourceSets.main.get().compileClasspath += nativeRuntimeJars
|
||||
nativeTest.compileClasspath += sourceSets.main.get().output + nativeRuntimeJars
|
||||
nativeTest.runtimeClasspath += sourceSets.main.get().output + nativeRuntimeJars
|
||||
val nativeCompatibilityTest = tasks.register<Test>("nativeCompatibilityTest") {
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import com.comphenix.protocol.ProtocolLibrary;
|
||||
import games.dmg.fantasystick.presentation.CharacterPresentation;
|
||||
import games.dmg.fantasystick.presentation.CharacterChatNames;
|
||||
import games.dmg.fantasystick.presentation.ProtocolPresentation;
|
||||
import games.dmg.fantasystick.crafting.CharacterFactory;
|
||||
import games.dmg.fantasystick.crafting.CharacterAnvilNames;
|
||||
import games.dmg.fantasystick.crafting.ManualCraftingController;
|
||||
@@ -17,7 +21,7 @@ import java.time.Clock;
|
||||
import java.util.logging.Level;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
/** Crafting, names and equipment-only sessions; health, nutrition, display and spells remain inactive. */
|
||||
/** Crafting, equipment sessions and standalone names; health, nutrition and spells remain inactive. */
|
||||
public final class FantasyStickPlugin extends JavaPlugin {
|
||||
private CharacterStorage characters;
|
||||
private ManualCraftingController crafting;
|
||||
@@ -29,6 +33,9 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
private EquipmentSessionEvents sessionEvents;
|
||||
private EquipmentAdminCommand admin;
|
||||
private volatile Object lifetime;
|
||||
private CharacterPresentation presentation;
|
||||
private ProtocolPresentation protocolPresentation;
|
||||
private CharacterChatNames chatNames;
|
||||
|
||||
@Override public void onEnable() {
|
||||
try {
|
||||
@@ -45,17 +52,36 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
player -> new PlayerSheetDrops(player, event -> getServer().getPluginManager().callEvent(event)),
|
||||
problem -> getLogger().log(Level.WARNING, "Character craft " + problem.operation() + " for player "
|
||||
+ problem.player() + "; character records " + problem.characters(), problem.cause()));
|
||||
java.util.function.Consumer<Runnable> nextTick = task -> getServer().getScheduler().runTask(this, task);
|
||||
java.util.function.Consumer<Throwable> presentationFailures = problem ->
|
||||
getLogger().log(Level.WARNING, "Character presentation failed", problem);
|
||||
// This supplier belongs to one enable, never the mutable plugin field after re-enable.
|
||||
var localPresentation = new java.util.concurrent.atomic.AtomicReference<CharacterPresentation>();
|
||||
var installationFailure = new java.util.concurrent.atomic.AtomicReference<Throwable>();
|
||||
protocolPresentation = new ProtocolPresentation(this, ProtocolLibrary.getProtocolManager(),
|
||||
() -> localPresentation.get().snapshot(), problem -> {
|
||||
installationFailure.compareAndSet(null, problem);
|
||||
presentationFailures.accept(problem);
|
||||
});
|
||||
presentation = new CharacterPresentation(protocolPresentation, nextTick,
|
||||
() -> getServer().isPrimaryThread(), presentationFailures, characters::find);
|
||||
localPresentation.set(presentation);
|
||||
chatNames = new CharacterChatNames(presentation::name);
|
||||
protocolPresentation.install();
|
||||
if (installationFailure.get() != null) {
|
||||
throw new IllegalStateException("Could not install character presentation", installationFailure.get());
|
||||
}
|
||||
guard = new ManualCraftingGuard();
|
||||
anvilNames = new CharacterAnvilNames(characters,
|
||||
problem -> getLogger().log(Level.WARNING, "Character name update was refused or failed for player "
|
||||
+ problem.player() + "; character " + problem.character(), problem.cause()), getServer().getItemFactory());
|
||||
+ problem.player() + "; character " + problem.character(), problem.cause()), getServer().getItemFactory(),
|
||||
presentation::acknowledged);
|
||||
receipts = new EquipmentSessionStore(getDataFolder().toPath(), Clock.systemUTC());
|
||||
java.util.function.Consumer<Runnable> nextTick = task -> getServer().getScheduler().runTask(this, task);
|
||||
java.util.function.Consumer<EquipmentSessions.Failure> diagnostics = problem ->
|
||||
getLogger().log(Level.WARNING, "Equipment transition/recovery for player " + problem.player()
|
||||
+ "; session " + problem.session(), problem.cause());
|
||||
sessions = new EquipmentSessions(characters, receipts, switchDelay, nextTick,
|
||||
notice -> notifyPlayer(generation, notice), diagnostics);
|
||||
sessions = new EquipmentSessions(characters, receipts, switchDelay, Clock.systemUTC(), nextTick,
|
||||
notice -> notifyPlayer(generation, notice), diagnostics, presentation);
|
||||
sessionEvents = new EquipmentSessionEvents(sessions, nextTick, diagnostics);
|
||||
admin = new EquipmentAdminCommand(receipts, sessions, getServer(), nextTick,
|
||||
problem -> getLogger().log(Level.WARNING, "Equipment admin " + problem.operation()
|
||||
@@ -67,59 +93,65 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
getServer().getPluginManager().registerEvents(guard, this);
|
||||
getServer().getPluginManager().registerEvents(anvilNames, this);
|
||||
getServer().getPluginManager().registerEvents(sessionEvents, this);
|
||||
getServer().getPluginManager().registerEvents(chatNames, this);
|
||||
recipeRegistered = getServer().addRecipe(new CharacterSheets().recipe());
|
||||
if (!recipeRegistered) throw new IllegalStateException("Character-sheet recipe key is already registered");
|
||||
for (var player : getServer().getOnlinePlayers()) sessions.arrive(player);
|
||||
} catch (RuntimeException failure) {
|
||||
} catch (RuntimeException | LinkageError failure) {
|
||||
try { onDisable(); }
|
||||
catch (RuntimeException cleanupFailure) { failure.addSuppressed(cleanupFailure); }
|
||||
catch (RuntimeException | LinkageError cleanupFailure) { failure.addSuppressed(cleanupFailure); }
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void onDisable() {
|
||||
lifetime = null;
|
||||
if (admin != null) { admin.close(); admin = null; }
|
||||
if (sessionEvents != null) sessionEvents.close();
|
||||
if (crafting != null) crafting.close();
|
||||
var closingSessions = sessions;
|
||||
var closingReceipts = receipts;
|
||||
sessions = null;
|
||||
receipts = null; // A reentrant disable cannot close the store ahead of this sweep.
|
||||
if (closingSessions != null) closingSessions.close();
|
||||
if (sessionEvents != null) {
|
||||
org.bukkit.event.HandlerList.unregisterAll(sessionEvents);
|
||||
sessionEvents = null;
|
||||
}
|
||||
if (recipeRegistered) {
|
||||
try {
|
||||
getServer().removeRecipe(CharacterSheets.RECIPE);
|
||||
recipeRegistered = false;
|
||||
} catch (RuntimeException failure) {
|
||||
getLogger().log(Level.WARNING, "Could not remove the character-sheet recipe; continuing shutdown cleanup", failure);
|
||||
}
|
||||
}
|
||||
if (crafting != null) {
|
||||
org.bukkit.event.HandlerList.unregisterAll(crafting);
|
||||
crafting = null;
|
||||
}
|
||||
if (guard != null) {
|
||||
org.bukkit.event.HandlerList.unregisterAll(guard);
|
||||
guard = null;
|
||||
}
|
||||
if (anvilNames != null) {
|
||||
org.bukkit.event.HandlerList.unregisterAll(anvilNames);
|
||||
anvilNames = null;
|
||||
}
|
||||
if (characters != null) {
|
||||
characters.close();
|
||||
characters = null;
|
||||
}
|
||||
// Do not await IO on the server thread. Capture this lifetime's store: an old
|
||||
// preparation may still acknowledge and clear its never-packed receipt after re-enable.
|
||||
if (closingReceipts != null) {
|
||||
// Detach this enable's resources before any native callback can reenter disable.
|
||||
var closingPresentation = presentation; presentation = null;
|
||||
var closingProtocol = protocolPresentation; protocolPresentation = null;
|
||||
var closingChat = chatNames; chatNames = null;
|
||||
var closingAdmin = admin; admin = null;
|
||||
var closingEvents = sessionEvents; sessionEvents = null;
|
||||
var closingCrafting = crafting; crafting = null;
|
||||
var closingGuard = guard; guard = null;
|
||||
var closingAnvil = anvilNames; anvilNames = null;
|
||||
var closingSessions = sessions; sessions = null;
|
||||
var closingReceipts = receipts; receipts = null;
|
||||
var closingCharacters = characters; characters = null;
|
||||
// Retire client resources independently of successful ordinary-equipment restoration.
|
||||
if (closingPresentation != null) cleanup("presentation", closingPresentation::close);
|
||||
if (closingProtocol != null) cleanup("protocol presentation", closingProtocol::close);
|
||||
if (closingAdmin != null) cleanup("admin command", closingAdmin::close);
|
||||
if (closingEvents != null) cleanup("session events", closingEvents::close);
|
||||
if (closingCrafting != null) cleanup("craft attempts", closingCrafting::close);
|
||||
if (closingSessions != null) cleanup("equipment sessions", closingSessions::close);
|
||||
unregister(closingChat);
|
||||
unregister(closingEvents);
|
||||
unregister(closingCrafting);
|
||||
unregister(closingGuard);
|
||||
unregister(closingAnvil);
|
||||
if (recipeRegistered) cleanup("character-sheet recipe", () -> {
|
||||
getServer().removeRecipe(CharacterSheets.RECIPE);
|
||||
recipeRegistered = false; // Retain ownership for a later retry if removal failed.
|
||||
});
|
||||
if (closingCharacters != null) cleanup("character storage", closingCharacters::close);
|
||||
// Never await IO on the server thread or close receipts ahead of accepted preparations.
|
||||
if (closingReceipts != null) cleanup("equipment receipt drain", () -> {
|
||||
if (closingSessions == null) closingReceipts.close();
|
||||
else closingSessions.drained().whenComplete((ignored, failure) -> closingReceipts.close());
|
||||
});
|
||||
}
|
||||
|
||||
private void unregister(org.bukkit.event.Listener listener) {
|
||||
if (listener != null) cleanup("listener " + listener.getClass().getSimpleName(),
|
||||
() -> org.bukkit.event.HandlerList.unregisterAll(listener));
|
||||
}
|
||||
|
||||
private void cleanup(String resource, Runnable action) {
|
||||
try { action.run(); }
|
||||
catch (RuntimeException | LinkageError failure) {
|
||||
try { getLogger().log(Level.WARNING, "Could not close " + resource + "; continuing shutdown cleanup", failure); }
|
||||
catch (RuntimeException | LinkageError ignored) { /* Diagnostics must not prevent remaining cleanup. */ }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,12 +16,20 @@ public final class CharacterAnvilNames implements Listener {
|
||||
private final CharacterStorage storage;
|
||||
private final Consumer<Failure> failures;
|
||||
private final org.bukkit.inventory.ItemFactory items;
|
||||
private final Consumer<games.dmg.fantasystick.persistence.CharacterRecord> acknowledged;
|
||||
|
||||
/** Diagnostics may run on the persistence worker and must not access native player state. */
|
||||
public CharacterAnvilNames(CharacterStorage storage, Consumer<Failure> failures, org.bukkit.inventory.ItemFactory items) {
|
||||
this(storage, failures, items, ignored -> { });
|
||||
}
|
||||
|
||||
/** Acknowledgments run after file commit, possibly on the worker; never access Bukkit in that callback. */
|
||||
public CharacterAnvilNames(CharacterStorage storage, Consumer<Failure> failures, org.bukkit.inventory.ItemFactory items,
|
||||
Consumer<games.dmg.fantasystick.persistence.CharacterRecord> acknowledged) {
|
||||
this.items = java.util.Objects.requireNonNull(items);
|
||||
this.storage = java.util.Objects.requireNonNull(storage);
|
||||
this.failures = java.util.Objects.requireNonNull(failures);
|
||||
this.acknowledged = java.util.Objects.requireNonNull(acknowledged);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
@@ -37,7 +45,9 @@ public final class CharacterAnvilNames implements Listener {
|
||||
var player = event.getPlayer().getUniqueId();
|
||||
var character = id.orElseThrow();
|
||||
storage.renameCharacter(character, name).whenComplete((renamed, failure) -> {
|
||||
if (failure != null || renamed.isEmpty()) failures.accept(new Failure(player, character, failure));
|
||||
if (failure != null || renamed.isEmpty()) { failures.accept(new Failure(player, character, failure)); return; }
|
||||
try { acknowledged.accept(renamed.orElseThrow()); }
|
||||
catch (RuntimeException | LinkageError error) { failures.accept(new Failure(player, character, error)); }
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package games.dmg.fantasystick.presentation;
|
||||
|
||||
import io.papermc.paper.event.player.AsyncChatEvent;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
|
||||
/** Substitutes only the renderer's sender-name argument; signed body and delivery stay native. */
|
||||
public final class CharacterChatNames implements Listener {
|
||||
private final Function<UUID, String> names;
|
||||
public CharacterChatNames(Function<UUID, String> names) { this.names = names; }
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onChat(AsyncChatEvent event) {
|
||||
if (event.isCancelled()) return;
|
||||
String name = names.apply(event.getPlayer().getUniqueId());
|
||||
if (name == null) return;
|
||||
var literal = net.kyori.adventure.text.Component.text(name);
|
||||
var ordinary = event.renderer();
|
||||
event.renderer((source, ignoredName, message, viewer) -> ordinary.render(source, literal, message, viewer));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package games.dmg.fantasystick.presentation;
|
||||
|
||||
import games.dmg.fantasystick.persistence.CharacterRecord;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/** Immutable session decisions shared by chat/packet threads; native output stays on the server thread. */
|
||||
public final class CharacterPresentation implements SessionPresentation, AutoCloseable {
|
||||
public record View(UUID holder, UUID session, UUID character, BigInteger revision, String name) { }
|
||||
public interface Output extends AutoCloseable {
|
||||
void show(Player player, View view);
|
||||
void rename(View view);
|
||||
void clear(View view);
|
||||
@Override void close();
|
||||
}
|
||||
private final Output output;
|
||||
private final Consumer<Runnable> nextTick;
|
||||
private final BooleanSupplier mainThread;
|
||||
private final Consumer<Throwable> failures;
|
||||
private volatile Map<UUID, View> views = Map.of();
|
||||
private boolean closed;
|
||||
private java.util.function.Function<UUID, java.util.concurrent.CompletionStage<java.util.Optional<CharacterRecord>>> currentRecord =
|
||||
ignored -> java.util.concurrent.CompletableFuture.completedFuture(java.util.Optional.empty());
|
||||
public CharacterPresentation(Output output, Consumer<Runnable> nextTick, BooleanSupplier mainThread, Consumer<Throwable> failures) {
|
||||
this.output = output; this.nextTick = nextTick; this.mainThread = mainThread; this.failures = failures;
|
||||
}
|
||||
public CharacterPresentation(Output output, Consumer<Runnable> nextTick, BooleanSupplier mainThread, Consumer<Throwable> failures,
|
||||
java.util.function.Function<UUID, java.util.concurrent.CompletionStage<java.util.Optional<CharacterRecord>>> currentRecord) {
|
||||
this(output, nextTick, mainThread, failures);
|
||||
this.currentRecord = java.util.Objects.requireNonNull(currentRecord);
|
||||
}
|
||||
public Map<UUID, View> snapshot() { return views; }
|
||||
public String name(UUID holder) { var view = views.get(holder); return view == null ? null : view.name(); }
|
||||
@Override public synchronized void activate(Player player, UUID session, CharacterRecord record) {
|
||||
if (closed) return;
|
||||
UUID holder = player.getUniqueId();
|
||||
var previous = views.get(holder);
|
||||
if (previous != null) withdraw(holder, previous.session());
|
||||
var view = new View(holder, session, record.id(), record.revision(), record.name());
|
||||
put(view);
|
||||
safely(() -> output.show(player, view));
|
||||
if (!closed && view.equals(views.get(holder))) safely(() -> currentRecord.apply(record.id()).whenComplete((saved, failure) -> {
|
||||
if (failure != null) { safely(() -> { throw new java.util.concurrent.CompletionException(failure); }); return; }
|
||||
saved.ifPresent(fresh -> acknowledge(view, fresh));
|
||||
}));
|
||||
}
|
||||
@Override public synchronized void withdraw(UUID player, UUID session) {
|
||||
var view = views.get(player);
|
||||
if (view == null || !view.session().equals(session)) return;
|
||||
var copy = new java.util.HashMap<>(views); copy.remove(player); views = Map.copyOf(copy);
|
||||
// Invalidate synchronously even on a worker failure; never access Bukkit on that worker.
|
||||
if (mainThread.getAsBoolean()) safely(() -> output.clear(view));
|
||||
else safely(() -> nextTick.accept(() -> safely(() -> output.clear(view))));
|
||||
}
|
||||
/** File acknowledgment, not the physical sheet name. Safe to call from the persistence worker. */
|
||||
public void acknowledged(CharacterRecord record) {
|
||||
// Capture lifetime tokens now. A late callback cannot name a replacement holder/session.
|
||||
for (var view : views.values()) acknowledge(view, record);
|
||||
}
|
||||
private void acknowledge(View target, CharacterRecord record) {
|
||||
if (!newer(target, record)) return;
|
||||
safely(() -> nextTick.accept(() -> {
|
||||
synchronized (CharacterPresentation.this) {
|
||||
if (closed || !newer(target, record)) return;
|
||||
var updated = new View(target.holder(), target.session(), target.character(), record.revision(), record.name());
|
||||
put(updated);
|
||||
safely(() -> output.rename(updated));
|
||||
}
|
||||
}));
|
||||
}
|
||||
private boolean newer(View target, CharacterRecord record) {
|
||||
var current = views.get(target.holder());
|
||||
return current != null && current.session().equals(target.session()) && record.id().equals(current.character())
|
||||
&& !record.dead() && record.revision().compareTo(current.revision()) > 0;
|
||||
}
|
||||
private void put(View view) {
|
||||
var copy = new java.util.HashMap<>(views); copy.put(view.holder(), view); views = Map.copyOf(copy);
|
||||
}
|
||||
private void safely(Runnable action) {
|
||||
try { action.run(); }
|
||||
catch (RuntimeException | LinkageError failure) {
|
||||
try { failures.accept(failure); } catch (RuntimeException | LinkageError ignored) { /* Cleanup must continue. */ }
|
||||
}
|
||||
}
|
||||
@Override public synchronized void close() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
for (var view : java.util.List.copyOf(views.values())) withdraw(view.holder(), view.session());
|
||||
safely(output::close);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package games.dmg.fantasystick.presentation;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.protocol.game.ClientboundAddEntityPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket.Action;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket.Entry;
|
||||
import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket.AttributeSnapshot;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.entity.Display.BillboardConstraints;
|
||||
import net.minecraft.world.entity.Display.TextDisplay;
|
||||
import net.minecraft.world.entity.EntityTypes;
|
||||
import net.minecraft.world.entity.PositionMoveRotation;
|
||||
import net.minecraft.world.entity.ai.attributes.Attributes;
|
||||
import net.minecraft.world.level.GameType;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
/**
|
||||
* Display-only codec pinned to Purpur 26.2 build 2618. No packet delivery, world insertion,
|
||||
* profile/team changes, or authoritative player mutations belong here.
|
||||
*
|
||||
* <p>Player reads and detached-label creation/updates belong on the server thread. Pure
|
||||
* packet projections accept already-captured session identity/text; the caller owns visibility,
|
||||
* per-viewer range, lifecycle checks and removing each viewer's client-only labels.
|
||||
*/
|
||||
public final class NativePresentationPackets {
|
||||
private NativePresentationPackets() { }
|
||||
|
||||
/**
|
||||
* Replace only the selected UUID's display component when its action is already present.
|
||||
* Preserve all other entry fields and the exact action set, including mixed ADD packets.
|
||||
* ADD without UPDATE_DISPLAY_NAME needs a separate targeted update after acceptance.
|
||||
*/
|
||||
public static ClientboundPlayerInfoUpdatePacket projectPlayerInfo(
|
||||
ClientboundPlayerInfoUpdatePacket packet, UUID activePlayer, String name) {
|
||||
var actions = packet.actions();
|
||||
if (!actions.contains(Action.UPDATE_DISPLAY_NAME)) {
|
||||
return packet;
|
||||
}
|
||||
var entries = new ArrayList<Entry>(packet.entries().size());
|
||||
boolean changed = false;
|
||||
for (var entry : packet.entries()) {
|
||||
if (entry.profileId().equals(activePlayer)) {
|
||||
entries.add(new Entry(entry.profileId(), entry.profile(), entry.listed(), entry.latency(),
|
||||
entry.gameMode(), literal(name), entry.showHat(), entry.listOrder(), entry.chatSession()));
|
||||
changed = true;
|
||||
} else {
|
||||
entries.add(entry);
|
||||
}
|
||||
}
|
||||
if (!changed) { return packet; }
|
||||
return new ClientboundPlayerInfoUpdatePacket(EnumSet.copyOf(actions), entries);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace an existing NAME_TAG_DISTANCE snapshot with base zero/no modifiers, only for
|
||||
* the selected entity. Do not inject absent attributes; use suppressNameTag on activation.
|
||||
*/
|
||||
public static ClientboundUpdateAttributesPacket projectAttributes(
|
||||
ClientboundUpdateAttributesPacket packet, int activeEntityId) {
|
||||
if (packet.getEntityId() != activeEntityId || packet.getValues().stream()
|
||||
.noneMatch(value -> value.attribute().equals(Attributes.NAME_TAG_DISTANCE))) {
|
||||
return packet;
|
||||
}
|
||||
var projected = new ClientboundUpdateAttributesPacket(activeEntityId, List.of());
|
||||
for (var value : packet.getValues()) {
|
||||
projected.getValues().add(value.attribute().equals(Attributes.NAME_TAG_DISTANCE)
|
||||
? new AttributeSnapshot(Attributes.NAME_TAG_DISTANCE, 0, List.of()) : value);
|
||||
}
|
||||
return projected;
|
||||
}
|
||||
|
||||
/** One client-only distance snapshot; never changes the server's attribute instance. */
|
||||
public static ClientboundUpdateAttributesPacket suppressNameTag(int entityId) {
|
||||
var packet = new ClientboundUpdateAttributesPacket(entityId, List.of());
|
||||
packet.getValues().add(new AttributeSnapshot(Attributes.NAME_TAG_DISTANCE, 0, List.of()));
|
||||
return packet;
|
||||
}
|
||||
|
||||
/** Snapshot the current authoritative distance base and all modifiers, not an old default. */
|
||||
public static ClientboundUpdateAttributesPacket restoreNameTag(ServerPlayer player) {
|
||||
var distance = player.getAttribute(Attributes.NAME_TAG_DISTANCE);
|
||||
if (distance == null) {
|
||||
throw new IllegalStateException("Native player has no NAME_TAG_DISTANCE attribute");
|
||||
}
|
||||
var packet = new ClientboundUpdateAttributesPacket(player.getId(), List.of());
|
||||
packet.getValues().add(new AttributeSnapshot(Attributes.NAME_TAG_DISTANCE,
|
||||
distance.getBaseValue(), List.copyOf(distance.getModifiers())));
|
||||
return packet;
|
||||
}
|
||||
|
||||
/** UPDATE_DISPLAY_NAME only, using the current ordinary native tab display (including null). */
|
||||
public static ClientboundPlayerInfoUpdatePacket refreshTab(ServerPlayer player) {
|
||||
// Only UUID and displayName are serialized by this action. Do not capture unrelated
|
||||
// connection/game-mode state or synthesize ADD_PLAYER/listed/profile updates.
|
||||
var ordinary = player.getTabListDisplayName();
|
||||
var entry = new Entry(player.getUUID(), null, false, 0,
|
||||
GameType.DEFAULT_MODE, ordinary == null ? null : ordinary.copy(),
|
||||
false, 0, null);
|
||||
return new ClientboundPlayerInfoUpdatePacket(EnumSet.of(Action.UPDATE_DISPLAY_NAME), List.of(entry));
|
||||
}
|
||||
|
||||
/** Pure targeted display update: no profile, listed, game-mode or reconnect actions. */
|
||||
public static ClientboundPlayerInfoUpdatePacket displayName(UUID player, String name) {
|
||||
var entry = new Entry(player, null, false, 0, GameType.DEFAULT_MODE, literal(name), false, 0, null);
|
||||
return new ClientboundPlayerInfoUpdatePacket(EnumSet.of(Action.UPDATE_DISPLAY_NAME), List.of(entry));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a detached TextDisplay in the player's current native level at explicit coordinates.
|
||||
* Native construction allocates its ID through ServerLevel.getNextEntityId; never register it.
|
||||
* The caller chooses overhead position and recreates the label after world changes.
|
||||
*/
|
||||
public static Label createLabel(ServerPlayer player, String text, double x, double y, double z) {
|
||||
validatePosition(x, y, z);
|
||||
var component = literal(text);
|
||||
var level = player.level();
|
||||
if (level == null) { throw new IllegalStateException("Native player has no current server level"); }
|
||||
// A native constructor supplies the exact metadata schema and native ID allocation.
|
||||
// Never spawn, tick, wrap in a Bukkit entity, or expose this detached instance.
|
||||
var display = new TextDisplay(EntityTypes.TEXT_DISPLAY, level);
|
||||
display.persist = false;
|
||||
display.setNoGravity(true);
|
||||
display.setBillboardConstraints(BillboardConstraints.CENTER);
|
||||
display.getEntityData().set(TextDisplay.DATA_LINE_WIDTH_ID, Integer.MAX_VALUE);
|
||||
display.setFlags((byte) (TextDisplay.FLAG_SHADOW | TextDisplay.FLAG_USE_DEFAULT_BACKGROUND));
|
||||
display.setText(component);
|
||||
display.setPos(x, y, z);
|
||||
return new Label(display);
|
||||
}
|
||||
|
||||
private static Component literal(String text) {
|
||||
if (text == null) { throw new IllegalArgumentException("Display text must not be null"); }
|
||||
return Component.literal(text);
|
||||
}
|
||||
|
||||
private static void validatePosition(double x, double y, double z) {
|
||||
if (!Double.isFinite(x) || !Double.isFinite(y) || !Double.isFinite(z)) {
|
||||
throw new IllegalArgumentException("Label coordinates must be finite");
|
||||
}
|
||||
}
|
||||
|
||||
/** A session-owned detached entity; no native entity is exposed for accidental world insertion. */
|
||||
public static final class Label {
|
||||
private final TextDisplay display;
|
||||
|
||||
private Label(TextDisplay display) { this.display = display; }
|
||||
|
||||
public int id() { return display.getId(); }
|
||||
public UUID uuid() { return display.getUUID(); }
|
||||
|
||||
/** Send spawn followed by metadata to each newly eligible viewer. */
|
||||
public ClientboundAddEntityPacket spawn() {
|
||||
return new ClientboundAddEntityPacket(id(), uuid(), display.getX(), display.getY(), display.getZ(),
|
||||
0, 0, display.getType(), 0, Vec3.ZERO, 0);
|
||||
}
|
||||
|
||||
/** Complete metadata, not consumable packDirty state: safe for multiple viewers. */
|
||||
public ClientboundSetEntityDataPacket metadata() {
|
||||
return new ClientboundSetEntityDataPacket(id(), display.getEntityData().packAll());
|
||||
}
|
||||
|
||||
/** Update only the detached label and return an absolute teleport packet. */
|
||||
public ClientboundTeleportEntityPacket move(double x, double y, double z) {
|
||||
validatePosition(x, y, z);
|
||||
display.setPos(x, y, z);
|
||||
return ClientboundTeleportEntityPacket.teleport(id(),
|
||||
PositionMoveRotation.of(display), Set.of(), false);
|
||||
}
|
||||
|
||||
/** Replace only the detached label's literal text and return complete metadata. */
|
||||
public ClientboundSetEntityDataPacket rename(String text) {
|
||||
display.setText(literal(text));
|
||||
return metadata();
|
||||
}
|
||||
|
||||
/** Client-only removal; never calls entity discard/remove on the server world. */
|
||||
public ClientboundRemoveEntitiesPacket remove() {
|
||||
return new ClientboundRemoveEntitiesPacket(id());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,537 @@
|
||||
package games.dmg.fantasystick.presentation;
|
||||
|
||||
import com.comphenix.protocol.PacketType;
|
||||
import com.comphenix.protocol.ProtocolManager;
|
||||
import com.comphenix.protocol.events.ListenerPriority;
|
||||
import com.comphenix.protocol.events.PacketAdapter;
|
||||
import com.comphenix.protocol.events.PacketContainer;
|
||||
import com.comphenix.protocol.events.PacketEvent;
|
||||
import com.comphenix.protocol.events.NetworkMarker;
|
||||
import com.comphenix.protocol.events.PacketPostListener;
|
||||
import games.dmg.fantasystick.presentation.CharacterPresentation.View;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.WeakHashMap;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import net.minecraft.network.protocol.game.ClientboundAddEntityPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundBundlePacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerInfoRemovePacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundRespawnPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket;
|
||||
import org.bukkit.GameMode;
|
||||
import org.bukkit.craftbukkit.entity.CraftPlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.scheduler.BukkitTask;
|
||||
|
||||
/**
|
||||
* Pinned native output adapter. Public lifecycle methods and the scheduled reconciliation run
|
||||
* on the server thread. Packet callbacks use only immutable decisions, the parent's published
|
||||
* snapshot, packet values and recipient UUIDs. No authoritative presentation is ever changed.
|
||||
* The snapshot supplier is not read during construction: the owner may initialize its field
|
||||
* lazily, then publish a View before calling show/rename. Diagnostics may run on packet threads.
|
||||
*/
|
||||
public final class ProtocolPresentation implements CharacterPresentation.Output {
|
||||
private final Plugin plugin;
|
||||
private final ProtocolManager protocol;
|
||||
private final Supplier<Map<UUID, View>> snapshot;
|
||||
private final Consumer<Throwable> diagnostics;
|
||||
private final Map<UUID, State> states = new HashMap<>();
|
||||
private final PacketAdapter listener;
|
||||
// Cancelled events never post. Weak keys release their immutable context with the marker.
|
||||
private final Map<NetworkMarker, Map<UUID, Decision>> deliveries = new WeakHashMap<>();
|
||||
private final PacketPostListener postListener = new PacketPostListener() {
|
||||
@Override public Plugin getPlugin() { return plugin; }
|
||||
@Override public void onPostEvent(PacketEvent event) { accepted(event); }
|
||||
};
|
||||
private record Decision(View view, int entity, Map<UUID, Integer> labels) { }
|
||||
private Map<UUID, Decision> decisions = Map.of();
|
||||
private record Route(UUID holder, UUID session, UUID viewer) { }
|
||||
private final Map<Route, Integer> blocked = new HashMap<>();
|
||||
private final Set<Route> retired = new HashSet<>();
|
||||
private final Set<Route> tracking = new HashSet<>();
|
||||
private static final int UNTRACKED = 1;
|
||||
private static final int INVISIBLE = 2;
|
||||
private static final int FAILED = 4;
|
||||
private static final int TAB_REMOVED = 8;
|
||||
private BukkitTask task;
|
||||
private boolean installed;
|
||||
private boolean closed;
|
||||
private int warnings;
|
||||
private boolean operating;
|
||||
private boolean draining;
|
||||
private final ArrayDeque<Runnable> pending = new ArrayDeque<>();
|
||||
|
||||
private static final class State {
|
||||
private final Player player;
|
||||
private int entity;
|
||||
private View view;
|
||||
private org.bukkit.World world;
|
||||
private NativePresentationPackets.Label label;
|
||||
private final Map<UUID, Player> viewers = new HashMap<>();
|
||||
private State(Player player, View view) {
|
||||
this.player = player; this.view = view; this.entity = player.getEntityId();
|
||||
this.world = player.getWorld();
|
||||
}
|
||||
}
|
||||
|
||||
public ProtocolPresentation(Plugin plugin, ProtocolManager protocol,
|
||||
Supplier<Map<UUID, View>> snapshot, Consumer<Throwable> diagnostics) {
|
||||
this.plugin = Objects.requireNonNull(plugin);
|
||||
this.protocol = Objects.requireNonNull(protocol);
|
||||
this.snapshot = Objects.requireNonNull(snapshot);
|
||||
this.diagnostics = Objects.requireNonNull(diagnostics);
|
||||
listener = new PacketAdapter(plugin, ListenerPriority.HIGHEST,
|
||||
PacketType.Play.Server.PLAYER_INFO, PacketType.Play.Server.UPDATE_ATTRIBUTES,
|
||||
PacketType.Play.Server.ENTITY_DESTROY, PacketType.Play.Server.ENTITY_METADATA,
|
||||
PacketType.Play.Server.SPAWN_ENTITY, PacketType.Play.Server.PLAYER_INFO_REMOVE,
|
||||
PacketType.Play.Server.RESPAWN, PacketType.Play.Server.BUNDLE) {
|
||||
@Override public void onPacketSending(PacketEvent event) { project(event); }
|
||||
};
|
||||
}
|
||||
|
||||
/** Idempotent; the supplied manager is the sole ProtocolLib dependency. */
|
||||
public synchronized void install() {
|
||||
if (closed || installed) { return; }
|
||||
installed = true;
|
||||
try {
|
||||
protocol.addPacketListener(listener);
|
||||
task = plugin.getServer().getScheduler().runTaskTimer(plugin, this::tick, 1L, 1L);
|
||||
} catch (RuntimeException | LinkageError failure) {
|
||||
report(failure); close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override public synchronized void show(Player player, View view) {
|
||||
if (!begin(() -> show(player, view))) { return; }
|
||||
try {
|
||||
if (closed || !view.equals(snapshot.get().get(view.holder()))
|
||||
|| !player.getUniqueId().equals(view.holder())) { return; }
|
||||
var old = states.get(view.holder());
|
||||
if (old != null) {
|
||||
if (sameSession(old.view, view)) { rename(view); return; }
|
||||
states.remove(view.holder());
|
||||
removeLabels(old);
|
||||
forget(old);
|
||||
}
|
||||
if (closed || !view.equals(snapshot.get().get(view.holder())) || states.containsKey(view.holder())) { return; }
|
||||
var state = new State(player, view);
|
||||
states.put(view.holder(), state);
|
||||
// Existing trackers predate activation; subsequent viewers need an accepted pairing.
|
||||
for (var viewer : player.getTrackedBy()) { tracking.add(route(view, viewer.getUniqueId())); }
|
||||
publish();
|
||||
refreshTab(state, true);
|
||||
reconcile(state);
|
||||
} finally { finish(); }
|
||||
}
|
||||
|
||||
@Override public synchronized void rename(View view) {
|
||||
if (!begin(() -> rename(view))) { return; }
|
||||
try {
|
||||
var state = states.get(view.holder());
|
||||
if (closed || state == null || !sameSession(state.view, view)
|
||||
|| !view.equals(snapshot.get().get(view.holder()))
|
||||
|| view.revision().compareTo(state.view.revision()) < 0) { return; }
|
||||
state.view = view;
|
||||
publish();
|
||||
refreshTab(state, true);
|
||||
reconcile(state);
|
||||
} finally { finish(); }
|
||||
}
|
||||
|
||||
@Override public synchronized void clear(View view) {
|
||||
if (!begin(() -> clear(view))) { return; }
|
||||
try {
|
||||
var state = states.get(view.holder());
|
||||
if (state == null || !sameSession(state.view, view)) { return; }
|
||||
states.remove(view.holder());
|
||||
publish();
|
||||
removeLabels(state);
|
||||
forget(state);
|
||||
restore(state);
|
||||
} finally { finish(); }
|
||||
}
|
||||
|
||||
private synchronized void tick() {
|
||||
if (!begin(this::tick)) { return; }
|
||||
try {
|
||||
if (closed) { return; }
|
||||
for (var state : List.copyOf(states.values())) {
|
||||
try {
|
||||
if (!state.player.isOnline() || !sameSession(state.view, snapshot.get().get(state.view.holder()))) {
|
||||
clear(state.view);
|
||||
} else { reconcile(state); }
|
||||
} catch (RuntimeException | LinkageError failure) {
|
||||
report(failure); removeLabels(state);
|
||||
}
|
||||
}
|
||||
} finally { finish(); }
|
||||
}
|
||||
|
||||
private boolean current(State state, View expected) {
|
||||
return !closed && states.get(expected.holder()) == state && expected.equals(state.view)
|
||||
&& expected.equals(snapshot.get().get(expected.holder()));
|
||||
}
|
||||
|
||||
private boolean deliver(State state, View expected, Player viewer, Object packet) {
|
||||
// A stale decision is skipped, not classified as an uncertain transport failure.
|
||||
return !current(state, expected) || send(viewer, packet);
|
||||
}
|
||||
|
||||
private void reconcile(State state) {
|
||||
var expected = state.view;
|
||||
if (!current(state, expected)) { return; }
|
||||
try {
|
||||
var player = state.player;
|
||||
for (var id : List.copyOf(state.viewers.keySet())) {
|
||||
if (retired.remove(route(state.view, id))) { state.viewers.remove(id); }
|
||||
}
|
||||
publish();
|
||||
var location = player.getLocation();
|
||||
if (state.world != player.getWorld() || state.entity != player.getEntityId()) {
|
||||
removeLabels(state);
|
||||
if (!current(state, expected)) { return; }
|
||||
state.label = null;
|
||||
state.world = player.getWorld();
|
||||
state.entity = player.getEntityId();
|
||||
// A world/entity change is not delivery evidence. Only an accepted native
|
||||
// spawn may clear UNTRACKED/INVISIBLE, never a tick with stale platform trackers.
|
||||
publish();
|
||||
}
|
||||
if (state.label == null) {
|
||||
state.label = NativePresentationPackets.createLabel(((CraftPlayer) player).getHandle(),
|
||||
state.view.name(), location.getX(), location.getY() + player.getHeight() + 0.3, location.getZ());
|
||||
}
|
||||
var move = state.label.move(location.getX(), location.getY() + player.getHeight() + 0.3, location.getZ());
|
||||
var metadata = state.label.rename(state.view.name());
|
||||
var tracked = player.getTrackedBy();
|
||||
for (var entry : List.copyOf(state.viewers.entrySet())) {
|
||||
if (!tracked.contains(entry.getValue()) || !eligible(player, entry.getValue())) {
|
||||
state.viewers.remove(entry.getKey());
|
||||
removeLabel(state, entry.getValue());
|
||||
}
|
||||
}
|
||||
for (var viewer : tracked) {
|
||||
if (!current(state, expected)) { return; }
|
||||
try {
|
||||
if (!eligible(player, viewer)) { continue; }
|
||||
var id = viewer.getUniqueId();
|
||||
var key = route(state.view, id);
|
||||
if (!tracking.contains(key) || blocked.containsKey(key)) { continue; }
|
||||
if (!state.viewers.containsKey(id)) {
|
||||
state.viewers.put(id, viewer);
|
||||
publish();
|
||||
if (!deliver(state, expected, viewer, NativePresentationPackets.suppressNameTag(state.entity))
|
||||
|| !deliver(state, expected, viewer, state.label.spawn()) || !deliver(state, expected, viewer, metadata)) {
|
||||
quarantine(state, viewer);
|
||||
}
|
||||
} else if (!deliver(state, expected, viewer, move) || !deliver(state, expected, viewer, metadata)) {
|
||||
quarantine(state, viewer);
|
||||
}
|
||||
} catch (RuntimeException | LinkageError failure) { report(failure); }
|
||||
}
|
||||
} catch (RuntimeException | LinkageError failure) { report(failure); removeLabels(state); }
|
||||
finally { publish(); }
|
||||
}
|
||||
|
||||
private void quarantine(State state, Player viewer) {
|
||||
if (states.get(state.view.holder()) != state) { return; }
|
||||
var id = viewer.getUniqueId();
|
||||
// A send can have escaped before throwing. Retire once; never retry its spawn sequence.
|
||||
blocked.merge(route(state.view, id), FAILED, (before, flag) -> before | flag);
|
||||
state.viewers.remove(id);
|
||||
publish();
|
||||
send(viewer, state.label.remove());
|
||||
}
|
||||
|
||||
private boolean eligible(Player target, Player viewer) {
|
||||
if (viewer.getUniqueId().equals(target.getUniqueId()) || !viewer.isOnline()
|
||||
|| target.getWorld() != viewer.getWorld() || !viewer.canSee(target)
|
||||
|| target.isInvisible() || target.getGameMode() == GameMode.SPECTATOR) { return false; }
|
||||
var nativeTarget = ((CraftPlayer) target).getHandle();
|
||||
var distance = nativeTarget.getAttribute(net.minecraft.world.entity.ai.attributes.Attributes.NAME_TAG_DISTANCE);
|
||||
if (distance == null) { return false; }
|
||||
double range = distance.getValue();
|
||||
if (target.isSneaking()) { range = Math.min(32, range); }
|
||||
if (!(range > 0) || !(viewer.getLocation().distanceSquared(target.getLocation()) < range * range)) { return false; }
|
||||
// The recipient's native scoreboard is the one its client sees (it may differ from
|
||||
// the main scoreboard). Read existing membership only; never create private teams.
|
||||
var board = ((CraftPlayer) viewer).getScoreboard().getHandle();
|
||||
var team = board.getPlayersTeam(target.getName());
|
||||
if (team == null) { return true; }
|
||||
var viewerTeam = board.getPlayersTeam(viewer.getName());
|
||||
return switch (team.getNameTagVisibility()) {
|
||||
case ALWAYS -> true;
|
||||
case NEVER -> false;
|
||||
case HIDE_FOR_OTHER_TEAMS -> viewerTeam == null || team.isAlliedTo(viewerTeam);
|
||||
case HIDE_FOR_OWN_TEAM -> viewerTeam == null || !team.isAlliedTo(viewerTeam);
|
||||
};
|
||||
}
|
||||
|
||||
private void refreshTab(State state, boolean fantasy) {
|
||||
var expected = state.view;
|
||||
try {
|
||||
var ordinary = NativePresentationPackets.refreshTab(((CraftPlayer) state.player).getHandle());
|
||||
var packet = fantasy ? NativePresentationPackets.projectPlayerInfo(ordinary, state.view.holder(), state.view.name()) : ordinary;
|
||||
for (var viewer : List.copyOf(plugin.getServer().getOnlinePlayers())) {
|
||||
if (fantasy ? !current(state, expected) : !restorable(state)) { return; }
|
||||
try { if (viewer.canSee(state.player)) { send(viewer, packet); } }
|
||||
catch (RuntimeException | LinkageError failure) { report(failure); }
|
||||
}
|
||||
} catch (RuntimeException | LinkageError failure) { report(failure); }
|
||||
}
|
||||
|
||||
private boolean restorable(State state) {
|
||||
var replacement = snapshot.get().get(state.view.holder());
|
||||
return !states.containsKey(state.view.holder()) && (replacement == null || sameSession(state.view, replacement));
|
||||
}
|
||||
|
||||
private void restore(State state) {
|
||||
if (!restorable(state)) { return; }
|
||||
refreshTab(state, false);
|
||||
try {
|
||||
var packet = NativePresentationPackets.restoreNameTag(((CraftPlayer) state.player).getHandle());
|
||||
var recipients = new HashSet<>(state.player.getTrackedBy());
|
||||
recipients.add(state.player);
|
||||
for (var viewer : recipients) {
|
||||
if (!restorable(state)) { return; }
|
||||
try { if (viewer.canSee(state.player)) { send(viewer, packet); } }
|
||||
catch (RuntimeException | LinkageError failure) { report(failure); }
|
||||
}
|
||||
} catch (RuntimeException | LinkageError failure) { report(failure); }
|
||||
}
|
||||
|
||||
private void removeLabel(State state, Player viewer) {
|
||||
if (!send(viewer, state.label.remove()) && states.get(state.view.holder()) == state) {
|
||||
blocked.merge(route(state.view, viewer.getUniqueId()), FAILED, (before, flag) -> before | flag);
|
||||
}
|
||||
}
|
||||
|
||||
private void removeLabels(State state) {
|
||||
var viewers = List.copyOf(state.viewers.values());
|
||||
var label = state.label;
|
||||
state.viewers.clear();
|
||||
publish();
|
||||
if (label != null) {
|
||||
for (var viewer : viewers) {
|
||||
if (!send(viewer, label.remove()) && states.get(state.view.holder()) == state) {
|
||||
blocked.merge(route(state.view, viewer.getUniqueId()), FAILED, (before, flag) -> before | flag);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void publish() {
|
||||
var next = new HashMap<UUID, Decision>();
|
||||
for (var state : states.values()) {
|
||||
var labels = new HashMap<UUID, Integer>();
|
||||
if (state.label != null) {
|
||||
for (var viewer : state.viewers.keySet()) { labels.put(viewer, state.label.id()); }
|
||||
}
|
||||
next.put(state.view.holder(), new Decision(state.view, state.entity, Map.copyOf(labels)));
|
||||
}
|
||||
decisions = Map.copyOf(next);
|
||||
}
|
||||
|
||||
private static Route route(View view, UUID viewer) { return new Route(view.holder(), view.session(), viewer); }
|
||||
|
||||
private void forget(State state) {
|
||||
blocked.keySet().removeIf(key -> key.holder().equals(state.view.holder()) && key.session().equals(state.view.session()));
|
||||
retired.removeIf(key -> key.holder().equals(state.view.holder()) && key.session().equals(state.view.session()));
|
||||
tracking.removeIf(key -> key.holder().equals(state.view.holder()) && key.session().equals(state.view.session()));
|
||||
}
|
||||
|
||||
private synchronized void project(PacketEvent event) {
|
||||
if (closed) { return; }
|
||||
try {
|
||||
var original = event.getPacket().getHandle();
|
||||
var viewer = event.getPlayer().getUniqueId();
|
||||
reserveSpawn(original, viewer);
|
||||
if (event.isCancelled()) { return; }
|
||||
var marker = event.getNetworkMarker();
|
||||
deliveries.putIfAbsent(marker, decisions);
|
||||
marker.addPostListener(postListener); // The parent and children share this deduplicating set.
|
||||
// ProtocolLib visits children AFTER the parent, including lower-priority vetoes.
|
||||
// Never expand a child into a bundle or mutate route state speculatively here.
|
||||
Object projected = original;
|
||||
for (var decision : decisions.values()) {
|
||||
var view = currentView(decision);
|
||||
if (view == null) { continue; }
|
||||
if (projected instanceof ClientboundPlayerInfoUpdatePacket info) {
|
||||
projected = NativePresentationPackets.projectPlayerInfo(info, view.holder(), view.name());
|
||||
} else if (projected instanceof ClientboundUpdateAttributesPacket attributes) {
|
||||
projected = NativePresentationPackets.projectAttributes(attributes, decision.entity());
|
||||
}
|
||||
}
|
||||
if (projected != original) { event.setPacket(wrap(projected)); }
|
||||
} catch (RuntimeException | LinkageError failure) { report(failure); }
|
||||
}
|
||||
|
||||
private void reserveSpawn(Object packet, UUID viewer) {
|
||||
if (packet instanceof ClientboundBundlePacket bundle) {
|
||||
bundle.subPackets().forEach(child -> reserveSpawn(child, viewer));
|
||||
} else if (packet instanceof ClientboundAddEntityPacket spawn) {
|
||||
var decision = decisions.get(spawn.getUUID());
|
||||
if (decision != null && decision.entity() == spawn.getId() && !decision.labels().containsKey(viewer)) {
|
||||
// A tick between dispatch and post must not invent a successful new pairing.
|
||||
// Do not retire an existing label or clear any visibility flag on an attempt.
|
||||
blocked.merge(route(decision.view(), viewer), UNTRACKED, (before, flag) -> before | flag);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Native topology survives renames; any rendering payload uses the latest published view. */
|
||||
private View currentView(Decision expected) {
|
||||
var now = decisions.get(expected.view().holder());
|
||||
var latest = snapshot.get().get(expected.view().holder());
|
||||
return !closed && now != null && now.entity() == expected.entity()
|
||||
&& sameSession(expected.view(), now.view()) && sameSession(expected.view(), latest) ? latest : null;
|
||||
}
|
||||
|
||||
private synchronized void accepted(PacketEvent event) {
|
||||
if (!begin(() -> accepted(event))) { return; }
|
||||
try {
|
||||
var captured = deliveries.remove(NetworkMarker.getNetworkMarker(event));
|
||||
if (closed || event.isCancelled() || captured == null) { return; }
|
||||
var viewer = event.getPlayer();
|
||||
var id = viewer.getUniqueId();
|
||||
var removals = new HashMap<Decision, Integer>();
|
||||
var displays = new HashSet<Decision>();
|
||||
commitNative(event.getPacket().getHandle(), id, captured, removals, displays);
|
||||
for (var entry : removals.entrySet()) {
|
||||
var decision = entry.getKey();
|
||||
if (currentView(decision) != null && !send(viewer, new ClientboundRemoveEntitiesPacket(entry.getValue()))) {
|
||||
blocked.merge(route(decision.view(), id), FAILED, (before, flag) -> before | flag);
|
||||
}
|
||||
}
|
||||
for (var decision : displays) {
|
||||
var view = currentView(decision);
|
||||
if (view != null && (blocked.getOrDefault(route(view, id), 0) & TAB_REMOVED) == 0) {
|
||||
send(viewer, NativePresentationPackets.displayName(view.holder(), view.name()));
|
||||
}
|
||||
}
|
||||
} catch (RuntimeException | LinkageError failure) { report(failure); }
|
||||
finally { finish(); }
|
||||
}
|
||||
|
||||
private void commitNative(Object packet, UUID viewer, Map<UUID, Decision> captured,
|
||||
Map<Decision, Integer> removals, Set<Decision> displays) {
|
||||
if (packet instanceof ClientboundBundlePacket bundle) {
|
||||
bundle.subPackets().forEach(child -> commitNative(child, viewer, captured, removals, displays));
|
||||
return;
|
||||
}
|
||||
for (var decision : captured.values()) {
|
||||
var view = currentView(decision);
|
||||
if (view == null) { continue; }
|
||||
var key = route(view, viewer);
|
||||
int mask = blocked.getOrDefault(key, 0);
|
||||
if (packet instanceof ClientboundPlayerInfoUpdatePacket info) {
|
||||
if (info.actions().contains(ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER)
|
||||
&& info.entries().stream().anyMatch(entry -> entry.profileId().equals(view.holder()))) {
|
||||
mask &= ~TAB_REMOVED;
|
||||
if (!info.actions().contains(ClientboundPlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME)) {
|
||||
displays.add(decision);
|
||||
}
|
||||
}
|
||||
} else if (packet instanceof ClientboundRemoveEntitiesPacket removal
|
||||
&& removal.getEntityIds().contains(decision.entity())) { mask |= UNTRACKED; }
|
||||
else if (packet instanceof ClientboundPlayerInfoRemovePacket removal
|
||||
&& removal.profileIds().contains(view.holder())) { mask |= TAB_REMOVED; }
|
||||
else if (packet instanceof ClientboundRespawnPacket) { mask |= UNTRACKED; }
|
||||
else if (packet instanceof ClientboundAddEntityPacket spawn && spawn.getId() == decision.entity()
|
||||
&& spawn.getUUID().equals(view.holder())) {
|
||||
mask &= ~(UNTRACKED | INVISIBLE);
|
||||
tracking.add(key);
|
||||
}
|
||||
else if (packet instanceof ClientboundSetEntityDataPacket metadata && metadata.id() == decision.entity()) {
|
||||
for (var value : metadata.packedItems()) {
|
||||
if (value.id() == 0 && value.serializer() == net.minecraft.network.syncher.EntityDataSerializers.BYTE
|
||||
&& value.value() instanceof Byte flags) {
|
||||
mask = (flags & 0x20) != 0 ? mask | INVISIBLE : mask & ~INVISIBLE;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (mask == 0) { blocked.remove(key); } else { blocked.put(key, mask); }
|
||||
var label = decisions.get(view.holder()).labels().get(viewer);
|
||||
if (mask != 0 && label != null && retired.add(key)) { removals.put(decision, label); }
|
||||
}
|
||||
}
|
||||
|
||||
private boolean send(Player viewer, Object raw) {
|
||||
try { protocol.sendServerPacket(viewer, wrap(raw), false); return true; }
|
||||
catch (RuntimeException | LinkageError failure) { report(failure); return false; }
|
||||
}
|
||||
|
||||
private boolean begin(Runnable retry) {
|
||||
if (operating) { pending.add(retry); return false; }
|
||||
operating = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
private void finish() {
|
||||
operating = false;
|
||||
if (draining) { return; }
|
||||
// Reentrant lifecycle operations wait until the transport attempt AND its failure/
|
||||
// resource bookkeeping finish. Cleanup is thus ordered after every possibly escaped
|
||||
// old packet, and a queued rename cannot continue an uncertain spawn. Never replay it.
|
||||
draining = true;
|
||||
try {
|
||||
while (!pending.isEmpty()) {
|
||||
try { pending.removeFirst().run(); }
|
||||
catch (RuntimeException | LinkageError failure) { report(failure); }
|
||||
}
|
||||
} finally { draining = false; }
|
||||
}
|
||||
|
||||
private static PacketContainer wrap(Object raw) {
|
||||
PacketType type;
|
||||
if (raw instanceof ClientboundBundlePacket) { type = PacketType.Play.Server.BUNDLE; }
|
||||
else if (raw instanceof ClientboundPlayerInfoUpdatePacket) { type = PacketType.Play.Server.PLAYER_INFO; }
|
||||
else if (raw instanceof ClientboundUpdateAttributesPacket) { type = PacketType.Play.Server.UPDATE_ATTRIBUTES; }
|
||||
else if (raw instanceof ClientboundAddEntityPacket) { type = PacketType.Play.Server.SPAWN_ENTITY; }
|
||||
else if (raw instanceof ClientboundSetEntityDataPacket) { type = PacketType.Play.Server.ENTITY_METADATA; }
|
||||
else if (raw instanceof ClientboundTeleportEntityPacket) { type = PacketType.Play.Server.ENTITY_TELEPORT; }
|
||||
else if (raw instanceof ClientboundRemoveEntitiesPacket) { type = PacketType.Play.Server.ENTITY_DESTROY; }
|
||||
else { throw new IllegalArgumentException("Unsupported presentation packet"); }
|
||||
return new PacketContainer(type, raw);
|
||||
}
|
||||
|
||||
private static boolean sameSession(View first, View second) {
|
||||
return second != null && first.holder().equals(second.holder())
|
||||
&& first.session().equals(second.session()) && first.character().equals(second.character());
|
||||
}
|
||||
|
||||
private void report(Throwable failure) {
|
||||
if (warnings < 8) {
|
||||
warnings++;
|
||||
try { diagnostics.accept(failure); } catch (RuntimeException | LinkageError ignored) { /* Cleanup must continue. */ }
|
||||
}
|
||||
}
|
||||
|
||||
@Override public synchronized void close() {
|
||||
if (!begin(this::close)) { return; }
|
||||
try {
|
||||
if (closed) { return; }
|
||||
closed = true;
|
||||
deliveries.clear();
|
||||
if (task != null) {
|
||||
try { task.cancel(); } catch (RuntimeException | LinkageError failure) { report(failure); }
|
||||
}
|
||||
if (installed) {
|
||||
try { protocol.removePacketListener(listener); } catch (RuntimeException | LinkageError failure) { report(failure); }
|
||||
}
|
||||
for (var state : List.copyOf(states.values())) { clear(state.view); }
|
||||
} finally { finish(); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package games.dmg.fantasystick.presentation;
|
||||
|
||||
import games.dmg.fantasystick.persistence.CharacterRecord;
|
||||
import java.util.UUID;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/** Session-owned output only. Withdrawal must invalidate decisions even when native cleanup fails. */
|
||||
public interface SessionPresentation {
|
||||
SessionPresentation NONE = new SessionPresentation() {
|
||||
@Override public void activate(Player player, UUID session, CharacterRecord record) { }
|
||||
@Override public void withdraw(UUID player, UUID session) { }
|
||||
};
|
||||
void activate(Player player, UUID session, CharacterRecord record);
|
||||
/** May be called by a failed worker completion: no worker Bukkit access is permitted. */
|
||||
void withdraw(UUID player, UUID session);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import games.dmg.fantasystick.items.SessionControls;
|
||||
import games.dmg.fantasystick.persistence.CharacterRecord;
|
||||
import games.dmg.fantasystick.persistence.CharacterStorage;
|
||||
import games.dmg.fantasystick.persistence.EquipmentSessionStore;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
@@ -24,7 +25,7 @@ import org.bukkit.inventory.ItemStack;
|
||||
|
||||
/**
|
||||
* Server-thread equipment custody and minimal defeat handling. Fantasy health attributes,
|
||||
* nutrition, display and rewards are not applied here. No inventory/file transaction,
|
||||
* nutrition and rewards are not applied here. Presentation is an independently cleaned output port. No inventory/file transaction,
|
||||
* automatic retry or snapshot rollback is promised. The scheduler must defer onto
|
||||
* the server thread; diagnostics must be thread-safe and must not use Player APIs.
|
||||
*/
|
||||
@@ -36,9 +37,11 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
private final CharacterStorage characters;
|
||||
private final EquipmentSessionStore receipts;
|
||||
private final Duration switchDelay;
|
||||
private final Clock clock;
|
||||
private final Consumer<Runnable> nextTick;
|
||||
private final Consumer<Notice> notices;
|
||||
private final Consumer<Failure> diagnostics;
|
||||
private games.dmg.fantasystick.presentation.SessionPresentation presentation = games.dmg.fantasystick.presentation.SessionPresentation.NONE;
|
||||
private final SessionClaims claims = new SessionClaims();
|
||||
private final EquipmentStorage equipment = new EquipmentStorage();
|
||||
private final SessionControls controls = new SessionControls();
|
||||
@@ -68,6 +71,7 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
boolean acknowledged;
|
||||
boolean saving;
|
||||
boolean effectsStarted;
|
||||
boolean presentationInstalled;
|
||||
boolean cleaning;
|
||||
boolean cleanupAttempted;
|
||||
boolean uncertainSave;
|
||||
@@ -91,15 +95,29 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
|
||||
public EquipmentSessions(CharacterStorage characters, EquipmentSessionStore receipts, Duration switchDelay,
|
||||
Consumer<Runnable> nextTick, Consumer<Notice> notices, Consumer<Failure> diagnostics) {
|
||||
this(characters, receipts, switchDelay, Clock.systemUTC(), nextTick, notices, diagnostics);
|
||||
}
|
||||
|
||||
/** Supply the same wall clock as persistence when testing entry/exit deadline boundaries. */
|
||||
public EquipmentSessions(CharacterStorage characters, EquipmentSessionStore receipts, Duration switchDelay, Clock clock,
|
||||
Consumer<Runnable> nextTick, Consumer<Notice> notices, Consumer<Failure> diagnostics) {
|
||||
this.characters = Objects.requireNonNull(characters);
|
||||
this.receipts = Objects.requireNonNull(receipts);
|
||||
this.switchDelay = Objects.requireNonNull(switchDelay);
|
||||
this.clock = Objects.requireNonNull(clock);
|
||||
if (switchDelay.isNegative()) throw new IllegalArgumentException("Negative switch delay");
|
||||
this.nextTick = Objects.requireNonNull(nextTick);
|
||||
this.notices = Objects.requireNonNull(notices);
|
||||
this.diagnostics = Objects.requireNonNull(diagnostics);
|
||||
}
|
||||
|
||||
public EquipmentSessions(CharacterStorage characters, EquipmentSessionStore receipts, Duration switchDelay, Clock clock,
|
||||
Consumer<Runnable> nextTick, Consumer<Notice> notices, Consumer<Failure> diagnostics,
|
||||
games.dmg.fantasystick.presentation.SessionPresentation presentation) {
|
||||
this(characters, receipts, switchDelay, clock, nextTick, notices, diagnostics);
|
||||
this.presentation = Objects.requireNonNull(presentation);
|
||||
}
|
||||
|
||||
/** One server-thread custody bridge per coordinator; never called by persistence workers. */
|
||||
synchronized void attachCursorCustody(Consumer<UUID> invalidate) {
|
||||
if (cursorCustodyAttached) throw new IllegalStateException("Cursor custody already attached");
|
||||
@@ -214,9 +232,12 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
if (state.pending() != null) {
|
||||
refuse(attempt, "RECOVERY_REQUIRED", "An unresolved equipment receipt requires validated recovery."); return;
|
||||
}
|
||||
if (!state.canEnter(attempt.character, switchDelay, Instant.now())) {
|
||||
refuse(attempt, "COOLDOWN", "Wait until " + state.lastExit().deadline()
|
||||
+ " to switch characters; the same character may be resumed now."); return;
|
||||
Instant now = clock.instant();
|
||||
if (!state.canEnter(attempt.character, switchDelay, now)) {
|
||||
Duration remaining = Duration.between(now, state.lastExit().deadline());
|
||||
long seconds = remaining.getSeconds() + (remaining.getNano() == 0 ? 0 : 1);
|
||||
refuse(attempt, "COOLDOWN", "Wait " + seconds + " seconds to switch characters (until "
|
||||
+ state.lastExit().deadline() + "); the same character may be resumed now."); return;
|
||||
}
|
||||
}
|
||||
if (!entryNativeSafe(attempt, loaded.state().orElse(null))) {
|
||||
@@ -276,7 +297,12 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
}
|
||||
mark(attempt, EquipmentSessionMarker.Phase.PACKED);
|
||||
pending.remove(attempt.owner, attempt);
|
||||
if (!attempt.exitRequested) active.put(attempt.owner, attempt);
|
||||
if (!attempt.exitRequested) {
|
||||
active.put(attempt.owner, attempt);
|
||||
attempt.presentationInstalled = true;
|
||||
try { presentation.activate(attempt.player, attempt.session, record); }
|
||||
catch (RuntimeException | LinkageError error) { withdrawPresentation(attempt); diagnostic(attempt, error); }
|
||||
}
|
||||
attempt.player.updateInventory();
|
||||
} catch (RuntimeException error) {
|
||||
fail(attempt, error); // Effects may have started: never roll back or replay them.
|
||||
@@ -306,6 +332,7 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
var transition = transitioning.get(owner);
|
||||
if (transition != null) {
|
||||
active.remove(owner, transition);
|
||||
withdrawPresentation(transition);
|
||||
transition.exitRequested = true;
|
||||
invalidateCursor(owner);
|
||||
return EquipmentStorage.RestoreResult.NOT_FOUND;
|
||||
@@ -336,6 +363,7 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
}
|
||||
return;
|
||||
}
|
||||
withdrawPresentation(attempt);
|
||||
attempt.defeated = true;
|
||||
event.setCancelled(true);
|
||||
boolean reserved = transitioning.putIfAbsent(attempt.owner, attempt) == null;
|
||||
@@ -436,8 +464,16 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
+ ". Retain current items and authoritative state; no automatic reissue or revival."));
|
||||
}
|
||||
|
||||
private void withdrawPresentation(Attempt attempt) {
|
||||
if (!attempt.presentationInstalled) return;
|
||||
attempt.presentationInstalled = false;
|
||||
try { presentation.withdraw(attempt.owner, attempt.session); }
|
||||
catch (RuntimeException | LinkageError failure) { diagnostic(attempt, failure); }
|
||||
}
|
||||
|
||||
private EquipmentStorage.RestoreResult restoreExit(Attempt attempt) {
|
||||
active.remove(attempt.owner, attempt);
|
||||
withdrawPresentation(attempt);
|
||||
boolean reserved = transitioning.putIfAbsent(attempt.owner, attempt) == null;
|
||||
try {
|
||||
EquipmentStorage.RestoreResult result;
|
||||
@@ -547,6 +583,7 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
if (attempt.effectsStarted && owned.get(attempt.owner) == attempt) attempt.nativeUncertain = true;
|
||||
pending.remove(attempt.owner, attempt);
|
||||
active.remove(attempt.owner, attempt);
|
||||
withdrawPresentation(attempt);
|
||||
abandon(attempt);
|
||||
diagnostic(attempt, failure);
|
||||
}
|
||||
@@ -662,7 +699,10 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
try {
|
||||
for (var attempt : transitioning.values()) attempt.exitRequested = true;
|
||||
for (var attempt : transitioning.values()) {
|
||||
attempt.exitRequested = true;
|
||||
withdrawPresentation(attempt);
|
||||
}
|
||||
// Accepted main-thread tasks may be discarded on disable. Report now as well as
|
||||
// from worker completion; neither path needs a scheduler on a disabled plugin.
|
||||
for (var attempt : java.util.List.copyOf(owned.values())) {
|
||||
|
||||
@@ -2,6 +2,7 @@ name: FantasyStick
|
||||
version: ${version}
|
||||
main: games.dmg.fantasystick.FantasyStickPlugin
|
||||
api-version: "26.2"
|
||||
depend: [ProtocolLib]
|
||||
description: Transferable character sheets and recoverable equipment sessions; other RPG gameplay is not activated.
|
||||
author: dmg.games
|
||||
commands:
|
||||
|
||||
@@ -31,6 +31,47 @@ class CharacterAnvilNamesNativeTest {
|
||||
@TempDir Path data;
|
||||
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
|
||||
|
||||
@Test
|
||||
void onlyAcknowledgedCopyRenameRefreshesAnActiveOtherHolderAndLateCallbacksCannotReplay() throws Exception {
|
||||
var original = new CharacterFactory().create(ProgressionRules.defaults());
|
||||
var anvil = new AnvilFixture();
|
||||
var sheet = new CharacterSheets().create(original); anvil.grid.setItem(0, sheet);
|
||||
var problems = new CopyOnWriteArrayList<CharacterAnvilNames.Failure>();
|
||||
var tasks = new java.util.concurrent.LinkedBlockingQueue<Runnable>();
|
||||
var output = new CharacterPresentationNativeTest.Output();
|
||||
var holder = java.util.UUID.randomUUID(); var session = java.util.UUID.randomUUID();
|
||||
var player = FantasyStickLifecycleNativeTest.port(org.bukkit.entity.Player.class, (name, args) -> holder);
|
||||
var main = Thread.currentThread();
|
||||
var presentation = new games.dmg.fantasystick.presentation.CharacterPresentation(output, tasks::add,
|
||||
() -> Thread.currentThread() == main, failure -> { throw new AssertionError(failure); });
|
||||
presentation.activate(player, session, original);
|
||||
try (var storage = new CharacterStorage(new YamlCharacterRepository(data), Clock.systemUTC())) {
|
||||
storage.create(original).join();
|
||||
var listener = new CharacterAnvilNames(storage, problems::add,
|
||||
org.bukkit.craftbukkit.inventory.CraftItemFactory.instance(), presentation::acknowledged);
|
||||
var renamed = named(sheet, Component.text("Copy's <red>saved name 雪 🐉"));
|
||||
listener.onTaken(new AnvilTakeResultEvent(anvil.actor.player, anvil.view, renamed));
|
||||
var saved = storage.find(original.id()).join().orElseThrow();
|
||||
assertEquals(original.name(), presentation.name(holder), "Worker may not perform native output");
|
||||
var callback = tasks.poll(5, java.util.concurrent.TimeUnit.SECONDS); assertNotNull(callback); callback.run();
|
||||
assertEquals(saved.name(), presentation.name(holder)); assertEquals(1, output.renamed.size());
|
||||
assertNotEquals(holder, anvil.actor.id, "An inactive physical copy may rename another holder's active character");
|
||||
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());
|
||||
listener.onTaken(new AnvilTakeResultEvent(anvil.actor.player, anvil.view, named(sheet, Component.text("failed"))));
|
||||
assertEquals(saved, storage.find(original.id()).join().orElseThrow());
|
||||
assertEquals(1, problems.size()); assertTrue(tasks.isEmpty());
|
||||
assertEquals(saved.name(), presentation.name(holder));
|
||||
}
|
||||
listener.onTaken(new AnvilTakeResultEvent(anvil.actor.player, anvil.view, named(sheet, Component.text("late"))));
|
||||
storage.find(original.id()).join();
|
||||
callback = tasks.poll(5, java.util.concurrent.TimeUnit.SECONDS); assertNotNull(callback);
|
||||
presentation.withdraw(holder, session); presentation.close(); callback.run();
|
||||
assertNull(presentation.name(holder)); assertEquals(1, output.renamed.size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAcceptedNativeResultSavesItsNewNameWithoutTouchingInventoryOrPlayerXp() throws Exception {
|
||||
var original = new CharacterFactory().create(ProgressionRules.defaults());
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import games.dmg.fantasystick.presentation.CharacterChatNames;
|
||||
import io.papermc.paper.chat.ChatRenderer;
|
||||
import io.papermc.paper.event.player.AsyncChatEvent;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.UUID;
|
||||
import net.kyori.adventure.audience.Audience;
|
||||
import net.kyori.adventure.chat.SignedMessage;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class CharacterChatNamesNativeTest {
|
||||
@Test void nativeRendererReceivesLiteralSessionNameWithoutReplacingSignedBodyOrRecipients() {
|
||||
UUID id = UUID.randomUUID();
|
||||
Player player = FantasyStickLifecycleNativeTest.port(Player.class, (name, args) -> {
|
||||
assertEquals("getUniqueId", name); return id;
|
||||
});
|
||||
var names = new HashMap<UUID, String>();
|
||||
String name = "<rainbow>雪 🐉 literal name longer than sixteen";
|
||||
names.put(id, name);
|
||||
var listener = new CharacterChatNames(names::get);
|
||||
var body = Component.text("original signed <body>");
|
||||
var signed = SignedMessage.system("original signed <body>", body);
|
||||
var viewers = new HashSet<Audience>(); viewers.add(Audience.empty());
|
||||
ChatRenderer renderer = (sender, display, message, viewer) -> {
|
||||
assertSame(player, sender); assertSame(body, message);
|
||||
assertEquals(Component.text(name), display);
|
||||
return Component.text("prefix ").append(display).append(message);
|
||||
};
|
||||
var event = new AsyncChatEvent(true, player, viewers, renderer, body, body, signed);
|
||||
listener.onChat(event);
|
||||
assertSame(body, event.message()); assertSame(body, event.originalMessage());
|
||||
assertSame(signed, event.signedMessage()); assertEquals(viewers, event.viewers()); assertFalse(event.isCancelled());
|
||||
// The renderer may run after a switch; this accepted event captures its immutable sender name.
|
||||
names.put(id, "replacement");
|
||||
assertEquals(Component.text("prefix ").append(Component.text(name)).append(body),
|
||||
event.renderer().render(player, Component.text("account"), event.message(), Audience.empty()));
|
||||
}
|
||||
|
||||
@Test void cancellationsAndOrdinaryRenderersAreUntouched() {
|
||||
UUID id = UUID.randomUUID();
|
||||
Player player = FantasyStickLifecycleNativeTest.port(Player.class, (name, args) -> id);
|
||||
var listener = new CharacterChatNames(ignored -> "fantasy");
|
||||
var body = Component.text("body"); var renderer = ChatRenderer.defaultRenderer();
|
||||
var event = new AsyncChatEvent(true, player, new HashSet<>(), renderer, body, body, SignedMessage.system("body", body));
|
||||
event.setCancelled(true); listener.onChat(event);
|
||||
assertTrue(event.isCancelled()); assertSame(renderer, event.renderer());
|
||||
event.setCancelled(false); new CharacterChatNames(ignored -> null).onChat(event);
|
||||
assertSame(renderer, event.renderer()); assertSame(body, event.message());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import games.dmg.fantasystick.crafting.CharacterFactory;
|
||||
import games.dmg.fantasystick.persistence.CharacterRecord;
|
||||
import games.dmg.fantasystick.presentation.CharacterPresentation;
|
||||
import games.dmg.fantasystick.progression.ProgressionRules;
|
||||
import java.util.ArrayList;
|
||||
import java.util.UUID;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class CharacterPresentationNativeTest {
|
||||
@Test void immutableSessionNamesWithdrawBeforeOutputFailureAndRejectOldAcknowledgments() {
|
||||
UUID holder = UUID.randomUUID(); var first = UUID.randomUUID(); var second = UUID.randomUUID();
|
||||
var player = FantasyStickLifecycleNativeTest.port(Player.class, (name, args) -> { assertEquals("getUniqueId", name); return holder; });
|
||||
var record = new CharacterFactory().create(ProgressionRules.defaults());
|
||||
var tasks = new ArrayList<Runnable>(); var failures = new ArrayList<Throwable>();
|
||||
var output = new Output();
|
||||
var presentation = new CharacterPresentation(output, tasks::add, () -> true, failures::add);
|
||||
presentation.activate(player, first, record);
|
||||
assertEquals(record.name(), presentation.name(holder));
|
||||
assertEquals(1, output.shown.size());
|
||||
var snapshot = presentation.snapshot();
|
||||
var renamed = rename(record, "雪 <red>literal 🐉", 1);
|
||||
presentation.acknowledged(renamed);
|
||||
presentation.withdraw(holder, first);
|
||||
presentation.activate(player, second, rename(record, "new authoritative", 2));
|
||||
tasks.forEach(Runnable::run); tasks.clear();
|
||||
assertEquals("new authoritative", presentation.name(holder));
|
||||
assertEquals(record.name(), snapshot.get(holder).name());
|
||||
presentation.withdraw(holder, first); // Old token cannot erase replacement.
|
||||
assertEquals("new authoritative", presentation.name(holder));
|
||||
output.failClear = true;
|
||||
presentation.withdraw(holder, second);
|
||||
assertNull(presentation.name(holder)); assertEquals(1, failures.size());
|
||||
presentation.close(); presentation.acknowledged(rename(record, "late", 3));
|
||||
tasks.forEach(Runnable::run);
|
||||
presentation.activate(player, first, record);
|
||||
assertTrue(presentation.snapshot().isEmpty());
|
||||
}
|
||||
|
||||
@Test void activationClosesTheFreshReadToRenameAcknowledgmentRaceAndNeverAppliesAnOldReadToANewSession() {
|
||||
UUID holder = UUID.randomUUID();
|
||||
Player player = FantasyStickLifecycleNativeTest.port(Player.class, (name, args) -> holder);
|
||||
var record = new CharacterFactory().create(ProgressionRules.defaults());
|
||||
var reads = new ArrayList<java.util.concurrent.CompletableFuture<java.util.Optional<CharacterRecord>>>();
|
||||
var tasks = new ArrayList<Runnable>(); var output = new Output();
|
||||
var presentation = new CharacterPresentation(output, tasks::add, () -> true, failure -> { throw new AssertionError(failure); }, id -> {
|
||||
assertEquals(record.id(), id);
|
||||
var read = new java.util.concurrent.CompletableFuture<java.util.Optional<CharacterRecord>>(); reads.add(read); return read;
|
||||
});
|
||||
// Rename committed after EquipmentSessions' final load but before presentation activation.
|
||||
presentation.acknowledged(rename(record, "already saved while not active", 1));
|
||||
UUID session = UUID.randomUUID();
|
||||
presentation.activate(player, session, record);
|
||||
assertEquals(1, reads.size(), "Resume always rechecks the authoritative record, not a physical-sheet/cache name");
|
||||
reads.getFirst().complete(java.util.Optional.of(rename(record, "already saved while not active", 1)));
|
||||
tasks.forEach(Runnable::run); tasks.clear();
|
||||
assertEquals("already saved while not active", presentation.name(holder));
|
||||
presentation.withdraw(holder, session);
|
||||
UUID replacement = UUID.randomUUID();
|
||||
presentation.activate(player, replacement, record);
|
||||
reads.get(1).complete(java.util.Optional.of(rename(record, "old queued name", 2)));
|
||||
presentation.withdraw(holder, replacement);
|
||||
presentation.activate(player, UUID.randomUUID(), rename(record, "fresh current name", 3));
|
||||
tasks.forEach(Runnable::run); tasks.clear();
|
||||
assertEquals("fresh current name", presentation.name(holder));
|
||||
reads.get(2).complete(java.util.Optional.of(rename(record, "fresh current name", 3)));
|
||||
assertTrue(tasks.isEmpty(), "Equal revision does not enqueue redundant native output");
|
||||
presentation.close();
|
||||
}
|
||||
|
||||
static CharacterRecord rename(CharacterRecord r, String name, int revision) {
|
||||
return new CharacterRecord(r.id(), name, java.math.BigInteger.valueOf(revision), r.stats(), r.level(), r.experience(),
|
||||
r.unspentPoints(), r.health(), r.learned(), r.loadout(), r.cooldowns(), r.dead(), r.deathId(), r.diedAt());
|
||||
}
|
||||
static final class Output implements CharacterPresentation.Output {
|
||||
final ArrayList<CharacterPresentation.View> shown = new ArrayList<>();
|
||||
final ArrayList<CharacterPresentation.View> renamed = new ArrayList<>();
|
||||
final ArrayList<CharacterPresentation.View> cleared = new ArrayList<>();
|
||||
boolean failClear;
|
||||
@Override public void show(Player player, CharacterPresentation.View view) { shown.add(view); }
|
||||
@Override public void rename(CharacterPresentation.View view) { renamed.add(view); }
|
||||
@Override public void clear(CharacterPresentation.View view) { cleared.add(view); if (failClear) throw new IllegalStateException("native send failed"); }
|
||||
@Override public void close() { }
|
||||
}
|
||||
}
|
||||
@@ -626,7 +626,9 @@ class EquipmentSessionEventsNativeTest {
|
||||
assertTrue(dead.dead()); assertEquals("Newest name", dead.name());
|
||||
assertEquals(dead.deathId(), new games.dmg.fantasystick.items.TailBooks().identify(book).orElseThrow().deathId());
|
||||
assertEquals(1, a.teleports); assertEquals(0, f.world.creates);
|
||||
assertNull(f.core.state(a).pending());
|
||||
var exited = f.core.state(a);
|
||||
assertNull(exited.pending()); assertEquals(a.record.id(), exited.lastExit().characterId());
|
||||
assertEquals(java.time.Duration.ofSeconds(900), java.time.Duration.between(exited.lastExit().exitedAt(), exited.lastExit().deadline()));
|
||||
assertTrue(f.core.notices.stream().anyMatch(n -> n.code().equals("DEFEAT")));
|
||||
}
|
||||
}
|
||||
@@ -1536,16 +1538,51 @@ class EquipmentSessionEventsNativeTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test void defeatStartsPlayerDelayButLegitimateBackendRevivalCanResumeTheSameIdentity() throws Exception {
|
||||
try (var f = new Fixture()) {
|
||||
var a = f.actor; var copiedSheet = a.inventory.getItemInOffHand().clone();
|
||||
f.core.activate(a); f.changed();
|
||||
var active = f.core.sessions.active(a.id).orElseThrow();
|
||||
f.dispatcher.accept(f.death(org.bukkit.damage.DamageType.GENERIC));
|
||||
var exit = f.core.state(a).lastExit();
|
||||
assertEquals(active.session(), exit.sessionId()); assertEquals(a.record.id(), exit.characterId());
|
||||
assertEquals(java.time.Duration.ofSeconds(900), java.time.Duration.between(exit.exitedAt(), exit.deadline()));
|
||||
f.core.tick(); // Confirm Tail delivery and release the defeat's claim.
|
||||
assertEquals(Material.WRITTEN_BOOK, a.inventory.getItemInOffHand().getType());
|
||||
a.inventory.setItemInOffHand(copiedSheet); f.changed();
|
||||
// The bridge observed the original ID before defeat; join explicitly requests saved-state eligibility.
|
||||
f.dispatcher.accept(new org.bukkit.event.player.PlayerJoinEvent(a.player, (net.kyori.adventure.text.Component) null));
|
||||
f.core.tick(); f.core.tick();
|
||||
assertEquals("UNAVAILABLE_CHARACTER", f.core.notices.getLast().code());
|
||||
assertEquals(exit, f.core.state(a).lastExit());
|
||||
var other = f.core.actor(); a.inventory.setItemInOffHand(other.inventory.getItemInOffHand()); f.changed();
|
||||
f.ticks.remove().run(); f.core.tick();
|
||||
assertEquals("COOLDOWN", f.core.notices.getLast().code());
|
||||
var dead = f.core.characters.find(a.record.id()).get(5, java.util.concurrent.TimeUnit.SECONDS).orElseThrow();
|
||||
var live = f.core.characters.restoreDeathRecord(dead.id(), dead.deathId()).get(5, java.util.concurrent.TimeUnit.SECONDS).orElseThrow();
|
||||
a.inventory.setItemInOffHand(new games.dmg.fantasystick.items.CharacterSheets().create(live)); f.changed();
|
||||
f.ticks.remove().run(); f.core.tick(); f.core.tick();
|
||||
assertEquals(live.id(), f.core.sessions.active(a.id).orElseThrow().character());
|
||||
assertEquals(exit, f.core.state(a).lastExit());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void replacingCharacterExitsFirstAndCoordinatorEnforcesDifferentIdCooldownWithoutExtendingIt() throws Exception {
|
||||
try (var f = new Fixture()) {
|
||||
var a = f.actor; f.core.activate(a); f.changed();
|
||||
var other = f.core.actor();
|
||||
a.inventory.setItemInOffHand(other.inventory.getItemInOffHand().clone());
|
||||
var sameName = f.core.characters.renameCharacter(other.record.id(), a.record.name())
|
||||
.get(5, java.util.concurrent.TimeUnit.SECONDS).orElseThrow();
|
||||
a.inventory.setItemInOffHand(new games.dmg.fantasystick.items.CharacterSheets().create(sameName));
|
||||
f.changed();
|
||||
assertTrue(f.core.sessions.active(a.id).isEmpty());
|
||||
assertEquals(Material.DIAMOND_SWORD, a.inventory.getItem(0).getType(), "Replacement exits and restores before its new entry");
|
||||
assertEquals(Material.DIAMOND_HELMET, a.inventory.getHelmet().getType());
|
||||
var restored = a.snapshot(); var cursor = a.cursor.clone();
|
||||
var exited = f.core.state(a).lastExit(); // IO barrier, not a tick-thread production wait.
|
||||
f.ticks.remove().run(); f.core.tick();
|
||||
assertEquals("COOLDOWN", f.core.notices.getLast().code());
|
||||
assertArrayEquals(restored, a.snapshot()); assertEquals(cursor, a.cursor);
|
||||
assertEquals(exited, f.core.state(a).lastExit());
|
||||
a.inventory.setItemInOffHand(new ItemStack(Material.AIR)); f.changed();
|
||||
a.inventory.setItemInOffHand(new games.dmg.fantasystick.items.CharacterSheets().create(a.record)); f.changed();
|
||||
|
||||
@@ -38,6 +38,30 @@ class EquipmentSessionsNativeTest {
|
||||
@TempDir Path data;
|
||||
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
|
||||
|
||||
@Test void presentationUsesAuthoritativeRecordAndWithdrawsBeforeEvenRefusedGearRestoration() throws Exception {
|
||||
try (var f = new Fixture()) {
|
||||
var actor = f.actor();
|
||||
var renamed = f.characters.renameCharacter(actor.record.id(), "<rainbow>雪 🐉 character longer than sixteen").get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
var shown = new ArrayList<CharacterRecord>();
|
||||
var withdrawn = new ArrayList<UUID>();
|
||||
f.presentation = new games.dmg.fantasystick.presentation.SessionPresentation() {
|
||||
@Override public void activate(Player player, UUID session, CharacterRecord record) {
|
||||
assertSame(f.main, Thread.currentThread()); assertSame(actor.player, player);
|
||||
assertTrue(f.sessions.active(actor.id).isPresent()); shown.add(record);
|
||||
}
|
||||
@Override public void withdraw(UUID player, UUID session) { withdrawn.add(session); }
|
||||
};
|
||||
f.sessions = f.coordinator(Duration.ofSeconds(900));
|
||||
f.activate(actor);
|
||||
var session = f.sessions.active(actor.id).orElseThrow().session();
|
||||
assertEquals(java.util.List.of(renamed), shown);
|
||||
actor.inventory.setItem(9, null); // Missing genuine box cannot retain a fantasy display.
|
||||
f.sessions.exit(actor.player);
|
||||
assertEquals(java.util.List.of(session), withdrawn);
|
||||
assertTrue(f.sessions.active(actor.id).isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void nativePlayerMarkerBracketsPackingAndRestorationAndSurvivesSerialization() throws Exception {
|
||||
try (var f = new Fixture()) {
|
||||
var actor = f.actor();
|
||||
@@ -849,6 +873,247 @@ class EquipmentSessionsNativeTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test void reopenedCoordinatorCountsOfflineTimeAtExactExpiryAndNewExitsUseCurrentDuration() throws Exception {
|
||||
for (long configured : new long[]{1, 900, 3600}) try (var f = new Fixture(Duration.ofSeconds(900), new MutableClock())) {
|
||||
var clock = (MutableClock) f.clock;
|
||||
var actor = f.actor(); var other = f.actor(); f.activate(actor); f.sessions.exit(actor.player);
|
||||
var exited = f.state(actor); var deadline = exited.lastExit().deadline();
|
||||
clock.now = deadline.minusNanos(1);
|
||||
actor = f.reopen(actor, Duration.ofSeconds(configured));
|
||||
actor.inventory.setItemInOffHand(other.inventory.getItemInOffHand().clone());
|
||||
var before = actor.snapshot();
|
||||
f.sessions.arrive(actor.player); f.tick(); f.tick();
|
||||
assertEquals("COOLDOWN", f.notices.getLast().code());
|
||||
assertTrue(f.notices.getLast().message().startsWith("Wait 1 seconds"));
|
||||
assertEquals(exited, f.state(actor)); assertArrayEquals(before, actor.snapshot());
|
||||
clock.now = deadline; // Inclusive expiry, even with a longer/shorter newly configured duration.
|
||||
f.sessions.arrive(actor.player); f.tick(); f.tick(); f.tick();
|
||||
assertEquals(other.record.id(), f.sessions.active(actor.id).orElseThrow().character());
|
||||
assertEquals(exited.lastExit(), f.state(actor).lastExit());
|
||||
clock.advance(Duration.ofSeconds(5)); f.sessions.exit(actor.player);
|
||||
var next = f.state(actor).lastExit();
|
||||
assertNotEquals(exited.lastExit().sessionId(), next.sessionId());
|
||||
assertEquals(other.record.id(), next.characterId());
|
||||
assertEquals(clock.now, next.exitedAt()); assertEquals(clock.now.plusSeconds(configured), next.deadline());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void sameIdFailedEquipmentPreflightPreservesExistingDeadlineAndAllItems() throws Exception {
|
||||
for (boolean full : new boolean[]{false, true}) {
|
||||
var clock = new MutableClock();
|
||||
try (var f = new Fixture(Duration.ofSeconds(900), clock)) {
|
||||
var actor = f.actor(); f.activate(actor); f.sessions.exit(actor.player);
|
||||
var exited = f.state(actor); clock.advance(Duration.ofSeconds(60));
|
||||
if (full) for (int slot = 9; slot < 36; slot++) actor.inventory.setItem(slot, new ItemStack(Material.STONE, 64));
|
||||
else actor.inventory.setItem(0, new ItemStack(Material.SHULKER_BOX));
|
||||
var before = actor.snapshot(); var marker = actor.marker();
|
||||
f.sessions.enter(actor.player); f.tick();
|
||||
assertTrue(f.sessions.active(actor.id).isEmpty());
|
||||
assertFalse(f.notices.isEmpty()); assertNotEquals("COOLDOWN", f.notices.getLast().code());
|
||||
assertArrayEquals(before, actor.snapshot()); assertEquals(marker, actor.marker());
|
||||
assertEquals(exited, f.state(actor), "Failed packing preflight is not an actual exit or a timer reset");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test void zeroBypassesSavedDeadlineAfterRestartWithoutSkippingAuthoritativeEligibility() throws Exception {
|
||||
var clock = new MutableClock();
|
||||
try (var f = new Fixture(Duration.ofSeconds(900), clock)) {
|
||||
var actor = f.actor(); var other = f.actor(); f.activate(actor); f.sessions.exit(actor.player);
|
||||
var exited = f.state(actor); clock.advance(Duration.ofSeconds(100));
|
||||
actor = f.reopen(actor, Duration.ZERO);
|
||||
actor.inventory.setItemInOffHand(other.inventory.getItemInOffHand().clone());
|
||||
var dead = f.characters.recordDeath(other.record.id()).get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
var before = actor.snapshot(); f.sessions.enter(actor.player); f.tick();
|
||||
assertEquals("UNAVAILABLE_CHARACTER", f.notices.getLast().code());
|
||||
assertArrayEquals(before, actor.snapshot()); assertEquals(exited, f.state(actor));
|
||||
var live = f.characters.restoreDeathRecord(dead.id(), dead.deathId()).get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
actor.inventory.setItemInOffHand(new CharacterSheets().create(live)); f.activate(actor);
|
||||
assertEquals(exited.lastExit(), f.state(actor).lastExit(), "Zero bypass does not rewrite the old absolute deadline");
|
||||
f.sessions.exit(actor.player);
|
||||
var next = f.state(actor).lastExit();
|
||||
assertEquals(clock.now, next.exitedAt()); assertEquals(clock.now, next.deadline());
|
||||
assertEquals(live.id(), next.characterId());
|
||||
actor = f.reopen(actor, Duration.ofSeconds(900));
|
||||
actor.inventory.setItemInOffHand(new CharacterSheets().create(actor.record)); f.activate(actor);
|
||||
assertEquals(next, f.state(actor).lastExit(), "Re-enabling delay cannot retroactively stretch a zero-duration exit");
|
||||
}
|
||||
}
|
||||
|
||||
@Test void sameCharacterReentryDoesNotResetDelayButItsNextActualExitDoes() throws Exception {
|
||||
var clock = new MutableClock();
|
||||
try (var f = new Fixture(Duration.ofSeconds(900), clock)) {
|
||||
var actor = f.actor(); var other = f.actor(); f.activate(actor); f.sessions.exit(actor.player);
|
||||
var first = f.state(actor).lastExit(); clock.advance(Duration.ofSeconds(30));
|
||||
f.activate(actor); assertEquals(first, f.state(actor).lastExit());
|
||||
clock.advance(Duration.ofSeconds(20)); f.sessions.exit(actor.player);
|
||||
var second = f.state(actor).lastExit();
|
||||
assertNotEquals(first.sessionId(), second.sessionId()); assertEquals(first.characterId(), second.characterId());
|
||||
assertEquals(clock.now, second.exitedAt()); assertEquals(first.deadline().plusSeconds(50), second.deadline());
|
||||
clock.now = first.deadline(); actor.inventory.setItemInOffHand(other.inventory.getItemInOffHand());
|
||||
var before = actor.snapshot(); f.sessions.enter(actor.player); f.tick();
|
||||
assertEquals("COOLDOWN", f.notices.getLast().code());
|
||||
assertTrue(f.notices.getLast().message().startsWith("Wait 50 seconds")); assertArrayEquals(before, actor.snapshot());
|
||||
assertEquals(second, f.state(actor).lastExit());
|
||||
clock.now = second.deadline().plusNanos(1); f.activate(actor);
|
||||
}
|
||||
}
|
||||
|
||||
@Test void repeatedRecoveryAfterRestartAndDurationChangeNeverExtendsTheActualExit() throws Exception {
|
||||
var clock = new MutableClock();
|
||||
try (var f = new Fixture(Duration.ofSeconds(900), clock)) {
|
||||
var actor = f.actor(); f.activate(actor); var control = actor.inventory.getItem(0).clone();
|
||||
actor.inventory.setItem(0, new ItemStack(Material.EMERALD));
|
||||
assertEquals(EquipmentStorage.RestoreResult.OCCUPIED_SLOT, f.sessions.exit(actor.player));
|
||||
var exit = f.state(actor).lastExit();
|
||||
clock.advance(Duration.ofSeconds(200)); actor = f.reopen(actor, Duration.ofSeconds(3600));
|
||||
var before = actor.snapshot(); f.sessions.recover(actor.player); f.tick();
|
||||
assertArrayEquals(before, actor.snapshot()); assertEquals(exit, f.state(actor).lastExit());
|
||||
actor.inventory.setItem(0, control); f.sessions.recover(actor.player); f.tick();
|
||||
assertNull(f.state(actor).pending()); assertEquals(exit, f.state(actor).lastExit());
|
||||
var restored = actor.snapshot();
|
||||
for (int retry = 0; retry < 2; retry++) {
|
||||
clock.advance(Duration.ofSeconds(100)); f.sessions.recover(actor.player); f.tick();
|
||||
assertArrayEquals(restored, actor.snapshot()); assertEquals(exit, f.state(actor).lastExit());
|
||||
assertEquals("NO_RECEIPT", f.notices.getLast().code());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test void actualNativeExitStartsAtRequestNotDelayedReceiptWorkerExecution() throws Exception {
|
||||
for (boolean restored : new boolean[]{false, true}) {
|
||||
var clock = new MutableClock();
|
||||
var entered = new java.util.concurrent.CountDownLatch(1);
|
||||
var release = new java.util.concurrent.CountDownLatch(1);
|
||||
var block = new java.util.concurrent.atomic.AtomicBoolean();
|
||||
try (var f = new Fixture((source, target) -> {
|
||||
if (block.compareAndSet(true, false)) { entered.countDown(); gate(release); }
|
||||
move(source, target);
|
||||
}, Duration.ofSeconds(900), EquipmentSessionsNativeTest::move, clock)) {
|
||||
var actor = f.actor(); f.activate(actor);
|
||||
if (!restored) actor.inventory.setItem(0, new ItemStack(Material.EMERALD));
|
||||
var before = actor.snapshot();
|
||||
block.set(true);
|
||||
var blocker = f.receipts.prepare(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID());
|
||||
java.time.Instant requested;
|
||||
try {
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||
clock.advance(Duration.ofSeconds(2)); requested = clock.now;
|
||||
assertEquals(restored ? EquipmentStorage.RestoreResult.RESTORED : EquipmentStorage.RestoreResult.OCCUPIED_SLOT,
|
||||
f.sessions.exit(actor.player));
|
||||
assertTrue(f.sessions.active(actor.id).isEmpty());
|
||||
if (restored) assertEquals(Material.DIAMOND_SWORD, actor.inventory.getItem(0).getType());
|
||||
else assertArrayEquals(before, actor.snapshot());
|
||||
clock.advance(Duration.ofHours(1));
|
||||
} finally { release.countDown(); }
|
||||
blocker.toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
var state = f.state(actor);
|
||||
assertEquals(requested, state.lastExit().exitedAt());
|
||||
assertEquals(requested.plusSeconds(900), state.lastExit().deadline());
|
||||
assertEquals(restored, state.pending() == null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test void sameStableIdReentersThroughLiveRenamedSerializedCopiedAndBackendRevivedReferences() throws Exception {
|
||||
for (int kind = 0; kind < 4; kind++) try (var f = new Fixture()) {
|
||||
var actor = f.actor(); f.activate(actor);
|
||||
f.sessions.exit(actor.player); var exited = f.state(actor);
|
||||
var record = actor.record;
|
||||
if (kind == 1) record = f.characters.renameCharacter(record.id(), "Renamed adventurer").get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
if (kind == 3) {
|
||||
var dead = f.characters.recordDeath(record.id()).get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
var before = actor.snapshot();
|
||||
f.sessions.enter(actor.player); f.tick();
|
||||
assertEquals("UNAVAILABLE_CHARACTER", f.notices.getLast().code());
|
||||
assertArrayEquals(before, actor.snapshot()); assertEquals(exited, f.state(actor));
|
||||
assertTrue(f.characters.restoreDeathRecord(dead.id(), UUID.randomUUID()).get(5, TimeUnit.SECONDS).isEmpty());
|
||||
record = f.characters.restoreDeathRecord(dead.id(), dead.deathId()).get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
assertEquals(actor.record.id(), record.id()); assertFalse(record.dead());
|
||||
// Real consume-once backend + native reference factory; not a claim of a Revive spell/UI.
|
||||
assertTrue(f.characters.restoreDeathRecord(dead.id(), dead.deathId()).get(5, TimeUnit.SECONDS).isEmpty());
|
||||
}
|
||||
var sheet = new CharacterSheets().create(record);
|
||||
if (kind == 2) sheet.setAmount(3);
|
||||
actor.inventory.setItemInOffHand(sheet.clone());
|
||||
actor = actor.reload(); // Real native item codec + player PDC, not the original item object.
|
||||
f.activate(actor);
|
||||
assertEquals(exited.lastExit(), f.state(actor).lastExit(), "Reentry itself does not start a delay");
|
||||
assertEquals(record.id(), f.sessions.active(actor.id).orElseThrow().character());
|
||||
assertNotEquals(exited.lastExit().sessionId(), f.sessions.active(actor.id).orElseThrow().session());
|
||||
assertEquals(record, f.characters.find(record.id()).get(5, TimeUnit.SECONDS).orElseThrow(),
|
||||
"Session delay does not rewrite character progress or ability cooldowns");
|
||||
}
|
||||
}
|
||||
|
||||
@Test void missingFakeAndDifferentIdSameNameCannotUseTheSameCharacterException() throws Exception {
|
||||
for (int kind = 0; kind < 3; kind++) try (var f = new Fixture()) {
|
||||
var actor = f.actor(); f.activate(actor); f.sessions.exit(actor.player);
|
||||
var exited = f.state(actor);
|
||||
if (kind == 0) java.nio.file.Files.delete(data.resolve("characters").resolve(actor.record.id() + ".yml"));
|
||||
if (kind == 1) {
|
||||
var fake = new ItemStack(Material.PAPER); fake.setItemMeta(actor.inventory.getItemInOffHand().getItemMeta());
|
||||
var meta = fake.getItemMeta();
|
||||
meta.getPersistentDataContainer().remove(new org.bukkit.NamespacedKey("fantasystick", "character_id"));
|
||||
fake.setItemMeta(meta); actor.inventory.setItemInOffHand(fake);
|
||||
}
|
||||
if (kind == 2) {
|
||||
var other = f.actor();
|
||||
var sameName = f.characters.renameCharacter(other.record.id(), actor.record.name()).get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
actor.inventory.setItemInOffHand(new CharacterSheets().create(sameName));
|
||||
}
|
||||
var before = actor.snapshot(); var marker = actor.marker();
|
||||
f.sessions.enter(actor.player); if (kind != 1) f.tick();
|
||||
assertEquals(kind == 0 ? "UNAVAILABLE_CHARACTER" : kind == 1 ? "INVALID_SHEET" : "COOLDOWN", f.notices.getLast().code());
|
||||
assertTrue(f.sessions.active(actor.id).isEmpty()); assertArrayEquals(before, actor.snapshot());
|
||||
assertEquals(marker, actor.marker()); assertEquals(exited, f.state(actor));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void sheetTransferDoesNotInheritOrResetEitherPlayersExistingSwitchDeadline() throws Exception {
|
||||
try (var f = new Fixture()) {
|
||||
var first = f.actor(); var second = f.actor(); var freshHolder = f.actor(first.record);
|
||||
f.activate(first); f.activate(second);
|
||||
f.sessions.exit(first.player); f.sessions.exit(second.player);
|
||||
var firstExit = f.state(first); var secondExit = f.state(second);
|
||||
var renamed = f.characters.renameCharacter(first.record.id(), "Transferred identity").get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
var transferred = new CharacterSheets().create(renamed);
|
||||
first.inventory.setItemInOffHand(new CharacterSheets().create(second.record));
|
||||
second.inventory.setItemInOffHand(transferred.clone());
|
||||
for (var holder : java.util.List.of(first, second)) {
|
||||
var before = holder.snapshot(); f.sessions.enter(holder.player); f.tick();
|
||||
assertEquals("COOLDOWN", f.notices.getLast().code()); assertArrayEquals(before, holder.snapshot());
|
||||
}
|
||||
freshHolder.inventory.setItemInOffHand(transferred.clone()); f.activate(freshHolder);
|
||||
assertNull(f.state(freshHolder).lastExit(), "The new holder does not inherit the sender's delay");
|
||||
assertEquals(firstExit, f.state(first)); assertEquals(secondExit, f.state(second));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void cooldownExplainsRemainingSecondsAndSameCharacterBeforeEquipmentPreflight() throws Exception {
|
||||
try (var f = new Fixture()) {
|
||||
var actor = f.actor(); f.activate(actor);
|
||||
f.sessions.exit(actor.player);
|
||||
var exited = f.state(actor);
|
||||
var other = f.actor();
|
||||
actor.inventory.setItemInOffHand(other.inventory.getItemInOffHand().clone());
|
||||
// Both equipment checks would refuse too, but the switch explanation must win.
|
||||
for (int slot = 9; slot < 36; slot++) actor.inventory.setItem(slot, new ItemStack(Material.STONE, 64));
|
||||
actor.inventory.setItem(0, new ItemStack(Material.SHULKER_BOX));
|
||||
actor.cursor = new ItemStack(Material.EMERALD);
|
||||
var before = actor.snapshot(); var cursor = actor.cursor.clone(); var marker = actor.marker();
|
||||
for (int retry = 0; retry < 2; retry++) {
|
||||
f.sessions.enter(actor.player); f.tick();
|
||||
var notice = f.notices.getLast();
|
||||
assertEquals("COOLDOWN", notice.code());
|
||||
assertTrue(notice.message().matches("(?s).*Wait [1-9][0-9]* seconds.*"), notice::message);
|
||||
assertTrue(notice.message().contains("same character may be resumed now"), notice::message);
|
||||
assertArrayEquals(before, actor.snapshot()); assertEquals(cursor, actor.cursor);
|
||||
assertEquals(marker, actor.marker()); assertEquals(exited, f.state(actor));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test void zeroHealthLiveRecordCannotEnterAndNoReceiptIsInvented() throws Exception {
|
||||
try (var f = new Fixture()) {
|
||||
var actor = f.actor(); var old = actor.record;
|
||||
@@ -1107,8 +1372,10 @@ class EquipmentSessionsNativeTest {
|
||||
final CopyOnWriteArrayList<EquipmentSessions.Failure> failures = new CopyOnWriteArrayList<>();
|
||||
final ArrayList<EquipmentSessions.Notice> notices = new ArrayList<>();
|
||||
final CharacterStorage characters;
|
||||
final EquipmentSessionStore receipts;
|
||||
EquipmentSessionStore receipts;
|
||||
final Clock clock;
|
||||
EquipmentSessions sessions;
|
||||
games.dmg.fantasystick.presentation.SessionPresentation presentation = games.dmg.fantasystick.presentation.SessionPresentation.NONE;
|
||||
volatile boolean rejectSchedule;
|
||||
boolean receiptClosed;
|
||||
boolean characterClosed;
|
||||
@@ -1119,22 +1386,29 @@ class EquipmentSessionsNativeTest {
|
||||
Fixture(DiskMove move) throws Exception { this(move, Duration.ofSeconds(900)); }
|
||||
Fixture(DiskMove move, Duration delay) throws Exception { this(move, delay, EquipmentSessionsNativeTest::move); }
|
||||
Fixture(DiskMove move, Duration delay, DiskMove characterMove) throws Exception {
|
||||
this(move, delay, characterMove, Clock.systemUTC());
|
||||
}
|
||||
Fixture(Duration delay, Clock clock) throws Exception {
|
||||
this(EquipmentSessionsNativeTest::move, delay, EquipmentSessionsNativeTest::move, clock);
|
||||
}
|
||||
Fixture(DiskMove move, Duration delay, DiskMove characterMove, Clock clock) throws Exception {
|
||||
this.clock = clock;
|
||||
var characterSeam = Class.forName("games.dmg.fantasystick.persistence.YamlCharacterRepository$Replacement");
|
||||
var characterConstructor = YamlCharacterRepository.class.getDeclaredConstructor(Path.class, characterSeam);
|
||||
characterConstructor.setAccessible(true);
|
||||
Object characterReplacement = Proxy.newProxyInstance(characterSeam.getClassLoader(), new Class<?>[]{characterSeam},
|
||||
(proxy, method, args) -> { characterMove.move((Path) args[0], (Path) args[1]); return null; });
|
||||
characters = new CharacterStorage(characterConstructor.newInstance(data, characterReplacement), Clock.systemUTC());
|
||||
characters = new CharacterStorage(characterConstructor.newInstance(data, characterReplacement), clock);
|
||||
var seam = Class.forName("games.dmg.fantasystick.persistence.EquipmentSessionStore$Replacement");
|
||||
var constructor = EquipmentSessionStore.class.getDeclaredConstructor(Path.class, Clock.class, seam);
|
||||
constructor.setAccessible(true);
|
||||
Object replacement = Proxy.newProxyInstance(seam.getClassLoader(), new Class<?>[]{seam},
|
||||
(proxy, method, args) -> { move.move((Path) args[0], (Path) args[1]); return null; });
|
||||
receipts = constructor.newInstance(data, Clock.systemUTC(), replacement);
|
||||
receipts = constructor.newInstance(data, clock, replacement);
|
||||
sessions = coordinator(delay);
|
||||
}
|
||||
EquipmentSessions coordinator(Duration delay) {
|
||||
return new EquipmentSessions(characters, receipts, delay, task -> {
|
||||
return new EquipmentSessions(characters, receipts, delay, clock, task -> {
|
||||
if (rejectSchedule) throw new java.util.concurrent.RejectedExecutionException("test scheduler stopped");
|
||||
tasks.add(task);
|
||||
}, notice -> {
|
||||
@@ -1143,7 +1417,7 @@ class EquipmentSessionsNativeTest {
|
||||
}, failure -> {
|
||||
failures.add(failure);
|
||||
if (throwDiagnostic) throw new IllegalStateException("Injected diagnostic observer failure");
|
||||
});
|
||||
}, presentation);
|
||||
}
|
||||
Actor restart(Actor actor) throws Exception {
|
||||
state(actor); // Drain the owned store, then discard process-local coordinator proof (no orderly close).
|
||||
@@ -1151,6 +1425,14 @@ class EquipmentSessionsNativeTest {
|
||||
sessions = coordinator(Duration.ofSeconds(900));
|
||||
return actor.reload();
|
||||
}
|
||||
Actor reopen(Actor actor, Duration delay) throws Exception {
|
||||
sessions.close(); sessions.drained().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
state(actor); receipts.close();
|
||||
assertTrue(tasks.isEmpty());
|
||||
receipts = new EquipmentSessionStore(data, clock);
|
||||
sessions = coordinator(delay);
|
||||
return actor.reload();
|
||||
}
|
||||
Actor actor() throws Exception {
|
||||
var record = new CharacterFactory().create(ProgressionRules.defaults());
|
||||
characters.create(record).get(5, TimeUnit.SECONDS);
|
||||
@@ -1186,6 +1468,15 @@ class EquipmentSessionsNativeTest {
|
||||
}
|
||||
}
|
||||
|
||||
static final class MutableClock extends Clock {
|
||||
// Synthetic clock for exact boundaries, not a document/event timestamp.
|
||||
volatile java.time.Instant now = java.time.Instant.parse("2000-01-01T00:00:00.123456789Z");
|
||||
@Override public java.time.ZoneId getZone() { return java.time.ZoneOffset.UTC; }
|
||||
@Override public Clock withZone(java.time.ZoneId zone) { return this; }
|
||||
@Override public java.time.Instant instant() { return now; }
|
||||
void advance(Duration elapsed) { now = now.plus(elapsed); }
|
||||
}
|
||||
|
||||
@FunctionalInterface interface DiskMove { void move(Path source, Path target) throws java.io.IOException; }
|
||||
static void move(Path source, Path target) throws java.io.IOException {
|
||||
java.nio.file.Files.move(source, target, java.nio.file.StandardCopyOption.ATOMIC_MOVE, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import games.dmg.fantasystick.items.CharacterSheets;
|
||||
import games.dmg.fantasystick.persistence.CharacterStorage;
|
||||
@@ -46,6 +47,7 @@ class FantasyStickLifecycleNativeTest {
|
||||
try (var fixture = new Fixture(data)) {
|
||||
fixture.plugin.setEnabled(true);
|
||||
assertTrue(fixture.recipes.containsKey(CharacterSheets.RECIPE));
|
||||
assertTrue(fixture.plugin.getDescription().getDepend().contains("ProtocolLib"));
|
||||
int recipe = fixture.order.indexOf("recipe");
|
||||
assertTrue(fixture.order.indexOf("ManualCraftingController") >= 0);
|
||||
assertTrue(fixture.order.indexOf("ManualCraftingController") < recipe);
|
||||
@@ -53,6 +55,12 @@ class FantasyStickLifecycleNativeTest {
|
||||
assertTrue(fixture.order.indexOf("ManualCraftingGuard") < recipe);
|
||||
assertTrue(fixture.order.indexOf("EquipmentSessionEvents") >= 0);
|
||||
assertTrue(fixture.order.indexOf("EquipmentSessionEvents") < recipe);
|
||||
assertTrue(fixture.order.indexOf("ProtocolPresentation") >= 0);
|
||||
assertTrue(fixture.order.indexOf("ProtocolPresentation") < recipe);
|
||||
assertTrue(fixture.order.indexOf("CharacterChatNames") >= 0);
|
||||
assertTrue(fixture.order.indexOf("CharacterChatNames") < recipe);
|
||||
assertNotNull(fixture.packetListener);
|
||||
assertEquals(1, fixture.timers.size());
|
||||
assertNotNull(fixture.command);
|
||||
assertEquals("EquipmentAdminCommand", fixture.command.getExecutor().getClass().getSimpleName());
|
||||
assertTrue(fixture.tasks.isEmpty());
|
||||
@@ -76,6 +84,10 @@ class FantasyStickLifecycleNativeTest {
|
||||
.anyMatch(listener -> listener.getPlugin() == fixture.plugin));
|
||||
assertFalse(java.util.Arrays.stream(org.bukkit.event.block.CrafterCraftEvent.getHandlerList().getRegisteredListeners())
|
||||
.anyMatch(listener -> listener.getPlugin() == fixture.plugin));
|
||||
assertFalse(java.util.Arrays.stream(io.papermc.paper.event.player.AsyncChatEvent.getHandlerList().getRegisteredListeners())
|
||||
.anyMatch(listener -> listener.getPlugin() == fixture.plugin));
|
||||
verify(fixture.protocol).removePacketListener(fixture.packetListener);
|
||||
verify(fixture.timers.getFirst()).cancel();
|
||||
fixture.plugin.onDisable();
|
||||
assertSame(other, fixture.recipes.get(otherKey));
|
||||
}
|
||||
@@ -83,7 +95,7 @@ class FantasyStickLifecycleNativeTest {
|
||||
|
||||
@Test
|
||||
void recipeCollisionAndPartialListenerRegistrationFailureRollbackOnlyThisEnableAttempt() throws Exception {
|
||||
for (String stage : List.of("collision", "recipe", "ManualCraftingGuard", "CharacterAnvilNames", "EquipmentSessionEvents")) {
|
||||
for (String stage : List.of("collision", "recipe", "ManualCraftingGuard", "CharacterAnvilNames", "EquipmentSessionEvents", "CharacterChatNames", "ProtocolPresentation", "presentation-timer")) {
|
||||
boolean collision = stage.equals("collision");
|
||||
try (var fixture = new Fixture(data)) {
|
||||
var existing = new org.bukkit.inventory.ShapelessRecipe(CharacterSheets.RECIPE,
|
||||
@@ -101,6 +113,10 @@ class FantasyStickLifecycleNativeTest {
|
||||
.anyMatch(listener -> listener.getPlugin() == fixture.plugin));
|
||||
assertFalse(java.util.Arrays.stream(io.papermc.paper.event.player.PlayerInventorySlotChangeEvent.getHandlerList().getRegisteredListeners())
|
||||
.anyMatch(listener -> listener.getPlugin() == fixture.plugin));
|
||||
assertFalse(java.util.Arrays.stream(io.papermc.paper.event.player.AsyncChatEvent.getHandlerList().getRegisteredListeners())
|
||||
.anyMatch(listener -> listener.getPlugin() == fixture.plugin));
|
||||
verify(fixture.protocol).removePacketListener(fixture.packetListener);
|
||||
fixture.timers.forEach(timer -> verify(timer).cancel());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -307,7 +323,9 @@ class FantasyStickLifecycleNativeTest {
|
||||
var directory = data.resolve("death-" + disable);
|
||||
try (var f = new Fixture(directory)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new Actor(directory); f.players.put(a.core.id, a.player); f.activate(a);
|
||||
var a = new Actor(directory); f.players.put(a.core.id, a.player);
|
||||
var viewer = f.viewer(a, directory); f.activate(a);
|
||||
assertNativeName(f, a, viewer, a.core.record.name());
|
||||
var characters = (CharacterStorage) Fixture.field(f.plugin, "characters");
|
||||
var sessions = (games.dmg.fantasystick.session.EquipmentSessions) Fixture.field(f.plugin, "sessions");
|
||||
var worker = (java.util.concurrent.ExecutorService) Fixture.field(characters, "worker");
|
||||
@@ -327,6 +345,7 @@ class FantasyStickLifecycleNativeTest {
|
||||
try {
|
||||
f.dispatcher.accept(death);
|
||||
assertTrue(death.isCancelled()); assertFalse(death.getKeepInventory());
|
||||
assertRestored(f, a, viewer);
|
||||
assertEquals(a.core.normalMaximum, a.core.health);
|
||||
assertEquals(org.bukkit.Material.DIAMOND_SWORD, a.core.inventory.getItem(0).getType());
|
||||
assertEquals(sheet, a.core.inventory.getItemInOffHand());
|
||||
@@ -376,8 +395,12 @@ class FantasyStickLifecycleNativeTest {
|
||||
for (String route : List.of("removal", "swap", "quit", "disable")) {
|
||||
try (var f = new Fixture(data.resolve(route))) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new Actor(data.resolve(route)); f.players.put(a.core.id, a.player); f.activate(a);
|
||||
var a = new Actor(data.resolve(route)); f.players.put(a.core.id, a.player);
|
||||
var viewer = f.viewer(a, data.resolve(route)); f.activate(a);
|
||||
assertNativeName(f, a, viewer, a.core.record.name()); assertChat(f, a, a.core.record.name());
|
||||
var receipts = f.receipts();
|
||||
var session = receipts.find(a.core.id).toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS).orElseThrow().pending();
|
||||
var requested = java.time.Instant.now();
|
||||
if (route.equals("removal")) {
|
||||
a.core.cursor = a.core.inventory.getItemInOffHand().clone();
|
||||
a.core.inventory.setItemInOffHand(null); f.changed(a);
|
||||
@@ -388,6 +411,7 @@ class FantasyStickLifecycleNativeTest {
|
||||
} else if (route.equals("quit")) {
|
||||
f.dispatcher.accept(new org.bukkit.event.player.PlayerQuitEvent(a.player, (net.kyori.adventure.text.Component) null));
|
||||
} else { f.plugin.setEnabled(false); f.awaitWorkers(); }
|
||||
assertRestored(f, a, viewer);
|
||||
assertTrue(a.core.marker().endsWith("|RESTORED"));
|
||||
assertEquals(org.bukkit.Material.DIAMOND_HELMET, a.core.inventory.getHelmet().getType());
|
||||
assertEquals(org.bukkit.Material.DIAMOND_SWORD, route.equals("swap")
|
||||
@@ -399,7 +423,14 @@ class FantasyStickLifecycleNativeTest {
|
||||
while (!f.tasks.isEmpty()) f.tasks.remove().run();
|
||||
assertArrayEquals(restored, a.core.snapshot());
|
||||
try (var reopened = new games.dmg.fantasystick.persistence.EquipmentSessionStore(data.resolve(route), java.time.Clock.systemUTC())) {
|
||||
assertNull(reopened.find(a.core.id).toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS).orElseThrow().pending());
|
||||
var state = reopened.find(a.core.id).toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS).orElseThrow();
|
||||
assertNull(state.pending());
|
||||
var exit = state.lastExit();
|
||||
assertEquals(session.sessionId(), exit.sessionId()); assertEquals(a.core.record.id(), exit.characterId());
|
||||
assertFalse(exit.exitedAt().isBefore(requested)); assertFalse(exit.exitedAt().isAfter(java.time.Instant.now()));
|
||||
assertEquals(java.time.Duration.ofSeconds(900), java.time.Duration.between(exit.exitedAt(), exit.deadline()));
|
||||
assertEquals(state, reopened.completeExit(a.core.id, session.sessionId(), java.time.Duration.ofHours(1))
|
||||
.toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS), "Repeated lifecycle acknowledgment must not extend the delay");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -617,6 +648,23 @@ class FantasyStickLifecycleNativeTest {
|
||||
var exit = f.receipts().find(a.core.id).toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS).orElseThrow().lastExit();
|
||||
assertEquals(java.time.Duration.ofSeconds(value.equals("default") ? 900 : Long.parseLong(value)),
|
||||
java.time.Duration.between(exit.exitedAt(), exit.deadline()));
|
||||
assertEquals(a.core.record.id(), exit.characterId());
|
||||
var other = new Actor(directory);
|
||||
a.core.inventory.setItemInOffHand(other.core.inventory.getItemInOffHand().clone());
|
||||
var before = a.core.snapshot();
|
||||
f.dispatcher.accept(new org.bukkit.event.player.PlayerJoinEvent(a.player, (net.kyori.adventure.text.Component) null));
|
||||
f.tick(); f.tick(); // Join receipt reconciliation, then actual coordinator eligibility.
|
||||
if (value.equals("0")) {
|
||||
f.tick(); assertTrue(a.core.marker().endsWith("|PACKED"), "Configured zero reaches entry, not only persisted arithmetic");
|
||||
} else {
|
||||
assertArrayEquals(before, a.core.snapshot()); assertTrue(a.core.marker().endsWith("|RESTORED"));
|
||||
assertTrue(a.messages.getLast().matches("(?s).*Wait [1-9][0-9]* seconds.*same character may be resumed now.*"), a.messages::toString);
|
||||
var state = f.receipts().find(a.core.id).toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS).orElseThrow();
|
||||
assertNull(state.pending()); assertEquals(exit, state.lastExit());
|
||||
a.core.inventory.setItemInOffHand(new CharacterSheets().create(a.core.record));
|
||||
f.dispatcher.accept(new org.bukkit.event.player.PlayerJoinEvent(a.player, (net.kyori.adventure.text.Component) null));
|
||||
f.tick(); f.tick(); f.tick(); assertTrue(a.core.marker().endsWith("|PACKED"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -636,6 +684,142 @@ class FantasyStickLifecycleNativeTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test void presentationAndRemainingResourcesCloseEvenWhenEquipmentCleanupThrows() throws Exception {
|
||||
try (var f = new Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var actual = (games.dmg.fantasystick.session.EquipmentSessions) Fixture.field(f.plugin, "sessions");
|
||||
var broken = mock(games.dmg.fantasystick.session.EquipmentSessions.class, org.mockito.AdditionalAnswers.delegatesTo(actual));
|
||||
doAnswer(call -> { actual.close(); throw new IllegalStateException("Equipment cleanup failed"); }).when(broken).close();
|
||||
setField(f.plugin.getClass(), f.plugin, "sessions", broken);
|
||||
assertDoesNotThrow(() -> f.plugin.setEnabled(false));
|
||||
verify(f.protocol).removePacketListener(f.packetListener); verify(f.timers.getFirst()).cancel();
|
||||
assertFalse(f.recipes.containsKey(CharacterSheets.RECIPE));
|
||||
assertFalse(java.util.Arrays.stream(io.papermc.paper.event.player.AsyncChatEvent.getHandlerList().getRegisteredListeners())
|
||||
.anyMatch(listener -> listener.getPlugin() == f.plugin));
|
||||
assertNull(Fixture.field(f.plugin, "characters"));
|
||||
f.awaitWorkers();
|
||||
}
|
||||
}
|
||||
|
||||
@Test void assembledSessionUsesAuthoritativeUnicodeNameOnNativeOverheadTabAndChat() throws Exception {
|
||||
try (var f = new Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new Actor(data); var viewer = new Actor(data);
|
||||
viewer.core.inventory.setItemInOffHand(null);
|
||||
viewer.core.location.setWorld(a.core.location.getWorld());
|
||||
a.tracked.add(viewer.player);
|
||||
f.players.put(a.core.id, a.player); f.players.put(viewer.core.id, viewer.player);
|
||||
String saved = "勇者 🐉 <red>literal</red> longer than sixteen";
|
||||
var characters = (CharacterStorage) Fixture.field(f.plugin, "characters");
|
||||
characters.renameCharacter(a.core.record.id(), saved).get(5, java.util.concurrent.TimeUnit.SECONDS);
|
||||
f.activate(a); // Offhand still has its old physical name; YAML is authoritative.
|
||||
assertNativeName(f, a, viewer, saved);
|
||||
assertChat(f, a, saved);
|
||||
assertEquals("Account", a.player.getName()); assertEquals(a.core.id, a.player.getUniqueId());
|
||||
assertEquals(64, a.distance.getValue()); assertTrue(a.board.getPlayerTeams().isEmpty());
|
||||
verify(a.player, never()).setDisplayName(anyString());
|
||||
verify(a.player, never()).setPlayerListName(anyString());
|
||||
String renamed = "雪 🐈 renamed by another holder's copy";
|
||||
f.renameCopy(a, renamed);
|
||||
assertNativeName(f, a, viewer, saved); // No native mutation on the persistence worker.
|
||||
f.tick();
|
||||
assertNativeName(f, a, viewer, renamed); assertChat(f, a, renamed);
|
||||
assertEquals(renamed, new YamlCharacterRepository(data).load(a.core.record.id()).orElseThrow().name());
|
||||
assertTrue(f.presentationFailures.isEmpty(), f.presentationFailures::toString);
|
||||
}
|
||||
}
|
||||
|
||||
@Test void anvilAcknowledgmentFromDisabledLifetimeCannotReachReenabledPresentationAndRestartReadsSavedName() throws Exception {
|
||||
try (var f = new Fixture(data)) {
|
||||
f.plugin.setEnabled(true);
|
||||
var a = new Actor(data); f.players.put(a.core.id, a.player); var viewer = f.viewer(a, data); f.activate(a);
|
||||
var oldCharacters = (CharacterStorage) Fixture.field(f.plugin, "characters");
|
||||
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");
|
||||
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, java.util.concurrent.TimeUnit.SECONDS)); }
|
||||
catch (InterruptedException interrupted) { throw new AssertionError(interrupted); }
|
||||
});
|
||||
try {
|
||||
assertTrue(entered.await(5, java.util.concurrent.TimeUnit.SECONDS));
|
||||
f.renameCopy(a, "Late old-lifetime 雪 rename");
|
||||
var retiredListener = f.packetListener;
|
||||
f.plugin.setEnabled(false); assertRestored(f, a, viewer);
|
||||
oldSessions.drained().toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS);
|
||||
assertTrue(receiptWorker.awaitTermination(5, java.util.concurrent.TimeUnit.SECONDS));
|
||||
f.players.clear(); f.plugin.setEnabled(true);
|
||||
f.players.put(a.core.id, a.player); f.players.put(viewer.core.id, viewer.player); f.reenter(a);
|
||||
assertNativeName(f, a, viewer, a.core.record.name());
|
||||
int scheduled = f.schedulerCalls.get(); int packets = f.sent.size();
|
||||
release.countDown(); gate.get(5, java.util.concurrent.TimeUnit.SECONDS);
|
||||
assertTrue(worker.awaitTermination(5, java.util.concurrent.TimeUnit.SECONDS));
|
||||
assertEquals(scheduled, f.schedulerCalls.get(), "Old observer must capture its manager, not dereference the new plugin field");
|
||||
assertEquals(packets, f.sent.size()); assertTrue(f.tasks.isEmpty());
|
||||
assertChat(f, a, a.core.record.name());
|
||||
var ordinary = games.dmg.fantasystick.presentation.NativePresentationPackets.refreshTab(a.nativePlayer);
|
||||
var event = com.comphenix.protocol.events.PacketEvent.fromServer(this,
|
||||
new com.comphenix.protocol.events.PacketContainer(com.comphenix.protocol.PacketType.Play.Server.PLAYER_INFO, ordinary), viewer.player);
|
||||
retiredListener.onPacketSending(event); f.pulses.getFirst().run();
|
||||
assertSame(ordinary, event.getPacket().getHandle()); assertEquals(packets, f.sent.size());
|
||||
f.plugin.setEnabled(false); f.awaitWorkers();
|
||||
f.players.clear(); f.plugin.setEnabled(true);
|
||||
f.players.put(a.core.id, a.player); f.players.put(viewer.core.id, viewer.player); f.reenter(a);
|
||||
assertNativeName(f, a, viewer, "Late old-lifetime 雪 rename"); assertChat(f, a, "Late old-lifetime 雪 rename");
|
||||
assertTrue(f.presentationFailures.isEmpty(), f.presentationFailures::toString);
|
||||
} finally { release.countDown(); }
|
||||
}
|
||||
}
|
||||
|
||||
private static void assertNativeName(Fixture f, Actor a, Actor viewer, String name) {
|
||||
var tabs = f.packets(viewer.player, net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket.class);
|
||||
assertFalse(tabs.isEmpty(), "Assembled session must send native tab output, not merely catch a CraftPlayer failure");
|
||||
var tab = tabs.getLast();
|
||||
assertEquals(java.util.EnumSet.of(net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME), tab.actions());
|
||||
assertEquals(a.core.id, tab.entries().getFirst().profileId());
|
||||
assertEquals(net.minecraft.network.chat.Component.literal(name), tab.entries().getFirst().displayName());
|
||||
var spawn = f.packets(viewer.player, net.minecraft.network.protocol.game.ClientboundAddEntityPacket.class).getLast();
|
||||
assertEquals(net.minecraft.world.entity.EntityTypes.TEXT_DISPLAY, spawn.getType());
|
||||
var metadata = f.packets(viewer.player, net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket.class).getLast();
|
||||
assertEquals(spawn.getId(), metadata.id());
|
||||
assertTrue(metadata.packedItems().stream().anyMatch(value -> net.minecraft.network.chat.Component.literal(name).equals(value.value())));
|
||||
assertEquals(0, f.packets(viewer.player, net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket.class)
|
||||
.getFirst().getValues().getFirst().base());
|
||||
assertTrue(f.packets(a.player, net.minecraft.network.protocol.game.ClientboundAddEntityPacket.class).isEmpty());
|
||||
}
|
||||
|
||||
private static void assertRestored(Fixture f, Actor actor, Actor viewer) {
|
||||
var spawn = f.packets(viewer.player, net.minecraft.network.protocol.game.ClientboundAddEntityPacket.class).getLast();
|
||||
assertTrue(f.packets(viewer.player, net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket.class).stream()
|
||||
.anyMatch(packet -> packet.getEntityIds().contains(spawn.getId())));
|
||||
var tab = f.packets(viewer.player, net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket.class).getLast();
|
||||
assertEquals(net.minecraft.network.chat.Component.literal("Ordinary tab"), tab.entries().getFirst().displayName());
|
||||
var attributes = f.packets(viewer.player, net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket.class).getLast();
|
||||
assertEquals(64, attributes.getValues().getFirst().base());
|
||||
assertEquals(64, actor.distance.getValue()); assertChat(f, actor, null);
|
||||
assertTrue(f.presentationFailures.isEmpty(), f.presentationFailures::toString);
|
||||
}
|
||||
|
||||
private static void assertChat(Fixture f, Actor actor, String expected) {
|
||||
var body = net.kyori.adventure.text.Component.text("signed body <untouched>");
|
||||
var signed = net.kyori.adventure.chat.SignedMessage.system("signed body <untouched>", body);
|
||||
var viewers = new java.util.HashSet<net.kyori.adventure.audience.Audience>(); viewers.add(actor.player);
|
||||
io.papermc.paper.chat.ChatRenderer renderer = (sender, display, message, recipient) -> {
|
||||
assertSame(actor.player, sender); assertSame(body, message); assertSame(actor.player, recipient);
|
||||
return display.append(message);
|
||||
};
|
||||
var event = new io.papermc.paper.event.player.AsyncChatEvent(false, actor.player, viewers, renderer, body, body, signed);
|
||||
f.dispatcher.accept(event);
|
||||
assertSame(signed, event.signedMessage()); assertSame(body, event.message()); assertSame(body, event.originalMessage());
|
||||
assertEquals(viewers, event.viewers()); assertFalse(event.isCancelled());
|
||||
if (expected == null) assertSame(renderer, event.renderer());
|
||||
var ordinary = net.kyori.adventure.text.Component.text("Ordinary chat");
|
||||
assertEquals((expected == null ? ordinary : net.kyori.adventure.text.Component.text(expected)).append(body),
|
||||
event.renderer().render(actor.player, ordinary, body, actor.player));
|
||||
}
|
||||
|
||||
private static void awaitUnissuedRecordCleanup(Path directory) throws Exception {
|
||||
// The batch was ready before disable, so its cleanup was queued before shutdown.
|
||||
// Production disable remains nonblocking; only the test waits before deleting its fixture directory.
|
||||
@@ -655,6 +839,23 @@ class FantasyStickLifecycleNativeTest {
|
||||
final LinkedBlockingQueue<Runnable> tasks = new LinkedBlockingQueue<>();
|
||||
final java.util.concurrent.atomic.AtomicInteger schedulerCalls = new java.util.concurrent.atomic.AtomicInteger();
|
||||
final List<Listener> listeners = new ArrayList<>();
|
||||
final com.comphenix.protocol.ProtocolManager protocol = mock(com.comphenix.protocol.ProtocolManager.class);
|
||||
final org.mockito.MockedStatic<com.comphenix.protocol.ProtocolLibrary> protocolScope;
|
||||
final org.mockito.MockedStatic<org.bukkit.Bukkit> platform;
|
||||
final org.mockito.MockedStatic<io.papermc.paper.configuration.GlobalConfiguration> configScope;
|
||||
record Sent(org.bukkit.entity.Player viewer, Object packet) { }
|
||||
final List<Sent> sent = new ArrayList<>();
|
||||
final List<java.util.logging.LogRecord> presentationFailures = new java.util.concurrent.CopyOnWriteArrayList<>();
|
||||
final java.util.logging.Handler logHandler = new java.util.logging.Handler() {
|
||||
@Override public void publish(java.util.logging.LogRecord record) {
|
||||
if (record.getMessage().contains("presentation")) presentationFailures.add(record);
|
||||
}
|
||||
@Override public void flush() { }
|
||||
@Override public void close() { }
|
||||
};
|
||||
final List<BukkitTask> timers = new ArrayList<>();
|
||||
final List<Runnable> pulses = new ArrayList<>();
|
||||
com.comphenix.protocol.events.PacketListener packetListener;
|
||||
final List<java.util.concurrent.ExecutorService> workers = new ArrayList<>();
|
||||
final Thread main = Thread.currentThread();
|
||||
final Map<java.util.UUID, org.bukkit.entity.Player> players = new HashMap<>();
|
||||
@@ -668,6 +869,35 @@ class FantasyStickLifecycleNativeTest {
|
||||
final JavaPlugin plugin;
|
||||
|
||||
Fixture(Path data) throws Exception {
|
||||
protocolScope = mockStatic(com.comphenix.protocol.ProtocolLibrary.class);
|
||||
protocolScope.when(com.comphenix.protocol.ProtocolLibrary::getProtocolManager).thenReturn(protocol);
|
||||
var nativeServer = mock(org.bukkit.craftbukkit.CraftServer.class);
|
||||
platform = mockStatic(org.bukkit.Bukkit.class, call -> switch (call.getMethod().getName()) {
|
||||
case "getServer" -> nativeServer;
|
||||
case "isPrimaryThread" -> Thread.currentThread() == main;
|
||||
case "getVersion" -> "Purpur 2618 (MC: 26.2)";
|
||||
case "getMinecraftVersion" -> "26.2";
|
||||
case "getBukkitVersion" -> "26.2-R0.1-SNAPSHOT";
|
||||
default -> call.callRealMethod();
|
||||
});
|
||||
var config = new io.papermc.paper.configuration.GlobalConfiguration();
|
||||
config.anticheat = config.new Anticheat();
|
||||
config.anticheat.obfuscation = config.anticheat.new Obfuscation();
|
||||
config.anticheat.obfuscation.items = config.anticheat.obfuscation.new Items();
|
||||
config.anticheat.obfuscation.items.binding = mock(io.papermc.paper.util.sanitizer.ItemObfuscationBinding.class);
|
||||
setField(io.papermc.paper.util.sanitizer.ItemObfuscationBinding.class, config.anticheat.obfuscation.items.binding, "level",
|
||||
io.papermc.paper.util.sanitizer.ItemObfuscationSession.ObfuscationLevel.OVERSIZED);
|
||||
configScope = mockStatic(io.papermc.paper.configuration.GlobalConfiguration.class);
|
||||
configScope.when(io.papermc.paper.configuration.GlobalConfiguration::get).thenReturn(config);
|
||||
doAnswer(call -> {
|
||||
sent.add(new Sent(call.getArgument(0), ((com.comphenix.protocol.events.PacketContainer) call.getArgument(1)).getHandle()));
|
||||
return null;
|
||||
}).when(protocol).sendServerPacket(any(org.bukkit.entity.Player.class), any(com.comphenix.protocol.events.PacketContainer.class), eq(false));
|
||||
doAnswer(call -> {
|
||||
packetListener = call.getArgument(0); order.add("ProtocolPresentation");
|
||||
if ("ProtocolPresentation".equals(failRegistrationAt)) throw new IllegalStateException("Partial protocol registration");
|
||||
return null;
|
||||
}).when(protocol).addPacketListener(any());
|
||||
var manager = port(PluginManager.class, (name, args) -> switch (name) {
|
||||
case "registerEvents" -> {
|
||||
var listener = (Listener) args[0];
|
||||
@@ -682,6 +912,11 @@ class FantasyStickLifecycleNativeTest {
|
||||
default -> throw new AssertionError("Unexpected manager call " + name);
|
||||
});
|
||||
var scheduler = port(BukkitScheduler.class, (name, args) -> switch (name) {
|
||||
case "runTaskTimer" -> {
|
||||
if ("presentation-timer".equals(failRegistrationAt)) throw new IllegalStateException("Timer rejected");
|
||||
pulses.add((Runnable) args[1]);
|
||||
var timer = mock(BukkitTask.class); timers.add(timer); yield timer;
|
||||
}
|
||||
case "runTask" -> {
|
||||
schedulerCalls.incrementAndGet();
|
||||
assertTrue(((org.bukkit.plugin.Plugin) args[0]).isEnabled());
|
||||
@@ -715,6 +950,7 @@ class FantasyStickLifecycleNativeTest {
|
||||
dispatcher = new NativeEventDispatcher(server);
|
||||
loader = new Loader(server, data);
|
||||
plugin = (JavaPlugin) loader.loadClass("games.dmg.fantasystick.FantasyStickPlugin").getConstructor().newInstance();
|
||||
plugin.getLogger().addHandler(logHandler);
|
||||
var definition = plugin.getDescription().getCommands().get("fantasystick");
|
||||
if (definition != null) {
|
||||
// Bukkit normally constructs this from the packaged descriptor during plugin loading.
|
||||
@@ -728,6 +964,9 @@ class FantasyStickLifecycleNativeTest {
|
||||
}
|
||||
}
|
||||
|
||||
<T> List<T> packets(org.bukkit.entity.Player viewer, Class<T> type) {
|
||||
return sent.stream().filter(s -> s.viewer() == viewer && type.isInstance(s.packet())).map(s -> type.cast(s.packet())).toList();
|
||||
}
|
||||
private NativeEventDispatcher dispatcher() { return dispatcher; }
|
||||
games.dmg.fantasystick.persistence.EquipmentSessionStore receipts() {
|
||||
return (games.dmg.fantasystick.persistence.EquipmentSessionStore) field(plugin, "receipts");
|
||||
@@ -736,10 +975,29 @@ class FantasyStickLifecycleNativeTest {
|
||||
var task = tasks.poll(5, java.util.concurrent.TimeUnit.SECONDS);
|
||||
assertNotNull(task, "Missing deferred main-thread callback"); task.run();
|
||||
}
|
||||
void renameCopy(Actor actor, String name) throws Exception {
|
||||
var anvil = new CharacterAnvilNamesNativeTest.AnvilFixture();
|
||||
var sheet = new CharacterSheets().create(actor.core.record);
|
||||
var output = CharacterAnvilNamesNativeTest.named(sheet, net.kyori.adventure.text.Component.text(name));
|
||||
anvil.grid.setItem(0, sheet); anvil.grid.setItem(2, output);
|
||||
dispatcher.accept(new org.purpurmc.purpur.event.inventory.AnvilTakeResultEvent(anvil.actor.player, anvil.view, output));
|
||||
assertEquals(sheet, anvil.grid.getItem(0)); assertEquals(output, anvil.grid.getItem(2));
|
||||
}
|
||||
Actor viewer(Actor target, Path directory) throws Exception {
|
||||
var viewer = new Actor(directory); viewer.core.inventory.setItemInOffHand(null);
|
||||
viewer.core.location.setWorld(target.core.location.getWorld()); target.tracked.add(viewer.player);
|
||||
players.put(viewer.core.id, viewer.player); return viewer;
|
||||
}
|
||||
void changed(Actor actor) {
|
||||
dispatcher.accept(new io.papermc.paper.event.player.PlayerInventorySlotChangeEvent(actor.player, 40,
|
||||
new org.bukkit.inventory.ItemStack(org.bukkit.Material.AIR), actor.core.inventory.getItemInOffHand()));
|
||||
}
|
||||
void reenter(Actor actor) throws Exception {
|
||||
// A restored-marker observation is deliberately not itself a fresh entry request.
|
||||
var sheet = actor.core.inventory.getItemInOffHand().clone();
|
||||
actor.core.inventory.setItemInOffHand(null); changed(actor);
|
||||
actor.core.inventory.setItemInOffHand(sheet); activate(actor);
|
||||
}
|
||||
void activate(Actor actor) throws Exception {
|
||||
changed(actor); tick(); tick(); tick();
|
||||
assertTrue(actor.core.marker().endsWith("|PACKED"));
|
||||
@@ -766,7 +1024,10 @@ class FantasyStickLifecycleNativeTest {
|
||||
}
|
||||
@Override public void close() throws IOException {
|
||||
try { plugin.setEnabled(false); awaitWorkers(); }
|
||||
finally { HandlerList.unregisterAll(plugin); loader.close(); }
|
||||
finally {
|
||||
HandlerList.unregisterAll(plugin); plugin.getLogger().removeHandler(logHandler);
|
||||
loader.close(); configScope.close(); platform.close(); protocolScope.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -775,21 +1036,58 @@ class FantasyStickLifecycleNativeTest {
|
||||
final EquipmentSessionsNativeTest.Actor core;
|
||||
final List<String> messages = new ArrayList<>();
|
||||
final List<Integer> particles = new ArrayList<>();
|
||||
final org.bukkit.entity.Player player;
|
||||
final org.bukkit.craftbukkit.entity.CraftPlayer player;
|
||||
final net.minecraft.server.level.ServerPlayer nativePlayer = mock(net.minecraft.server.level.ServerPlayer.class);
|
||||
final net.minecraft.world.entity.ai.attributes.AttributeInstance distance = new net.minecraft.world.entity.ai.attributes.AttributeInstance(
|
||||
net.minecraft.world.entity.ai.attributes.Attributes.NAME_TAG_DISTANCE, ignored -> {});
|
||||
final java.util.Set<org.bukkit.entity.Player> tracked = new java.util.HashSet<>();
|
||||
final net.minecraft.world.scores.Scoreboard board = new net.minecraft.world.scores.Scoreboard();
|
||||
Actor(Path data) throws Exception {
|
||||
var record = new games.dmg.fantasystick.crafting.CharacterFactory()
|
||||
.create(games.dmg.fantasystick.progression.ProgressionRules.defaults());
|
||||
new games.dmg.fantasystick.persistence.YamlCharacterRepository(data).create(record);
|
||||
core = new EquipmentSessionsNativeTest.Actor(record);
|
||||
player = (org.bukkit.entity.Player) Proxy.newProxyInstance(org.bukkit.entity.Player.class.getClassLoader(),
|
||||
new Class<?>[]{org.bukkit.entity.Player.class}, (proxy, method, args) -> {
|
||||
assertSame(core.main, Thread.currentThread(), "Worker accessed Player: " + method.getName());
|
||||
return switch (method.getName()) {
|
||||
case "sendMessage" -> { messages.add((String) args[0]); yield null; }
|
||||
case "spawnParticle" -> { particles.add((Integer) args[2]); yield null; }
|
||||
default -> Proxy.getInvocationHandler(core.player).invoke(core.player, method, args);
|
||||
};
|
||||
});
|
||||
var craftBoard = mock(org.bukkit.craftbukkit.scoreboard.CraftScoreboard.class);
|
||||
when(craftBoard.getHandle()).thenReturn(board);
|
||||
player = mock(org.bukkit.craftbukkit.entity.CraftPlayer.class, call -> {
|
||||
var method = call.getMethod(); var args = call.getArguments();
|
||||
assertSame(core.main, Thread.currentThread(), "Worker accessed Player: " + method.getName());
|
||||
return switch (method.getName()) {
|
||||
case "hashCode" -> System.identityHashCode(call.getMock());
|
||||
case "equals" -> call.getMock() == args[0];
|
||||
case "getHandle" -> nativePlayer;
|
||||
case "getEntityId" -> 42;
|
||||
case "getName" -> "Account";
|
||||
case "getWorld" -> core.location.getWorld();
|
||||
case "getHeight" -> 1.8;
|
||||
case "getTrackedBy" -> tracked;
|
||||
case "canSee" -> true;
|
||||
case "getGameMode" -> org.bukkit.GameMode.SURVIVAL;
|
||||
case "isSneaking", "isInvisible" -> false;
|
||||
case "getScoreboard" -> craftBoard;
|
||||
case "sendMessage" -> { messages.add((String) args[0]); yield null; }
|
||||
case "spawnParticle" -> { particles.add((Integer) args[2]); yield null; }
|
||||
default -> Proxy.getInvocationHandler(core.player).invoke(core.player, method, args);
|
||||
};
|
||||
});
|
||||
core.location.setWorld(mock(org.bukkit.World.class));
|
||||
when(nativePlayer.getId()).thenReturn(42);
|
||||
when(nativePlayer.getUUID()).thenReturn(core.id);
|
||||
when(nativePlayer.getTabListDisplayName()).thenReturn(net.minecraft.network.chat.Component.literal("Ordinary tab"));
|
||||
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);
|
||||
when(nativePlayer.level()).thenReturn(level);
|
||||
var worldConfig = mock(io.papermc.paper.configuration.WorldConfiguration.class);
|
||||
worldConfig.entities = allocate(io.papermc.paper.configuration.WorldConfiguration.Entities.class);
|
||||
worldConfig.entities.spawning = allocate(io.papermc.paper.configuration.WorldConfiguration.Entities.Spawning.class);
|
||||
worldConfig.entities.spawning.despawnTime = new it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap<>();
|
||||
when(level.paperConfig()).thenReturn(worldConfig);
|
||||
setField(net.minecraft.world.level.Level.class, level, "spigotConfig", allocate(org.spigotmc.SpigotWorldConfig.class));
|
||||
var purpur = allocate(org.purpurmc.purpur.PurpurWorldConfig.class); purpur.drowningAirTicks = 300;
|
||||
setField(net.minecraft.world.level.Level.class, level, "purpurConfig", purpur);
|
||||
var ids = new java.util.concurrent.atomic.AtomicInteger(100);
|
||||
when(level.getNextEntityId()).thenAnswer(call -> ids.incrementAndGet());
|
||||
var grid = new ManualCraftPlanNativeTest.Fixture(2, 1).grid;
|
||||
core.view = new org.bukkit.craftbukkit.inventory.CraftAbstractInventoryView() {
|
||||
@Override public org.bukkit.inventory.Inventory getTopInventory() { return grid; }
|
||||
@@ -844,6 +1142,15 @@ class FantasyStickLifecycleNativeTest {
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> T allocate(Class<T> type) throws Exception {
|
||||
var unsafe = Class.forName("sun.misc.Unsafe");
|
||||
var field = unsafe.getDeclaredField("theUnsafe"); field.setAccessible(true);
|
||||
return type.cast(unsafe.getMethod("allocateInstance", Class.class).invoke(field.get(null), type));
|
||||
}
|
||||
private static void setField(Class<?> owner, Object target, String name, Object value) throws Exception {
|
||||
var field = owner.getDeclaredField(name); field.setAccessible(true); field.set(target, value);
|
||||
}
|
||||
|
||||
@FunctionalInterface interface Call { Object invoke(String name, Object[] args); }
|
||||
static <T> T port(Class<T> type, Call call) {
|
||||
return type.cast(Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] {type}, (object, method, args) -> {
|
||||
|
||||
@@ -0,0 +1,536 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import com.google.common.collect.ImmutableMultimap;
|
||||
import com.mojang.authlib.GameProfile;
|
||||
import com.mojang.authlib.properties.Property;
|
||||
import com.mojang.authlib.properties.PropertyMap;
|
||||
import games.dmg.fantasystick.presentation.NativePresentationPackets;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.time.Instant;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.RemoteChatSession;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket.Action;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket.Entry;
|
||||
import net.minecraft.world.entity.player.ProfilePublicKey;
|
||||
import net.minecraft.world.level.GameType;
|
||||
import org.bukkit.craftbukkit.CraftRegistry;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class NativePresentationPacketsTest {
|
||||
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
|
||||
|
||||
private io.papermc.paper.configuration.GlobalConfiguration previousConfig;
|
||||
|
||||
@org.junit.jupiter.api.BeforeEach
|
||||
void metadataSerializationConfig() throws Exception {
|
||||
// Pinned metadata encoding opens Paper's item-obfuscation scope even for TextDisplay.
|
||||
// Install only this test JVM's default binding, and restore the previous global afterward.
|
||||
previousConfig = io.papermc.paper.configuration.GlobalConfiguration.get();
|
||||
var config = new io.papermc.paper.configuration.GlobalConfiguration();
|
||||
config.anticheat = config.new Anticheat();
|
||||
config.anticheat.obfuscation = config.anticheat.new Obfuscation();
|
||||
config.anticheat.obfuscation.items = config.anticheat.obfuscation.new Items();
|
||||
var binding = allocate(io.papermc.paper.util.sanitizer.ItemObfuscationBinding.class);
|
||||
setField(io.papermc.paper.util.sanitizer.ItemObfuscationBinding.class, binding, "level",
|
||||
io.papermc.paper.util.sanitizer.ItemObfuscationSession.ObfuscationLevel.OVERSIZED);
|
||||
config.anticheat.obfuscation.items.binding = binding;
|
||||
setField(io.papermc.paper.configuration.GlobalConfiguration.class, null, "instance", config);
|
||||
}
|
||||
|
||||
@org.junit.jupiter.api.AfterEach
|
||||
void restoreSerializationConfig() throws Exception {
|
||||
setField(io.papermc.paper.configuration.GlobalConfiguration.class, null, "instance", previousConfig);
|
||||
}
|
||||
|
||||
@Test
|
||||
void projectsOnlyActiveDisplayNameAndPreservesEveryNativeEntryFieldThroughTheWire() throws Exception {
|
||||
var active = entry("AccountOne", false, 217, GameType.SPECTATOR, false, 43);
|
||||
var ordinary = entry("AccountTwo", true, 7, GameType.CREATIVE, true, 81);
|
||||
var actions = EnumSet.allOf(Action.class);
|
||||
var original = new ClientboundPlayerInfoUpdatePacket(actions, List.of(active, ordinary));
|
||||
String name = "勇者 🧙🏽♀️ e\u0301 <red>literal</red> §a " + "長い名前".repeat(40);
|
||||
|
||||
var projected = NativePresentationPackets.projectPlayerInfo(original, active.profileId(), name);
|
||||
|
||||
assertEquals(Component.literal(name), projected.entries().getFirst().displayName(),
|
||||
"Character names are full literal Unicode components, not account/profile replacements");
|
||||
assertNotSame(original, projected);
|
||||
assertEquals(actions, projected.actions());
|
||||
assertEquals(EnumSet.allOf(Action.class), original.actions());
|
||||
assertSame(active, original.entries().getFirst());
|
||||
assertSame(ordinary, projected.entries().get(1));
|
||||
assertSame(active.profile(), projected.entries().getFirst().profile());
|
||||
assertSame(active.chatSession(), projected.entries().getFirst().chatSession());
|
||||
assertEquals(Component.literal("Ordinary AccountOne"), active.displayName());
|
||||
|
||||
var decoded = roundTrip(projected);
|
||||
assertEquals(actions, decoded.actions());
|
||||
assertEquals(2, decoded.entries().size());
|
||||
assertPreserved(active, decoded.entries().getFirst(), Component.literal(name));
|
||||
assertPreserved(ordinary, decoded.entries().get(1), ordinary.displayName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void attributesSuppressOnlySelectedNativeSnapshotAndNeverMutateOriginalInstances() {
|
||||
var distance = attribute(net.minecraft.world.entity.ai.attributes.Attributes.NAME_TAG_DISTANCE, 57.25);
|
||||
var speed = attribute(net.minecraft.world.entity.ai.attributes.Attributes.MOVEMENT_SPEED, 0.37);
|
||||
var original = new net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket(81, List.of(speed, distance));
|
||||
var projected = NativePresentationPackets.projectAttributes(original, 81);
|
||||
var decoded = wire(net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket.STREAM_CODEC, projected);
|
||||
assertNotSame(original, projected);
|
||||
assertEquals(81, decoded.getEntityId());
|
||||
assertEquals(2, decoded.getValues().size());
|
||||
assertSame(original.getValues().getFirst(), projected.getValues().getFirst());
|
||||
assertEquals(speed.getAttribute(), decoded.getValues().getFirst().attribute());
|
||||
assertEquals(speed.getBaseValue(), decoded.getValues().getFirst().base());
|
||||
assertEquals(speed.getModifiers(), java.util.Set.copyOf(decoded.getValues().getFirst().modifiers()));
|
||||
assertEquals(0, decoded.getValues().get(1).base());
|
||||
assertTrue(decoded.getValues().get(1).modifiers().isEmpty());
|
||||
assertEquals(57.25, original.getValues().get(1).base());
|
||||
assertEquals(3, original.getValues().get(1).modifiers().size());
|
||||
assertEquals(57.25, distance.getBaseValue());
|
||||
assertEquals(3, distance.getModifiers().size());
|
||||
assertSame(original, NativePresentationPackets.projectAttributes(original, 82));
|
||||
var absent = new net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket(81, List.of(speed));
|
||||
assertSame(absent, NativePresentationPackets.projectAttributes(absent, 81));
|
||||
var suppression = wire(net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket.STREAM_CODEC,
|
||||
NativePresentationPackets.suppressNameTag(81));
|
||||
assertEquals(81, suppression.getEntityId());
|
||||
assertEquals(1, suppression.getValues().size());
|
||||
assertEquals(net.minecraft.world.entity.ai.attributes.Attributes.NAME_TAG_DISTANCE, suppression.getValues().getFirst().attribute());
|
||||
assertEquals(0, suppression.getValues().getFirst().base());
|
||||
assertTrue(suppression.getValues().getFirst().modifiers().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restorationSnapshotsCurrentAuthoritativeAttributeAndRefusesMissingNativeSupport() throws Exception {
|
||||
var player = player();
|
||||
var distance = player.distance;
|
||||
var modifiers = java.util.Set.copyOf(distance.getModifiers());
|
||||
var first = NativePresentationPackets.restoreNameTag(player);
|
||||
distance.setBaseValue(13.75);
|
||||
distance.removeModifiers();
|
||||
var decodedFirst = wire(net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket.STREAM_CODEC, first);
|
||||
assertEquals(player.getId(), decodedFirst.getEntityId());
|
||||
assertEquals(1, decodedFirst.getValues().size());
|
||||
assertEquals(57.25, decodedFirst.getValues().getFirst().base());
|
||||
assertEquals(modifiers, java.util.Set.copyOf(decodedFirst.getValues().getFirst().modifiers()));
|
||||
var latest = wire(net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket.STREAM_CODEC,
|
||||
NativePresentationPackets.restoreNameTag(player));
|
||||
assertEquals(13.75, latest.getValues().getFirst().base());
|
||||
assertTrue(latest.getValues().getFirst().modifiers().isEmpty());
|
||||
assertEquals(13.75, distance.getBaseValue());
|
||||
assertTrue(distance.getModifiers().isEmpty());
|
||||
player.distance = null;
|
||||
assertThrows(IllegalStateException.class, () -> NativePresentationPackets.restoreNameTag(player));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tabRefreshUsesCurrentOrdinaryComponentIncludingNullAndOnlyDisplayAction() throws Exception {
|
||||
var player = player();
|
||||
var id = player.getUUID();
|
||||
player.ordinary = Component.literal("Ordinary 🐈").withStyle(net.minecraft.ChatFormatting.GOLD);
|
||||
var first = NativePresentationPackets.refreshTab(player);
|
||||
player.ordinary = Component.literal("New ordinary");
|
||||
var decoded = roundTrip(first);
|
||||
assertEquals(EnumSet.of(Action.UPDATE_DISPLAY_NAME), decoded.actions());
|
||||
assertEquals(1, decoded.entries().size());
|
||||
assertEquals(id, decoded.entries().getFirst().profileId());
|
||||
assertEquals(Component.literal("Ordinary 🐈").withStyle(net.minecraft.ChatFormatting.GOLD), decoded.entries().getFirst().displayName());
|
||||
assertEquals(player.ordinary, roundTrip(NativePresentationPackets.refreshTab(player)).entries().getFirst().displayName());
|
||||
player.ordinary = null;
|
||||
assertNull(roundTrip(NativePresentationPackets.refreshTab(player)).entries().getFirst().displayName());
|
||||
assertEquals(id, player.getUUID());
|
||||
assertEquals(57.25, player.distance.getBaseValue());
|
||||
assertEquals(3, player.distance.getModifiers().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tabProjectionNeverBroadensActionsOrChangesUnrelatedIdentities() throws Exception {
|
||||
var active = entry("Account", true, 9, GameType.SURVIVAL, true, 8);
|
||||
for (var action : Action.values()) {
|
||||
var original = new ClientboundPlayerInfoUpdatePacket(EnumSet.of(action), List.of(active));
|
||||
var projected = NativePresentationPackets.projectPlayerInfo(original, active.profileId(), "角色");
|
||||
if (action == Action.UPDATE_DISPLAY_NAME) {
|
||||
var expected = EnumSet.of(action, Action.UPDATE_DISPLAY_NAME);
|
||||
assertEquals(expected, roundTrip(projected).actions());
|
||||
assertEquals(Component.literal("角色"), roundTrip(projected).entries().getFirst().displayName());
|
||||
} else {
|
||||
assertSame(original, projected, action.name());
|
||||
}
|
||||
assertEquals(EnumSet.of(action), original.actions());
|
||||
assertSame(original, NativePresentationPackets.projectPlayerInfo(original, UUID.randomUUID(), "Other"));
|
||||
}
|
||||
var empty = new ClientboundPlayerInfoUpdatePacket(EnumSet.noneOf(Action.class), List.of(active));
|
||||
assertSame(empty, NativePresentationPackets.projectPlayerInfo(empty, active.profileId(), "Ignored"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mixedAddOnlyRetainsOriginalActionsAndEveryEntryField() throws Exception {
|
||||
var active = entry("Account", false, 97, GameType.SPECTATOR, false, 13);
|
||||
var unrelated = entry("Unrelated", true, 42, GameType.CREATIVE, true, 9);
|
||||
var original = new ClientboundPlayerInfoUpdatePacket(EnumSet.of(Action.ADD_PLAYER), List.of(active, unrelated));
|
||||
var projected = NativePresentationPackets.projectPlayerInfo(original, active.profileId(), "Character");
|
||||
assertEquals(EnumSet.of(Action.ADD_PLAYER), roundTrip(projected).actions(),
|
||||
"Adding UPDATE_DISPLAY_NAME would serialize the unrelated entry's currently irrelevant display component");
|
||||
assertSame(original, projected);
|
||||
assertEquals(List.of(active, unrelated), projected.entries());
|
||||
}
|
||||
|
||||
@Test
|
||||
void detachedLabelSpawnsWithNativeIdsAndCompleteTextDisplaySchemaForEveryViewer() throws Exception {
|
||||
var player = player();
|
||||
var level = level();
|
||||
player.world = level;
|
||||
int before = level.getNextEntityId();
|
||||
level.chunks.rejectNext = true; // Exercise the real allocator's existing-ID collision check.
|
||||
String text = "勇者 🧙🏽♀️ e\u0301 <red>literal</red> §a " + "長い名前".repeat(80);
|
||||
var label = NativePresentationPackets.createLabel(player, text, 12.25, 89.125, -3.75);
|
||||
assertTrue(label.id() > before + 1, "Native allocator skips an occupied ID");
|
||||
assertEquals(3, level.chunks.checks);
|
||||
int after = level.getNextEntityId();
|
||||
assertTrue(after > label.id());
|
||||
var spawn = wire(net.minecraft.network.protocol.game.ClientboundAddEntityPacket.STREAM_CODEC, label.spawn());
|
||||
assertEquals(label.id(), spawn.getId());
|
||||
assertEquals(label.uuid(), spawn.getUUID());
|
||||
assertNotEquals(player.getUUID(), label.uuid());
|
||||
assertEquals(net.minecraft.world.entity.EntityTypes.TEXT_DISPLAY, spawn.getType());
|
||||
assertEquals(12.25, spawn.getX());
|
||||
assertEquals(89.125, spawn.getY());
|
||||
assertEquals(-3.75, spawn.getZ());
|
||||
assertEquals(net.minecraft.world.phys.Vec3.ZERO, spawn.getMovement());
|
||||
assertEquals(0, spawn.getData());
|
||||
assertEquals(0, spawn.getXRot());
|
||||
assertEquals(0, spawn.getYRot());
|
||||
assertEquals(0, spawn.getYHeadRot());
|
||||
|
||||
var metadata = wire(net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket.STREAM_CODEC, label.metadata());
|
||||
var nextViewer = wire(net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket.STREAM_CODEC, label.metadata());
|
||||
assertEquals(label.id(), metadata.id());
|
||||
assertEquals(metadata, nextViewer, "Metadata is a full repeatable snapshot, never packDirty");
|
||||
var receiver = new net.minecraft.world.entity.Display.TextDisplay(net.minecraft.world.entity.EntityTypes.TEXT_DISPLAY, level);
|
||||
assertEquals(receiver.getEntityData().packAll().size(), metadata.packedItems().size());
|
||||
receiver.getEntityData().assignValues(metadata.packedItems());
|
||||
assertEquals(Component.literal(text), receiver.getText());
|
||||
assertEquals(net.minecraft.world.entity.Display.BillboardConstraints.CENTER, receiver.getBillboardConstraints());
|
||||
assertEquals(Integer.MAX_VALUE, receiver.getLineWidth());
|
||||
assertEquals((byte) -1, receiver.getTextOpacity());
|
||||
assertEquals(net.minecraft.world.entity.Display.TextDisplay.FLAG_SHADOW
|
||||
| net.minecraft.world.entity.Display.TextDisplay.FLAG_USE_DEFAULT_BACKGROUND, receiver.getFlags());
|
||||
assertEquals(0, receiver.getFlags() & net.minecraft.world.entity.Display.TextDisplay.FLAG_SEE_THROUGH);
|
||||
assertTrue(receiver.isNoGravity());
|
||||
assertEquals(0, receiver.getShadowRadius());
|
||||
assertEquals(0, receiver.getWidth());
|
||||
assertEquals(0, receiver.getHeight());
|
||||
assertEquals(57.25, player.distance.getBaseValue());
|
||||
assertEquals(3, player.distance.getModifiers().size());
|
||||
|
||||
// White-box safety invariant only: the opaque session handle cannot expose/register this entity.
|
||||
var field = label.getClass().getDeclaredField("display");
|
||||
field.setAccessible(true);
|
||||
var detached = (net.minecraft.world.entity.Display.TextDisplay) field.get(label);
|
||||
assertFalse(detached.persist);
|
||||
assertFalse(detached.valid);
|
||||
assertFalse(detached.isRemoved());
|
||||
assertSame(level, detached.level());
|
||||
}
|
||||
|
||||
@Test
|
||||
void labelMoveRenameAndRemoveSerializeWithoutChangingIdentityOrAuthoritativeState() throws Exception {
|
||||
var player = player();
|
||||
player.world = level();
|
||||
var label = NativePresentationPackets.createLabel(player, "Old", 1, 2, 3);
|
||||
var other = NativePresentationPackets.createLabel(player, "Other", 4, 5, 6);
|
||||
assertNotEquals(label.id(), other.id());
|
||||
assertNotEquals(label.uuid(), other.uuid());
|
||||
var id = label.id();
|
||||
var uuid = label.uuid();
|
||||
int allocated = player.world.chunks.checks;
|
||||
var originalMetadata = label.metadata();
|
||||
var move = wire(net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket.STREAM_CODEC,
|
||||
label.move(-17.625, 193.125, 4.5));
|
||||
assertEquals(id, move.id());
|
||||
assertEquals(new net.minecraft.world.phys.Vec3(-17.625, 193.125, 4.5), move.change().position());
|
||||
assertEquals(net.minecraft.world.phys.Vec3.ZERO, move.change().deltaMovement());
|
||||
assertEquals(0, move.change().xRot());
|
||||
assertEquals(0, move.change().yRot());
|
||||
assertTrue(move.relatives().isEmpty());
|
||||
assertFalse(move.onGround());
|
||||
var lateSpawn = wire(net.minecraft.network.protocol.game.ClientboundAddEntityPacket.STREAM_CODEC, label.spawn());
|
||||
assertEquals(-17.625, lateSpawn.getX());
|
||||
assertEquals(193.125, lateSpawn.getY());
|
||||
assertEquals(4.5, lateSpawn.getZ());
|
||||
String name = "改名 🌈 e\u0301 <bold>literal</bold>";
|
||||
var renamed = wire(net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket.STREAM_CODEC, label.rename(name));
|
||||
assertEquals(id, renamed.id());
|
||||
assertEquals(renamed, wire(net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket.STREAM_CODEC, label.metadata()));
|
||||
var changed = new java.util.ArrayList<net.minecraft.network.syncher.SynchedEntityData.DataValue<?>>();
|
||||
for (int index = 0; index < renamed.packedItems().size(); index++) {
|
||||
var value = renamed.packedItems().get(index);
|
||||
if (!value.equals(originalMetadata.packedItems().get(index))) { changed.add(value); }
|
||||
}
|
||||
assertEquals(1, changed.size(), "Rename changes only literal text, not any other native field");
|
||||
assertSame(net.minecraft.network.syncher.EntityDataSerializers.COMPONENT, changed.getFirst().serializer());
|
||||
assertEquals(Component.literal(name), changed.getFirst().value());
|
||||
assertEquals(Component.literal("Old"), originalMetadata.packedItems().stream()
|
||||
.filter(value -> value.id() == changed.getFirst().id()).findFirst().orElseThrow().value());
|
||||
var removal = wire(net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket.STREAM_CODEC, label.remove());
|
||||
assertArrayEquals(new int[] {id}, removal.getEntityIds().toIntArray());
|
||||
assertArrayEquals(new int[] {id}, label.remove().getEntityIds().toIntArray());
|
||||
assertEquals(id, label.id());
|
||||
assertEquals(uuid, label.uuid());
|
||||
assertEquals(allocated, player.world.chunks.checks, "Updates and removals never allocate replacement IDs");
|
||||
assertEquals(4, other.spawn().getX());
|
||||
assertEquals(5, other.spawn().getY());
|
||||
assertEquals(6, other.spawn().getZ());
|
||||
assertEquals(57.25, player.distance.getBaseValue());
|
||||
assertEquals(3, player.distance.getModifiers().size());
|
||||
var field = label.getClass().getDeclaredField("display");
|
||||
field.setAccessible(true);
|
||||
var detached = (net.minecraft.world.entity.Display.TextDisplay) field.get(label);
|
||||
assertFalse(detached.persist);
|
||||
assertFalse(detached.valid);
|
||||
assertFalse(detached.isRemoved(), "Client removal must not invoke native discard/remove");
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidLabelInputsFailBeforeAllocationOrMutationAndMissingWorldIsUnsupported() throws Exception {
|
||||
var player = player();
|
||||
player.world = level();
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> NativePresentationPackets.createLabel(player, "Name", Double.NaN, 1, 2));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> NativePresentationPackets.createLabel(player, "Name", 1, Double.POSITIVE_INFINITY, 2));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> NativePresentationPackets.createLabel(player, "Name", 1, 2, Double.NEGATIVE_INFINITY));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> NativePresentationPackets.createLabel(player, null, 1, 2, 3));
|
||||
assertEquals(0, player.world.chunks.checks);
|
||||
var label = NativePresentationPackets.createLabel(player, "Unchanged", 1, 2, 3);
|
||||
var metadata = label.metadata();
|
||||
assertThrows(IllegalArgumentException.class, () -> label.move(Double.NaN, 6, 7));
|
||||
assertThrows(IllegalArgumentException.class, () -> label.move(5, Double.NEGATIVE_INFINITY, 7));
|
||||
assertThrows(IllegalArgumentException.class, () -> label.move(5, 6, Double.POSITIVE_INFINITY));
|
||||
assertThrows(IllegalArgumentException.class, () -> label.rename(null));
|
||||
assertEquals(metadata, label.metadata());
|
||||
assertEquals(1, label.spawn().getX());
|
||||
assertEquals(2, label.spawn().getY());
|
||||
assertEquals(3, label.spawn().getZ());
|
||||
assertEquals(1, player.world.chunks.checks);
|
||||
player.world = null;
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> NativePresentationPackets.createLabel(player, "Name", 1, 2, 3));
|
||||
assertDoesNotThrow(() -> wire(net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket.STREAM_CODEC,
|
||||
label.rename("")), "Empty literal text is valid; it is not an account-name restriction");
|
||||
}
|
||||
|
||||
@Test
|
||||
void allPresentationOperationsPreserveNativeAccountUuidTeamAndInventoryAcrossWorldChange() throws Exception {
|
||||
var player = player();
|
||||
player.world = level();
|
||||
var oldLevel = player.world;
|
||||
var id = player.getUUID();
|
||||
var entityId = player.getId();
|
||||
var profile = player.getGameProfile();
|
||||
var team = player.board.addPlayerTeam("ordinary-team");
|
||||
team.setPlayerPrefix(Component.literal("[Ordinary]"));
|
||||
team.setNameTagVisibility(net.minecraft.world.scores.Team.Visibility.HIDE_FOR_OTHER_TEAMS);
|
||||
player.board.addPlayerToTeam(profile.name(), team);
|
||||
var members = java.util.Set.copyOf(team.getPlayers());
|
||||
var prefix = team.getPlayerPrefix().copy();
|
||||
var stack = new net.minecraft.world.item.ItemStack(net.minecraft.world.item.Items.DIAMOND, 23);
|
||||
stack.set(net.minecraft.core.component.DataComponents.CUSTOM_NAME, Component.literal("Do not change 🐈"));
|
||||
player.getInventory().getNonEquipmentItems().set(17, stack);
|
||||
var savedStack = stack.copy();
|
||||
var modifiers = java.util.Set.copyOf(player.distance.getModifiers());
|
||||
player.ordinary = Component.literal("Ordinary Tab");
|
||||
var label = NativePresentationPackets.createLabel(player, "Character", 1, 2, 3);
|
||||
wire(net.minecraft.network.protocol.game.ClientboundAddEntityPacket.STREAM_CODEC, label.spawn());
|
||||
wire(net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket.STREAM_CODEC, label.metadata());
|
||||
wire(net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket.STREAM_CODEC,
|
||||
NativePresentationPackets.suppressNameTag(entityId));
|
||||
var info = new ClientboundPlayerInfoUpdatePacket(EnumSet.of(Action.ADD_PLAYER), List.of(
|
||||
new Entry(id, profile, true, 51, GameType.CREATIVE, player.ordinary, true, 11, null)));
|
||||
roundTrip(NativePresentationPackets.projectPlayerInfo(info, id, "Character"));
|
||||
player.world = level();
|
||||
int oldAllocations = oldLevel.chunks.checks;
|
||||
wire(net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket.STREAM_CODEC, label.move(4, 5, 6));
|
||||
wire(net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket.STREAM_CODEC, label.rename("New character"));
|
||||
wire(net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket.STREAM_CODEC, label.remove());
|
||||
wire(net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket.STREAM_CODEC,
|
||||
NativePresentationPackets.restoreNameTag(player));
|
||||
roundTrip(NativePresentationPackets.refreshTab(player));
|
||||
assertEquals(oldAllocations, oldLevel.chunks.checks);
|
||||
assertEquals(0, player.world.chunks.checks, "Updating an old handle never silently creates a new-world entity");
|
||||
assertEquals(id, player.getUUID());
|
||||
assertEquals(entityId, player.getId());
|
||||
assertSame(profile, player.getGameProfile());
|
||||
assertEquals("Account", player.getGameProfile().name());
|
||||
assertEquals("skin-payload", player.getGameProfile().properties().get("textures").iterator().next().value());
|
||||
assertSame(team, player.getTeam());
|
||||
assertEquals(members, java.util.Set.copyOf(team.getPlayers()));
|
||||
assertEquals(prefix, team.getPlayerPrefix());
|
||||
assertEquals(net.minecraft.world.scores.Team.Visibility.HIDE_FOR_OTHER_TEAMS, team.getNameTagVisibility());
|
||||
assertEquals(1, player.board.getPlayerTeams().size());
|
||||
assertSame(stack, player.getInventory().getNonEquipmentItems().get(17));
|
||||
assertTrue(net.minecraft.world.item.ItemStack.matches(savedStack, stack));
|
||||
assertEquals(57.25, player.distance.getBaseValue());
|
||||
assertEquals(modifiers, player.distance.getModifiers());
|
||||
assertEquals(Component.literal("Ordinary Tab"), player.getTabListDisplayName());
|
||||
}
|
||||
|
||||
/** The real ServerLevel ID allocator runs against an explicit tracking-index read port. */
|
||||
private static final class ReadChunks extends net.minecraft.server.level.ServerChunkCache {
|
||||
private int checks;
|
||||
private boolean rejectNext;
|
||||
private ReadChunks() { super(null, null, null, null, null, null, 0, 0, false, null, null, null); }
|
||||
@Override public boolean hasEntityWithId(int id) {
|
||||
checks++;
|
||||
boolean reject = rejectNext;
|
||||
rejectNext = false;
|
||||
return reject;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class ReadLevel extends net.minecraft.server.level.ServerLevel {
|
||||
private io.papermc.paper.configuration.WorldConfiguration config;
|
||||
private ReadChunks chunks;
|
||||
private ReadLevel() { super(null, null, null, null, null, null, false, 0, null, false, null, null, null, null, null, null); }
|
||||
@Override public io.papermc.paper.configuration.WorldConfiguration paperConfig() { return config; }
|
||||
@Override public boolean addFreshEntity(net.minecraft.world.entity.Entity entity) { throw new AssertionError("Never insert a label"); }
|
||||
@Override public boolean addFreshEntity(net.minecraft.world.entity.Entity entity, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason reason) {
|
||||
throw new AssertionError("Never insert a label");
|
||||
}
|
||||
}
|
||||
|
||||
private static ReadLevel level() throws Exception {
|
||||
var level = allocate(ReadLevel.class);
|
||||
level.chunks = allocate(ReadChunks.class);
|
||||
setField(net.minecraft.server.level.ServerLevel.class, level, "chunkSource", level.chunks);
|
||||
setField(net.minecraft.world.level.Level.class, level, "spigotConfig", allocate(org.spigotmc.SpigotWorldConfig.class));
|
||||
var purpur = allocate(org.purpurmc.purpur.PurpurWorldConfig.class);
|
||||
purpur.drowningAirTicks = 300;
|
||||
setField(net.minecraft.world.level.Level.class, level, "purpurConfig", purpur);
|
||||
level.config = allocate(io.papermc.paper.configuration.WorldConfiguration.class);
|
||||
level.config.entities = allocate(io.papermc.paper.configuration.WorldConfiguration.Entities.class);
|
||||
level.config.entities.spawning = allocate(io.papermc.paper.configuration.WorldConfiguration.Entities.Spawning.class);
|
||||
level.config.entities.spawning.despawnTime = new it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap<>();
|
||||
return level;
|
||||
}
|
||||
|
||||
private static void setField(Class<?> owner, Object target, String name, Object value) throws Exception {
|
||||
var field = owner.getDeclaredField(name);
|
||||
field.setAccessible(true);
|
||||
field.set(target, value);
|
||||
}
|
||||
|
||||
/** Constructor-free read boundary. Native attributes and packet codecs are real. */
|
||||
private static final class ReadPlayer extends net.minecraft.server.level.ServerPlayer {
|
||||
private net.minecraft.world.entity.ai.attributes.AttributeInstance distance;
|
||||
private Component ordinary;
|
||||
private net.minecraft.world.scores.Scoreboard board;
|
||||
private ReadLevel world;
|
||||
@Override public net.minecraft.server.level.ServerLevel level() { return world; }
|
||||
private ReadPlayer() { super(null, null, null, null); throw new AssertionError("Never construct a server player"); }
|
||||
@Override public Component getTabListDisplayName() { return ordinary; }
|
||||
@Override public net.minecraft.world.scores.PlayerTeam getTeam() { return board.getPlayersTeam(getScoreboardName()); }
|
||||
@Override public net.minecraft.world.entity.ai.attributes.AttributeInstance getAttribute(
|
||||
net.minecraft.core.Holder<net.minecraft.world.entity.ai.attributes.Attribute> type) {
|
||||
assertEquals(net.minecraft.world.entity.ai.attributes.Attributes.NAME_TAG_DISTANCE, type);
|
||||
return distance;
|
||||
}
|
||||
}
|
||||
|
||||
private static ReadPlayer player() throws Exception {
|
||||
var player = allocate(ReadPlayer.class);
|
||||
player.setId(93);
|
||||
player.setUUID(UUID.randomUUID());
|
||||
player.gameProfile = new GameProfile(player.getUUID(), "Account", new PropertyMap(ImmutableMultimap.of("textures",
|
||||
new Property("textures", "skin-payload", "skin-signature"))));
|
||||
player.board = new net.minecraft.world.scores.Scoreboard();
|
||||
setField(net.minecraft.world.entity.player.Player.class, player, "inventory",
|
||||
new net.minecraft.world.entity.player.Inventory(player, new net.minecraft.world.entity.EntityEquipment()));
|
||||
player.distance = attribute(net.minecraft.world.entity.ai.attributes.Attributes.NAME_TAG_DISTANCE, 57.25);
|
||||
return player;
|
||||
}
|
||||
|
||||
private static <T> T allocate(Class<T> type) throws Exception {
|
||||
var unsafe = Class.forName("sun.misc.Unsafe");
|
||||
var field = unsafe.getDeclaredField("theUnsafe");
|
||||
field.setAccessible(true);
|
||||
return type.cast(unsafe.getMethod("allocateInstance", Class.class).invoke(field.get(null), type));
|
||||
}
|
||||
|
||||
private static net.minecraft.world.entity.ai.attributes.AttributeInstance attribute(
|
||||
net.minecraft.core.Holder<net.minecraft.world.entity.ai.attributes.Attribute> type, double base) {
|
||||
var instance = new net.minecraft.world.entity.ai.attributes.AttributeInstance(type, ignored -> { });
|
||||
instance.setBaseValue(base);
|
||||
for (var operation : net.minecraft.world.entity.ai.attributes.AttributeModifier.Operation.values()) {
|
||||
instance.addTransientModifier(new net.minecraft.world.entity.ai.attributes.AttributeModifier(
|
||||
net.minecraft.resources.Identifier.fromNamespaceAndPath("test", operation.name().toLowerCase(java.util.Locale.ROOT)),
|
||||
0.25, operation));
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
private static <T> T wire(net.minecraft.network.codec.StreamCodec<? super RegistryFriendlyByteBuf, T> codec, T packet) {
|
||||
var buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), CraftRegistry.getMinecraftRegistry());
|
||||
try {
|
||||
codec.encode(buffer, packet);
|
||||
T decoded = codec.decode(buffer);
|
||||
assertFalse(buffer.isReadable(), "The actual pinned schema consumes every byte");
|
||||
return decoded;
|
||||
} finally { buffer.release(); }
|
||||
}
|
||||
|
||||
private static Entry entry(String account, boolean listed, int latency, GameType gameMode,
|
||||
boolean hat, int order) throws Exception {
|
||||
UUID id = UUID.randomUUID();
|
||||
var profile = new GameProfile(id, account, new PropertyMap(ImmutableMultimap.of("textures",
|
||||
new Property("textures", "skin-payload-" + account, "skin-signature-" + account))));
|
||||
var keyGenerator = KeyPairGenerator.getInstance("RSA");
|
||||
keyGenerator.initialize(2048);
|
||||
var key = new ProfilePublicKey.Data(Instant.ofEpochSecond(2_000_000_000L),
|
||||
keyGenerator.generateKeyPair().getPublic(), new byte[] {1, 3, 7, 9});
|
||||
return new Entry(id, profile, listed, latency, gameMode, Component.literal("Ordinary " + account),
|
||||
hat, order, new RemoteChatSession.Data(UUID.randomUUID(), key));
|
||||
}
|
||||
|
||||
private static void assertPreserved(Entry before, Entry after, Component expectedDisplay) {
|
||||
assertEquals(before.profileId(), after.profileId());
|
||||
assertEquals(before.profile().id(), after.profile().id());
|
||||
assertEquals(before.profile().name(), after.profile().name());
|
||||
assertEquals(before.profile().properties(), after.profile().properties());
|
||||
assertEquals(before.listed(), after.listed());
|
||||
assertEquals(before.latency(), after.latency());
|
||||
assertEquals(before.gameMode(), after.gameMode());
|
||||
assertEquals(expectedDisplay, after.displayName());
|
||||
assertEquals(before.showHat(), after.showHat());
|
||||
assertEquals(before.listOrder(), after.listOrder());
|
||||
assertEquals(before.chatSession().sessionId(), after.chatSession().sessionId());
|
||||
var beforeKey = before.chatSession().profilePublicKey();
|
||||
var afterKey = after.chatSession().profilePublicKey();
|
||||
assertEquals(beforeKey.expiresAt(), afterKey.expiresAt());
|
||||
assertEquals(beforeKey.key(), afterKey.key());
|
||||
assertArrayEquals(beforeKey.keySignature(), afterKey.keySignature());
|
||||
}
|
||||
|
||||
private static ClientboundPlayerInfoUpdatePacket roundTrip(ClientboundPlayerInfoUpdatePacket packet) {
|
||||
var buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), CraftRegistry.getMinecraftRegistry());
|
||||
try {
|
||||
ClientboundPlayerInfoUpdatePacket.STREAM_CODEC.encode(buffer, packet);
|
||||
var decoded = ClientboundPlayerInfoUpdatePacket.STREAM_CODEC.decode(buffer);
|
||||
assertFalse(buffer.isReadable(), "The actual pinned packet schema consumes every byte");
|
||||
return decoded;
|
||||
} finally { buffer.release(); }
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,528 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import games.dmg.fantasystick.items.CharacterSheets;
|
||||
import games.dmg.fantasystick.items.EquipmentStorage;
|
||||
import games.dmg.fantasystick.persistence.CharacterRecord;
|
||||
import games.dmg.fantasystick.presentation.CharacterPresentation;
|
||||
import games.dmg.fantasystick.progression.Stat;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/** Equipment-session composition, not a fantasy health/nutrition engine or live display test. */
|
||||
@SuppressWarnings("try")
|
||||
class WholeCharacterTransferNativeTest {
|
||||
@TempDir Path data;
|
||||
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
|
||||
|
||||
@Test void completeCharacterTransfersWhileGearVitalsLocationsDeadlinesAndOrdinaryIdentityStayWithHolders() throws Exception {
|
||||
try (var h = new Harness()) {
|
||||
var record = h.saveCharacter("Original sheet name");
|
||||
var a = h.holder(record, "AccountA", Material.DIAMOND_SWORD, 13.5, 7, 1.5f, 2.75f);
|
||||
var b = h.holder(record, "AccountB", Material.IRON_AXE, 6.25, 18, 8.5f, 0.25f);
|
||||
a.actor.location = new Location(null, 11, 71, -8, 30, 10);
|
||||
b.actor.location = new Location(null, -90, 65, 123, -45, 20);
|
||||
var aEntry = a.actor.location.clone(); var bEntry = b.actor.location.clone();
|
||||
var aBefore = a.actor.snapshot(); var bBefore = b.actor.snapshot();
|
||||
var aOrdinary = a.ordinary(); var bOrdinary = b.ordinary();
|
||||
// Physical sheets are now stale. Activation must read the complete authoritative YAML record.
|
||||
var current = h.f.characters.renameCharacter(record.id(), "雪 <red>Literal transferred character 🐉")
|
||||
.get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
h.activate(a);
|
||||
var aSession = h.f.sessions.active(a.actor.id).orElseThrow();
|
||||
assertEquals(current.name(), h.presentation.name(a.actor.id));
|
||||
assertEquals(current.revision(), h.output.shown.getLast().revision());
|
||||
assertEquals(current.id(), h.output.shown.getLast().character());
|
||||
assertEquals(aOrdinary, a.ordinary()); assertEquals(bOrdinary, b.ordinary());
|
||||
assertEquals(current, h.saved(record.id()));
|
||||
a.actor.location = new Location(null, 222, 80, -333);
|
||||
var aExitLocation = a.actor.location.clone();
|
||||
assertEquals(EquipmentStorage.RestoreResult.RESTORED, h.f.sessions.exit(a.player));
|
||||
var aExit = h.f.state(a.actor);
|
||||
assertArrayEquals(aBefore, a.actor.snapshot());
|
||||
assertEquals(aExitLocation, a.actor.location, "Voluntary exit does not use the entry return location");
|
||||
assertEquals(0, a.actor.teleports);
|
||||
assertNull(h.presentation.name(a.actor.id));
|
||||
assertEquals(aSession.session(), h.output.cleared.getLast().session());
|
||||
|
||||
var transferred = a.actor.inventory.getItemInOffHand().clone();
|
||||
a.actor.inventory.setItemInOffHand(null);
|
||||
b.actor.inventory.setItemInOffHand(transferred);
|
||||
h.activate(b);
|
||||
var bSession = h.f.sessions.active(b.actor.id).orElseThrow();
|
||||
assertEquals(current.id(), bSession.character()); assertNotEquals(aSession.session(), bSession.session());
|
||||
assertEquals(current.name(), h.presentation.name(b.actor.id));
|
||||
assertNull(h.presentation.name(a.actor.id));
|
||||
assertNull(h.f.state(b.actor).lastExit(), "A's switch deadline is not a character property");
|
||||
assertEquals(aExit, h.f.state(a.actor));
|
||||
assertEquals(bEntry, b.actor.location); assertNotEquals(aEntry, b.actor.location);
|
||||
assertEquals(aOrdinary, a.ordinary()); assertEquals(bOrdinary, b.ordinary());
|
||||
assertEquals(current, h.saved(record.id()), "Transfer preserves stats, XP, points, health, learned/loadout and cooldowns");
|
||||
assertEquals(current, new games.dmg.fantasystick.persistence.YamlCharacterRepository(data).load(record.id()).orElseThrow());
|
||||
assertEquals(EquipmentStorage.RestoreResult.RESTORED, h.f.sessions.exit(b.player));
|
||||
assertNull(h.f.state(b.actor).pending());
|
||||
assertArrayEquals(bBefore, b.actor.snapshot(), "B restores B's real native gear, never A's");
|
||||
assertEquals(Material.DIAMOND_SWORD, a.actor.inventory.getItem(0).getType());
|
||||
assertEquals(aOrdinary, a.ordinary()); assertEquals(bOrdinary, b.ordinary());
|
||||
assertEquals(bEntry, b.actor.location); assertEquals(0, b.actor.teleports);
|
||||
assertEquals(aExit, h.f.state(a.actor)); assertEquals(current, h.saved(record.id()));
|
||||
assertTrue(h.presentation.snapshot().isEmpty());
|
||||
assertEquals(List.of(a.actor.id, b.actor.id), h.output.cleared.stream().map(CharacterPresentation.View::holder).toList());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void pendingAndActiveCopiesAreBusyCounterfeitsAndDeadRecordsRefuseButConsumeOnceBackendRevivalEnters() throws Exception {
|
||||
try (var h = new Harness()) {
|
||||
var record = h.saveCharacter("One transferable life");
|
||||
var a = h.holder(record); var b = h.holder(record);
|
||||
var beforeB = b.actor.snapshot();
|
||||
h.f.sessions.enter(a.player); var loadA = h.f.next();
|
||||
h.f.sessions.enter(b.player); var loadB = h.f.next();
|
||||
loadA.run(); loadB.run(); // Both reads were pending before either player acquired the character.
|
||||
assertEquals("CHARACTER_BUSY", h.f.notices.getLast().code());
|
||||
assertArrayEquals(beforeB, b.actor.snapshot());
|
||||
assertTrue(h.f.sessions.active(b.actor.id).isEmpty());
|
||||
assertTrue(h.presentation.snapshot().isEmpty(), "No presentation before native activation");
|
||||
h.f.tick();
|
||||
assertTrue(h.f.sessions.active(a.actor.id).isPresent());
|
||||
h.f.sessions.enter(b.player); h.f.tick();
|
||||
assertEquals("CHARACTER_BUSY", h.f.notices.getLast().code());
|
||||
assertArrayEquals(beforeB, b.actor.snapshot()); assertNull(h.presentation.name(b.actor.id));
|
||||
assertEquals(record, h.saved(record.id()));
|
||||
assertTrue(h.f.receipts.find(b.actor.id).toCompletableFuture().get(5, TimeUnit.SECONDS).isEmpty());
|
||||
h.f.sessions.exit(a.player); var exit = h.f.state(a.actor);
|
||||
|
||||
var fake = b.actor.inventory.getItemInOffHand().clone();
|
||||
var meta = fake.getItemMeta();
|
||||
meta.getPersistentDataContainer().remove(new org.bukkit.NamespacedKey("fantasystick", "character_id"));
|
||||
fake.setItemMeta(meta); b.actor.inventory.setItemInOffHand(fake);
|
||||
var counterfeitState = b.actor.snapshot();
|
||||
h.f.sessions.enter(b.player);
|
||||
assertEquals("INVALID_SHEET", h.f.notices.getLast().code());
|
||||
assertArrayEquals(counterfeitState, b.actor.snapshot()); assertNull(h.presentation.name(b.actor.id));
|
||||
assertEquals(record, h.saved(record.id())); assertTrue(h.f.tasks.isEmpty());
|
||||
|
||||
var dead = h.f.characters.recordDeath(record.id()).get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
var beforeA = a.actor.snapshot();
|
||||
h.f.sessions.enter(a.player); h.f.tick();
|
||||
assertEquals("UNAVAILABLE_CHARACTER", h.f.notices.getLast().code());
|
||||
assertArrayEquals(beforeA, a.actor.snapshot()); assertEquals(exit, h.f.state(a.actor));
|
||||
assertTrue(h.f.sessions.active(a.actor.id).isEmpty()); assertNull(h.presentation.name(a.actor.id));
|
||||
assertEquals(dead, h.saved(record.id()));
|
||||
assertTrue(h.f.characters.restoreDeathRecord(dead.id(), UUID.randomUUID()).get(5, TimeUnit.SECONDS).isEmpty());
|
||||
assertEquals(dead, h.saved(record.id()));
|
||||
var revived = h.f.characters.restoreDeathRecord(dead.id(), dead.deathId()).get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
assertProgress(record, revived); assertFalse(revived.dead());
|
||||
assertEquals(0, record.maximumHealth().compareTo(revived.health()));
|
||||
assertTrue(h.f.characters.restoreDeathRecord(dead.id(), dead.deathId()).get(5, TimeUnit.SECONDS).isEmpty());
|
||||
a.actor.inventory.setItemInOffHand(new CharacterSheets().create(revived));
|
||||
h.activate(a); // Real session, despite the still-running player delay: exact stable ID exception.
|
||||
assertEquals(revived.id(), h.f.sessions.active(a.actor.id).orElseThrow().character());
|
||||
assertEquals(revived.revision(), h.presentation.snapshot().get(a.actor.id).revision());
|
||||
assertEquals(exit.lastExit(), h.f.state(a.actor).lastExit());
|
||||
b.actor.inventory.setItemInOffHand(beforeB[40]); // Old copied native reference still cannot create a second life.
|
||||
h.f.sessions.enter(b.player); h.f.tick();
|
||||
assertEquals("CHARACTER_BUSY", h.f.notices.getLast().code());
|
||||
assertTrue(h.f.sessions.active(b.actor.id).isEmpty()); assertNull(h.presentation.name(b.actor.id));
|
||||
assertEquals(revived, h.saved(record.id()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void directSheetReplacementExitsBeforeDelayCheckSameIdResumesAndDifferentIdEntersOnlyAtExactDeadline() throws Exception {
|
||||
try (var h = new Harness()) {
|
||||
var first = h.saveCharacter("Identical name"); var second = h.saveCharacter("Identical name");
|
||||
var holder = h.holder(first); var ordinaryGear = holder.actor.inventory.getItem(0).clone();
|
||||
h.activate(holder);
|
||||
var firstSession = h.f.sessions.active(holder.actor.id).orElseThrow().session();
|
||||
holder.actor.inventory.setItemInOffHand(new CharacterSheets().create(second));
|
||||
h.changed(holder); // Actual event bridge must perform orderly exit before deferred entry.
|
||||
assertTrue(h.f.sessions.active(holder.actor.id).isEmpty()); assertNull(h.presentation.name(holder.actor.id));
|
||||
assertEquals(ordinaryGear, holder.actor.inventory.getItem(0));
|
||||
var exit = h.f.state(holder.actor);
|
||||
assertEquals(first.id(), exit.lastExit().characterId());
|
||||
assertEquals(firstSession, exit.lastExit().sessionId());
|
||||
h.eventTasks.remove().run(); h.f.tick();
|
||||
assertEquals("COOLDOWN", h.f.notices.getLast().code());
|
||||
assertEquals(exit, h.f.state(holder.actor)); assertEquals(1, h.output.shown.size());
|
||||
|
||||
h.clock.advance(Duration.ofSeconds(20));
|
||||
var renamed = h.f.characters.renameCharacter(first.id(), "Same ID, different name").get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
holder.actor.inventory.setItemInOffHand(new CharacterSheets().create(renamed).clone());
|
||||
h.changed(holder); h.eventTasks.remove().run(); h.f.tick(); h.f.tick();
|
||||
assertEquals(first.id(), h.f.sessions.active(holder.actor.id).orElseThrow().character());
|
||||
assertEquals(renamed.name(), h.presentation.name(holder.actor.id));
|
||||
assertEquals(exit.lastExit(), h.f.state(holder.actor).lastExit(), "Resume does not extend the deadline");
|
||||
h.clock.advance(Duration.ofSeconds(10));
|
||||
h.f.sessions.exit(holder.player); var nextExit = h.f.state(holder.actor);
|
||||
assertEquals(exit.lastExit().deadline().plusSeconds(30), nextExit.lastExit().deadline());
|
||||
holder.actor.inventory.setItemInOffHand(new CharacterSheets().create(second));
|
||||
var before = holder.actor.snapshot();
|
||||
h.clock.now = nextExit.lastExit().deadline().minusNanos(1);
|
||||
h.f.sessions.enter(holder.player); h.f.tick();
|
||||
assertEquals("COOLDOWN", h.f.notices.getLast().code());
|
||||
assertArrayEquals(before, holder.actor.snapshot()); assertEquals(nextExit, h.f.state(holder.actor));
|
||||
assertNull(h.presentation.name(holder.actor.id));
|
||||
h.clock.now = nextExit.lastExit().deadline(); h.activate(holder);
|
||||
assertEquals(second.id(), h.f.sessions.active(holder.actor.id).orElseThrow().character());
|
||||
assertEquals(second.id(), h.output.shown.getLast().character());
|
||||
assertEquals(second.name(), h.presentation.name(holder.actor.id));
|
||||
assertEquals(nextExit.lastExit(), h.f.state(holder.actor).lastExit());
|
||||
assertEquals(renamed, h.saved(first.id())); assertEquals(second, h.saved(second.id()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void acknowledgedNamesUseImmutableViewsAndLateCallbacksCannotRenameOrWithdrawTransferredReplacementSessions() throws Exception {
|
||||
try (var h = new Harness()) {
|
||||
var record = h.saveCharacter("Before accepted rename");
|
||||
var a = h.holder(record); var b = h.holder(record); h.activate(a);
|
||||
var oldSnapshot = h.presentation.snapshot();
|
||||
var firstView = oldSnapshot.get(a.actor.id);
|
||||
assertThrows(UnsupportedOperationException.class, oldSnapshot::clear);
|
||||
var renamed = h.f.characters.renameCharacter(record.id(), "Acknowledged 雪 🐉").get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
h.presentation.acknowledged(renamed);
|
||||
assertEquals(record.name(), h.presentation.name(a.actor.id), "Acknowledgment queues native output, never writes it inline");
|
||||
h.displayTasks.remove().run();
|
||||
assertEquals(renamed.name(), h.presentation.name(a.actor.id));
|
||||
assertEquals(renamed.revision(), h.output.renamed.getLast().revision());
|
||||
assertEquals(record.name(), oldSnapshot.get(a.actor.id).name());
|
||||
assertEquals(firstView.session(), h.output.renamed.getLast().session());
|
||||
var latest = h.f.characters.renameCharacter(record.id(), "Transferred authoritative name").get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
h.presentation.acknowledged(latest); var stale = h.displayTasks.remove();
|
||||
h.f.sessions.exit(a.player); h.f.state(a.actor);
|
||||
var sheet = a.actor.inventory.getItemInOffHand().clone(); a.actor.inventory.setItemInOffHand(null);
|
||||
b.actor.inventory.setItemInOffHand(sheet); h.activate(b);
|
||||
var bView = h.presentation.snapshot().get(b.actor.id);
|
||||
assertEquals(latest.name(), bView.name());
|
||||
stale.run(); stale.run(); h.presentation.withdraw(a.actor.id, firstView.session());
|
||||
assertEquals(Map.of(b.actor.id, bView), h.presentation.snapshot());
|
||||
assertEquals(1, h.output.renamed.size(), "A's delayed acknowledgment does not become B's callback");
|
||||
h.f.sessions.exit(b.player); h.f.state(b.actor); h.activate(b);
|
||||
var replacement = h.presentation.snapshot().get(b.actor.id);
|
||||
assertNotEquals(bView.session(), replacement.session());
|
||||
h.presentation.withdraw(b.actor.id, bView.session()); stale.run();
|
||||
assertEquals(Map.of(b.actor.id, replacement), h.presentation.snapshot());
|
||||
assertEquals(latest, h.saved(record.id()));
|
||||
}
|
||||
}
|
||||
|
||||
private enum Ending { EXIT, QUIT, DISABLE, DEFEAT }
|
||||
private enum Restoration { SUCCESS, MISSING_BOX, WRITE_FAILURE }
|
||||
|
||||
static java.util.stream.Stream<org.junit.jupiter.params.provider.Arguments> lifecycleCases() {
|
||||
return java.util.Arrays.stream(Ending.values()).flatMap(ending -> java.util.Arrays.stream(Restoration.values())
|
||||
.map(restoration -> org.junit.jupiter.params.provider.Arguments.of(ending, restoration)));
|
||||
}
|
||||
|
||||
@org.junit.jupiter.params.ParameterizedTest(name = "{0} / {1}")
|
||||
@org.junit.jupiter.params.provider.MethodSource("lifecycleCases")
|
||||
void lifecycleWithdrawsBeforeRestorationEvenOnRefusalOrExceptionAndLateNamesCannotResurrectDisplay(
|
||||
Ending ending, Restoration restoration) throws Exception {
|
||||
try (var h = new Harness()) {
|
||||
var record = h.saveCharacter("Lifecycle character"); var holder = h.holder(record);
|
||||
var original = holder.actor.snapshot(); var ordinary = holder.ordinary();
|
||||
h.activate(holder);
|
||||
var view = h.presentation.snapshot().get(holder.actor.id);
|
||||
var renamed = h.f.characters.renameCharacter(record.id(), "Late lifecycle name").get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
h.presentation.acknowledged(renamed); var lateName = h.displayTasks.remove();
|
||||
if (restoration == Restoration.MISSING_BOX) holder.actor.inventory.setItem(9, null);
|
||||
if (restoration == Restoration.WRITE_FAILURE) {
|
||||
h.f.expectedFailure = IllegalStateException.class;
|
||||
holder.actor.beforeMutation = () -> {
|
||||
holder.actor.beforeMutation = () -> {};
|
||||
throw new IllegalStateException("Interrupted equipment restoration before first slot write");
|
||||
};
|
||||
}
|
||||
var beforeExit = holder.actor.snapshot();
|
||||
h.output.onClear = cleared -> {
|
||||
assertEquals(view.session(), cleared.session());
|
||||
assertNull(h.presentation.name(holder.actor.id), "Invalidate the view before native output cleanup");
|
||||
assertArrayEquals(beforeExit, holder.actor.snapshot(), "Display withdrawal precedes equipment writes");
|
||||
};
|
||||
org.bukkit.event.entity.PlayerDeathEvent death = null;
|
||||
switch (ending) {
|
||||
case EXIT -> h.f.sessions.exit(holder.player);
|
||||
case QUIT -> {
|
||||
h.events.quit(new org.bukkit.event.player.PlayerQuitEvent(holder.player, Component.empty()));
|
||||
holder.actor.online = false;
|
||||
}
|
||||
case DISABLE -> { h.events.close(); h.f.sessions.close(); }
|
||||
case DEFEAT -> {
|
||||
death = death(holder); h.events.death(death); assertTrue(death.isCancelled());
|
||||
}
|
||||
}
|
||||
assertTrue(h.f.sessions.active(holder.actor.id).isEmpty());
|
||||
assertTrue(h.presentation.snapshot().isEmpty()); assertEquals(List.of(view), h.output.cleared);
|
||||
lateName.run(); lateName.run();
|
||||
assertTrue(h.output.renamed.isEmpty()); assertTrue(h.presentation.snapshot().isEmpty());
|
||||
var state = h.f.state(holder.actor);
|
||||
assertNotNull(state.lastExit()); assertEquals(record.id(), state.lastExit().characterId());
|
||||
if (restoration == Restoration.SUCCESS) {
|
||||
assertNull(state.pending()); assertArrayEquals(original, holder.actor.snapshot());
|
||||
} else {
|
||||
assertNotNull(state.pending()); assertArrayEquals(beforeExit, holder.actor.snapshot());
|
||||
assertTrue(holder.actor.marker().endsWith(restoration == Restoration.MISSING_BOX ? "|PACKED" : "|RESTORING"));
|
||||
}
|
||||
if (ending == Ending.DEFEAT) {
|
||||
if (restoration != Restoration.SUCCESS) h.f.expectedFailure = IllegalStateException.class;
|
||||
h.f.tick(); // Actual asynchronous death acknowledgment / one-use Tail attempt.
|
||||
var dead = h.saved(record.id()); assertTrue(dead.dead()); assertProgress(renamed, dead);
|
||||
assertEquals(0, dead.health().signum());
|
||||
assertEquals(restoration == Restoration.SUCCESS ? Material.WRITTEN_BOOK : Material.PAPER,
|
||||
holder.actor.inventory.getItemInOffHand().getType());
|
||||
assertEquals(holder.actor.normalMaximum, death.getReviveHealth());
|
||||
assertEquals(holder.actor.normalMaximum, holder.actor.health, "Existing minimal defeat healing, not a fantasy health engine");
|
||||
assertEquals(ordinary.food(), holder.player.getFoodLevel());
|
||||
assertEquals(ordinary.saturation(), holder.player.getSaturation());
|
||||
assertEquals(ordinary.exhaustion(), holder.player.getExhaustion());
|
||||
} else {
|
||||
assertEquals(renamed, h.saved(record.id())); assertEquals(ordinary, holder.ordinary());
|
||||
}
|
||||
assertTrue(h.presentation.snapshot().isEmpty()); assertEquals(1, h.output.cleared.size());
|
||||
h.f.sessions.exit(holder.player); // Repeated cleanup cannot output a second stale withdrawal.
|
||||
assertEquals(1, h.output.cleared.size()); assertEquals(state, h.f.state(holder.actor));
|
||||
}
|
||||
}
|
||||
|
||||
@org.junit.jupiter.params.ParameterizedTest(name = "disable={0}")
|
||||
@org.junit.jupiter.params.provider.ValueSource(booleans = {false, true})
|
||||
void quitOrDisableBeforeAcknowledgedNativeEntryCannotInstallPresentationFromStaleCallback(boolean disable) throws Exception {
|
||||
try (var h = new Harness()) {
|
||||
var record = h.saveCharacter("Never activated"); var holder = h.holder(record);
|
||||
var before = holder.actor.snapshot();
|
||||
h.f.sessions.enter(holder.player); h.f.tick(); var callback = h.f.next();
|
||||
assertNotNull(h.f.state(holder.actor).pending()); assertTrue(h.presentation.snapshot().isEmpty());
|
||||
if (disable) { h.events.close(); h.f.sessions.close(); }
|
||||
else h.events.quit(new org.bukkit.event.player.PlayerQuitEvent(holder.player, Component.empty()));
|
||||
assertNull(h.f.state(holder.actor).pending());
|
||||
callback.run(); callback.run();
|
||||
assertArrayEquals(before, holder.actor.snapshot()); assertNull(holder.actor.marker());
|
||||
assertTrue(h.f.sessions.active(holder.actor.id).isEmpty()); assertTrue(h.presentation.snapshot().isEmpty());
|
||||
assertTrue(h.output.shown.isEmpty()); assertTrue(h.output.cleared.isEmpty());
|
||||
assertEquals(record, h.saved(record.id()));
|
||||
if (!disable) {
|
||||
h.activate(holder); var replacement = h.presentation.snapshot().get(holder.actor.id);
|
||||
callback.run(); assertEquals(Map.of(holder.actor.id, replacement), h.presentation.snapshot());
|
||||
assertEquals(1, h.output.shown.size());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test void refusedThenSuccessfulRecoveryNeverReinstallsOldPresentationOrReplaysItsDelayedCallbacks() throws Exception {
|
||||
try (var h = new Harness()) {
|
||||
var record = h.saveCharacter("Recoverable character"); var holder = h.holder(record);
|
||||
var original = holder.actor.snapshot(); h.activate(holder);
|
||||
var oldView = h.presentation.snapshot().get(holder.actor.id);
|
||||
var renamed = h.f.characters.renameCharacter(record.id(), "Recovered current name").get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
h.presentation.acknowledged(renamed); var oldName = h.displayTasks.remove();
|
||||
var control = holder.actor.inventory.getItem(0).clone();
|
||||
holder.actor.inventory.setItem(0, new ItemStack(Material.EMERALD));
|
||||
var refused = holder.actor.snapshot();
|
||||
assertEquals(EquipmentStorage.RestoreResult.OCCUPIED_SLOT, h.f.sessions.exit(holder.player));
|
||||
var exited = h.f.state(holder.actor);
|
||||
assertTrue(h.presentation.snapshot().isEmpty()); assertEquals(List.of(oldView), h.output.cleared);
|
||||
h.f.sessions.recover(holder.player); h.f.tick();
|
||||
assertArrayEquals(refused, holder.actor.snapshot()); assertEquals(exited, h.f.state(holder.actor));
|
||||
assertTrue(h.presentation.snapshot().isEmpty()); assertEquals(1, h.output.shown.size());
|
||||
holder.actor.inventory.setItem(0, control);
|
||||
h.f.sessions.recover(holder.player); var staleRecovery = h.f.next();
|
||||
h.f.sessions.cancelEntry(holder.actor.id);
|
||||
h.f.sessions.recover(holder.player); h.f.tick();
|
||||
assertArrayEquals(original, holder.actor.snapshot()); assertNull(h.f.state(holder.actor).pending());
|
||||
assertEquals(exited.lastExit(), h.f.state(holder.actor).lastExit());
|
||||
oldName.run(); staleRecovery.run();
|
||||
assertTrue(h.presentation.snapshot().isEmpty()); assertTrue(h.output.renamed.isEmpty());
|
||||
assertEquals(1, h.output.shown.size()); assertEquals(1, h.output.cleared.size());
|
||||
h.activate(holder); var replacement = h.presentation.snapshot().get(holder.actor.id);
|
||||
assertNotEquals(oldView.session(), replacement.session()); assertEquals(renamed.name(), replacement.name());
|
||||
oldName.run(); staleRecovery.run(); h.presentation.withdraw(holder.actor.id, oldView.session());
|
||||
assertEquals(Map.of(holder.actor.id, replacement), h.presentation.snapshot());
|
||||
assertEquals(replacement.session(), h.f.state(holder.actor).pending().sessionId());
|
||||
assertEquals(renamed, h.saved(record.id()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void defeatAfterTransferReturnsOnlyTheNewHolderToTheirOwnEntryAndLeavesTheFormerHolderUntouched() throws Exception {
|
||||
try (var h = new Harness()) {
|
||||
var record = h.saveCharacter("Transferred then defeated"); var a = h.holder(record); var b = h.holder(record);
|
||||
a.actor.location = new Location(null, 100, 70, 100);
|
||||
b.actor.location = new Location(null, -500, 80, -600);
|
||||
var bEntry = b.actor.location.clone(); var bGear = b.actor.inventory.getItem(0).clone();
|
||||
h.activate(a); h.f.sessions.exit(a.player); var aExit = h.f.state(a.actor);
|
||||
b.actor.inventory.setItemInOffHand(a.actor.inventory.getItemInOffHand().clone()); a.actor.inventory.setItemInOffHand(null);
|
||||
var aItems = a.actor.snapshot(); var aOrdinary = a.ordinary(); var aLocation = a.actor.location.clone();
|
||||
h.activate(b); b.actor.location = new Location(null, 999, 64, 888);
|
||||
var event = death(b); h.events.death(event);
|
||||
assertTrue(event.isCancelled()); assertEquals(bEntry, b.actor.teleported); assertEquals(bEntry, b.actor.location);
|
||||
assertEquals(1, b.actor.teleports); assertEquals(0, a.actor.teleports);
|
||||
assertEquals(bGear, b.actor.inventory.getItem(0));
|
||||
assertNull(h.presentation.name(b.actor.id)); assertNull(h.f.state(b.actor).pending());
|
||||
h.f.tick();
|
||||
assertEquals(Material.WRITTEN_BOOK, b.actor.inventory.getItemInOffHand().getType());
|
||||
assertTrue(h.saved(record.id()).dead()); assertProgress(record, h.saved(record.id()));
|
||||
assertArrayEquals(aItems, a.actor.snapshot()); assertEquals(aOrdinary, a.ordinary());
|
||||
assertEquals(aLocation, a.actor.location); assertEquals(aExit, h.f.state(a.actor));
|
||||
assertTrue(h.presentation.snapshot().isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
private static org.bukkit.event.entity.PlayerDeathEvent death(Holder holder) {
|
||||
var source = new org.bukkit.craftbukkit.damage.CraftDamageSource(new net.minecraft.world.damagesource.DamageSource(
|
||||
org.bukkit.craftbukkit.damage.CraftDamageType.bukkitToMinecraftHolder(org.bukkit.damage.DamageType.GENERIC)));
|
||||
return new org.bukkit.event.entity.PlayerDeathEvent(holder.player, source, new ArrayList<>(), 7,
|
||||
Component.text("ordinary death"), true);
|
||||
}
|
||||
|
||||
private static void assertProgress(CharacterRecord expected, CharacterRecord actual) {
|
||||
assertEquals(expected.id(), actual.id()); assertEquals(expected.name(), actual.name());
|
||||
assertEquals(expected.stats(), actual.stats()); assertEquals(expected.level(), actual.level());
|
||||
assertEquals(expected.experience(), actual.experience()); assertEquals(expected.unspentPoints(), actual.unspentPoints());
|
||||
assertEquals(expected.learned(), actual.learned()); assertEquals(expected.loadout(), actual.loadout());
|
||||
assertEquals(expected.cooldowns(), actual.cooldowns());
|
||||
}
|
||||
|
||||
private final class Harness implements AutoCloseable {
|
||||
final EquipmentSessionsNativeTest.MutableClock clock = new EquipmentSessionsNativeTest.MutableClock();
|
||||
final EquipmentSessionsNativeTest.Fixture f;
|
||||
final ArrayDeque<Runnable> displayTasks = new ArrayDeque<>();
|
||||
final ArrayDeque<Runnable> eventTasks = new ArrayDeque<>();
|
||||
final games.dmg.fantasystick.session.EquipmentSessionEvents events;
|
||||
final ArrayList<Throwable> displayFailures = new ArrayList<>();
|
||||
final RecordingOutput output = new RecordingOutput();
|
||||
final CharacterPresentation presentation;
|
||||
Harness() throws Exception {
|
||||
var owner = new EquipmentSessionsNativeTest(); owner.data = data;
|
||||
f = owner.new Fixture(Duration.ofSeconds(900), clock);
|
||||
presentation = new CharacterPresentation(output, displayTasks::add,
|
||||
() -> Thread.currentThread() == f.main, displayFailures::add);
|
||||
f.presentation = presentation;
|
||||
f.sessions = f.coordinator(Duration.ofSeconds(900));
|
||||
events = new games.dmg.fantasystick.session.EquipmentSessionEvents(f.sessions, eventTasks::add, f.failures::add);
|
||||
}
|
||||
void changed(Holder holder) {
|
||||
events.changed(new io.papermc.paper.event.player.PlayerInventorySlotChangeEvent(holder.player, 40,
|
||||
new ItemStack(Material.AIR), holder.actor.inventory.getItemInOffHand()));
|
||||
}
|
||||
CharacterRecord saveCharacter(String name) throws Exception {
|
||||
var stats = new EnumMap<Stat, BigInteger>(Stat.class);
|
||||
for (var stat : Stat.values()) stats.put(stat, BigInteger.valueOf(10L + stat.ordinal()));
|
||||
var record = new CharacterRecord(UUID.randomUUID(), name, BigInteger.ZERO, stats, 7,
|
||||
BigInteger.valueOf(643), BigInteger.valueOf(9), new BigDecimal("12.25"),
|
||||
Set.of("fireball", "heal", "revive"), List.of("fireball", "", "heal", "", "revive", "", ""),
|
||||
Map.of("fireball", clock.instant().plusSeconds(30), "revive", clock.instant().plusSeconds(86400)),
|
||||
false, null, null);
|
||||
f.characters.create(record).get(5, TimeUnit.SECONDS);
|
||||
return record;
|
||||
}
|
||||
Holder holder(CharacterRecord record, String account, Material gear, double health, int food, float saturation, float exhaustion) {
|
||||
return new Holder(f.actor(record), account, gear, health, food, saturation, exhaustion);
|
||||
}
|
||||
Holder holder(CharacterRecord record) { return holder(record, "Account-" + UUID.randomUUID(), Material.IRON_AXE, 8.25, 9, 2.5f, 1.25f); }
|
||||
void activate(Holder holder) throws Exception {
|
||||
f.sessions.enter(holder.player); f.tick(); f.tick();
|
||||
assertTrue(f.sessions.active(holder.actor.id).isPresent());
|
||||
}
|
||||
CharacterRecord saved(UUID id) throws Exception { return f.characters.find(id).get(5, TimeUnit.SECONDS).orElseThrow(); }
|
||||
@Override public void close() throws Exception {
|
||||
events.close();
|
||||
try { f.close(); }
|
||||
finally { presentation.close(); }
|
||||
assertTrue(displayFailures.isEmpty(), displayFailures::toString);
|
||||
}
|
||||
}
|
||||
|
||||
private record Ordinary(UUID id, String account, double health, double maximum,
|
||||
int food, float saturation, float exhaustion, Component chat, Component tab) { }
|
||||
|
||||
/** Strict Player port adds observable ordinary nutrition/identity to the existing native-inventory actor. */
|
||||
private static final class Holder {
|
||||
final EquipmentSessionsNativeTest.Actor actor;
|
||||
final Player player;
|
||||
final String account;
|
||||
final Component chat;
|
||||
final Component tab;
|
||||
int food;
|
||||
float saturation;
|
||||
float exhaustion;
|
||||
Holder(EquipmentSessionsNativeTest.Actor actor, String account, Material gear,
|
||||
double health, int food, float saturation, float exhaustion) {
|
||||
this.actor = actor; this.account = account; this.food = food;
|
||||
this.saturation = saturation; this.exhaustion = exhaustion;
|
||||
chat = Component.text("ordinary chat " + account); tab = Component.text("ordinary tab " + account);
|
||||
actor.health = health; actor.inventory.setItem(0, new ItemStack(gear));
|
||||
player = (Player) Proxy.newProxyInstance(Player.class.getClassLoader(), new Class<?>[]{Player.class}, (proxy, method, args) -> {
|
||||
assertSame(actor.main, Thread.currentThread(), "Ordinary Player access stays on the server thread");
|
||||
return switch (method.getName()) {
|
||||
case "getName" -> account;
|
||||
case "displayName" -> { assertEquals(0, method.getParameterCount()); yield chat; }
|
||||
case "playerListName" -> { assertEquals(0, method.getParameterCount()); yield tab; }
|
||||
case "getFoodLevel" -> this.food;
|
||||
case "setFoodLevel" -> { this.food = (Integer) args[0]; yield null; }
|
||||
case "getSaturation" -> this.saturation;
|
||||
case "setSaturation" -> { this.saturation = (Float) args[0]; yield null; }
|
||||
case "getExhaustion" -> this.exhaustion;
|
||||
case "setExhaustion" -> { this.exhaustion = (Float) args[0]; yield null; }
|
||||
default -> {
|
||||
try { yield method.invoke(actor.player, args); }
|
||||
catch (InvocationTargetException failure) { throw failure.getCause(); }
|
||||
}
|
||||
};
|
||||
});
|
||||
var grid = new ManualCraftPlanNativeTest.Fixture(2, 1).grid;
|
||||
actor.view = new org.bukkit.craftbukkit.inventory.CraftAbstractInventoryView() {
|
||||
@Override public org.bukkit.inventory.Inventory getTopInventory() { return grid; }
|
||||
@Override public org.bukkit.inventory.PlayerInventory getBottomInventory() { return actor.inventory; }
|
||||
@Override public org.bukkit.entity.HumanEntity getPlayer() { return player; }
|
||||
@Override public org.bukkit.event.inventory.InventoryType getType() { return org.bukkit.event.inventory.InventoryType.CRAFTING; }
|
||||
@Override public ItemStack getCursor() { return actor.cursor; }
|
||||
@Override public void setCursor(ItemStack item) { actor.cursor = item; }
|
||||
@Override public String getTitle() { return "Whole-character native fixture"; }
|
||||
@Override public String getOriginalTitle() { return getTitle(); }
|
||||
@Override public void setTitle(String title) { throw new AssertionError("Unexpected title mutation"); }
|
||||
@Override public org.bukkit.inventory.MenuType getMenuType() { return null; }
|
||||
};
|
||||
}
|
||||
Ordinary ordinary() {
|
||||
return new Ordinary(player.getUniqueId(), player.getName(), player.getHealth(),
|
||||
player.getAttribute(org.bukkit.attribute.Attribute.MAX_HEALTH).getValue(),
|
||||
player.getFoodLevel(), player.getSaturation(), player.getExhaustion(), player.displayName(), player.playerListName());
|
||||
}
|
||||
}
|
||||
|
||||
/** Output boundary only: native overhead/chat/tab adapters have separate tests owned by the parent. */
|
||||
private static final class RecordingOutput implements CharacterPresentation.Output {
|
||||
final Thread main = Thread.currentThread();
|
||||
final ArrayList<CharacterPresentation.View> shown = new ArrayList<>();
|
||||
final ArrayList<CharacterPresentation.View> renamed = new ArrayList<>();
|
||||
final ArrayList<CharacterPresentation.View> cleared = new ArrayList<>();
|
||||
java.util.function.Consumer<CharacterPresentation.View> onClear = ignored -> {};
|
||||
@Override public void show(Player player, CharacterPresentation.View view) {
|
||||
assertSame(main, Thread.currentThread()); assertEquals(player.getUniqueId(), view.holder()); shown.add(view);
|
||||
}
|
||||
@Override public void rename(CharacterPresentation.View view) { assertSame(main, Thread.currentThread()); renamed.add(view); }
|
||||
@Override public void clear(CharacterPresentation.View view) {
|
||||
assertSame(main, Thread.currentThread()); onClear.accept(view); cleared.add(view);
|
||||
}
|
||||
@Override public void close() { assertSame(main, Thread.currentThread()); }
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ class DistributionTest {
|
||||
assertFalse(metadata.getVersion().contains("${"));
|
||||
assertEquals("games.dmg.fantasystick.FantasyStickPlugin", metadata.getMain());
|
||||
assertNotNull(metadata.getAPIVersion(), "Declare the native API compatibility contract");
|
||||
assertEquals(java.util.List.of("ProtocolLib"), metadata.getDepend());
|
||||
assertEquals(java.util.Set.of("fantasystick"), metadata.getCommands().keySet());
|
||||
assertEquals("fantasystick.admin", metadata.getCommands().get("fantasystick").get("permission"));
|
||||
assertEquals(1, metadata.getPermissions().size());
|
||||
@@ -40,7 +41,7 @@ class DistributionTest {
|
||||
bytecode.readUnsignedShort();
|
||||
assertEquals(69, bytecode.readUnsignedShort(), "Java 25 bytecode");
|
||||
}
|
||||
assertFalse(jar.stream().anyMatch(entry -> entry.getName().startsWith("org/")
|
||||
assertFalse(jar.stream().anyMatch(entry -> entry.getName().startsWith("com/comphenix/") || entry.getName().startsWith("org/")
|
||||
|| entry.getName().startsWith("net/") || entry.getName().endsWith("Test.class")),
|
||||
"Server API and test dependencies must not ship in the plugin");
|
||||
}
|
||||
|
||||
@@ -183,6 +183,39 @@ class EquipmentSessionStoreTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void completedExitUsesRequestTimeBehindAWorkerBacklogAndRetriesKeepThatDeadline() throws Exception {
|
||||
var entered = new CountDownLatch(1);
|
||||
var release = new CountDownLatch(1);
|
||||
var time = new AtomicReference<>(NOW);
|
||||
Clock clock = new Clock() {
|
||||
@Override public ZoneId getZone() { return ZoneOffset.UTC; }
|
||||
@Override public Clock withZone(ZoneId zone) { return this; }
|
||||
@Override public Instant instant() { return time.get(); }
|
||||
};
|
||||
try (var store = new EquipmentSessionStore(data, clock, (source, target) -> {
|
||||
entered.countDown(); waitFor(release); replace(source, target);
|
||||
})) {
|
||||
var preparation = store.prepare(player, session, character);
|
||||
CompletionStage<EquipmentSessionStore.State> completion;
|
||||
try {
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||
time.set(NOW.plusSeconds(2));
|
||||
completion = store.completeExit(player, session, Duration.ofSeconds(900));
|
||||
assertFalse(completion.toCompletableFuture().isDone());
|
||||
time.set(NOW.plusSeconds(3600)); // Worker cannot execute the exit until after its deadline.
|
||||
} finally { release.countDown(); }
|
||||
await(preparation);
|
||||
var completed = await(completion);
|
||||
assertNull(completed.pending());
|
||||
assertEquals(NOW.plusSeconds(2), completed.lastExit().exitedAt());
|
||||
assertEquals(NOW.plusSeconds(902), completed.lastExit().deadline());
|
||||
assertTrue(completed.canEnter(UUID.randomUUID(), Duration.ofSeconds(900), clock.instant()));
|
||||
assertEquals(completed, await(store.completeExit(player, session, Duration.ofDays(1))));
|
||||
assertEquals(completed, await(store.recordExit(player, session, Duration.ofDays(1))));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedForcedTemporaryReplacementPreservesOriginalAndRetryIsPossible() throws Exception {
|
||||
EquipmentSessionStore.State original;
|
||||
|
||||
Reference in new issue
Block a user