package games.dmg.fantasystick.persistence; import java.io.IOException; 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.Instant; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; 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.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; /** Feature-scoped Revive interruption proof; never authority to guess or mint an item. */ public final class RevivalStore implements AutoCloseable { private static final int MAX_FILE_BYTES = 32_768; private static final int MAX_FILES = 4096; private static final Set KEYS_V1 = Set.of("schema-version", "reservation-id", "caster-character-id", "target-player-id", "character-id", "death-id", "created-at", "source-slot", "source-amount", "destination-slot"); private static final Set KEYS_V2 = java.util.stream.Stream.concat(KEYS_V1.stream(), java.util.stream.Stream.of("administrative")) .collect(java.util.stream.Collectors.toUnmodifiableSet()); public record Reservation(UUID id, UUID casterCharacter, UUID targetPlayer, UUID character, UUID death, Instant createdAt, int sourceSlot, int sourceAmount, int destinationSlot, boolean administrative) { public Reservation(UUID id, UUID casterCharacter, UUID targetPlayer, UUID character, UUID death, Instant createdAt, int sourceSlot, int sourceAmount, int destinationSlot) { this(id, casterCharacter, targetPlayer, character, death, createdAt, sourceSlot, sourceAmount, destinationSlot, false); } public Reservation { Objects.requireNonNull(id); Objects.requireNonNull(casterCharacter); Objects.requireNonNull(targetPlayer); Objects.requireNonNull(character); Objects.requireNonNull(death); Objects.requireNonNull(createdAt); if (createdAt.getNano() != 0 || sourceSlot < 0 || sourceSlot > 40 || sourceSlot > 35 && sourceSlot != 40 || sourceAmount < 1 || sourceAmount > 99 || destinationSlot < -1 || destinationSlot > 40 || destinationSlot > 35 && destinationSlot != 40 || destinationSlot == sourceSlot) { throw new IllegalArgumentException("Invalid revival reservation"); } } } private final Path directory; private final ExecutorService worker = Executors.newSingleThreadExecutor( task -> new Thread(task, "fantasy-revival-persistence")); public RevivalStore(Path pluginDataDirectory) { directory = Objects.requireNonNull(pluginDataDirectory).resolve("revivals").toAbsolutePath(); } public CompletableFuture> reserve(Reservation reservation) { Objects.requireNonNull(reservation); return submit(() -> { Path file = file(reservation.character()); if (Files.exists(file, LinkOption.NOFOLLOW_LINKS)) return Optional.empty(); safeDirectory(); Path temporary = directory.resolve("." + reservation.character() + "." + UUID.randomUUID() + ".tmp"); try { Files.writeString(temporary, encode(reservation), StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE); Files.move(temporary, file, StandardCopyOption.ATOMIC_MOVE); } finally { Files.deleteIfExists(temporary); } return Optional.of(reservation); }); } public CompletableFuture> find(UUID character) { Objects.requireNonNull(character); return submit(() -> load(file(character))); } public CompletableFuture> target(UUID player) { Objects.requireNonNull(player); return submit(() -> { if (!Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) return List.of(); if (Files.isSymbolicLink(directory) || !Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) { throw new IOException("Unsafe revival directory"); } var result = new ArrayList(); try (var files = Files.list(directory)) { for (var path : files.limit(MAX_FILES + 1).toList()) { if (result.size() >= MAX_FILES) throw new IOException("Too many revival reservations"); if (!path.getFileName().toString().endsWith(".yml")) continue; var reservation = load(path).orElseThrow(() -> new IOException("Missing revival reservation")); if (reservation.targetPlayer().equals(player)) result.add(reservation); } } return List.copyOf(result); }); } public CompletableFuture clear(UUID character, UUID reservation) { Objects.requireNonNull(character); Objects.requireNonNull(reservation); return submit(() -> { var found = load(file(character)); if (found.isEmpty() || !found.orElseThrow().id().equals(reservation)) return false; return Files.deleteIfExists(file(character)); }); } 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("Unsafe revival directory"); } } else Files.createDirectories(directory); } private Path file(UUID character) { return directory.resolve(character + ".yml"); } private Optional load(Path file) throws IOException { if (!Files.exists(file, LinkOption.NOFOLLOW_LINKS)) return Optional.empty(); if (Files.isSymbolicLink(file) || !Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS) || Files.size(file) > MAX_FILE_BYTES) throw new IOException("Unsafe revival reservation"); Object decoded; try { var options = new LoaderOptions(); options.setAllowDuplicateKeys(false); options.setMaxAliasesForCollections(0); decoded = new Yaml(new SafeConstructor(options)).load(Files.readString(file, StandardCharsets.UTF_8)); } catch (RuntimeException invalid) { throw new IOException("Invalid revival reservation", invalid); } if (!(decoded instanceof Map raw) || !(raw.keySet().equals(KEYS_V1) || raw.keySet().equals(KEYS_V2))) throw new IOException("Invalid revival reservation keys"); try { String schema=text(raw,"schema-version");if(!(schema.equals("1")&&raw.keySet().equals(KEYS_V1)||schema.equals("2")&&raw.keySet().equals(KEYS_V2)))throw new IllegalArgumentException("schema"); var value = new Reservation(uuid(raw, "reservation-id"), uuid(raw, "caster-character-id"), uuid(raw, "target-player-id"), uuid(raw, "character-id"), uuid(raw, "death-id"), Instant.parse(text(raw, "created-at")), integer(raw, "source-slot"), integer(raw, "source-amount"), integer(raw, "destination-slot"), schema.equals("2") && bool(raw,"administrative")); if (!file.getFileName().toString().equals(value.character() + ".yml")) throw new IllegalArgumentException("identity"); return Optional.of(value); } catch (RuntimeException invalid) { throw new IOException("Invalid revival reservation", invalid); } } private static String encode(Reservation value) { var map = new LinkedHashMap(); map.put("schema-version", "2"); map.put("reservation-id", value.id().toString()); map.put("caster-character-id", value.casterCharacter().toString()); map.put("target-player-id", value.targetPlayer().toString()); map.put("character-id", value.character().toString()); map.put("death-id", value.death().toString()); map.put("created-at", value.createdAt().toString()); map.put("source-slot", Integer.toString(value.sourceSlot())); map.put("source-amount", Integer.toString(value.sourceAmount())); map.put("destination-slot", Integer.toString(value.destinationSlot())); map.put("administrative", Boolean.toString(value.administrative())); return new Yaml().dump(map); } private static String text(Map map, String key) { Object value = map.get(key); if (!(value instanceof String text) || text.isBlank()) throw new IllegalArgumentException(key); return text; } private static UUID uuid(Map map, String key) { var value = UUID.fromString(text(map, key)); if (!value.toString().equals(text(map, key))) throw new IllegalArgumentException(key); return value; } private static int integer(Map map, String key) { return Integer.parseInt(text(map, key)); } private static boolean bool(Map map,String key){String value=text(map,key);if(!value.equals("true")&&!value.equals("false"))throw new IllegalArgumentException(key);return Boolean.parseBoolean(value);} @FunctionalInterface private interface Work { T run() throws IOException; } private CompletableFuture submit(Work work) { try { return CompletableFuture.supplyAsync(() -> { try { return work.run(); } catch (IOException error) { throw new CompletionException(error); } }, worker); } catch (RejectedExecutionException rejected) { return CompletableFuture.failedFuture(rejected); } } @Override public void close() { worker.shutdown(); } }