diff --git a/src/main/java/com/volmit/host/DiscoveredModule.java b/src/main/java/com/volmit/host/DiscoveredModule.java new file mode 100644 index 000000000..48ac392d3 --- /dev/null +++ b/src/main/java/com/volmit/host/DiscoveredModule.java @@ -0,0 +1,24 @@ +package com.volmit.host; + +import com.volmit.IrisModule; +import java.util.Objects; + +/** A module and where the host found it. Load errors name the origin so the author knows which + * jar to fix. + */ +public record DiscoveredModule(IrisModule module, String origin) { + static final String HOST_CLASSPATH = "host classpath"; + + public DiscoveredModule { + Objects.requireNonNull(module, "module"); + Objects.requireNonNull(origin, "origin"); + if (origin.isBlank()) { + throw new IllegalArgumentException("Blank module origin: " + module.getClass().getName()); + } + } + + /** A module that ships with the host instead of a pack. */ + public static DiscoveredModule builtIn(IrisModule module) { + return new DiscoveredModule(module, HOST_CLASSPATH); + } +} diff --git a/src/main/java/com/volmit/host/LoadedModules.java b/src/main/java/com/volmit/host/LoadedModules.java index 63eea6d50..c9c50556d 100644 --- a/src/main/java/com/volmit/host/LoadedModules.java +++ b/src/main/java/com/volmit/host/LoadedModules.java @@ -1,7 +1,6 @@ package com.volmit.host; import com.volmit.FeatureAttachment; -import com.volmit.IrisModule; import com.volmit.stage.Pipeline; import java.util.List; import java.util.Map; @@ -18,15 +17,15 @@ public record LoadedModules(FeatureCatalog catalog, ResolvedGraph placement, Res Objects.requireNonNull(chunk, "chunk"); } - /** Module discovery and version gating stay host work; pass the accepted modules here. */ + /** Pass the built-in modules together with {@link PackModules#modules()} of the pack. */ public static LoadedModules load( - List modules, + List modules, Map> reservedHostFields) { var registry = new ModuleRegistry(reservedHostFields); var stages = new StageGraphBuilder(); - for (var module : modules) { - stages.install(module); - module.register(registry); + for (var discovered : modules) { + stages.install(discovered); + discovered.module().register(registry); } stages.settingsTypes().forEach(registry::registerSettings); return new LoadedModules(registry.freeze(), stages.resolve(Pipeline.PLACEMENT), stages.resolve(Pipeline.CHUNK)); diff --git a/src/main/java/com/volmit/host/ModuleJar.java b/src/main/java/com/volmit/host/ModuleJar.java new file mode 100644 index 000000000..239eb7883 --- /dev/null +++ b/src/main/java/com/volmit/host/ModuleJar.java @@ -0,0 +1,136 @@ +package com.volmit.host; + +import com.volmit.IrisModule; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.UncheckedIOException; +import java.lang.reflect.InvocationTargetException; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.List; +import java.util.Objects; +import java.util.function.Predicate; +import java.util.jar.JarFile; + +/** One jar in a pack's modules directory and the entry class it names. + * + *

The entry point is the jar's own {@code META-INF/services/com.volmit.IrisModule} file, in + * the format {@link java.util.ServiceLoader} reads. The host reads that file from this jar only: + * {@code ServiceLoader} would also return providers from parent class loaders and could not tell + * which jar a broken entry came from. + */ +record ModuleJar(Path path, String origin, String entryClass) { + static final String ENTRY_POINT_FILE = "META-INF/services/" + IrisModule.class.getName(); + private static final String COMMENT_START = "#"; + + ModuleJar { + Objects.requireNonNull(path, "path"); + Objects.requireNonNull(origin, "origin"); + Objects.requireNonNull(entryClass, "entryClass"); + } + + /** Reads the single entry class a jar names. The origin is the jar path relative to its pack. */ + static ModuleJar read(Path packRoot, Path jar) { + var origin = packRoot.relativize(jar).toString(); + var entryClasses = readEntryClasses(jar, origin); + if (entryClasses.isEmpty()) { + throw new IllegalArgumentException("Module jar " + origin + " has no entry point; name its " + + IrisModule.class.getSimpleName() + " class in " + ENTRY_POINT_FILE); + } + if (entryClasses.size() > 1) { + throw new IllegalArgumentException("Module jar " + origin + " names " + entryClasses.size() + + " entry points " + entryClasses + "; one jar holds exactly one module"); + } + return new ModuleJar(jar, origin, entryClasses.getFirst()); + } + + URL url() { + try { + return path.toUri().toURL(); + } catch (MalformedURLException exception) { + throw new IllegalArgumentException("Module jar " + origin + " has no URL form", exception); + } + } + + /** Loads and instantiates the entry class through the pack's class loader. The class must come + * from this jar, so a copy on the host classpath cannot silently replace the jar's module. + */ + DiscoveredModule createModule(ClassLoader packLoader) { + var type = loadEntryClass(packLoader); + requireDefinedHere(type); + var module = instantiate(type); + requireIdentity(module); + return new DiscoveredModule(module, origin); + } + + private static List readEntryClasses(Path jar, String origin) { + try (var file = new JarFile(jar.toFile())) { + var entry = file.getJarEntry(ENTRY_POINT_FILE); + if (entry == null) return List.of(); + try (var reader = new BufferedReader(new InputStreamReader(file.getInputStream(entry), StandardCharsets.UTF_8))) { + return reader.lines() + .map(ModuleJar::withoutComment) + .map(String::strip) + .filter(Predicate.not(String::isEmpty)) + .distinct() + .toList(); + } + } catch (IOException exception) { + throw new UncheckedIOException("Module jar " + origin + " is not a readable jar", exception); + } + } + + private static String withoutComment(String line) { + int comment = line.indexOf(COMMENT_START); + return comment < 0 ? line : line.substring(0, comment); + } + + private Class loadEntryClass(ClassLoader packLoader) { + Class type; + try { + type = Class.forName(entryClass, false, packLoader); + } catch (ClassNotFoundException | LinkageError exception) { + throw brokenEntryPoint("class cannot be loaded: " + exception, exception); + } + if (!IrisModule.class.isAssignableFrom(type)) { + throw brokenEntryPoint("class does not implement " + IrisModule.class.getName(), null); + } + return type.asSubclass(IrisModule.class); + } + + private void requireDefinedHere(Class type) { + var source = type.getProtectionDomain().getCodeSource(); + var location = source == null ? null : source.getLocation(); + if (location == null || !location.toExternalForm().equals(url().toExternalForm())) { + throw brokenEntryPoint("class is loaded from " + location + ", not from this jar", null); + } + } + + private IrisModule instantiate(Class type) { + try { + return type.getConstructor().newInstance(); + } catch (InvocationTargetException exception) { + throw brokenEntryPoint("constructor threw " + exception.getCause(), exception.getCause()); + } catch (ReflectiveOperationException exception) { + throw brokenEntryPoint("class needs to be public and concrete with a public no-argument constructor", exception); + } catch (LinkageError exception) { + throw brokenEntryPoint("class cannot be initialized: " + exception, exception); + } + } + + private void requireIdentity(IrisModule module) { + try { + Objects.requireNonNull(module.info(), "info() returned null"); + } catch (RuntimeException | LinkageError exception) { + throw brokenEntryPoint("info() failed: " + exception, exception); + } + } + + private IllegalArgumentException brokenEntryPoint(String problem, Throwable cause) { + return new IllegalArgumentException("Module jar " + origin + " has a broken entry point " + + entryClass + ": " + problem, cause); + } +} diff --git a/src/main/java/com/volmit/host/PackModules.java b/src/main/java/com/volmit/host/PackModules.java new file mode 100644 index 000000000..da4fa096a --- /dev/null +++ b/src/main/java/com/volmit/host/PackModules.java @@ -0,0 +1,100 @@ +package com.volmit.host; + +import com.volmit.IrisModule; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; + +/** The module jars of one pack: every {@code /modules/*.jar}, one module per jar, ordered + * by file name so the result never depends on directory listing order. + * + *

All jars of a pack share one class loader whose parent is the loader of the API. A pack jar + * can therefore name another pack jar's stage constants in {@code requires(...)}, as well as + * those of built-in modules visible to the API. Packs do not see each other's classes. + * + *

Close this when the pack unloads, after dropping everything built from its modules, such as + * {@link LoadedModules}. Classes not loaded before then can no longer be loaded. + */ +public final class PackModules implements AutoCloseable { + public static final String MODULES_DIRECTORY = "modules"; + static final String JAR_EXTENSION = ".jar"; + + private final List modules; + private final URLClassLoader loader; + + private PackModules(List modules, URLClassLoader loader) { + this.modules = List.copyOf(modules); + this.loader = loader; + } + + /** Loads the modules of the pack at {@code packRoot}. A pack without a modules directory has + * no modules. Errors name the offending jar relative to the pack root. + */ + public static PackModules load(Path packRoot) { + Objects.requireNonNull(packRoot, "packRoot"); + var jars = findModuleJars(packRoot).stream() + .map(jar -> ModuleJar.read(packRoot, jar)) + .toList(); + var loader = newPackClassLoader(packRoot, jars); + try { + return new PackModules(createModules(jars, loader), loader); + } catch (RuntimeException | Error failure) { + closeAfterFailure(loader, failure); + throw failure; + } + } + + /** One module per jar, in jar file name order. */ + public List modules() { + return modules; + } + + @Override + public void close() { + try { + loader.close(); + } catch (IOException exception) { + throw new UncheckedIOException("Cannot close module class loader " + loader.getName(), exception); + } + } + + private static List findModuleJars(Path packRoot) { + var directory = packRoot.resolve(MODULES_DIRECTORY); + if (!Files.isDirectory(directory)) return List.of(); + try (var entries = Files.list(directory)) { + return entries + .filter(PackModules::isJar) + .sorted(Comparator.comparing(jar -> jar.getFileName().toString())) + .toList(); + } catch (IOException exception) { + throw new UncheckedIOException("Cannot list module jars in " + directory, exception); + } + } + + private static boolean isJar(Path path) { + return Files.isRegularFile(path) && path.getFileName().toString().endsWith(JAR_EXTENSION); + } + + private static URLClassLoader newPackClassLoader(Path packRoot, List jars) { + var urls = jars.stream().map(ModuleJar::url).toArray(URL[]::new); + return new URLClassLoader("pack:" + packRoot.getFileName(), urls, IrisModule.class.getClassLoader()); + } + + private static List createModules(List jars, ClassLoader loader) { + return jars.stream().map(jar -> jar.createModule(loader)).toList(); + } + + private static void closeAfterFailure(URLClassLoader loader, Throwable failure) { + try { + loader.close(); + } catch (IOException exception) { + failure.addSuppressed(exception); + } + } +} diff --git a/src/main/java/com/volmit/host/StageGraphBuilder.java b/src/main/java/com/volmit/host/StageGraphBuilder.java index 15c1b36c8..876a12da4 100644 --- a/src/main/java/com/volmit/host/StageGraphBuilder.java +++ b/src/main/java/com/volmit/host/StageGraphBuilder.java @@ -1,7 +1,6 @@ package com.volmit.host; import com.volmit.IrisFeature; -import com.volmit.IrisModule; import com.volmit.resource.ResourceId; import com.volmit.stage.BlockStage; import com.volmit.stage.BlockStageDefinition; @@ -15,25 +14,24 @@ import com.volmit.stage.StageDefinition; import com.volmit.stage.StageGraph; import java.util.Comparator; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.Set; /** Reference host collection of module stages. Install every module, then resolve each pipeline * once per pack load. Install order never affects the result. If a module's install throws, - * discard the whole builder: it may hold a partial module. + * discard the whole builder: it may hold a partial module. Errors about one module name its origin. */ public final class StageGraphBuilder implements StageGraph { private final Map declarations = new HashMap<>(); - private final Set modules = new HashSet<>(); + private final Map moduleOrigins = new HashMap<>(); private ResourceId installingModule; - public void install(IrisModule module) { - Objects.requireNonNull(module, "module"); + public void install(DiscoveredModule discovered) { + Objects.requireNonNull(discovered, "discovered"); + var module = discovered.module(); var moduleId = Objects.requireNonNull(module.info(), "module info").id(); - claimModule(moduleId); + claimModule(moduleId, discovered.origin()); installingModule = moduleId; try { module.install(this); @@ -73,12 +71,14 @@ public final class StageGraphBuilder implements StageGraph { .toList(); } - private void claimModule(ResourceId moduleId) { + private void claimModule(ResourceId moduleId, String origin) { if (installingModule != null) { throw new IllegalStateException("Module " + moduleId + " installed during " + installingModule); } - if (!modules.add(moduleId)) { - throw new IllegalArgumentException("Duplicate module: " + moduleId); + var previous = moduleOrigins.putIfAbsent(moduleId, origin); + if (previous != null) { + throw new IllegalArgumentException("Duplicate module " + moduleId + " from " + origin + + "; already loaded from " + previous); } } @@ -103,10 +103,10 @@ public final class StageGraphBuilder implements StageGraph { return installingModule; } - private static void requireModuleNamespace(Stage stage, ResourceId module) { + private void requireModuleNamespace(Stage stage, ResourceId module) { if (!stage.id().namespace().equals(module.namespace())) { throw new IllegalArgumentException("Stage " + stage + " must use namespace '" - + module.namespace() + "' of its defining module " + module); + + module.namespace() + "' of its defining module " + module + " from " + moduleOrigins.get(module)); } } diff --git a/src/test/java/com/volmit/example/ChunkPipelineTest.java b/src/test/java/com/volmit/example/ChunkPipelineTest.java index 734897119..65c881a7f 100644 --- a/src/test/java/com/volmit/example/ChunkPipelineTest.java +++ b/src/test/java/com/volmit/example/ChunkPipelineTest.java @@ -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()); diff --git a/src/test/java/com/volmit/example/PlacementLifecyclePortTest.java b/src/test/java/com/volmit/example/PlacementLifecyclePortTest.java index afe8221af..9a0174f9b 100644 --- a/src/test/java/com/volmit/example/PlacementLifecyclePortTest.java +++ b/src/test/java/com/volmit/example/PlacementLifecyclePortTest.java @@ -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 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()); diff --git a/src/test/java/com/volmit/example/placement/PlacementModules.java b/src/test/java/com/volmit/example/placement/PlacementModules.java index fa72d2834..c2327c349 100644 --- a/src/test/java/com/volmit/example/placement/PlacementModules.java +++ b/src/test/java/com/volmit/example/placement/PlacementModules.java @@ -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 builtIns() { + return all().stream().map(DiscoveredModule::builtIn).toList(); + } } diff --git a/src/test/java/com/volmit/host/ModuleRegistryTest.java b/src/test/java/com/volmit/host/ModuleRegistryTest.java index 803104727..ac8b5b8ae 100644 --- a/src/test/java/com/volmit/host/ModuleRegistryTest.java +++ b/src/test/java/com/volmit/host/ModuleRegistryTest.java @@ -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 codec(int version) { diff --git a/src/test/java/com/volmit/host/PackModulesTest.java b/src/test/java/com/volmit/host/PackModulesTest.java new file mode 100644 index 000000000..a02c647c9 --- /dev/null +++ b/src/test/java/com/volmit/host/PackModulesTest.java @@ -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 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")); + } + } +} diff --git a/src/test/java/com/volmit/host/StageGraphTest.java b/src/test/java/com/volmit/host/StageGraphTest.java index c3b0a27ab..597ffc664 100644 --- a/src/test/java/com/volmit/host/StageGraphTest.java +++ b/src/test/java/com/volmit/host/StageGraphTest.java @@ -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(); - 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"))); } diff --git a/src/test/java/com/volmit/support/TestModuleJar.java b/src/test/java/com/volmit/support/TestModuleJar.java new file mode 100644 index 000000000..e0531e0cf --- /dev/null +++ b/src/test/java/com/volmit/support/TestModuleJar.java @@ -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 sources = new LinkedHashMap<>(); + private final List entryPoints = new ArrayList<>(); + private final List 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 /modules/} 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(); + 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; + } + } +}