feat(equipment): complete safe session packing and restoration
This commit is contained in:
1 parent
db87505142
commit
f7d01381ec
23 files changed
+7296
-33
No files matched your search
@@ -27,8 +27,11 @@ class DistributionTest {
|
||||
assertFalse(metadata.getVersion().contains("${"));
|
||||
assertEquals("games.dmg.fantasystick.FantasyStickPlugin", metadata.getMain());
|
||||
assertNotNull(metadata.getAPIVersion(), "Declare the native API compatibility contract");
|
||||
assertTrue(metadata.getCommands().isEmpty(), "Admin commands are not yet approved");
|
||||
assertTrue(metadata.getPermissions().isEmpty());
|
||||
assertEquals(java.util.Set.of("fantasystick"), metadata.getCommands().keySet());
|
||||
assertEquals("fantasystick.admin", metadata.getCommands().get("fantasystick").get("permission"));
|
||||
assertEquals(1, metadata.getPermissions().size());
|
||||
assertEquals("fantasystick.admin", metadata.getPermissions().getFirst().getName());
|
||||
assertEquals(org.bukkit.permissions.PermissionDefault.OP, metadata.getPermissions().getFirst().getDefault());
|
||||
assertTrue(JavaPlugin.class.isAssignableFrom(FantasyStickPlugin.class));
|
||||
var entrypoint = jar.getJarEntry(metadata.getMain().replace('.', '/') + ".class");
|
||||
assertNotNull(entrypoint);
|
||||
|
||||
@@ -129,6 +129,96 @@ class CharacterStorageTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void latestDeathPreservesQueuedRenameAndProgressAndAcknowledgesOnlyOneDeath() throws Exception {
|
||||
var template = YamlCharacterRepositoryTest.sample(UUID.randomUUID());
|
||||
var live = new CharacterRecord(template.id(), template.name(), BigInteger.ZERO, template.stats(),
|
||||
template.level(), template.experience(), template.unspentPoints(), template.maximumHealth(),
|
||||
template.learned(), template.loadout(), template.cooldowns(), false, null, null);
|
||||
var now = template.diedAt().plusSeconds(60);
|
||||
try (var storage = new CharacterStorage(new YamlCharacterRepository(data), Clock.fixed(now, ZoneOffset.UTC))) {
|
||||
storage.create(live).join();
|
||||
var rename = storage.renameCharacter(live.id(), "Newest anvil name");
|
||||
// This is one worker operation, not a caller-side find -> expected-revision write.
|
||||
var death = storage.recordDeath(live.id());
|
||||
var duplicate = storage.recordDeath(live.id());
|
||||
var latest = rename.join().orElseThrow();
|
||||
var dead = death.join().orElseThrow();
|
||||
assertEquals(latest.name(), dead.name());
|
||||
assertEquals(latest.revision().add(BigInteger.ONE), dead.revision());
|
||||
assertEquals(latest.stats(), dead.stats()); assertEquals(latest.cooldowns(), dead.cooldowns());
|
||||
assertEquals(latest.experience(), dead.experience()); assertEquals(latest.loadout(), dead.loadout());
|
||||
assertEquals(latest.level(), dead.level()); assertEquals(latest.unspentPoints(), dead.unspentPoints());
|
||||
assertEquals(latest.learned(), dead.learned()); assertEquals(java.math.BigDecimal.ZERO, dead.health());
|
||||
assertEquals(now, dead.diedAt()); assertNotNull(dead.deathId()); assertTrue(dead.dead());
|
||||
assertTrue(duplicate.join().isEmpty());
|
||||
assertEquals(dead, storage.find(live.id()).join().orElseThrow());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void deathCapturesRequestTimeAndDoesNotAcknowledgeBeforeAtomicReplacement() throws Exception {
|
||||
var template = YamlCharacterRepositoryTest.sample(UUID.randomUUID());
|
||||
var live = new CharacterRecord(template.id(), template.name(), BigInteger.ZERO, template.stats(),
|
||||
template.level(), template.experience(), template.unspentPoints(), template.maximumHealth(),
|
||||
template.learned(), template.loadout(), template.cooldowns(), false, null, null);
|
||||
var requestedAt = template.diedAt().plusSeconds(10);
|
||||
var time = new java.util.concurrent.atomic.AtomicReference<>(requestedAt);
|
||||
var clock = new Clock() {
|
||||
@Override public java.time.ZoneId getZone() { return ZoneOffset.UTC; }
|
||||
@Override public Clock withZone(java.time.ZoneId zone) { return this; }
|
||||
@Override public java.time.Instant instant() { return time.get(); }
|
||||
};
|
||||
var entered = new CountDownLatch(1); var release = new CountDownLatch(1);
|
||||
var writes = new java.util.concurrent.atomic.AtomicInteger(); var caller = Thread.currentThread();
|
||||
var repository = new YamlCharacterRepository(data, (source, target) -> {
|
||||
assertNotSame(caller, Thread.currentThread());
|
||||
if (writes.incrementAndGet() == 1) {
|
||||
entered.countDown();
|
||||
try { if (!release.await(5, TimeUnit.SECONDS)) throw new IOException("Gate timeout"); }
|
||||
catch (InterruptedException e) { throw new IOException(e); }
|
||||
}
|
||||
Files.move(source, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
});
|
||||
try (var storage = new CharacterStorage(repository, clock)) {
|
||||
var create = storage.create(live);
|
||||
java.util.concurrent.CompletableFuture<java.util.Optional<CharacterRecord>> death;
|
||||
try {
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||
death = storage.recordDeath(live.id());
|
||||
time.set(requestedAt.plusSeconds(90));
|
||||
assertFalse(death.isDone());
|
||||
} finally { release.countDown(); }
|
||||
create.get(5, TimeUnit.SECONDS);
|
||||
var dead = death.get(5, TimeUnit.SECONDS).orElseThrow();
|
||||
assertEquals(requestedAt, dead.diedAt()); assertEquals(dead, repository.load(live.id()).orElseThrow());
|
||||
assertEquals(2, writes.get());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void deathWriteFailureOrLostAcknowledgmentNeverPermitsDuplicateDeathOfAnAlreadyDeadRecord() throws Exception {
|
||||
for (boolean moved : new boolean[]{false, true}) {
|
||||
var template = YamlCharacterRepositoryTest.sample(UUID.randomUUID());
|
||||
var live = new CharacterRecord(template.id(), template.name(), BigInteger.ZERO, template.stats(),
|
||||
template.level(), template.experience(), template.unspentPoints(), template.maximumHealth(),
|
||||
template.learned(), template.loadout(), template.cooldowns(), false, null, null);
|
||||
var repository = new YamlCharacterRepository(data); repository.create(live);
|
||||
var broken = new YamlCharacterRepository(data, (source, target) -> {
|
||||
if (moved) Files.move(source, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
throw new IOException("Unacknowledged death");
|
||||
});
|
||||
try (var storage = new CharacterStorage(broken, Clock.systemUTC())) {
|
||||
assertThrows(CompletionException.class, () -> storage.recordDeath(live.id()).join());
|
||||
var current = repository.load(live.id()).orElseThrow(); assertEquals(moved, current.dead());
|
||||
if (moved) {
|
||||
assertTrue(storage.recordDeath(live.id()).join().isEmpty());
|
||||
assertEquals(current, repository.load(live.id()).orElseThrow());
|
||||
} else assertEquals(live, current);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesAnOldOrUnknownDeathBookWithoutChangingTheSavedCharacter() throws Exception {
|
||||
var saved = YamlCharacterRepositoryTest.sample(UUID.randomUUID());
|
||||
|
||||
@@ -0,0 +1,577 @@
|
||||
package games.dmg.fantasystick.persistence;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class EquipmentSessionStoreTest {
|
||||
@TempDir Path data;
|
||||
// Synthetic clock, not a document/event timestamp.
|
||||
private static final Instant NOW = Instant.parse("2000-01-01T00:00:00.123456789Z");
|
||||
private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC);
|
||||
private final UUID player = UUID.randomUUID();
|
||||
private final UUID session = UUID.randomUUID();
|
||||
private final UUID character = UUID.randomUUID();
|
||||
|
||||
private static <T> T await(CompletionStage<T> stage) throws Exception {
|
||||
return stage.toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private Path record() { return data.resolve("sessions").resolve(player + ".yml"); }
|
||||
|
||||
private static Throwable failure(CompletionStage<?> stage) {
|
||||
return assertThrows(ExecutionException.class,
|
||||
() -> stage.toCompletableFuture().get(5, TimeUnit.SECONDS)).getCause();
|
||||
}
|
||||
|
||||
private static void replace(Path source, Path target) throws IOException {
|
||||
Files.move(source, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
|
||||
private static void waitFor(CountDownLatch latch) throws IOException {
|
||||
try {
|
||||
if (!latch.await(5, TimeUnit.SECONDS)) throw new IOException("Test gate timed out");
|
||||
} catch (InterruptedException exception) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("Test gate interrupted");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void completeExitAtomicallyClearsMatchingReceiptAndDrainsAcrossShutdown() throws Exception {
|
||||
var store = new EquipmentSessionStore(data, CLOCK);
|
||||
await(store.prepare(player, session, character));
|
||||
var completed = store.completeExit(player, session, Duration.ofSeconds(900));
|
||||
store.close();
|
||||
var saved = await(completed);
|
||||
assertNull(saved.pending(), "Accepted exit must include cleanup, not queue it after shutdown");
|
||||
assertEquals(BigInteger.ONE, saved.revision(), "One atomic write");
|
||||
assertEquals(NOW.plusSeconds(900), saved.lastExit().deadline());
|
||||
try (var reopened = new EquipmentSessionStore(data, Clock.offset(CLOCK, Duration.ofHours(1)))) {
|
||||
assertEquals(saved, await(reopened.completeExit(player, session, Duration.ofDays(1))));
|
||||
UUID next = UUID.randomUUID();
|
||||
var pending = await(reopened.prepare(player, next, character));
|
||||
assertEquals(pending, await(reopened.completeExit(player, session, Duration.ZERO)));
|
||||
var exited = await(reopened.recordExit(player, next, Duration.ofSeconds(30)));
|
||||
var restored = await(reopened.completeExit(player, next, Duration.ofDays(2)));
|
||||
assertNull(restored.pending());
|
||||
assertEquals(exited.lastExit(), restored.lastExit());
|
||||
assertInstanceOf(IOException.class, failure(reopened.completeExit(player, UUID.randomUUID(), Duration.ZERO)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void atomicExitFailureKeepsReceiptAndExistingDeadlineUntilSingleWriteRetry() throws Exception {
|
||||
EquipmentSessionStore.State exited;
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
await(store.prepare(player, session, character));
|
||||
exited = await(store.recordExit(player, session, Duration.ofSeconds(30)));
|
||||
}
|
||||
byte[] before = Files.readAllBytes(record());
|
||||
try (var failing = new EquipmentSessionStore(data, CLOCK, (source, target) -> {
|
||||
throw new IOException("Injected exit replacement failure");
|
||||
})) {
|
||||
assertInstanceOf(IOException.class, failure(failing.completeExit(player, session, Duration.ofDays(1))));
|
||||
assertArrayEquals(before, Files.readAllBytes(record()));
|
||||
assertEquals(exited, await(failing.find(player)).orElseThrow());
|
||||
}
|
||||
try (var reopened = new EquipmentSessionStore(data, Clock.offset(CLOCK, Duration.ofDays(1)))) {
|
||||
for (Duration invalid : List.of(Duration.ofNanos(-1), Duration.ofSeconds(Long.MAX_VALUE))) {
|
||||
failure(reopened.completeExit(player, session, invalid));
|
||||
assertArrayEquals(before, Files.readAllBytes(record()));
|
||||
}
|
||||
var result = await(reopened.completeExit(player, session, Duration.ZERO));
|
||||
assertNull(result.pending());
|
||||
assertEquals(exited.lastExit(), result.lastExit());
|
||||
assertEquals(exited.revision().add(BigInteger.ONE), result.revision());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void acknowledgmentsFollowWorkerCommitAndObserversCannotCancelOwnedWork() throws Exception {
|
||||
var entered = new CountDownLatch(1);
|
||||
var release = new CountDownLatch(1);
|
||||
Thread caller = Thread.currentThread();
|
||||
var diskThread = new AtomicReference<Thread>();
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK, (source, target) -> {
|
||||
diskThread.set(Thread.currentThread());
|
||||
entered.countDown();
|
||||
waitFor(release);
|
||||
replace(source, target);
|
||||
})) {
|
||||
var stage = store.prepare(player, session, character);
|
||||
try {
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||
assertNotSame(caller, diskThread.get());
|
||||
assertFalse(Files.exists(record()));
|
||||
assertFalse(stage.toCompletableFuture().isDone());
|
||||
assertTrue(stage.toCompletableFuture().cancel(true));
|
||||
assertTrue(stage.toCompletableFuture().complete(null));
|
||||
assertFalse(stage.toCompletableFuture().isDone(), "Observations cannot complete the owned acknowledgment");
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
var saved = await(stage);
|
||||
assertNotNull(saved.pending());
|
||||
assertEquals(saved, await(store.find(player)).orElseThrow());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void closeIsNonblockingDrainsAcceptedWorkAndExitTimeIsCapturedBeforeTheQueueRuns() throws Exception {
|
||||
var entered = new CountDownLatch(1);
|
||||
var release = new CountDownLatch(1);
|
||||
var time = new AtomicReference<>(NOW);
|
||||
Clock clock = new Clock() {
|
||||
@Override public ZoneId getZone() { return ZoneOffset.UTC; }
|
||||
@Override public Clock withZone(ZoneId zone) { return this; }
|
||||
@Override public Instant instant() { return time.get(); }
|
||||
};
|
||||
var store = new EquipmentSessionStore(data, clock, (source, target) -> {
|
||||
entered.countDown();
|
||||
waitFor(release);
|
||||
replace(source, target);
|
||||
});
|
||||
var prepared = store.prepare(player, session, character);
|
||||
CompletionStage<EquipmentSessionStore.State> exited = null;
|
||||
CompletionStage<EquipmentSessionStore.State> cleared = null;
|
||||
try {
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||
time.set(NOW.plusSeconds(2));
|
||||
exited = store.recordExit(player, session, Duration.ofSeconds(30));
|
||||
cleared = store.clearReceipt(player, session);
|
||||
time.set(NOW.plusSeconds(600));
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(1), store::close);
|
||||
assertInstanceOf(RejectedExecutionException.class, failure(store.find(player)));
|
||||
assertInstanceOf(RejectedExecutionException.class, failure(store.prepare(player, UUID.randomUUID(), character)));
|
||||
assertInstanceOf(RejectedExecutionException.class, failure(store.recordExit(player, session, Duration.ZERO)));
|
||||
assertInstanceOf(RejectedExecutionException.class, failure(store.clearReceipt(player, session)));
|
||||
} finally {
|
||||
release.countDown();
|
||||
store.close();
|
||||
await(prepared);
|
||||
if (exited != null) await(exited);
|
||||
if (cleared != null) await(cleared);
|
||||
}
|
||||
var exit = await(exited);
|
||||
assertEquals(NOW.plusSeconds(2), exit.lastExit().exitedAt());
|
||||
assertEquals(NOW.plusSeconds(32), exit.lastExit().deadline());
|
||||
try (var reopened = new EquipmentSessionStore(data, CLOCK)) {
|
||||
assertEquals(await(cleared), await(reopened.find(player)).orElseThrow());
|
||||
assertNull(await(cleared).pending());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedForcedTemporaryReplacementPreservesOriginalAndRetryIsPossible() throws Exception {
|
||||
EquipmentSessionStore.State original;
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
original = await(store.prepare(player, session, character));
|
||||
}
|
||||
byte[] before = Files.readAllBytes(record());
|
||||
try (var failing = new EquipmentSessionStore(data, CLOCK, (source, target) -> {
|
||||
assertTrue(Files.isRegularFile(source));
|
||||
assertTrue(Files.readString(source).contains("schema-version: 1"));
|
||||
assertArrayEquals(before, Files.readAllBytes(target));
|
||||
throw new IOException("PRIVATE injected filesystem detail");
|
||||
})) {
|
||||
Throwable error = failure(failing.recordExit(player, session, Duration.ofSeconds(900)));
|
||||
assertInstanceOf(IOException.class, error);
|
||||
assertFalse(error.toString().contains("PRIVATE"));
|
||||
assertNull(error.getCause());
|
||||
assertArrayEquals(before, Files.readAllBytes(record()));
|
||||
assertEquals(original, await(failing.find(player)).orElseThrow());
|
||||
assertInstanceOf(IOException.class, failure(failing.clearReceipt(player, session)));
|
||||
assertArrayEquals(before, Files.readAllBytes(record()));
|
||||
}
|
||||
try (var paths = Files.list(data.resolve("sessions"))) {
|
||||
assertFalse(paths.anyMatch(path -> path.toString().endsWith(".tmp")));
|
||||
}
|
||||
try (var retry = new EquipmentSessionStore(data, CLOCK)) {
|
||||
assertEquals(BigInteger.ONE, await(retry.recordExit(player, session, Duration.ZERO)).revision());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedPreparationDoesNotCreateAReceiptAndConstructorDoesNotTouchInvalidDirectory() throws Exception {
|
||||
try (var failing = new EquipmentSessionStore(data, CLOCK, (source, target) -> {
|
||||
throw new IOException("Refused atomic replacement");
|
||||
})) {
|
||||
assertInstanceOf(IOException.class, failure(failing.prepare(player, session, character)));
|
||||
assertFalse(Files.exists(record()));
|
||||
assertTrue(await(failing.find(player)).isEmpty());
|
||||
}
|
||||
Path blocked = data.resolve("not-a-directory");
|
||||
Files.writeString(blocked, "untouched");
|
||||
try (var store = new EquipmentSessionStore(blocked, CLOCK)) {
|
||||
assertInstanceOf(IOException.class, failure(store.prepare(player, session, character)));
|
||||
assertEquals("untouched", Files.readString(blocked));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void oneFailFastLockCoordinatesInstancesWithoutLeakingPerSessionLockFiles() throws Exception {
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
var original = await(store.prepare(player, session, character));
|
||||
byte[] before = Files.readAllBytes(record());
|
||||
try (var channel = FileChannel.open(data.resolve("sessions/.sessions.lock"), StandardOpenOption.WRITE);
|
||||
var lock = channel.lock();
|
||||
var other = new EquipmentSessionStore(data, CLOCK)) {
|
||||
assertTrue(lock.isValid());
|
||||
assertInstanceOf(IOException.class, failure(other.prepare(player, UUID.randomUUID(), character)));
|
||||
assertInstanceOf(IOException.class, failure(other.recordExit(player, session, Duration.ZERO)));
|
||||
assertInstanceOf(IOException.class, failure(other.clearReceipt(player, session)));
|
||||
assertInstanceOf(IOException.class, failure(other.find(player)));
|
||||
assertArrayEquals(before, Files.readAllBytes(record()));
|
||||
}
|
||||
assertEquals(original, await(store.find(player)).orElseThrow());
|
||||
for (int index = 0; index < 48; index++) {
|
||||
UUID owner = UUID.randomUUID();
|
||||
UUID attempt = UUID.randomUUID();
|
||||
await(store.prepare(owner, attempt, character));
|
||||
await(store.clearReceipt(owner, attempt));
|
||||
}
|
||||
try (var paths = Files.list(data.resolve("sessions"))) {
|
||||
var files = paths.toList();
|
||||
assertEquals(1L, files.stream().filter(path -> path.toString().endsWith(".lock")).count());
|
||||
assertFalse(files.stream().anyMatch(path -> path.toString().endsWith(".tmp")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void competingInstancesCannotReplaceAnAcknowledgedPendingSession() throws Exception {
|
||||
var entered = new CountDownLatch(1);
|
||||
var release = new CountDownLatch(1);
|
||||
try (var first = new EquipmentSessionStore(data, CLOCK, (source, target) -> {
|
||||
entered.countDown();
|
||||
waitFor(release);
|
||||
replace(source, target);
|
||||
}); var second = new EquipmentSessionStore(data, CLOCK)) {
|
||||
var preparation = first.prepare(player, session, character);
|
||||
UUID competing = UUID.randomUUID();
|
||||
try {
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||
assertInstanceOf(IOException.class, failure(second.prepare(player, competing, character)));
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
var saved = await(preparation);
|
||||
assertInstanceOf(IOException.class, failure(second.prepare(player, competing, character)));
|
||||
assertEquals(saved, await(second.prepare(player, session, character)));
|
||||
assertEquals(saved, await(second.find(player)).orElseThrow());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void symlinkedRecordsAndLockFilesAreNeverFollowedOrReplaced() throws Exception {
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
await(store.prepare(player, session, character));
|
||||
Path outside = data.resolve("outside.yml");
|
||||
Files.move(record(), outside);
|
||||
byte[] bytes = Files.readAllBytes(outside);
|
||||
Files.createSymbolicLink(record(), outside);
|
||||
assertInstanceOf(IOException.class, failure(store.find(player)));
|
||||
assertInstanceOf(IOException.class, failure(store.prepare(player, session, character)));
|
||||
assertInstanceOf(IOException.class, failure(store.recordExit(player, session, Duration.ZERO)));
|
||||
assertInstanceOf(IOException.class, failure(store.clearReceipt(player, session)));
|
||||
assertTrue(Files.isSymbolicLink(record()));
|
||||
assertArrayEquals(bytes, Files.readAllBytes(outside));
|
||||
Files.delete(record());
|
||||
Files.move(outside, record());
|
||||
Path lock = data.resolve("sessions/.sessions.lock");
|
||||
Files.delete(lock); // Fixture only; no work is running or holding this lock.
|
||||
Files.writeString(outside, "protected lock target");
|
||||
Files.createSymbolicLink(lock, outside);
|
||||
assertInstanceOf(IOException.class, failure(store.prepare(player, session, character)));
|
||||
assertInstanceOf(IOException.class, failure(store.recordExit(player, session, Duration.ZERO)));
|
||||
assertInstanceOf(IOException.class, failure(store.clearReceipt(player, session)));
|
||||
assertInstanceOf(IOException.class, failure(store.find(player)));
|
||||
assertEquals("protected lock target", Files.readString(outside));
|
||||
assertArrayEquals(bytes, Files.readAllBytes(record()));
|
||||
assertTrue(Files.isSymbolicLink(lock));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void symlinkedSessionDirectoryAndNonregularRecordAreRefused() throws Exception {
|
||||
Path outside = Files.createDirectory(data.resolve("outside"));
|
||||
Files.createSymbolicLink(data.resolve("sessions"), outside);
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
assertInstanceOf(IOException.class, failure(store.prepare(player, session, character)));
|
||||
try (var paths = Files.list(outside)) { assertEquals(0, paths.count()); }
|
||||
Files.delete(data.resolve("sessions"));
|
||||
Files.createDirectories(record());
|
||||
assertInstanceOf(IOException.class, failure(store.find(player)));
|
||||
assertInstanceOf(IOException.class, failure(store.prepare(player, session, character)));
|
||||
assertTrue(Files.isDirectory(record()));
|
||||
}
|
||||
}
|
||||
|
||||
private String validYaml() {
|
||||
return """
|
||||
schema-version: 1
|
||||
player-id: %s
|
||||
revision: '9'
|
||||
pending:
|
||||
session-id: %s
|
||||
character-id: %s
|
||||
prepared-at: '%s'
|
||||
last-exit:
|
||||
session-id: %s
|
||||
character-id: %s
|
||||
exited-at: '%s'
|
||||
deadline: '%s'
|
||||
""".formatted(player, session, character, NOW, session, character, NOW.plusSeconds(1), NOW.plusSeconds(901));
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedUnsafeAndInconsistentYamlIsPreservedWithSanitizedFailures() throws Exception {
|
||||
Files.createDirectories(data.resolve("sessions"));
|
||||
String valid = validYaml();
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
Files.writeString(record(), valid);
|
||||
assertEquals(BigInteger.valueOf(9), await(store.find(player)).orElseThrow().revision());
|
||||
for (String invalid : List.of(
|
||||
valid.replace("schema-version: 1", "schema-version: 2"),
|
||||
valid + "schema-version: 1\n",
|
||||
valid.replace("revision: '9'", "revision: '-1'"),
|
||||
valid.replace("revision: '9'", "revision: '01'"),
|
||||
valid.replace("revision: '9'", "revision: 1.5"),
|
||||
valid.replace(player.toString(), UUID.randomUUID().toString()),
|
||||
valid.replace(session.toString(), "1-1-1-1-1"),
|
||||
valid.replace(" prepared-at: '" + NOW + "'\n", ""),
|
||||
valid.replace(" character-id: " + character + "\n", ""),
|
||||
valid.replace("last-exit:\n session-id: " + session + "\n character-id: " + character,
|
||||
"last-exit:\n session-id: " + session + "\n character-id: " + UUID.randomUUID()),
|
||||
valid.replace(NOW.plusSeconds(901).toString(), NOW.toString()),
|
||||
valid.replace(NOW.toString(), "2000-02-30T00:00:00Z"),
|
||||
valid.replace(NOW.toString(), "2000-01-01T00:00:00+00:00"),
|
||||
valid.replace(NOW.toString(), "2000-01-01T24:00:00Z"),
|
||||
valid.replace(NOW.toString(), "2000-01-01T00:00:60Z"),
|
||||
valid + "unknown-recovery-authority: true\n",
|
||||
"pending: &receipt [*receipt]\n",
|
||||
"!!java.net.URL ['https://PRIVATE.invalid/']",
|
||||
"PRIVATE: [unterminated", "", valid + "---\n" + valid)) {
|
||||
Files.writeString(record(), invalid);
|
||||
for (CompletionStage<?> attempt : List.of(store.find(player), store.prepare(player, session, character),
|
||||
store.recordExit(player, session, Duration.ZERO), store.clearReceipt(player, session))) {
|
||||
Throwable error = failure(attempt);
|
||||
assertInstanceOf(IOException.class, error);
|
||||
assertFalse(error.toString().contains("PRIVATE"));
|
||||
assertNull(error.getCause(), "No parser snippets through nested exceptions");
|
||||
}
|
||||
assertEquals(invalid, Files.readString(record()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void boundsUtf8ReadsAndKeepsArbitraryPrecisionRevisionsExact() throws Exception {
|
||||
Files.createDirectories(data.resolve("sessions"));
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
for (byte[] invalid : List.of(new byte[] {(byte) 0xc3, 0x28}, "x".repeat(16_385).getBytes(java.nio.charset.StandardCharsets.UTF_8))) {
|
||||
Files.write(record(), invalid);
|
||||
assertInstanceOf(IOException.class, failure(store.find(player)));
|
||||
assertInstanceOf(IOException.class, failure(store.prepare(player, session, character)));
|
||||
assertArrayEquals(invalid, Files.readAllBytes(record()));
|
||||
}
|
||||
BigInteger revision = BigInteger.TEN.pow(100);
|
||||
Files.writeString(record(), validYaml().replace("revision: '9'", "revision: '" + revision + "'"));
|
||||
assertEquals(revision, await(store.find(player)).orElseThrow().revision());
|
||||
assertEquals(revision.add(BigInteger.ONE), await(store.clearReceipt(player, session)).revision());
|
||||
}
|
||||
try (var reopened = new EquipmentSessionStore(data, CLOCK)) {
|
||||
assertEquals(BigInteger.TEN.pow(100).add(BigInteger.ONE), await(reopened.find(player)).orElseThrow().revision());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void boundedWritesCannotReplaceALoadableRecordWithAnOversizedOne() throws Exception {
|
||||
Files.createDirectories(data.resolve("sessions"));
|
||||
String original = "schema-version: 1\nplayer-id: " + player + "\nrevision: '" + "9".repeat(16_200) + "'\n";
|
||||
Files.writeString(record(), original);
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
assertTrue(await(store.find(player)).isPresent(), "Input fits the bounded format");
|
||||
assertInstanceOf(IOException.class, failure(store.prepare(player, session, character)));
|
||||
assertEquals(original, Files.readString(record()));
|
||||
assertNull(await(store.find(player)).orElseThrow().pending());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnacknowledgedPostMoveFailureRetainsItsAmbiguousReceiptAndNeverReplaysOrDeletesIt() throws Exception {
|
||||
try (var uncertain = new EquipmentSessionStore(data, CLOCK, (source, target) -> {
|
||||
replace(source, target);
|
||||
throw new IOException("Failure after replacement; result uncertain to caller");
|
||||
})) {
|
||||
assertInstanceOf(IOException.class, failure(uncertain.prepare(player, session, character)));
|
||||
}
|
||||
byte[] before = Files.readAllBytes(record());
|
||||
try (var reopened = new EquipmentSessionStore(data, Clock.offset(CLOCK, Duration.ofDays(1)))) {
|
||||
var retained = await(reopened.find(player)).orElseThrow();
|
||||
assertEquals(new EquipmentSessionStore.Receipt(session, character, NOW), retained.pending());
|
||||
assertEquals(BigInteger.ZERO, retained.revision());
|
||||
assertInstanceOf(IOException.class, failure(reopened.prepare(player, UUID.randomUUID(), character)));
|
||||
assertEquals(retained, await(reopened.prepare(player, session, character)));
|
||||
assertArrayEquals(before, Files.readAllBytes(record()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void abortedPreparationCanBeClearedWithoutInventingAnExitAndDoesNotTouchCharacterFiles() throws Exception {
|
||||
Path characterFile = data.resolve("characters").resolve(character + ".yml");
|
||||
Files.createDirectories(characterFile.getParent());
|
||||
Files.writeString(characterFile, "existing character data is not this store's schema");
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
await(store.prepare(player, session, character));
|
||||
var cleared = await(store.clearReceipt(player, session)); // Test caller supplies never-packed proof.
|
||||
assertNull(cleared.pending());
|
||||
assertNull(cleared.lastExit());
|
||||
assertEquals(BigInteger.ONE, cleared.revision());
|
||||
assertEquals(cleared, await(store.clearReceipt(player, session)));
|
||||
assertInstanceOf(IOException.class, failure(store.recordExit(player, session, Duration.ZERO)));
|
||||
assertNotNull(await(store.prepare(player, UUID.randomUUID(), character)).pending());
|
||||
}
|
||||
assertEquals("existing character data is not this store's schema", Files.readString(characterFile));
|
||||
}
|
||||
|
||||
@Test
|
||||
void publicRecordsValidateMembersAndPairedSessionIdentity() {
|
||||
assertThrows(NullPointerException.class, () -> new EquipmentSessionStore.Receipt(session, null, NOW));
|
||||
assertThrows(NullPointerException.class, () -> new EquipmentSessionStore.Exit(session, character, null, NOW));
|
||||
assertThrows(IllegalArgumentException.class, () -> new EquipmentSessionStore.Exit(session, character, NOW, NOW.minusNanos(1)));
|
||||
assertThrows(IllegalArgumentException.class, () -> new EquipmentSessionStore.Receipt(session, character, Instant.MAX));
|
||||
assertThrows(IllegalArgumentException.class, () -> new EquipmentSessionStore.State(player, BigInteger.valueOf(-1), null, null));
|
||||
var receipt = new EquipmentSessionStore.Receipt(session, character, NOW);
|
||||
var wrongCharacter = new EquipmentSessionStore.Exit(session, UUID.randomUUID(), NOW, NOW);
|
||||
assertThrows(IllegalArgumentException.class, () -> new EquipmentSessionStore.State(player, BigInteger.ZERO, receipt, wrongCharacter));
|
||||
}
|
||||
|
||||
@Test
|
||||
void switchChecksUseSavedDeadlineNotNewConfigurationAndZeroOnlyBypassesTheDelay() throws Exception {
|
||||
EquipmentSessionStore.State exited;
|
||||
UUID other = UUID.randomUUID();
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
var prepared = await(store.prepare(player, session, character));
|
||||
assertTrue(prepared.canEnter(other, Duration.ofSeconds(900), NOW));
|
||||
exited = await(store.recordExit(player, session, Duration.ofSeconds(900)));
|
||||
assertTrue(exited.canEnter(character, Duration.ofSeconds(900), NOW));
|
||||
assertFalse(exited.canEnter(other, Duration.ofSeconds(1), NOW.plusSeconds(899)));
|
||||
assertFalse(exited.canEnter(other, Duration.ofDays(7), NOW.plusSeconds(899)));
|
||||
assertTrue(exited.canEnter(other, Duration.ofDays(7), NOW.plusSeconds(900)));
|
||||
assertTrue(exited.canEnter(other, Duration.ZERO, NOW));
|
||||
assertFalse(exited.canEnter(other, Duration.ofSeconds(900), NOW), "Zero bypass does not erase saved deadline");
|
||||
assertThrows(IllegalArgumentException.class, () -> exited.canEnter(other, Duration.ofSeconds(-1), NOW));
|
||||
assertEquals(exited, await(store.find(player)).orElseThrow());
|
||||
}
|
||||
try (var reopened = new EquipmentSessionStore(data, Clock.offset(CLOCK, Duration.ofDays(1)))) {
|
||||
assertTrue(await(reopened.find(player)).orElseThrow().canEnter(other, Duration.ofDays(7), NOW.plusSeconds(86400)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidDelaysFailUnchangedEvenForDuplicateExitsAndMissingSessionsAreNotInvented() throws Exception {
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
assertInstanceOf(IOException.class, failure(store.recordExit(player, session, Duration.ZERO)));
|
||||
assertInstanceOf(IOException.class, failure(store.clearReceipt(player, session)));
|
||||
assertTrue(await(store.find(player)).isEmpty());
|
||||
var prepared = await(store.prepare(player, session, character));
|
||||
for (Duration invalid : java.util.List.of(Duration.ofNanos(-1), Duration.ofSeconds(Long.MAX_VALUE),
|
||||
Duration.ofDays(4_000_000))) {
|
||||
failure(store.recordExit(player, session, invalid));
|
||||
assertEquals(prepared, await(store.find(player)).orElseThrow());
|
||||
}
|
||||
var exited = await(store.recordExit(player, session, Duration.ZERO));
|
||||
byte[] before = Files.readAllBytes(record());
|
||||
for (Duration invalid : java.util.List.of(Duration.ofNanos(-1), Duration.ofSeconds(Long.MAX_VALUE))) {
|
||||
failure(store.recordExit(player, session, invalid));
|
||||
assertArrayEquals(before, Files.readAllBytes(record()));
|
||||
assertEquals(exited, await(store.find(player)).orElseThrow());
|
||||
}
|
||||
assertEquals(NOW, exited.lastExit().deadline());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void exitsRetainReceiptsUntilProvenRestorationAndDuplicatesNeverExtendDeadlines() throws Exception {
|
||||
EquipmentSessionStore.State cleared;
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
var prepared = await(store.prepare(player, session, character));
|
||||
assertEquals(prepared, await(store.prepare(player, session, character)));
|
||||
assertInstanceOf(IOException.class, failure(store.prepare(player, session, UUID.randomUUID())));
|
||||
assertInstanceOf(IOException.class, failure(store.prepare(player, UUID.randomUUID(), character)));
|
||||
assertInstanceOf(IOException.class, failure(store.recordExit(player, UUID.randomUUID(), Duration.ZERO)));
|
||||
assertInstanceOf(IOException.class, failure(store.clearReceipt(player, UUID.randomUUID())));
|
||||
assertEquals(prepared, await(store.find(player)).orElseThrow());
|
||||
|
||||
var exited = await(store.recordExit(player, session, Duration.ofMinutes(15)));
|
||||
assertEquals(BigInteger.ONE, exited.revision());
|
||||
assertEquals(prepared.pending(), exited.pending(), "Exit is not proof of restoration");
|
||||
assertEquals(new EquipmentSessionStore.Exit(session, character, NOW, NOW.plusSeconds(900)), exited.lastExit());
|
||||
assertEquals(exited, await(store.recordExit(player, session, Duration.ofDays(1))));
|
||||
assertEquals(exited, await(store.prepare(player, session, character)));
|
||||
cleared = await(store.clearReceipt(player, session));
|
||||
assertEquals(BigInteger.TWO, cleared.revision());
|
||||
assertNull(cleared.pending());
|
||||
assertEquals(exited.lastExit(), cleared.lastExit());
|
||||
assertEquals(cleared, await(store.clearReceipt(player, session)));
|
||||
}
|
||||
try (var reopened = new EquipmentSessionStore(data, Clock.offset(CLOCK, Duration.ofHours(1)))) {
|
||||
assertEquals(cleared, await(reopened.recordExit(player, session, Duration.ofDays(7))));
|
||||
assertInstanceOf(IOException.class, failure(reopened.prepare(player, session, character)));
|
||||
UUID nextSession = UUID.randomUUID();
|
||||
var next = await(reopened.prepare(player, nextSession, character));
|
||||
assertEquals(BigInteger.valueOf(3), next.revision());
|
||||
assertEquals(cleared.lastExit(), next.lastExit());
|
||||
assertInstanceOf(IOException.class, failure(reopened.clearReceipt(player, session)));
|
||||
assertEquals(next, await(reopened.recordExit(player, session, Duration.ZERO)), "Old retry must not mutate new pending session");
|
||||
var nextExit = await(reopened.recordExit(player, nextSession, Duration.ofSeconds(30)));
|
||||
assertEquals(BigInteger.valueOf(4), nextExit.revision());
|
||||
assertEquals(NOW.plusSeconds(3630), nextExit.lastExit().deadline());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void preparationAcknowledgesRealVersionedYamlAndSurvivesReopen() throws Exception {
|
||||
EquipmentSessionStore.State saved;
|
||||
try (var store = new EquipmentSessionStore(data, CLOCK)) {
|
||||
assertFalse(Files.exists(data.resolve("sessions")), "Constructor must defer disk IO");
|
||||
assertTrue(await(store.find(player)).isEmpty());
|
||||
saved = await(store.prepare(player, session, character));
|
||||
assertEquals(player, saved.playerId());
|
||||
assertEquals(BigInteger.ZERO, saved.revision());
|
||||
assertEquals(new EquipmentSessionStore.Receipt(session, character, NOW), saved.pending());
|
||||
assertNull(saved.lastExit());
|
||||
assertTrue(Files.isRegularFile(record()), "Acknowledgment follows persistence");
|
||||
String yaml = Files.readString(record());
|
||||
assertTrue(yaml.contains("schema-version: 1"));
|
||||
assertFalse(yaml.contains("!!"));
|
||||
}
|
||||
try (var reopened = new EquipmentSessionStore(data, CLOCK)) {
|
||||
assertEquals(saved, await(reopened.find(player)).orElseThrow());
|
||||
}
|
||||
assertFalse(Files.exists(data.resolve("characters")), "Existing character storage is untouched");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user