190 lines
9.9 KiB
Java
190 lines
9.9 KiB
Java
package games.dmg.fantasystick.persistence;
|
|
|
|
import games.dmg.fantasystick.ability.StoneSkin;
|
|
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.time.Duration;
|
|
import java.util.LinkedHashMap;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
import java.util.Objects;
|
|
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;
|
|
|
|
/** Serialized durable Stone Skin settings; publication remains a server-thread caller decision. */
|
|
public final class StoneSkinSettings implements AutoCloseable {
|
|
private static final int MAX_BYTES = 1_048_576;
|
|
public static final String COOLDOWN = "stone-skin-cooldown-seconds";
|
|
public static final String DURATION = "stone-skin-duration-seconds";
|
|
public static final String REDUCTION = "stone-skin-damage-reduction-percent";
|
|
private static final List<String> KEYS = List.of(COOLDOWN, DURATION, REDUCTION);
|
|
private static final Map<String, String> DEFAULTS = Map.of(COOLDOWN, "14", DURATION, "4", REDUCTION, "25");
|
|
|
|
@FunctionalInterface interface Replacement { void move(Path from, Path to) throws IOException; }
|
|
public record Update(String key, String value, StoneSkin.Settings settings,
|
|
Map<String, String> values, long sequence) {
|
|
public Update { values = Map.copyOf(values); }
|
|
}
|
|
|
|
private final Path directory;
|
|
private final Replacement replacement;
|
|
private final java.util.concurrent.ExecutorService worker = Executors.newSingleThreadExecutor(
|
|
task -> new Thread(task, "fantasy-stone-skin-configuration"));
|
|
private volatile Map<String, String> effectiveValues;
|
|
private Map<String, String> persistedValues;
|
|
private long persistedSequence;
|
|
private long publishedSequence;
|
|
private boolean closed;
|
|
private int pending;
|
|
private final CompletableFuture<Void> drained = new CompletableFuture<>();
|
|
|
|
public StoneSkinSettings(Path directory, Map<String, String> initial) {
|
|
this(directory, initial, (from, to) -> Files.move(from, to,
|
|
StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING));
|
|
}
|
|
|
|
StoneSkinSettings(Path directory, Map<String, String> initial, Replacement replacement) {
|
|
this.directory = Objects.requireNonNull(directory).toAbsolutePath();
|
|
this.replacement = Objects.requireNonNull(replacement);
|
|
var copy = new LinkedHashMap<String, String>();
|
|
for (String key : KEYS) copy.put(key, Objects.requireNonNull(initial.get(key)));
|
|
parse(copy);
|
|
effectiveValues = Map.copyOf(copy); persistedValues = Map.copyOf(copy);
|
|
}
|
|
|
|
public static List<String> keys() { return KEYS; }
|
|
public static String defaultValue(String key) { return DEFAULTS.get(key); }
|
|
public String value(String key) { return effectiveValues.get(key); }
|
|
public StoneSkin.Settings settings() { return parse(effectiveValues); }
|
|
|
|
/** Publish only after the caller returns the durable acknowledgment to the server thread. */
|
|
public synchronized boolean publish(Update update) {
|
|
Objects.requireNonNull(update);
|
|
if (update.sequence() <= publishedSequence) return false;
|
|
parse(update.values());
|
|
effectiveValues = update.values(); publishedSequence = update.sequence();
|
|
return true;
|
|
}
|
|
|
|
public CompletionStage<Update> set(String key, String value) {
|
|
Objects.requireNonNull(key); Objects.requireNonNull(value);
|
|
if (!KEYS.contains(key)) return CompletableFuture.failedStage(new IllegalArgumentException("Unknown setting"));
|
|
String accepted = canonical(key, value);
|
|
var preview = new LinkedHashMap<>(effectiveValues); preview.put(key, accepted);
|
|
parse(preview); // Fail malformed/out-of-range command input before queueing accepted persistence.
|
|
synchronized (this) {
|
|
if (closed) return CompletableFuture.failedStage(new IOException("Configuration store is closed"));
|
|
pending++;
|
|
}
|
|
try {
|
|
return CompletableFuture.supplyAsync(() -> {
|
|
try {
|
|
var next = new LinkedHashMap<>(persistedValues);
|
|
next.put(key, accepted);
|
|
var parsed = parse(next);
|
|
save(key, accepted);
|
|
persistedValues = Map.copyOf(next);
|
|
return new Update(key, accepted, parsed, persistedValues, ++persistedSequence);
|
|
} catch (IOException | RuntimeException failure) {
|
|
throw new java.util.concurrent.CompletionException(failure instanceof IllegalArgumentException
|
|
? failure : new IOException("Stone Skin 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"));
|
|
}
|
|
}
|
|
|
|
private static String canonical(String key, String raw) {
|
|
try {
|
|
return new java.math.BigDecimal(raw).stripTrailingZeros().toPlainString();
|
|
} catch (NumberFormatException invalid) { throw new IllegalArgumentException("Invalid value", invalid); }
|
|
}
|
|
|
|
public static StoneSkin.Settings parse(Map<String, String> values) {
|
|
try {
|
|
var cooldown = seconds(values.get(COOLDOWN));
|
|
var duration = seconds(values.get(DURATION));
|
|
var reduction = new java.math.BigDecimal(values.get(REDUCTION));
|
|
return new StoneSkin.Settings(cooldown, duration, reduction);
|
|
} catch (ArithmeticException | NumberFormatException | NullPointerException invalid) {
|
|
throw new IllegalArgumentException("Stone Skin settings must use supported numeric values", invalid);
|
|
}
|
|
}
|
|
|
|
private static Duration seconds(String value) {
|
|
var nanos = new java.math.BigDecimal(value).movePointRight(9).toBigIntegerExact().longValueExact();
|
|
return Duration.ofNanos(nanos);
|
|
}
|
|
|
|
private static double finite(String value) {
|
|
double result = new java.math.BigDecimal(value).doubleValue();
|
|
if (!Double.isFinite(result)) throw new IllegalArgumentException("Setting is not finite");
|
|
return result;
|
|
}
|
|
|
|
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> document = 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 savedKey)) throw new IOException("Invalid configuration key");
|
|
document.put(savedKey, entry.getValue());
|
|
}
|
|
}
|
|
}
|
|
document.put(key, value);
|
|
byte[] bytes = yaml.dump(document).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);
|
|
}
|
|
}
|