Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1e7cdf888a |
No files matched your search
@@ -1,8 +1,8 @@
|
||||
# Fantasy Stick
|
||||
|
||||
**Development foundation only. No playable gameplay is registered, and this JAR is not ready for deployment.**
|
||||
**Development in progress. Manual character crafting is registered; fantasy sessions and the full RPG are not ready for deployment.**
|
||||
|
||||
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. These remain planned native features. 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. None is yet wired into playable crafting, health, session or spell interactions.
|
||||
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 is now assembled; fantasy-mode activation and most gameplay integrations remain planned. 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; health, session, anvil rename and spell interactions remain incomplete.
|
||||
|
||||
## Build and verify
|
||||
|
||||
@@ -17,7 +17,7 @@ Fantasy Stick is the proposed transferable-character RPG plugin for Social Minec
|
||||
|
||||
`check` runs Java packaging tests, TypeScript release-client/credential-helper tests, and a native compatibility test against the checksum-verified Purpur runtime. Native preparation downloads and patches the declared runtime and loads vanilla registries/components **without starting a listening server or creating a gameplay world**. The item tests decode signed written books with Minecraft's real codec, without a plugin instance or YAML lookup. A clean build repeats that preparation. Dependencies and runtime downloads require network access.
|
||||
|
||||
Build output is `build/libs/purpur-fantasy-stick-<version>.jar`. Server APIs, tests, credentials, and Node tooling are not bundled in the plugin. Runtime identity is `FantasyStick`, entrypoint `games.dmg.fantasystick.FantasyStickPlugin`, data folder `FantasyStick`, namespace `fantasystick`. Bootstrap registers no commands, permissions, recipes, sessions or gameplay listeners.
|
||||
Build output is `build/libs/purpur-fantasy-stick-<version>.jar`. Server APIs, tests, credentials, and Node tooling are not bundled in the plugin. Runtime identity is `FantasyStick`, entrypoint `games.dmg.fantasystick.FantasyStickPlugin`, data folder `FantasyStick`, namespace `fantasystick`. Startup registers the manual crafting controller and automated-Crafter guard before the character-sheet recipe. Commands, permissions, fantasy sessions and spells remain absent.
|
||||
|
||||
## Character storage and keepsakes
|
||||
|
||||
@@ -37,7 +37,7 @@ File-level atomic replacement is **not** atomicity with Minecraft inventory/play
|
||||
|
||||
Abandonment skips remaining queued writes and schedules cleanup for acknowledged, never-issued creations. Cleanup checks the original file identity/creation and modification attributes and exact bytes under the repository lock. Changed, replaced, corrupt, symlinked, busy or unidentifiable files are retained. Partial-save failure cleans only acknowledged creations and reports uncertain targets without deleting them. Shutdown rejection preserves records rather than inventing successful cleanup. Repeated cleanup cannot delete a later file. Restart never reconstructs cleanup authority from revision zero or scans records for automatic deletion/reissue.
|
||||
|
||||
Thirteen craft-persistence tests cover these backend boundaries, including worker timing, partial/post-rename failures, ownership changes, restart, shutdown, claim/abandon races, and mutated/cancelled observer futures. This is **not native inventory delivery**: the controller still must contain vanilla consumption, validate current view/lifecycle/content and commit actual items. Filesystem locks coordinate cooperating writers; concurrent external filesystem mutation must be excluded/coordinated. File flush/atomic rename does not establish directory power-loss durability or Minecraft/plugin-save atomicity. All create/update/cleanup mutations now share one fail-fast `characters/.records.lock` coordination file, so abandoning new characters does not accumulate one lock file per ID. Read-only atomic-file loads remain unlocked. The file stays present but its OS lock is held only for an operation, not an administrator-unlock flag. Never unlink it while writers may use it. Old per-ID lock files are left intact; no new ones are created.
|
||||
Thirteen craft-persistence tests cover these backend boundaries, including worker timing, partial/post-rename failures, ownership changes, restart, shutdown, claim/abandon races, and mutated/cancelled observer futures. This backend alone is **not native inventory delivery**: the assembled controller separately contains vanilla consumption, validates current view/lifecycle/content and commits actual items. Filesystem locks coordinate cooperating writers; concurrent external filesystem mutation must be excluded/coordinated. File flush/atomic rename does not establish directory power-loss durability or Minecraft/plugin-save atomicity. All create/update/cleanup mutations now share one fail-fast `characters/.records.lock` coordination file, so abandoning new characters does not accumulate one lock file per ID. Read-only atomic-file loads remain unlocked. The file stays present but its OS lock is held only for an operation, not an administrator-unlock flag. Never unlink it while writers may use it. Old per-ID lock files are left intact; no new ones are created.
|
||||
|
||||
**Upgrade boundary:** stop all older per-ID-protocol writers before opening the same data directory with this shared-lock implementation. Mixing versions or hot-reloading while old worker writes remain queued is unsafe. YAML format and record filenames are unchanged; no deployment or existing-server data migration has been performed. Contention between cooperating repository instances fails without mutation and can be retried, rather than blocking a server tick or deleting coordination files.
|
||||
|
||||
@@ -45,40 +45,54 @@ Thirteen craft-persistence tests cover these backend boundaries, including worke
|
||||
|
||||
`CharacterSheets` renders one Paper sheet from a saved live record, with its current name and the exact offhand instruction. `fantasystick:sheet_version` (integer 1) and `character_id` (UUID string) identify the character, with no owner lock or duplicated progress snapshot. Identification is only a reference: it does not authorize entry or replace saved-state/session validation. Rendering from a dead record is refused.
|
||||
|
||||
`CharacterFactory` allocates a fresh UUID and randomized two-part character name when explicitly called. It reuses the progression initializer for zero stats, level 1/zero XP, configured unspent points and full base health, with empty abilities/loadout/cooldowns and no prior death. Name collisions are allowed; identity is independent. Construction and recipe previews do not invoke allocation. Unit tests check fresh defaults/configured arbitrary-precision points, request-time allocation, seeded name variation and same-name/different-ID characters. A native composition test prepares a planned batch through YAML and verifies individually named sheets/IDs after native serialization without consuming or delivering inventory items. The actual craft-event controller is still absent.
|
||||
`CharacterFactory` allocates a fresh UUID and randomized two-part character name when explicitly called. It reuses the progression initializer for zero stats, level 1/zero XP, configured unspent points and full base health, with empty abilities/loadout/cooldowns and no prior death. Name collisions are allowed; identity is independent. Construction and recipe previews do not invoke allocation. Unit tests check fresh defaults/configured arbitrary-precision points, request-time allocation, seeded name variation and same-name/different-ID characters. A native composition test prepares a planned batch through YAML and verifies individually named sheets/IDs after native serialization without consuming or delivering inventory items. The assembled craft-event controller now invokes this allocator only for accepted current attempts.
|
||||
|
||||
The `fantasystick:character_sheet` shapeless recipe definition contains one stick, paper, feather and ink sac. Character creation is **manual player crafting only** (inventory grid or crafting table). `ManualCraftingGuard` cancels this recipe's automated `CrafterCraftEvent` before native consumption/ejection, without touching other recipes or reversing cancellations; register the guard with the eventual completed-crafting adapter before exposing the recipe. Its preview has no character metadata and allocates no identity/name. It is deliberately **not registered** yet: actual completion, bulk crafting, cancellation/save handling and anvil rename persistence still need their event adapters. Presentation edits preserving metadata are tested, not a claim that complete anvil transactions work.
|
||||
The `fantasystick:character_sheet` shapeless recipe definition contains one stick, paper, feather and ink sac. Character creation is **manual player crafting only** (inventory grid or crafting table). `ManualCraftingGuard` cancels this recipe's automated `CrafterCraftEvent` before native consumption/ejection, without touching other recipes or reversing cancellations. Startup installs this guard and the manual controller before exposing the recipe. Its preview has no character metadata and allocates no identity/name. Manual completion, bulk crafting and cancellation/save handling are registered; anvil rename persistence remains unimplemented. Presentation edits preserving metadata are tested, not a claim that complete anvil transactions work.
|
||||
|
||||
## Manual craft planning (not delivery)
|
||||
|
||||
`ManualCraftPlan` reads real crafting inventories without mutation. It calculates one result for cursor/number/offhand clicks, distinct empty destination slots for shift-click, and single/bulk intent for Q/Ctrl-Q. It bounds quantity by ingredients and storage capacity, preserves native reverse storage order, rejects cancelled/non-craft/wrong-recipe/malformed input, and snapshots full item data rather than retaining mutable native stack mirrors. Returned leftovers are detached copies; `matches` detects changed inputs, result, recipe, cursor or planned destinations without overwriting intervening items.
|
||||
|
||||
This is **not a transaction commit**. Ten native planner/composition tests use actual 2×2/3×3 crafting containers, player storage, menu-carried stacks and recipe holders, with the absent player/network boundary stubbed. They do not execute packet dispatch or vanilla result consumption. A controller still needs one-use lifecycle tokens (a native menu may be reused after close/reopen), wiring of name/ID allocation and asynchronous persistence, reentrant matrix-update handling and delivery. Drop intent is not proof that a cancellable native drop succeeds. No recipe/listener registration, recovery policy or cross-save atomicity is added by this planner.
|
||||
This is **not a transaction commit**. Eleven native planner/composition tests use actual 2×2/3×3 crafting containers, player storage, menu-carried stacks and recipe holders, with the absent player/network boundary stubbed. They do not execute packet dispatch or vanilla result consumption. The assembled controller separately supplies one-use lifecycle tokens (a native menu may be reused after close/reopen), allocation/persistence wiring, reentrant update handling and delivery. Drop intent is not proof that a cancellable native drop succeeds. No recipe/listener registration, recovery policy or cross-save atomicity is added by this planner.
|
||||
|
||||
## Fixed-destination craft delivery (not registered)
|
||||
## Fixed-destination craft delivery
|
||||
|
||||
`ManualCraftDelivery` can apply a validated plan and exact-sized saved batch to the cursor, selected hotbar/offhand slot or bulk storage destinations. It rechecks current contents before claiming delivery, constructs all sheets first, then debits fresh native input mirrors and places all outputs before triggering one matrix recomputation. This deliberately relies on the pinned Purpur 2618 mirror/count/setter behavior. No further adapter-planned writes occur after the prepare-callback boundary. Existing native setters may send packets; this is not packet-silent or exception/crash-atomic.
|
||||
|
||||
Nine native delivery tests cover normal/right-click, bulk and exact-slot delivery, partial ingredient metadata, empty first matrix cells, stale context refusal, mismatched/abandoned/reused batches, reentrancy, callback item changes, new-menu cursor safety and post-callback exceptions. The fixture uses actual containers/cursor stacks and intercepts `slotsChanged`; it does not execute a listening server's recipe manager or event dispatch. A mismatch refuses before consuming cleanup authority; an exception after claiming delivery conservatively retains records rather than replaying or rolling back.
|
||||
|
||||
The caller still must contain vanilla consumption, validate a one-use lifecycle/attempt token, schedule on the server thread, pass the player's actual current view and synchronize the appropriate client menu afterward. World-drop plans return `UNSUPPORTED_ROUTE` unchanged in this component; that is not a registered gameplay policy. No completed-craft listener or recipe is exposed yet.
|
||||
The caller still must contain vanilla consumption, validate a one-use lifecycle/attempt token, schedule on the server thread, pass the player's actual current view and synchronize the appropriate client menu afterward. World-drop plans return `UNSUPPORTED_ROUTE` unchanged in this component; that is not a registered gameplay policy. The registered controller uses this component only for fixed destinations and routes Q/Ctrl-Q separately.
|
||||
|
||||
## Q/Ctrl-Q craft delivery (not registered)
|
||||
## Q/Ctrl-Q craft delivery
|
||||
|
||||
Q/Ctrl-Q remain supported scope; no shortcut restriction was accepted or enabled. `ManualDropDelivery` executes saved drop plans one unit at a time, checking original contents minus completed debits before every next unit. `PlayerSheetDrops` creates an unspawned item, dispatches `PlayerDropItemEvent`, revalidates, and uses native `Item.spawnAt` for the cancellable `ItemSpawnEvent` path. It never uses inventory-source dropping or cancellation's return-to-inventory fallback. A successful unit consumes one ingredient set, then recomputes; cancellation stops the suffix without charging it.
|
||||
|
||||
Thirteen additional tests cover sequential/bulk/cancelled drops, exact remaining-input validation, stale context, changed/removed entities, same-batch reentry and exceptions. Tests combine real native matrices, serialized sheets, YAML and Paper's event dispatcher; world insertion itself remains an explicit API boundary double, supplemented by pinned-runtime bytecode inspection. No live world or packet dispatch is claimed.
|
||||
|
||||
After public callbacks, records are conservatively retained—including unused batch records. Repeated late cancellations can therefore accumulate records. A spawn callback can change inventory after an output escapes but before a safe debit; `UNCONFIRMED` means stop/report without speculative charging, deletion, rollback or replay. This is not arbitrary-plugin/cross-save atomicity. The controller must hold a per-attempt guard across callbacks (including against newly started attempts), revalidate actual current view/lifecycle, and synchronize the client. The controller now has native lifecycle coverage as described below, but it and the recipe remain unregistered.
|
||||
After public callbacks, records are conservatively retained—including unused batch records. Repeated late cancellations can therefore accumulate records. A spawn callback can change inventory after an output escapes but before a safe debit; `UNCONFIRMED` means stop/report without speculative charging, deletion, rollback or replay. This is not arbitrary-plugin/cross-save atomicity. The controller must hold a per-attempt guard across callbacks (including against newly started attempts), revalidate actual current view/lifecycle, and synchronize the client. The registered controller supplies these guards and has native lifecycle coverage as described below.
|
||||
|
||||
## Manual craft controller (not registered)
|
||||
## Manual craft controller
|
||||
|
||||
`ManualCraftingController` contains vanilla handling before deferred work, allocates/saves accepted plans, returns delivery to an always-deferred server-thread callback and synchronizes the player's actual current inventory afterward. It uses attempt-object identity plus a delivery reservation that survives close/reopen and remains held through client-sync callbacks. It invalidates on close, accepted open, quit and disable; stale callbacks cannot clear a newer attempt, and rejected scheduling abandons owned unissued records without worker-side player access.
|
||||
|
||||
Twelve native controller tests cover saved deferred delivery, Q/Ctrl-Q routing with full storage, replay/reentrancy, menu reuse, client-sync reentry, pre-existing cancellation/unrelated recipes, rejected intents, allocation/save/scheduler failures, postclaim exceptions and retained-file reporting. Review reproduced a planning exception escaping before vanilla cancellation; capture now always cancels in `finally`. Async diagnostics are collected and asserted on the test thread rather than lost inside discarded futures. These tests invoke controller callbacks with real native grids/items/YAML and explicit player/scheduler/world boundaries, not a listening server. Clean and incremental packaging pass all 153 tests, audit and static analysis. Registration/lifecycle assembly is still pending.
|
||||
Twelve native controller tests cover saved deferred delivery, Q/Ctrl-Q routing with full storage, replay/reentrancy, menu reuse, client-sync reentry, pre-existing cancellation/unrelated recipes, rejected intents, allocation/save/scheduler failures, postclaim exceptions and retained-file reporting. Review reproduced a planning exception escaping before vanilla cancellation; capture now always cancels in `finally`. Async diagnostics are collected and asserted on the test thread rather than lost inside discarded futures. These tests invoke controller callbacks with real native grids/items/YAML and explicit player/scheduler/world boundaries, not a listening server. The controller checkpoint passed all 153 tests, audit and static analysis. The newer registration assembly is described below.
|
||||
|
||||
Scheduler injection must always enqueue (never run inline) or throw on rejection. Diagnostic callbacks must be nonthrowing, thread-safe and avoid native player access. The existing cancellation boolean cannot distinguish this handler's containment from a later plugin's independent veto; prior cancellations are preserved. No new Q/Ctrl-Q restriction, global inventory lock or automatic uncertain-delivery replay is introduced.
|
||||
|
||||
## Startup, configuration and shutdown
|
||||
|
||||
The packaged `FantasyStickPlugin` now wires storage, allocation, deferred scheduling, native drop-event dispatch and logger diagnostics. Both protective listeners are installed before `fantasystick:character_sheet` is exposed. Recipe-key collisions and partial registration failures clean up this enable attempt without replacing an existing recipe. Shutdown invalidates attempts before closing storage, unregisters its listeners and removes its recipe; removal exceptions are reported while remaining cleanup continues.
|
||||
|
||||
An optional `<plugin data>/config.yml` setting controls **new** characters' initial points:
|
||||
|
||||
```yaml
|
||||
starting-points: 40
|
||||
```
|
||||
|
||||
The default is 40; nonnegative arbitrary-precision integers are supported. Invalid values fail before gameplay registration. Existing saved characters are not rewritten. Configuration is read on enable; no reload command or automatic data migration is supplied.
|
||||
|
||||
Nine native lifecycle tests load the actual packaged entrypoint through a test configured classloader and native `JavaPlugin.setEnabled`, then register/dispatch through Paper. They cover registration ordering, configured points, all craft routes, distinct persisted sheets, installed Crafter cancellation, failed startup and shutdown/queued-callback cleanup. Server registry/scheduler/player/world insertion are explicit test ports; this is not a listening world/client test. The assembled checkpoint passes clean/incremental packaging, all 162 tests, audit and static analysis; remote publication is tracked separately. Anvil rename, fantasy-mode entry and the remaining RPG are not implemented.
|
||||
|
||||
## Native equipment adapter
|
||||
|
||||
`EquipmentStorage` preflights and moves nine hotbar/four armor slots into an actual named shulker in one free main-inventory slot. Item counts, metadata/damage/enchantments and legal nested contents remain native item data, accessible without this plugin. Eligibility is tested against the real vanilla shulker slot for every nonlegacy native item material; a main-inventory shulker does not prevent entry. Oversized or ineligible equipment and missing space produce unchanged refusals.
|
||||
@@ -103,4 +117,4 @@ The release credential must be a repository-write credential authorized for `dmg
|
||||
|
||||
Stories, design, open decisions and evidence are in the private [SoMC wiki project](https://git.garvis.dev/dmg/somc-okf/src/branch/main/projects/purpur-fantasy-stick/index.md). See [AGENTS.md](AGENTS.md) for the shared process. Source builds do not need wiki access.
|
||||
|
||||
No inventory recovery guarantees, gameplay balance, multiplayer behavior, or production compatibility have been verified by this bootstrap. Production rollout and GitOps changes remain separately approved; the development cycle never pushes GitOps.
|
||||
The documented crafting/cleanup boundaries are automated-test evidence, not cross-save atomicity, complete RPG balance, live multiplayer or production-compatibility verification. Production rollout and GitOps changes remain separately approved; the development cycle never pushes GitOps.
|
||||
@@ -1,7 +1,69 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import games.dmg.fantasystick.crafting.CharacterFactory;
|
||||
import games.dmg.fantasystick.crafting.ManualCraftingController;
|
||||
import games.dmg.fantasystick.crafting.ManualCraftingGuard;
|
||||
import games.dmg.fantasystick.crafting.PlayerSheetDrops;
|
||||
import games.dmg.fantasystick.items.CharacterSheets;
|
||||
import games.dmg.fantasystick.persistence.CharacterStorage;
|
||||
import games.dmg.fantasystick.persistence.YamlCharacterRepository;
|
||||
import games.dmg.fantasystick.progression.ProgressionRules;
|
||||
import java.time.Clock;
|
||||
import java.util.logging.Level;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
/** Build foundation only; gameplay is not yet registered or ready for deployment. */
|
||||
/** Manual character crafting; fantasy sessions and the remaining gameplay adapters are not registered yet. */
|
||||
public final class FantasyStickPlugin extends JavaPlugin {
|
||||
private CharacterStorage characters;
|
||||
private ManualCraftingController crafting;
|
||||
private ManualCraftingGuard guard;
|
||||
private boolean recipeRegistered;
|
||||
|
||||
@Override public void onEnable() {
|
||||
try {
|
||||
var defaults = ProgressionRules.defaults();
|
||||
var rules = new ProgressionRules(new java.math.BigInteger(getConfig().getString("starting-points", "40")),
|
||||
defaults.xpPerLevel(), defaults.maximumLevel());
|
||||
var factory = new CharacterFactory();
|
||||
characters = new CharacterStorage(new YamlCharacterRepository(getDataFolder().toPath()), Clock.systemUTC());
|
||||
crafting = new ManualCraftingController(characters, () -> factory.create(rules),
|
||||
task -> getServer().getScheduler().runTask(this, task),
|
||||
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()));
|
||||
guard = new ManualCraftingGuard();
|
||||
getServer().getPluginManager().registerEvents(crafting, this);
|
||||
getServer().getPluginManager().registerEvents(guard, this);
|
||||
recipeRegistered = getServer().addRecipe(new CharacterSheets().recipe());
|
||||
if (!recipeRegistered) throw new IllegalStateException("Character-sheet recipe key is already registered");
|
||||
} catch (RuntimeException failure) {
|
||||
try { onDisable(); }
|
||||
catch (RuntimeException cleanupFailure) { failure.addSuppressed(cleanupFailure); }
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void onDisable() {
|
||||
if (crafting != null) crafting.close();
|
||||
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 (characters != null) {
|
||||
characters.close();
|
||||
characters = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import games.dmg.fantasystick.items.CharacterSheets;
|
||||
import io.papermc.paper.plugin.configuration.PluginMeta;
|
||||
import io.papermc.paper.plugin.manager.NativeEventDispatcher;
|
||||
import io.papermc.paper.plugin.provider.classloader.ConfiguredPluginClassLoader;
|
||||
import io.papermc.paper.plugin.provider.classloader.PluginClassLoaderGroup;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.net.URL;
|
||||
import java.net.URLClassLoader;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.jar.JarFile;
|
||||
import java.util.logging.Logger;
|
||||
import org.bukkit.Keyed;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.Server;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.inventory.Recipe;
|
||||
import org.bukkit.plugin.PluginDescriptionFile;
|
||||
import org.bukkit.plugin.PluginManager;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.bukkit.scheduler.BukkitScheduler;
|
||||
import org.bukkit.scheduler.BukkitTask;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/** Loads the actual packaged entrypoint with native JavaPlugin lifecycle/dispatcher and explicit server ports. */
|
||||
class FantasyStickLifecycleNativeTest {
|
||||
@TempDir Path data;
|
||||
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
|
||||
|
||||
@Test
|
||||
void enableRegistersCraftControllerAndCrafterGuardBeforeExposingTheRecipe() throws Exception {
|
||||
try (var fixture = new Fixture(data)) {
|
||||
fixture.plugin.setEnabled(true);
|
||||
assertTrue(fixture.recipes.containsKey(CharacterSheets.RECIPE));
|
||||
int recipe = fixture.order.indexOf("recipe");
|
||||
assertTrue(fixture.order.indexOf("ManualCraftingController") >= 0);
|
||||
assertTrue(fixture.order.indexOf("ManualCraftingController") < recipe);
|
||||
assertTrue(fixture.order.indexOf("ManualCraftingGuard") >= 0);
|
||||
assertTrue(fixture.order.indexOf("ManualCraftingGuard") < recipe);
|
||||
assertTrue(fixture.tasks.isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void disableRemovesOnlyItsRecipeAndListenersAndIsSafeToRepeat() throws Exception {
|
||||
try (var fixture = new Fixture(data)) {
|
||||
var otherKey = new NamespacedKey("unrelated", "character_sheet");
|
||||
var other = new org.bukkit.inventory.ShapelessRecipe(otherKey, new org.bukkit.inventory.ItemStack(org.bukkit.Material.DIAMOND))
|
||||
.addIngredient(org.bukkit.Material.STICK);
|
||||
fixture.recipes.put(otherKey, other);
|
||||
fixture.plugin.setEnabled(true);
|
||||
assertTrue(java.util.Arrays.stream(org.bukkit.event.inventory.CraftItemEvent.getHandlerList().getRegisteredListeners())
|
||||
.anyMatch(listener -> listener.getPlugin() == fixture.plugin));
|
||||
fixture.plugin.setEnabled(false);
|
||||
assertFalse(fixture.recipes.containsKey(CharacterSheets.RECIPE));
|
||||
assertSame(other, fixture.recipes.get(otherKey));
|
||||
assertFalse(java.util.Arrays.stream(org.bukkit.event.inventory.CraftItemEvent.getHandlerList().getRegisteredListeners())
|
||||
.anyMatch(listener -> listener.getPlugin() == fixture.plugin));
|
||||
assertFalse(java.util.Arrays.stream(org.bukkit.event.block.CrafterCraftEvent.getHandlerList().getRegisteredListeners())
|
||||
.anyMatch(listener -> listener.getPlugin() == fixture.plugin));
|
||||
fixture.plugin.onDisable();
|
||||
assertSame(other, fixture.recipes.get(otherKey));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void recipeCollisionAndPartialListenerRegistrationFailureRollbackOnlyThisEnableAttempt() throws Exception {
|
||||
for (boolean collision : new boolean[] {true, false}) {
|
||||
try (var fixture = new Fixture(data)) {
|
||||
var existing = new org.bukkit.inventory.ShapelessRecipe(CharacterSheets.RECIPE,
|
||||
new org.bukkit.inventory.ItemStack(org.bukkit.Material.DIAMOND)).addIngredient(org.bukkit.Material.STICK);
|
||||
if (collision) fixture.recipes.put(CharacterSheets.RECIPE, existing);
|
||||
else fixture.failRegistrationAt = "ManualCraftingGuard";
|
||||
assertThrows(IllegalStateException.class, () -> fixture.plugin.setEnabled(true));
|
||||
if (collision) assertSame(existing, fixture.recipes.get(CharacterSheets.RECIPE));
|
||||
else assertFalse(fixture.recipes.containsKey(CharacterSheets.RECIPE));
|
||||
assertFalse(java.util.Arrays.stream(org.bukkit.event.inventory.CraftItemEvent.getHandlerList().getRegisteredListeners())
|
||||
.anyMatch(listener -> listener.getPlugin() == fixture.plugin));
|
||||
assertFalse(java.util.Arrays.stream(org.bukkit.event.block.CrafterCraftEvent.getHandlerList().getRegisteredListeners())
|
||||
.anyMatch(listener -> listener.getPlugin() == fixture.plugin));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void registeredCraftDispatchUsesConfiguredPointsAndOnlySavesAcceptedCompletedAttempts() throws Exception {
|
||||
for (String points : List.of("40", "0", "922337203685477580812345")) {
|
||||
var directory = data.resolve(points);
|
||||
java.nio.file.Files.createDirectories(directory);
|
||||
if (!points.equals("40")) java.nio.file.Files.writeString(directory.resolve("config.yml"), "starting-points: '" + points + "'\n");
|
||||
try (var fixture = new Fixture(directory)) {
|
||||
fixture.plugin.setEnabled(true);
|
||||
var actor = new ManualCraftingControllerNativeTest.Actor(2, 2);
|
||||
assertFalse(java.nio.file.Files.exists(directory.resolve("characters")));
|
||||
assertTrue(new CharacterSheets().identify(fixture.recipes.get(CharacterSheets.RECIPE).getResult()).isEmpty());
|
||||
var cancelled = actor.fixture.event(org.bukkit.event.inventory.ClickType.LEFT,
|
||||
org.bukkit.event.inventory.InventoryAction.PICKUP_ALL);
|
||||
cancelled.setCancelled(true);
|
||||
fixture.dispatcher.accept(cancelled);
|
||||
assertTrue(fixture.tasks.isEmpty());
|
||||
assertFalse(java.nio.file.Files.exists(directory.resolve("characters")));
|
||||
var event = actor.fixture.event(org.bukkit.event.inventory.ClickType.LEFT,
|
||||
org.bukkit.event.inventory.InventoryAction.PICKUP_ALL);
|
||||
fixture.dispatcher.accept(event);
|
||||
assertTrue(event.isCancelled());
|
||||
assertTrue(actor.fixture.view.getCursor().isEmpty());
|
||||
var complete = fixture.tasks.poll(5, java.util.concurrent.TimeUnit.SECONDS); assertNotNull(complete);
|
||||
complete.run();
|
||||
var id = new CharacterSheets().identify(actor.fixture.view.getCursor()).orElseThrow();
|
||||
var saved = new games.dmg.fantasystick.persistence.YamlCharacterRepository(directory).load(id).orElseThrow();
|
||||
assertEquals(new java.math.BigInteger(points), saved.unspentPoints());
|
||||
assertEquals(1, saved.level());
|
||||
assertEquals(1, actor.fixture.grid.getMatrix()[0].getAmount());
|
||||
assertEquals(1, actor.syncs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidStartingPointValuesFailBeforeInstallingAnyGameplay() throws Exception {
|
||||
for (String value : List.of("-1", "not-a-number", "1.5")) {
|
||||
var directory = data.resolve(value);
|
||||
java.nio.file.Files.createDirectories(directory);
|
||||
java.nio.file.Files.writeString(directory.resolve("config.yml"), "starting-points: '" + value + "'\n");
|
||||
try (var fixture = new Fixture(directory)) {
|
||||
assertThrows(IllegalArgumentException.class, () -> fixture.plugin.setEnabled(true));
|
||||
assertTrue(fixture.order.isEmpty());
|
||||
assertTrue(fixture.recipes.isEmpty());
|
||||
assertFalse(java.nio.file.Files.exists(directory.resolve("characters")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void installedGuardRejectsOnlyTheCharacterRecipeThroughTheNativeDispatcher() throws Exception {
|
||||
try (var fixture = new Fixture(data)) {
|
||||
fixture.plugin.setEnabled(true);
|
||||
var block = port(org.bukkit.block.Block.class, (name, args) -> { throw new AssertionError("Unexpected block access"); });
|
||||
for (boolean ours : new boolean[] {false, true}) {
|
||||
var recipe = ours ? new CharacterSheets().recipe() : new org.bukkit.inventory.ShapelessRecipe(
|
||||
new NamespacedKey("other", "character_sheet"), new org.bukkit.inventory.ItemStack(org.bukkit.Material.PAPER))
|
||||
.addIngredient(org.bukkit.Material.STICK);
|
||||
for (boolean cancelled : new boolean[] {false, true}) {
|
||||
var event = new org.bukkit.event.block.CrafterCraftEvent(block, recipe, recipe.getResult());
|
||||
event.setCancelled(cancelled);
|
||||
fixture.dispatcher.accept(event);
|
||||
assertEquals(ours || cancelled, event.isCancelled());
|
||||
assertEquals(recipe.getResult(), event.getResult());
|
||||
}
|
||||
}
|
||||
assertTrue(fixture.tasks.isEmpty());
|
||||
assertFalse(java.nio.file.Files.exists(data.resolve("characters")));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void disableInvalidatesAlreadyQueuedCraftCompletionBeforeStorageShutdown() throws Exception {
|
||||
try (var fixture = new Fixture(data)) {
|
||||
fixture.plugin.setEnabled(true);
|
||||
var actor = new ManualCraftingControllerNativeTest.Actor(2, 2);
|
||||
fixture.dispatcher.accept(actor.fixture.event(org.bukkit.event.inventory.ClickType.LEFT,
|
||||
org.bukkit.event.inventory.InventoryAction.PICKUP_ALL));
|
||||
var complete = fixture.tasks.poll(5, java.util.concurrent.TimeUnit.SECONDS); assertNotNull(complete);
|
||||
fixture.plugin.setEnabled(false);
|
||||
complete.run(); complete.run();
|
||||
assertTrue(actor.fixture.view.getCursor().isEmpty());
|
||||
assertEquals(2, actor.fixture.grid.getMatrix()[0].getAmount());
|
||||
assertEquals(0, actor.syncs);
|
||||
assertFalse(fixture.recipes.containsKey(CharacterSheets.RECIPE));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void installedManualRoutesDeliverSavedDistinctSheetsIncludingQAndCtrlQ() throws Exception {
|
||||
for (int route = 0; route < 6; route++) {
|
||||
var directory = data.resolve("route-" + route);
|
||||
try (var fixture = new Fixture(directory)) {
|
||||
fixture.plugin.setEnabled(true);
|
||||
var actor = new ManualCraftingControllerNativeTest.Actor(3, 2);
|
||||
var world = new PlayerSheetDropsNativeTest.WorldFixture();
|
||||
actor.eyeLocation = new org.bukkit.Location(world.world, 10, 66, 10);
|
||||
var dropped = new ArrayList<org.bukkit.inventory.ItemStack>();
|
||||
world.onSpawn = event -> {
|
||||
fixture.dispatcher.accept(event);
|
||||
if (!event.isCancelled()) dropped.add(event.getEntity().getItemStack().clone());
|
||||
};
|
||||
var click = switch (route) {
|
||||
case 0 -> org.bukkit.event.inventory.ClickType.RIGHT;
|
||||
case 1 -> org.bukkit.event.inventory.ClickType.SHIFT_LEFT;
|
||||
case 2 -> org.bukkit.event.inventory.ClickType.NUMBER_KEY;
|
||||
case 3 -> org.bukkit.event.inventory.ClickType.SWAP_OFFHAND;
|
||||
case 4 -> org.bukkit.event.inventory.ClickType.DROP;
|
||||
default -> org.bukkit.event.inventory.ClickType.CONTROL_DROP;
|
||||
};
|
||||
var action = switch (route) {
|
||||
case 0 -> org.bukkit.event.inventory.InventoryAction.PICKUP_HALF;
|
||||
case 1 -> org.bukkit.event.inventory.InventoryAction.MOVE_TO_OTHER_INVENTORY;
|
||||
case 2, 3 -> org.bukkit.event.inventory.InventoryAction.HOTBAR_SWAP;
|
||||
case 4 -> org.bukkit.event.inventory.InventoryAction.DROP_ONE_SLOT;
|
||||
default -> org.bukkit.event.inventory.InventoryAction.DROP_ALL_SLOT;
|
||||
};
|
||||
var event = new org.bukkit.event.inventory.CraftItemEvent(fixture.recipes.get(CharacterSheets.RECIPE),
|
||||
actor.fixture.view, org.bukkit.event.inventory.InventoryType.SlotType.RESULT, 0, click, action, route == 2 ? 4 : -1);
|
||||
fixture.dispatcher.accept(event);
|
||||
assertTrue(event.isCancelled());
|
||||
var complete = fixture.tasks.poll(5, java.util.concurrent.TimeUnit.SECONDS); assertNotNull(complete); complete.run();
|
||||
var outputs = new ArrayList<org.bukkit.inventory.ItemStack>(dropped);
|
||||
for (var item : actor.fixture.inventory.getContents()) if (new CharacterSheets().identify(item).isPresent()) outputs.add(item);
|
||||
if (new CharacterSheets().identify(actor.fixture.view.getCursor()).isPresent()) outputs.add(actor.fixture.view.getCursor());
|
||||
int quantity = route == 1 || route == 5 ? 2 : 1;
|
||||
assertEquals(quantity, outputs.size());
|
||||
var ids = outputs.stream().map(item -> new CharacterSheets().identify(item).orElseThrow()).toList();
|
||||
assertEquals(quantity, ids.stream().distinct().count());
|
||||
for (var id : ids) assertTrue(new games.dmg.fantasystick.persistence.YamlCharacterRepository(directory).load(id).isPresent());
|
||||
var first = actor.fixture.grid.getMatrix()[0];
|
||||
assertEquals(2 - quantity, first == null ? 0 : first.getAmount());
|
||||
assertEquals(1, actor.syncs);
|
||||
if (route >= 4) assertEquals(quantity, world.spawnCalls);
|
||||
complete.run();
|
||||
assertEquals(1, actor.syncs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void recipeRemovalFailureDoesNotPreventAttemptInvalidationOrListenerCleanup() throws Exception {
|
||||
try (var fixture = new Fixture(data)) {
|
||||
fixture.plugin.setEnabled(true);
|
||||
var actor = new ManualCraftingControllerNativeTest.Actor(2, 2);
|
||||
fixture.dispatcher.accept(actor.fixture.event(org.bukkit.event.inventory.ClickType.LEFT,
|
||||
org.bukkit.event.inventory.InventoryAction.PICKUP_ALL));
|
||||
var complete = fixture.tasks.poll(5, java.util.concurrent.TimeUnit.SECONDS); assertNotNull(complete);
|
||||
fixture.failRemoval = true;
|
||||
assertDoesNotThrow(() -> fixture.plugin.setEnabled(false));
|
||||
complete.run();
|
||||
assertTrue(actor.fixture.view.getCursor().isEmpty());
|
||||
assertEquals(2, actor.fixture.grid.getMatrix()[0].getAmount());
|
||||
assertFalse(java.util.Arrays.stream(org.bukkit.event.inventory.CraftItemEvent.getHandlerList().getRegisteredListeners())
|
||||
.anyMatch(listener -> listener.getPlugin() == fixture.plugin));
|
||||
fixture.failRemoval = false;
|
||||
fixture.plugin.onDisable();
|
||||
assertFalse(fixture.recipes.containsKey(CharacterSheets.RECIPE));
|
||||
}
|
||||
}
|
||||
|
||||
static final class Fixture implements AutoCloseable {
|
||||
final List<String> order = new ArrayList<>();
|
||||
final Map<NamespacedKey, Recipe> recipes = new HashMap<>();
|
||||
final LinkedBlockingQueue<Runnable> tasks = new LinkedBlockingQueue<>();
|
||||
final List<Listener> listeners = new ArrayList<>();
|
||||
String failRegistrationAt;
|
||||
boolean failRemoval;
|
||||
final NativeEventDispatcher dispatcher;
|
||||
final Server server;
|
||||
final Loader loader;
|
||||
final JavaPlugin plugin;
|
||||
|
||||
Fixture(Path data) throws Exception {
|
||||
var manager = port(PluginManager.class, (name, args) -> switch (name) {
|
||||
case "registerEvents" -> {
|
||||
var listener = (Listener) args[0];
|
||||
order.add(listener.getClass().getSimpleName());
|
||||
listeners.add(listener);
|
||||
dispatcher().register(listener, (org.bukkit.plugin.Plugin) args[1]);
|
||||
if (listener.getClass().getSimpleName().equals(failRegistrationAt)) throw new IllegalStateException("registration failed");
|
||||
yield null;
|
||||
}
|
||||
case "callEvent" -> { dispatcher().accept((org.bukkit.event.Event) args[0]); yield null; }
|
||||
default -> throw new AssertionError("Unexpected manager call " + name);
|
||||
});
|
||||
var scheduler = port(BukkitScheduler.class, (name, args) -> switch (name) {
|
||||
case "runTask" -> {
|
||||
assertTrue(((org.bukkit.plugin.Plugin) args[0]).isEnabled());
|
||||
tasks.add((Runnable) args[1]);
|
||||
yield port(BukkitTask.class, (method, values) -> { throw new AssertionError("Unexpected task call " + method); });
|
||||
}
|
||||
default -> throw new AssertionError("Unexpected scheduler call " + name);
|
||||
});
|
||||
server = port(Server.class, (name, args) -> switch (name) {
|
||||
case "getPluginManager" -> manager;
|
||||
case "getScheduler" -> scheduler;
|
||||
case "getLogger" -> Logger.getLogger("FantasyStick lifecycle fixture");
|
||||
case "isPrimaryThread" -> true;
|
||||
case "getOnlinePlayers" -> List.of();
|
||||
case "addRecipe" -> {
|
||||
order.add("recipe");
|
||||
var recipe = (Recipe) args[0];
|
||||
yield recipes.putIfAbsent(((Keyed) recipe).getKey(), recipe) == null;
|
||||
}
|
||||
case "getRecipe" -> recipes.get((NamespacedKey) args[0]);
|
||||
case "removeRecipe" -> {
|
||||
if (failRemoval) throw new IllegalStateException("Simulated registry removal failure");
|
||||
yield recipes.remove((NamespacedKey) args[0]) != null;
|
||||
}
|
||||
default -> throw new AssertionError("Unexpected server call " + name);
|
||||
});
|
||||
dispatcher = new NativeEventDispatcher(server);
|
||||
loader = new Loader(server, data);
|
||||
plugin = (JavaPlugin) loader.loadClass("games.dmg.fantasystick.FantasyStickPlugin").getConstructor().newInstance();
|
||||
}
|
||||
|
||||
private NativeEventDispatcher dispatcher() { return dispatcher; }
|
||||
@Override public void close() throws IOException {
|
||||
try { plugin.setEnabled(false); }
|
||||
finally { HandlerList.unregisterAll(plugin); loader.close(); }
|
||||
}
|
||||
}
|
||||
|
||||
static final class Loader extends URLClassLoader implements ConfiguredPluginClassLoader {
|
||||
private static final String ENTRY = "games.dmg.fantasystick.FantasyStickPlugin";
|
||||
private final Server server;
|
||||
private final Path data;
|
||||
private final Path jar = Path.of(System.getProperty("distribution.jar"));
|
||||
private final PluginDescriptionFile description;
|
||||
private JavaPlugin plugin;
|
||||
|
||||
Loader(Server server, Path data) throws Exception {
|
||||
super(new URL[] {Path.of(System.getProperty("distribution.jar")).toUri().toURL()}, FantasyStickLifecycleNativeTest.class.getClassLoader());
|
||||
this.server = server;
|
||||
this.data = data;
|
||||
try (var archive = new JarFile(jar.toFile()); var input = archive.getInputStream(archive.getJarEntry("plugin.yml"))) {
|
||||
description = new PluginDescriptionFile(input);
|
||||
}
|
||||
}
|
||||
|
||||
@Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
|
||||
synchronized (getClassLoadingLock(name)) {
|
||||
if (!name.equals(ENTRY)) return super.loadClass(name, resolve);
|
||||
var loaded = findLoadedClass(name);
|
||||
if (loaded == null) loaded = findClass(name);
|
||||
if (resolve) resolveClass(loaded);
|
||||
return loaded;
|
||||
}
|
||||
}
|
||||
@Override public Class<?> loadClass(String name, boolean resolve, boolean global, boolean libraries) throws ClassNotFoundException {
|
||||
return loadClass(name, resolve);
|
||||
}
|
||||
@Override public PluginMeta getConfiguration() { return description; }
|
||||
@Override public JavaPlugin getPlugin() { return plugin; }
|
||||
@Override public PluginClassLoaderGroup getGroup() { return null; }
|
||||
@Override public void init(JavaPlugin created) {
|
||||
plugin = created;
|
||||
created.init(server, description, data.toFile(), jar.toFile(), this, description, Logger.getLogger("FantasyStick lifecycle fixture"));
|
||||
}
|
||||
}
|
||||
|
||||
@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) -> {
|
||||
if (method.getDeclaringClass() == Object.class) return switch (method.getName()) {
|
||||
case "equals" -> object == args[0];
|
||||
case "hashCode" -> System.identityHashCode(object);
|
||||
case "toString" -> "Lifecycle port " + type.getSimpleName();
|
||||
default -> throw new AssertionError(method.getName());
|
||||
};
|
||||
return call.invoke(method.getName(), args);
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -414,6 +414,7 @@ class ManualCraftingControllerNativeTest {
|
||||
final Player player;
|
||||
final Thread serverThread = Thread.currentThread();
|
||||
InventoryView current;
|
||||
org.bukkit.Location eyeLocation;
|
||||
boolean online = true;
|
||||
int syncs;
|
||||
Runnable onSync = () -> { };
|
||||
@@ -427,6 +428,7 @@ class ManualCraftingControllerNativeTest {
|
||||
return switch (method.getName()) {
|
||||
case "getUniqueId" -> id;
|
||||
case "getOpenInventory" -> current;
|
||||
case "getEyeLocation" -> java.util.Objects.requireNonNull(eyeLocation).clone();
|
||||
case "isOnline" -> online;
|
||||
case "updateInventory" -> { syncs++; onSync.run(); yield null; }
|
||||
case "equals" -> object == args[0];
|
||||
|
||||
@@ -11,4 +11,8 @@ public final class NativeEventDispatcher implements Consumer<Event> {
|
||||
public NativeEventDispatcher(Server server) { manager = new PaperEventManager(server); }
|
||||
|
||||
@Override public void accept(Event event) { manager.callEvent(event); }
|
||||
|
||||
public void register(org.bukkit.event.Listener listener, org.bukkit.plugin.Plugin plugin) {
|
||||
manager.registerEvents(listener, plugin);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user