diff --git a/src/main/java/com/volmit/host/LoadedPack.java b/src/main/java/com/volmit/host/LoadedPack.java new file mode 100644 index 000000000..bf12bdd92 --- /dev/null +++ b/src/main/java/com/volmit/host/LoadedPack.java @@ -0,0 +1,80 @@ +package com.volmit.host; + +import java.nio.file.Path; +import java.util.List; +import java.util.Objects; + +/** One loaded pack: its module jars and everything derived from them together with the host's + * built-in modules. This is the host's entry point for loading and unloading a pack's modules. + * + *
{@code
+ * try (var pack = LoadedPack.load(packRoot, host)) {
+ *     var placer = new PlacementRunner(pack.placement());
+ *     ...
+ * }
+ * }
+ * + * A load either returns a complete pack or throws with nothing left open. Close the pack when it + * unloads, after the host has stopped using its graphs, catalog and runners: closing releases the + * pack's class loader. + */ +public final class LoadedPack implements AutoCloseable { + private final PackModules packModules; + private final LoadedModules loaded; + + private LoadedPack(PackModules packModules, LoadedModules loaded) { + this.packModules = packModules; + this.loaded = loaded; + } + + /** Loads the pack's module jars, installs them with the host's built-in modules and resolves both + * pipelines. Fails with the first load error, naming the jar or module at fault. + */ + public static LoadedPack load(Path packRoot, ModuleHost host) { + Objects.requireNonNull(host, "host"); + var packModules = PackModules.load(packRoot, host.exposedHostPackages()); + try { + var loaded = LoadedModules.load(host.withPackModules(packModules.modules()), + host.reservedHostFields(), host.reservedNamespaces()); + return new LoadedPack(packModules, loaded); + } catch (RuntimeException | Error failure) { + closeAfterFailure(packModules, failure); + throw failure; + } + } + + /** The pack's own modules, one per jar, in jar file name order. */ + public List packModules() { + return packModules.modules(); + } + + /** Classes the pack's jars use that nobody has, per jar; see {@link PackModules#missingClasses()}. */ + public List missingClasses() { + return packModules.missingClasses(); + } + + public FeatureCatalog catalog() { + return loaded.catalog(); + } + + public ResolvedGraph placement() { + return loaded.placement(); + } + + public ResolvedGraph chunk() { + return loaded.chunk(); + } + + @Override + public void close() { + packModules.close(); + } + + private static void closeAfterFailure(PackModules packModules, Throwable failure) { + try { + packModules.close(); + } catch (RuntimeException exception) { + failure.addSuppressed(exception); + } + } +} diff --git a/src/main/java/com/volmit/host/ModuleHost.java b/src/main/java/com/volmit/host/ModuleHost.java new file mode 100644 index 000000000..61def7252 --- /dev/null +++ b/src/main/java/com/volmit/host/ModuleHost.java @@ -0,0 +1,84 @@ +package com.volmit.host; + +import com.volmit.FeatureAttachment; +import com.volmit.IrisModule; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.TreeSet; + +/** The host's side of every pack load, the same for all packs: its built-in modules, the host + * packages pack modules may use besides the Iris API, the JSON fields the host itself uses, and the + * namespaces only built-in modules may use. Build it once and pass it to every + * {@link LoadedPack#load(java.nio.file.Path, ModuleHost)}. + * + *
{@code
+ * var host = ModuleHost.of(builtInModules)
+ *         .exposing("art.arcane.iris.engine.modules")
+ *         .reservingNamespaces("iris")
+ *         .reservingFields(reservedHostFields);
+ * }
+ * + * Built-in modules' {@code info()} is read here, once. Exposed package names and reserved namespaces + * are checked here, so a mistake fails when the host starts rather than at the first pack load. + */ +public record ModuleHost( + List builtIns, + Set exposedHostPackages, + Map> reservedHostFields, + Set reservedNamespaces) { + public ModuleHost { + builtIns = List.copyOf(builtIns); + exposedHostPackages = Set.copyOf(exposedHostPackages); + reservedHostFields = copyOf(reservedHostFields); + reservedNamespaces = Set.copyOf(reservedNamespaces); + ExposedPackages.apiAnd(exposedHostPackages); + ReservedNamespaces.of(reservedNamespaces); + } + + /** The given built-in modules, exposing only the Iris API and reserving nothing. */ + public static ModuleHost of(List builtInModules) { + var builtIns = builtInModules.stream().map(DiscoveredModule::builtIn).toList(); + return new ModuleHost(builtIns, Set.of(), Map.of(), Set.of()); + } + + /** This configuration with {@code packages}, each with its subpackages, also exposed to pack + * modules, such as the packages that hold built-in modules' stage constants. + */ + public ModuleHost exposing(String... packages) { + return new ModuleHost(builtIns, union(exposedHostPackages, packages), reservedHostFields, reservedNamespaces); + } + + /** This configuration with {@code namespaces} reserved for built-in modules. */ + public ModuleHost reservingNamespaces(String... namespaces) { + return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, union(reservedNamespaces, namespaces)); + } + + /** This configuration with {@code fields} as the JSON fields the host itself uses, per target. */ + public ModuleHost reservingFields(Map> fields) { + return new ModuleHost(builtIns, exposedHostPackages, fields, reservedNamespaces); + } + + /** The built-in modules followed by a pack's modules, in the order {@link LoadedModules} installs them. */ + List withPackModules(List packModules) { + var modules = new ArrayList<>(builtIns); + modules.addAll(Objects.requireNonNull(packModules, "packModules")); + return modules; + } + + private static Map> copyOf(Map> fields) { + var copy = new EnumMap>(FeatureAttachment.Target.class); + fields.forEach((target, names) -> copy.put(target, Set.copyOf(names))); + return Map.copyOf(copy); + } + + private static Set union(Set existing, String... added) { + var names = new TreeSet<>(existing); + names.addAll(Arrays.asList(added)); + return names; + } +} diff --git a/src/test/java/com/volmit/host/LoadedPackTest.java b/src/test/java/com/volmit/host/LoadedPackTest.java new file mode 100644 index 000000000..5b08f7317 --- /dev/null +++ b/src/test/java/com/volmit/host/LoadedPackTest.java @@ -0,0 +1,89 @@ +package com.volmit.host; + +import com.volmit.support.TestModuleJar; +import example.builtin.CarveModule; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import java.nio.file.Path; +import java.util.List; +import static com.volmit.support.TestModuleJar.module; +import static org.junit.jupiter.api.Assertions.*; + +class LoadedPackTest { + private static final String LOADER_PROPERTY = "irisapi.test.packClassLoader"; + private static final String UNUSED_CLASS = "pack.user.Unused"; + private static final String NO_MEMBERS = ""; + private static final String NO_STAGES = ""; + private static final ModuleHost HOST = ModuleHost.of(List.of(new CarveModule())) + .exposing(CarveModule.class.getPackageName()) + .reservingNamespaces("iris"); + + @TempDir + Path pack; + + @AfterEach + void forgetLoader() { + System.getProperties().remove(LOADER_PROPERTY); + } + + /** A pack module that hands its class loader to the test when constructed, plus a class nothing loads. */ + private void writeModule(String moduleId, String install) { + module("pack.user.User", moduleId, + "public User() { System.getProperties().put(\"" + LOADER_PROPERTY + "\", getClass().getClassLoader()); }", + install) + .source(UNUSED_CLASS, "package pack.user; final class Unused {}") + .compileAgainstHostOf(CarveModule.class) + .writeInto(pack, "user.jar"); + } + + private static ClassLoader packLoader() { + return (ClassLoader) System.getProperties().get(LOADER_PROPERTY); + } + + @Test + void loadsPackModulesWithTheHostsBuiltInsAndResolvesBothPipelines() { + writeModule("user:core", "graph.define(Stage.placement(\"user:core/carved\"))" + + ".requires(example.builtin.CarveModule.CLEAR).run(context -> {});"); + + try (var loaded = LoadedPack.load(pack, HOST)) { + assertEquals(List.of("user:core"), loaded.packModules().stream().map(found -> found.info().id().toString()).toList()); + assertEquals(List.of("iris:carve/clear", "user:core/carved"), + loaded.placement().stages().stream().map(stage -> stage.stage().id().toString()).toList()); + assertTrue(loaded.chunk().stages().isEmpty()); + assertTrue(loaded.missingClasses().isEmpty()); + assertTrue(loaded.catalog().settings().isEmpty()); + } + } + + @Test + void closingThePackReleasesItsClassLoader() { + writeModule("user:core", NO_STAGES); + + try (var ignored = LoadedPack.load(pack, HOST)) { + assertNotNull(packLoader()); + } + + assertThrows(ClassNotFoundException.class, () -> packLoader().loadClass(UNUSED_CLASS)); + } + + @Test + void failedLoadLeavesNothingOpen() { + writeModule("iris:stolen", NO_STAGES); + + var error = assertThrows(IllegalArgumentException.class, () -> LoadedPack.load(pack, HOST)); + + assertTrue(error.getMessage().contains("uses reserved namespace 'iris'"), error.getMessage()); + assertNotNull(packLoader(), "the module was constructed before installation failed"); + assertThrows(ClassNotFoundException.class, () -> packLoader().loadClass(UNUSED_CLASS)); + } + + @Test + void invalidHostConfigurationFailsWhenBuilt() { + var host = ModuleHost.of(List.of()); + assertThrows(IllegalArgumentException.class, () -> host.exposing("org.*")); + assertThrows(IllegalArgumentException.class, () -> host.reservingNamespaces("iris:core")); + assertEquals(List.of(), host.builtIns()); + assertEquals(java.util.Set.of(), host.exposedHostPackages()); + } +}