Files
purpur-fantasy-stick/src/main/java/games/dmg/fantasystick/persistence/YamlCharacterRepository.java
T
dmg b35cac3d1c
Release / release (push) Successful in 7m21s
CI / build (push) Successful in 2m36s
feat(persistence): save characters and create signed Tail books
2026-09-17 08:23:52 -04:00

110 lines
5.1 KiB
Java

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");
}
}