feat(ignis): establish durable progression foundations
This commit is contained in:
commit
7a481f366c
27 files changed
+1213
No files matched your search
@@ -0,0 +1,125 @@
|
||||
package games.dmg.spigotignis;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Versioned data, never Java object deserialization. Call from the persistence worker only. */
|
||||
public final class FileStateRepository implements StateRepository {
|
||||
private static final int MAGIC = 0x49474e49;
|
||||
private static final int VERSION = 1;
|
||||
private static final int MAX_RECORDS = 100_000;
|
||||
private final Path path;
|
||||
|
||||
public FileStateRepository(Path path) { this.path = path.toAbsolutePath(); }
|
||||
|
||||
@Override
|
||||
public IgnisState load() throws IOException {
|
||||
if (Files.notExists(path)) return IgnisState.empty();
|
||||
try (var input = new DataInputStream(new BufferedInputStream(Files.newInputStream(path)))) {
|
||||
if (input.readInt() != MAGIC || input.readInt() != VERSION) {
|
||||
throw new IOException("Unsupported Ignis state header or version.");
|
||||
}
|
||||
var limits = new ProgressLimits(input.readLong(), input.readLong(), input.readLong());
|
||||
Map<UUID, PlayerState> players = new HashMap<>();
|
||||
int count = count(input, MAX_RECORDS);
|
||||
for (int i = 0; i < count; i++) {
|
||||
UUID id = uuid(input);
|
||||
Map<Track, TrackState> tracks = new HashMap<>();
|
||||
int trackCount = count(input, Track.values().length);
|
||||
for (int j = 0; j < trackCount; j++) {
|
||||
Track track = Track.valueOf(input.readUTF());
|
||||
var state = new TrackState(input.readLong(), flag(input),
|
||||
flag(input), input.readLong());
|
||||
if (tracks.putIfAbsent(track, state) != null) throw new IOException("Duplicate track.");
|
||||
}
|
||||
Map<UUID, Track> pending = new HashMap<>();
|
||||
int rewards = count(input, MAX_RECORDS);
|
||||
for (int j = 0; j < rewards; j++) {
|
||||
if (pending.putIfAbsent(uuid(input), Track.valueOf(input.readUTF())) != null) {
|
||||
throw new IOException("Duplicate pending reward.");
|
||||
}
|
||||
}
|
||||
if (players.putIfAbsent(id, new PlayerState(tracks, pending)) != null) {
|
||||
throw new IOException("Duplicate player.");
|
||||
}
|
||||
}
|
||||
if (input.read() != -1) throw new IOException("Trailing Ignis state data.");
|
||||
return new IgnisState(limits, players);
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw new IOException("Invalid Ignis state; original file retained.", exception);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(IgnisState state) throws IOException {
|
||||
if (state.players().size() > MAX_RECORDS
|
||||
|| state.players().values().stream().anyMatch(p -> p.pendingRewards().size() > MAX_RECORDS)) {
|
||||
throw new IOException("Ignis state exceeds supported record count.");
|
||||
}
|
||||
Files.createDirectories(path.getParent());
|
||||
Path temporary = Files.createTempFile(path.getParent(), ".ignis-", ".tmp");
|
||||
try {
|
||||
try (var output = new DataOutputStream(new BufferedOutputStream(Files.newOutputStream(temporary)))) {
|
||||
output.writeInt(MAGIC);
|
||||
output.writeInt(VERSION);
|
||||
output.writeLong(state.limits().invisibilityMillis());
|
||||
output.writeLong(state.limits().pearls());
|
||||
output.writeLong(state.limits().darknessMillis());
|
||||
output.writeInt(state.players().size());
|
||||
for (var entry : state.players().entrySet()) {
|
||||
uuid(output, entry.getKey());
|
||||
output.writeInt(entry.getValue().tracks().size());
|
||||
for (var track : entry.getValue().tracks().entrySet()) {
|
||||
output.writeUTF(track.getKey().name());
|
||||
output.writeLong(track.getValue().progress());
|
||||
output.writeBoolean(track.getValue().unlocked());
|
||||
output.writeBoolean(track.getValue().activated());
|
||||
output.writeLong(track.getValue().generation());
|
||||
}
|
||||
output.writeInt(entry.getValue().pendingRewards().size());
|
||||
for (var reward : entry.getValue().pendingRewards().entrySet()) {
|
||||
uuid(output, reward.getKey());
|
||||
output.writeUTF(reward.getValue().name());
|
||||
}
|
||||
}
|
||||
}
|
||||
try (var file = FileChannel.open(temporary, StandardOpenOption.WRITE)) { file.force(true); }
|
||||
// Deliberately fail rather than fall back to a partial non-atomic replacement.
|
||||
Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
} finally {
|
||||
Files.deleteIfExists(temporary);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean flag(DataInputStream input) throws IOException {
|
||||
int value = input.readUnsignedByte();
|
||||
if (value > 1) throw new IOException("Invalid state flag.");
|
||||
return value == 1;
|
||||
}
|
||||
|
||||
private static int count(DataInputStream input, int maximum) throws IOException {
|
||||
int result = input.readInt();
|
||||
if (result < 0 || result > maximum) throw new IOException("Invalid record count.");
|
||||
return result;
|
||||
}
|
||||
|
||||
private static UUID uuid(DataInputStream input) throws IOException {
|
||||
return new UUID(input.readLong(), input.readLong());
|
||||
}
|
||||
|
||||
private static void uuid(DataOutputStream output, UUID id) throws IOException {
|
||||
output.writeLong(id.getMostSignificantBits());
|
||||
output.writeLong(id.getLeastSignificantBits());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package games.dmg.spigotignis;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
public record IgnisState(ProgressLimits limits, Map<UUID, PlayerState> players) {
|
||||
public IgnisState {
|
||||
Objects.requireNonNull(limits);
|
||||
players = Map.copyOf(players);
|
||||
}
|
||||
|
||||
public static IgnisState empty() { return new IgnisState(ProgressLimits.defaults(), Map.of()); }
|
||||
|
||||
public IgnisState evaluate(ProgressLimits nextLimits) {
|
||||
Objects.requireNonNull(nextLimits);
|
||||
Map<UUID, PlayerState> evaluated = new HashMap<>();
|
||||
players.forEach((id, player) -> {
|
||||
Map<Track, TrackState> tracks = new HashMap<>(player.tracks());
|
||||
for (Track track : Track.values()) {
|
||||
if (track == Track.VOID) continue;
|
||||
TrackState previous = player.track(track);
|
||||
long threshold = switch (track) {
|
||||
case MASK -> nextLimits.invisibilityMillis();
|
||||
case DAGGER -> nextLimits.pearls();
|
||||
case HEART -> nextLimits.darknessMillis();
|
||||
case VOID -> throw new IllegalStateException("Void is objective-based.");
|
||||
};
|
||||
if (previous.progress() >= threshold && !previous.unlocked()) {
|
||||
tracks.put(track, new TrackState(previous.progress(), true,
|
||||
previous.activated(), previous.generation()));
|
||||
}
|
||||
}
|
||||
evaluated.put(id, new PlayerState(tracks, player.pendingRewards()));
|
||||
});
|
||||
return new IgnisState(nextLimits, evaluated);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package games.dmg.spigotignis;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Pending reward identifiers are durable; gameplay delivery is a later adapter. */
|
||||
public record PlayerState(Map<Track, TrackState> tracks, Map<UUID, Track> pendingRewards) {
|
||||
public PlayerState {
|
||||
tracks = Map.copyOf(tracks);
|
||||
pendingRewards = Map.copyOf(pendingRewards);
|
||||
}
|
||||
|
||||
public static PlayerState empty() { return new PlayerState(Map.of(), Map.of()); }
|
||||
public TrackState track(Track track) { return tracks.getOrDefault(track, TrackState.empty()); }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package games.dmg.spigotignis;
|
||||
|
||||
/** Thresholds use milliseconds for online time and units for consumed pearls. */
|
||||
public record ProgressLimits(long invisibilityMillis, long pearls, long darknessMillis) {
|
||||
public ProgressLimits {
|
||||
if (invisibilityMillis <= 0 || pearls <= 0 || darknessMillis <= 0) {
|
||||
throw new IllegalArgumentException("All progression thresholds must be positive.");
|
||||
}
|
||||
}
|
||||
|
||||
public static ProgressLimits defaults() {
|
||||
return new ProgressLimits(12 * 60 * 60 * 1000L, 313, 6 * 60 * 60 * 1000L);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package games.dmg.spigotignis;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
/** Foundation bootstrap only: no gameplay listeners or player/admin commands are registered. */
|
||||
public final class SpigotIgnisPlugin extends JavaPlugin {
|
||||
private CompletableFuture<StateService> initialization;
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
initialization = StateService.open(new FileStateRepository(getDataFolder().toPath().resolve("state.bin")));
|
||||
initialization.whenComplete((service, error) -> {
|
||||
if (error != null) {
|
||||
getLogger().severe("Ignis state unavailable; original data retained. Restore a verified backup before retrying.");
|
||||
} else {
|
||||
getLogger().info("Ignis foundation loaded. No gameplay abilities or commands are enabled.");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
if (initialization != null) initialization.thenAccept(StateService::close);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package games.dmg.spigotignis;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public interface StateRepository {
|
||||
IgnisState load() throws IOException;
|
||||
void save(IgnisState state) throws IOException;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package games.dmg.spigotignis;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.function.UnaryOperator;
|
||||
|
||||
/** Serialized persistence: acknowledge and publish only after a successful atomic save. */
|
||||
public final class StateService implements AutoCloseable {
|
||||
private final StateRepository repository;
|
||||
private final ExecutorService worker;
|
||||
private volatile IgnisState current;
|
||||
|
||||
private StateService(StateRepository repository, ExecutorService worker, IgnisState current) {
|
||||
this.repository = repository;
|
||||
this.worker = worker;
|
||||
this.current = current;
|
||||
}
|
||||
|
||||
public static CompletableFuture<StateService> open(StateRepository repository) {
|
||||
Objects.requireNonNull(repository);
|
||||
ExecutorService worker = Executors.newSingleThreadExecutor(task -> new Thread(task, "ignis-persistence"));
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
return new StateService(repository, worker, repository.load());
|
||||
} catch (IOException | RuntimeException exception) {
|
||||
worker.shutdown();
|
||||
throw new java.util.concurrent.CompletionException(exception);
|
||||
}
|
||||
}, worker);
|
||||
}
|
||||
|
||||
public IgnisState snapshot() { return current; }
|
||||
|
||||
public CompletableFuture<IgnisState> configure(long invisibilityMillis, long pearls, long darknessMillis) {
|
||||
return update(state -> state.evaluate(new ProgressLimits(invisibilityMillis, pearls, darknessMillis)));
|
||||
}
|
||||
|
||||
/** Changes must be pure and must not access Bukkit or cause gameplay side effects. */
|
||||
public CompletableFuture<IgnisState> update(UnaryOperator<IgnisState> change) {
|
||||
Objects.requireNonNull(change);
|
||||
try {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
IgnisState next = Objects.requireNonNull(change.apply(current));
|
||||
try {
|
||||
repository.save(next);
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException(exception);
|
||||
}
|
||||
current = next;
|
||||
return next;
|
||||
}, worker);
|
||||
} catch (RejectedExecutionException exception) {
|
||||
return CompletableFuture.failedFuture(exception);
|
||||
}
|
||||
}
|
||||
|
||||
/** Non-blocking; already queued mutations finish, and further mutations are rejected. */
|
||||
@Override public void close() { worker.shutdown(); }
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package games.dmg.spigotignis;
|
||||
|
||||
public enum Track { VOID, MASK, DAGGER, HEART }
|
||||
@@ -0,0 +1,12 @@
|
||||
package games.dmg.spigotignis;
|
||||
|
||||
/** Immutable durable foundation; time counters are online milliseconds. */
|
||||
public record TrackState(long progress, boolean unlocked, boolean activated, long generation) {
|
||||
public TrackState {
|
||||
if (progress < 0 || generation < 0 || activated && !unlocked) {
|
||||
throw new IllegalArgumentException("Invalid progression state.");
|
||||
}
|
||||
}
|
||||
|
||||
public static TrackState empty() { return new TrackState(0, false, false, 0); }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
name: SpigotIgnis
|
||||
version: '${version}'
|
||||
main: games.dmg.spigotignis.SpigotIgnisPlugin
|
||||
api-version: '1.21'
|
||||
description: Ignis progression foundation; gameplay is not implemented yet.
|
||||
@@ -0,0 +1,80 @@
|
||||
package games.dmg.spigotignis;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class FileStateRepositoryTest {
|
||||
@TempDir Path directory;
|
||||
|
||||
@Test
|
||||
void missingStateStartsEmptyAndInterruptedTemporaryFilesAreNeverPromoted() throws Exception {
|
||||
java.nio.file.Files.writeString(directory.resolve(".ignis-interrupted.tmp"), "incomplete");
|
||||
assertEquals(IgnisState.empty(), new FileStateRepository(directory.resolve("state.bin")).load());
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedTruncatedFutureVersionAndTrailingDataAreRejectedWithoutRewriting() throws Exception {
|
||||
Path path = directory.resolve("state.bin");
|
||||
var repository = new FileStateRepository(path);
|
||||
repository.save(IgnisState.empty());
|
||||
byte[] valid = java.nio.file.Files.readAllBytes(path);
|
||||
byte[] future = valid.clone();
|
||||
future[7] = 2;
|
||||
byte[] negativeCount = valid.clone();
|
||||
java.util.Arrays.fill(negativeCount, 32, 36, (byte) 0xff);
|
||||
for (byte[] invalid : java.util.List.of(new byte[0], java.util.Arrays.copyOf(valid, 12),
|
||||
future, negativeCount, java.util.Arrays.copyOf(valid, valid.length + 1))) {
|
||||
java.nio.file.Files.write(path, invalid);
|
||||
assertThrows(java.io.IOException.class, repository::load);
|
||||
assertArrayEquals(invalid, java.nio.file.Files.readAllBytes(path));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedBooleanCannotSilentlyGrantAnUnlock() throws Exception {
|
||||
Path path = directory.resolve("state.bin");
|
||||
var repository = new FileStateRepository(path);
|
||||
repository.save(new IgnisState(ProgressLimits.defaults(), Map.of(UUID.randomUUID(),
|
||||
new PlayerState(Map.of(Track.MASK, TrackState.empty()), Map.of()))));
|
||||
byte[] bytes = java.nio.file.Files.readAllBytes(path);
|
||||
// Locate the schema's MASK tag, then corrupt the unlocked flag after the 8-byte counter.
|
||||
byte[] marker = "MASK".getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
int position = -1;
|
||||
for (int i = 0; i <= bytes.length - marker.length; i++) {
|
||||
if (java.util.Arrays.equals(marker, java.util.Arrays.copyOfRange(bytes, i, i + marker.length))) {
|
||||
position = i + marker.length + Long.BYTES;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assertTrue(position > 0);
|
||||
bytes[position] = 2;
|
||||
java.nio.file.Files.write(path, bytes);
|
||||
assertThrows(java.io.IOException.class, repository::load);
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidDestinationFailsWithoutLeavingTemporaryFiles() throws Exception {
|
||||
Path destination = directory.resolve("state.bin");
|
||||
java.nio.file.Files.createDirectory(destination);
|
||||
java.nio.file.Files.writeString(destination.resolve("preserve"), "unchanged");
|
||||
assertThrows(java.io.IOException.class, () -> new FileStateRepository(destination).save(IgnisState.empty()));
|
||||
assertEquals("unchanged", java.nio.file.Files.readString(destination.resolve("preserve")));
|
||||
try (var files = java.nio.file.Files.list(directory)) { assertEquals(1, files.count()); }
|
||||
}
|
||||
|
||||
@Test
|
||||
void progressActivationPendingRewardsAndInvalidationSurviveRepositoryReopen() throws Exception {
|
||||
var path = directory.resolve("ignis/state.bin");
|
||||
var expected = new IgnisState(new ProgressLimits(120, 313, 60), Map.of(UUID.randomUUID(),
|
||||
new PlayerState(Map.of(
|
||||
Track.VOID, new TrackState(1, true, true, 8),
|
||||
Track.MASK, new TrackState(119, false, false, 3)),
|
||||
Map.of(UUID.randomUUID(), Track.HEART))));
|
||||
new FileStateRepository(path).save(expected);
|
||||
assertEquals(expected, new FileStateRepository(path).load());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package games.dmg.spigotignis;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class PluginPackagingTest {
|
||||
@Test
|
||||
void packagedDescriptorHasExpandedVersionAndCorrectEntrypoint() throws Exception {
|
||||
try (var input = getClass().getResourceAsStream("/plugin.yml")) {
|
||||
assertNotNull(input, "A deployable plugin requires a descriptor");
|
||||
String descriptor = new String(input.readAllBytes(), StandardCharsets.UTF_8);
|
||||
assertTrue(descriptor.contains("name: SpigotIgnis"));
|
||||
assertTrue(descriptor.contains("main: games.dmg.spigotignis.SpigotIgnisPlugin"));
|
||||
assertFalse(descriptor.contains("${version}"));
|
||||
assertTrue(org.bukkit.plugin.java.JavaPlugin.class.isAssignableFrom(
|
||||
Class.forName("games.dmg.spigotignis.SpigotIgnisPlugin", false, getClass().getClassLoader())));
|
||||
assertFalse(descriptor.contains("commands:"), "Do not advertise unimplemented commands");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package games.dmg.spigotignis;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import java.time.Duration;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ProgressLimitsTest {
|
||||
@Test
|
||||
void rejectsNonPositiveThresholdsBeforeTheyCanBecomeActive() {
|
||||
assertThrows(IllegalArgumentException.class, () -> new ProgressLimits(0, 313, 1));
|
||||
assertThrows(IllegalArgumentException.class, () -> new ProgressLimits(1, -1, 1));
|
||||
assertThrows(IllegalArgumentException.class, () -> new ProgressLimits(1, 1, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultsUseApprovedTwelveHour313PearlAndSixHourThresholds() {
|
||||
assertEquals(new ProgressLimits(Duration.ofHours(12).toMillis(), 313,
|
||||
Duration.ofHours(6).toMillis()), ProgressLimits.defaults());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package games.dmg.spigotignis;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Static guardrails, not proof of remote CI or credential validity. */
|
||||
class ReleaseWorkflowTest {
|
||||
@Test
|
||||
void releaseScaffoldUsesVersionedAssetsAndProtectedCredentialInput() throws Exception {
|
||||
Path path = Path.of(".gitea/workflows/release.yml");
|
||||
assertTrue(Files.exists(path), "Release workflow must exist");
|
||||
String workflow = Files.readString(path);
|
||||
assertTrue(workflow.contains("spigot-ignis-${VERSION}.jar"));
|
||||
assertTrue(workflow.contains("--header @-"));
|
||||
assertTrue(workflow.contains("GIT_ASKPASS"));
|
||||
assertTrue(workflow.contains("persist-credentials: false"));
|
||||
assertFalse(workflow.contains("-H \"Authorization:"));
|
||||
assertFalse(workflow.contains("GITHUB_TOKEN:"), "Do not pass a token for semantic-release to embed into git URLs");
|
||||
assertFalse(workflow.contains("spigot-base"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package games.dmg.spigotignis;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class StateServiceTest {
|
||||
@TempDir Path directory;
|
||||
|
||||
@Test
|
||||
void failedWriteLeavesPreviousSnapshotAndAllowsRetryOffCallingThread() throws Exception {
|
||||
var disk = new FileStateRepository(directory.resolve("state.bin"));
|
||||
var fail = new java.util.concurrent.atomic.AtomicBoolean(true);
|
||||
Thread caller = Thread.currentThread();
|
||||
StateRepository boundary = new StateRepository() {
|
||||
@Override public IgnisState load() throws java.io.IOException {
|
||||
assertNotSame(caller, Thread.currentThread());
|
||||
return disk.load();
|
||||
}
|
||||
@Override public void save(IgnisState state) throws java.io.IOException {
|
||||
assertNotSame(caller, Thread.currentThread());
|
||||
if (fail.get()) throw new java.io.IOException("Simulated disk failure");
|
||||
disk.save(state);
|
||||
}
|
||||
};
|
||||
try (var service = StateService.open(boundary).get(3, TimeUnit.SECONDS)) {
|
||||
assertThrows(java.util.concurrent.ExecutionException.class,
|
||||
() -> service.configure(100, 200, 300).get(3, TimeUnit.SECONDS));
|
||||
assertEquals(IgnisState.empty(), service.snapshot());
|
||||
assertEquals(IgnisState.empty(), disk.load());
|
||||
fail.set(false);
|
||||
service.configure(100, 200, 300).get(3, TimeUnit.SECONDS);
|
||||
assertEquals(service.snapshot(), disk.load());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentQueuedUpdatesDoNotLoseProgressAndCloseRejectsNewWrites() throws Exception {
|
||||
UUID id = UUID.randomUUID();
|
||||
var repository = new FileStateRepository(directory.resolve("state.bin"));
|
||||
var service = StateService.open(repository).get(3, TimeUnit.SECONDS);
|
||||
try (service) {
|
||||
var writes = new java.util.ArrayList<java.util.concurrent.CompletableFuture<IgnisState>>();
|
||||
for (int i = 0; i < 30; i++) {
|
||||
writes.add(service.update(state -> {
|
||||
var player = state.players().getOrDefault(id, PlayerState.empty());
|
||||
long count = player.track(Track.DAGGER).progress();
|
||||
return new IgnisState(state.limits(), Map.of(id, new PlayerState(
|
||||
Map.of(Track.DAGGER, new TrackState(count + 1, false, false, 0)), Map.of())));
|
||||
}));
|
||||
}
|
||||
java.util.concurrent.CompletableFuture.allOf(writes.toArray(java.util.concurrent.CompletableFuture[]::new))
|
||||
.get(5, TimeUnit.SECONDS);
|
||||
assertEquals(30, repository.load().players().get(id).track(Track.DAGGER).progress());
|
||||
}
|
||||
assertThrows(java.util.concurrent.ExecutionException.class,
|
||||
() -> service.configure(1, 1, 1).get(3, TimeUnit.SECONDS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedExistingStateFailsInitializationInsteadOfGrantingBlankState() throws Exception {
|
||||
Path path = directory.resolve("state.bin");
|
||||
java.nio.file.Files.writeString(path, "broken");
|
||||
assertThrows(java.util.concurrent.ExecutionException.class,
|
||||
() -> StateService.open(new FileStateRepository(path)).get(3, TimeUnit.SECONDS));
|
||||
assertEquals("broken", java.nio.file.Files.readString(path));
|
||||
}
|
||||
|
||||
@Test
|
||||
void configurationValidatesBeforeChangingAnyDurableOrActiveSetting() throws Exception {
|
||||
var repository = new FileStateRepository(directory.resolve("state.bin"));
|
||||
try (var service = StateService.open(repository).get(3, TimeUnit.SECONDS)) {
|
||||
assertThrows(java.util.concurrent.ExecutionException.class,
|
||||
() -> service.configure(100, 0, 100).get(3, TimeUnit.SECONDS));
|
||||
assertEquals(ProgressLimits.defaults(), service.snapshot().limits());
|
||||
var limits = new ProgressLimits(100, 200, 300);
|
||||
service.configure(100, 200, 300).get(3, TimeUnit.SECONDS);
|
||||
assertEquals(limits, service.snapshot().limits());
|
||||
assertEquals(limits, repository.load().limits());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void acknowledgedUpdatesAreDurableAcrossReopen() throws Exception {
|
||||
var repository = new FileStateRepository(directory.resolve("state.bin"));
|
||||
UUID id = UUID.randomUUID();
|
||||
var expected = new IgnisState(ProgressLimits.defaults(), Map.of(id,
|
||||
new PlayerState(Map.of(Track.DAGGER, new TrackState(12, false, false, 0)), Map.of())));
|
||||
try (var service = StateService.open(repository).get(3, TimeUnit.SECONDS)) {
|
||||
assertEquals(expected, service.update(ignored -> expected).get(3, TimeUnit.SECONDS));
|
||||
assertEquals(expected, service.snapshot());
|
||||
}
|
||||
try (var reopened = StateService.open(repository).get(3, TimeUnit.SECONDS)) {
|
||||
assertEquals(expected, reopened.snapshot());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package games.dmg.spigotignis;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ThresholdEvaluationTest {
|
||||
@Test
|
||||
void evaluationIsIdempotentAndHigherLimitsDoNotRevokeEarnedUnlocks() {
|
||||
UUID id = UUID.randomUUID();
|
||||
var state = new IgnisState(new ProgressLimits(1, 1, 1), Map.of(id,
|
||||
new PlayerState(Map.of(
|
||||
Track.MASK, new TrackState(1, true, true, 5),
|
||||
Track.DAGGER, new TrackState(312, false, false, 0),
|
||||
Track.HEART, new TrackState(100, false, false, 0),
|
||||
Track.VOID, new TrackState(100, false, false, 0)), Map.of())));
|
||||
var next = state.evaluate(new ProgressLimits(200, 313, 100));
|
||||
assertTrue(next.players().get(id).track(Track.MASK).activated());
|
||||
assertFalse(next.players().get(id).track(Track.DAGGER).unlocked());
|
||||
assertTrue(next.players().get(id).track(Track.HEART).unlocked());
|
||||
assertFalse(next.players().get(id).track(Track.VOID).unlocked());
|
||||
assertEquals(next, next.evaluate(next.limits()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void negativeStateAndMutableCallerCollectionsCannotCorruptSnapshots() {
|
||||
assertThrows(IllegalArgumentException.class, () -> new TrackState(-1, false, false, 0));
|
||||
assertThrows(IllegalArgumentException.class, () -> new TrackState(0, false, true, 0));
|
||||
assertThrows(IllegalArgumentException.class, () -> new TrackState(0, false, false, -1));
|
||||
var tracks = new java.util.HashMap<Track, TrackState>();
|
||||
tracks.put(Track.MASK, TrackState.empty());
|
||||
var player = new PlayerState(tracks, Map.of());
|
||||
tracks.clear();
|
||||
assertEquals(1, player.tracks().size());
|
||||
assertThrows(UnsupportedOperationException.class, () -> player.tracks().clear());
|
||||
}
|
||||
|
||||
@Test
|
||||
void loweredThresholdUnlocksOnEvaluationWithoutChangingProgressOrRewards() {
|
||||
UUID player = UUID.randomUUID();
|
||||
UUID reward = UUID.randomUUID();
|
||||
var before = new IgnisState(ProgressLimits.defaults(), Map.of(player,
|
||||
new PlayerState(Map.of(Track.MASK, new TrackState(100, false, false, 2)),
|
||||
Map.of(reward, Track.VOID))));
|
||||
var after = before.evaluate(new ProgressLimits(100, 313, 1000));
|
||||
assertEquals(new TrackState(100, true, false, 2), after.players().get(player).track(Track.MASK));
|
||||
assertEquals(before.players().get(player).pendingRewards(), after.players().get(player).pendingRewards());
|
||||
assertFalse(before.players().get(player).track(Track.MASK).unlocked());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user