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:
piexel committed 2026-10-05 17:48:58 +02:00
1 parent e918cd44a8
commit 6388173f19
12 files changed
+606 -29

No files matched your search

@@ -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);
}
}
@@ -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<? extends IrisModule> modules,
List<DiscoveredModule> modules,
Map<FeatureAttachment.Target, Set<String>> 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));
@@ -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.
*
* <p>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<String> 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<? extends IrisModule> 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<? extends IrisModule> 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);
}
}
@@ -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 <pack>/modules/*.jar}, one module per jar, ordered
* by file name so the result never depends on directory listing order.
*
* <p>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.
*
* <p>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<DiscoveredModule> modules;
private final URLClassLoader loader;
private PackModules(List<DiscoveredModule> 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<DiscoveredModule> 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<Path> 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<ModuleJar> jars) {
var urls = jars.stream().map(ModuleJar::url).toArray(URL[]::new);
return new URLClassLoader("pack:" + packRoot.getFileName(), urls, IrisModule.class.getClassLoader());
}
private static List<DiscoveredModule> createModules(List<ModuleJar> 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);
}
}
}
@@ -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<ResourceId, StageDeclaration> declarations = new HashMap<>();
private final Set<ResourceId> modules = new HashSet<>();
private final Map<ResourceId, String> 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));
}
}