From a0fcb743658a5ecc362d8731f3c1b0bce52eda36 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 11:22:29 +0100 Subject: [PATCH] Add RunningWorld.saved, state a module keeps with the world across restarts A world's state store is memory only, so Iris offered spawner cooldowns through a facade to persist them. SavedKey names a value with its codec and initial value; the host reads it on first ask and writes it when it saves and stops the world. --- CONTRACTS.md | 5 +- DESIGN.md | 21 ++--- README.md | 20 ++++- .../java/com/volmit/world/RunningWorld.java | 17 ++++ .../main/java/com/volmit/world/SavedKey.java | 35 ++++++++ .../java/com/volmit/world/SavedKeyTest.java | 79 +++++++++++++++++++ 6 files changed, 166 insertions(+), 11 deletions(-) create mode 100644 api/src/main/java/com/volmit/world/SavedKey.java create mode 100644 api/src/test/java/com/volmit/world/SavedKeyTest.java diff --git a/CONTRACTS.md b/CONTRACTS.md index 37020ce8a..9a44cad05 100644 --- a/CONTRACTS.md +++ b/CONTRACTS.md @@ -25,6 +25,7 @@ types that carry them and lists what the Iris adapter still owes. | Reference execution | host `PlacementRunner` (returns the API `PlacementOutcome`), `ChunkRunner`, `MantleRunner`, each timed through host `StageTimings` | | Work across chunks and mantle writes | `Stage.mantle`, `MantleStage`, `MantleStageContext`, `MantleGenerationContext`; chunk stages write registered layers in their own chunk only and read the neighbors | | Annotated settings | `IrisFeature`, `@Feature` (id, short JSON `key`, optional `root`), config annotations, host `OptionsMetadata`, `LinkedBiomes` (`treeBiomes`, `usedBiomes`: pack biomes the settings bring into the layout) | +| Module state that survives a restart | `RunningWorld.saved(SavedKey)`, `SavedKey` (id, type, `Codec`, `initial`), `com.volmit.data.Codec` (also the codec of mantle layers) | | Host facades for the host's own modules | `PackWorld.extension(type)`, `InvocationContext.extension(type)`, `PackSettings.extension(type)` (each an `Optional`, empty by default) | | Area a stage writes | `reach(blocks)`, `reach(PackReach)`, `writesMantle(...)` on stage definitions, `PackSettings` (with `resources()`, for a reach that depends on the size of the pack's objects), host `StageReach`, `ResolvedStage.reachBlocks`, `PipelineReach` | | Settings described for studio | `@Desc`, `@Required`, `@MinNumber`, `@MaxNumber`, `@MinItems`, `@Snippet`, `@Ref`/`Reference`, `@ResourceRef`, `FeatureRegistry.registerSettings`, host `LoadedPack.schema()` (`PackSchema`, `FeatureSchema`, `ObjectType`, `SchemaOption`, `ValueKind` with `HostKind`), `ModuleHost.describingHostTypesIn` | @@ -99,7 +100,9 @@ and what it mounts, is the adapter's. `ModuleJarCheck --platform=: WAVES = new SavedKey<>("example:waves/last", LastWaves.class, new LastWavesCodec(), LastWaves::new); + +LastWaves waves = world.running().orElseThrow().saved(WAVES); // the world's one instance, read on first ask +waves.record(now); // changed in place; the module owns its thread safety +``` + +- The host reads the value when it is first asked for (`initial` when none is stored), writes it when it saves the world + and when the world stops, and hands a world started over the same storage, such as after a hotload, what the old + one wrote. +- `Codec.write` may run while module threads change the value, so it must read it safely. A stored payload the codec + rejects is logged and replaced with `initial`. +- The id names the stored file, so its path has no empty, `.` or `..` segment. + A module that wants to act when the host loads a pack or starts or stops a world registers a `ModuleLifecycle`. Every hook does nothing by default, and a module class may implement it and register itself: @@ -1099,7 +1116,8 @@ Optional clock = pack.catalog().service(Clock.class); // a Pro a block with a block entity goes through `access.set(PlacedBlock)`. `BlockState.withProperty` copies the properties once. - Invocation views (`ctx.mantle()`, its layers and blocks, a placement's `access().mantle()`) are made once per invocation, so asking again returns the same view. -- The `mantle` package keeps namespaced typed layers, codecs, lifetimes and buffered edits. +- The `mantle` package keeps namespaced typed layers, lifetimes and buffered edits; `com.volmit.data.Codec` stores + their values, and the values of `RunningWorld.saved`. - `IrisFeature`, `@Feature`, the config annotations (`@Desc`, `@Required`, `@MinNumber`, `@MaxNumber`, `@MinItems`, `@Snippet`, `@Ref`) describe settings; the host reads them with `OptionsMetadata` (`com.volmit.host`). diff --git a/api/src/main/java/com/volmit/world/RunningWorld.java b/api/src/main/java/com/volmit/world/RunningWorld.java index 7f7f1685d..0735d855f 100644 --- a/api/src/main/java/com/volmit/world/RunningWorld.java +++ b/api/src/main/java/com/volmit/world/RunningWorld.java @@ -42,6 +42,23 @@ public interface RunningWorld { */ Optional placementAt(int worldX, int y, int worldZ); + /** + * The value the module keeps with this world across restarts under {@code key}: the host's one instance of it for + * the world, read from the world's storage the first time anyone asks (or {@code key.initial()} when none was + * stored), and written back when the host saves the world and when it stops. Keep what a spawner last did or a + * counter that must outlive the server here, not what can be rebuilt from the pack; per-world caches belong in + * {@link PackWorld#state}. + * + *

The module changes the value in place and owns its thread safety. The host writes it while module threads may + * still change it, so {@link com.volmit.data.Codec#write} must read the value safely. A stored payload the codec + * rejects is logged and replaced by {@code key.initial()}; the next save overwrites it. A pack reload or hotload + * stops the world and starts another over the same storage, so the new world reads what the old one wrote when it + * stopped. + * + * @throws IllegalArgumentException if another key with the same id but another type was used for this world + */ + T saved(SavedKey key); + /** The time and weather of the world; empty while the platform has not loaded the world. */ Optional sky(); diff --git a/api/src/main/java/com/volmit/world/SavedKey.java b/api/src/main/java/com/volmit/world/SavedKey.java new file mode 100644 index 000000000..5d680965d --- /dev/null +++ b/api/src/main/java/com/volmit/world/SavedKey.java @@ -0,0 +1,35 @@ +package com.volmit.world; + +import com.volmit.data.Codec; +import java.util.Objects; +import java.util.function.Supplier; + +/** The identity and form of one value a module keeps with a running world across restarts + * ({@link RunningWorld#saved}). The id is namespaced like a mantle key and starts with the owning module's id or its + * namespace; the host names its storage after it, so each {@code /} separated segment of the path must be a name, never + * empty, {@code .} or {@code ..}. + * + * @param id the stable storage identity, such as {@code example:moss/patches} + * @param type the value class + * @param codec how the value is stored; its version is written with the value + * @param initial the value for a world that has none stored, or whose stored one the codec rejects + */ +public record SavedKey(String id, Class type, Codec codec, Supplier initial) { + public SavedKey { + Objects.requireNonNull(id, "id"); + Objects.requireNonNull(type, "type"); + Objects.requireNonNull(codec, "codec"); + Objects.requireNonNull(initial, "initial"); + if (!id.matches("[a-z0-9_.-]+:[a-z0-9_./-]+")) { + throw new IllegalArgumentException("Expected a namespaced saved ID: " + id); + } + if (type.isPrimitive()) { + throw new IllegalArgumentException("Saved values require a reference type"); + } + for (String segment : id.substring(id.indexOf(':') + 1).split("/", -1)) { + if (segment.isEmpty() || segment.equals(".") || segment.equals("..")) { + throw new IllegalArgumentException("A saved ID names files, so its path has no empty, . or .. segment: " + id); + } + } + } +} diff --git a/api/src/test/java/com/volmit/world/SavedKeyTest.java b/api/src/test/java/com/volmit/world/SavedKeyTest.java new file mode 100644 index 000000000..6f17fba2e --- /dev/null +++ b/api/src/test/java/com/volmit/world/SavedKeyTest.java @@ -0,0 +1,79 @@ +package com.volmit.world; + +import com.volmit.data.Codec; +import org.junit.jupiter.api.Test; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class SavedKeyTest { + private static final Codec 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(); + } + }; + + @Test + void acceptsNamespacedIdsWithNestedPaths() { + assertDoesNotThrow(() -> key("example:spawn/cooldowns")); + assertDoesNotThrow(() -> key("example:book.v2")); + } + + @Test + void rejectsIdsThatAreNotNamespaced() { + for (String id : new String[]{"", "book", ":book", "example:", "Example:book", "a:b:c"}) { + assertThrows(IllegalArgumentException.class, () -> key(id)); + } + } + + @Test + void rejectsIdsThatCouldLeaveTheWorldsStorage() { + for (String id : new String[]{"example:../book", "example:a/../b", "example:./book", "example:/book", "example:book/", "example:a//b"}) { + assertThrows(IllegalArgumentException.class, () -> key(id), id); + } + } + + @Test + void rejectsMissingPartsAndPrimitiveTypes() { + assertThrows(NullPointerException.class, () -> new SavedKey<>(null, String.class, TEXT, () -> "")); + assertThrows(NullPointerException.class, () -> new SavedKey<>("a:b", null, TEXT, () -> "")); + assertThrows(NullPointerException.class, () -> new SavedKey<>("a:b", String.class, null, () -> "")); + assertThrows(NullPointerException.class, () -> new SavedKey<>("a:b", String.class, TEXT, null)); + Codec number = new Codec<>() { + @Override + public int version() { + return 1; + } + + @Override + public void write(DataOutput output, Integer value) throws IOException { + output.writeInt(value); + } + + @Override + public Integer read(DataInput input, int storedVersion) throws IOException { + return input.readInt(); + } + }; + assertThrows(IllegalArgumentException.class, () -> new SavedKey<>("a:b", int.class, number, () -> 0)); + } + + private static SavedKey key(String id) { + return new SavedKey<>(id, String.class, TEXT, () -> ""); + } +}