From 42d31a9ce400781d6d9429999418c80c2e16827c Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 14:08:33 +0200 Subject: [PATCH] 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. --- CONTRACTS.md | 4 +- DESIGN.md | 22 ++-- README.md | 28 +++-- .../com/volmit/host/DiscoveredModule.java | 5 + .../java/com/volmit/host/LoadedModules.java | 5 - src/main/java/com/volmit/host/LoadedPack.java | 2 +- src/main/java/com/volmit/host/ModuleHost.java | 32 ++--- src/main/java/com/volmit/host/ModuleJar.java | 76 ++++++------ .../java/com/volmit/host/ModuleJarCheck.java | 59 ++++++++++ .../java/com/volmit/host/PackModules.java | 17 +-- .../com/volmit/host/ReservedNamespaces.java | 47 -------- .../com/volmit/host/StageGraphBuilder.java | 4 +- .../com/volmit/example/ChunkPipelineTest.java | 2 +- .../example/PlacementLifecyclePortTest.java | 2 +- .../com/volmit/host/DiscoveredModuleTest.java | 2 +- .../java/com/volmit/host/LoadedPackTest.java | 11 +- .../com/volmit/host/ModuleJarCheckTest.java | 87 ++++++++++++++ .../com/volmit/host/ModuleRegistryTest.java | 8 +- .../java/com/volmit/host/PackModulesTest.java | 109 +++++++++++------- .../java/com/volmit/host/StageGraphTest.java | 10 +- .../com/volmit/support/TestModuleJar.java | 6 + 21 files changed, 330 insertions(+), 208 deletions(-) create mode 100644 src/main/java/com/volmit/host/ModuleJarCheck.java delete mode 100644 src/main/java/com/volmit/host/ReservedNamespaces.java create mode 100644 src/test/java/com/volmit/host/ModuleJarCheckTest.java diff --git a/CONTRACTS.md b/CONTRACTS.md index 8b8ac2508..ea5942437 100644 --- a/CONTRACTS.md +++ b/CONTRACTS.md @@ -10,7 +10,7 @@ types that carry them and lists what the Iris adapter still owes. | Module identity and composition | `IrisModule`, `ModuleInfo` (with optional packages), `StageGraph` | | Loading and unloading a pack | host `LoadedPack`, `ModuleHost` | | Module jars in a pack | `META-INF/services/com.volmit.IrisModule`, host `PackModules` (jar copies), `DiscoveredModule`, `MissingClasses` | -| Namespace ownership | module-prefixed stage, feature and mantle ids, `ModuleInfo.ownsStage`/`ownsId`, `ModuleHost.reservingNamespaces` | +| Namespace ownership | module-prefixed stage, feature and mantle ids, `ModuleInfo.ownsStage`/`ownsId`; no reserved namespaces | | Randomness independent of other modules | `StageContext.random()`, host `StageStreams`, invocation seed passed to the runners | | Random values identical on every JDK | `WorldRandom`, pinned by `WorldRandomTest` | | Module-owned work and ordering | `Stage`, `StageRef`, stage definitions, `requires`/`softAfter`/`softBefore` | @@ -112,7 +112,7 @@ running Iris is the pack publisher's responsibility. storage. Abort chunk publication when any stage fails. - Preserve unknown persisted mantle layers or fail explicitly. - Build one `ModuleHost` at startup with the built-in modules, exposed packages, reserved JSON - fields and `reservingNamespaces("iris")`. Its methods accumulate, so the configuration can be + fields. Its methods accumulate, so the configuration can be built in steps. Load each pack with `LoadedPack.load(packRoot, host)` and close it only after nothing built from it is in use. - Pass a `System.Logger` that writes to the server log to `ModuleHost.loggingTo(...)`, so the diff --git a/DESIGN.md b/DESIGN.md index 71643a3b7..7d8133948 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -43,18 +43,18 @@ flowchart TD The `IrisModule` implementation is the module's entry point. `info()` returns its id, display name, version and optional packages; there is no separate descriptor. A pack keeps its modules in -`/modules/*.jar`, one module per jar. +`/modules/*.jar`, one or more modules per jar. The host loads a pack with `LoadedPack.load(packRoot, host)`. `ModuleHost` is the host's fixed configuration, built once and the same for every pack: built-in modules, exposed host packages, -reserved JSON fields and reserved namespaces. Each of its methods adds to what earlier calls +reserved JSON fields. Each of its methods adds to what earlier calls configured, and all names are checked when it is built. `LoadedPack` runs `PackModules.load` (below), then `LoadedModules.load` on the built-ins followed by the pack's modules. If the second step fails it closes the first before rethrowing, so a failed load leaves no class loader or jar copy behind. `close()` closes the pack's class loader, then deletes its jar copies. -A jar names its entry class in `META-INF/services/com.volmit.IrisModule`, the provider format of -`ServiceLoader`. The host reads that file from the jar itself rather than calling +A jar names its entry classes, one per line, in `META-INF/services/com.volmit.IrisModule`, the +provider format of `ServiceLoader`. The host reads that file from the jar itself rather than calling `ServiceLoader`, which would also return providers of parent class loaders and could not say which jar a broken provider came from. The rejected alternatives: @@ -73,7 +73,7 @@ API): 3. Copies them into a fresh temporary directory (see "Jar copies"). Every later step reads the copies; messages name the originals. 4. Reads each jar's entry point file and its class files. Comments (`#`) and blank lines are - ignored; zero or more than one entry class name fails. + ignored; zero entry class names fail, several load in the order listed. 5. Fails if a jar holds a class of an exposed package, naming the jar and the first such class. 6. Fails if a class is in two jars, naming the class and both jars. 7. Resolves every class each class uses (see below). A class that Iris has but hides, a class of a @@ -226,7 +226,7 @@ public ModuleInfo info() { Each package covers its subpackages. Missing classes of that jar inside them are dropped from the warning and from `missingClasses()`; the rest still warn, and other jars of the pack are not -affected. `ModuleInfo.of(id, name, version)` declares none. Invalid names fail in `info()`, which the +affected. A jar with several modules is excused by the optional packages of all of them. `ModuleInfo.of(id, name, version)` declares none. Invalid names fail in `info()`, which the load reports as a broken entry point of the jar. The declaration lives in the entry point because all module metadata does. That fixes its timing: @@ -272,11 +272,11 @@ owns in this sense: its owner. Other modules may name it too, to run only where configured. Checking against the module that names it alone would forbid that; checking nothing would let any module claim another module's settings id. -The host reserves namespaces for its own modules (`ModuleHost.reservingNamespaces("iris")`). A -module from a pack jar whose id uses a reserved namespace fails the load, naming the jar and the -namespace. Its stage ids, settings ids and mantle keys start with its id, so this one check keeps -pack modules out of reserved namespaces everywhere. Built-in modules, discovered with -`DiscoveredModule.builtIn`, may use them. +No namespace is reserved: `iris` is as free to a pack module as any other. A host that ships +modules of its own protects nothing by a reservation, so a module id is only ever loaded once: a +second module with the same id fails the load wherever it comes from (one jar, two jars, the host's +built-ins), naming both the origin and the class of each. That one check is what keeps a built-in +module that moves into a pack jar from being loaded twice. The load summary and the missing-classes warning go to the `System.Logger` the host passes to `ModuleHost.loggingTo(...)`, by default `System.getLogger(PackModules.class.getName())`. A host diff --git a/README.md b/README.md index 3d293db62..475d59cc4 100644 --- a/README.md +++ b/README.md @@ -206,8 +206,8 @@ A validator reports and returns; one that throws fails the pack's validation, na ## Module jars -A pack loads its modules from `/modules/*.jar`. One jar holds one module. Its entry point -is the `IrisModule` class, named in the jar's `META-INF/services/com.volmit.IrisModule`: +A pack loads its modules from `/modules/*.jar`. A jar holds one or more modules. Each module's +entry point is its `IrisModule` class, one per line in the jar's `META-INF/services/com.volmit.IrisModule`: ``` modules/moss.jar @@ -221,14 +221,19 @@ the module expects may be missing (see below). The host reads it once, when it f Every stage id of the module starts with the module id and `/`; the name is what logs show. Names and versions must fit on one line: line breaks and other control characters are rejected. -The host reserves namespaces for its own modules, such as `iris`. A pack module whose id uses a -reserved namespace fails the load, and because stage ids, settings ids and mantle keys start with the -module id, none of them can use it either: +Every entry class must be defined in the jar that lists it. No namespace is reserved: a pack module +may use any namespace, `iris` included. A module id is loaded once, though. Two modules with the same +id, in one jar, in two jars or one of them compiled into the host, fail the load and the message names +both sources, jar and class: ``` -Module iris:stilt from modules/stilt.jar uses reserved namespace 'iris', 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 +Duplicate module example:moss from modules/moss.jar (com.example.moss.MossModule); already loaded from host classpath (com.volmit.example.placement.MossModule) ``` +`ModuleJarCheck.check(jar, exposedHostPackages)` (also its `main`) runs the load's class checks on one +jar, without loading it: for a build that writes a module jar and wants to fail on a jar a pack would +refuse. + A module compiles against the Iris API as `compileOnly` (Maven: `provided`) and never ships it; Iris provides the API at runtime. At runtime a module can use the Iris API (`com.volmit.*`), the packages the host exposes besides it (meant for built-in modules, so packs can require their @@ -342,7 +347,6 @@ Settings com.example.flora.FloraSettings of module example:flora from modules/fl // Once, at startup: the same for every pack. var host = ModuleHost.of(builtInModules) .exposing("art.arcane.iris.engine.modules") // besides the API - .reservingNamespaces("iris") .reservingFields(reservedHostFields) .describingHostTypesIn("art.arcane.iris.engine.object") // classes the host describes itself .reservingFolders("biomes", "regions", "objects") // pack folders the host reads itself @@ -367,7 +371,7 @@ try (var pack = LoadedPack.load(packRoot, host)) { `ModuleHost` holds what the host passes to every pack load: built-in modules (their `info()` is read once, here), the host packages pack modules may use, the JSON fields the host itself uses, the -reserved namespaces, the packages of the classes it describes itself and the pack folders it reads itself. Each method adds to what earlier calls configured. Package names, namespaces and +packages of the classes it describes itself and the pack folders it reads itself. Each method adds to what earlier calls configured. Package names and reserved field names are checked when it is built. `LoadedPack.load` loads the pack's jars, installs them after the built-ins, catalogs settings and registrations, describes them for studio and resolves the three pipelines. It returns a complete pack or throws with nothing left open. `close()` @@ -388,10 +392,10 @@ holding nothing but that file and jars. Pack modules see the API plus the packages given to `ModuleHost.exposing(...)`, each with its subpackages. The host chooses those packages, such as the ones that hold built-in modules' stage -constants. The load (`PackModules`, under `LoadedPack`) reads one entry point per jar, in jar file -name order, and loads every jar of the pack through one class loader. A pack without a `modules` +constants. The load (`PackModules`, under `LoadedPack`) reads the entry points of each jar, in jar file +name order and in the order each jar lists them, and loads every jar of the pack through one class loader. A pack without a `modules` directory has no modules. Errors name the -jar: no entry point, several entry points, a class of an exposed package in the jar, a class that is +jar: no entry point, a class of an exposed package in the jar, a class that is also in another jar of the pack (both jars are named), a class that uses a class Iris has but hides, a class of a JDK module modules cannot see, a class of a JDK package not exported to modules, a class missing from an exposed package, or an entry @@ -443,7 +447,7 @@ A pack without jars logs `Pack overworld uses no modules: no jars in its modules together with explicitly registered settings, geometry and mantle registrations, resource kinds and validators (`catalog().resourceKinds()`, `catalog().validators()`), describes them and resolves the pipelines. Graph errors (missing requirement, cycle, a stage outside its module's id, duplicate, cross-pipeline edge) fail -here, at pack load, and so do reserved namespaces and feature ids or mantle keys outside the +here, at pack load, and so do duplicate module ids and feature ids or mantle keys outside the module's id. Errors about one module name its jar or "host classpath", and so does a module that fails to link a class while installing, such as a jar built against an API whose methods have since changed: diff --git a/src/main/java/com/volmit/host/DiscoveredModule.java b/src/main/java/com/volmit/host/DiscoveredModule.java index 484e82259..6c474db17 100644 --- a/src/main/java/com/volmit/host/DiscoveredModule.java +++ b/src/main/java/com/volmit/host/DiscoveredModule.java @@ -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; } diff --git a/src/main/java/com/volmit/host/LoadedModules.java b/src/main/java/com/volmit/host/LoadedModules.java index e107dceb2..ddb59fb5d 100644 --- a/src/main/java/com/volmit/host/LoadedModules.java +++ b/src/main/java/com/volmit/host/LoadedModules.java @@ -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 modules, Map> reservedHostFields, - Collection reservedNamespaces, Collection hostTypePackages, Collection 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) { diff --git a/src/main/java/com/volmit/host/LoadedPack.java b/src/main/java/com/volmit/host/LoadedPack.java index 3861514d5..ed65a833e 100644 --- a/src/main/java/com/volmit/host/LoadedPack.java +++ b/src/main/java/com/volmit/host/LoadedPack.java @@ -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); diff --git a/src/main/java/com/volmit/host/ModuleHost.java b/src/main/java/com/volmit/host/ModuleHost.java index 392326be6..88f857e6e 100644 --- a/src/main/java/com/volmit/host/ModuleHost.java +++ b/src/main/java/com/volmit/host/ModuleHost.java @@ -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)}. * *
{@code
  * var host = ModuleHost.of(builtInModules)
  *         .exposing("art.arcane.iris.engine.modules")
- *         .reservingNamespaces("iris")
  *         .reservingFields(reservedHostFields);
  * }
