Files
purpur-fantasy-stick/src/main/java/games/dmg/fantasystick/persistence/YamlCharacterRepository.java
T
2026-10-06 18:33:38 -04:00

233 lines
11 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.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
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;
private volatile java.util.function.Predicate<UUID> unavailable = ignored -> false;
private volatile java.util.function.Predicate<UUID> mutationUnavailable = ignored -> false;
@FunctionalInterface
interface Replacement { void move(Path source, Path target) throws IOException; }
@FunctionalInterface
private interface Operation { void run() throws IOException; }
public void attachUnavailable(java.util.function.Predicate<UUID> predicate){unavailable=Objects.requireNonNull(predicate);}
void attachMutationUnavailable(java.util.function.Predicate<UUID> predicate) {
mutationUnavailable = Objects.requireNonNull(predicate);
}
Path pluginDataDirectory() { return directory.getParent(); }
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 {
createTracked(character);
}
/** Process-local proof; never reconstructed from a revision-zero file after restart. */
static final class Creation {
final CharacterRecord record;
private final BasicFileAttributes attributes;
private final byte[] bytes;
private Creation(CharacterRecord record, BasicFileAttributes attributes, byte[] bytes) {
this.record = record;
this.attributes = attributes;
this.bytes = bytes;
}
}
Creation createTracked(CharacterRecord character) throws IOException {
if (character.revision().signum() != 0) throw new IOException("New character revision must be zero");
Creation[] created = new Creation[1];
withLock(() -> {
if (Files.exists(file(character.id()), LinkOption.NOFOLLOW_LINKS)) {
throw new IOException("Character already exists: " + character.id());
}
created[0] = write(character);
});
return created[0];
}
public void replace(CharacterRecord character, BigInteger expectedRevision) throws IOException {
replace(character, expectedRevision, true);
}
/** Recovery owns its separately persisted reservation but still honors dungeon custody. */
void replaceForRecovery(CharacterRecord character, BigInteger expectedRevision) throws IOException {
replace(character, expectedRevision, false);
}
private void replace(CharacterRecord character, BigInteger expectedRevision,
boolean enforceMutationAvailability) throws IOException {
if (unavailable.test(character.id())) throw new IOException("Character is in dungeon boss custody");
if (enforceMutationAvailability && mutationUnavailable.test(character.id()))
throw new IOException("Character has unresolved recovery custody");
if (!character.revision().equals(expectedRevision.add(BigInteger.ONE))) {
throw new IOException("Character update must advance exactly one revision");
}
withLock(() -> replaceLocked(character, expectedRevision, enforceMutationAvailability));
}
boolean mutationAvailable(UUID id) { return !unavailable.test(id) && !mutationUnavailable.test(id); }
/** Caller owns the same directory lock used by every character writer. */
void replaceLocked(CharacterRecord character, BigInteger expectedRevision, boolean enforceAvailability) throws IOException {
if (unavailable.test(character.id()) || enforceAvailability && mutationUnavailable.test(character.id()))
throw new IOException("Character custody is unresolved");
CharacterRecord current = load(character.id()).orElseThrow(() -> new IOException("Character not found"));
if (!current.revision().equals(expectedRevision)
|| !character.revision().equals(expectedRevision.add(BigInteger.ONE))) throw new IOException("Stale character revision");
write(character);
}
@FunctionalInterface interface Transaction<T> { T run() throws IOException; }
<T> T transaction(Transaction<T> operation) throws IOException {
var result = new java.util.concurrent.atomic.AtomicReference<T>();
withLock(() -> result.set(operation.run()));
return result.get();
}
/** Only the in-memory creator of a never-issued batch may request this cleanup. */
boolean discardUnissued(Creation created) throws IOException {
boolean[] removed = {false};
withLock(() -> {
var path = file(created.record.id());
if (Files.notExists(path, LinkOption.NOFOLLOW_LINKS)) {
removed[0] = true;
return;
}
var current = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
var expected = created.attributes;
if (!current.isRegularFile() || expected.fileKey() == null
|| !expected.fileKey().equals(current.fileKey())
|| !expected.creationTime().equals(current.creationTime())
|| !expected.lastModifiedTime().equals(current.lastModifiedTime())
|| current.size() != created.bytes.length) return;
try (var input = Files.newInputStream(path, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) {
if (!Arrays.equals(created.bytes, input.readNBytes(created.bytes.length + 1))) return;
}
Files.delete(path);
removed[0] = true;
});
return removed[0];
}
public record Catalog(List<CharacterRecord> records, int unreadable) {
public Catalog { records = List.copyOf(records); }
}
/** Enumerate only canonical record files without following directory-entry symlinks. */
public Catalog catalog() throws IOException {
if (Files.notExists(directory, LinkOption.NOFOLLOW_LINKS)) return new Catalog(List.of(), 0);
if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS))
throw new IOException("Character directory is unavailable");
var records = new ArrayList<CharacterRecord>();
int unreadable = 0;
try (var entries = Files.newDirectoryStream(directory, "*.yml")) {
for (var entry : entries) {
String filename = entry.getFileName().toString();
if (!filename.endsWith(".yml")) continue;
UUID id;
try {
String stem = filename.substring(0, filename.length() - 4);
id = UUID.fromString(stem);
if (!id.toString().equals(stem)) continue;
} catch (IllegalArgumentException invalid) { continue; }
if (!Files.isRegularFile(entry, LinkOption.NOFOLLOW_LINKS)) {
unreadable++;
continue;
}
try {
var record = load(id);
if (record.isPresent()) records.add(record.orElseThrow());
else unreadable++;
} catch (IOException failure) { unreadable++; }
}
}
return new Catalog(records, unreadable);
}
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 Creation 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);
}
var attributes = Files.readAttributes(temporary, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
// Never fall back to an in-place, partially written character record.
replacement.move(temporary, file(character.id()));
DurableFiles.forceDirectory(directory);
return new Creation(character, attributes, bytes);
} finally {
Files.deleteIfExists(temporary);
}
}
/** Bounded coordination for all mutations; never mix with older per-ID writers in this directory. */
private void withLock(Operation operation) throws IOException {
Files.createDirectories(directory);
Path lockPath = directory.resolve(".records.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");
}
}