feat(persistence): save characters and create signed Tail books
Release / release (push) Successful in 7m21s
CI / build (push) Successful in 2m36s

This commit is contained in:
dmg committed 2026-09-17 08:23:52 -04:00
1 parent 638965e474
commit b35cac3d1c
11 files changed
+991 -3

No files matched your search

@@ -0,0 +1,70 @@
package games.dmg.fantasystick.items;
import games.dmg.fantasystick.persistence.CharacterRecord;
import games.dmg.fantasystick.progression.Stat;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import net.kyori.adventure.text.Component;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.persistence.PersistentDataType;
/** Native readable keepsake; revival uses only its IDs to consult authoritative saved character data. */
public final class TailBooks {
private static final NamespacedKey VERSION = new NamespacedKey("fantasystick", "tail_version");
private static final NamespacedKey CHARACTER = new NamespacedKey("fantasystick", "character_id");
private static final NamespacedKey DEATH = new NamespacedKey("fantasystick", "death_id");
public record Identity(UUID characterId, UUID deathId) { }
public ItemStack create(CharacterRecord character) {
if (!character.dead()) throw new IllegalArgumentException("A Tail book requires a dead character record");
var item = new ItemStack(Material.WRITTEN_BOOK);
var meta = (BookMeta) item.getItemMeta();
String fullTitle = "Tail of " + character.name();
int titleEnd = Math.min(32, fullTitle.length());
if (titleEnd < fullTitle.length() && Character.isHighSurrogate(fullTitle.charAt(titleEnd - 1))) titleEnd--;
if (!meta.setTitle(fullTitle.substring(0, titleEnd))) {
throw new IllegalStateException("Native written-book title was rejected");
}
meta.setAuthor("Fantasy Stick");
meta.setGeneration(BookMeta.Generation.ORIGINAL);
meta.displayName(Component.text(fullTitle));
List<Component> pages = new ArrayList<>();
pages.add(Component.text(fullTitle));
pages.add(Component.text("Level: " + character.level()));
pages.add(Component.text("XP: " + character.experience()));
pages.add(Component.text("Unspent points: " + character.unspentPoints()));
for (Stat stat : Stat.values()) pages.add(Component.text(stat + ": " + character.stats().get(stat)));
pages.add(Component.text("Abilities: " + (character.learned().isEmpty() ? "None" : "")));
character.learned().stream().sorted().forEach(ability -> pages.add(Component.text(ability)));
pages.add(Component.text("Fell: " + character.diedAt()));
meta.pages(pages);
var data = meta.getPersistentDataContainer();
data.set(VERSION, PersistentDataType.INTEGER, 1);
data.set(CHARACTER, PersistentDataType.STRING, character.id().toString());
data.set(DEATH, PersistentDataType.STRING, character.deathId().toString());
item.setItemMeta(meta);
return item;
}
public Optional<Identity> identify(ItemStack item) {
if (item == null || item.getType() != Material.WRITTEN_BOOK || !item.hasItemMeta()) return Optional.empty();
var data = item.getItemMeta().getPersistentDataContainer();
if (!data.has(VERSION, PersistentDataType.INTEGER)
|| !Integer.valueOf(1).equals(data.get(VERSION, PersistentDataType.INTEGER))
|| !data.has(CHARACTER, PersistentDataType.STRING) || !data.has(DEATH, PersistentDataType.STRING)) {
return Optional.empty();
}
try {
return Optional.of(new Identity(UUID.fromString(data.get(CHARACTER, PersistentDataType.STRING)),
UUID.fromString(data.get(DEATH, PersistentDataType.STRING))));
} catch (IllegalArgumentException exception) {
return Optional.empty();
}
}
}
@@ -0,0 +1,51 @@
package games.dmg.fantasystick.persistence;
import games.dmg.fantasystick.progression.Stat;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.Instant;
import java.util.EnumSet;
import java.util.Map;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
/** Immutable character data, never a holder's ordinary equipment or session snapshot. */
public record CharacterRecord(
UUID id, String name, BigInteger revision, Map<Stat, BigInteger> stats,
int level, BigInteger experience, BigInteger unspentPoints, BigDecimal health,
Set<String> learned, List<String> loadout, Map<String, Instant> cooldowns,
boolean dead, UUID deathId, Instant diedAt) {
public CharacterRecord {
Objects.requireNonNull(id);
Objects.requireNonNull(name);
Objects.requireNonNull(revision);
Objects.requireNonNull(experience);
Objects.requireNonNull(unspentPoints);
Objects.requireNonNull(health);
stats = Map.copyOf(stats);
learned = Set.copyOf(learned);
loadout = List.copyOf(loadout);
cooldowns = Map.copyOf(cooldowns);
if (revision.signum() < 0 || experience.signum() < 0 || unspentPoints.signum() < 0 || level < 1
|| !stats.keySet().equals(EnumSet.allOf(Stat.class))
|| stats.values().stream().anyMatch(value -> value.signum() < 0)
|| health.signum() < 0
|| health.compareTo(new BigDecimal(stats.get(Stat.CON).add(BigInteger.TEN))) > 0
|| loadout.size() != 7 || learned.stream().anyMatch(String::isBlank)
|| cooldowns.keySet().stream().anyMatch(String::isBlank)
|| (deathId == null) != (diedAt == null) || dead && deathId == null) {
throw new IllegalArgumentException("Invalid character record");
}
for (String ability : loadout) {
if (!ability.isEmpty() && !learned.contains(ability)) {
throw new IllegalArgumentException("Loadout references an unlearned ability");
}
}
}
public BigDecimal maximumHealth() {
return new BigDecimal(stats.get(Stat.CON).add(BigInteger.TEN));
}
}
@@ -0,0 +1,99 @@
package games.dmg.fantasystick.persistence;
import java.io.IOException;
import java.math.BigInteger;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
/** Asynchronous character persistence; this does not cast Revive or consume/deliver inventory items. */
public final class CharacterStorage implements AutoCloseable {
private final YamlCharacterRepository repository;
private final Clock clock;
private final ExecutorService worker = Executors.newSingleThreadExecutor(
task -> new Thread(task, "fantasy-character-persistence"));
public CharacterStorage(YamlCharacterRepository repository, Clock clock) {
this.repository = Objects.requireNonNull(repository);
this.clock = Objects.requireNonNull(clock);
}
public CompletableFuture<Void> create(CharacterRecord character) {
return submit(() -> {
repository.create(character);
return null;
});
}
public CompletableFuture<Optional<CharacterRecord>> find(UUID id) {
return submit(() -> repository.load(id));
}
public CompletableFuture<Optional<CharacterRecord>> recordDeath(UUID characterId, BigInteger expectedRevision) {
Objects.requireNonNull(characterId);
Objects.requireNonNull(expectedRevision);
Instant diedAt = clock.instant();
return submit(() -> {
Optional<CharacterRecord> found = repository.load(characterId);
if (found.isEmpty()) return Optional.empty();
CharacterRecord old = found.orElseThrow();
if (old.dead() || !old.revision().equals(expectedRevision)) return Optional.empty();
var dead = new CharacterRecord(old.id(), old.name(), old.revision().add(BigInteger.ONE), old.stats(),
old.level(), old.experience(), old.unspentPoints(), java.math.BigDecimal.ZERO, old.learned(),
old.loadout(), old.cooldowns(), true, UUID.randomUUID(), diedAt);
repository.replace(dead, old.revision());
return Optional.of(dead);
});
}
public CompletableFuture<Optional<CharacterRecord>> restoreDeathRecord(UUID characterId, UUID deathId) {
Objects.requireNonNull(characterId);
Objects.requireNonNull(deathId);
Instant selectedAt = clock.instant();
return submit(() -> {
Optional<CharacterRecord> found = repository.load(characterId);
if (found.isEmpty() || !found.orElseThrow().dead()) return Optional.empty();
CharacterRecord old = found.orElseThrow();
Duration age = Duration.between(old.diedAt(), selectedAt);
if (!deathId.equals(old.deathId()) || age.isNegative() || age.compareTo(Duration.ofHours(24)) >= 0) {
return Optional.empty();
}
var restored = new CharacterRecord(old.id(), old.name(), old.revision().add(BigInteger.ONE), old.stats(),
old.level(), old.experience(), old.unspentPoints(), old.maximumHealth(), old.learned(),
old.loadout(), old.cooldowns(), false, old.deathId(), old.diedAt());
repository.replace(restored, old.revision());
return Optional.of(restored);
});
}
@FunctionalInterface
private interface DiskOperation<T> { T run() throws IOException; }
private <T> CompletableFuture<T> submit(DiskOperation<T> operation) {
try {
return CompletableFuture.supplyAsync(() -> {
try {
return operation.run();
} catch (IOException exception) {
throw new CompletionException(exception);
}
}, worker);
} catch (RejectedExecutionException exception) {
return CompletableFuture.failedFuture(exception);
}
}
/** Stop accepting work without blocking shutdown; already queued file writes may finish. */
@Override
public void close() {
worker.shutdown();
}
}
@@ -0,0 +1,117 @@
package games.dmg.fantasystick.persistence;
import games.dmg.fantasystick.progression.Stat;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.Instant;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
/** Plain values only: no Bukkit item deserialization or arbitrary Java YAML tags. */
final class CharacterYaml {
private CharacterYaml() { }
private static Yaml yaml() {
var options = new LoaderOptions();
options.setAllowDuplicateKeys(false);
options.setMaxAliasesForCollections(0);
options.setCodePointLimit(1_048_576);
return new Yaml(new SafeConstructor(options));
}
static String encode(CharacterRecord record) {
Map<String, Object> root = new LinkedHashMap<>();
root.put("schema-version", 1);
root.put("character-id", record.id().toString());
root.put("name", record.name());
root.put("revision", record.revision().toString());
Map<String, String> stats = new LinkedHashMap<>();
for (Stat stat : Stat.values()) stats.put(stat.name(), record.stats().get(stat).toString());
root.put("stats", stats);
root.put("level", record.level());
root.put("experience", record.experience().toString());
root.put("unspent-points", record.unspentPoints().toString());
root.put("health", record.health().toString());
root.put("learned-abilities", record.learned().stream().sorted().toList());
root.put("loadout", record.loadout());
List<Map<String, String>> cooldowns = new ArrayList<>();
record.cooldowns().entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(entry ->
cooldowns.add(Map.of("ability", entry.getKey(), "ready-at", entry.getValue().toString())));
root.put("cooldowns", cooldowns);
root.put("dead", record.dead());
if (record.deathId() != null) {
root.put("death-id", record.deathId().toString());
root.put("died-at", record.diedAt().toString());
}
return yaml().dump(root);
}
static CharacterRecord decode(String input) {
Map<?, ?> root = object(yaml().load(input));
if (!number(root.get("schema-version")).equals(BigInteger.ONE)) {
throw new IllegalArgumentException("Unsupported character schema");
}
Map<?, ?> storedStats = object(root.get("stats"));
var stats = new EnumMap<Stat, BigInteger>(Stat.class);
for (var entry : storedStats.entrySet()) {
stats.put(Stat.valueOf(text(entry.getKey())), number(entry.getValue()));
}
List<String> learnedList = strings(root.get("learned-abilities"));
var learned = new LinkedHashSet<>(learnedList);
if (learned.size() != learnedList.size()) throw new IllegalArgumentException("Duplicate learned ability");
Map<String, Instant> cooldowns = new LinkedHashMap<>();
for (Object value : list(root.get("cooldowns"))) {
Map<?, ?> row = object(value);
if (cooldowns.putIfAbsent(text(row.get("ability")), instant(row.get("ready-at"))) != null) {
throw new IllegalArgumentException("Duplicate cooldown");
}
}
if (!(root.get("dead") instanceof Boolean dead)) throw new IllegalArgumentException("Missing dead flag");
return new CharacterRecord(UUID.fromString(text(root.get("character-id"))), text(root.get("name")),
number(root.get("revision")), stats, number(root.get("level")).intValueExact(),
number(root.get("experience")), number(root.get("unspent-points")),
new BigDecimal(text(root.get("health"))), learned, strings(root.get("loadout")), cooldowns,
dead, root.containsKey("death-id") ? UUID.fromString(text(root.get("death-id"))) : null,
root.containsKey("died-at") ? instant(root.get("died-at")) : null);
}
private static Map<?, ?> object(Object value) {
if (value instanceof Map<?, ?> map) return map;
throw new IllegalArgumentException("Expected YAML mapping");
}
private static List<?> list(Object value) {
if (value instanceof List<?> result) return result;
throw new IllegalArgumentException("Expected YAML list");
}
private static List<String> strings(Object value) {
return list(value).stream().map(CharacterYaml::text).toList();
}
private static String text(Object value) {
if (value instanceof String string) return string;
throw new IllegalArgumentException("Expected YAML string");
}
private static BigInteger number(Object value) {
if (value instanceof Integer || value instanceof Long || value instanceof BigInteger) {
return new BigInteger(value.toString());
}
return new BigInteger(text(value));
}
private static Instant instant(Object value) {
String string = text(value);
if (!string.endsWith("Z")) throw new IllegalArgumentException("Expected UTC timestamp");
return Instant.parse(string);
}
}
@@ -0,0 +1,109 @@
package games.dmg.fantasystick.persistence;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.OverlappingFileLockException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
/** Blocking disk adapter: callers must use the persistence worker, never the server tick thread. */
public final class YamlCharacterRepository {
private static final int MAX_FILE_BYTES = 1_048_576;
private final Path directory;
private final Replacement replacement;
@FunctionalInterface
interface Replacement { void move(Path source, Path target) throws IOException; }
@FunctionalInterface
private interface Operation { void run() throws IOException; }
public YamlCharacterRepository(Path pluginDataDirectory) {
this(pluginDataDirectory, (source, target) -> Files.move(source, target,
StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING));
}
YamlCharacterRepository(Path pluginDataDirectory, Replacement replacement) {
directory = pluginDataDirectory.resolve("characters").toAbsolutePath();
this.replacement = Objects.requireNonNull(replacement);
}
public void create(CharacterRecord character) throws IOException {
if (character.revision().signum() != 0) throw new IOException("New character revision must be zero");
withLock(character.id(), () -> {
if (Files.exists(file(character.id()), LinkOption.NOFOLLOW_LINKS)) {
throw new IOException("Character already exists: " + character.id());
}
write(character);
});
}
public void replace(CharacterRecord character, BigInteger expectedRevision) throws IOException {
if (!character.revision().equals(expectedRevision.add(BigInteger.ONE))) {
throw new IOException("Character update must advance exactly one revision");
}
withLock(character.id(), () -> {
CharacterRecord current = load(character.id()).orElseThrow(() -> new IOException("Character not found"));
if (!current.revision().equals(expectedRevision)) throw new IOException("Stale character revision");
write(character);
});
}
public Optional<CharacterRecord> load(UUID id) throws IOException {
Path file = file(id);
if (Files.notExists(file, LinkOption.NOFOLLOW_LINKS)) return Optional.empty();
try (var input = Files.newInputStream(file, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) {
byte[] bytes = input.readNBytes(MAX_FILE_BYTES + 1);
if (bytes.length > MAX_FILE_BYTES) throw new IOException("Character YAML exceeds the safe file-size limit");
String text = StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString();
CharacterRecord record = CharacterYaml.decode(text);
if (!record.id().equals(id)) throw new IllegalArgumentException("Character ID mismatch");
return Optional.of(record);
} catch (RuntimeException exception) {
// Parser diagnostics may contain user-controlled data; preserve the file, not its text in logs.
throw new IOException("Invalid character YAML for " + id);
}
}
private void write(CharacterRecord character) throws IOException {
byte[] bytes = CharacterYaml.encode(character).getBytes(StandardCharsets.UTF_8);
if (bytes.length > MAX_FILE_BYTES) throw new IOException("Character YAML exceeds the safe file-size limit");
Path temporary = Files.createTempFile(directory, ".character-", ".tmp");
try {
try (var output = FileChannel.open(temporary, StandardOpenOption.WRITE)) {
ByteBuffer buffer = ByteBuffer.wrap(bytes);
while (buffer.hasRemaining()) output.write(buffer);
output.force(true);
}
// Never fall back to an in-place, partially written character record.
replacement.move(temporary, file(character.id()));
} finally {
Files.deleteIfExists(temporary);
}
}
private void withLock(UUID id, Operation operation) throws IOException {
Files.createDirectories(directory);
Path lockPath = directory.resolve(id + ".lock");
try (var channel = FileChannel.open(lockPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE,
LinkOption.NOFOLLOW_LINKS);
var lock = channel.tryLock()) {
if (lock == null) throw new IOException("Character record busy; retry the operation");
operation.run();
} catch (OverlappingFileLockException exception) {
throw new IOException("Character record busy; retry the operation");
}
}
private Path file(UUID id) {
return directory.resolve(Objects.requireNonNull(id) + ".yml");
}
}