feat(recovery): publish saved-character recovery events
CI / build (pull_request) Failing after 11m15s
CI / build (push) Failing after 11m16s

This commit is contained in:
dmg committed 2026-10-07 09:18:18 -04:00
1 parent b62b7952e6
commit cd51ef127d
6 files changed
+902 -24

No files matched your search

@@ -0,0 +1,457 @@
package games.dmg.fantasystick;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import com.google.gson.JsonObject;
import games.dmg.fantasystick.persistence.CharacterRecord;
import games.dmg.fantasystick.persistence.CharacterStorage;
import java.nio.file.Path;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.bukkit.event.inventory.InventoryAction;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryType;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
/** Registered command -> exact native confirmation -> authoritative recovery -> published JSONL. */
class CharacterRecoveryEventsNativeTest {
@TempDir Path data;
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
@Test void livingRecoveryExportsCommittedAndCompletedWithFrozenIdentityAndRevokedGeneration() throws Exception {
try (var fixture = new QuestTrackingAuditNativeFixture(data)) {
var entry = new AdminActionEntryNativeTest.Entry(fixture, "player", true);
var recipient = new FantasyStickLifecycleNativeTest.Actor(data); recipient.accountName = "Recipient";
fixture.f.players.put(recipient.core.id, recipient.player);
var source = sourceRecord(data);
var before = storage(fixture.f).renameCharacter(source.id(), "Ω \"Knight\"\n<saved>")
.get(5, TimeUnit.SECONDS).orElseThrow();
assertTrue(entry.map.dispatch(entry.sender, "fstickadmin character recover " + before.id() + " Recipient"));
drain(fixture.f, recipient.core.id);
assertFalse(fixture.actor.inventories.isEmpty());
var confirmationClick = click(fixture.f, fixture.actor, fixture.actor.inventories.getLast(), 2);
drain(fixture.f, recipient.core.id);
fixture.f.dispatcher.accept(confirmationClick);
drain(fixture.f, recipient.core.id);
var after = storage(fixture.f).inspect(before.id()).get(5, TimeUnit.SECONDS).orElseThrow();
assertEquals(before.sheetGeneration().add(java.math.BigInteger.ONE), after.sheetGeneration());
FixtureAuditAcknowledgmentNativeTest.awaitOwnQuiescence(fixture.f);
var rows = recoveryRows(data);
assertEquals(List.of("character.recovery_committed", "character.recovery_completed"), rows.stream()
.map(row -> row.get("type").getAsString().replace("games.dmg.minecraft.fantasystick.", "")).toList());
assertEquals(1, rows.stream().map(row -> row.getAsJsonObject("data").get("operation_id").getAsString()).distinct().count());
for (var row : rows) {
var values = row.getAsJsonObject("data");
assertEquals("living_reissue", values.get("mode").getAsString());
assertEquals(before.id().toString(), values.get("recovered_character_id").getAsString());
assertEquals(before.name(), values.get("recovered_character_name").getAsString());
assertEquals(recipient.core.id.toString(), values.get("recipient_player_id").getAsString());
assertEquals(fixture.actor.core.id.toString(), values.get("admin_player_id").getAsString());
assertEquals(before.sheetGeneration().toString(), values.get("generation_before").getAsString());
assertEquals(after.sheetGeneration().toString(), values.get("generation_after").getAsString());
assertEquals(before.revision().toString(), values.get("revision_before").getAsString());
assertEquals(after.revision().toString(), values.get("revision_after").getAsString());
assertNotEquals(values.get("command_action_id").getAsString(), values.get("confirmation_action_id").getAsString());
assertTrue(values.has("recipient_location"));
assertTrue(values.has("location"));
assertFalse(row.toString().contains("fstickadmin character recover"));
}
assertEquals("pending_delivery", rows.getFirst().getAsJsonObject("data").get("outcome").getAsString());
assertEquals("acknowledged", rows.getLast().getAsJsonObject("data").get("outcome").getAsString());
var domain = rows.getFirst().getAsJsonObject("data");
var actions = AdminActionEntryNativeTest.rows(data);
assertTrue(actions.stream().anyMatch(row -> "request".equals(row.getAsJsonObject("data").get("stage").getAsString())
&& domain.get("command_action_id").equals(row.getAsJsonObject("data").get("action_id"))));
assertTrue(actions.stream().anyMatch(row -> "confirmation".equals(row.getAsJsonObject("data").get("stage").getAsString())
&& domain.get("confirmation_action_id").equals(row.getAsJsonObject("data").get("causation_id"))));
}
}
@Test void noTailRevivalExportsExactDeathAndPostDefeatHealthWithoutReplayingConsequences() throws Exception {
try (var fixture = new QuestTrackingAuditNativeFixture(data)) {
var entry = new AdminActionEntryNativeTest.Entry(fixture, "player", true);
var recipient = new FantasyStickLifecycleNativeTest.Actor(data); recipient.accountName = "Recipient";
fixture.f.players.put(recipient.core.id, recipient.player);
var source = sourceRecord(data);
var before = storage(fixture.f).recordDeath(source.id(), true).get(5, TimeUnit.SECONDS).orElseThrow();
entry.map.dispatch(entry.sender, "fstickadmin character recover " + before.id() + " Recipient");
drain(fixture.f, recipient.core.id);
click(fixture.f, fixture.actor, fixture.actor.inventories.getLast(), 6);
drain(fixture.f, recipient.core.id);
var after = storage(fixture.f).inspect(before.id()).get(5, TimeUnit.SECONDS).orElseThrow();
assertFalse(after.dead()); assertEquals(after.maximumHealth(), after.health()); assertEquals(before.coins(), after.coins());
FixtureAuditAcknowledgmentNativeTest.awaitOwnQuiescence(fixture.f);
assertEquals(2, recoveryRows(data).size());
for (var row : recoveryRows(data)) {
var values = row.getAsJsonObject("data");
assertEquals("no_tail_revival", values.get("mode").getAsString());
assertEquals(before.deathId().toString(), values.get("death_id").getAsString());
assertEquals(before.diedAt().toString(), values.get("death_time").getAsString());
assertFalse(values.get("alive_before").getAsBoolean()); assertTrue(values.get("alive_after").getAsBoolean());
assertEquals(after.health().toPlainString(), values.get("health_after").getAsString());
}
assertTrue(storage(fixture.f).restoreDeathRecordAdministratively(before.id(), before.deathId(), after.maximumHealth())
.get(5, TimeUnit.SECONDS).isEmpty());
}
}
@ParameterizedTest @ValueSource(strings = {"stale", "failed_commit"})
void preCommitRefusalsAndFailedWritesNeverPublishRecoverySuccess(String failure) throws Exception {
try (var fixture = new QuestTrackingAuditNativeFixture(data)) {
var entry = new AdminActionEntryNativeTest.Entry(fixture, "player", true);
var recipient = new FantasyStickLifecycleNativeTest.Actor(data); recipient.accountName = "Recipient";
fixture.f.players.put(recipient.core.id, recipient.player);
var source = sourceRecord(data);
var before = storage(fixture.f).inspect(source.id()).get(5, TimeUnit.SECONDS).orElseThrow();
entry.map.dispatch(entry.sender, "fstickadmin character recover " + before.id() + " Recipient");
drain(fixture.f, recipient.core.id);
Path lock = data.resolve("character-recoveries/.recoveries.lock");
if (failure.equals("stale")) storage(fixture.f).renameCharacter(before.id(), "After preview").get(5, TimeUnit.SECONDS);
else { java.nio.file.Files.createDirectories(lock.getParent()); java.nio.file.Files.createDirectory(lock); }
try {
click(fixture.f, fixture.actor, fixture.actor.inventories.getLast(), 2);
drain(fixture.f, recipient.core.id);
assertEquals(before.sheetGeneration(), storage(fixture.f).inspect(before.id()).get(5, TimeUnit.SECONDS).orElseThrow().sheetGeneration());
FixtureAuditAcknowledgmentNativeTest.awaitOwnQuiescence(fixture.f);
assertTrue(recoveryRows(data).isEmpty());
assertTrue(AdminActionEntryNativeTest.rows(data).stream().anyMatch(row -> row.getAsJsonObject("data").get("stage")
.getAsString().equals("result")));
} finally { if (failure.equals("failed_commit")) java.nio.file.Files.delete(lock); }
}
}
@ParameterizedTest @ValueSource(strings = {"destination", "native_write", "completion"})
void uncertainNativeOrCompletionFailureIsTruthfulAndCannotBlindlyDeliverAgain(String failure) throws Exception {
try (var fixture = new QuestTrackingAuditNativeFixture(data)) {
var f = fixture.f; var entry = new AdminActionEntryNativeTest.Entry(fixture, "player", true);
var recipient = new FantasyStickLifecycleNativeTest.Actor(data); recipient.accountName = "Recipient";
f.players.put(recipient.core.id, recipient.player);
var source = sourceRecord(data);
var before = storage(f).inspect(source.id()).get(5, TimeUnit.SECONDS).orElseThrow();
int destination = recipient.core.inventory.firstEmpty();
entry.map.dispatch(entry.sender, "fstickadmin character recover " + before.id() + " Recipient");
drain(f, recipient.core.id); click(f, fixture.actor, fixture.actor.inventories.getLast(), 2);
nextTask(f, recipient.core.id).run(); nextTask(f, recipient.core.id).run();
storage(f).inspect(UUID.randomUUID()).get(5, TimeUnit.SECONDS);
var delivery = nextTask(f, recipient.core.id);
Path lock = data.resolve("character-recoveries/.recoveries.lock");
if (failure.equals("destination")) recipient.core.inventory.setItem(destination, new org.bukkit.inventory.ItemStack(org.bukkit.Material.DIAMOND));
else if (failure.equals("completion")) { java.nio.file.Files.delete(lock); java.nio.file.Files.createDirectory(lock); }
else {
var proxy = (org.bukkit.inventory.PlayerInventory) java.lang.reflect.Proxy.newProxyInstance(
org.bukkit.inventory.PlayerInventory.class.getClassLoader(), new Class<?>[]{org.bukkit.inventory.PlayerInventory.class},
(ignored, method, args) -> {
try {
var result = method.invoke(recipient.core.inventory, args);
if (method.getName().equals("setItem")) throw new IllegalStateException("test-only failure after native sheet installation");
return result;
} catch (java.lang.reflect.InvocationTargetException cause) { throw cause.getCause(); }
});
when(recipient.player.getInventory()).thenReturn(proxy);
}
try {
delivery.run(); drain(f, recipient.core.id);
FixtureAuditAcknowledgmentNativeTest.awaitOwnQuiescence(f);
var rows = recoveryRows(data);
assertEquals(List.of("character.recovery_committed", "character.recovery_uncertain"), rows.stream()
.map(row -> row.get("type").getAsString().replace("games.dmg.minecraft.fantasystick.", "")).toList());
var uncertain = rows.getLast().getAsJsonObject("data");
assertEquals("uncertain", uncertain.get("outcome").getAsString());
assertEquals(!failure.equals("destination"), uncertain.get("native_write_may_have_occurred").getAsBoolean());
assertEquals(destination, uncertain.get("destination_slot").getAsInt());
assertThrows(java.util.concurrent.CompletionException.class, () -> storage(f).find(before.id()).join());
if (failure.equals("completion")) java.nio.file.Files.delete(lock);
var nativeBefore = recipient.core.snapshot();
entry.map.dispatch(entry.sender, "fstickadmin character recover " + before.id() + " Recipient");
drain(f, recipient.core.id);
assertArrayEquals(nativeBefore, recipient.core.snapshot());
FixtureAuditAcknowledgmentNativeTest.awaitOwnQuiescence(f);
assertEquals(2, recoveryRows(data).size(), "refused retry must not claim another domain outcome");
} finally {
if (java.nio.file.Files.isDirectory(lock)) java.nio.file.Files.delete(lock);
when(recipient.player.getInventory()).thenReturn(recipient.core.inventory);
}
}
}
@Test void restartReplaysRejectedEventsWithIdenticalIdsPayloadAndNoNativeOrCharacterReplay() throws Exception {
var received = new java.util.concurrent.CopyOnWriteArrayList<games.dmg.fantasystick.events.EventInput>();
UUID character; CharacterRecord after;
try (var fixture = new QuestTrackingAuditNativeFixture(data)) {
FixtureAuditAcknowledgmentNativeTest.awaitOwnQuiescence(fixture.f);
var bridge = FantasyStickLifecycleNativeTest.Fixture.field(fixture.f.plugin, "characterRecoveryEvents");
var outbox = FantasyStickLifecycleNativeTest.Fixture.field(bridge, "outbox");
var sink = outbox.getClass().getDeclaredField("sink"); sink.setAccessible(true);
java.util.function.Function<games.dmg.fantasystick.events.EventInput, java.util.concurrent.CompletionStage<games.dmg.fantasystick.events.LocalEventLog.Delivery>>
reject = event -> { received.add(event); return java.util.concurrent.CompletableFuture.completedFuture(
games.dmg.fantasystick.events.LocalEventLog.Delivery.REJECTED); };
sink.set(outbox, reject);
var entry = new AdminActionEntryNativeTest.Entry(fixture, "player", true);
var recipient = new FantasyStickLifecycleNativeTest.Actor(data); recipient.accountName = "Recipient";
fixture.f.players.put(recipient.core.id, recipient.player);
var source = sourceRecord(data); character = source.id();
entry.map.dispatch(entry.sender, "fstickadmin character recover " + character + " Recipient");
drain(fixture.f, recipient.core.id); click(fixture.f, fixture.actor, fixture.actor.inventories.getLast(), 2);
drain(fixture.f, recipient.core.id);
FixtureAuditAcknowledgmentNativeTest.awaitOwnQuiescence(fixture.f);
assertEquals(2, received.size()); assertTrue(recoveryRows(data).isEmpty());
after = storage(fixture.f).inspect(character).get(5, TimeUnit.SECONDS).orElseThrow();
}
try (var fixture = new QuestTrackingAuditNativeFixture(data)) {
ReskillEventsNativeTest.await(fixture.f, () -> { try { return recoveryRows(data).size() >= 2; }
catch (Exception failure) { throw new AssertionError(failure); } });
FixtureAuditAcknowledgmentNativeTest.awaitOwnQuiescence(fixture.f);
var rows = recoveryRows(data);
assertEquals(2, rows.stream().map(row -> row.get("id").getAsString()).distinct().count());
for (var input : received) {
var row = rows.stream().filter(value -> value.get("id").getAsString().equals(input.id().toString())).findFirst().orElseThrow();
assertEquals(input.time().toString(), row.get("time").getAsString());
var frozen = com.google.gson.JsonParser.parseString(games.dmg.fantasystick.events.CharacterRecoveryEventBridge.encode(input)).getAsJsonObject().getAsJsonObject("data");
for (var field : frozen.entrySet()) assertEquals(field.getValue(), row.getAsJsonObject("data").get(field.getKey()), field.getKey());
}
assertEquals(after, storage(fixture.f).inspect(character).get(5, TimeUnit.SECONDS).orElseThrow());
}
}
@ParameterizedTest @ValueSource(strings = {"completed", "uncertain"})
void ownerReceiptClosesHandoffGapAndSurvivesLaterReissueWithoutAuthorizingNativeReplay(String outcome) throws Exception {
var originals = new java.util.ArrayList<games.dmg.fantasystick.events.EventInput>();
UUID character; CharacterRecord finalState;
try (var fixture = new QuestTrackingAuditNativeFixture(data)) {
var f = fixture.f; FixtureAuditAcknowledgmentNativeTest.awaitOwnQuiescence(f);
var bridge = (games.dmg.fantasystick.events.CharacterRecoveryEventBridge)
FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "characterRecoveryEvents");
bridge.close(); bridge.drained().toCompletableFuture().get(5, TimeUnit.SECONDS);
var entry = new AdminActionEntryNativeTest.Entry(fixture, "player", true);
var recipient = new FantasyStickLifecycleNativeTest.Actor(data); recipient.accountName = "Recipient";
f.players.put(recipient.core.id, recipient.player);
var source = sourceRecord(data); character = source.id();
int destination = recipient.core.inventory.firstEmpty();
entry.map.dispatch(entry.sender, "fstickadmin character recover " + character + " Recipient");
drain(f, recipient.core.id); click(f, fixture.actor, fixture.actor.inventories.getLast(), 2);
if (outcome.equals("uncertain")) {
nextTask(f, recipient.core.id).run(); nextTask(f, recipient.core.id).run();
var delivery = nextTask(f, recipient.core.id);
recipient.core.inventory.setItem(destination, new org.bukkit.inventory.ItemStack(org.bukkit.Material.DIAMOND));
delivery.run();
}
drain(f, recipient.core.id);
originals.addAll(receiptEvents(data, character));
assertEquals(2, originals.size());
if (outcome.equals("completed")) {
entry.map.dispatch(entry.sender, "fstickadmin character recover " + character + " Recipient");
drain(f, recipient.core.id); click(f, fixture.actor, fixture.actor.inventories.getLast(), 2);
drain(f, recipient.core.id); originals.addAll(receiptEvents(data, character));
assertEquals(4, originals.size());
}
assertTrue(recoveryRows(data).isEmpty(), "no audit worker accepted the handoff");
finalState = storage(f).inspect(character).get(5, TimeUnit.SECONDS).orElseThrow();
}
try (var fixture = new QuestTrackingAuditNativeFixture(data)) {
ReskillEventsNativeTest.await(fixture.f, () -> { try { return recoveryRows(data).size() >= originals.size(); }
catch (Exception failure) { throw new AssertionError(failure); } });
FixtureAuditAcknowledgmentNativeTest.awaitOwnQuiescence(fixture.f);
var rows = recoveryRows(data);
assertEquals(originals.size(), rows.stream().map(row -> row.get("id").getAsString()).distinct().count());
for (var original : originals) assertFrozen(original, rows);
assertEquals(finalState, storage(fixture.f).inspect(character).get(5, TimeUnit.SECONDS).orElseThrow());
if (outcome.equals("uncertain")) {
assertTrue(rows.stream().noneMatch(row -> row.get("type").getAsString().endsWith("recovery_completed")));
assertThrows(java.util.concurrent.CompletionException.class, () -> storage(fixture.f).find(character).join());
}
}
}
@ParameterizedTest @ValueSource(strings = {"before_move", "after_move"})
void fileMoveFailureOnlyEmitsCommitWhenAuthoritativeReplacementIsProvedAndNeverReleasesAmbiguousCustody(String moment) throws Exception {
try (var fixture = new QuestTrackingAuditNativeFixture(data)) {
var f = fixture.f; var entry = new AdminActionEntryNativeTest.Entry(fixture, "player", true);
var recipient = new FantasyStickLifecycleNativeTest.Actor(data); recipient.accountName = "Recipient";
f.players.put(recipient.core.id, recipient.player);
var source = sourceRecord(data);
var before = storage(f).inspect(source.id()).get(5, TimeUnit.SECONDS).orElseThrow();
entry.map.dispatch(entry.sender, "fstickadmin character recover " + before.id() + " Recipient");
drain(f, recipient.core.id);
var repository = FantasyStickLifecycleNativeTest.Fixture.field(storage(f), "repository");
var mover = repository.getClass().getDeclaredField("replacement"); mover.setAccessible(true);
var original = mover.get(repository);
var failing = java.lang.reflect.Proxy.newProxyInstance(mover.getType().getClassLoader(), new Class<?>[]{mover.getType()},
(ignored, method, args) -> {
assertEquals("move", method.getName());
if (moment.equals("after_move")) java.nio.file.Files.move((Path) args[0], (Path) args[1],
java.nio.file.StandardCopyOption.ATOMIC_MOVE, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
throw new java.io.IOException("test-only recovery move failure " + moment);
});
mover.set(repository, failing);
try { click(f, fixture.actor, fixture.actor.inventories.getLast(), 2); drain(f, recipient.core.id); }
finally { mover.set(repository, original); }
FixtureAuditAcknowledgmentNativeTest.awaitOwnQuiescence(f);
var saved = storage(f).inspect(before.id()).get(5, TimeUnit.SECONDS).orElseThrow();
if (moment.equals("before_move")) { assertEquals(before, saved); assertTrue(recoveryRows(data).isEmpty()); }
else {
assertEquals(before.sheetGeneration().add(java.math.BigInteger.ONE), saved.sheetGeneration());
var rows = recoveryRows(data);
assertEquals(List.of("character.recovery_committed", "character.recovery_uncertain"), rows.stream()
.map(row -> row.get("type").getAsString().replace("games.dmg.minecraft.fantasystick.", "")).toList());
assertEquals("commit_acknowledgment", rows.getLast().getAsJsonObject("data").get("uncertain_stage").getAsString());
assertFalse(rows.getLast().getAsJsonObject("data").get("native_write_may_have_occurred").getAsBoolean());
assertThrows(java.util.concurrent.CompletionException.class, () -> storage(f).find(before.id()).join());
}
}
}
@ParameterizedTest @ValueSource(strings = {"committed", "prepared"})
void startupReconcilesOnlyProvedCommitAndRetainsUncertaintyWithoutDeliveryOrUnlock(String phase) throws Exception {
UUID character; CharacterRecord committed; games.dmg.fantasystick.events.EventInput original;
try (var fixture = new QuestTrackingAuditNativeFixture(data)) {
var f = fixture.f; var entry = new AdminActionEntryNativeTest.Entry(fixture, "player", true);
var recipient = new FantasyStickLifecycleNativeTest.Actor(data); recipient.accountName = "Recipient";
f.players.put(recipient.core.id, recipient.player);
var source = sourceRecord(data); character = source.id();
entry.map.dispatch(entry.sender, "fstickadmin character recover " + character + " Recipient");
drain(f, recipient.core.id); click(f, fixture.actor, fixture.actor.inventories.getLast(), 2);
nextTask(f, recipient.core.id).run(); nextTask(f, recipient.core.id).run();
// Simulated lost callback after real generation mutation, before any native sheet write.
nextTask(f, recipient.core.id);
committed = storage(f).inspect(character).get(5, TimeUnit.SECONDS).orElseThrow();
original = receiptEvents(data, character).getFirst();
if (phase.equals("prepared")) {
var path = data.resolve("character-recoveries").resolve(character + ".yml");
java.nio.file.Files.writeString(path, java.nio.file.Files.readString(path).replace("phase: COMMITTED", "phase: PREPARED"));
}
}
try (var fixture = new QuestTrackingAuditNativeFixture(data)) {
ReskillEventsNativeTest.await(fixture.f, () -> { try { return recoveryRows(data).stream()
.anyMatch(row -> row.get("type").getAsString().endsWith("recovery_uncertain")); }
catch (Exception failure) { throw new AssertionError(failure); } });
FixtureAuditAcknowledgmentNativeTest.awaitOwnQuiescence(fixture.f);
var rows = recoveryRows(data); assertFrozen(original, rows);
var uncertain = rows.stream().filter(row -> row.get("type").getAsString().endsWith("recovery_uncertain")).findFirst().orElseThrow();
assertEquals("reconciliation", uncertain.getAsJsonObject("data").get("uncertain_stage").getAsString());
assertTrue(uncertain.getAsJsonObject("data").get("native_write_may_have_occurred").getAsBoolean());
assertTrue(rows.stream().noneMatch(row -> row.get("type").getAsString().endsWith("recovery_completed")));
assertEquals(committed, storage(fixture.f).inspect(character).get(5, TimeUnit.SECONDS).orElseThrow());
assertThrows(java.util.concurrent.CompletionException.class, () -> storage(fixture.f).find(character).join());
var entry = new AdminActionEntryNativeTest.Entry(fixture, "player", true);
var recipient = new FantasyStickLifecycleNativeTest.Actor(data); recipient.accountName = "Recipient";
fixture.f.players.put(recipient.core.id, recipient.player);
var inventory = recipient.core.snapshot();
entry.map.dispatch(entry.sender, "fstickadmin character recover " + character + " Recipient");
drain(fixture.f, recipient.core.id);
// A read-only preview is not recovery authority. Exercise the explicit confirmation,
// where authoritative unresolved custody must refuse the actual generation/delivery mutation.
assertEquals(1, fixture.actor.inventories.size());
click(fixture.f, fixture.actor, fixture.actor.inventories.getLast(), 2);
drain(fixture.f, recipient.core.id);
FixtureAuditAcknowledgmentNativeTest.awaitOwnQuiescence(fixture.f);
assertArrayEquals(inventory, recipient.core.snapshot());
assertEquals(committed, storage(fixture.f).inspect(character).get(5, TimeUnit.SECONDS).orElseThrow());
assertTrue(recoveryRows(data).stream().noneMatch(row -> row.get("type").getAsString().endsWith("recovery_completed")));
}
}
@Test void repeatedDeferredDeliveryCallbackCannotReclassifyAcknowledgedRecoveryOrWriteAnotherSheet() throws Exception {
try (var fixture = new QuestTrackingAuditNativeFixture(data)) {
var f = fixture.f; var entry = new AdminActionEntryNativeTest.Entry(fixture, "player", true);
var recipient = new FantasyStickLifecycleNativeTest.Actor(data); recipient.accountName = "Recipient";
f.players.put(recipient.core.id, recipient.player);
var source = sourceRecord(data);
var character = source.id();
entry.map.dispatch(entry.sender, "fstickadmin character recover " + character + " Recipient");
drain(f, recipient.core.id); click(f, fixture.actor, fixture.actor.inventories.getLast(), 2);
nextTask(f, recipient.core.id).run(); nextTask(f, recipient.core.id).run();
var delivery = nextTask(f, recipient.core.id); delivery.run(); drain(f, recipient.core.id);
FixtureAuditAcknowledgmentNativeTest.awaitOwnQuiescence(f);
assertEquals(2, recoveryRows(data).size());
var saved = storage(f).inspect(character).get(5, TimeUnit.SECONDS).orElseThrow();
var inventory = recipient.core.snapshot();
delivery.run(); drain(f, recipient.core.id);
FixtureAuditAcknowledgmentNativeTest.awaitOwnQuiescence(f);
assertArrayEquals(inventory, recipient.core.snapshot());
assertEquals(saved, storage(f).inspect(character).get(5, TimeUnit.SECONDS).orElseThrow());
assertEquals(2, recoveryRows(data).size(), "one callback lifetime must not produce a false uncertain stage after success");
}
}
static List<games.dmg.fantasystick.events.EventInput> receiptEvents(Path data, UUID character) throws Exception {
var line = java.nio.file.Files.readAllLines(data.resolve("character-recoveries").resolve(character + ".yml"))
.stream().filter(value -> value.startsWith("events: ")).findFirst().orElseThrow().substring(8);
var json = new String(java.util.Base64.getDecoder().decode(line), java.nio.charset.StandardCharsets.UTF_8);
return com.google.gson.JsonParser.parseString(json).getAsJsonArray().asList().stream()
.map(value -> games.dmg.fantasystick.events.CharacterRecoveryEventBridge.decode(value.getAsString())).toList();
}
static void assertFrozen(games.dmg.fantasystick.events.EventInput input, List<JsonObject> rows) {
for (var row : rows.stream().filter(value -> value.get("id").getAsString().equals(input.id().toString())).toList()) {
assertEquals(input.time().toString(), row.get("time").getAsString());
var context = input.context();
assertEquals(context.playerId().toString(), row.get("playerid").getAsString());
if (context.characterId() != null) {
assertEquals(context.characterId().toString(), row.get("characterid").getAsString());
assertEquals(context.sessionId().toString(), row.getAsJsonObject("data").get("session_id").getAsString());
}
var encoded = com.google.gson.JsonParser.parseString(games.dmg.fantasystick.events.CharacterRecoveryEventBridge.encode(input))
.getAsJsonObject();
if (context.location() != null) assertEquals(encoded.getAsJsonObject("context").getAsJsonObject("location"),
row.getAsJsonObject("data").getAsJsonObject("location"));
var frozen = com.google.gson.JsonParser.parseString(games.dmg.fantasystick.events.CharacterRecoveryEventBridge.encode(input))
.getAsJsonObject().getAsJsonObject("data");
for (var field : frozen.entrySet()) assertEquals(field.getValue(), row.getAsJsonObject("data").get(field.getKey()), field.getKey());
}
assertTrue(rows.stream().anyMatch(value -> value.get("id").getAsString().equals(input.id().toString())));
}
static Runnable nextTask(FantasyStickLifecycleNativeTest.Fixture f, UUID recipient) throws Exception {
for (int pass = 0; pass < 100; pass++) {
storage(f).inspect(UUID.randomUUID()).get(5, TimeUnit.SECONDS);
f.receipts().find(recipient).toCompletableFuture().get(5, TimeUnit.SECONDS);
((games.dmg.fantasystick.persistence.RevivalStore) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "revivals"))
.find(UUID.randomUUID()).get(5, TimeUnit.SECONDS);
var callback = f.tasks.poll(); if (callback != null) return callback;
Thread.sleep(5);
}
throw new AssertionError("Expected deferred recovery callback");
}
/** Real inactive saved subject: no native actor/mocks are needed or left outside fixture ownership. */
static CharacterRecord sourceRecord(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);
return record;
}
static List<JsonObject> recoveryRows(Path data) throws Exception {
return ReskillEventsNativeTest.records(data).stream().filter(row -> row.get("type").getAsString()
.startsWith("games.dmg.minecraft.fantasystick.character.recovery_")).toList();
}
static CharacterStorage storage(FantasyStickLifecycleNativeTest.Fixture f) {
return (CharacterStorage) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "characters");
}
static InventoryClickEvent click(FantasyStickLifecycleNativeTest.Fixture f, FantasyStickLifecycleNativeTest.Actor admin,
org.bukkit.inventory.Inventory inventory, int slot) {
var view = f.own(mock(org.bukkit.inventory.InventoryView.class));
when(view.getTopInventory()).thenReturn(inventory); when(view.getBottomInventory()).thenReturn(admin.core.inventory);
when(view.getPlayer()).thenReturn(admin.player);
when(view.getType()).thenReturn(InventoryType.CHEST);
var event = new InventoryClickEvent(view, InventoryType.SlotType.CONTAINER, slot,
org.bukkit.event.inventory.ClickType.LEFT, InventoryAction.PICKUP_ALL);
f.dispatcher.accept(event); assertTrue(event.isCancelled()); return event;
}
static void drain(FantasyStickLifecycleNativeTest.Fixture f, UUID recipient) throws Exception {
for (int pass = 0; pass < 40; pass++) {
storage(f).inspect(UUID.randomUUID()).get(5, TimeUnit.SECONDS);
f.receipts().find(recipient).toCompletableFuture().get(5, TimeUnit.SECONDS);
((games.dmg.fantasystick.persistence.RevivalStore) FantasyStickLifecycleNativeTest.Fixture.field(f.plugin, "revivals"))
.find(UUID.randomUUID()).get(5, TimeUnit.SECONDS);
Runnable callback; boolean ran = false;
while ((callback = f.tasks.poll()) != null) { callback.run(); ran = true; }
if (!ran) Thread.sleep(5);
}
}
}