mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-28 08:44:50 +00:00
Load pack modules from <pack>/modules jars
A module jar names its IrisModule class in META-INF/services/com.volmit.IrisModule. PackModules scans <pack>/modules/*.jar in file name order, loads all jars of a pack through one URLClassLoader whose parent is the API's loader, and closes it when the pack unloads. Modules now reach LoadedModules as DiscoveredModule (module plus origin), so errors name the offending jar: missing or multiple entry points, broken entry classes, duplicate module ids and foreign stage namespaces.
This commit is contained in:
1 parent
e918cd44a8
commit
6388173f19
12 files changed
+606
-29
No files matched your search
@@ -7,6 +7,7 @@ import com.volmit.example.chunk.TerrainModule;
|
||||
import com.volmit.host.ArrayHunk;
|
||||
import com.volmit.host.ChunkRunner;
|
||||
import com.volmit.host.ConfiguredSettings;
|
||||
import com.volmit.host.DiscoveredModule;
|
||||
import com.volmit.host.StageGraphBuilder;
|
||||
import com.volmit.hunk.Hunk;
|
||||
import com.volmit.stage.Pipeline;
|
||||
@@ -25,8 +26,8 @@ class ChunkPipelineTest {
|
||||
|
||||
private static ChunkRunner runner() {
|
||||
var builder = new StageGraphBuilder();
|
||||
builder.install(new GrassModule());
|
||||
builder.install(new TerrainModule());
|
||||
builder.install(DiscoveredModule.builtIn(new GrassModule()));
|
||||
builder.install(DiscoveredModule.builtIn(new TerrainModule()));
|
||||
var graph = builder.resolve(Pipeline.CHUNK);
|
||||
assertEquals(List.of("iris:terrain/surface", "example:grass/top"),
|
||||
graph.stages().stream().map(stage -> stage.stage().id().toString()).toList());
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.volmit.ModuleInfo;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.example.placement.*;
|
||||
import com.volmit.host.ConfiguredSettings;
|
||||
import com.volmit.host.DiscoveredModule;
|
||||
import com.volmit.host.LoadedModules;
|
||||
import com.volmit.host.PlacementRunner;
|
||||
import com.volmit.host.ResolvedGraph;
|
||||
@@ -83,7 +84,7 @@ class PlacementLifecyclePortTest {
|
||||
|
||||
private static ResolvedGraph resolve(List<? extends IrisModule> modules) {
|
||||
var builder = new StageGraphBuilder();
|
||||
modules.forEach(builder::install);
|
||||
modules.stream().map(DiscoveredModule::builtIn).forEach(builder::install);
|
||||
return builder.resolve(Pipeline.PLACEMENT);
|
||||
}
|
||||
|
||||
@@ -196,7 +197,7 @@ class PlacementLifecyclePortTest {
|
||||
|
||||
@Test
|
||||
void loadingThePortCatalogsEveryConditioningSettingsType() {
|
||||
var loaded = LoadedModules.load(PlacementModules.all(), Map.of());
|
||||
var loaded = LoadedModules.load(PlacementModules.builtIns(), Map.of());
|
||||
|
||||
assertEquals(List.of("example:moss", "iris:snow", "iris:stilt"),
|
||||
loaded.catalog().settings().stream().map(settings -> settings.id().toString()).toList());
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.volmit.example.placement;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.host.DiscoveredModule;
|
||||
import java.util.List;
|
||||
|
||||
public final class PlacementModules {
|
||||
@@ -11,4 +12,9 @@ public final class PlacementModules {
|
||||
return List.of(new PrepareModule(), new AnchorModule(), new BlocksModule(),
|
||||
new StiltModule(), new SnowModule(), new MossModule());
|
||||
}
|
||||
|
||||
/** {@link #all()} as modules shipped with the host. */
|
||||
public static List<DiscoveredModule> builtIns() {
|
||||
return all().stream().map(DiscoveredModule::builtIn).toList();
|
||||
}
|
||||
}
|
||||
@@ -73,14 +73,14 @@ class ModuleRegistryTest {
|
||||
public void install(StageGraph graph) { graph.define(WORK).when(One.class).run((context, one) -> {}); }
|
||||
public void register(FeatureRegistry registry) { registry.registerObject(Two.class, ignored -> context -> null); }
|
||||
};
|
||||
var loaded = LoadedModules.load(List.of(conditioned), Map.of());
|
||||
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(conditioned)), Map.of());
|
||||
assertEquals(List.of("test:one"), loaded.catalog().settings().stream().map(value -> value.id().toString()).toList());
|
||||
assertEquals(1, loaded.catalog().objects().size());
|
||||
assertEquals(1, loaded.placement().stages().size());
|
||||
assertTrue(loaded.chunk().stages().isEmpty());
|
||||
|
||||
var reserved = Map.of(FeatureAttachment.Target.BIOME, Set.of("shared"));
|
||||
assertThrows(IllegalArgumentException.class, () -> LoadedModules.load(List.of(conditioned), reserved));
|
||||
assertThrows(IllegalArgumentException.class, () -> LoadedModules.load(List.of(DiscoveredModule.builtIn(conditioned)), reserved));
|
||||
}
|
||||
|
||||
private static MantleCodec<String> codec(int version) {
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import com.volmit.example.placement.PlacementModules;
|
||||
import com.volmit.support.TestModuleJar;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import static com.volmit.support.TestModuleJar.module;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PackModulesTest {
|
||||
private static final String ALPHA_MEMBERS =
|
||||
"public static final PlacementStage<Void> MARK = Stage.placement(\"alpha:core/mark\");";
|
||||
private static final String NO_MEMBERS = "";
|
||||
private static final String NO_STAGES = "";
|
||||
|
||||
@TempDir
|
||||
Path pack;
|
||||
|
||||
private static String origin(String jarName) {
|
||||
return Path.of(PackModules.MODULES_DIRECTORY, jarName).toString();
|
||||
}
|
||||
|
||||
private static LoadedModules loadWithBuiltIns(PackModules packModules) {
|
||||
var modules = new ArrayList<>(PlacementModules.builtIns());
|
||||
modules.addAll(packModules.modules());
|
||||
return LoadedModules.load(modules, Map.of());
|
||||
}
|
||||
|
||||
private static String failure(Executable load) {
|
||||
return assertThrows(IllegalArgumentException.class, load).getMessage();
|
||||
}
|
||||
|
||||
private static void assertMentions(String message, String... parts) {
|
||||
for (var part : parts) assertTrue(message.contains(part), message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void packWithoutModulesDirectoryHasNoModules() {
|
||||
try (var modules = PackModules.load(pack)) {
|
||||
assertTrue(modules.modules().isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadsOneModulePerJarInFileNameOrderAndResolvesThemWithBuiltIns(@TempDir Path build) throws Exception {
|
||||
var alpha = module("pack.alpha.AlphaModule", "alpha:core", ALPHA_MEMBERS,
|
||||
"graph.define(MARK).requires(com.volmit.example.placement.AnchorModule.HEIGHT).run(context -> {});");
|
||||
var alphaJar = alpha.writeInto(build, "alpha.jar");
|
||||
module("pack.beta.BetaModule", "beta:core", NO_MEMBERS,
|
||||
"graph.define(Stage.placement(\"beta:core/use\")).requires(pack.alpha.AlphaModule.MARK).run(context -> {});")
|
||||
.compileAgainst(alphaJar)
|
||||
.writeInto(pack, "beta.jar");
|
||||
alpha.writeInto(pack, "alpha.jar");
|
||||
Files.writeString(pack.resolve(PackModules.MODULES_DIRECTORY).resolve("notes.txt"), "not a module");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertEquals(List.of(origin("alpha.jar"), origin("beta.jar")),
|
||||
packModules.modules().stream().map(DiscoveredModule::origin).toList());
|
||||
assertEquals(List.of("alpha:core", "beta:core"),
|
||||
packModules.modules().stream().map(found -> found.module().info().id().toString()).toList());
|
||||
assertNotSame(PackModules.class.getClassLoader(), packModules.modules().getFirst().module().getClass().getClassLoader());
|
||||
|
||||
var order = loadWithBuiltIns(packModules).placement().stages().stream()
|
||||
.map(stage -> stage.stage().id().toString()).toList();
|
||||
assertTrue(order.indexOf("iris:anchor/height") < order.indexOf("alpha:core/mark"), order.toString());
|
||||
assertTrue(order.indexOf("alpha:core/mark") < order.indexOf("beta:core/use"), order.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void closingThePackStopsItsClassLoaderFromLoadingMoreClasses() throws Exception {
|
||||
module("pack.gamma.GammaModule", "gamma:core", NO_MEMBERS, NO_STAGES)
|
||||
.source("pack.gamma.Unused", "package pack.gamma; final class Unused {}")
|
||||
.writeInto(pack, "gamma.jar");
|
||||
|
||||
ClassLoader loader;
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
loader = packModules.modules().getFirst().module().getClass().getClassLoader();
|
||||
assertNotNull(loader.loadClass("pack.gamma.GammaModule"));
|
||||
}
|
||||
assertThrows(ClassNotFoundException.class, () -> loader.loadClass("pack.gamma.Unused"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void jarWithoutEntryPointFails() {
|
||||
new TestModuleJar().source("pack.Lonely", "package pack; public final class Lonely {}").writeInto(pack, "lonely.jar");
|
||||
|
||||
assertMentions(failure(() -> PackModules.load(pack)),
|
||||
"Module jar " + origin("lonely.jar") + " has no entry point", ModuleJar.ENTRY_POINT_FILE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void jarNamingSeveralEntryPointsFails() {
|
||||
module("pack.First", "first:core", NO_MEMBERS, NO_STAGES)
|
||||
.source("pack.Second", "package pack; public final class Second {}")
|
||||
.entryPoint("pack.Second")
|
||||
.writeInto(pack, "two.jar");
|
||||
|
||||
assertMentions(failure(() -> PackModules.load(pack)),
|
||||
"Module jar " + origin("two.jar") + " names 2 entry points [pack.First, pack.Second]");
|
||||
}
|
||||
|
||||
@Test
|
||||
void brokenEntryClassesFailNamingTheJar() {
|
||||
var missing = pack.resolve("missing");
|
||||
new TestModuleJar().entryPoint("pack.Missing").writeInto(missing, "missing.jar");
|
||||
assertMentions(failure(() -> PackModules.load(missing)),
|
||||
"Module jar " + origin("missing.jar") + " has a broken entry point pack.Missing: class cannot be loaded");
|
||||
|
||||
var unrelated = pack.resolve("unrelated");
|
||||
new TestModuleJar().source("pack.Plain", "package pack; public final class Plain {}")
|
||||
.entryPoint("pack.Plain").writeInto(unrelated, "plain.jar");
|
||||
assertMentions(failure(() -> PackModules.load(unrelated)),
|
||||
"Module jar " + origin("plain.jar") + " has a broken entry point pack.Plain: class does not implement com.volmit.IrisModule");
|
||||
|
||||
var throwing = pack.resolve("throwing");
|
||||
module("pack.Throwing", "throwing:core", "public Throwing() { throw new IllegalStateException(\"boom\"); }", NO_STAGES)
|
||||
.writeInto(throwing, "throwing.jar");
|
||||
assertMentions(failure(() -> PackModules.load(throwing)),
|
||||
"Module jar " + origin("throwing.jar") + " has a broken entry point pack.Throwing: constructor threw",
|
||||
"boom");
|
||||
|
||||
var shadowed = pack.resolve("shadowed");
|
||||
new TestModuleJar().entryPoint("com.volmit.example.placement.MossModule").writeInto(shadowed, "moss.jar");
|
||||
assertMentions(failure(() -> PackModules.load(shadowed)),
|
||||
"Module jar " + origin("moss.jar") + " has a broken entry point com.volmit.example.placement.MossModule",
|
||||
"not from this jar");
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateModuleIdsAcrossJarsFailNamingBothJars() {
|
||||
module("pack.one.Duplicate", "dup:core", NO_MEMBERS, NO_STAGES).writeInto(pack, "one.jar");
|
||||
module("pack.two.Duplicate", "dup:core", NO_MEMBERS, NO_STAGES).writeInto(pack, "two.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of())),
|
||||
"Duplicate module dup:core from " + origin("two.jar") + "; already loaded from " + origin("one.jar"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateOfABuiltInModuleFailsNamingTheJar() {
|
||||
module("pack.Moss", "example:moss", NO_MEMBERS, NO_STAGES).writeInto(pack, "moss.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertMentions(failure(() -> loadWithBuiltIns(packModules)),
|
||||
"Duplicate module example:moss from " + origin("moss.jar") + "; already loaded from host classpath");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void foreignStageNamespaceFailsNamingTheJar() {
|
||||
module("pack.Foreign", "mine:core", NO_MEMBERS,
|
||||
"graph.define(Stage.placement(\"theirs:core/work\")).run(context -> {});")
|
||||
.writeInto(pack, "foreign.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of())),
|
||||
"must use namespace 'mine' of its defining module mine:core from " + origin("foreign.jar"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,7 @@ class StageGraphTest {
|
||||
|
||||
private static ResolvedGraph resolve(Pipeline pipeline, IrisModule... modules) {
|
||||
var builder = new StageGraphBuilder();
|
||||
for (var module : modules) builder.install(module);
|
||||
for (var module : modules) builder.install(DiscoveredModule.builtIn(module));
|
||||
return builder.resolve(pipeline);
|
||||
}
|
||||
|
||||
@@ -207,8 +207,8 @@ class StageGraphTest {
|
||||
|
||||
var module = module("test:twice", stages -> {});
|
||||
var builder = new StageGraphBuilder();
|
||||
builder.install(module);
|
||||
assertThrows(IllegalArgumentException.class, () -> builder.install(module));
|
||||
builder.install(DiscoveredModule.builtIn(module));
|
||||
assertThrows(IllegalArgumentException.class, () -> builder.install(DiscoveredModule.builtIn(module)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -268,7 +268,7 @@ class StageGraphTest {
|
||||
stages.define(Stage.placement("test:plain/work")).when(Unannotated.class).run((context, settings) -> {}))));
|
||||
|
||||
var retained = new ArrayList<StageGraph>();
|
||||
new StageGraphBuilder().install(module("test:retained", retained::add));
|
||||
new StageGraphBuilder().install(DiscoveredModule.builtIn(module("test:retained", retained::add)));
|
||||
assertThrows(IllegalStateException.class, () -> retained.getFirst().define(Stage.placement("test:retained/late")));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
package com.volmit.support;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.example.placement.AnchorModule;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarOutputStream;
|
||||
import java.util.jar.Manifest;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.tools.DiagnosticCollector;
|
||||
import javax.tools.JavaFileObject;
|
||||
import javax.tools.SimpleJavaFileObject;
|
||||
import javax.tools.ToolProvider;
|
||||
|
||||
/** Builds a real module jar from Java source at test time. Its classes are not on the test
|
||||
* classpath, so only a pack class loader can define them.
|
||||
*/
|
||||
public final class TestModuleJar {
|
||||
private static final String SERVICES_FILE = "META-INF/services/" + IrisModule.class.getName();
|
||||
|
||||
private final Map<String, String> sources = new LinkedHashMap<>();
|
||||
private final List<String> entryPoints = new ArrayList<>();
|
||||
private final List<Path> classpath = new ArrayList<>(List.of(classesOf(IrisModule.class), classesOf(AnchorModule.class)));
|
||||
|
||||
/** An entry class with the given module id whose install body may use {@code graph}. */
|
||||
public static TestModuleJar module(String className, String moduleId, String members, String install) {
|
||||
return new TestModuleJar().source(className, moduleSource(className, moduleId, members, install)).entryPoint(className);
|
||||
}
|
||||
|
||||
public TestModuleJar source(String className, String code) {
|
||||
sources.put(className, code);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Adds one line to the jar's entry point file. */
|
||||
public TestModuleJar entryPoint(String className) {
|
||||
entryPoints.add(className);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TestModuleJar compileAgainst(Path jar) {
|
||||
classpath.add(jar);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Writes {@code <packRoot>/modules/<jarName>} and returns its path. */
|
||||
public Path writeInto(Path packRoot, String jarName) {
|
||||
try {
|
||||
var jar = Files.createDirectories(packRoot.resolve("modules")).resolve(jarName);
|
||||
var classes = compile(Files.createTempDirectory(packRoot, "classes"));
|
||||
try (var output = new JarOutputStream(Files.newOutputStream(jar), new Manifest())) {
|
||||
writeClasses(output, classes);
|
||||
writeEntryPoints(output);
|
||||
}
|
||||
return jar;
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
private Path compile(Path classes) {
|
||||
if (sources.isEmpty()) return classes;
|
||||
var compiler = ToolProvider.getSystemJavaCompiler();
|
||||
var diagnostics = new DiagnosticCollector<JavaFileObject>();
|
||||
var units = sources.entrySet().stream().map(source -> new StringSource(source.getKey(), source.getValue())).toList();
|
||||
var options = List.of("-d", classes.toString(), "-proc:none", "-classpath",
|
||||
classpath.stream().map(Path::toString).collect(Collectors.joining(File.pathSeparator)));
|
||||
if (!compiler.getTask(null, null, diagnostics, options, null, units).call()) {
|
||||
throw new IllegalStateException("Test module does not compile: " + diagnostics.getDiagnostics());
|
||||
}
|
||||
return classes;
|
||||
}
|
||||
|
||||
private static void writeClasses(JarOutputStream output, Path classes) throws IOException {
|
||||
try (var files = Files.walk(classes)) {
|
||||
for (var file : files.filter(Files::isRegularFile).sorted().toList()) {
|
||||
output.putNextEntry(new JarEntry(classes.relativize(file).toString().replace(File.separatorChar, '/')));
|
||||
output.write(Files.readAllBytes(file));
|
||||
output.closeEntry();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void writeEntryPoints(JarOutputStream output) throws IOException {
|
||||
if (entryPoints.isEmpty()) return;
|
||||
output.putNextEntry(new JarEntry(SERVICES_FILE));
|
||||
output.write(("# entry point\n" + String.join("\n", entryPoints) + "\n").getBytes(StandardCharsets.UTF_8));
|
||||
output.closeEntry();
|
||||
}
|
||||
|
||||
private static String moduleSource(String className, String moduleId, String members, String install) {
|
||||
int dot = className.lastIndexOf('.');
|
||||
return """
|
||||
package %s;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.stage.*;
|
||||
|
||||
public final class %s implements IrisModule {
|
||||
%s
|
||||
|
||||
public ModuleInfo info() { return ModuleInfo.of("%s", "1.0.0"); }
|
||||
|
||||
public void install(StageGraph graph) { %s }
|
||||
}
|
||||
""".formatted(className.substring(0, dot), className.substring(dot + 1), members, moduleId, install);
|
||||
}
|
||||
|
||||
private static Path classesOf(Class<?> type) {
|
||||
try {
|
||||
return Path.of(type.getProtectionDomain().getCodeSource().getLocation().toURI());
|
||||
} catch (URISyntaxException exception) {
|
||||
throw new IllegalStateException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static final class StringSource extends SimpleJavaFileObject {
|
||||
private final String code;
|
||||
|
||||
StringSource(String className, String code) {
|
||||
super(URI.create("string:///" + className.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user