mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-28 16:54:04 +00:00
Merge wave1/a1
This commit is contained in:
commit
adb848bf9f
29 files changed
+1286
-17
No files matched your search
@@ -5,6 +5,7 @@ import com.volmit.mantle.MantleKey;
|
||||
import com.volmit.mantle.MantleLifetime;
|
||||
import com.volmit.object.ObjectGeneratorFactory;
|
||||
import com.volmit.resource.ResourceKind;
|
||||
import com.volmit.service.Service;
|
||||
import com.volmit.stage.StageGraph;
|
||||
import com.volmit.validation.Validator;
|
||||
|
||||
@@ -42,4 +43,12 @@ public interface FeatureRegistry {
|
||||
|
||||
/** Adds a check the host runs over the whole pack wherever it validates packs. */
|
||||
void registerValidator(Validator validator);
|
||||
|
||||
/** Adds hooks the host calls when it loads the pack and starts or stops a world with it. */
|
||||
void registerLifecycle(ModuleLifecycle lifecycle);
|
||||
|
||||
/** Provides {@code service}, an interface marked {@link Service}, with {@code provider}. A service whose providers
|
||||
* are {@link com.volmit.service.Providers#ONE} fails the pack load when a second module provides it, naming both.
|
||||
*/
|
||||
<S> void registerService(Class<S> service, S provider);
|
||||
}
|
||||
@@ -17,7 +17,7 @@ public interface IrisModule {
|
||||
void install(StageGraph graph);
|
||||
|
||||
/** Registers non-stage contributions: geometry generators, mantle layers, settings no stage names, pack
|
||||
* resource kinds and validators.
|
||||
* resource kinds, validators, lifecycle hooks and services.
|
||||
*/
|
||||
default void register(FeatureRegistry registry) {}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.volmit;
|
||||
|
||||
import com.volmit.config.PackSettings;
|
||||
import com.volmit.resource.PackResources;
|
||||
import com.volmit.world.PackWorld;
|
||||
|
||||
/** What a module does when the host loads a pack and starts or stops a world with it. Every hook does nothing by
|
||||
* default. Modules register it with {@link FeatureRegistry#registerLifecycle}; a module class may implement it and
|
||||
* register itself.
|
||||
*
|
||||
* <p>Order: {@link #packLoaded} for a pack snapshot before the first world using it starts, then
|
||||
* {@link #worldStarted} before that world generates anything, and {@link #worldStopped} when it stops. A hotload, or a
|
||||
* reload of the pack's resources while worlds run, stops each world of the old snapshot, loads the new snapshot and
|
||||
* starts its worlds again, with empty state (see {@link PackWorld}). The host calls the hooks of a pack's modules in
|
||||
* module id order and stops them in reverse, one hook at a time, on the thread that starts or stops the world.
|
||||
*
|
||||
* <p>Hooks keep what they build in the world's state ({@link PackWorld#state}), never in fields: a module instance may
|
||||
* serve several packs and worlds at once.
|
||||
*/
|
||||
public interface ModuleLifecycle {
|
||||
/** The pack's modules are installed and its resources can be read. {@code settings} holds every entry of every
|
||||
* dimension, region and biome of the pack, as validators see them. A hook that throws stops the pack's worlds from
|
||||
* starting, naming its module.
|
||||
*/
|
||||
default void packLoaded(PackResources resources, PackSettings settings) {}
|
||||
|
||||
/** {@code world} starts, before it generates anything: the place to build state eagerly, such as caches a world
|
||||
* would otherwise build on its first chunk. A hook that throws stops the world from starting, naming its module; the
|
||||
* modules that had started it already get {@link #worldStopped}.
|
||||
*/
|
||||
default void worldStarted(PackWorld world) {}
|
||||
|
||||
/** {@code world} stops: it generates nothing more with this pack snapshot. Its state is still readable here and is
|
||||
* closed afterwards. The host runs every module's hook even when one throws, then reports the failures.
|
||||
*/
|
||||
default void worldStopped(PackWorld world) {}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.volmit.generation;
|
||||
|
||||
import com.volmit.resource.PackResources;
|
||||
import com.volmit.world.PackWorld;
|
||||
|
||||
/** Host-owned invocation inputs. Views must not be retained or used by detached tasks.
|
||||
*
|
||||
@@ -10,4 +11,9 @@ import com.volmit.resource.PackResources;
|
||||
public interface InvocationContext {
|
||||
long worldSeed();
|
||||
PackResources resources();
|
||||
|
||||
/** The world this invocation generates, where modules keep their per-world state ({@link PackWorld#state}). An
|
||||
* invocation outside any world, such as an object a studio tool pastes, throws IllegalStateException.
|
||||
*/
|
||||
PackWorld world();
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import com.volmit.hunk.Hunk;
|
||||
import com.volmit.mantle.Mantle;
|
||||
import com.volmit.random.WorldRandom;
|
||||
import com.volmit.resource.PackResources;
|
||||
import com.volmit.world.PackWorld;
|
||||
import com.volmit.stage.ChunkStageContext;
|
||||
import com.volmit.stage.Stage;
|
||||
import com.volmit.world.TerrainSampler;
|
||||
@@ -65,6 +66,11 @@ final class ChunkInvocation implements ChunkStageContext {
|
||||
return inputs.worldSeed();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PackWorld world() {
|
||||
return inputs.world();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PackResources resources() {
|
||||
return inputs.resources();
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.service.Providers;
|
||||
import com.volmit.service.Service;
|
||||
import java.util.Collection;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
|
||||
/** Frozen registrations. Lists use lexical feature/layer/kind ID order, and validators are in module id order,
|
||||
* so nothing depends on discovery. Factory, codec and validator implementations must themselves obey their
|
||||
* concurrency contracts.
|
||||
/** Frozen registrations. Lists use lexical feature/layer/kind ID order, and validators, lifecycle hooks and service
|
||||
* providers are in module id order, each module's in the order it registered them, so nothing depends on discovery.
|
||||
* Factory, codec, validator, hook and provider implementations must themselves obey their concurrency contracts.
|
||||
*/
|
||||
public final class FeatureCatalog {
|
||||
private final Map<Class<?>, FeatureDescriptor<?>> settings;
|
||||
@@ -18,20 +21,24 @@ public final class FeatureCatalog {
|
||||
private final Map<String, MantleRegistration<?>> mantle;
|
||||
private final List<ResourceKindRegistration> resourceKinds;
|
||||
private final List<ValidatorRegistration> validators;
|
||||
private final List<LifecycleRegistration> lifecycles;
|
||||
private final List<ServiceRegistration> services;
|
||||
|
||||
FeatureCatalog(
|
||||
Map<Class<?>, FeatureDescriptor<?>> settings,
|
||||
Map<Class<?>, ObjectRegistration<?>> objects,
|
||||
Map<String, MantleRegistration<?>> mantle,
|
||||
Collection<ResourceKindRegistration> resourceKinds,
|
||||
List<ValidatorRegistration> validators) {
|
||||
List<ValidatorRegistration> validators,
|
||||
List<LifecycleRegistration> lifecycles,
|
||||
List<ServiceRegistration> services) {
|
||||
this.settings = Map.copyOf(settings);
|
||||
this.objects = Map.copyOf(objects);
|
||||
this.mantle = Map.copyOf(mantle);
|
||||
this.resourceKinds = sorted(resourceKinds, registration -> registration.kind().id());
|
||||
this.validators = validators.stream()
|
||||
.sorted(Comparator.comparing(registration -> registration.module().info().id()))
|
||||
.toList();
|
||||
this.validators = inModuleOrder(validators, ValidatorRegistration::module);
|
||||
this.lifecycles = inModuleOrder(lifecycles, LifecycleRegistration::module);
|
||||
this.services = inModuleOrder(services, ServiceRegistration::module);
|
||||
}
|
||||
|
||||
/** Settings types that activate stages; the host decodes them from pack JSON. */
|
||||
@@ -57,6 +64,47 @@ public final class FeatureCatalog {
|
||||
return validators;
|
||||
}
|
||||
|
||||
/** The lifecycle hooks modules registered, by module id, each module's in the order it registered them. */
|
||||
public List<LifecycleRegistration> lifecycles() {
|
||||
return lifecycles;
|
||||
}
|
||||
|
||||
/** Every provider of {@code service}, an interface marked {@link Service}, in module id order and each module's in the
|
||||
* order it registered them; empty when no module provides it.
|
||||
*/
|
||||
public <S> List<S> services(Class<S> service) {
|
||||
requireService(service);
|
||||
return services.stream()
|
||||
.filter(registration -> registration.service() == service)
|
||||
.map(registration -> service.cast(registration.provider()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/** The one provider of {@code service}, a service whose providers are {@link Providers#ONE}, if a module provides it. */
|
||||
public <S> Optional<S> service(Class<S> service) {
|
||||
if (requireService(service).value() != Providers.ONE) {
|
||||
throw new IllegalArgumentException("Service " + service.getName() + " may have several providers; ask for all of"
|
||||
+ " them with services(...)");
|
||||
}
|
||||
return services(service).stream().findFirst();
|
||||
}
|
||||
|
||||
/** The {@link Service} annotation of {@code type}, which must be an interface carrying one. */
|
||||
static Service requireService(Class<?> type) {
|
||||
var service = type.isInterface() ? type.getAnnotation(Service.class) : null;
|
||||
if (service == null) {
|
||||
throw new IllegalArgumentException(type.getName() + " is not a service: services are interfaces marked @"
|
||||
+ Service.class.getName());
|
||||
}
|
||||
return service;
|
||||
}
|
||||
|
||||
private static <T> List<T> inModuleOrder(List<T> registrations, Function<? super T, DiscoveredModule> module) {
|
||||
return registrations.stream()
|
||||
.sorted(Comparator.comparing(registration -> module.apply(registration).info().id()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static <T, K extends Comparable<? super K>> List<T> sorted(
|
||||
Collection<T> registrations,
|
||||
Function<? super T, ? extends K> key) {
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import com.volmit.ModuleLifecycle;
|
||||
import java.util.Objects;
|
||||
|
||||
/** Lifecycle hooks and the module that registered them, which the host names when a hook fails. */
|
||||
public record LifecycleRegistration(ModuleLifecycle lifecycle, DiscoveredModule module) {
|
||||
public LifecycleRegistration {
|
||||
Objects.requireNonNull(lifecycle, "lifecycle");
|
||||
Objects.requireNonNull(module, "module");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import com.volmit.config.PackSettings;
|
||||
import com.volmit.resource.PackResources;
|
||||
import com.volmit.world.PackWorld;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/** Calls the lifecycle hooks of one pack's modules ({@link FeatureCatalog#lifecycles()}) the way
|
||||
* {@link com.volmit.ModuleLifecycle} promises: loading and starting in module id order, stopping in reverse.
|
||||
*
|
||||
* <pre>{@code
|
||||
* var lifecycles = new LifecycleRunner(pack.catalog());
|
||||
* lifecycles.packLoaded(resources, packSettings); // once per pack snapshot, before its first world starts
|
||||
* lifecycles.worldStarted(world); // before the world generates anything
|
||||
* ...
|
||||
* lifecycles.worldStopped(world); // then close the world's state
|
||||
* }</pre>
|
||||
*
|
||||
* A failure names the module whose hook failed. The runner keeps no state: the host decides when a snapshot is loaded
|
||||
* and which worlds run, and calls one method at a time per world.
|
||||
*/
|
||||
public final class LifecycleRunner {
|
||||
private final List<LifecycleRegistration> lifecycles;
|
||||
|
||||
public LifecycleRunner(FeatureCatalog catalog) {
|
||||
this.lifecycles = Objects.requireNonNull(catalog, "catalog").lifecycles();
|
||||
}
|
||||
|
||||
/** Runs every {@code packLoaded} hook in order; the first that throws ends the run with an IllegalStateException
|
||||
* naming its module, and the hooks after it do not run.
|
||||
*/
|
||||
public void packLoaded(PackResources resources, PackSettings settings) {
|
||||
Objects.requireNonNull(resources, "resources");
|
||||
Objects.requireNonNull(settings, "settings");
|
||||
for (var registration : lifecycles) {
|
||||
try {
|
||||
registration.lifecycle().packLoaded(resources, settings);
|
||||
} catch (RuntimeException failure) {
|
||||
throw failed("loading pack " + resources.packId(), registration, failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs every {@code worldStarted} hook in order. When one throws, the modules started before it are stopped again,
|
||||
* in reverse, and an IllegalStateException naming the failed module is thrown, with failures of those stops
|
||||
* suppressed in it.
|
||||
*/
|
||||
public void worldStarted(PackWorld world) {
|
||||
Objects.requireNonNull(world, "world");
|
||||
for (int index = 0; index < lifecycles.size(); index++) {
|
||||
var registration = lifecycles.get(index);
|
||||
try {
|
||||
registration.lifecycle().worldStarted(world);
|
||||
} catch (RuntimeException failure) {
|
||||
var startFailure = failed("starting a world", registration, failure);
|
||||
stopInReverse(world, index - 1, startFailure);
|
||||
throw startFailure;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs every {@code worldStopped} hook in reverse order, each even when an earlier one threw; afterwards throws the
|
||||
* first failure, naming its module, with the later ones suppressed.
|
||||
*/
|
||||
public void worldStopped(PackWorld world) {
|
||||
Objects.requireNonNull(world, "world");
|
||||
IllegalStateException failure = stopInReverse(world, lifecycles.size() - 1, null);
|
||||
if (failure != null) {
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
/** Stops the modules from {@code last} down to the first, collecting failures into {@code failure}. */
|
||||
private IllegalStateException stopInReverse(PackWorld world, int last, IllegalStateException failure) {
|
||||
for (int index = last; index >= 0; index--) {
|
||||
var registration = lifecycles.get(index);
|
||||
try {
|
||||
registration.lifecycle().worldStopped(world);
|
||||
} catch (RuntimeException stopFailure) {
|
||||
var named = failed("stopping a world", registration, stopFailure);
|
||||
if (failure == null) {
|
||||
failure = named;
|
||||
} else {
|
||||
failure.addSuppressed(named);
|
||||
}
|
||||
}
|
||||
}
|
||||
return failure;
|
||||
}
|
||||
|
||||
private static IllegalStateException failed(String action, LifecycleRegistration registration, RuntimeException cause) {
|
||||
return new IllegalStateException("Module " + registration.module() + " failed while " + action + ": " + cause, cause);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import com.volmit.generation.MantleGenerationContext;
|
||||
import com.volmit.mantle.Mantle;
|
||||
import com.volmit.random.WorldRandom;
|
||||
import com.volmit.resource.PackResources;
|
||||
import com.volmit.world.PackWorld;
|
||||
import com.volmit.stage.MantleStageContext;
|
||||
import com.volmit.stage.Stage;
|
||||
import com.volmit.world.TerrainSampler;
|
||||
@@ -59,6 +60,11 @@ final class MantleInvocation implements MantleStageContext {
|
||||
return inputs.worldSeed();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PackWorld world() {
|
||||
return inputs.world();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PackResources resources() {
|
||||
return inputs.resources();
|
||||
|
||||
@@ -4,12 +4,14 @@ import com.volmit.FeatureAttachment;
|
||||
import com.volmit.FeatureRegistry;
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleLifecycle;
|
||||
import com.volmit.mantle.MantleCodec;
|
||||
import com.volmit.mantle.MantleKey;
|
||||
import com.volmit.mantle.MantleLifetime;
|
||||
import com.volmit.object.ObjectGeneratorFactory;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.resource.ResourceKind;
|
||||
import com.volmit.service.Providers;
|
||||
import com.volmit.validation.Validator;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
@@ -26,7 +28,8 @@ import java.util.Set;
|
||||
* {@link #register(DiscoveredModule)}; object feature ids, mantle 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. A failed registration leaves the registry unchanged. A failed module callback
|
||||
* files. Lifecycle hooks and service providers are registered by the module that owns them; a service whose providers
|
||||
* are {@link Providers#ONE} has at most one. A failed registration leaves the registry unchanged. A failed module callback
|
||||
* invalidates the host's whole build. This does not decode JSON, discover modules or instantiate
|
||||
* settings.
|
||||
*/
|
||||
@@ -40,6 +43,8 @@ public final class ModuleRegistry implements FeatureRegistry {
|
||||
private final Map<Field, String> fields = new HashMap<>();
|
||||
private final Map<ResourceId, ResourceKindRegistration> resourceKinds = new HashMap<>();
|
||||
private final List<ValidatorRegistration> validators = new ArrayList<>();
|
||||
private final List<LifecycleRegistration> lifecycles = new ArrayList<>();
|
||||
private final List<ServiceRegistration> services = new ArrayList<>();
|
||||
private final Set<String> reservedFolders;
|
||||
private final List<DiscoveredModule> registered = new ArrayList<>();
|
||||
private FeatureCatalog catalog;
|
||||
@@ -129,6 +134,32 @@ public final class ModuleRegistry implements FeatureRegistry {
|
||||
validators.add(new ValidatorRegistration(validator, registering));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerLifecycle(ModuleLifecycle lifecycle) {
|
||||
checkOpen();
|
||||
Objects.requireNonNull(lifecycle, "lifecycle");
|
||||
requireRegistering("Lifecycle " + lifecycle);
|
||||
lifecycles.add(new LifecycleRegistration(lifecycle, registering));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <S> void registerService(Class<S> service, S provider) {
|
||||
checkOpen();
|
||||
Objects.requireNonNull(service, "service");
|
||||
Objects.requireNonNull(provider, "provider");
|
||||
requireRegistering("Provider of " + service.getName());
|
||||
var providers = FeatureCatalog.requireService(service).value();
|
||||
if (!service.isInstance(provider)) {
|
||||
throw new IllegalArgumentException("Provider " + provider + " of module " + registering + " does not implement "
|
||||
+ service.getName());
|
||||
}
|
||||
var added = new ServiceRegistration(service, provider, registering);
|
||||
if (providers == Providers.ONE) {
|
||||
requireNoProvider(added);
|
||||
}
|
||||
services.add(added);
|
||||
}
|
||||
|
||||
/** Catalogs a settings type named by a stage's when(...), whose owner {@link StageGraphBuilder}
|
||||
* has checked. Several stages, and the owner's {@link #registerSettings}, may name one type. Call
|
||||
* it after every module has registered, so the owner is known.
|
||||
@@ -149,7 +180,7 @@ public final class ModuleRegistry implements FeatureRegistry {
|
||||
|
||||
public FeatureCatalog freeze() {
|
||||
if (catalog == null) {
|
||||
catalog = new FeatureCatalog(settings, objects, mantle, resourceKinds.values(), validators);
|
||||
catalog = new FeatureCatalog(settings, objects, mantle, resourceKinds.values(), validators, lifecycles, services);
|
||||
}
|
||||
return catalog;
|
||||
}
|
||||
@@ -179,6 +210,23 @@ public final class ModuleRegistry implements FeatureRegistry {
|
||||
+ info.idPrefix() + ", the id of its registering module " + registering);
|
||||
}
|
||||
|
||||
private void requireRegistering(String registration) {
|
||||
if (registering == null) {
|
||||
throw new IllegalStateException(registration + " registered outside IrisModule.register");
|
||||
}
|
||||
}
|
||||
|
||||
/** A service a pack has one provider of: a second provider, from this module or another, fails. */
|
||||
private void requireNoProvider(ServiceRegistration added) {
|
||||
for (var existing : services) {
|
||||
if (existing.service() == added.service()) {
|
||||
throw new IllegalArgumentException("Service " + added.service().getName() + " is provided by module "
|
||||
+ existing.module() + " already, and module " + added.module() + " provides it too; a pack has"
|
||||
+ " one provider of it (Providers.ONE), so remove one of them");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One id, one type and one folder per kind: the host finds resources by type and reads each folder as one kind. */
|
||||
private void requireUnclaimedKind(ResourceKindRegistration added) {
|
||||
var kind = added.kind();
|
||||
|
||||
@@ -8,6 +8,7 @@ import com.volmit.placement.PlacementContext;
|
||||
import com.volmit.placement.PlacementRequest;
|
||||
import com.volmit.random.WorldRandom;
|
||||
import com.volmit.resource.PackResources;
|
||||
import com.volmit.world.PackWorld;
|
||||
import com.volmit.stage.BlockStageContext;
|
||||
import com.volmit.stage.Stage;
|
||||
import com.volmit.world.BlockView;
|
||||
@@ -111,6 +112,11 @@ final class PlacementInvocation implements BlockStageContext {
|
||||
return inputs.worldSeed();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PackWorld world() {
|
||||
return inputs.world();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PackResources resources() {
|
||||
return inputs.resources();
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/** One provider of a service and the module that registered it. */
|
||||
public record ServiceRegistration(Class<?> service, Object provider, DiscoveredModule module) {
|
||||
public ServiceRegistration {
|
||||
Objects.requireNonNull(service, "service");
|
||||
Objects.requireNonNull(provider, "provider");
|
||||
Objects.requireNonNull(module, "module");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "provider of " + service.getName() + " from module " + module;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Deque;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/** The reference store behind {@link com.volmit.world.PackWorld#state}: one instance per type, created once, closed
|
||||
* with the world. A host's world implementation keeps one per world and passes {@code state} calls on, binding the
|
||||
* world into the factory.
|
||||
*
|
||||
* <p>Reads of existing state take no lock. Creation runs under the store's lock, so each type is created once even
|
||||
* when threads race; a factory may ask for other state on its own thread (the lock is re-entrant), and a type asked
|
||||
* for again while it is being created fails instead of recursing. {@link #close()} closes every {@link AutoCloseable}
|
||||
* state, newest first, and ends the store.
|
||||
*/
|
||||
public final class WorldStates implements AutoCloseable {
|
||||
private final Map<Class<?>, Object> states = new ConcurrentHashMap<>();
|
||||
private final List<Object> createdInOrder = new ArrayList<>();
|
||||
private final Deque<Class<?>> creating = new ArrayDeque<>();
|
||||
private final Object lock = new Object();
|
||||
private boolean closed;
|
||||
|
||||
/** The {@code type} state, created by {@code create} the first time it is asked for. See {@link com.volmit.world.PackWorld#state}. */
|
||||
public <T> T state(Class<T> type, Supplier<? extends T> create) {
|
||||
Objects.requireNonNull(type, "type");
|
||||
Objects.requireNonNull(create, "create");
|
||||
Object existing = states.get(type);
|
||||
if (existing != null) {
|
||||
return type.cast(existing);
|
||||
}
|
||||
synchronized (lock) {
|
||||
requireOpen(type);
|
||||
existing = states.get(type);
|
||||
if (existing != null) {
|
||||
return type.cast(existing);
|
||||
}
|
||||
return create(type, create);
|
||||
}
|
||||
}
|
||||
|
||||
/** Closes every {@link AutoCloseable} state, the newest first, even when one fails, then throws the first failure
|
||||
* with the others suppressed. Asking for state afterwards throws. Closing twice does nothing.
|
||||
*/
|
||||
@Override
|
||||
public void close() {
|
||||
List<Object> closing;
|
||||
synchronized (lock) {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
closed = true;
|
||||
closing = new ArrayList<>(createdInOrder);
|
||||
createdInOrder.clear();
|
||||
states.clear();
|
||||
}
|
||||
RuntimeException failure = null;
|
||||
for (int index = closing.size() - 1; index >= 0; index--) {
|
||||
failure = closeState(closing.get(index), failure);
|
||||
}
|
||||
if (failure != null) {
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T create(Class<T> type, Supplier<? extends T> create) {
|
||||
if (creating.contains(type)) {
|
||||
throw new IllegalStateException("World state " + type.getName() + " was asked for while it is being created: "
|
||||
+ creationChain(type));
|
||||
}
|
||||
creating.push(type);
|
||||
try {
|
||||
T created = type.cast(Objects.requireNonNull(create.get(), () -> "The factory of world state " + type.getName()
|
||||
+ " returned null"));
|
||||
states.put(type, created);
|
||||
createdInOrder.add(created);
|
||||
return created;
|
||||
} finally {
|
||||
creating.pop();
|
||||
}
|
||||
}
|
||||
|
||||
private String creationChain(Class<?> repeated) {
|
||||
var chain = new ArrayList<Class<?>>(creating);
|
||||
Collections.reverse(chain);
|
||||
chain.add(repeated);
|
||||
return chain.stream().map(Class::getName).collect(Collectors.joining(" -> "));
|
||||
}
|
||||
|
||||
private void requireOpen(Class<?> type) {
|
||||
if (closed) {
|
||||
throw new IllegalStateException("World state " + type.getName() + " was asked for after the world stopped");
|
||||
}
|
||||
}
|
||||
|
||||
private static RuntimeException closeState(Object state, RuntimeException failure) {
|
||||
if (!(state instanceof AutoCloseable closeable)) {
|
||||
return failure;
|
||||
}
|
||||
try {
|
||||
closeable.close();
|
||||
return failure;
|
||||
} catch (Exception exception) {
|
||||
var closeFailure = new IllegalStateException("World state " + state.getClass().getName() + " failed to close: "
|
||||
+ exception, exception);
|
||||
if (failure == null) {
|
||||
return closeFailure;
|
||||
}
|
||||
failure.addSuppressed(closeFailure);
|
||||
return failure;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.volmit.service;
|
||||
|
||||
import com.volmit.world.BlockPosition;
|
||||
import java.util.Objects;
|
||||
|
||||
/** How a search for something in a world ended: found at a position, not there, or given up before covering the whole
|
||||
* area asked for.
|
||||
*/
|
||||
public sealed interface LocateResult {
|
||||
LocateResult NOT_FOUND = new NotFound();
|
||||
LocateResult SEARCH_LIMIT_REACHED = new SearchLimitReached();
|
||||
|
||||
static LocateResult found(BlockPosition position) {
|
||||
return new Found(position);
|
||||
}
|
||||
|
||||
/** Found at {@code position}: world X and Z, and Y the height above the dimension's bottom. */
|
||||
record Found(BlockPosition position) implements LocateResult {
|
||||
public Found {
|
||||
Objects.requireNonNull(position, "position");
|
||||
}
|
||||
}
|
||||
|
||||
/** The whole area was searched and holds none. */
|
||||
record NotFound() implements LocateResult {}
|
||||
|
||||
/** The search stopped before covering the area, such as after checking as many candidates as it allows itself. */
|
||||
record SearchLimitReached() implements LocateResult {}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.volmit.service;
|
||||
|
||||
import com.volmit.world.PackWorld;
|
||||
import java.util.Set;
|
||||
|
||||
/** Which pack objects a module places in a chunk, predicted without generating it. The host's object search and its
|
||||
* studio tools ask every provider and use all the keys together.
|
||||
*/
|
||||
@Service(Providers.ALL)
|
||||
public interface ObjectsAt {
|
||||
/**
|
||||
* The keys of the pack objects this module would place in the chunk at {@code chunkX}, {@code chunkZ} (chunk
|
||||
* coordinates, world X and Z divided by 16), in the form packs write them ({@code trees/oak}). It is a prediction:
|
||||
* it may name an object whose placement the chunk's generation later rejects. Empty when the module places nothing
|
||||
* there.
|
||||
*/
|
||||
Set<String> objectsAt(PackWorld world, int chunkX, int chunkZ);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.volmit.service;
|
||||
|
||||
/** How the host combines the providers of one {@link Service}. A service chooses one; its javadoc says how the host
|
||||
* uses the answers. Providers are always in module id order, each module's in the order it registered them, so the
|
||||
* outcome never depends on how modules were discovered.
|
||||
*/
|
||||
public enum Providers {
|
||||
/** The host asks every provider and combines their answers, such as the objects each module places in a chunk. */
|
||||
ALL,
|
||||
/** The host asks the providers in order until one answers, such as the module that knows a structure key. A provider
|
||||
* that has no answer says so in the service's own terms (an empty result) and the next one is asked.
|
||||
*/
|
||||
FIRST,
|
||||
/** A pack has at most one provider. A second module registering one fails the pack load, naming both modules. */
|
||||
ONE
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.volmit.service;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/** Marks an interface as a service: a capability modules provide and the host looks up, such as finding a module's
|
||||
* structures, instead of knowing the feature behind it. Modules register providers with
|
||||
* {@link com.volmit.FeatureRegistry#registerService}; the host gets them from the pack's catalog.
|
||||
*
|
||||
* <p>Providers hold no state of their own: a provider is shared by every world, and the host may call it from any
|
||||
* thread, also from several at once. A provider keeps what it needs in the world's state store
|
||||
* ({@link com.volmit.world.PackWorld#state}), which is why service methods take the world. Services compute answers;
|
||||
* they never act on the platform themselves: what should happen in the world comes back as a value the host carries out
|
||||
* on the right thread.
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.TYPE)
|
||||
public @interface Service {
|
||||
/** How the host treats several modules providing this service. */
|
||||
Providers value();
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.volmit.service;
|
||||
|
||||
import com.volmit.resource.PackResources;
|
||||
import com.volmit.world.PackWorld;
|
||||
import java.util.Set;
|
||||
|
||||
/** Finds the structures a module places, for the host's structure commands and index. Structures are named by their
|
||||
* keys, in the form packs write them ({@code castle}, {@code villages/plains}). The host asks the providers in order and
|
||||
* sends a key to the first that can locate it in the world.
|
||||
*/
|
||||
@Service(Providers.FIRST)
|
||||
public interface StructureLocator {
|
||||
/** Every structure key of the pack this module knows, placed in a world or not, such as one per structure file. The
|
||||
* host lists them in its index of the structures a pack has.
|
||||
*/
|
||||
Set<String> structures(PackResources pack);
|
||||
|
||||
/** The keys of the structures this module places in {@code world} and can find with {@link #locate}: commands offer
|
||||
* them and send a search for one of them here. A structure no placement of the world uses is not among them.
|
||||
*/
|
||||
Set<String> locatable(PackWorld world);
|
||||
|
||||
/**
|
||||
* The start of structure {@code key} nearest to the column {@code fromX}, {@code fromZ} (world coordinates), searched
|
||||
* up to {@code maxRadiusChunks} chunks away from it. The position is the structure's origin: world X and Z, and Y the
|
||||
* height above the dimension's bottom of its base. Called with a key from {@link #locatable}. May take long; the
|
||||
* host calls it off the server's main thread.
|
||||
*/
|
||||
LocateResult locate(PackWorld world, String key, int fromX, int fromZ, int maxRadiusChunks);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.volmit.world;
|
||||
|
||||
import com.volmit.config.PackSettings;
|
||||
import com.volmit.resource.PackResources;
|
||||
import java.util.function.Function;
|
||||
|
||||
/** One world the host generates with a pack, for as long as the pack stays loaded: the world's seed, the pack's
|
||||
* resources and settings, and the state modules keep for this world. Stage bodies reach it through
|
||||
* {@link com.volmit.generation.InvocationContext#world()}, services as their first argument and lifecycle hooks as
|
||||
* theirs ({@link com.volmit.ModuleLifecycle}).
|
||||
*
|
||||
* <p>A hotload ends the world: the host stops it ({@link com.volmit.ModuleLifecycle#worldStopped}) and starts a new
|
||||
* one with the reloaded pack and an empty state store. So does a reload of the pack's resources while the world runs,
|
||||
* such as after a tool rewrote some of its files. State therefore never outlives the resources it was built from.
|
||||
* Invocations that began before the restart finish with the world they began with.
|
||||
*
|
||||
* <p>Safe to use from any thread.
|
||||
*/
|
||||
public interface PackWorld {
|
||||
long seed();
|
||||
|
||||
/** The pack snapshot this world generates with. */
|
||||
PackResources resources();
|
||||
|
||||
/** The settings of the world's dimension and of every region and biome it can reach, as mantle reaches see them. */
|
||||
PackSettings settings();
|
||||
|
||||
/**
|
||||
* The world's one {@code type} instance, created by {@code create} the first time anyone asks for it. Modules keep
|
||||
* their caches and per-world workers here instead of in fields, since stage bodies and services are shared by every
|
||||
* world and every invocation. Use a class of the module as {@code type}, so two modules never share an entry.
|
||||
*
|
||||
* <p>{@code create} runs once per world, even when several threads ask at once; the others wait for it and get the
|
||||
* same instance. It may ask for other state of this world on its own thread, but must not wait for other threads
|
||||
* that ask for state, and a type that is asked for again while it is being created fails with
|
||||
* IllegalStateException. If {@code create} throws, nothing is kept and the next call tries again. A state that is
|
||||
* {@link AutoCloseable} is closed after the world stops, once nothing generates with it any more. After the world
|
||||
* stopped, asking for state throws IllegalStateException.
|
||||
*/
|
||||
<T> T state(Class<T> type, Function<? super PackWorld, ? extends T> create);
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user