Files
purpur-fantasy-stick/src/main/java/games/dmg/fantasystick/persistence/EquipmentSessionStore.java
T
dmg 6ac4c4bfde
CI / build (push) Failing after 4m43s
Release / release (push) Failing after 4m45s
feat(sessions): complete native health and fantasy defeat
2026-09-19 12:37:20 -04:00

383 lines
19 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.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
/**
* Player/session receipts, never an external copy of equipment or proof of restoration.
* All disk work is deferred. Coordination assumes cooperating writers, not adversarial
* replacement of directories. Forced atomic file replacement is not inventory/save atomicity
* or a guarantee of directory durability after power loss. Ambiguous receipts are retained.
*/
public final class EquipmentSessionStore implements AutoCloseable {
private static final int MAX_FILE_BYTES = 16_384;
private final Path directory;
private final Clock clock;
private final Replacement replacement;
@FunctionalInterface
interface Replacement { void move(Path source, Path target) throws IOException; }
private final ExecutorService worker = Executors.newSingleThreadExecutor(
task -> new Thread(task, "fantasy-equipment-session-persistence"));
public record Receipt(UUID sessionId, UUID characterId, Instant preparedAt, String previousGameMode, OrdinaryVitals ordinaryVitals) {
public Receipt(UUID sessionId, UUID characterId, Instant preparedAt) { this(sessionId, characterId, preparedAt, null, null); }
public Receipt(UUID sessionId, UUID characterId, Instant preparedAt, String previousGameMode) {
this(sessionId, characterId, preparedAt, previousGameMode, null);
}
public Receipt {
Objects.requireNonNull(sessionId);
Objects.requireNonNull(characterId);
timestamp(preparedAt);
if (previousGameMode != null && !Set.of("SURVIVAL", "CREATIVE", "ADVENTURE", "SPECTATOR").contains(previousGameMode)) {
throw new IllegalArgumentException("Invalid previous game mode");
}
}
}
public record Exit(UUID sessionId, UUID characterId, Instant exitedAt, Instant deadline) {
public Exit {
Objects.requireNonNull(sessionId);
Objects.requireNonNull(characterId);
timestamp(exitedAt);
timestamp(deadline);
if (deadline.isBefore(exitedAt)) throw new IllegalArgumentException("Deadline precedes exit");
}
}
public record State(UUID playerId, BigInteger revision, Receipt pending, Exit lastExit) {
public State {
Objects.requireNonNull(playerId);
Objects.requireNonNull(revision);
if (revision.signum() < 0) throw new IllegalArgumentException("Negative session revision");
if (pending != null && lastExit != null && pending.sessionId().equals(lastExit.sessionId())
&& !pending.characterId().equals(lastExit.characterId())) {
throw new IllegalArgumentException("Inconsistent session character");
}
}
/** Only a delay check; this does not authorize a sheet, equipment, or native state changes. */
public boolean canEnter(UUID character, Duration configuredDelay, Instant now) {
Objects.requireNonNull(character);
Objects.requireNonNull(configuredDelay);
Objects.requireNonNull(now);
if (configuredDelay.isNegative()) throw new IllegalArgumentException("Negative switch delay");
return configuredDelay.isZero() || lastExit == null || character.equals(lastExit.characterId())
|| !now.isBefore(lastExit.deadline());
}
}
/** No filesystem access, directory creation or recovery occurs in the constructor. */
public EquipmentSessionStore(Path pluginDataDirectory, Clock clock) {
this(pluginDataDirectory, clock, (source, target) -> Files.move(source, target,
StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING));
}
// Narrow disk-boundary seam for deterministic acknowledgment/failure tests.
EquipmentSessionStore(Path pluginDataDirectory, Clock clock, Replacement replacement) {
directory = Objects.requireNonNull(pluginDataDirectory).resolve("sessions").toAbsolutePath();
this.clock = Objects.requireNonNull(clock);
this.replacement = Objects.requireNonNull(replacement);
}
public CompletionStage<Optional<State>> find(UUID player) {
Objects.requireNonNull(player);
return submit(() -> withLock(() -> load(player)));
}
public CompletionStage<State> prepare(UUID player, UUID session, UUID character) {
return prepare(player, session, character, null);
}
/** A receipt acknowledgment precedes mode/gear mutation; it is not proof either happened. */
public CompletionStage<State> prepare(UUID player, UUID session, UUID character, String previousGameMode) {
return prepare(player, session, character, previousGameMode, null);
}
public CompletionStage<State> prepare(UUID player, UUID session, UUID character, String previousGameMode, OrdinaryVitals ordinaryVitals) {
Objects.requireNonNull(player);
var receipt = new Receipt(session, character, clock.instant(), previousGameMode, ordinaryVitals);
return submit(() -> withLock(() -> {
var found = load(player);
if (found.isPresent()) {
var old = found.orElseThrow();
if (old.pending() != null) {
if (session.equals(old.pending().sessionId()) && character.equals(old.pending().characterId())
&& Objects.equals(previousGameMode, old.pending().previousGameMode())
&& Objects.equals(ordinaryVitals, old.pending().ordinaryVitals())) {
return old;
}
throw new IOException("Conflicting pending equipment session");
}
if (old.lastExit() != null && session.equals(old.lastExit().sessionId())) {
throw new IOException("Exited session cannot be prepared again");
}
return write(new State(player, old.revision().add(BigInteger.ONE), receipt, old.lastExit()));
}
return write(new State(player, BigInteger.ZERO, receipt, null));
}));
}
/** Capture the actual exit request time, never queue completion time. The receipt remains pending. */
public CompletionStage<State> recordExit(UUID player, UUID session, Duration delay) {
Objects.requireNonNull(player);
Objects.requireNonNull(session);
Objects.requireNonNull(delay);
Instant exitedAt = clock.instant();
return submit(() -> {
if (delay.isNegative()) throw new IllegalArgumentException("Negative switch delay");
Instant deadline = exitedAt.plus(delay);
timestamp(exitedAt);
timestamp(deadline);
return withLock(() -> {
var old = load(player).orElseThrow(() -> new IOException("Equipment session not found"));
if (old.lastExit() != null && session.equals(old.lastExit().sessionId())) return old;
if (old.pending() == null || !session.equals(old.pending().sessionId())) {
throw new IOException("Exit does not identify the prepared session");
}
var exit = new Exit(session, old.pending().characterId(), exitedAt, deadline);
return write(new State(player, old.revision().add(BigInteger.ONE), old.pending(), exit));
});
});
}
/** Atomically record a proven native restoration and clear only its matching receipt. */
public CompletionStage<State> completeExit(UUID player, UUID session, Duration delay) {
Objects.requireNonNull(player);
Objects.requireNonNull(session);
Objects.requireNonNull(delay);
Instant exitedAt = clock.instant();
return submit(() -> {
if (delay.isNegative()) throw new IllegalArgumentException("Negative switch delay");
Instant deadline = exitedAt.plus(delay);
timestamp(exitedAt);
timestamp(deadline);
return withLock(() -> {
var old = load(player).orElseThrow(() -> new IOException("Equipment session not found"));
boolean recorded = old.lastExit() != null && session.equals(old.lastExit().sessionId());
boolean matching = old.pending() != null && session.equals(old.pending().sessionId());
if (recorded && !matching) return old; // Never clear a newer pending receipt.
if (!matching) throw new IOException("Exit does not identify the prepared session");
var exit = recorded ? old.lastExit()
: new Exit(session, old.pending().characterId(), exitedAt, deadline);
return write(new State(player, old.revision().add(BigInteger.ONE), null, exit));
});
});
}
/** Caller must prove never-packed or actually restored; absent items are not such proof. */
public CompletionStage<State> clearReceipt(UUID player, UUID session) {
Objects.requireNonNull(player);
Objects.requireNonNull(session);
return submit(() -> withLock(() -> {
var old = load(player).orElseThrow(() -> new IOException("Equipment session not found"));
if (old.pending() == null) return old;
if (!session.equals(old.pending().sessionId())) throw new IOException("Receipt session mismatch");
return write(new State(player, old.revision().add(BigInteger.ONE), null, old.lastExit()));
}));
}
@FunctionalInterface
private interface DiskOperation<T> { T run() throws IOException; }
private <T> CompletionStage<T> submit(DiskOperation<T> operation) {
try {
return CompletableFuture.supplyAsync(() -> {
try {
return operation.run();
} catch (IOException exception) {
throw new CompletionException(exception);
}
}, worker).minimalCompletionStage();
} catch (RejectedExecutionException exception) {
return CompletableFuture.failedStage(exception);
}
}
private <T> T withLock(DiskOperation<T> operation) throws IOException {
try {
Files.createDirectories(directory);
if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) {
throw new IOException("Unsafe session directory");
}
Path lockPath = directory.resolve(".sessions.lock");
if (Files.exists(lockPath, LinkOption.NOFOLLOW_LINKS)
&& !Files.isRegularFile(lockPath, LinkOption.NOFOLLOW_LINKS)) {
throw new IOException("Unsafe session coordination file");
}
try (var channel = FileChannel.open(lockPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE,
LinkOption.NOFOLLOW_LINKS);
var lock = channel.tryLock()) {
if (lock == null) throw new IOException("Equipment session busy; retry the operation");
return operation.run();
}
} catch (OverlappingFileLockException exception) {
throw new IOException("Equipment session busy; retry the operation");
} catch (IOException exception) {
// Filesystem paths and parser data must not escape through diagnostics/cause chains.
throw new IOException("Equipment session IO refused or failed; original state must be inspected");
}
}
private Optional<State> load(UUID player) throws IOException {
Path path = file(player);
if (Files.notExists(path, LinkOption.NOFOLLOW_LINKS)) return Optional.empty();
if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe session record");
try (var input = Files.newInputStream(path, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) {
byte[] bytes = input.readNBytes(MAX_FILE_BYTES + 1);
if (bytes.length > MAX_FILE_BYTES) throw new IOException("Session record exceeds size limit");
String text = StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString();
State state = decode(text);
if (!state.playerId().equals(player)) throw new IllegalArgumentException("Session player mismatch");
return Optional.of(state);
} catch (RuntimeException exception) {
throw new IOException("Invalid equipment session YAML");
}
}
private State write(State state) throws IOException {
byte[] bytes = encode(state).getBytes(StandardCharsets.UTF_8);
if (bytes.length > MAX_FILE_BYTES) throw new IOException("Session record exceeds size limit");
Path temporary = Files.createTempFile(directory, ".session-", ".tmp");
try {
try (var output = FileChannel.open(temporary, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS)) {
ByteBuffer buffer = ByteBuffer.wrap(bytes);
while (buffer.hasRemaining()) output.write(buffer);
output.force(true);
}
// Do not fall back to truncating or non-atomic replacement of an existing record.
replacement.move(temporary, file(state.playerId()));
return state;
} finally {
Files.deleteIfExists(temporary);
}
}
private Path file(UUID player) { return directory.resolve(player + ".yml"); }
private static Yaml yaml() {
var options = new LoaderOptions();
options.setAllowDuplicateKeys(false);
options.setMaxAliasesForCollections(0);
options.setNestingDepthLimit(8);
options.setCodePointLimit(MAX_FILE_BYTES);
return new Yaml(new SafeConstructor(options));
}
private static String encode(State state) {
Map<String, Object> root = new LinkedHashMap<>();
root.put("schema-version", 1);
root.put("player-id", state.playerId().toString());
root.put("revision", state.revision().toString());
if (state.pending() != null) {
var receipt = state.pending();
var pending = new LinkedHashMap<String, Object>();
pending.put("session-id", receipt.sessionId().toString());
pending.put("character-id", receipt.characterId().toString());
pending.put("prepared-at", receipt.preparedAt().toString());
if (receipt.previousGameMode() != null) pending.put("previous-game-mode", receipt.previousGameMode());
if (receipt.ordinaryVitals() != null) pending.put("ordinary-vitals", receipt.ordinaryVitals().encode());
root.put("pending", pending);
}
if (state.lastExit() != null) {
var exit = state.lastExit();
root.put("last-exit", Map.of("session-id", exit.sessionId().toString(),
"character-id", exit.characterId().toString(), "exited-at", exit.exitedAt().toString(),
"deadline", exit.deadline().toString()));
}
return yaml().dump(root);
}
private static State decode(String input) {
Map<?, ?> root = mapping(yaml().load(input), Set.of("schema-version", "player-id", "revision"),
Set.of("schema-version", "player-id", "revision", "pending", "last-exit"));
if (!Integer.valueOf(1).equals(root.get("schema-version"))) {
throw new IllegalArgumentException("Unsupported session schema");
}
Receipt pending = null;
Exit exit = null;
if (root.containsKey("pending")) {
var keys = Set.of("session-id", "character-id", "prepared-at");
var row = mapping(root.get("pending"), keys, Set.of("session-id", "character-id", "prepared-at", "previous-game-mode", "ordinary-vitals"));
String previousMode = null;
if (row.containsKey("previous-game-mode")) {
if (!(row.get("previous-game-mode") instanceof String value)) throw new IllegalArgumentException("Invalid previous mode");
previousMode = value;
}
pending = new Receipt(id(row.get("session-id")), id(row.get("character-id")), instant(row.get("prepared-at")), previousMode,
row.containsKey("ordinary-vitals") ? OrdinaryVitals.decode(text(row.get("ordinary-vitals"))) : null);
}
if (root.containsKey("last-exit")) {
var keys = Set.of("session-id", "character-id", "exited-at", "deadline");
var row = mapping(root.get("last-exit"), keys, keys);
exit = new Exit(id(row.get("session-id")), id(row.get("character-id")),
instant(row.get("exited-at")), instant(row.get("deadline")));
}
String revision = text(root.get("revision"));
if (!revision.matches("0|[1-9][0-9]*")) throw new IllegalArgumentException("Invalid revision");
return new State(id(root.get("player-id")), new BigInteger(revision), pending, exit);
}
private static Map<?, ?> mapping(Object value, Set<String> required, Set<String> allowed) {
if (value instanceof Map<?, ?> map && map.keySet().containsAll(required) && allowed.containsAll(map.keySet())) {
return map;
}
throw new IllegalArgumentException("Invalid session mapping");
}
private static String text(Object value) {
if (value instanceof String string) return string;
throw new IllegalArgumentException("Expected session string");
}
private static UUID id(Object value) {
String string = text(value);
UUID id = UUID.fromString(string);
if (!id.toString().equals(string)) throw new IllegalArgumentException("Noncanonical session UUID");
return id;
}
private static Instant instant(Object value) {
String string = text(value);
if (!string.matches("[0-9]{4}-[0-9]{2}-[0-9]{2}T(?:[01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](?:\\.[0-9]{1,9})?Z")) {
throw new IllegalArgumentException("Expected UTC session timestamp");
}
return Instant.parse(string);
}
private static void timestamp(Instant value) {
instant(Objects.requireNonNull(value).toString());
}
/** Nonblocking shutdown: accepted work drains; no recovery sweep, deletion or replay. */
@Override public void close() { worker.shutdown(); }
}