Merge wave1/a1

This commit is contained in:
piexel committed 2026-10-09 14:43:33 +02:00
commit adb848bf9f
29 files changed
+1286 -17

No files matched your search

@@ -0,0 +1,100 @@
package com.volmit.example.world;
import com.volmit.FeatureRegistry;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.ModuleLifecycle;
import com.volmit.host.ChunkRunner;
import com.volmit.host.DiscoveredModule;
import com.volmit.host.LifecycleRunner;
import com.volmit.host.LoadedModules;
import com.volmit.service.ObjectsAt;
import com.volmit.stage.ChunkStage;
import com.volmit.stage.ChunkStageContext;
import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph;
import com.volmit.support.ColumnSettings;
import com.volmit.support.TestContexts;
import com.volmit.support.TestWorld;
import com.volmit.world.PackWorld;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import static org.junit.jupiter.api.Assertions.*;
/** A module that remembers, per world, which chunks it planted ruins in: its chunk stage writes the world's state,
* its {@link ObjectsAt} service reads it, and its lifecycle builds the state when the world starts.
*/
class WorldStateExampleTest {
static final class RuinsModule implements IrisModule, ModuleLifecycle {
static final ChunkStage<Void> PLANT = Stage.chunk("example:ruins/plant");
/** What ruins keeps per world. A field of the module would be shared by every world. */
static final class PlantedChunks {
final long seed;
final Set<Long> chunks = ConcurrentHashMap.newKeySet();
PlantedChunks(PackWorld world) {
this.seed = world.seed();
}
}
public ModuleInfo info() { return ModuleInfo.of("example:ruins", "Ruins", "1"); }
public void install(StageGraph graph) {
graph.define(PLANT).run(RuinsModule::plant);
}
public void register(FeatureRegistry registry) {
registry.registerLifecycle(this);
registry.registerService(ObjectsAt.class, RuinsModule::objectsAt);
}
@Override
public void worldStarted(PackWorld world) {
planted(world);
}
static PlantedChunks planted(PackWorld world) {
return world.state(PlantedChunks.class, PlantedChunks::new);
}
private static void plant(ChunkStageContext context) {
planted(context.world()).chunks.add(key(context.originX() >> 4, context.originZ() >> 4));
}
private static Set<String> objectsAt(PackWorld world, int chunkX, int chunkZ) {
return planted(world).chunks.contains(key(chunkX, chunkZ)) ? Set.of("ruins/arch") : Set.of();
}
private static long key(int chunkX, int chunkZ) {
return ((long) chunkX << 32) ^ (chunkZ & 0xFFFFFFFFL);
}
}
@Test
void stagesServicesAndHooksShareTheStateOfTheirWorldAndANewWorldStartsEmpty() {
var pack = LoadedModules.load(List.of(DiscoveredModule.builtIn(new RuinsModule())), Map.of(), Set.of(), Set.of(), Set.of());
var lifecycles = new LifecycleRunner(pack.catalog());
ObjectsAt objects = pack.catalog().services(ObjectsAt.class).getFirst();
try (var world = new TestWorld()) {
lifecycles.worldStarted(world);
var startedWith = RuinsModule.planted(world);
assertEquals(TestContexts.SEED, startedWith.seed);
new ChunkRunner(pack.chunk()).generate(TestContexts.generation(Map.of(), ColumnSettings.NONE, null, world), TestContexts.SEED);
assertSame(startedWith, RuinsModule.planted(world), "the stage used the state the hook built");
assertEquals(Set.of("ruins/arch"), objects.objectsAt(world, 0, 0));
assertEquals(Set.of(), objects.objectsAt(world, 1, 0));
lifecycles.worldStopped(world);
}
try (var reloaded = new TestWorld()) {
assertEquals(Set.of(), objects.objectsAt(reloaded, 0, 0), "a new world starts with empty state");
}
}
}
@@ -0,0 +1,101 @@
package com.volmit.host;
import com.volmit.FeatureRegistry;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.ModuleLifecycle;
import com.volmit.config.PackSettings;
import com.volmit.resource.PackResources;
import com.volmit.stage.StageGraph;
import com.volmit.support.EmptyResources;
import com.volmit.support.TestWorld;
import com.volmit.world.PackWorld;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
class LifecycleRunnerTest {
/** A module whose hooks record themselves into {@code calls} and throw on the named hook. */
private static IrisModule module(String id, List<String> calls, String failingHook) {
return new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of(id, "Lifecycle " + id, "1"); }
public void install(StageGraph graph) {}
public void register(FeatureRegistry registry) {
registry.registerLifecycle(new ModuleLifecycle() {
public void packLoaded(PackResources resources, PackSettings settings) { record("loaded"); }
public void worldStarted(PackWorld world) { record("started"); }
public void worldStopped(PackWorld world) { record("stopped"); }
private void record(String hook) {
calls.add(hook + " " + id);
if (hook.equals(failingHook)) {
throw new IllegalStateException(id + " cannot be " + hook);
}
}
});
}
};
}
private static LifecycleRunner runner(IrisModule... modules) {
var discovered = Arrays.stream(modules).map(DiscoveredModule::builtIn).toList();
return new LifecycleRunner(LoadedModules.load(discovered, Map.of(), Set.of(), Set.of(), Set.of()).catalog());
}
@Test
void startsInModuleIdOrderAndStopsInReverse() {
var calls = new ArrayList<String>();
var runner = runner(module("test:zeta", calls, null), module("test:alpha", calls, null));
try (var world = new TestWorld()) {
runner.worldStarted(world);
runner.worldStopped(world);
}
assertEquals(List.of("started test:alpha", "started test:zeta", "stopped test:zeta", "stopped test:alpha"), calls);
}
@Test
void aFailedStartStopsTheModulesThatStartedAndNamesTheModule() {
var calls = new ArrayList<String>();
var runner = runner(module("test:alpha", calls, null), module("test:beta", calls, "started"), module("test:gamma", calls, null));
try (var world = new TestWorld()) {
var failure = assertThrows(IllegalStateException.class, () -> runner.worldStarted(world));
assertTrue(failure.getMessage().startsWith("Module test:beta from host classpath failed while starting a world"),
failure.getMessage());
}
assertEquals(List.of("started test:alpha", "started test:beta", "stopped test:alpha"), calls);
}
@Test
void everyModuleStopsEvenWhenOneFailsAndEveryFailureIsReported() {
var calls = new ArrayList<String>();
var runner = runner(module("test:alpha", calls, "stopped"), module("test:beta", calls, null), module("test:gamma", calls, "stopped"));
try (var world = new TestWorld()) {
var failure = assertThrows(IllegalStateException.class, () -> runner.worldStopped(world));
assertTrue(failure.getMessage().startsWith("Module test:gamma from host classpath failed while stopping a world"),
failure.getMessage());
assertEquals(1, failure.getSuppressed().length);
assertTrue(failure.getSuppressed()[0].getMessage().startsWith("Module test:alpha"));
}
assertEquals(List.of("stopped test:gamma", "stopped test:beta", "stopped test:alpha"), calls);
}
@Test
void aFailedPackLoadNamesTheModuleAndSkipsTheRest() {
var calls = new ArrayList<String>();
var runner = runner(module("test:alpha", calls, "loaded"), module("test:beta", calls, null));
PackResources resources = new EmptyResources();
var failure = assertThrows(IllegalStateException.class, () -> runner.packLoaded(resources, new TestWorld().settings()));
assertTrue(failure.getMessage().startsWith("Module test:alpha from host classpath failed while loading pack test:pack"),
failure.getMessage());
assertEquals(List.of("loaded test:alpha"), calls);
}
}
@@ -4,6 +4,8 @@ import com.volmit.*;
import com.volmit.config.Feature;
import com.volmit.mantle.*;
import com.volmit.resource.ResourceKind;
import com.volmit.service.Providers;
import com.volmit.service.Service;
import com.volmit.validation.Validator;
import com.volmit.stage.PlacementStage;
import com.volmit.stage.Stage;
@@ -13,6 +15,7 @@ import java.io.DataInput;
import java.io.DataOutput;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import static org.junit.jupiter.api.Assertions.*;
@@ -248,6 +251,82 @@ class ModuleRegistryTest {
assertThrows(IllegalStateException.class, () -> registry.registerValidator(pack -> {}), "registration has ended");
}
@Service(Providers.ALL)
interface Greeting { String greet(); }
@Service(Providers.ONE)
interface Clock { long now(); }
interface NotAService { void run(); }
@Test
void lifecyclesAreCataloguedByModuleIdInTheOrderEachModuleRegisteredThem() {
var registry = new ModuleRegistry();
ModuleLifecycle first = new ModuleLifecycle() {};
ModuleLifecycle second = new ModuleLifecycle() {};
ModuleLifecycle other = new ModuleLifecycle() {};
registerAs(registry, "test:zeta", hooks -> hooks.registerLifecycle(other));
registerAs(registry, "test:alpha", hooks -> {
hooks.registerLifecycle(first);
hooks.registerLifecycle(second);
});
assertThrows(IllegalStateException.class, () -> registry.registerLifecycle(new ModuleLifecycle() {}),
"registration outside IrisModule.register");
var catalog = registry.freeze();
assertEquals(List.of(first, second, other), catalog.lifecycles().stream().map(LifecycleRegistration::lifecycle).toList());
assertEquals("test:alpha", catalog.lifecycles().getFirst().module().info().id().toString());
}
@Test
void serviceProvidersComeInModuleIdOrderAndEachModulesInRegistrationOrder() {
var registry = new ModuleRegistry();
Greeting zeta = () -> "zeta";
Greeting alphaFirst = () -> "alpha 1";
Greeting alphaSecond = () -> "alpha 2";
registerAs(registry, "test:zeta", services -> services.registerService(Greeting.class, zeta));
registerAs(registry, "test:alpha", services -> {
services.registerService(Greeting.class, alphaFirst);
services.registerService(Greeting.class, alphaSecond);
});
var catalog = registry.freeze();
assertEquals(List.of(alphaFirst, alphaSecond, zeta), catalog.services(Greeting.class));
assertEquals(List.of(), catalog.services(Clock.class), "a service nobody provides has no providers");
assertEquals(Optional.empty(), catalog.service(Clock.class));
var several = assertThrows(IllegalArgumentException.class, () -> catalog.service(Greeting.class));
assertTrue(several.getMessage().contains("services(...)"), several.getMessage());
assertThrows(IllegalArgumentException.class, () -> catalog.services(NotAService.class));
}
@Test
void aServiceWithOneProviderFailsTheLoadWhenASecondModuleProvidesIt() {
var registry = new ModuleRegistry();
Clock clock = () -> 1L;
registerAs(registry, "test:alpha", services -> services.registerService(Clock.class, clock));
registerAs(registry, "test:zeta", services -> {
var duplicate = assertThrows(IllegalArgumentException.class, () -> services.registerService(Clock.class, () -> 2L));
assertTrue(duplicate.getMessage().contains("test:alpha from host classpath"), duplicate.getMessage());
assertTrue(duplicate.getMessage().contains("test:zeta from host classpath"), duplicate.getMessage());
});
assertEquals(Optional.of(clock), registry.freeze().service(Clock.class));
}
@Test
@SuppressWarnings({"unchecked", "rawtypes"}) // A raw class lets a provider of the wrong type reach the check.
void servicesMustBeMarkedInterfacesThatTheProviderImplements() {
var registry = new ModuleRegistry();
registerAs(registry, "test:alpha", services -> {
var unmarked = assertThrows(IllegalArgumentException.class,
() -> services.registerService(NotAService.class, () -> {}));
assertTrue(unmarked.getMessage().contains("@" + Service.class.getName()), unmarked.getMessage());
assertThrows(IllegalArgumentException.class, () -> services.registerService(Object.class, new Object()));
assertThrows(IllegalArgumentException.class, () -> services.registerService((Class) Greeting.class, (Clock) () -> 1L));
assertThrows(NullPointerException.class, () -> services.registerService(Greeting.class, null));
});
assertThrows(IllegalStateException.class, () -> registry.registerService(Greeting.class, () -> "outside"));
assertEquals(List.of(), registry.freeze().services(Greeting.class));
}
private static MantleCodec<String> codec(int version) {
return new MantleCodec<>() {
public int version() { return version; }
@@ -0,0 +1,138 @@
package com.volmit.host;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
class WorldStatesTest {
static final class Cache {}
static final class Index {
final Cache cache;
Index(Cache cache) { this.cache = cache; }
}
static final class Loop {}
static final class Other {}
record Closing(String name, List<String> closed, boolean fails) implements AutoCloseable {
@Override
public void close() {
closed.add(name);
if (fails) {
throw new IllegalStateException(name + " broke");
}
}
}
static final class ClosingA {}
@Test
void createsEachTypeOnceAndHandsEveryCallerTheSameInstance() {
var states = new WorldStates();
var created = new AtomicInteger();
Cache first = states.state(Cache.class, () -> {
created.incrementAndGet();
return new Cache();
});
Cache second = states.state(Cache.class, () -> {
created.incrementAndGet();
return new Cache();
});
assertSame(first, second);
assertEquals(1, created.get());
}
@Test
void racingThreadsShareOneCreation() throws Exception {
var states = new WorldStates();
var created = new AtomicInteger();
var start = new CountDownLatch(1);
var threads = 8;
try (var executor = Executors.newFixedThreadPool(threads)) {
var results = new ArrayList<Future<Cache>>();
for (int thread = 0; thread < threads; thread++) {
results.add(executor.submit(() -> {
start.await();
return states.state(Cache.class, () -> {
created.incrementAndGet();
return new Cache();
});
}));
}
start.countDown();
Cache shared = results.getFirst().get(10, TimeUnit.SECONDS);
for (var result : results) {
assertSame(shared, result.get(10, TimeUnit.SECONDS));
}
}
assertEquals(1, created.get());
}
@Test
void aFactoryMayAskForOtherStateButNotForItself() {
var states = new WorldStates();
Index index = states.state(Index.class, () -> new Index(states.state(Cache.class, Cache::new)));
assertSame(index.cache, states.state(Cache.class, Cache::new));
var loop = assertThrows(IllegalStateException.class, () -> states.state(Loop.class, () -> {
states.state(Other.class, () -> {
states.state(Loop.class, Loop::new);
return new Other();
});
return new Loop();
}));
assertTrue(loop.getMessage().contains(Loop.class.getName() + " -> " + Other.class.getName() + " -> " + Loop.class.getName()),
loop.getMessage());
assertNotNull(states.state(Loop.class, Loop::new), "a failed creation keeps nothing, so the next call creates it");
}
@Test
void aFactoryThatFailsOrReturnsNullKeepsNothing() {
var states = new WorldStates();
assertThrows(IllegalArgumentException.class, () -> states.state(Cache.class, () -> {
throw new IllegalArgumentException("not yet");
}));
var nothing = assertThrows(NullPointerException.class, () -> states.state(Cache.class, () -> null));
assertTrue(nothing.getMessage().contains(Cache.class.getName()), nothing.getMessage());
var cache = new Cache();
assertSame(cache, states.state(Cache.class, () -> cache));
}
@Test
void closingClosesEveryCloseableStateNewestFirstAndEndsTheStore() {
var states = new WorldStates();
var closed = new ArrayList<String>();
states.state(Closing.class, () -> new Closing("first", closed, false));
states.state(Cache.class, Cache::new);
states.state(ClosingA.class, ClosingA::new);
states.state(AutoCloseable.class, () -> () -> closed.add("second"));
states.close();
states.close();
assertEquals(List.of("second", "first"), closed);
var after = assertThrows(IllegalStateException.class, () -> states.state(Cache.class, Cache::new));
assertTrue(after.getMessage().contains("after the world stopped"), after.getMessage());
}
@Test
void closingContinuesPastAFailureAndReportsEveryOne() {
var states = new WorldStates();
var closed = new ArrayList<String>();
states.state(Closing.class, () -> new Closing("first", closed, true));
states.state(AutoCloseable.class, () -> new Closing("second", closed, true));
var failure = assertThrows(IllegalStateException.class, states::close);
assertEquals(List.of("second", "first"), closed);
assertTrue(failure.getMessage().contains("second broke"), failure.getMessage());
assertEquals(1, failure.getSuppressed().length);
assertTrue(failure.getSuppressed()[0].getMessage().contains("first broke"));
}
}
@@ -0,0 +1,39 @@
package com.volmit.support;
import com.volmit.block.BlockRegistry;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKey;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
/** A pack {@code test:pack} without resources. */
public final class EmptyResources implements PackResources {
private final UUID snapshot = UUID.randomUUID();
@Override
public ResourceId packId() {
return new ResourceId("test", "pack");
}
@Override
public UUID snapshotId() {
return snapshot;
}
@Override
public BlockRegistry blocks() {
throw new AssertionError("Unused blocks");
}
@Override
public <T> Optional<T> find(ResourceKey<T> key) {
return Optional.empty();
}
@Override
public List<ResourceId> ids(Class<?> type) {
return List.of();
}
}
@@ -10,6 +10,7 @@ import com.volmit.placement.PlacementContext;
import com.volmit.resource.PackResources;
import com.volmit.world.TerrainSampler;
import com.volmit.world.BlockView;
import com.volmit.world.PackWorld;
import java.util.Map;
/** Tests needing no platform facilities fail loudly if code starts using one. */
@@ -24,11 +25,17 @@ public final class TestContexts {
/** The chunk at the origin; a null {@code settings} or {@code mantle} fails when used. */
public static GenerationContext generation(Map<Class<?>, Hunk<?>> hunks, FeatureSettings settings, Mantle mantle) {
return generation(hunks, settings, mantle, null);
}
/** The chunk at the origin in {@code world}; a null {@code settings}, {@code mantle} or {@code world} fails when used. */
public static GenerationContext generation(Map<Class<?>, Hunk<?>> hunks, FeatureSettings settings, Mantle mantle, PackWorld world) {
return new GenerationContext() {
public int originX() { return 0; }
public int originZ() { return 0; }
public long worldSeed() { return SEED; }
public PackResources resources() { throw new AssertionError("Unused resources"); }
public PackWorld world() { return used(world, "world"); }
public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); }
public FeatureSettings settings() { return used(settings, "settings"); }
public Mantle mantle() { return used(mantle, "mantle"); }
@@ -48,6 +55,7 @@ public final class TestContexts {
public int originZ() { return originZ; }
public long worldSeed() { return SEED; }
public PackResources resources() { throw new AssertionError("Unused resources"); }
public PackWorld world() { throw new AssertionError("Unused world"); }
public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); }
public FeatureSettings settings() { return settings; }
public Mantle mantle() { return mantle; }
@@ -62,6 +70,7 @@ public final class TestContexts {
return new PlacementContext() {
public long worldSeed() { return SEED; }
public PackResources resources() { throw new AssertionError("Unused resources"); }
public PackWorld world() { throw new AssertionError("Unused world"); }
public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); }
public FeatureSettings settings() { throw new AssertionError("Unused settings"); }
public ObjectTransformer objects() { throw new AssertionError("Unused transforms"); }
@@ -0,0 +1,44 @@
package com.volmit.support;
import com.volmit.IrisFeature;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.config.PackSettings;
import com.volmit.host.WorldStates;
import com.volmit.resource.PackResources;
import com.volmit.world.PackWorld;
import java.util.List;
import java.util.function.Function;
/** A world for tests: the test seed, no resources, no declared settings, and a real state store. */
public final class TestWorld implements PackWorld, AutoCloseable {
private final WorldStates states = new WorldStates();
@Override
public long seed() {
return TestContexts.SEED;
}
@Override
public PackResources resources() {
throw new AssertionError("Unused resources");
}
@Override
public PackSettings settings() {
return new PackSettings() {
public <F extends IrisFeature> List<Entry<F>> declared(Class<F> featureType) {
return List.of();
}
};
}
@Override
public <T> T state(Class<T> type, Function<? super PackWorld, ? extends T> create) {
return states.state(type, () -> create.apply(this));
}
@Override
public void close() {
states.close();
}
}