Files
purpur-fantasy-stick/src/nativeTest/java/games/dmg/fantasystick/RecipeDiscoveryNativeTest.java
T
dmg 3f104cb0e2
Release / release (push) Successful in 14m50s
feat(events): record native recipe discovery
2026-09-25 10:07:18 -04:00

180 lines
11 KiB
Java

package games.dmg.fantasystick;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.Mockito.doAnswer;
import games.dmg.fantasystick.items.CharacterSheets;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import org.bukkit.event.player.PlayerJoinEvent;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class RecipeDiscoveryNativeTest {
@TempDir Path data;
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
@Test void packagedRegistrationDiscoversOnlineAndJoinPlayersOnceWithoutMintingAndRetainsKnowledge() throws Exception {
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
var online = new FantasyStickLifecycleNativeTest.Actor(data);
f.players.put(online.core.id, online.player);
long records = records(data);
f.plugin.setEnabled(true);
var recipe = (org.bukkit.inventory.ShapelessRecipe) f.recipes.get(CharacterSheets.RECIPE);
assertNotNull(recipe);
assertEquals(org.bukkit.inventory.recipe.CraftingBookCategory.MISC, recipe.getCategory());
assertEquals(java.util.Set.of(CharacterSheets.RECIPE), online.knownRecipes);
assertEquals(List.of(List.of(CharacterSheets.RECIPE)), online.recipeAwards);
assertEquals(records, records(data));
assertTrue(new CharacterSheets().identify(recipe.getResult()).isEmpty());
var joining = new FantasyStickLifecycleNativeTest.Actor(data);
f.players.put(joining.core.id, joining.player);
f.dispatcher.accept(new PlayerJoinEvent(joining.player, "joined"));
f.dispatcher.accept(new PlayerJoinEvent(joining.player, "joined again"));
assertEquals(List.of(List.of(CharacterSheets.RECIPE)), joining.recipeAwards);
assertEquals(records + 1, records(data));
f.plugin.setEnabled(false);
f.dispatcher.accept(new PlayerJoinEvent(joining.player, "disabled"));
assertEquals(List.of(List.of(CharacterSheets.RECIPE)), joining.recipeAwards);
assertEquals(java.util.Set.of(CharacterSheets.RECIPE), joining.knownRecipes);
f.plugin.setEnabled(true);
assertEquals(List.of(List.of(CharacterSheets.RECIPE)), online.recipeAwards);
assertEquals(List.of(List.of(CharacterSheets.RECIPE)), joining.recipeAwards);
f.plugin.setEnabled(false);
}
var discoveries = events(data).stream().filter(e -> e.get("type").getAsString().endsWith("recipe.discovered"))
.toList();
assertEquals(2, discoveries.size(), "One native first discovery per account; reload/join creates no duplicate");
assertEquals(java.util.Set.of("enable_online", "join"), discoveries.stream()
.map(e -> e.getAsJsonObject("data").get("trigger").getAsString())
.collect(java.util.stream.Collectors.toSet()));
assertTrue(discoveries.stream().allMatch(e -> e.getAsJsonObject("data").get("recipe_id")
.getAsString().equals("fantasystick:character_sheet")));
assertEquals(2, discoveries.stream().map(e -> e.get("id").getAsString()).distinct().count());
}
@Test void playerFailureIsLoggedIsolatedAndRetryableButRegistrationFailureAwardsNobody() throws Exception {
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data.resolve("player-failure"))) {
var failing = new FantasyStickLifecycleNativeTest.Actor(data.resolve("player-failure"));
var healthy = new FantasyStickLifecycleNativeTest.Actor(data.resolve("player-failure"));
var fail = new AtomicBoolean(true);
doAnswer(call -> {
if (fail.getAndSet(false)) throw new IllegalStateException("simulated discovery failure");
var requested = ((java.util.Collection<?>) call.getArgument(0)).stream()
.map(org.bukkit.NamespacedKey.class::cast).toList();
failing.recipeAwards.add(requested); failing.knownRecipes.addAll(requested); return requested.size();
}).when(failing.player).discoverRecipes(anyCollection());
f.players.put(failing.core.id, failing.player); f.players.put(healthy.core.id, healthy.player);
var logs = new java.util.ArrayList<LogRecord>();
var handler = new Handler() {
@Override public void publish(LogRecord record) { logs.add(record); }
@Override public void flush() { }
@Override public void close() { }
};
f.plugin.getLogger().addHandler(handler);
try {
f.plugin.setEnabled(true);
assertTrue(f.recipes.containsKey(CharacterSheets.RECIPE));
assertTrue(failing.knownRecipes.isEmpty());
assertEquals(java.util.Set.of(CharacterSheets.RECIPE), healthy.knownRecipes);
assertTrue(logs.stream().anyMatch(log -> log.getMessage().contains("discover character-sheet recipe")));
f.dispatcher.accept(new PlayerJoinEvent(failing.player, "retry"));
assertEquals(java.util.Set.of(CharacterSheets.RECIPE), failing.knownRecipes);
} finally { f.plugin.getLogger().removeHandler(handler); }
}
var first = events(data.resolve("player-failure"));
assertEquals(1, first.stream().filter(e -> e.get("type").getAsString().endsWith("action.resolved")
&& e.getAsJsonObject("data").has("action_kind")
&& e.getAsJsonObject("data").get("action_kind").getAsString().equals("recipe_discovery")
&& e.getAsJsonObject("data").get("reason").getAsString().equals("native_failed")).count());
assertEquals(2, first.stream().filter(e -> e.get("type").getAsString().endsWith("recipe.discovered")).count(),
"Healthy and retried players each get one first-discovery acknowledgment");
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data.resolve("registration-failure"))) {
var online = new FantasyStickLifecycleNativeTest.Actor(data.resolve("registration-failure"));
f.players.put(online.core.id, online.player); f.failRegistrationAt = "recipe";
assertThrows(IllegalStateException.class, () -> f.plugin.setEnabled(true));
assertTrue(online.knownRecipes.isEmpty());
assertTrue(online.recipeAwards.isEmpty());
assertTrue(f.recipes.isEmpty());
}
var registration = data.resolve("registration-failure").resolve("events");
if (java.nio.file.Files.isDirectory(registration))
assertEquals(0, events(data.resolve("registration-failure")).stream()
.filter(e -> e.get("type").getAsString().endsWith("recipe.discovered")).count());
}
@Test void nativeDiscoveryWithoutPostconditionReportsUnavailableAndRetriesWithoutInventingSuccess() throws Exception {
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
f.plugin.setEnabled(true);
var player = new FantasyStickLifecycleNativeTest.Actor(data);
var unavailable = new AtomicBoolean(true);
doAnswer(call -> {
if (unavailable.getAndSet(false)) return 0;
var requested = ((java.util.Collection<?>) call.getArgument(0)).stream()
.map(org.bukkit.NamespacedKey.class::cast).toList();
player.recipeAwards.add(requested); player.knownRecipes.addAll(requested); return requested.size();
}).when(player.player).discoverRecipes(anyCollection());
f.players.put(player.core.id, player.player);
f.dispatcher.accept(new PlayerJoinEvent(player.player, "unavailable"));
assertTrue(player.knownRecipes.isEmpty());
f.dispatcher.accept(new PlayerJoinEvent(player.player, "retry"));
assertEquals(java.util.Set.of(CharacterSheets.RECIPE), player.knownRecipes);
f.plugin.setEnabled(false);
var records = events(data);
assertEquals(1, records.stream().filter(e -> e.get("type").getAsString().endsWith("recipe.discovered")
&& e.getAsJsonObject("data").get("player_id").getAsString().equals(player.core.id.toString())).count());
assertEquals(1, records.stream().filter(e -> e.get("type").getAsString().endsWith("action.resolved")
&& e.getAsJsonObject("data").has("reason")
&& e.getAsJsonObject("data").get("reason").getAsString().equals("native_unavailable")).count());
}
}
@Test void acknowledgedNativeDiscoveryRetainsStableIdentityThroughEventSinkOutage() throws Exception {
try (var f = new FantasyStickLifecycleNativeTest.Fixture(data)) {
f.plugin.setEnabled(true);
((games.dmg.fantasystick.events.LocalEventLog)
FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "eventLog")).close();
var joining = new FantasyStickLifecycleNativeTest.Actor(data);
f.players.put(joining.core.id, joining.player);
f.dispatcher.accept(new PlayerJoinEvent(joining.player, "join"));
assertEquals(java.util.Set.of(CharacterSheets.RECIPE), joining.knownRecipes);
f.plugin.setEnabled(false);
f.plugin.setEnabled(true);
f.dispatcher.accept(new PlayerJoinEvent(joining.player, "already known"));
f.plugin.setEnabled(false);
var discoveries = events(data).stream().filter(e -> e.get("type").getAsString().endsWith("recipe.discovered")
&& e.getAsJsonObject("data").get("player_id").getAsString().equals(joining.core.id.toString())).toList();
assertEquals(1, discoveries.stream().map(e -> e.get("id").getAsString()).distinct().count(),
"An acknowledged first discovery must be recoverable with its original event identity");
assertEquals("join", discoveries.getFirst().getAsJsonObject("data").get("trigger").getAsString());
assertEquals(List.of(List.of(CharacterSheets.RECIPE)), joining.recipeAwards);
}
}
private static List<com.google.gson.JsonObject> events(Path directory) throws Exception {
var entries = new java.util.ArrayList<com.google.gson.JsonObject>();
try (var files = java.nio.file.Files.walk(directory.resolve("events"))) {
for (var path : files.filter(p -> p.getFileName().toString().endsWith(".jsonl")).toList())
for (var line : java.nio.file.Files.readAllLines(path))
if (!line.isBlank()) entries.add(com.google.gson.JsonParser.parseString(line).getAsJsonObject());
}
return entries;
}
private static long records(Path directory) throws Exception {
var characters = directory.resolve("characters");
if (!java.nio.file.Files.isDirectory(characters)) return 0;
try (var files = java.nio.file.Files.list(characters)) {
return files.filter(file -> file.getFileName().toString().endsWith(".yml")).count();
}
}
}