* * 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 builtIns, Set exposedHostPackages, Map> reservedHostFields, - Set reservedNamespaces, Set hostTypePackages, Set 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 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> 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); } diff --git a/src/main/java/com/volmit/host/ModuleJar.java b/src/main/java/com/volmit/host/ModuleJar.java index 58e075639..5a1e79c2a 100644 --- a/src/main/java/com/volmit/host/ModuleJar.java +++ b/src/main/java/com/volmit/host/ModuleJar.java @@ -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. * - *

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: + *

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 classes) { +record ModuleJar(Path path, String origin, List entryClasses, List 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 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 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 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 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 cla return new JarFile(jar.toFile(), true, ZipFile.OPEN_READ, JarFile.runtimeVersion()); } - private static String requireSingleEntryClass(String origin, List 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 requireEntryClasses(String origin, List 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 readEntryClasses(JarFile file) throws IOException { @@ -168,24 +168,24 @@ record ModuleJar(Path path, String origin, String entryClass, List cla return comment < 0 ? line : line.substring(0, comment); } - private Class loadEntryClass(ClassLoader packLoader) { + private Class 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 cla } } - private IrisModule instantiate(Class type) { + private IrisModule instantiate(String entryClass, Class 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); } diff --git a/src/main/java/com/volmit/host/ModuleJarCheck.java b/src/main/java/com/volmit/host/ModuleJarCheck.java new file mode 100644 index 000000000..1b4c0de68 --- /dev/null +++ b/src/main/java/com/volmit/host/ModuleJarCheck.java @@ -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. + * + *

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 check(Path jar, Collection 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 [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); + } + } +} diff --git a/src/main/java/com/volmit/host/PackModules.java b/src/main/java/com/volmit/host/PackModules.java index 693699d79..0f683a973 100644 --- a/src/main/java/com/volmit/host/PackModules.java +++ b/src/main/java/com/volmit/host/PackModules.java @@ -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 /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 /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. * *

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 modules() { return modules; } @@ -183,16 +183,17 @@ public final class PackModules implements AutoCloseable { } private static List createModules(List 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 withoutDeclaredOptional(List missingClasses, List 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)) diff --git a/src/main/java/com/volmit/host/ReservedNamespaces.java b/src/main/java/com/volmit/host/ReservedNamespaces.java deleted file mode 100644 index 7973850b3..000000000 --- a/src/main/java/com/volmit/host/ReservedNamespaces.java +++ /dev/null @@ -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 namespaces; - - private ReservedNamespaces(Set 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 namespaces) { - Objects.requireNonNull(namespaces, "reservedNamespaces"); - var valid = new TreeSet(); - 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; - } -} diff --git a/src/main/java/com/volmit/host/StageGraphBuilder.java b/src/main/java/com/volmit/host/StageGraphBuilder.java index 004646bf8..976f22347 100644 --- a/src/main/java/com/volmit/host/StageGraphBuilder.java +++ b/src/main/java/com/volmit/host/StageGraphBuilder.java @@ -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()); } } diff --git a/src/test/java/com/volmit/example/ChunkPipelineTest.java b/src/test/java/com/volmit/example/ChunkPipelineTest.java index 66fcee2ad..6f809532a 100644 --- a/src/test/java/com/volmit/example/ChunkPipelineTest.java +++ b/src/test/java/com/volmit/example/ChunkPipelineTest.java @@ -135,7 +135,7 @@ class ChunkPipelineTest { @Test void mantleStagesWriteBeyondTheirChunkAndChunkStagesReadTheirOwnPart() { - var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(new VeinModule())), Map.of(), Set.of(), Set.of(), Set.of()); + var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(new VeinModule())), Map.of(), Set.of(), Set.of()); var vein = new Entry<>(Target.BIOME, PLAINS, new VeinSettings(12, 4)); int reach = loaded.mantle().stages().getFirst().reachBlocks(new DeclaredSettings(vein)); assertEquals(3, reach, "a 12 block vein from the centre column runs 3 blocks into the next chunk"); diff --git a/src/test/java/com/volmit/example/PlacementLifecyclePortTest.java b/src/test/java/com/volmit/example/PlacementLifecyclePortTest.java index a6d481f90..756c4cacf 100644 --- a/src/test/java/com/volmit/example/PlacementLifecyclePortTest.java +++ b/src/test/java/com/volmit/example/PlacementLifecyclePortTest.java @@ -202,7 +202,7 @@ class PlacementLifecyclePortTest { @Test void loadingThePortCatalogsEveryConditioningSettingsType() { - var loaded = LoadedModules.load(PlacementModules.builtIns(), Map.of(), Set.of(), Set.of(), Set.of()); + var loaded = LoadedModules.load(PlacementModules.builtIns(), Map.of(), Set.of(), Set.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/host/DiscoveredModuleTest.java b/src/test/java/com/volmit/host/DiscoveredModuleTest.java index 9970ff11f..de4c2f34d 100644 --- a/src/test/java/com/volmit/host/DiscoveredModuleTest.java +++ b/src/test/java/com/volmit/host/DiscoveredModuleTest.java @@ -30,7 +30,7 @@ class DiscoveredModuleTest { var module = new ShiftingIdentity(); var discovered = DiscoveredModule.builtIn(module); - var loaded = LoadedModules.load(List.of(discovered), Map.of(), Set.of(), Set.of(), Set.of()); + var loaded = LoadedModules.load(List.of(discovered), Map.of(), Set.of(), Set.of()); assertEquals("first:core", discovered.info().id().toString()); assertEquals(List.of("first:core/mark"), diff --git a/src/test/java/com/volmit/host/LoadedPackTest.java b/src/test/java/com/volmit/host/LoadedPackTest.java index 3ed0c75d9..a27866a9e 100644 --- a/src/test/java/com/volmit/host/LoadedPackTest.java +++ b/src/test/java/com/volmit/host/LoadedPackTest.java @@ -19,8 +19,7 @@ class LoadedPackTest { 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"); + .exposing(CarveModule.class.getPackageName()); @TempDir Path pack; @@ -72,11 +71,11 @@ class LoadedPackTest { @Test void failedLoadLeavesNothingOpen() { - writeModule("iris:stolen", NO_STAGES); + writeModule("iris:carve", NO_STAGES); var error = assertThrows(IllegalArgumentException.class, () -> LoadedPack.load(pack, HOST)); - assertTrue(error.getMessage().contains("uses reserved namespace 'iris'"), error.getMessage()); + assertTrue(error.getMessage().contains("Duplicate module iris:carve"), error.getMessage()); assertNotNull(packLoader(), "the module was constructed before installation failed"); assertThrows(ClassNotFoundException.class, () -> packLoader().loadClass(UNUSED_CLASS)); } @@ -85,7 +84,6 @@ class LoadedPackTest { void invalidHostConfigurationFailsWhenBuilt() { var host = ModuleHost.of(List.of()); assertThrows(IllegalArgumentException.class, () -> host.exposing("org.*")); - assertThrows(IllegalArgumentException.class, () -> host.reservingNamespaces("iris:core")); assertThrows(IllegalArgumentException.class, () -> host.reservingFields(Map.of(Target.BIOME, Set.of(" ")))); assertEquals(List.of(), host.builtIns()); assertEquals(Set.of(), host.exposedHostPackages()); @@ -96,13 +94,10 @@ class LoadedPackTest { var host = ModuleHost.of(List.of()) .exposing("example.first") .exposing("example.second") - .reservingNamespaces("iris") - .reservingNamespaces("vanilla") .reservingFields(Map.of(Target.BIOME, Set.of("carving"), Target.REGION, Set.of("spawns"))) .reservingFields(Map.of(Target.BIOME, Set.of("objects"))); assertEquals(Set.of("example.first", "example.second"), host.exposedHostPackages()); - assertEquals(Set.of("iris", "vanilla"), host.reservedNamespaces()); assertEquals(Map.of(Target.BIOME, Set.of("carving", "objects"), Target.REGION, Set.of("spawns")), host.reservedHostFields()); } diff --git a/src/test/java/com/volmit/host/ModuleJarCheckTest.java b/src/test/java/com/volmit/host/ModuleJarCheckTest.java new file mode 100644 index 000000000..82ce4a78f --- /dev/null +++ b/src/test/java/com/volmit/host/ModuleJarCheckTest.java @@ -0,0 +1,87 @@ +package com.volmit.host; + +import com.volmit.support.TestModuleJar; +import example.builtin.CarveModule; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +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 ModuleJarCheckTest { + private static final String NO_MEMBERS = ""; + private static final String NO_STAGES = ""; + private static final String USES_JUNIT = "static Object used() { return org.junit.jupiter.api.Test.class; }"; + private static final List NO_EXPOSED_PACKAGES = List.of(); + + @TempDir + Path build; + + private static String failure(Executable check) { + return assertThrows(IllegalArgumentException.class, check).getMessage(); + } + + @Test + void jarOfSeveralModulesPassesAndReturnsThemInListedOrder() { + var jar = module("pack.First", "first:core", NO_MEMBERS, NO_STAGES) + .alsoModule("pack.Second", "second:core", NO_MEMBERS, NO_STAGES) + .writeInto(build, "two.jar"); + + assertEquals(List.of("pack.First", "pack.Second"), ModuleJarCheck.check(jar, NO_EXPOSED_PACKAGES)); + } + + @Test + void jarThatUsesAnExposedHostPackagePasses() { + var jar = module("pack.User", "user:core", NO_MEMBERS, + "graph.define(Stage.placement(\"user:core/carved\")).requires(example.builtin.CarveModule.CLEAR).run(context -> {});") + .compileAgainstHostOf(CarveModule.class) + .writeInto(build, "user.jar"); + + assertEquals(List.of("pack.User"), ModuleJarCheck.check(jar, List.of(CarveModule.class.getPackageName()))); + } + + @Test + void jarThatUsesAHiddenHostClassFailsNamingTheClass() { + var jar = module("pack.User", "user:core", USES_JUNIT, NO_STAGES) + .compileAgainstHostOf(Test.class) + .writeInto(build, "user.jar"); + + var message = failure(() -> ModuleJarCheck.check(jar, NO_EXPOSED_PACKAGES)); + + assertTrue(message.contains("hidden from modules"), message); + assertTrue(message.contains("pack.User -> org.junit.jupiter.api.Test"), message); + } + + @Test + void jarThatUsesAHostClassItsHostDoesNotExposeFails() { + var jar = module("pack.User", "user:core", NO_MEMBERS, + "graph.define(Stage.placement(\"user:core/carved\")).requires(example.builtin.CarveModule.CLEAR).run(context -> {});") + .compileAgainstHostOf(CarveModule.class) + .writeInto(build, "user.jar"); + + var message = failure(() -> ModuleJarCheck.check(jar, NO_EXPOSED_PACKAGES)); + + assertTrue(message.contains("pack.User -> example.builtin.CarveModule"), message); + } + + @Test + void moduleClassOutsideTheJarFailsNamingTheJarAndTheClass() { + var jar = module("pack.User", "user:core", NO_MEMBERS, NO_STAGES) + .entryPoint("pack.Elsewhere") + .writeInto(build, "user.jar"); + + var message = failure(() -> ModuleJarCheck.check(jar, NO_EXPOSED_PACKAGES)); + + assertTrue(message.contains(jar.toString()), message); + assertTrue(message.contains("lists pack.Elsewhere"), message); + } + + @Test + void jarThatListsNoModuleFails() { + var jar = new TestModuleJar().source("pack.Plain", "package pack; public final class Plain {}").writeInto(build, "plain.jar"); + + assertTrue(failure(() -> ModuleJarCheck.check(jar, NO_EXPOSED_PACKAGES)).contains("has no entry point")); + } +} diff --git a/src/test/java/com/volmit/host/ModuleRegistryTest.java b/src/test/java/com/volmit/host/ModuleRegistryTest.java index 0ead31edc..aed84ac52 100644 --- a/src/test/java/com/volmit/host/ModuleRegistryTest.java +++ b/src/test/java/com/volmit/host/ModuleRegistryTest.java @@ -130,14 +130,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(DiscoveredModule.builtIn(conditioned)), Map.of(), Set.of(), Set.of(), Set.of()); + var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(conditioned)), Map.of(), Set.of(), Set.of()); assertEquals(List.of("test:core/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(DiscoveredModule.builtIn(conditioned)), reserved, Set.of(), Set.of(), Set.of())); + assertThrows(IllegalArgumentException.class, () -> LoadedModules.load(List.of(DiscoveredModule.builtIn(conditioned)), reserved, Set.of(), Set.of())); } @Test @@ -182,11 +182,11 @@ class ModuleRegistryTest { public void install(StageGraph graph) { graph.define(WORK).when(One.class).run((context, one) -> {}); } }; - var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(owner), DiscoveredModule.builtIn(user)), Map.of(), Set.of(), Set.of(), Set.of()); + var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(owner), DiscoveredModule.builtIn(user)), Map.of(), Set.of(), Set.of()); assertEquals(List.of("test:core/one"), loaded.catalog().settings().stream().map(value -> value.id().toString()).toList()); var unowned = assertThrows(IllegalArgumentException.class, - () -> LoadedModules.load(List.of(DiscoveredModule.builtIn(user)), Map.of(), Set.of(), Set.of(), Set.of())); + () -> LoadedModules.load(List.of(DiscoveredModule.builtIn(user)), Map.of(), Set.of(), Set.of())); assertTrue(unowned.getMessage().contains("which none of the modules naming it in when(...) owns"), unowned.getMessage()); } diff --git a/src/test/java/com/volmit/host/PackModulesTest.java b/src/test/java/com/volmit/host/PackModulesTest.java index 6f0c59034..8314eb191 100644 --- a/src/test/java/com/volmit/host/PackModulesTest.java +++ b/src/test/java/com/volmit/host/PackModulesTest.java @@ -2,6 +2,7 @@ package com.volmit.host; import com.volmit.IrisModule; import com.volmit.example.placement.AnchorModule; +import com.volmit.example.placement.MossModule; import com.volmit.example.placement.PlacementModules; import com.volmit.support.TestModuleJar; import example.builtin.CarveModule; @@ -32,8 +33,6 @@ class PackModulesTest { private static final String REQUIRES_BUILT_IN_STAGE = "graph.define(Stage.placement(\"user:core/carved\")).requires(example.builtin.CarveModule.CLEAR).run(context -> {});"; - private static final Set RESERVED_NAMESPACES = Set.of("iris"); - @TempDir Path pack; @@ -44,7 +43,7 @@ class PackModulesTest { private static LoadedModules loadWithBuiltIns(PackModules packModules) { var modules = new ArrayList<>(PlacementModules.builtIns()); modules.addAll(packModules.modules()); - return LoadedModules.load(modules, Map.of(), Set.of(), Set.of(), Set.of()); + return LoadedModules.load(modules, Map.of(), Set.of(), Set.of()); } /** Versioned entries of a multi-release jar are read like any class, so they must be real class files. */ @@ -145,14 +144,50 @@ class PackModulesTest { } @Test - void jarNamingSeveralEntryPointsFails() { + void jarNamingSeveralEntryPointsLoadsEachModuleInListedOrder() { module("pack.First", "first:core", NO_MEMBERS, NO_STAGES) - .source("pack.Second", "package pack; public final class Second {}") - .entryPoint("pack.Second") + .alsoModule("pack.Second", "second:core", NO_MEMBERS, NO_STAGES) + .writeInto(pack, "two.jar"); + + try (var packModules = PackModules.load(pack)) { + assertEquals(List.of("first:core", "second:core"), + packModules.modules().stream().map(found -> found.info().id().toString()).toList()); + assertEquals(List.of(origin("two.jar"), origin("two.jar")), + packModules.modules().stream().map(DiscoveredModule::origin).toList()); + assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())); + } + } + + @Test + void secondEntryPointOfAJarThatBreaksNamesItsClass() { + module("pack.First", "first:core", NO_MEMBERS, NO_STAGES) + .entryPoint("pack.Missing") .writeInto(pack, "two.jar"); assertMentions(failure(() -> PackModules.load(pack)), - "Module jar " + origin("two.jar") + " names 2 entry points [pack.First, pack.Second]"); + "Module jar " + origin("two.jar") + " has a broken entry point pack.Missing: class cannot be loaded"); + } + + @Test + void entryPointOfAnotherJarFailsNamingTheJarThatListsIt() { + module("pack.First", "first:core", NO_MEMBERS, NO_STAGES).writeInto(pack, "first.jar"); + new TestModuleJar().entryPoint("pack.First").writeInto(pack, "second.jar"); + + assertMentions(failure(() -> PackModules.load(pack)), + "Module jar " + origin("second.jar") + " has a broken entry point pack.First", + "loaded from " + origin("first.jar") + ", not from this jar"); + } + + @Test + void optionalPackagesOfAnyModuleOfAJarExcuseItsMissingClasses(@TempDir Path build) { + module("pack.First", "first:core", List.of("org.optional"), NO_MEMBERS, NO_STAGES) + .alsoModule("pack.Second", "second:core", using(OPTIONAL_CLASS), NO_STAGES) + .compileAgainst(library(build, "optional.jar", OPTIONAL_CLASS)) + .writeInto(pack, "two.jar"); + + try (var packModules = PackModules.load(pack)) { + assertEquals(List.of(), packModules.missingClasses()); + } } @Test @@ -343,7 +378,7 @@ class PackModulesTest { try (var packModules = PackModules.load(pack)) { assertEquals(List.of(new MissingClasses(origin("user.jar"), List.of(OPTIONAL_CLASS))), packModules.missingClasses()); - assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of(), Set.of())); + assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())); } } @@ -477,7 +512,7 @@ class PackModulesTest { .writeInto(pack, "beta.jar"); try (var packModules = PackModules.load(pack)) { - var loaded = LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of(), Set.of()); + var loaded = LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of()); assertTrue(loaded.placement().stages().stream().anyMatch(stage -> stage.stage().id().toString().equals("beta:core/size"))); var beta = packModules.modules().getLast().module().getClass(); assertEquals(0, beta.getDeclaredField("SHARED").getAnnotations().length, @@ -494,7 +529,7 @@ class PackModulesTest { try (var packModules = PackModules.load(pack, List.of(BUILT_IN_PACKAGE))) { var modules = new ArrayList<>(List.of(DiscoveredModule.builtIn(new CarveModule()))); modules.addAll(packModules.modules()); - var order = LoadedModules.load(modules, Map.of(), Set.of(), Set.of(), Set.of()).placement().stages().stream() + var order = LoadedModules.load(modules, Map.of(), Set.of(), Set.of()).placement().stages().stream() .map(stage -> stage.stage().id().toString()).toList(); assertEquals(List.of("iris:carve/clear", "user:core/carved"), order); } @@ -572,7 +607,7 @@ class PackModulesTest { .writeInto(pack, "once.jar"); try (var packModules = PackModules.load(pack)) { - var loaded = assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of(), Set.of())); + var loaded = assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())); assertEquals("once:core", packModules.modules().getFirst().info().id().toString()); assertEquals(1, loaded.placement().stages().size()); } @@ -591,7 +626,7 @@ class PackModulesTest { .writeInto(pack, "beta.jar"); try (var packModules = PackModules.load(pack)) { - assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of(), Set.of())), + assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())), "Module beta:core from " + origin("beta.jar") + " failed to link or initialize a class while installing", "java.lang.NoSuchMethodError", "pack.lib.Lib.added()"); } @@ -603,8 +638,9 @@ class PackModulesTest { 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(), Set.of(), Set.of(), Set.of())), - "Duplicate module dup:core from " + origin("two.jar") + "; already loaded from " + origin("one.jar")); + assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())), + "Duplicate module dup:core from " + origin("two.jar") + " (pack.two.Duplicate); already loaded from " + + origin("one.jar") + " (pack.one.Duplicate)"); } } @@ -614,7 +650,8 @@ class PackModulesTest { try (var packModules = PackModules.load(pack)) { assertMentions(failure(() -> loadWithBuiltIns(packModules)), - "Duplicate module example:moss from " + origin("moss.jar") + "; already loaded from host classpath"); + "Duplicate module example:moss from " + origin("moss.jar") + " (pack.Moss); already loaded from host classpath (" + + MossModule.class.getName() + ")"); } } @@ -625,42 +662,32 @@ class PackModulesTest { .writeInto(pack, "foreign.jar"); try (var packModules = PackModules.load(pack)) { - assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of(), Set.of())), + assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())), "Stage mine:other/work must start with mine:core/, the id of its defining module mine:core from " + origin("foreign.jar")); } } @Test - void packModuleInAReservedNamespaceFailsNamingTheJarAndTheNamespace() { + void duplicateModuleIdWithinOneJarFailsNamingBothClasses() { + module("pack.One", "dup:core", NO_MEMBERS, NO_STAGES) + .alsoModule("pack.Two", "dup:core", NO_MEMBERS, NO_STAGES) + .writeInto(pack, "both.jar"); + + try (var packModules = PackModules.load(pack)) { + assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())), + "Duplicate module dup:core from " + origin("both.jar") + " (pack.Two); already loaded from " + + origin("both.jar") + " (pack.One)"); + } + } + + @Test + void packModuleMayUseAnyNamespaceIncludingIris() { module("pack.Stilt", "iris:stilt", NO_MEMBERS, "graph.define(Stage.placement(\"iris:stilt/fill\")).run(context -> {});") .writeInto(pack, "stilt.jar"); try (var packModules = PackModules.load(pack)) { - assertEquals("Module iris:stilt from " + origin("stilt.jar") + " uses reserved namespace 'iris', 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", - failure(() -> LoadedModules.load(packModules.modules(), Map.of(), RESERVED_NAMESPACES, Set.of(), Set.of()))); - assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of(), Set.of())); + assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())); } } - - @Test - void builtInModulesMayUseReservedNamespaces() { - module("pack.user.User", "user:core", NO_MEMBERS, REQUIRES_BUILT_IN_STAGE) - .compileAgainstHostOf(CarveModule.class) - .writeInto(pack, "user.jar"); - - try (var packModules = PackModules.load(pack, List.of(BUILT_IN_PACKAGE))) { - var modules = new ArrayList<>(List.of(DiscoveredModule.builtIn(new CarveModule()))); - modules.addAll(packModules.modules()); - assertDoesNotThrow(() -> LoadedModules.load(modules, Map.of(), RESERVED_NAMESPACES, Set.of(), Set.of())); - } - } - - @Test - void invalidReservedNamespaceFails() { - assertEquals("Reserved namespace 'iris:core' is not a namespace; name one such as iris, without ':' or a path", - failure(() -> LoadedModules.load(List.of(), Map.of(), Set.of("iris:core"), Set.of(), Set.of()))); - } } diff --git a/src/test/java/com/volmit/host/StageGraphTest.java b/src/test/java/com/volmit/host/StageGraphTest.java index 8a7201e78..11562ff03 100644 --- a/src/test/java/com/volmit/host/StageGraphTest.java +++ b/src/test/java/com/volmit/host/StageGraphTest.java @@ -478,7 +478,7 @@ class StageGraphTest { stages.define(plain).run(context -> {}); stages.define(paint).reach(2).run(context -> {}); }); - var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(withMantle(reach, depth, marks))), Map.of(), Set.of(), Set.of(), Set.of()); + var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(withMantle(reach, depth, marks))), Map.of(), Set.of(), Set.of()); assertEquals(new StageReach(24, List.of(depth)), loaded.mantle().stages().getFirst().reach()); assertEquals(StageReach.NONE, loaded.mantle().stages().get(2).reach(), "an undeclared reach is 0 with no layers"); @@ -496,7 +496,7 @@ class StageGraphTest { var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(module("test:reach", stages -> { stages.define(carve).reach(settings -> settings.declared(Toggle.class).isEmpty() ? 4 : 40).run(context -> {}); stages.define(mark).reach(2).run(context -> {}); - }))), Map.of(), Set.of(), Set.of(), Set.of()); + }))), Map.of(), Set.of(), Set.of()); var computed = loaded.mantle().stages().getFirst(); var toggled = new DeclaredSettings(new Entry<>(FeatureAttachment.Target.DIMENSION, ResourceId.parse("pack:dimension/main"), new Toggle())); @@ -512,7 +512,7 @@ class StageGraphTest { @Test void onlyMantleStagesWorkOutTheirReachAndNeverANegativeOne() { var negative = LoadedModules.load(List.of(DiscoveredModule.builtIn(module("test:reach", stages -> - stages.define(Stage.mantle("test:reach/carve")).reach(settings -> -1).run(context -> {})))), Map.of(), Set.of(), Set.of(), Set.of()); + stages.define(Stage.mantle("test:reach/carve")).reach(settings -> -1).run(context -> {})))), Map.of(), Set.of(), Set.of()); var failure = assertThrows(IllegalStateException.class, () -> negative.mantle().stages().getFirst().reachBlocks(DeclaredSettings.NONE)); assertEquals("Stage test:reach/carve of module test:reach worked out a negative reach of -1 blocks for this pack", failure.getMessage()); @@ -567,13 +567,13 @@ class StageGraphTest { module("test:reach", stages -> stages.define(carve).writesMantle(depth, depth).run(context -> {})))); var unregistered = assertThrows(IllegalArgumentException.class, () -> LoadedModules.load(List.of(DiscoveredModule.builtIn( - module("test:reach", stages -> stages.define(carve).writesMantle(depth).run(context -> {})))), Map.of(), Set.of(), Set.of(), Set.of())); + module("test:reach", stages -> stages.define(carve).writesMantle(depth).run(context -> {})))), Map.of(), Set.of(), Set.of())); assertEquals("Stage test:reach/carve of module test:reach writes mantle layer test:reach/depth, which no module registers;" + " its owner registers it with FeatureRegistry.registerMantle", unregistered.getMessage()); var asText = new MantleKey<>("test:reach/depth", String.class); var mismatch = assertThrows(IllegalArgumentException.class, () -> LoadedModules.load(List.of(DiscoveredModule.builtIn(withMantle( - module("test:reach", stages -> stages.define(carve).writesMantle(asText).run(context -> {})), depth))), Map.of(), Set.of(), Set.of(), Set.of())); + module("test:reach", stages -> stages.define(carve).writesMantle(asText).run(context -> {})), depth))), Map.of(), Set.of(), Set.of())); assertEquals("Stage test:reach/carve of module test:reach writes mantle layer test:reach/depth as java.lang.String," + " but it is registered as java.lang.Integer", mismatch.getMessage()); } diff --git a/src/test/java/com/volmit/support/TestModuleJar.java b/src/test/java/com/volmit/support/TestModuleJar.java index a79b04e9b..4234089e6 100644 --- a/src/test/java/com/volmit/support/TestModuleJar.java +++ b/src/test/java/com/volmit/support/TestModuleJar.java @@ -49,6 +49,12 @@ public final class TestModuleJar { return new TestModuleJar().source(className, moduleSource(className, info, members, install)).entryPoint(className); } + /** Another entry class in the same jar, with the given module id; see {@link #module(String, String, String, String)}. */ + public TestModuleJar alsoModule(String className, String moduleId, String members, String install) { + var info = moduleInfo(moduleId, List.of()); + return source(className, moduleSource(className, info, members, install)).entryPoint(className); + } + /** Compiles one class on its own and returns its class file, for raw entries such as versioned classes. */ public static byte[] compileClass(Path workDirectory, String className, String code) { try {