Files
purpur-fantasy-stick/src/main/java/games/dmg/fantasystick/persistence/SheetResourcePackSettings.java
T
dmg 0fcb1e7e9c
Release / release (push) Failing after 8m32s
feat(presentation): hide held character sheets
2026-09-20 15:13:54 -04:00

210 lines
11 KiB
Java

package games.dmg.fantasystick.persistence;
import java.io.IOException;
import java.net.URI;
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.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
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;
/** Durable paired resource-pack overrides; each publication carries the latest complete saved snapshot. */
public final class SheetResourcePackSettings implements AutoCloseable {
public static final String URL_KEY = "sheet-resource-pack-url";
public static final String SHA1_KEY = "sheet-resource-pack-sha1";
private static final int MAX_BYTES = 1_048_576;
@FunctionalInterface interface Replacement { void move(Path from, Path to) throws IOException; }
public record Defaults(String url, String sha1) {
public Defaults { url = effectiveUrl(url, new DefaultsMarker()); sha1 = normalizeHash(sha1, false); }
}
private static final class DefaultsMarker { }
public record Snapshot(String configuredUrl, String configuredSha1, String url, String sha1) { }
public record Update(Snapshot snapshot, long sequence) { }
private final Path directory;
private final Defaults defaults;
private final Replacement replacement;
private final java.util.concurrent.ExecutorService worker;
private volatile Snapshot effective;
private String persistedUrl;
private String persistedSha1;
private long persistedSequence;
private long publishedSequence;
private boolean closed;
private int pending;
private final CompletableFuture<Void> drained = new CompletableFuture<>();
public SheetResourcePackSettings(Path directory, Object configuredUrl, Object configuredSha1, Defaults defaults) {
this(directory, raw(configuredUrl, URL_KEY), raw(configuredSha1, SHA1_KEY), defaults,
(from, to) -> Files.move(from, to, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING));
}
SheetResourcePackSettings(Path directory, String configuredUrl, String configuredSha1, Defaults defaults, Replacement replacement) {
this.directory = Objects.requireNonNull(directory).toAbsolutePath();
this.defaults = Objects.requireNonNull(defaults);
this.replacement = Objects.requireNonNull(replacement);
effective = snapshot(configuredUrl, configuredSha1);
worker = Executors.newSingleThreadExecutor(task -> new Thread(task, "fantasy-sheet-resource-pack-configuration"));
persistedUrl = configuredUrl;
persistedSha1 = configuredSha1;
}
public static Defaults packagedDefaults() {
try (var input = SheetResourcePackSettings.class.getResourceAsStream("/sheet-resource-pack.properties")) {
if (input == null) throw new IOException("Missing packaged sheet resource-pack metadata");
var values = new Properties(); values.load(input);
return new Defaults(values.getProperty("url"), values.getProperty("sha1"));
} catch (IOException | IllegalArgumentException failure) {
throw new IllegalStateException("Invalid packaged sheet resource-pack metadata", failure);
}
}
private static String raw(Object value, String key) {
if (value == null) return "";
if (value instanceof String text) return text;
throw new IllegalArgumentException(key + " must be a string");
}
public static String effectiveUrl(String configured, Defaults defaults) {
Objects.requireNonNull(defaults);
return configured == null || configured.isEmpty() ? defaults.url() : validateUrl(configured);
}
private static String effectiveUrl(String value, DefaultsMarker ignored) { return validateUrl(value); }
private static String validateUrl(String value) {
if (value == null || value.length() > 2048 || value.chars().anyMatch(Character::isWhitespace)) {
throw new IllegalArgumentException(URL_KEY + " must be a supported HTTPS URL");
}
try {
var uri = URI.create(value);
if (!"https".equals(uri.getScheme()) || uri.getHost() == null || uri.getHost().isBlank()
|| uri.getRawUserInfo() != null || uri.getRawFragment() != null
|| uri.getRawPath() == null || uri.getRawPath().isBlank()) {
throw new IllegalArgumentException(URL_KEY + " must be an absolute HTTPS asset URL without credentials or fragment");
}
return uri.toASCIIString();
} catch (IllegalArgumentException invalid) {
throw new IllegalArgumentException(URL_KEY + " must be a supported HTTPS URL", invalid);
}
}
public static String effectiveSha1(String configured, Defaults defaults) {
Objects.requireNonNull(defaults);
return configured == null || configured.isEmpty() ? defaults.sha1() : normalizeHash(configured, false);
}
private static String normalizeHash(String value, boolean allowEmpty) {
if (allowEmpty && (value == null || value.isEmpty())) return "";
if (value == null || !value.matches("[a-fA-F0-9]{40}")) {
throw new IllegalArgumentException(SHA1_KEY + " must be exactly 40 hexadecimal characters");
}
return value.toLowerCase(java.util.Locale.ROOT);
}
private Snapshot snapshot(String configuredUrl, String configuredSha1) {
String url = configuredUrl == null ? "" : configuredUrl;
String sha1 = configuredSha1 == null ? "" : normalizeHash(configuredSha1, true);
return new Snapshot(url, sha1, effectiveUrl(url, defaults), effectiveSha1(sha1, defaults));
}
public String url() { return effective.url(); }
public String sha1() { return effective.sha1(); }
public String value(String key) {
var state = effective;
return switch (key) {
case URL_KEY -> state.url();
case SHA1_KEY -> state.sha1();
default -> throw new IllegalArgumentException("Unknown sheet resource-pack key");
};
}
public CompletionStage<Update> set(String key, String raw) {
if (!URL_KEY.equals(key) && !SHA1_KEY.equals(key)) throw new IllegalArgumentException("Unknown sheet resource-pack key");
if (raw == null) throw new IllegalArgumentException(key + " requires a value");
if (URL_KEY.equals(key) && !raw.isEmpty()) validateUrl(raw);
if (SHA1_KEY.equals(key)) raw = normalizeHash(raw, true);
final String accepted = raw;
synchronized (this) {
if (closed) return CompletableFuture.failedStage(new IOException("Configuration store is closed"));
pending++;
}
try {
return CompletableFuture.supplyAsync(() -> {
try {
save(key, accepted);
if (URL_KEY.equals(key)) persistedUrl = accepted; else persistedSha1 = accepted;
return new Update(snapshot(persistedUrl, persistedSha1), ++persistedSequence);
} catch (IOException | RuntimeException failure) {
throw new java.util.concurrent.CompletionException(new IOException(
"Sheet resource-pack configuration save refused or failed; effective settings unchanged"));
} finally { finished(); }
}, worker).minimalCompletionStage();
} catch (RejectedExecutionException rejected) {
finished();
return CompletableFuture.failedStage(new IOException("Configuration store is closed"));
}
}
public synchronized boolean publish(Update update) {
if (update.sequence() <= publishedSequence) return false;
effective = update.snapshot();
publishedSequence = update.sequence();
return true;
}
private void save(String key, String value) throws IOException {
Files.createDirectories(directory);
if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe directory");
var file = directory.resolve("config.yml"); var lockFile = directory.resolve(".config.lock");
if (Files.exists(lockFile, LinkOption.NOFOLLOW_LINKS) && !Files.isRegularFile(lockFile, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe lock");
try (var channel = FileChannel.open(lockFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS);
var lock = channel.tryLock()) {
if (lock == null) throw new IOException("Configuration busy");
var options = new LoaderOptions(); options.setAllowDuplicateKeys(false); options.setMaxAliasesForCollections(20); options.setCodePointLimit(MAX_BYTES);
var yaml = new Yaml(new SafeConstructor(options)); Map<String, Object> values = new LinkedHashMap<>();
if (Files.exists(file, LinkOption.NOFOLLOW_LINKS)) {
if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe configuration");
byte[] bytes; try (var input = Files.newInputStream(file, LinkOption.NOFOLLOW_LINKS)) { bytes = input.readNBytes(MAX_BYTES + 1); }
if (bytes.length > MAX_BYTES) throw new IOException("Configuration too large");
Object loaded = yaml.load(StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString());
if (loaded != null) {
if (!(loaded instanceof Map<?, ?> map)) throw new IOException("Invalid configuration root");
for (var entry : map.entrySet()) {
if (!(entry.getKey() instanceof String name)) throw new IOException("Invalid configuration key");
values.put(name, entry.getValue());
}
}
}
values.put(key, value);
byte[] bytes = yaml.dump(values).getBytes(StandardCharsets.UTF_8);
if (bytes.length > MAX_BYTES) throw new IOException("Configuration too large");
Path temporary = Files.createTempFile(directory, ".config-", ".tmp");
try {
try (var output = FileChannel.open(temporary, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS)) {
var buffer = ByteBuffer.wrap(bytes); while (buffer.hasRemaining()) output.write(buffer); output.force(true);
}
replacement.move(temporary, file);
} finally { Files.deleteIfExists(temporary); }
} catch (OverlappingFileLockException busy) { throw new IOException("Configuration busy"); }
}
private synchronized void finished() { pending--; if (closed && pending == 0) drained.complete(null); }
public CompletionStage<Void> drained() { return drained.minimalCompletionStage(); }
@Override public synchronized void close() { closed = true; worker.shutdown(); if (pending == 0) drained.complete(null); }
}