Files
purpur-fantasy-stick/src/main/java/games/dmg/fantasystick/persistence/CharacterRecoveryStore.java
T
dmg cbd0f70a8b
Release / release (push) Failing after 11m7s
feat(admin): recover saved character sheets
2026-09-23 14:47:25 -04:00

168 lines
8.5 KiB
Java

package games.dmg.fantasystick.persistence;
import java.io.IOException;
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.math.BigInteger;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
/** Durable fail-closed authority for one explicitly confirmed saved-sheet recovery. */
final class CharacterRecoveryStore {
private static final int MAX_FILE_BYTES = 16_384;
enum Phase { PREPARED, COMMITTED, DELIVERED }
record Operation(UUID operation, UUID character, UUID administrator, UUID recipient,
BigInteger expectedRevision, BigInteger expectedGeneration,
BigInteger replacementGeneration, boolean revive, UUID death, Phase phase) {
Operation {
Objects.requireNonNull(operation); Objects.requireNonNull(character);
Objects.requireNonNull(administrator); Objects.requireNonNull(recipient);
Objects.requireNonNull(expectedRevision); Objects.requireNonNull(expectedGeneration);
Objects.requireNonNull(replacementGeneration); Objects.requireNonNull(phase);
if (expectedRevision.signum() < 0 || expectedGeneration.signum() < 0
|| !replacementGeneration.equals(expectedGeneration.add(BigInteger.ONE))
|| revive != (death != null)) throw new IllegalArgumentException("Invalid recovery operation");
}
Operation phase(Phase value) {
return new Operation(operation, character, administrator, recipient, expectedRevision,
expectedGeneration, replacementGeneration, revive, death, value);
}
}
private final Path directory;
CharacterRecoveryStore(Path pluginDataDirectory) {
directory = Objects.requireNonNull(pluginDataDirectory).resolve("character-recoveries").toAbsolutePath();
}
Optional<Operation> find(UUID character) throws IOException {
if (Files.notExists(directory, LinkOption.NOFOLLOW_LINKS)) return Optional.empty();
safeDirectory();
Path path = file(character);
if (Files.notExists(path, LinkOption.NOFOLLOW_LINKS)) return Optional.empty();
if (Files.isSymbolicLink(path) || !Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)
|| Files.size(path) > MAX_FILE_BYTES) throw new IOException("Recovery record is unsafe");
return Optional.of(decode(Files.readString(path, StandardCharsets.UTF_8)));
}
/** Mutation predicate: corrupt or unreadable proof is unresolved and therefore blocks. */
boolean blocks(UUID character) {
try { return find(character).map(operation -> operation.phase() != Phase.DELIVERED).orElse(false); }
catch (IOException unsafe) { return true; }
}
void prepare(Operation operation) throws IOException {
withLock(() -> {
var existing = find(operation.character());
if (existing.isPresent() && existing.orElseThrow().phase() != Phase.DELIVERED)
throw new IOException("Character recovery is unresolved");
write(operation);
});
}
void advance(UUID character, UUID operation, Phase expected, Phase replacement) throws IOException {
withLock(() -> {
var current = find(character).orElseThrow(() -> new IOException("Recovery operation missing"));
if (!current.operation().equals(operation) || current.phase() != expected)
throw new IOException("Recovery operation changed");
write(current.phase(replacement));
});
}
void cancelPrepared(UUID character, UUID operation) throws IOException {
withLock(() -> {
var current = find(character);
if (current.isEmpty()) return;
if (!current.orElseThrow().operation().equals(operation)
|| current.orElseThrow().phase() != Phase.PREPARED)
throw new IOException("Recovery operation cannot be cancelled");
Files.delete(file(character));
DurableFiles.forceDirectory(directory);
});
}
private void write(Operation operation) throws IOException {
safeDirectory();
byte[] bytes = encode(operation).getBytes(StandardCharsets.UTF_8);
Path temporary = Files.createTempFile(directory, ".recovery-", ".tmp");
try {
try (var output = FileChannel.open(temporary, StandardOpenOption.WRITE)) {
var buffer = ByteBuffer.wrap(bytes);
while (buffer.hasRemaining()) output.write(buffer);
output.force(true);
}
Files.move(temporary, file(operation.character()), StandardCopyOption.ATOMIC_MOVE,
StandardCopyOption.REPLACE_EXISTING);
DurableFiles.forceDirectory(directory);
} finally { Files.deleteIfExists(temporary); }
}
private void withLock(IoAction action) throws IOException {
safeDirectory();
Path lockPath = directory.resolve(".recoveries.lock");
try (var channel = FileChannel.open(lockPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE,
LinkOption.NOFOLLOW_LINKS); var lock = channel.tryLock()) {
if (lock == null) throw new IOException("Recovery store busy");
action.run();
} catch (OverlappingFileLockException failure) { throw new IOException("Recovery store busy", failure); }
}
private void safeDirectory() throws IOException {
if (Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) {
if (Files.isSymbolicLink(directory) || !Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS))
throw new IOException("Recovery directory is unsafe");
} else Files.createDirectories(directory);
}
private Path file(UUID character) { return directory.resolve(Objects.requireNonNull(character) + ".yml"); }
private static String encode(Operation value) {
return "schema-version: 1\n"
+ "operation: " + value.operation() + "\n"
+ "character: " + value.character() + "\n"
+ "administrator: " + value.administrator() + "\n"
+ "recipient: " + value.recipient() + "\n"
+ "expected-revision: " + value.expectedRevision() + "\n"
+ "expected-generation: " + value.expectedGeneration() + "\n"
+ "replacement-generation: " + value.replacementGeneration() + "\n"
+ "revive: " + value.revive() + "\n"
+ "death: " + (value.death() == null ? "" : value.death()) + "\n"
+ "phase: " + value.phase() + "\n";
}
private static Operation decode(String text) throws IOException {
var values = new LinkedHashMap<String, String>();
for (String line : text.split("\\n", -1)) {
if (line.isEmpty()) continue;
int split = line.indexOf(": ");
if (split < 1 || values.putIfAbsent(line.substring(0, split), line.substring(split + 2)) != null)
throw new IOException("Invalid recovery record");
}
try {
if (!values.keySet().equals(java.util.Set.of("schema-version", "operation", "character",
"administrator", "recipient", "expected-revision", "expected-generation",
"replacement-generation", "revive", "death", "phase"))
|| !values.get("schema-version").equals("1")) throw new IllegalArgumentException();
boolean revive = switch (values.get("revive")) { case "true" -> true; case "false" -> false;
default -> throw new IllegalArgumentException(); };
String death = values.get("death");
return new Operation(UUID.fromString(values.get("operation")), UUID.fromString(values.get("character")),
UUID.fromString(values.get("administrator")), UUID.fromString(values.get("recipient")),
new BigInteger(values.get("expected-revision")), new BigInteger(values.get("expected-generation")),
new BigInteger(values.get("replacement-generation")), revive,
death.isEmpty() ? null : UUID.fromString(death), Phase.valueOf(values.get("phase")));
} catch (RuntimeException invalid) { throw new IOException("Invalid recovery record"); }
}
@FunctionalInterface private interface IoAction { void run() throws IOException; }
}