Stop reserving namespaces, let a jar list several modules and add ModuleJarCheck for builds that write module jars

ReservedNamespaces and ModuleHost.reservingNamespaces are gone: a pack module may use any
namespace, iris included. A module id is still loaded once, and the duplicate error now names
the origin and class of both modules, so two modules of one jar can be told apart.

A jar lists one module class per line in META-INF/services/com.volmit.IrisModule and loads all
of them in that order; each class must still be defined in the jar. A jar with several modules
is excused by the optional packages of all of them.

ModuleJarCheck runs the load's class checks on one jar without loading it.
This commit is contained in:
piexel committed 2026-10-09 14:08:33 +02:00
1 parent ef4b640867
commit 42d31a9ce4
21 files changed
+330 -208

No files matched your search

@@ -63,6 +63,11 @@ public final class DiscoveredModule {
return origin;
}
/** The origin and the module's class, which tells apart two modules of one jar. */
String locationWithClass() {
return origin + " (" + module.getClass().getName() + ")";
}
Source source() {
return source;
}
@@ -26,8 +26,6 @@ public record LoadedModules(
/** Pass the built-in modules together with {@link PackModules#modules()} of the pack.
*
* @param reservedHostFields JSON fields the host itself uses, per attachment target
* @param reservedNamespaces namespaces only built-in modules may use, such as {@code iris}; a
* pack module whose id uses one fails the load
* @param hostTypePackages packages whose classes the host describes itself, each with its
* subpackages; only built-in modules' settings may use them (see {@link ModuleHost#describingHostTypesIn})
* @param reservedFolders pack folders the host reads itself, which no resource kind may read (see
@@ -36,11 +34,8 @@ public record LoadedModules(
public static LoadedModules load(
List<DiscoveredModule> modules,
Map<FeatureAttachment.Target, Set<String>> reservedHostFields,
Collection<String> reservedNamespaces,
Collection<String> hostTypePackages,
Collection<String> reservedFolders) {
var reserved = ReservedNamespaces.of(reservedNamespaces);
modules.forEach(reserved::requireAllowed);
var registry = new ModuleRegistry(reservedHostFields, Set.copyOf(reservedFolders));
var stages = new StageGraphBuilder();
for (var discovered : modules) {
@@ -37,7 +37,7 @@ public final class LoadedPack implements AutoCloseable {
var packModules = PackModules.load(packRoot, host.exposedHostPackages(), host.jarCopyRoot(), host.logger());
try {
var loaded = LoadedModules.load(host.withPackModules(packModules.modules()),
host.reservedHostFields(), host.reservedNamespaces(), host.hostTypePackages(), host.reservedFolders());
host.reservedHostFields(), host.hostTypePackages(), host.reservedFolders());
return new LoadedPack(packModules, loaded);
} catch (RuntimeException | Error failure) {
closeAfterFailure(packModules, failure);
+11 -21
View File
@@ -15,27 +15,25 @@ 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 (which no
* built-in alias may take), the namespaces only built-in modules may use, the packages of the
* classes the host describes itself and the pack folders it reads itself (which no resource kind may read). Build it once and pass it to every
* built-in alias may take), the packages of the classes the host describes itself and the pack folders it
* reads itself (which no resource kind may read). Build it once and pass it to every
* {@link LoadedPack#load(java.nio.file.Path, ModuleHost)}.
*
* <pre>{@code
* var host = ModuleHost.of(builtInModules)
* .exposing("art.arcane.iris.engine.modules")
* .reservingNamespaces("iris")
* .reservingFields(reservedHostFields);
* }</pre>
*
* Every method adds to what earlier calls configured, so a host can build the configuration in steps.
* Built-in modules' {@code info()} is read here, once. Exposed package names, reserved namespaces,
* host type packages, reserved folders and reserved field names are checked here, so a mistake fails when the host starts rather than at the
* Built-in modules' {@code info()} is read here, once. Exposed package names, host type packages,
* reserved folders and reserved field names are checked here, so a mistake fails when the host starts rather than at the
* first pack load.
*/
public record ModuleHost(
List<DiscoveredModule> builtIns,
Set<String> exposedHostPackages,
Map<FeatureAttachment.Target, Set<String>> reservedHostFields,
Set<String> reservedNamespaces,
Set<String> hostTypePackages,
Set<String> reservedFolders,
Path jarCopyRoot,
@@ -46,13 +44,11 @@ public record ModuleHost(
builtIns = List.copyOf(builtIns);
exposedHostPackages = Set.copyOf(exposedHostPackages);
reservedHostFields = copyOf(reservedHostFields);
reservedNamespaces = Set.copyOf(reservedNamespaces);
hostTypePackages = Set.copyOf(hostTypePackages);
reservedFolders = Set.copyOf(reservedFolders);
Objects.requireNonNull(jarCopyRoot, "jarCopyRoot");
Objects.requireNonNull(logger, "logger");
ExposedPackages.apiAnd(exposedHostPackages);
ReservedNamespaces.of(reservedNamespaces);
HostTypes.of(hostTypePackages);
requireFieldNames(reservedHostFields);
requireFolderNames(reservedFolders);
@@ -63,7 +59,7 @@ public record ModuleHost(
*/
public static ModuleHost of(List<? extends IrisModule> builtInModules) {
var builtIns = builtInModules.stream().map(DiscoveredModule::builtIn).toList();
return new ModuleHost(builtIns, Set.of(), Map.of(), Set.of(), Set.of(), Set.of(), systemTemporaryDirectory(),
return new ModuleHost(builtIns, Set.of(), Map.of(), Set.of(), Set.of(), systemTemporaryDirectory(),
System.getLogger(PackModules.class.getName()));
}
@@ -71,13 +67,7 @@ public record ModuleHost(
* 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,
hostTypePackages, reservedFolders, jarCopyRoot, logger);
}
/** This configuration with {@code namespaces} reserved for built-in modules. */
public ModuleHost reservingNamespaces(String... namespaces) {
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, union(reservedNamespaces, namespaces),
return new ModuleHost(builtIns, union(exposedHostPackages, packages), reservedHostFields,
hostTypePackages, reservedFolders, jarCopyRoot, logger);
}
@@ -85,7 +75,7 @@ public record ModuleHost(
* merged per attachment target with the fields reserved before.
*/
public ModuleHost reservingFields(Map<FeatureAttachment.Target, Set<String>> fields) {
return new ModuleHost(builtIns, exposedHostPackages, merge(reservedHostFields, fields), reservedNamespaces,
return new ModuleHost(builtIns, exposedHostPackages, merge(reservedHostFields, fields),
hostTypePackages, reservedFolders, jarCopyRoot, logger);
}
@@ -95,7 +85,7 @@ public record ModuleHost(
* instead of describing their fields. Pack modules' settings cannot use them.
*/
public ModuleHost describingHostTypesIn(String... packages) {
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, reservedNamespaces,
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields,
union(hostTypePackages, packages), reservedFolders, jarCopyRoot, logger);
}
@@ -103,7 +93,7 @@ public record ModuleHost(
* itself, such as its biome and object folders. A module resource kind that reads one fails the pack load.
*/
public ModuleHost reservingFolders(String... folders) {
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, reservedNamespaces, hostTypePackages,
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, hostTypePackages,
union(reservedFolders, folders), jarCopyRoot, logger);
}
@@ -111,7 +101,7 @@ public record ModuleHost(
* cache directory of the host, which is created when missing. The last call wins.
*/
public ModuleHost copyingJarsTo(Path directory) {
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, reservedNamespaces, hostTypePackages,
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, hostTypePackages,
reservedFolders, directory, logger);
}
@@ -119,7 +109,7 @@ public record ModuleHost(
* {@code logger}, such as an adapter to the host's own log. The last call wins.
*/
public ModuleHost loggingTo(System.Logger logger) {
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, reservedNamespaces, hostTypePackages,
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, hostTypePackages,
reservedFolders, jarCopyRoot, logger);
}
+38 -38
View File
@@ -22,17 +22,18 @@ import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipFile;
/** One jar in a pack's modules directory, the entry class it names and the classes it holds,
/** One jar in a pack's modules directory, the entry classes it names and the classes it holds,
* each with the classes it links against. {@code path} is the load's copy of the jar
* ({@link JarSnapshot}); {@code origin} is the original's path relative to the pack, which every
* message 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:
* <p>The entry points are the jar's own {@code META-INF/services/com.volmit.IrisModule} file, in
* the format {@link java.util.ServiceLoader} reads: one module class per line, so a jar holds as many
* modules as it lists. 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, List<JarClass> classes) {
record ModuleJar(Path path, String origin, List<String> entryClasses, List<JarClass> classes) {
static final String ENTRY_POINT_FILE = "META-INF/services/" + IrisModule.class.getName();
private static final String COMMENT_START = "#";
private static final String CLASS_FILE_SUFFIX = ".class";
@@ -42,7 +43,7 @@ record ModuleJar(Path path, String origin, String entryClass, List<JarClass> cla
ModuleJar {
Objects.requireNonNull(path, "path");
Objects.requireNonNull(origin, "origin");
Objects.requireNonNull(entryClass, "entryClass");
entryClasses = List.copyOf(entryClasses);
classes = List.copyOf(classes);
}
@@ -54,16 +55,16 @@ record ModuleJar(Path path, String origin, String entryClass, List<JarClass> cla
}
}
/** Reads the single entry class a jar names and the classes it holds. Fails if a class file
* cannot be parsed.
/** Reads the entry classes a jar names and the classes it holds. Fails if the jar names no
* entry class or a class file cannot be parsed.
*/
static ModuleJar read(JarSnapshot.CopiedJar copied) {
var origin = copied.origin();
var jar = copied.copy();
try (var file = openAsClassLoaderSeesIt(jar)) {
var entryClass = requireSingleEntryClass(origin, readEntryClasses(file));
var entryClasses = requireEntryClasses(origin, readEntryClasses(file));
var classEntries = findClassEntries(file);
return new ModuleJar(jar, origin, entryClass, readClasses(origin, file, classEntries));
return new ModuleJar(jar, origin, entryClasses, readClasses(origin, file, classEntries));
} catch (IOException exception) {
throw new UncheckedIOException("Module jar " + origin + " is not a readable jar", exception);
}
@@ -81,14 +82,19 @@ record ModuleJar(Path path, String origin, String entryClass, List<JarClass> cla
}
}
/** 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.
/** Loads and instantiates every entry class through the pack's class loader, in the order the
* jar lists them. Each class must come from this jar, so a copy on the host classpath cannot
* silently replace the jar's module.
*/
DiscoveredModule createModule(ClassLoader packLoader, JarSnapshot snapshot) {
var type = loadEntryClass(packLoader);
requireDefinedHere(type, snapshot);
var module = instantiate(type);
return DiscoveredModule.fromJar(module, readIdentity(module), origin);
List<DiscoveredModule> createModules(ClassLoader packLoader, JarSnapshot snapshot) {
return entryClasses.stream().map(entryClass -> createModule(entryClass, packLoader, snapshot)).toList();
}
private DiscoveredModule createModule(String entryClass, ClassLoader packLoader, JarSnapshot snapshot) {
var type = loadEntryClass(entryClass, packLoader);
requireDefinedHere(entryClass, type, snapshot);
var module = instantiate(entryClass, type);
return DiscoveredModule.fromJar(module, readIdentity(entryClass, module), origin);
}
/** Opens the jar with the runtime's multi-release version, like the pack class loader does, so
@@ -98,16 +104,10 @@ record ModuleJar(Path path, String origin, String entryClass, List<JarClass> cla
return new JarFile(jar.toFile(), true, ZipFile.OPEN_READ, JarFile.runtimeVersion());
}
private static String requireSingleEntryClass(String origin, List<String> entryClasses) {
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 entryClasses.getFirst();
private static List<String> requireEntryClasses(String origin, List<String> entryClasses) {
if (!entryClasses.isEmpty()) return entryClasses;
throw new IllegalArgumentException("Module jar " + origin + " has no entry point; name its "
+ IrisModule.class.getSimpleName() + " classes in " + ENTRY_POINT_FILE + ", one per line");
}
private static List<String> readEntryClasses(JarFile file) throws IOException {
@@ -168,24 +168,24 @@ record ModuleJar(Path path, String origin, String entryClass, List<JarClass> cla
return comment < 0 ? line : line.substring(0, comment);
}
private Class<? extends IrisModule> loadEntryClass(ClassLoader packLoader) {
private Class<? extends IrisModule> loadEntryClass(String entryClass, ClassLoader packLoader) {
Class<?> type;
try {
type = Class.forName(entryClass, false, packLoader);
} catch (ClassNotFoundException | LinkageError exception) {
throw brokenEntryPoint("class cannot be loaded: " + exception, exception);
throw brokenEntryPoint(entryClass, "class cannot be loaded: " + exception, exception);
}
if (!IrisModule.class.isAssignableFrom(type)) {
throw brokenEntryPoint("class does not implement " + IrisModule.class.getName(), null);
throw brokenEntryPoint(entryClass, "class does not implement " + IrisModule.class.getName(), null);
}
return type.asSubclass(IrisModule.class);
}
private void requireDefinedHere(Class<?> type, JarSnapshot snapshot) {
private void requireDefinedHere(String entryClass, Class<?> type, JarSnapshot snapshot) {
var source = type.getProtectionDomain().getCodeSource();
var location = source == null ? null : source.getLocation();
if (location != null && location.toExternalForm().equals(url().toExternalForm())) return;
throw brokenEntryPoint("class is loaded from " + describeLocation(location, snapshot) + ", not from this jar", null);
throw brokenEntryPoint(entryClass, "class is loaded from " + describeLocation(location, snapshot) + ", not from this jar", null);
}
/** Another jar of the pack by its origin, never by the path of its copy. */
@@ -199,27 +199,27 @@ record ModuleJar(Path path, String origin, String entryClass, List<JarClass> cla
}
}
private IrisModule instantiate(Class<? extends IrisModule> type) {
private IrisModule instantiate(String entryClass, Class<? extends IrisModule> type) {
try {
return type.getConstructor().newInstance();
} catch (InvocationTargetException exception) {
throw brokenEntryPoint("constructor threw " + exception.getCause(), exception.getCause());
throw brokenEntryPoint(entryClass, "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);
throw brokenEntryPoint(entryClass, "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);
throw brokenEntryPoint(entryClass, "class cannot be initialized: " + exception, exception);
}
}
private ModuleInfo readIdentity(IrisModule module) {
private ModuleInfo readIdentity(String entryClass, IrisModule module) {
try {
return Objects.requireNonNull(module.info(), "info() returned null");
} catch (RuntimeException | LinkageError exception) {
throw brokenEntryPoint("info() failed: " + exception, exception);
throw brokenEntryPoint(entryClass, "info() failed: " + exception, exception);
}
}
private IllegalArgumentException brokenEntryPoint(String problem, Throwable cause) {
private IllegalArgumentException brokenEntryPoint(String entryClass, String problem, Throwable cause) {
return new IllegalArgumentException("Module jar " + origin + " has a broken entry point "
+ entryClass + ": " + problem, cause);
}
@@ -0,0 +1,59 @@
package com.volmit.host;
import com.volmit.IrisModule;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
/** The checks a pack load makes on a module jar's classes, for a build to run on a jar it has just
* written: the jar names at least one module, every module class is in the jar, and no class uses
* what pack modules cannot see (Iris internals, JDK modules or packages packs may not use, missing
* classes of exposed packages). Nothing is loaded or instantiated. A jar that passes can still fail
* a pack load, for example on duplicate module ids, which only the pack's other modules reveal.
*
* <p>The host classes come from the class loader that defines the API, so run this with the API and the
* host's classes on the class path. {@link #main} takes a jar path followed by the host packages that
* pack modules may use, and exits with 1 and the message on stderr when the jar fails.
*/
public final class ModuleJarCheck {
private static final int FAILED_EXIT_CODE = 1;
private static final int MISSING_ARGUMENT_EXIT_CODE = 2;
private ModuleJarCheck() {}
/** Returns the module classes the jar names, in the order it lists them, or fails naming the jar. */
public static List<String> check(Path jar, Collection<String> exposedHostPackages) {
Objects.requireNonNull(jar, "jar");
var host = new ExposedHostClassLoader(IrisModule.class.getClassLoader(), ExposedPackages.apiAnd(exposedHostPackages));
var read = ModuleJar.read(new JarSnapshot.CopiedJar(jar.toString(), jar));
requireEntryClassesInJar(read);
PackClassCheck.requireLinkable(List.of(read), host);
return read.entryClasses();
}
private static void requireEntryClassesInJar(ModuleJar jar) {
var held = jar.classNames();
for (var entryClass : jar.entryClasses()) {
if (held.contains(entryClass)) continue;
throw new IllegalArgumentException("Module jar " + jar.origin() + " lists " + entryClass + " in "
+ ModuleJar.ENTRY_POINT_FILE + ", but the jar holds no such class; a module class must be in the jar that lists it");
}
}
public static void main(String[] arguments) {
if (arguments.length == 0) {
System.err.println("Usage: ModuleJarCheck <module jar> [exposed host package...]");
System.exit(MISSING_ARGUMENT_EXIT_CODE);
}
var exposed = Arrays.asList(arguments).subList(1, arguments.length);
try {
var modules = check(Path.of(arguments[0]), exposed);
System.out.println("Module jar " + arguments[0] + " passes the pack module checks: " + modules);
} catch (RuntimeException failure) {
System.err.println(failure.getMessage());
System.exit(FAILED_EXIT_CODE);
}
}
}
@@ -15,8 +15,8 @@ import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/** 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. Hosts normally load packs
/** The module jars of one pack: every {@code <pack>/modules/*.jar}, each with the modules it lists,
* ordered by file name so the result never depends on directory listing order. Hosts normally load packs
* through {@link LoadedPack}, which uses this.
*
* <p>The load first copies the jars into a fresh temporary directory ({@link JarSnapshot}) and works
@@ -101,7 +101,7 @@ public final class PackModules implements AutoCloseable {
}
}
/** One module per jar, in jar file name order. */
/** The modules of all jars, in jar file name order and, within a jar, in the order it lists them. */
public List<DiscoveredModule> modules() {
return modules;
}
@@ -183,16 +183,17 @@ public final class PackModules implements AutoCloseable {
}
private static List<DiscoveredModule> createModules(List<ModuleJar> jars, ClassLoader loader, JarSnapshot snapshot) {
return jars.stream().map(jar -> jar.createModule(loader, snapshot)).toList();
return jars.stream().flatMap(jar -> jar.createModules(loader, snapshot).stream()).toList();
}
/** A module's optional packages excuse only its own jar's missing classes. They are read from
* {@code info()}, so this runs after the entry classes exist; errors were decided before that and
* never depend on them.
/** A module's optional packages excuse only its own jar's missing classes; a jar with several
* modules is excused by the optional packages of all of them. They are read from {@code info()},
* so this runs after the entry classes exist; errors were decided before that and never depend on them.
*/
private static List<MissingClasses> withoutDeclaredOptional(List<MissingClasses> missingClasses, List<DiscoveredModule> modules) {
var optionalPackages = modules.stream()
.collect(Collectors.toMap(DiscoveredModule::origin, found -> found.info().optionalPackages()));
.collect(Collectors.groupingBy(DiscoveredModule::origin,
Collectors.flatMapping(found -> found.info().optionalPackages().stream(), Collectors.toList())));
return missingClasses.stream()
.map(jar -> jar.outside(optionalPackages.get(jar.origin())))
.filter(Predicate.not(MissingClasses::isEmpty))
@@ -1,47 +0,0 @@
package com.volmit.host;
import com.volmit.resource.ResourceId;
import java.util.Collection;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
/** Namespaces that only modules from the host's classpath may use, such as {@code iris}. A pack
* module's id must use another namespace. Its stages, settings ids and mantle keys follow its
* namespace, so none of them can be in a reserved namespace either.
*/
final class ReservedNamespaces {
private final Set<String> namespaces;
private ReservedNamespaces(Set<String> namespaces) {
this.namespaces = namespaces;
}
/** Fails on anything that is not a namespace, such as a blank string or a full id. */
static ReservedNamespaces of(Collection<String> namespaces) {
Objects.requireNonNull(namespaces, "reservedNamespaces");
var valid = new TreeSet<String>();
for (var namespace : namespaces) {
valid.add(requireNamespace(namespace));
}
return new ReservedNamespaces(Set.copyOf(valid));
}
void requireAllowed(DiscoveredModule discovered) {
if (discovered.source() == DiscoveredModule.Source.HOST) return;
var namespace = discovered.info().id().namespace();
if (!namespaces.contains(namespace)) return;
throw new IllegalArgumentException("Module " + discovered.info().id() + " from " + discovered.origin()
+ " uses reserved namespace '" + namespace + "', which only modules that ship with the host may use;"
+ " give the module a namespace of its own, which its stages, settings ids and mantle keys then use too");
}
private static String requireNamespace(String namespace) {
Objects.requireNonNull(namespace, "reserved namespace");
if (!ResourceId.isNamespace(namespace)) {
throw new IllegalArgumentException("Reserved namespace '" + namespace
+ "' is not a namespace; name one such as iris, without ':' or a path");
}
return namespace;
}
}
@@ -96,8 +96,8 @@ public final class StageGraphBuilder implements StageGraph {
}
var previous = modules.putIfAbsent(moduleId, discovered);
if (previous != null) {
throw new IllegalArgumentException("Duplicate module " + moduleId + " from " + discovered.origin()
+ "; already loaded from " + previous.origin());
throw new IllegalArgumentException("Duplicate module " + moduleId + " from " + discovered.locationWithClass()
+ "; already loaded from " + previous.locationWithClass());
}
}