Persist RunningWorld.saved under the world's module-data folder

SavedWorldState reads a value when first asked for and writes it, framed with
the codec version, when the engine saves its data and when the world stops, so a
hotload hands the new world what the old one wrote. A rejected payload is logged
and replaced by the key's initial value. Spawner cooldowns leave IrisEngineData
and the EngineSpawnCooldowns facade; old cooldowns in engine data are not migrated.
This commit is contained in:
piexel committed 2026-11-06 11:39:57 +01:00
1 parent 7c90040924
commit 97410afad9
15 files changed
+656 -206

No files matched your search

@@ -23,7 +23,6 @@ import art.arcane.iris.builtin.loot.ObjectLoot;
import art.arcane.volmlib.util.mantle.runtime.Mantle;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.matter.Matter;
import art.arcane.iris.builtin.spawn.SpawnCooldowns;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.loader.IrisRegistrant;
import art.arcane.iris.engine.UsableBlockPlatform;
@@ -33,7 +32,6 @@ import art.arcane.iris.engine.framework.PlacedObject;
import art.arcane.iris.engine.mantle.EngineMantle;
import art.arcane.iris.engine.object.TestSettings;
import art.arcane.iris.builtin.objects.ObjectPlacement;
import art.arcane.iris.engine.object.runtime.IrisEngineData;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.world.IrisWorld;
import art.arcane.iris.engine.object.world.biome.InferredType;
@@ -59,12 +57,11 @@ import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** What services ask a running Iris world: the engine's layout, settings and platform state, its spawners' cooldowns and the loot of its objects. */
/** What services ask a running Iris world: the engine's layout, settings and platform state and the loot of its objects. */
public class IrisRunningWorldTest {
private static final int X = 10;
private static final int Y = 70;
@@ -188,28 +185,6 @@ public class IrisRunningWorldTest {
assertTrue(running.placementAt(X + 2, Y, Z).isEmpty());
}
@Test
public void spawnCooldownsCountPerWorldAndPerChunkAndForgetWhatRanOut() {
IrisEngineData saved = new IrisEngineData();
when(engine.getEngineData()).thenReturn(saved);
SpawnCooldowns cooldowns = world.extension(SpawnCooldowns.class).orElseThrow();
assertTrue(cooldowns.canSpawn("wolves", 600_000L));
cooldowns.spawned("wolves");
cooldowns.spawnedInChunk(3, 4, "wolves");
cooldowns.spawned("gone");
assertFalse(cooldowns.canSpawn("wolves", 600_000L));
assertFalse(cooldowns.canSpawnInChunk(3, 4, "wolves", 600_000L));
assertTrue(cooldowns.canSpawnInChunk(3, 5, "wolves", 600_000L));
cooldowns.forgetExpired(spawner -> spawner.equals("wolves") ? 600_000L : -1L);
assertFalse("a cooldown still running stays", cooldowns.canSpawn("wolves", 600_000L));
assertFalse(cooldowns.canSpawnInChunk(3, 4, "wolves", 600_000L));
assertTrue("a spawner the pack lacks is forgotten", cooldowns.canSpawn("gone", 600_000L));
}
private <T extends IrisRegistrant> T owner(Class<T> type, String table) {
T owner = mock(type);
LootSettings loot = TestSettings.of(LootSettings.class, "{\"tables\": [\"" + table + "\"]}");
@@ -0,0 +1,248 @@
package art.arcane.iris.core.modules;
import art.arcane.iris.core.lifecycle.VanishedWorldStorage;
import com.volmit.ModuleLog;
import com.volmit.data.Codec;
import com.volmit.world.SavedKey;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/** What modules keep with a running world: read when first asked for, written on save, and never blocking the world when the stored data is bad. */
public class SavedWorldStateTest {
private static final int CODEC_VERSION = 2;
private static final int INITIAL_COUNT = 5;
@Rule
public TemporaryFolder worldFolder = new TemporaryFolder();
private ModuleLog log;
private SavedWorldState state;
@Before
public void startWorld() {
VanishedWorldStorage.reset();
log = mock(ModuleLog.class);
state = new SavedWorldState(worldFolder::getRoot, log);
}
@After
public void forgetVanishedWorlds() {
VanishedWorldStorage.reset();
}
/** The count a module keeps, stored as one int and rejecting every other version. */
private static final class Count {
private final AtomicInteger value;
private Count(int value) {
this.value = new AtomicInteger(value);
}
}
private static final Codec<Count> COUNT_CODEC = new Codec<>() {
@Override
public int version() {
return CODEC_VERSION;
}
@Override
public void write(DataOutput output, Count count) throws IOException {
output.writeInt(count.value.get());
}
@Override
public Count read(DataInput input, int storedVersion) throws IOException {
if (storedVersion != CODEC_VERSION) {
throw new IOException("Unsupported version " + storedVersion);
}
return new Count(input.readInt());
}
};
private static final SavedKey<Count> COUNT = new SavedKey<>("test:counts/waves", Count.class, COUNT_CODEC,
() -> new Count(INITIAL_COUNT));
@Test
public void aWorldWithNothingStoredStartsWithTheInitialValueAndKeepsOneInstance() {
Count first = state.saved(COUNT);
assertEquals(INITIAL_COUNT, first.value.get());
assertSame(first, state.saved(COUNT));
}
@Test
public void whatTheModuleChangedIsReadBackByTheWorldStartedAfterAStop() {
state.saved(COUNT).value.set(42);
state.saveAll();
SavedWorldState restarted = new SavedWorldState(worldFolder::getRoot, log);
assertEquals(42, restarted.saved(COUNT).value.get());
}
@Test
public void aValueIsStoredBelowTheWorldsModuleDataByNamespaceAndPath() throws IOException {
state.saved(COUNT);
state.saveAll();
File stored = new File(worldFolder.getRoot(), "iris/module-data/test/counts/waves.bin");
byte[] codecVersionThenPayload = {0, 0, 0, CODEC_VERSION, 0, 0, 0, INITIAL_COUNT};
assertArrayEquals(codecVersionThenPayload, Files.readAllBytes(stored.toPath()));
}
@Test
public void aPayloadTheCodecRejectsIsLoggedAndReplacedByTheInitialValue() throws IOException {
store(new byte[]{0, 0, 0, 1, 0, 0, 0, 9});
Count loaded = state.saved(COUNT);
assertEquals(INITIAL_COUNT, loaded.value.get());
verify(log).warn(contains("test:counts/waves"));
}
@Test
public void aTruncatedOrEmptyFileIsRejectedLikeAnyOtherBadPayload() throws IOException {
store(new byte[]{0, 0, 0, CODEC_VERSION, 0, 0});
assertEquals(INITIAL_COUNT, state.saved(COUNT).value.get());
SavedKey<Count> other = new SavedKey<>("test:counts/other", Count.class, COUNT_CODEC, () -> new Count(INITIAL_COUNT));
store("other", new byte[0]);
assertEquals(INITIAL_COUNT, state.saved(other).value.get());
}
@Test
public void aRejectedPayloadIsOverwrittenByTheNextSave() throws IOException {
store(new byte[]{1, 2, 3});
state.saved(COUNT).value.set(7);
state.saveAll();
assertEquals(7, new SavedWorldState(worldFolder::getRoot, log).saved(COUNT).value.get());
}
@Test
public void aCodecThatReadsNothingIsRejected() throws IOException {
Codec<Count> nothing = new Codec<>() {
@Override
public int version() {
return 1;
}
@Override
public void write(DataOutput output, Count count) {
}
@Override
public Count read(DataInput input, int storedVersion) {
return null;
}
};
SavedKey<Count> key = new SavedKey<>("test:counts/nothing", Count.class, nothing, () -> new Count(INITIAL_COUNT));
store("nothing", new byte[]{0, 0, 0, 1});
assertEquals(INITIAL_COUNT, state.saved(key).value.get());
verify(log).warn(contains("test:counts/nothing"));
}
@Test
public void theSameIdAskedForAnotherTypeIsRefused() {
state.saved(COUNT);
Codec<String> text = new Codec<>() {
@Override
public int version() {
return 1;
}
@Override
public void write(DataOutput output, String value) throws IOException {
output.writeUTF(value);
}
@Override
public String read(DataInput input, int storedVersion) throws IOException {
return input.readUTF();
}
};
assertThrows(IllegalArgumentException.class,
() -> state.saved(new SavedKey<>("test:counts/waves", String.class, text, () -> "")));
}
@Test
public void savingWritesNothingWhenNoValueWasAskedFor() {
state.saveAll();
assertFalse(new File(worldFolder.getRoot(), "iris").exists());
}
@Test
public void aFailingCodecIsReportedAndDoesNotStopTheOtherValuesFromBeingSaved() {
Codec<Count> failing = new Codec<>() {
@Override
public int version() {
return 1;
}
@Override
public void write(DataOutput output, Count count) throws IOException {
throw new IOException("cannot write");
}
@Override
public Count read(DataInput input, int storedVersion) {
return new Count(0);
}
};
state.saved(new SavedKey<>("test:counts/broken", Count.class, failing, () -> new Count(0)));
state.saved(COUNT).value.set(9);
state.saveAll();
verify(log).error(contains("test:counts/broken"), any(IOException.class));
assertEquals(9, new SavedWorldState(worldFolder::getRoot, log).saved(COUNT).value.get());
assertFalse(new File(worldFolder.getRoot(), "iris/module-data/test/counts/broken.bin").exists());
}
@Test
public void aWorldWhoseFolderIsGoneIsNotRebuiltBySaving() {
File vanishedFolder = new File(worldFolder.getRoot(), "gone");
SavedWorldState inVanishedWorld = new SavedWorldState(() -> vanishedFolder, log);
inVanishedWorld.saved(COUNT);
inVanishedWorld.saveAll();
assertFalse(vanishedFolder.exists());
verify(log, never()).error(any(), any());
}
private void store(byte[] payload) throws IOException {
store("waves", payload);
}
private void store(String name, byte[] payload) throws IOException {
File file = new File(worldFolder.getRoot(), "iris/module-data/test/counts/" + name + ".bin");
Files.createDirectories(file.getParentFile().toPath());
Files.write(file.toPath(), payload);
}
}
@@ -28,7 +28,6 @@ import art.arcane.iris.builtin.spawn.EntityDefinition;
import art.arcane.iris.builtin.spawn.SpawnMarker;
import art.arcane.iris.builtin.spawn.Spawner;
import art.arcane.iris.engine.object.TestSettings;
import art.arcane.iris.engine.object.runtime.IrisEngineData;
import art.arcane.iris.engine.object.world.IrisWorld;
import art.arcane.iris.spi.PlatformWorld;
import com.volmit.entity.EntitySpec;
@@ -42,7 +41,9 @@ import com.volmit.world.RunningWorld;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.util.List;
import java.util.Optional;
@@ -58,6 +59,9 @@ import static org.mockito.Mockito.when;
public class EntitySpawningTest {
private static final BlockPosition MARKER_BLOCK = new BlockPosition(40, 70, -12);
@Rule
public TemporaryFolder worldFolder = new TemporaryFolder();
private Engine engine;
private ModuleResourceFixture fixture;
private PackWorld world;
@@ -82,7 +86,7 @@ public class EntitySpawningTest {
IrisWorld engineWorld = mock(IrisWorld.class);
when(engineWorld.platformWorld()).thenReturn(mock(PlatformWorld.class));
when(engine.getWorld()).thenReturn(engineWorld);
when(engine.getEngineData()).thenReturn(new IrisEngineData());
when(engineWorld.worldFolder()).thenReturn(worldFolder.getRoot());
SeedManager seeds = mock(SeedManager.class);
when(seeds.getEntity()).thenReturn(11L);
when(engine.getSeedManager()).thenReturn(seeds);
@@ -0,0 +1,158 @@
package art.arcane.iris.engine.spawn;
import com.volmit.data.Codec;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
/** When spawners last fired: counted per spawner in the world and in each chunk, forgotten once spent, and kept across saves. */
public class SpawnCooldownBookTest {
private static final long TEN_MINUTES = 600_000L;
private static final long START = 1_000_000L;
private AtomicLong now;
private SpawnCooldownBook book;
@Before
public void openBook() {
now = new AtomicLong(START);
book = new SpawnCooldownBook(now::get);
}
@Test
public void aSpawnerThatNeverFiredMayFire() {
assertTrue(book.canSpawn("wolves", TEN_MINUTES));
assertTrue(book.canSpawnInChunk(3, 4, "wolves", TEN_MINUTES));
}
@Test
public void aSpawnerMayFireAgainOnceItsIntervalHasPassed() {
book.spawned("wolves");
assertFalse(book.canSpawn("wolves", TEN_MINUTES));
now.addAndGet(TEN_MINUTES);
assertFalse("the interval must pass, not just be reached", book.canSpawn("wolves", TEN_MINUTES));
now.addAndGet(1);
assertTrue(book.canSpawn("wolves", TEN_MINUTES));
}
@Test
public void theWorldAndEveryChunkCountSeparatelyPerSpawner() {
book.spawnedInChunk(3, 4, "wolves");
assertFalse(book.canSpawnInChunk(3, 4, "wolves", TEN_MINUTES));
assertTrue(book.canSpawnInChunk(3, 5, "wolves", TEN_MINUTES));
assertTrue(book.canSpawnInChunk(3, 4, "bats", TEN_MINUTES));
assertTrue("a chunk's spawn is not the world's", book.canSpawn("wolves", TEN_MINUTES));
}
@Test
public void forgettingKeepsCooldownsStillRunningAndDropsSpentOnesAndSpawnersThePackLacks() {
book.spawned("wolves");
book.spawnedInChunk(3, 4, "wolves");
book.spawned("gone");
book.spawnedInChunk(3, 4, "gone");
book.spawned("quick");
now.addAndGet(1_000L);
book.forgetExpired(spawner -> switch (spawner) {
case "wolves" -> TEN_MINUTES;
case "quick" -> 500L;
default -> -1L;
});
assertFalse(book.canSpawn("wolves", TEN_MINUTES));
assertFalse(book.canSpawnInChunk(3, 4, "wolves", TEN_MINUTES));
assertTrue(book.canSpawn("gone", TEN_MINUTES));
assertTrue(book.canSpawnInChunk(3, 4, "gone", TEN_MINUTES));
assertTrue(book.canSpawn("quick", 500L));
}
@Test
public void aSavedBookKeepsWhatFiredInTheWorldAndInChunks() throws IOException {
book.spawned("wolves");
book.spawnedInChunk(-3, 4, "wolves");
book.spawnedInChunk(-3, 4, "bats");
SpawnCooldownBook restored = roundTrip(book);
assertFalse(restored.canSpawn("wolves", TEN_MINUTES));
assertFalse(restored.canSpawnInChunk(-3, 4, "wolves", TEN_MINUTES));
assertFalse(restored.canSpawnInChunk(-3, 4, "bats", TEN_MINUTES));
assertTrue(restored.canSpawn("bats", TEN_MINUTES));
assertTrue(restored.canSpawnInChunk(3, 4, "wolves", TEN_MINUTES));
}
@Test
public void aSavedBookCountsTheTimeThatPassedWhileTheWorldWasStopped() throws IOException {
book.spawned("wolves");
SpawnCooldownBook restored = roundTrip(book);
now.addAndGet(TEN_MINUTES + 1);
assertTrue(restored.canSpawn("wolves", TEN_MINUTES));
}
@Test
public void anEmptyBookIsSavedAndRestoredEmpty() throws IOException {
assertTrue(roundTrip(book).canSpawn("wolves", TEN_MINUTES));
}
@Test
public void aBookOfAnotherFormatVersionIsRejected() {
byte[] stored = write(book);
assertThrows(IOException.class, () -> codec().read(new DataInputStream(new ByteArrayInputStream(stored)), codec().version() + 1));
}
@Test
public void aTruncatedBookIsRejected() {
book.spawned("wolves");
byte[] stored = write(book);
byte[] truncated = java.util.Arrays.copyOf(stored, stored.length - 1);
assertThrows(EOFException.class, () -> codec().read(new DataInputStream(new ByteArrayInputStream(truncated)), codec().version()));
}
@Test
public void aNegativeEntryCountIsRejected() {
byte[] negativeCount = {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff};
assertThrows(IOException.class, () -> codec().read(new DataInputStream(new ByteArrayInputStream(negativeCount)), codec().version()));
}
@Test
public void theBookTheWorldKeepsIsSavedWithTheSavedKey() {
assertTrue(SpawnCooldownBook.SAVED.id().startsWith("iris:spawn/"));
assertTrue(SpawnCooldownBook.SAVED.initial().get().canSpawn("wolves", TEN_MINUTES));
}
private Codec<SpawnCooldownBook> codec() {
return SpawnCooldownBook.codec(now::get);
}
private SpawnCooldownBook roundTrip(SpawnCooldownBook source) throws IOException {
return codec().read(new DataInputStream(new ByteArrayInputStream(write(source))), codec().version());
}
private byte[] write(SpawnCooldownBook source) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (DataOutputStream output = new DataOutputStream(bytes)) {
codec().write(output, source);
} catch (IOException impossible) {
throw new IllegalStateException(impossible);
}
return bytes.toByteArray();
}
}
@@ -23,33 +23,38 @@ import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineGeneration;
import art.arcane.iris.engine.object.TestSettings;
import art.arcane.iris.engine.object.runtime.IrisEngineData;
import art.arcane.iris.engine.object.world.IrisWorld;
import art.arcane.iris.spi.PlatformWorld;
import com.volmit.world.BiomeKind;
import com.volmit.world.RunningWorld.Sky;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** Whether a spawner may fire: the biome kind its group wants, the world's time and weather, and its rates in the engine's data. */
/** Whether a spawner may fire: the biome kind its group wants, the world's time and weather, and its rates in the world's saved cooldowns. */
public class SpawnerGateTest {
@Rule
public TemporaryFolder worldFolder = new TemporaryFolder();
private Engine engine;
private SpawnerGate gate;
@Before
public void buildEngine() {
Engine engine = mock(Engine.class);
engine = mock(Engine.class);
IrisWorld engineWorld = mock(IrisWorld.class);
PlatformWorld platformWorld = mock(PlatformWorld.class);
when(platformWorld.getTime()).thenReturn(6000L);
when(engineWorld.platformWorld()).thenReturn(platformWorld);
when(engineWorld.worldFolder()).thenReturn(worldFolder.getRoot());
when(engine.getWorld()).thenReturn(engineWorld);
when(engine.getData()).thenReturn(mock(IrisData.class));
when(engine.getEngineData()).thenReturn(new IrisEngineData());
gate = SpawnerGate.of(new EngineGeneration(engine).world());
}
@@ -98,11 +103,27 @@ public class SpawnerGateTest {
assertTrue(gate.canSpawn("other", limited, 9, 9));
}
@Test
public void aRateHoldsAfterTheWorldWasStoppedAndStartedAgain() {
Spawner limited = spawner("{\"maximumRate\": {\"amount\": 1, \"per\": {\"minutes\": 10}}, \"maximumRatePerChunk\": {\"amount\": 1, \"per\": {\"minutes\": 10}}}");
EngineGeneration firstRun = new EngineGeneration(engine);
SpawnerGate.of(firstRun.world()).spawned("limited", limited, 3, 4);
firstRun.close();
SpawnerGate restarted = SpawnerGate.of(new EngineGeneration(engine).world());
assertFalse(restarted.canSpawn("limited", limited, 3, 4));
assertFalse(restarted.canSpawn("limited", limited, 9, 9));
assertTrue(restarted.canSpawn("other", limited, 3, 4));
}
@Test
public void aWorldWithoutAPlatformWorldLetsNothingFire() {
Engine engine = mock(Engine.class);
IrisWorld engineWorld = mock(IrisWorld.class);
when(engineWorld.worldFolder()).thenReturn(worldFolder.getRoot());
when(engine.getData()).thenReturn(mock(IrisData.class));
when(engine.getWorld()).thenReturn(mock(IrisWorld.class));
when(engine.getWorld()).thenReturn(engineWorld);
assertFalse(SpawnerGate.of(new EngineGeneration(engine).world()).canSpawn("any", spawner("{}"), 0, 0));
}