feat(persistence): save characters and create signed Tail books
This commit is contained in:
1 parent
638965e474
commit
b35cac3d1c
11 files changed
+991
-3
No files matched your search
@@ -0,0 +1,191 @@
|
||||
package games.dmg.fantasystick.persistence;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Clock;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class CharacterStorageTest {
|
||||
@TempDir Path data;
|
||||
|
||||
@Test
|
||||
void performsFileWritesOffTheCallerThreadAndAcknowledgesOnlyAfterCommit() throws Exception {
|
||||
Thread caller = Thread.currentThread();
|
||||
var entered = new CountDownLatch(1);
|
||||
var allowCommit = new CountDownLatch(1);
|
||||
var saved = YamlCharacterRepositoryTest.sample(UUID.randomUUID());
|
||||
var repository = new YamlCharacterRepository(data, (source, target) -> {
|
||||
assertNotSame(caller, Thread.currentThread());
|
||||
entered.countDown();
|
||||
try {
|
||||
if (!allowCommit.await(5, TimeUnit.SECONDS)) throw new IOException("Test gate timed out");
|
||||
} catch (InterruptedException exception) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("Interrupted", exception);
|
||||
}
|
||||
Files.move(source, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
});
|
||||
try (var storage = new CharacterStorage(repository, Clock.systemUTC())) {
|
||||
var pending = storage.create(saved);
|
||||
try {
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||
assertFalse(pending.isDone(), "No success acknowledgment before the file commit");
|
||||
} finally {
|
||||
allowCommit.countDown();
|
||||
}
|
||||
pending.join();
|
||||
assertEquals(saved, storage.find(saved.id()).join().orElseThrow());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedRevivalSaveLeavesDeadStateRetryableAndShutdownRejectsNewWork() throws Exception {
|
||||
var saved = YamlCharacterRepositoryTest.sample(UUID.randomUUID());
|
||||
var repository = new YamlCharacterRepository(data);
|
||||
repository.create(saved);
|
||||
var failing = new YamlCharacterRepository(data, (source, target) -> { throw new IOException("Simulated failure"); });
|
||||
try (var storage = new CharacterStorage(failing, Clock.fixed(saved.diedAt().plusSeconds(60), ZoneOffset.UTC))) {
|
||||
assertThrows(CompletionException.class, () -> storage.restoreDeathRecord(saved.id(), saved.deathId()).join());
|
||||
assertEquals(saved, repository.load(saved.id()).orElseThrow());
|
||||
}
|
||||
var retry = new CharacterStorage(repository, Clock.fixed(saved.diedAt().plusSeconds(60), ZoneOffset.UTC));
|
||||
assertTrue(retry.restoreDeathRecord(saved.id(), saved.deathId()).join().isPresent());
|
||||
retry.close();
|
||||
assertThrows(CompletionException.class, () -> retry.find(saved.id()).join());
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentRequestsAndAReopenedStoreCannotRestoreTheSameDeathTwice() throws Exception {
|
||||
var saved = YamlCharacterRepositoryTest.sample(UUID.randomUUID());
|
||||
var repository = new YamlCharacterRepository(data);
|
||||
repository.create(saved);
|
||||
var clock = Clock.fixed(saved.diedAt().plusSeconds(60), ZoneOffset.UTC);
|
||||
try (var storage = new CharacterStorage(repository, clock)) {
|
||||
var first = storage.restoreDeathRecord(saved.id(), saved.deathId());
|
||||
var second = storage.restoreDeathRecord(saved.id(), saved.deathId());
|
||||
assertTrue(first.join().isPresent());
|
||||
assertTrue(second.join().isEmpty());
|
||||
}
|
||||
try (var reopened = new CharacterStorage(new YamlCharacterRepository(data), clock)) {
|
||||
assertTrue(reopened.restoreDeathRecord(saved.id(), saved.deathId()).join().isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLaterDeathDoesNotMakeThePreviousBookEligibleAgain() throws Exception {
|
||||
var original = YamlCharacterRepositoryTest.sample(UUID.randomUUID());
|
||||
var repository = new YamlCharacterRepository(data);
|
||||
repository.create(original);
|
||||
var clock = Clock.fixed(original.diedAt().plusSeconds(60), ZoneOffset.UTC);
|
||||
try (var storage = new CharacterStorage(repository, clock)) {
|
||||
var alive = storage.restoreDeathRecord(original.id(), original.deathId()).join().orElseThrow();
|
||||
var later = new CharacterRecord(alive.id(), "Saved current name", alive.revision().add(BigInteger.ONE),
|
||||
alive.stats(), alive.level(), alive.experience(), alive.unspentPoints(), java.math.BigDecimal.ZERO,
|
||||
alive.learned(), alive.loadout(), alive.cooldowns(), true, UUID.randomUUID(), original.diedAt().plusSeconds(30));
|
||||
repository.replace(later, alive.revision());
|
||||
assertTrue(storage.restoreDeathRecord(original.id(), original.deathId()).join().isEmpty());
|
||||
var restored = storage.restoreDeathRecord(later.id(), later.deathId()).join().orElseThrow();
|
||||
assertEquals("Saved current name", restored.name(), "Use saved state, not the old book's snapshot");
|
||||
assertFalse(restored.dead());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordsEachDeathOnceWithANewIdentityAndNeverReplaysAnOldDefeat() throws Exception {
|
||||
var template = YamlCharacterRepositoryTest.sample(UUID.randomUUID());
|
||||
var live = new CharacterRecord(template.id(), template.name(), BigInteger.ZERO, template.stats(),
|
||||
template.level(), template.experience(), template.unspentPoints(), template.maximumHealth(),
|
||||
template.learned(), template.loadout(), template.cooldowns(), false, null, null);
|
||||
var now = template.diedAt().plusSeconds(60);
|
||||
var repository = new YamlCharacterRepository(data);
|
||||
try (var storage = new CharacterStorage(repository, Clock.fixed(now, ZoneOffset.UTC))) {
|
||||
storage.create(live).join();
|
||||
var first = storage.recordDeath(live.id(), live.revision()).join();
|
||||
assertTrue(first.isPresent(), "Death must persist the dead flag and current death identity");
|
||||
var dead = first.orElseThrow();
|
||||
assertTrue(dead.dead());
|
||||
assertEquals(java.math.BigDecimal.ZERO, dead.health());
|
||||
assertNotNull(dead.deathId());
|
||||
assertEquals(now, dead.diedAt());
|
||||
assertTrue(storage.recordDeath(live.id(), live.revision()).join().isEmpty());
|
||||
assertEquals(dead, storage.find(live.id()).join().orElseThrow());
|
||||
var revived = storage.restoreDeathRecord(live.id(), dead.deathId()).join().orElseThrow();
|
||||
assertTrue(storage.recordDeath(live.id(), live.revision()).join().isEmpty(), "An old callback cannot kill a revived life");
|
||||
var later = storage.recordDeath(live.id(), revived.revision()).join().orElseThrow();
|
||||
assertNotEquals(dead.deathId(), later.deathId());
|
||||
assertTrue(storage.restoreDeathRecord(live.id(), dead.deathId()).join().isEmpty());
|
||||
assertTrue(storage.restoreDeathRecord(live.id(), later.deathId()).join().isPresent());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesAnOldOrUnknownDeathBookWithoutChangingTheSavedCharacter() throws Exception {
|
||||
var saved = YamlCharacterRepositoryTest.sample(UUID.randomUUID());
|
||||
var repository = new YamlCharacterRepository(data);
|
||||
repository.create(saved);
|
||||
try (var storage = new CharacterStorage(repository, Clock.fixed(saved.diedAt().plusSeconds(60), ZoneOffset.UTC))) {
|
||||
assertTrue(storage.restoreDeathRecord(saved.id(), UUID.randomUUID()).join().isEmpty());
|
||||
assertTrue(storage.restoreDeathRecord(UUID.randomUUID(), saved.deathId()).join().isEmpty());
|
||||
assertEquals(saved, repository.load(saved.id()).orElseThrow());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void requiresDeathAgeStrictlyBelowTwentyFourHoursAndNotInTheFuture() throws Exception {
|
||||
for (long seconds : new long[] {-1, 86400, 86401}) {
|
||||
var saved = YamlCharacterRepositoryTest.sample(UUID.randomUUID());
|
||||
var repository = new YamlCharacterRepository(data);
|
||||
repository.create(saved);
|
||||
try (var storage = new CharacterStorage(repository, Clock.fixed(saved.diedAt().plusSeconds(seconds), ZoneOffset.UTC))) {
|
||||
assertTrue(storage.restoreDeathRecord(saved.id(), saved.deathId()).join().isEmpty());
|
||||
assertEquals(saved, repository.load(saved.id()).orElseThrow());
|
||||
}
|
||||
}
|
||||
var saved = YamlCharacterRepositoryTest.sample(UUID.randomUUID());
|
||||
var repository = new YamlCharacterRepository(data);
|
||||
repository.create(saved);
|
||||
try (var storage = new CharacterStorage(repository,
|
||||
Clock.fixed(saved.diedAt().plusSeconds(86400).minusNanos(1), ZoneOffset.UTC))) {
|
||||
assertTrue(storage.restoreDeathRecord(saved.id(), saved.deathId()).join().isPresent());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoresOnlyFromTheSavedDeadCharacterAndPreservesProgressAndCooldowns() throws Exception {
|
||||
var saved = YamlCharacterRepositoryTest.sample(UUID.randomUUID());
|
||||
var repository = new YamlCharacterRepository(data);
|
||||
repository.create(saved);
|
||||
try (var storage = new CharacterStorage(repository, Clock.fixed(saved.diedAt().plusSeconds(60), ZoneOffset.UTC))) {
|
||||
var result = storage.restoreDeathRecord(saved.id(), saved.deathId()).join();
|
||||
assertTrue(result.isPresent(), "A current, recently dead saved character must be restored");
|
||||
var restored = result.orElseThrow();
|
||||
assertFalse(restored.dead());
|
||||
assertEquals(saved.maximumHealth(), restored.health());
|
||||
assertEquals(saved.id(), restored.id());
|
||||
assertEquals(saved.name(), restored.name());
|
||||
assertEquals(saved.stats(), restored.stats());
|
||||
assertEquals(saved.level(), restored.level());
|
||||
assertEquals(saved.experience(), restored.experience());
|
||||
assertEquals(saved.unspentPoints(), restored.unspentPoints());
|
||||
assertEquals(saved.learned(), restored.learned());
|
||||
assertEquals(saved.loadout(), restored.loadout());
|
||||
assertEquals(saved.cooldowns(), restored.cooldowns());
|
||||
assertEquals(saved.deathId(), restored.deathId());
|
||||
assertEquals(saved.diedAt(), restored.diedAt());
|
||||
assertEquals(saved.revision().add(BigInteger.ONE), restored.revision());
|
||||
assertEquals(restored, new YamlCharacterRepository(data).load(saved.id()).orElseThrow());
|
||||
assertTrue(storage.restoreDeathRecord(saved.id(), saved.deathId()).join().isEmpty());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package games.dmg.fantasystick.persistence;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import games.dmg.fantasystick.progression.Stat;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.Collections;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.Executors;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class YamlCharacterRepositoryTest {
|
||||
@TempDir Path data;
|
||||
private static final Instant DEATH = Instant.parse("2026-09-17T00:00:00Z"); // synthetic test clock
|
||||
|
||||
static CharacterRecord sample(UUID id) {
|
||||
var stats = new EnumMap<Stat, BigInteger>(Stat.class);
|
||||
for (Stat stat : Stat.values()) stats.put(stat, BigInteger.ZERO);
|
||||
stats.put(Stat.STR, BigInteger.TEN.pow(100));
|
||||
stats.put(Stat.CON, BigInteger.valueOf(6));
|
||||
return new CharacterRecord(id, "Ari 'Ash' ☃", BigInteger.ZERO, stats, 7,
|
||||
BigInteger.valueOf(600), BigInteger.TEN.pow(99), BigDecimal.ZERO,
|
||||
Set.of("fireball", "revive", "future.unknown"),
|
||||
List.of("fireball", "", "", "future.unknown", "revive", "", ""),
|
||||
Map.of("revive", DEATH.plusSeconds(86400), "unlearned.ability", DEATH.plusSeconds(60)),
|
||||
true, UUID.randomUUID(), DEATH);
|
||||
}
|
||||
|
||||
static CharacterRecord rename(CharacterRecord original, String name, BigInteger revision) {
|
||||
return new CharacterRecord(original.id(), name, revision, original.stats(), original.level(),
|
||||
original.experience(), original.unspentPoints(), original.health(), original.learned(),
|
||||
original.loadout(), original.cooldowns(), original.dead(), original.deathId(), original.diedAt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatesExactlyTheExpectedRevisionAndNeverOverwritesWithAStaleCopy() throws Exception {
|
||||
var repository = new YamlCharacterRepository(data);
|
||||
var original = sample(UUID.randomUUID());
|
||||
repository.create(original);
|
||||
var updated = rename(original, "New name", BigInteger.ONE);
|
||||
repository.replace(updated, BigInteger.ZERO);
|
||||
assertEquals(updated, repository.load(original.id()).orElseThrow());
|
||||
assertThrows(IOException.class, () -> repository.replace(rename(original, "Stale name", BigInteger.ONE), BigInteger.ZERO));
|
||||
assertThrows(IOException.class, () -> repository.create(original));
|
||||
assertEquals(updated, repository.load(original.id()).orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedAtomicReplacementKeepsOriginalStateAndCleansTemporaryData() throws Exception {
|
||||
var original = sample(UUID.randomUUID());
|
||||
var repository = new YamlCharacterRepository(data);
|
||||
repository.create(original);
|
||||
var failing = new YamlCharacterRepository(data, (temporary, target) -> {
|
||||
assertTrue(Files.isRegularFile(temporary));
|
||||
assertEquals(original, repository.load(original.id()).orElseThrow());
|
||||
throw new IOException("Simulated atomic-move failure");
|
||||
});
|
||||
assertThrows(IOException.class,
|
||||
() -> failing.replace(rename(original, "Unsaved", BigInteger.ONE), BigInteger.ZERO));
|
||||
assertEquals(original, repository.load(original.id()).orElseThrow());
|
||||
try (var paths = Files.list(data.resolve("characters"))) {
|
||||
assertFalse(paths.anyMatch(path -> path.getFileName().toString().endsWith(".tmp")));
|
||||
}
|
||||
// A normal retry succeeds; there is no persistent administrator-unlock flag.
|
||||
repository.replace(rename(original, "Retry", BigInteger.ONE), BigInteger.ZERO);
|
||||
assertEquals("Retry", repository.load(original.id()).orElseThrow().name());
|
||||
}
|
||||
|
||||
@Test
|
||||
void separateRepositoryInstancesCannotCommitTheSameRevisionTwice() throws Exception {
|
||||
var original = sample(UUID.randomUUID());
|
||||
new YamlCharacterRepository(data).create(original);
|
||||
Callable<Boolean> change = () -> {
|
||||
try {
|
||||
new YamlCharacterRepository(data).replace(rename(original, "Winner", BigInteger.ONE), BigInteger.ZERO);
|
||||
return true;
|
||||
} catch (IOException conflict) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
try (var pool = Executors.newVirtualThreadPerTaskExecutor()) {
|
||||
int successes = 0;
|
||||
for (var future : pool.invokeAll(Collections.nCopies(8, change))) if (future.get()) successes++;
|
||||
assertEquals(1, successes);
|
||||
}
|
||||
assertEquals(BigInteger.ONE, new YamlCharacterRepository(data).load(original.id()).orElseThrow().revision());
|
||||
}
|
||||
|
||||
@Test
|
||||
void preservesExactDecimalHealthWithoutExpandingHugeScalesOnSave() throws Exception {
|
||||
var template = sample(UUID.randomUUID());
|
||||
var tiny = new CharacterRecord(template.id(), template.name(), template.revision(), template.stats(),
|
||||
template.level(), template.experience(), template.unspentPoints(), new BigDecimal("1E-10000"),
|
||||
template.learned(), template.loadout(), template.cooldowns(), template.dead(), template.deathId(), template.diedAt());
|
||||
var repository = new YamlCharacterRepository(data);
|
||||
repository.create(tiny);
|
||||
assertTrue(Files.size(data.resolve("characters").resolve(tiny.id() + ".yml")) < 4096,
|
||||
"Persist decimal notation without allocating thousands of padding zeros");
|
||||
assertEquals(tiny, repository.load(tiny.id()).orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void boundsFileReadsAndWritesWithoutReplacingExistingData() throws Exception {
|
||||
var original = sample(UUID.randomUUID());
|
||||
var repository = new YamlCharacterRepository(data);
|
||||
repository.create(original);
|
||||
Path file = data.resolve("characters").resolve(original.id() + ".yml");
|
||||
byte[] before = Files.readAllBytes(file);
|
||||
String oversized = "x".repeat(1_048_577);
|
||||
assertThrows(IOException.class,
|
||||
() -> repository.replace(rename(original, oversized, BigInteger.ONE), BigInteger.ZERO));
|
||||
assertArrayEquals(before, Files.readAllBytes(file));
|
||||
Files.writeString(file, oversized);
|
||||
assertThrows(IOException.class, () -> repository.load(original.id()));
|
||||
assertEquals(oversized.length(), Files.size(file));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsInvalidCharacterDataWithoutChangingTheOriginalFile() throws Exception {
|
||||
var character = sample(UUID.randomUUID());
|
||||
var repository = new YamlCharacterRepository(data);
|
||||
repository.create(character);
|
||||
Path file = data.resolve("characters").resolve(character.id() + ".yml");
|
||||
String valid = Files.readString(file);
|
||||
for (String invalid : List.of(
|
||||
valid.replaceAll("(?m)^revision:.*$", "revision: '-1'"),
|
||||
valid.replaceAll("(?m)^health:.*$", "health: '17'"),
|
||||
valid.replaceAll("(?m)^level:.*$", "level: 0"),
|
||||
valid.replaceAll("(?m)^death-id:.*\\R", ""),
|
||||
valid.replaceAll("(?m)^died-at:.*\\R", ""),
|
||||
valid.replace("schema-version: 1", "schema-version: 2"),
|
||||
valid.replace("dead: true", "dead: true\ndead: false"),
|
||||
valid.replace(character.id().toString(), UUID.randomUUID().toString()),
|
||||
"!!java.net.URL ['https://invalid.example/']")) {
|
||||
Files.writeString(file, invalid);
|
||||
IOException error = assertThrows(IOException.class, () -> repository.load(character.id()));
|
||||
assertEquals("Invalid character YAML for " + character.id(), error.getMessage());
|
||||
assertEquals(invalid, Files.readString(file));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsSymlinkedRecordsInsteadOfReadingOutsideTheCharacterDirectory() throws Exception {
|
||||
var character = sample(UUID.randomUUID());
|
||||
Files.createDirectories(data.resolve("characters"));
|
||||
Path other = data.resolve("outside.yml");
|
||||
Files.writeString(other, CharacterYaml.encode(character));
|
||||
Files.createSymbolicLink(data.resolve("characters").resolve(character.id() + ".yml"), other);
|
||||
assertThrows(IOException.class, () -> new YamlCharacterRepository(data).load(character.id()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void storesACompleteVersionedCharacterYamlAndReloadsItWithoutItemOrHolderState() throws Exception {
|
||||
CharacterRecord character = sample(UUID.randomUUID());
|
||||
var repository = new YamlCharacterRepository(data);
|
||||
repository.create(character);
|
||||
Path file = data.resolve("characters").resolve(character.id() + ".yml");
|
||||
assertTrue(Files.isRegularFile(file), "Create must persist character YAML in the plugin data directory");
|
||||
String yaml = Files.readString(file);
|
||||
assertTrue(yaml.contains("schema-version: 1"));
|
||||
assertTrue(yaml.contains("dead: true"));
|
||||
assertTrue(yaml.contains("2026-09-17T00:00:00Z"));
|
||||
assertFalse(yaml.contains("!!"), "Use plain YAML data, never Java object tags");
|
||||
assertEquals(character, new YamlCharacterRepository(data).load(character.id()).orElseThrow());
|
||||
assertTrue(repository.load(UUID.randomUUID()).isEmpty());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user