diff --git a/CONTRACTS.md b/CONTRACTS.md index fd4f2f4dc..7271d1c57 100644 --- a/CONTRACTS.md +++ b/CONTRACTS.md @@ -25,7 +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) | +| Module state that survives a restart | `RunningWorld.saved(SavedKey)`, `FeatureRegistry.registerSaved`, `SavedKey` (`ResourceId` id, type, `StorageCodec`, `initial`), `com.volmit.data.StorageCodec` (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` | diff --git a/DESIGN.md b/DESIGN.md index b167cc734..9af25df67 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1148,8 +1148,12 @@ each world a state store and tells modules when worlds start and stop. chain instead of recursing or deadlocking. A factory that throws keeps nothing. Reads of existing state take no lock. `WorldStates` is the reference store hosts use. - **Saved state.** The store is memory, so what must survive a restart goes through `RunningWorld.saved(SavedKey)` - instead (the running world, because only it has a folder). A `SavedKey` is a namespaced id, the value class, a - `com.volmit.data.Codec` (the one mantle layers use) and an `initial` supplier. The host keeps one instance per key, + instead (the running world, because only it has a folder). A `SavedKey` is a `ResourceId`, the value class, a + `com.volmit.data.StorageCodec` (the one mantle layers use) and an `initial` supplier. A module registers it in its + setup with `FeatureRegistry.registerSaved`, owned like a mantle key (its id is the module's or below it), and `saved` + rejects a key nobody registered, so every stored file has a registered owner. `saved` cannot tell which module asks: + it accepts exactly the registered key, and rejects a key built with a registered id (such as one forged in another + module's namespace). The host keeps one instance per key, reads it on the first ask, and writes it when it saves the world and when the world stops, so the world a hotload starts reads what the stopped one wrote. The module mutates the value in place and owns its thread safety, so the codec's `write` must tolerate concurrent changes. A payload the codec rejects is logged and replaced by `initial`: a diff --git a/README.md b/README.md index e6e11bfe7..bd1cdc98a 100644 --- a/README.md +++ b/README.md @@ -355,10 +355,14 @@ static PlantedChunks planted(PackWorld world) { - A state that is `AutoCloseable` is closed after the world stops, once nothing generates with it. The state store is in memory and ends with the world. What must outlive a restart, such as when a spawner last fired, -a module keeps with `RunningWorld.saved`. Only a running world has a folder to save in, so a tool's world has none: +a module keeps with `RunningWorld.saved`. Only a running world has a folder to save in, so a tool's world has none. +The module registers the key in `setup` like a mantle layer, under its own id: ```java -private static final SavedKey WAVES = new SavedKey<>("example:waves/last", LastWaves.class, new LastWavesCodec(), LastWaves::new); +private static final SavedKey WAVES = new SavedKey<>(ResourceId.parse("example:waves/last"), LastWaves.class, + new LastWavesCodec(), LastWaves::new); + +registry.registerSaved(WAVES); // in setup 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 @@ -367,8 +371,10 @@ waves.record(now); // changed in pl - 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`. +- `StorageCodec.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`. +- `saved` throws `IllegalArgumentException` for a key nobody registered, and for another key with the id of a + registered one. The id is the module's id or starts with it and `/`, as a mantle key's does. - The id names the stored file, so none of its segments is empty, `.` or `..`. A module that wants to act when the host loads a pack or starts or stops a world registers a `ModuleLifecycle`. Every @@ -1117,8 +1123,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, lifetimes and buffered edits; `com.volmit.data.Codec` stores - their values, and the values of `RunningWorld.saved`. +- The `mantle` package keeps namespaced typed layers, lifetimes and buffered edits; `com.volmit.data.StorageCodec` stores + their values, and the values of `RunningWorld.saved` (`com.volmit.data.SavedKey`). - `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/FeatureRegistry.java b/api/src/main/java/com/volmit/FeatureRegistry.java index d56b3724d..5c087fe56 100644 --- a/api/src/main/java/com/volmit/FeatureRegistry.java +++ b/api/src/main/java/com/volmit/FeatureRegistry.java @@ -1,6 +1,7 @@ package com.volmit; -import com.volmit.data.Codec; +import com.volmit.data.SavedKey; +import com.volmit.data.StorageCodec; import com.volmit.mantle.MantleKey; import com.volmit.mantle.MantleLifetime; import com.volmit.resource.ResourceKind; @@ -11,7 +12,7 @@ import java.util.Set; /** Host implementation collects non-stage registrations before loading pack configuration. * Feature IDs must be unique. JSON keys must be unique per {@link com.volmit.config.Level}, including the - * settings types stages name in {@code when(...)}. Feature IDs, mantle keys and resource kind ids a module + * settings types stages name in {@code when(...)}. Feature IDs, mantle keys, saved keys and resource kind ids a module * registers are its module id or start with it and {@code /}, such as {@code iris:snow} or {@code iris:snow/depth}. */ public interface FeatureRegistry { @@ -21,7 +22,13 @@ public interface FeatureRegistry { * preserve unknown persisted layers or fail explicitly, never silently discard them. * GENERATION layers also require codecs. */ - void registerMantle(MantleKey key, MantleLifetime lifetime, Codec codec); + void registerMantle(MantleKey key, MantleLifetime lifetime, StorageCodec codec); + + /** Registers a value the module keeps with each running world across restarts, so + * {@link com.volmit.world.RunningWorld#saved} serves it; that method throws IllegalArgumentException for a key + * nobody registered. Null arguments throw NullPointerException; a duplicate id throws IllegalArgumentException. + */ + void registerSaved(SavedKey key); /** Catalogs a settings type that no stage names in {@code when(...)}, such as one read only * through {@link com.volmit.config.FeatureSettings#at}, so the host decodes it and studio diff --git a/api/src/main/java/com/volmit/world/SavedKey.java b/api/src/main/java/com/volmit/data/SavedKey.java similarity index 61% rename from api/src/main/java/com/volmit/world/SavedKey.java rename to api/src/main/java/com/volmit/data/SavedKey.java index 9d2a36991..61d721081 100644 --- a/api/src/main/java/com/volmit/world/SavedKey.java +++ b/api/src/main/java/com/volmit/data/SavedKey.java @@ -1,32 +1,30 @@ -package com.volmit.world; +package com.volmit.data; -import com.volmit.data.Codec; +import com.volmit.resource.ResourceId; 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 should start with the owning module's id; the host - * names its storage after it, so each segment of the namespace and of the {@code /} separated path must be a name, - * never empty, {@code .} or {@code ..}. + * ({@link com.volmit.world.RunningWorld#saved}). The module registers it in its setup + * ({@link com.volmit.FeatureRegistry#registerSaved}), and the id is the module's id or starts with it and {@code /}, + * as a mantle key's does. The host names its storage after the id, so each segment of the namespace and of the + * {@code /} separated 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 record SavedKey(ResourceId id, Class type, StorageCodec 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.replace(':', '/').split("/", -1)) { + for (String segment : id.toString().replace(':', '/').split("/", -1)) { if (segment.isEmpty() || segment.equals(".") || segment.equals("..")) { throw new IllegalArgumentException("A saved ID names files, so it has no empty, . or .. segment: " + id); } diff --git a/api/src/main/java/com/volmit/data/Codec.java b/api/src/main/java/com/volmit/data/StorageCodec.java similarity index 81% rename from api/src/main/java/com/volmit/data/Codec.java rename to api/src/main/java/com/volmit/data/StorageCodec.java index 38bb10259..da812887d 100644 --- a/api/src/main/java/com/volmit/data/Codec.java +++ b/api/src/main/java/com/volmit/data/StorageCodec.java @@ -5,11 +5,11 @@ import java.io.DataOutput; import java.io.IOException; /** Value serialization for data the host stores for a module: mantle layers ({@link com.volmit.mantle.MantleKey}) and - * saved world state ({@link com.volmit.world.SavedKey}). The host frames payloads and stores the key ID and version + * saved world state ({@link SavedKey}). The host frames payloads and stores the key ID and version * separately. Implementations must support concurrent calls, must not close streams, and must reject malformed data or * unsupported stored versions with IOException. Values cannot be null. */ -public interface Codec { +public interface StorageCodec { /** Nonnegative format version, stable for the registration lifetime. */ int version(); diff --git a/api/src/main/java/com/volmit/mantle/MantleKey.java b/api/src/main/java/com/volmit/mantle/MantleKey.java index 63389f4c9..7545bbc6e 100644 --- a/api/src/main/java/com/volmit/mantle/MantleKey.java +++ b/api/src/main/java/com/volmit/mantle/MantleKey.java @@ -1,15 +1,13 @@ package com.volmit.mantle; +import com.volmit.resource.ResourceId; import java.util.Objects; /** Stable storage identity. Different IDs may use the same value class without sharing data. */ -public record MantleKey(String id, Class type) { +public record MantleKey(ResourceId id, Class type) { public MantleKey { Objects.requireNonNull(id, "id"); Objects.requireNonNull(type, "type"); - if (!id.matches("[a-z0-9_.-]+:[a-z0-9_./-]+")) { - throw new IllegalArgumentException("Expected a namespaced mantle ID: " + id); - } if (type.isPrimitive()) { throw new IllegalArgumentException("Mantle values require a reference type"); } diff --git a/api/src/main/java/com/volmit/world/RunningWorld.java b/api/src/main/java/com/volmit/world/RunningWorld.java index 0735d855f..720f9ef35 100644 --- a/api/src/main/java/com/volmit/world/RunningWorld.java +++ b/api/src/main/java/com/volmit/world/RunningWorld.java @@ -1,6 +1,7 @@ package com.volmit.world; import com.volmit.config.FeatureSettings; +import com.volmit.data.SavedKey; import com.volmit.geometry.BlockPosition; import com.volmit.placement.PlacementRecord; import com.volmit.resource.ResourceId; @@ -50,12 +51,14 @@ public interface RunningWorld { * {@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 + * still change it, so {@link com.volmit.data.StorageCodec#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 + * @throws IllegalArgumentException if {@code key} is not the key a module registered with + * {@link com.volmit.FeatureRegistry#registerSaved}: an unregistered key, or another key with the id of a + * registered one, such as one that another module built in its namespace */ T saved(SavedKey key); diff --git a/api/src/test/java/com/volmit/world/SavedKeyTest.java b/api/src/test/java/com/volmit/data/SavedKeyTest.java similarity index 82% rename from api/src/test/java/com/volmit/world/SavedKeyTest.java rename to api/src/test/java/com/volmit/data/SavedKeyTest.java index 3b287fac8..bf8bc4ffd 100644 --- a/api/src/test/java/com/volmit/world/SavedKeyTest.java +++ b/api/src/test/java/com/volmit/data/SavedKeyTest.java @@ -1,6 +1,6 @@ -package com.volmit.world; +package com.volmit.data; -import com.volmit.data.Codec; +import com.volmit.resource.ResourceId; import org.junit.jupiter.api.Test; import java.io.DataInput; @@ -11,7 +11,9 @@ 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<>() { + private static final ResourceId ID = ResourceId.parse("a:b"); + + private static final StorageCodec TEXT = new StorageCodec<>() { @Override public int version() { return 1; @@ -51,10 +53,10 @@ class SavedKeyTest { @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<>() { + assertThrows(NullPointerException.class, () -> new SavedKey<>(ID, null, TEXT, () -> "")); + assertThrows(NullPointerException.class, () -> new SavedKey<>(ID, String.class, null, () -> "")); + assertThrows(NullPointerException.class, () -> new SavedKey<>(ID, String.class, TEXT, null)); + StorageCodec number = new StorageCodec<>() { @Override public int version() { return 1; @@ -70,10 +72,10 @@ class SavedKeyTest { return input.readInt(); } }; - assertThrows(IllegalArgumentException.class, () -> new SavedKey<>("a:b", int.class, number, () -> 0)); + assertThrows(IllegalArgumentException.class, () -> new SavedKey<>(ID, int.class, number, () -> 0)); } private static SavedKey key(String id) { - return new SavedKey<>(id, String.class, TEXT, () -> ""); + return new SavedKey<>(ResourceId.parse(id), String.class, TEXT, () -> ""); } } diff --git a/api/src/test/java/com/volmit/mantle/MantleValueTest.java b/api/src/test/java/com/volmit/mantle/MantleValueTest.java index 99f7e5f83..ae5ce1148 100644 --- a/api/src/test/java/com/volmit/mantle/MantleValueTest.java +++ b/api/src/test/java/com/volmit/mantle/MantleValueTest.java @@ -1,6 +1,7 @@ package com.volmit.mantle; import com.volmit.geometry.BlockBox; +import com.volmit.resource.ResourceId; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; @@ -33,20 +34,18 @@ class MantleValueTest { @Test void keysSeparateSameTypedLayersAndHaveValueEquality() { - var owner = new MantleKey<>("example:object-owner", String.class); - assertEquals(owner, new MantleKey<>("example:object-owner", String.class)); - assertNotEquals(owner, new MantleKey<>("example:quest/location", String.class)); - assertNotEquals(owner, new MantleKey<>("example:object-owner", Integer.class)); + var owner = new MantleKey<>(ResourceId.parse("example:object-owner"), String.class); + assertEquals(owner, new MantleKey<>(ResourceId.parse("example:object-owner"), String.class)); + assertNotEquals(owner, new MantleKey<>(ResourceId.parse("example:quest/location"), String.class)); + assertNotEquals(owner, new MantleKey<>(ResourceId.parse("example:object-owner"), Integer.class)); } @Test - void rejectsInvalidKeys() { - for (String id : new String[]{"", "owner", ":owner", "example:", "Example:owner", "a:b:c", "a: b"}) { - assertThrows(IllegalArgumentException.class, () -> new MantleKey<>(id, String.class)); - } + void rejectsMissingPartsAndPrimitiveTypes() { + var id = ResourceId.parse("a:b"); assertThrows(NullPointerException.class, () -> new MantleKey<>(null, String.class)); - assertThrows(NullPointerException.class, () -> new MantleKey<>("a:b", null)); - assertThrows(IllegalArgumentException.class, () -> new MantleKey<>("a:b", int.class)); + assertThrows(NullPointerException.class, () -> new MantleKey<>(id, null)); + assertThrows(IllegalArgumentException.class, () -> new MantleKey<>(id, int.class)); } @Test diff --git a/host/src/main/java/com/volmit/host/FeatureCatalog.java b/host/src/main/java/com/volmit/host/FeatureCatalog.java index 62c677642..d79a9a44d 100644 --- a/host/src/main/java/com/volmit/host/FeatureCatalog.java +++ b/host/src/main/java/com/volmit/host/FeatureCatalog.java @@ -1,5 +1,7 @@ package com.volmit.host; +import com.volmit.data.SavedKey; +import com.volmit.resource.ResourceId; import com.volmit.service.Providers; import com.volmit.service.Service; import java.util.Collection; @@ -31,7 +33,8 @@ public final class FeatureCatalog { }; private final Map, FeatureDescriptor> settings; - private final Map> mantle; + private final Map> mantle; + private final Map> saved; private final List resourceKinds; private final List validators; private final List lifecycles; @@ -43,7 +46,8 @@ public final class FeatureCatalog { FeatureCatalog( Map, FeatureDescriptor> settings, - Map> mantle, + Map> mantle, + Map> saved, Collection resourceKinds, List validators, List lifecycles, @@ -56,6 +60,7 @@ public final class FeatureCatalog { this.commands = sorted(commands, registration -> registration.command().name()); this.settings = Map.copyOf(settings); this.mantle = Map.copyOf(mantle); + this.saved = Map.copyOf(saved); this.resourceKinds = sorted(resourceKinds, registration -> registration.kind().id()); this.validators = inModuleOrder(validators, ValidatorRegistration::module); this.lifecycles = inModuleOrder(lifecycles, LifecycleRegistration::module); @@ -72,6 +77,11 @@ public final class FeatureCatalog { return sorted(mantle.values(), registration -> registration.key().id()); } + /** The values modules keep with each running world ({@code FeatureRegistry.registerSaved}), by id. */ + public List> saved() { + return sorted(saved.values(), SavedKey::id); + } + /** The type packs write their object placements as, if a module declared it ({@code FeatureRegistry.registerPlacementType}). */ public Optional placementType() { return placementType; diff --git a/host/src/main/java/com/volmit/host/MantleRegistration.java b/host/src/main/java/com/volmit/host/MantleRegistration.java index 303358093..8cc82624d 100644 --- a/host/src/main/java/com/volmit/host/MantleRegistration.java +++ b/host/src/main/java/com/volmit/host/MantleRegistration.java @@ -1,6 +1,6 @@ package com.volmit.host; -import com.volmit.data.Codec; +import com.volmit.data.StorageCodec; import com.volmit.mantle.MantleKey; import com.volmit.mantle.MantleLifetime; import java.util.Objects; @@ -8,7 +8,7 @@ import java.util.Objects; public record MantleRegistration( MantleKey key, MantleLifetime lifetime, - Codec codec, + StorageCodec codec, int version) { public MantleRegistration { Objects.requireNonNull(key, "key"); diff --git a/host/src/main/java/com/volmit/host/ModuleRegistry.java b/host/src/main/java/com/volmit/host/ModuleRegistry.java index 99e7ece68..c2f7bb9dc 100644 --- a/host/src/main/java/com/volmit/host/ModuleRegistry.java +++ b/host/src/main/java/com/volmit/host/ModuleRegistry.java @@ -4,7 +4,8 @@ import com.volmit.FeatureRegistry; import com.volmit.IrisFeature; import com.volmit.ModuleLifecycle; import com.volmit.config.Level; -import com.volmit.data.Codec; +import com.volmit.data.SavedKey; +import com.volmit.data.StorageCodec; import com.volmit.mantle.MantleKey; import com.volmit.mantle.MantleLifetime; import com.volmit.resource.ResourceId; @@ -27,7 +28,7 @@ import java.util.Set; * immutable. IDs are unique across feature kinds. A feature's JSON key (see {@link com.volmit.config.Feature#key}) * is unique per attachment target, and may not equal a host JSON field passed in to reserve it; a clash fails the * registration naming the key, the target and both claimants. Modules register during their setup - * ({@link ModuleSetups#run}); mantle keys, resource kind ids and explicitly registered + * ({@link ModuleSetups#run}); mantle keys, saved keys, resource kind ids and explicitly registered * settings ids must be the registering module's id or start with it and '/' ({@link com.volmit.ModuleInfo#ownsId}). * Resource kinds have unique ids, types and folders, and no kind may read a folder the host reserves for its own * files. Lifecycle hooks and service providers are registered by the module that owns them; a service whose providers @@ -38,7 +39,8 @@ import java.util.Set; */ public final class ModuleRegistry implements FeatureRegistry, ToolingRegistry { private final Map, FeatureDescriptor> settings = new HashMap<>(); - private final Map> mantle = new HashMap<>(); + private final Map> mantle = new HashMap<>(); + private final Map> saved = new HashMap<>(); private final Set featureIds = new HashSet<>(); private final Set> featureTypes = new HashSet<>(); private final Set> registeredByOwner = new HashSet<>(); @@ -84,11 +86,11 @@ public final class ModuleRegistry implements FeatureRegistry, ToolingRegistry { } @Override - public void registerMantle(MantleKey key, MantleLifetime lifetime, Codec codec) { + public void registerMantle(MantleKey key, MantleLifetime lifetime, StorageCodec codec) { checkOpen(); Objects.requireNonNull(key, "key"); Objects.requireNonNull(codec, "codec"); - requireOwnedId("Mantle layer", ResourceId.parse(key.id())); + requireOwnedId("Mantle layer", key.id()); var registration = new MantleRegistration<>(key, lifetime, codec, codec.version()); if (mantle.putIfAbsent(key.id(), registration) != null) { @@ -96,6 +98,19 @@ public final class ModuleRegistry implements FeatureRegistry, ToolingRegistry { } } + @Override + public void registerSaved(SavedKey key) { + checkOpen(); + Objects.requireNonNull(key, "key"); + requireOwnedId("Saved value", key.id()); + if (key.codec().version() < 0) { + throw new IllegalArgumentException("Negative saved codec version"); + } + if (saved.putIfAbsent(key.id(), key) != null) { + throw new IllegalArgumentException("Duplicate saved value: " + key.id()); + } + } + @Override public void registerSettings(Class settingsType) { checkOpen(); @@ -237,7 +252,7 @@ public final class ModuleRegistry implements FeatureRegistry, ToolingRegistry { public FeatureCatalog freeze() { if (catalog == null) { - catalog = new FeatureCatalog(settings, mantle, resourceKinds.values(), validators, lifecycles, services, + catalog = new FeatureCatalog(settings, mantle, saved, resourceKinds.values(), validators, lifecycles, services, placementType, studioViews.values(), commands); } return catalog; diff --git a/host/src/main/java/com/volmit/host/PipelineReach.java b/host/src/main/java/com/volmit/host/PipelineReach.java index 43d3996cb..33f0cdac6 100644 --- a/host/src/main/java/com/volmit/host/PipelineReach.java +++ b/host/src/main/java/com/volmit/host/PipelineReach.java @@ -1,5 +1,6 @@ package com.volmit.host; +import com.volmit.resource.ResourceId; import java.util.Collections; import java.util.Map; import java.util.TreeMap; @@ -12,7 +13,7 @@ import java.util.TreeMap; * @param mantleLayers for each mantle layer some stage writes, by layer id in id order, the largest * reach of the stages that write it */ -public record PipelineReach(int blocks, Map mantleLayers) { +public record PipelineReach(int blocks, Map mantleLayers) { public PipelineReach { if (blocks < 0) throw new IllegalArgumentException("Negative reach: " + blocks); mantleLayers = Collections.unmodifiableMap(new TreeMap<>(mantleLayers)); @@ -20,7 +21,7 @@ public record PipelineReach(int blocks, Map mantleLayers) { static PipelineReach of(Iterable stages) { int blocks = 0; - var layers = new TreeMap(); + var layers = new TreeMap(); for (var stage : stages) { int stageBlocks = stage.fixedReachBlocks(); blocks = Math.max(blocks, stageBlocks); diff --git a/host/src/main/java/com/volmit/host/StageReach.java b/host/src/main/java/com/volmit/host/StageReach.java index 61398bae0..e373bf64e 100644 --- a/host/src/main/java/com/volmit/host/StageReach.java +++ b/host/src/main/java/com/volmit/host/StageReach.java @@ -1,6 +1,7 @@ package com.volmit.host; import com.volmit.mantle.MantleKey; +import com.volmit.resource.ResourceId; import com.volmit.stage.PackReach; import java.util.HashSet; import java.util.List; @@ -22,7 +23,7 @@ public record StageReach(PackReach blocks, List> mantleLayers) { public StageReach { Objects.requireNonNull(blocks, "blocks"); mantleLayers = List.copyOf(mantleLayers); - var ids = new HashSet(); + var ids = new HashSet(); for (var layer : mantleLayers) { if (!ids.add(Objects.requireNonNull(layer, "mantle layer").id())) { throw new IllegalArgumentException("Mantle layer " + layer.id() + " declared twice"); diff --git a/host/src/test/java/com/volmit/example/chunk/VeinModule.java b/host/src/test/java/com/volmit/example/chunk/VeinModule.java index 100f9f1b8..2017f09d0 100644 --- a/host/src/test/java/com/volmit/example/chunk/VeinModule.java +++ b/host/src/test/java/com/volmit/example/chunk/VeinModule.java @@ -7,9 +7,10 @@ import com.volmit.block.BlockState; import com.volmit.config.PackSettings; import com.volmit.generation.ChunkContext; import com.volmit.geometry.BlockBox; -import com.volmit.data.Codec; +import com.volmit.data.StorageCodec; import com.volmit.mantle.MantleKey; import com.volmit.mantle.MantleLifetime; +import com.volmit.resource.ResourceId; import com.volmit.stage.ChunkStage; import com.volmit.stage.ChunkStageContext; import com.volmit.stage.MantleStage; @@ -25,7 +26,7 @@ import java.io.IOException; * its reach out when the pack loads. */ public final class VeinModule implements IrisModule { - public static final MantleKey ORE = new MantleKey<>("example:veins/ore", Integer.class); + public static final MantleKey ORE = new MantleKey<>(ResourceId.parse("example:veins/ore"),Integer.class); public static final MantleStage PLAN = Stage.mantle("example:veins/plan"); public static final ChunkStage PLACE = Stage.chunk("example:veins/place"); public static final BlockState ORE_BLOCK = new BlockState("minecraft:iron_ore"); @@ -69,7 +70,7 @@ public final class VeinModule implements IrisModule { blocks.set(x - context.originX(), y, z - context.originZ(), ORE_BLOCK)); } - private static final class IntegerCodec implements Codec { + private static final class IntegerCodec implements StorageCodec { public int version() { return 0; } public void write(DataOutput output, Integer value) throws IOException { output.writeInt(value); } public Integer read(DataInput input, int storedVersion) throws IOException { return input.readInt(); } diff --git a/host/src/test/java/com/volmit/host/ModuleRegistryTest.java b/host/src/test/java/com/volmit/host/ModuleRegistryTest.java index fc9d1496c..00aa4576e 100644 --- a/host/src/test/java/com/volmit/host/ModuleRegistryTest.java +++ b/host/src/test/java/com/volmit/host/ModuleRegistryTest.java @@ -3,8 +3,10 @@ package com.volmit.host; import com.volmit.*; import com.volmit.config.Feature; import com.volmit.config.Level; -import com.volmit.data.Codec; +import com.volmit.data.SavedKey; +import com.volmit.data.StorageCodec; import com.volmit.mantle.*; +import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceKind; import com.volmit.service.Providers; import com.volmit.service.Service; @@ -79,12 +81,12 @@ class ModuleRegistryTest { @Test void mantleIdsAreUniqueAndCodecVersionIsSnapshotted() { var registry = new ModuleRegistry(); - var key = new MantleKey<>("test:core/layer", String.class); + var key = new MantleKey<>(ResourceId.parse("test:core/layer"), String.class); var codec = codec(3); registerAs(registry, "test:core", layers -> { layers.registerMantle(key, MantleLifetime.GENERATION, codec); assertThrows(IllegalArgumentException.class, () -> layers.registerMantle(key, MantleLifetime.PERSISTENT, codec)); - assertThrows(IllegalArgumentException.class, () -> layers.registerMantle(new MantleKey<>("test:core/bad", String.class), MantleLifetime.GENERATION, codec(-1))); + assertThrows(IllegalArgumentException.class, () -> layers.registerMantle(new MantleKey<>(ResourceId.parse("test:core/bad"), String.class), MantleLifetime.GENERATION, codec(-1))); }); assertEquals(3, registry.freeze().mantle().getFirst().version()); assertEquals(1, registry.freeze().mantle().size()); @@ -98,11 +100,11 @@ class ModuleRegistryTest { assertTrue(sameNamespace.getMessage().contains("must be test:other or start with test:other/"), sameNamespace.getMessage()); var mantle = assertThrows(IllegalArgumentException.class, () -> registerAs(registry, "iris:snow", - layers -> layers.registerMantle(new MantleKey<>("iris:snowdepth", String.class), MantleLifetime.GENERATION, codec(1)))); + layers -> layers.registerMantle(new MantleKey<>(ResourceId.parse("iris:snowdepth"), String.class), MantleLifetime.GENERATION, codec(1)))); assertEquals("Mantle layer iris:snowdepth must be iris:snow or start with iris:snow/, the id of its registering module " + "iris:snow from host classpath", mantle.getMessage()); - assertThrows(IllegalStateException.class, () -> registry.registerMantle(new MantleKey<>("test:loose", String.class), + assertThrows(IllegalStateException.class, () -> registry.registerMantle(new MantleKey<>(ResourceId.parse("test:loose"), String.class), MantleLifetime.GENERATION, codec(1))); assertTrue(registry.freeze().settings().isEmpty()); assertTrue(registry.freeze().mantle().isEmpty()); @@ -208,16 +210,37 @@ class ModuleRegistryTest { }; } + private static SavedKey saved(String id) { + return new SavedKey<>(ResourceId.parse(id), String.class, codec(1), () -> ""); + } + + @Test + void savedKeysAreOwnedByTheRegisteringModuleAndUnique() { + var registry = new ModuleRegistry(); + var key = saved("test:core/book"); + registerAs(registry, "test:core", saves -> { + saves.registerSaved(key); + assertThrows(IllegalArgumentException.class, () -> saves.registerSaved(saved("test:core/book"))); + assertThrows(NullPointerException.class, () -> saves.registerSaved(null)); + }); + assertEquals(List.of(key), registry.freeze().saved()); + + var foreign = assertThrows(IllegalArgumentException.class, () -> registerAs(new ModuleRegistry(), "test:other", + saves -> saves.registerSaved(key))); + assertTrue(foreign.getMessage().contains("must be test:other or start with test:other/"), foreign.getMessage()); + assertThrows(IllegalStateException.class, () -> new ModuleRegistry().registerSaved(key)); + } + @Test void moduleMayRegisterItsOwnIdAndIdsBelowIt() { var registry = new ModuleRegistry(); registerAs(registry, "iris:snow", layers -> { - layers.registerMantle(new MantleKey<>("iris:snow", String.class), MantleLifetime.GENERATION, codec(1)); - layers.registerMantle(new MantleKey<>("iris:snow/depth/deep", String.class), MantleLifetime.GENERATION, codec(1)); + layers.registerMantle(new MantleKey<>(ResourceId.parse("iris:snow"), String.class), MantleLifetime.GENERATION, codec(1)); + layers.registerMantle(new MantleKey<>(ResourceId.parse("iris:snow/depth/deep"), String.class), MantleLifetime.GENERATION, codec(1)); }); assertEquals(List.of("iris:snow", "iris:snow/depth/deep"), - registry.freeze().mantle().stream().map(layer -> layer.key().id()).sorted().toList()); + registry.freeze().mantle().stream().map(layer -> layer.key().id().toString()).sorted().toList()); } @Test @@ -592,8 +615,8 @@ class ModuleRegistryTest { assertEquals("test:alpha", registrations.getFirst().module().info().id().toString()); } - private static Codec codec(int version) { - return new Codec<>() { + private static StorageCodec codec(int version) { + return new StorageCodec<>() { public int version() { return version; } public void write(DataOutput output, String value) {} public String read(DataInput input, int storedVersion) { return ""; } diff --git a/host/src/test/java/com/volmit/host/StageGraphTest.java b/host/src/test/java/com/volmit/host/StageGraphTest.java index f49bc0b6f..0108bb01d 100644 --- a/host/src/test/java/com/volmit/host/StageGraphTest.java +++ b/host/src/test/java/com/volmit/host/StageGraphTest.java @@ -11,7 +11,7 @@ import com.volmit.config.Feature; import com.volmit.config.FeatureSettings.Entry; import com.volmit.geometry.BlockBox; import com.volmit.geometry.BlockPosition; -import com.volmit.data.Codec; +import com.volmit.data.StorageCodec; import com.volmit.mantle.MantleKey; import com.volmit.mantle.MantleLifetime; import com.volmit.object.GeneratedObject; @@ -519,7 +519,7 @@ class StageGraphTest { @Test void onePlacementInvocationMakesItsMantleViewsOnce() { - var key = new MantleKey<>("test:views/depth", Integer.class); + var key = new MantleKey<>(ResourceId.parse("test:views/depth"),Integer.class); var views = new ArrayList(); var graph = resolve(Pipeline.PLACEMENT, module("test:views", stages -> stages.define(Stage.placement("test:views/read")).run(context -> { @@ -569,8 +569,8 @@ class StageGraphTest { @Test void reachIsDeclaredPerStageAndCollectedPerPipelineAndLayer() { - var depth = new MantleKey<>("test:reach/depth", Integer.class); - var marks = new MantleKey<>("test:reach/marks", String.class); + var depth = new MantleKey<>(ResourceId.parse("test:reach/depth"), Integer.class); + var marks = new MantleKey<>(ResourceId.parse("test:reach/marks"), String.class); var carve = Stage.mantle("test:reach/carve"); var mark = Stage.mantle("test:reach/mark"); var plain = Stage.mantle("test:reach/plain"); @@ -585,7 +585,7 @@ class StageGraphTest { assertEquals(new StageReach(24, List.of(depth)), loaded.mantle().stages().getFirst().reach()); assertEquals(StageReach.NONE, loaded.mantle().stages().get(2).reach(), "an undeclared reach is 0 with no layers"); - assertEquals(new PipelineReach(24, Map.of("test:reach/depth", 24, "test:reach/marks", 8)), loaded.mantle().reach()); + assertEquals(new PipelineReach(24, Map.of(depth.id(), 24, marks.id(), 8)), loaded.mantle().reach()); assertEquals(new PipelineReach(2, Map.of()), loaded.placement().reach()); assertEquals(new PipelineReach(0, Map.of()), loaded.chunk().reach()); assertTrue(loaded.mantle().describe().contains(" reach 24 blocks, writes mantle test:reach/depth\n"), loaded.mantle().describe()); @@ -655,7 +655,7 @@ class StageGraphTest { @Test void reachMustBeValidAndNameRegisteredLayers() { - var depth = new MantleKey<>("test:reach/depth", Integer.class); + var depth = new MantleKey<>(ResourceId.parse("test:reach/depth"), Integer.class); var carve = Stage.mantle("test:reach/carve"); var negative = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.MANTLE, @@ -672,7 +672,7 @@ class StageGraphTest { assertEquals("Stage test:reach/carve of module test:reach writes mantle layer test:reach/depth, which no module registers;" + " its owner registers it with FeatureRegistry.registerMantle", unregistered.getMessage()); - var asText = new MantleKey<>("test:reach/depth", String.class); + var asText = new MantleKey<>(ResourceId.parse("test:reach/depth"), String.class); var mismatch = assertThrows(ModuleLoadException.class, () -> LoadedModules.load(List.of(DiscoveredModule.builtIn(withMantle( module("test:reach", stages -> stages.define(carve).writesMantle(asText).run(context -> {})), depth))), Map.of(), Set.of(), Set.of())); assertEquals("Stage test:reach/carve of module test:reach writes mantle layer test:reach/depth as java.lang.String," @@ -694,8 +694,8 @@ class StageGraphTest { registry.registerMantle(layer, MantleLifetime.GENERATION, codec(layer)); } - private static Codec codec(MantleKey layer) { - return new Codec<>() { + private static StorageCodec codec(MantleKey layer) { + return new StorageCodec<>() { public int version() { return 0; } public void write(java.io.DataOutput output, T value) {} public T read(java.io.DataInput input, int storedVersion) { throw new UnsupportedOperationException(); } diff --git a/host/src/test/java/com/volmit/support/MemoryMantle.java b/host/src/test/java/com/volmit/support/MemoryMantle.java index 83f27efa8..41a7dd010 100644 --- a/host/src/test/java/com/volmit/support/MemoryMantle.java +++ b/host/src/test/java/com/volmit/support/MemoryMantle.java @@ -21,15 +21,15 @@ public final class MemoryMantle { .thenComparingInt(BlockPosition::y).thenComparingInt(BlockPosition::z); /** Where the planned blocks are kept; the host owns them, so no module registers this layer. */ - private static final MantleKey PLANNED_BLOCKS = new MantleKey<>("host:planned-blocks", BlockState.class); + private static final MantleKey PLANNED_BLOCKS = new MantleKey<>(ResourceId.parse("host:planned-blocks"),BlockState.class); /** Where the carved voids are kept; the host owns them, so no module registers this layer. */ - private static final MantleKey CAVERNS = new MantleKey<>("host:caverns", CarvedVoid.class); + private static final MantleKey CAVERNS = new MantleKey<>(ResourceId.parse("host:caverns"),CarvedVoid.class); /** Where the platform biomes stages set are kept; the host owns them, so no module registers this layer. */ - private static final MantleKey PLATFORM_BIOMES = new MantleKey<>("host:platform-biomes", ResourceId.class); + private static final MantleKey PLATFORM_BIOMES = new MantleKey<>(ResourceId.parse("host:platform-biomes"),ResourceId.class); - private final Map> layers = new HashMap<>(); + private final Map> layers = new HashMap<>(); /** A view that accepts reads and writes inside {@code bounds} only. */ public Mantle within(BlockBox bounds) {