ModuleLog: each module's own log, labelled with its id, reached as context.log(), PackWorld.log() and FeatureRegistry.log()

This commit is contained in:
piexel committed 2026-10-10 14:00:38 +02:00
1 parent d7de5939d7
commit e0ffe04a0d
26 files changed
+625 -27

No files matched your search

@@ -15,6 +15,11 @@ import com.volmit.validation.Validator;
* registers are its module id or start with it and {@code /}, such as {@code iris:snow} or {@code iris:snow/depth}.
*/
public interface FeatureRegistry {
/** The registering module's own log. A module that wants to log from its hooks keeps the one it gets here; a call
* outside {@link IrisModule#register} throws IllegalStateException.
*/
ModuleLog log();
/** Registers a layer before pack loading. Null arguments throw NullPointerException;
* duplicate IDs and negative codec versions throw IllegalArgumentException.
* Only the owner registers a shared layer; consumers refer to its key. The host must
+35
View File
@@ -0,0 +1,35 @@
package com.volmit;
/** The log of one module. The host labels every line with the module's id, such as {@code [iris:decorant]}, and writes it
* to its own log, so a module never needs a logging library of its own and its lines are easy to find. Each module has
* its own: reach it as {@code context.log()} in stage bodies and generators
* ({@link com.volmit.generation.InvocationContext#log}), as {@link com.volmit.world.PackWorld#log} in services and
* lifecycle hooks, and as {@link FeatureRegistry#log} while the module registers.
*
* <p>Safe to use from any thread. A message is plain text, not a format string.
*/
public interface ModuleLog {
/** Detail for people debugging the module. The host writes it only when its debug setting is on, so building the
* message costs time even when nobody reads it: guard a message that is expensive to build, or leave it out.
*/
void debug(String message);
/** Something worth telling the server owner once in a while, such as what the module did at startup. */
void info(String message);
/** Something is wrong or unusual, but the module carries on. */
void warn(String message);
/** Warns the first time {@code key} is used on this log and writes {@code message} at {@link #debug} level every
* time after, for a condition worth stating once that is met per block, per sample or per chunk. Keys belong to the
* module: two modules can use the same key and each warns once. The key space must be bounded, so never put a
* coordinate in it; the host stops claiming new keys beyond a few hundred and then only debugs.
*/
void warnOnce(String key, String message);
/** Logs {@code message} as an error and reports {@code cause} the way the host reports its own failures, such as
* to its error tracker. Use it for a failure the module caught but cannot recover from. A null {@code cause}
* only logs the message.
*/
void error(String message, Throwable cause);
}
@@ -1,5 +1,6 @@
package com.volmit.generation;
import com.volmit.ModuleLog;
import com.volmit.resource.PackResources;
import com.volmit.world.PackWorld;
@@ -16,4 +17,11 @@ public interface InvocationContext {
* invocation outside any world, such as an object a studio tool pastes, throws IllegalStateException.
*/
PackWorld world();
/** The log of the module this invocation runs for, labelled with the module's id. The same as
* {@code world().log()}, which a host overrides where an invocation has no world.
*/
default ModuleLog log() {
return world().log();
}
}
@@ -68,7 +68,7 @@ final class ChunkInvocation implements ChunkStageContext {
@Override
public PackWorld world() {
return inputs.world();
return stages.world(inputs.world());
}
@Override
@@ -2,6 +2,7 @@ package com.volmit.host;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.ModuleLog;
import java.util.Objects;
/** A module, its identity and where the host found it. Load errors name the origin so the author
@@ -21,12 +22,14 @@ public final class DiscoveredModule {
private final ModuleInfo info;
private final String origin;
private final Source source;
private final ModuleLog log;
private DiscoveredModule(IrisModule module, ModuleInfo info, String origin, Source source) {
private DiscoveredModule(IrisModule module, ModuleInfo info, String origin, Source source, ModuleLog log) {
this.module = Objects.requireNonNull(module, "module");
this.info = Objects.requireNonNull(info, "info");
this.origin = Objects.requireNonNull(origin, "origin");
this.source = Objects.requireNonNull(source, "source");
this.log = Objects.requireNonNull(log, "log");
if (origin.isBlank()) {
throw new IllegalArgumentException("Blank module origin: " + module.getClass().getName());
}
@@ -37,12 +40,17 @@ public final class DiscoveredModule {
*/
public static DiscoveredModule builtIn(IrisModule module) {
Objects.requireNonNull(module, "module");
return new DiscoveredModule(module, readInfo(module), HOST_CLASSPATH, Source.HOST);
var info = readInfo(module);
return new DiscoveredModule(module, info, HOST_CLASSPATH, Source.HOST, defaultLog(info));
}
/** A pack module whose {@code info()} the jar loader has already read and checked. */
static DiscoveredModule fromJar(IrisModule module, ModuleInfo info, String origin) {
return new DiscoveredModule(module, info, origin, Source.PACK);
return new DiscoveredModule(module, info, origin, Source.PACK, defaultLog(info));
}
private static ModuleLog defaultLog(ModuleInfo info) {
return ModuleLogs.labelled(info.id().toString(), PackModules.DEFAULT_LOGGER);
}
private static ModuleInfo readInfo(IrisModule module) {
@@ -58,6 +66,18 @@ public final class DiscoveredModule {
return info;
}
/** This module with a log of its own that writes to {@code logger}; the module keeps no keys of the log it had
* ({@link ModuleLog#warnOnce}). The host does it once for a module it hands out.
*/
public DiscoveredModule loggingTo(System.Logger logger) {
return new DiscoveredModule(module, info, origin, source, ModuleLogs.labelled(info.id().toString(), logger));
}
/** The module's own log, labelled with its id. */
public ModuleLog log() {
return log;
}
/** The jar path relative to the pack, or "host classpath" for built-in modules. */
public String origin() {
return origin;
@@ -1,11 +1,13 @@
package com.volmit.host;
import com.volmit.ModuleLog;
import com.volmit.stage.Stage;
/** Execution data of one resolved stage. Indices are positions in the resolved order.
* readableStages/readablePositions are the transitive requirements whose outputs it may read.
* settingsSlot indexes the graph's distinct settings types, or is NO_SETTINGS. idHash keys the
* stage's random stream ({@link StageStreams}), computed once per pack load.
* stage's random stream ({@link StageStreams}), computed once per pack load. log is the log of the module that
* defined the stage.
*/
record ExecutableStage(
Stage<?> stage,
@@ -14,7 +16,8 @@ record ExecutableStage(
Stage<?>[] readableStages,
int[] readablePositions,
int settingsSlot,
long idHash) {
long idHash,
ModuleLog log) {
static final int NO_SETTINGS = -1;
static final int NOT_READABLE = -1;
@@ -225,7 +225,8 @@ final class GraphResolver {
.toArray(Stage<?>[]::new),
readable[index].stream().toArray(),
settingsSlot(declaration, settingsTypes),
StageStreams.idHash(declaration.stage().id()));
StageStreams.idHash(declaration.stage().id()),
declaration.log());
stages.add(new ResolvedStage(declaration.stage(), declaration.module(), declaration.settings(),
incomingEdges(node, position), absentSoftTargets.get(node), declaration.reach()));
}
@@ -0,0 +1,60 @@
package com.volmit.host;
import com.volmit.ModuleLog;
import java.lang.System.Logger.Level;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/** A module's log on the host's {@link System.Logger}; see {@link ModuleLogs#labelled}. */
final class LabelledModuleLog implements ModuleLog {
/** What keeps a key space nobody bounded, such as block names, from growing without end. */
private static final int MAX_ONCE_KEYS = 512;
private final String label;
private final System.Logger logger;
private final Set<String> claimedKeys = ConcurrentHashMap.newKeySet();
LabelledModuleLog(String moduleId, System.Logger logger) {
this.label = "[" + moduleId + "] ";
this.logger = logger;
}
@Override
public void debug(String message) {
if (!logger.isLoggable(Level.DEBUG)) {
return;
}
logger.log(Level.DEBUG, label + message);
}
@Override
public void info(String message) {
logger.log(Level.INFO, label + message);
}
@Override
public void warn(String message) {
logger.log(Level.WARNING, label + message);
}
@Override
public void warnOnce(String key, String message) {
if (!claim(key)) {
debug(message);
return;
}
warn(message);
}
@Override
public void error(String message, Throwable cause) {
logger.log(Level.ERROR, label + message, cause);
}
private boolean claim(String key) {
if (claimedKeys.size() >= MAX_ONCE_KEYS) {
return false;
}
return claimedKeys.add(String.valueOf(key));
}
}
@@ -1,6 +1,7 @@
package com.volmit.host;
import com.volmit.ModuleLifecycle;
import com.volmit.world.PackWorld;
import java.util.Objects;
/** Lifecycle hooks and the module that registered them, which the host names when a hook fails. */
@@ -9,4 +10,11 @@ public record LifecycleRegistration(ModuleLifecycle lifecycle, DiscoveredModule
Objects.requireNonNull(lifecycle, "lifecycle");
Objects.requireNonNull(module, "module");
}
/** {@code world} as this hook's module sees it, which the host hands to the hook so that {@link PackWorld#log} is the
* module's own.
*/
PackWorld scope(PackWorld world) {
return world.withLog(module.log());
}
}
@@ -52,7 +52,7 @@ public final class LifecycleRunner {
for (int index = 0; index < lifecycles.size(); index++) {
var registration = lifecycles.get(index);
try {
registration.lifecycle().worldStarted(world);
registration.lifecycle().worldStarted(registration.scope(world));
} catch (RuntimeException failure) {
var startFailure = failed("starting a world", registration, failure);
stopInReverse(world, index - 1, startFailure);
@@ -70,7 +70,7 @@ public final class LifecycleRunner {
IllegalStateException failure = null;
for (var registration : lifecycles) {
try {
registration.lifecycle().warmUp(world);
registration.lifecycle().warmUp(registration.scope(world));
} catch (RuntimeException warmFailure) {
var named = failed("warming up a world", registration, warmFailure);
if (failure == null) {
@@ -101,7 +101,7 @@ public final class LifecycleRunner {
for (int index = last; index >= 0; index--) {
var registration = lifecycles.get(index);
try {
registration.lifecycle().worldStopped(world);
registration.lifecycle().worldStopped(registration.scope(world));
} catch (RuntimeException stopFailure) {
var named = failed("stopping a world", registration, stopFailure);
if (failure == null) {
@@ -62,7 +62,7 @@ final class MantleInvocation implements MantleStageContext {
@Override
public PackWorld world() {
return inputs.world();
return stages.world(inputs.world());
}
@Override
@@ -61,7 +61,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(), systemTemporaryDirectory(),
System.getLogger(PackModules.class.getName()));
PackModules.DEFAULT_LOGGER);
}
/** This configuration with {@code packages}, each with its subpackages, also exposed to pack
@@ -106,11 +106,14 @@ public record ModuleHost(
reservedFolders, directory, logger);
}
/** This configuration logging each pack load's module summary and missing-classes warning to
* {@code logger}, such as an adapter to the host's own log. The last call wins.
/** This configuration logging each pack load's module summary and missing-classes warning, and every module's own
* log ({@link com.volmit.ModuleLog}), to {@code logger}, such as an adapter to the host's own log. A module's lines
* carry its id and its {@link System.Logger.Level#ERROR} lines the failure to report. The last call wins.
*/
public ModuleHost loggingTo(System.Logger logger) {
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, hostTypePackages,
Objects.requireNonNull(logger, "logger");
var loggedBuiltIns = builtIns.stream().map(builtIn -> builtIn.loggingTo(logger)).toList();
return new ModuleHost(loggedBuiltIns, exposedHostPackages, reservedHostFields, hostTypePackages,
reservedFolders, jarCopyRoot, logger);
}
@@ -0,0 +1,49 @@
package com.volmit.host;
import com.volmit.ModuleLog;
import java.util.Objects;
/** The logs a host hands to modules. */
public final class ModuleLogs {
private static final ModuleLog DISCARDING = new DiscardingLog();
private ModuleLogs() {
}
/** A module's log writing to {@code logger} with the module's id in front of each message, such as
* {@code [iris:decorant] Empty Block Data for plains}. {@link ModuleLog#debug} writes at
* {@link System.Logger.Level#DEBUG} and only when {@code logger} is loggable at that level;
* {@link ModuleLog#error} passes its cause to the logger, which is where the host reports it. A log keeps its
* {@link ModuleLog#warnOnce} keys, so make one per module, not one per message.
*/
public static ModuleLog labelled(String moduleId, System.Logger logger) {
return new LabelledModuleLog(Objects.requireNonNull(moduleId, "moduleId"), Objects.requireNonNull(logger, "logger"));
}
/** A log that writes nothing, for tests and tools that run module code without a host. */
public static ModuleLog discarding() {
return DISCARDING;
}
private static final class DiscardingLog implements ModuleLog {
@Override
public void debug(String message) {
}
@Override
public void info(String message) {
}
@Override
public void warn(String message) {
}
@Override
public void warnOnce(String key, String message) {
}
@Override
public void error(String message, Throwable cause) {
}
}
}
@@ -5,6 +5,7 @@ import com.volmit.FeatureRegistry;
import com.volmit.IrisFeature;
import com.volmit.IrisModule;
import com.volmit.ModuleLifecycle;
import com.volmit.ModuleLog;
import com.volmit.mantle.MantleCodec;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
@@ -81,6 +82,14 @@ public final class ModuleRegistry implements FeatureRegistry {
}
}
@Override
public ModuleLog log() {
if (registering == null) {
throw new IllegalStateException("The registry's log is only available during IrisModule.register");
}
return registering.log();
}
@Override
public <F extends IrisFeature> void registerObject(
Class<F> featureType,
+13 -8
View File
@@ -47,7 +47,7 @@ public final class PackModules implements AutoCloseable {
public static final String MODULES_DIRECTORY = "modules";
static final String JAR_EXTENSION = ".jar";
private static final String TEMPORARY_DIRECTORY_PROPERTY = "java.io.tmpdir";
private static final System.Logger DEFAULT_LOGGER = System.getLogger(PackModules.class.getName());
static final System.Logger DEFAULT_LOGGER = System.getLogger(PackModules.class.getName());
private final List<DiscoveredModule> modules;
private final List<MissingClasses> missingClasses;
@@ -92,7 +92,7 @@ public final class PackModules implements AutoCloseable {
StaleJarSnapshots.remove(temporaryRoot);
var snapshot = JarSnapshot.take(packRoot, findModuleJars(packRoot), temporaryRoot);
try {
var packModules = loadSnapshot(packRoot, snapshot, host);
var packModules = loadSnapshot(packRoot, snapshot, host, logger);
logLoad(logger, packName(packRoot), packModules);
return packModules;
} catch (RuntimeException | Error failure) {
@@ -131,10 +131,10 @@ public final class PackModules implements AutoCloseable {
return Path.of(System.getProperty(TEMPORARY_DIRECTORY_PROPERTY));
}
private static PackModules loadSnapshot(Path packRoot, JarSnapshot snapshot, ExposedHostClassLoader host) {
private static PackModules loadSnapshot(Path packRoot, JarSnapshot snapshot, ExposedHostClassLoader host, System.Logger logger) {
var jars = snapshot.jars().stream().map(ModuleJar::read).toList();
var missingClasses = PackClassCheck.requireLinkable(jars, host);
return defineModules(packRoot, jars, missingClasses, host, snapshot);
return defineModules(packRoot, jars, missingClasses, host, snapshot, logger);
}
private static List<Path> findModuleJars(Path packRoot) {
@@ -155,10 +155,11 @@ public final class PackModules implements AutoCloseable {
}
private static PackModules defineModules(
Path packRoot, List<ModuleJar> jars, List<MissingClasses> missingClasses, ClassLoader host, JarSnapshot snapshot) {
Path packRoot, List<ModuleJar> jars, List<MissingClasses> missingClasses, ClassLoader host, JarSnapshot snapshot,
System.Logger logger) {
var loader = newPackClassLoader(packRoot, jars, host);
try {
var modules = createModules(jars, loader, snapshot);
var modules = createModules(jars, loader, snapshot, logger);
return new PackModules(modules, withoutDeclaredOptional(missingClasses, modules), loader, snapshot);
} catch (RuntimeException | Error failure) {
closeAfterFailure(loader, failure);
@@ -182,8 +183,12 @@ public final class PackModules implements AutoCloseable {
return name == null ? packRoot.toString() : name.toString();
}
private static List<DiscoveredModule> createModules(List<ModuleJar> jars, ClassLoader loader, JarSnapshot snapshot) {
return jars.stream().flatMap(jar -> jar.createModules(loader, snapshot).stream()).toList();
private static List<DiscoveredModule> createModules(
List<ModuleJar> jars, ClassLoader loader, JarSnapshot snapshot, System.Logger logger) {
return jars.stream()
.flatMap(jar -> jar.createModules(loader, snapshot).stream())
.map(module -> module.loggingTo(logger))
.toList();
}
/** A module's optional packages excuse only its own jar's missing classes; a jar with several
@@ -114,7 +114,7 @@ final class PlacementInvocation implements BlockStageContext {
@Override
public PackWorld world() {
return inputs.world();
return stages.world(inputs.world());
}
@Override
@@ -1,5 +1,6 @@
package com.volmit.host;
import com.volmit.world.PackWorld;
import java.util.Objects;
/** One provider of a service and the module that registered it. */
@@ -10,6 +11,13 @@ public record ServiceRegistration(Class<?> service, Object provider, DiscoveredM
Objects.requireNonNull(module, "module");
}
/** {@code world} as this provider's module sees it, which the host hands to the provider's methods so that
* {@link PackWorld#log} is the module's own.
*/
public PackWorld scope(PackWorld world) {
return world.withLog(module.log());
}
@Override
public String toString() {
return "provider of " + service.getName() + " from module " + module;
@@ -1,6 +1,7 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.ModuleLog;
import com.volmit.mantle.MantleKey;
import com.volmit.resource.ResourceId;
import com.volmit.stage.PackReach;
@@ -17,6 +18,7 @@ import java.util.Optional;
final class StageDeclaration {
private final Stage<?> stage;
private final ResourceId module;
private final ModuleLog log;
private final List<Stage<?>> requirements = new ArrayList<>();
private final List<StageRef> softAfter = new ArrayList<>();
private final List<StageRef> softBefore = new ArrayList<>();
@@ -25,9 +27,10 @@ final class StageDeclaration {
private final List<MantleKey<?>> mantleLayers = new ArrayList<>();
private StageBody body;
StageDeclaration(Stage<?> stage, ResourceId module) {
StageDeclaration(Stage<?> stage, ResourceId module, ModuleLog log) {
this.stage = Objects.requireNonNull(stage, "stage");
this.module = Objects.requireNonNull(module, "module");
this.log = Objects.requireNonNull(log, "log");
}
void require(Stage<?>... stages) {
@@ -122,6 +125,10 @@ final class StageDeclaration {
return module;
}
ModuleLog log() {
return log;
}
List<Stage<?>> requirements() {
return List.copyOf(requirements);
}
@@ -143,7 +143,7 @@ public final class StageGraphBuilder implements StageGraph {
requireOwnedStageId(stage, discovered);
var module = discovered.info().id();
var declaration = new StageDeclaration(stage, module);
var declaration = new StageDeclaration(stage, module, discovered.log());
var previous = declarations.putIfAbsent(stage.id(), declaration);
if (previous != null) {
throw new IllegalArgumentException("Duplicate definition of stage " + stage.id() + " by module "
@@ -4,6 +4,7 @@ import com.volmit.IrisFeature;
import com.volmit.random.WorldRandom;
import com.volmit.stage.BlockStageContext;
import com.volmit.stage.Stage;
import com.volmit.world.PackWorld;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.IntStream;
@@ -25,6 +26,7 @@ final class StageInvocation {
private final Object[] outputs;
private final long invocationSeed;
private final WorldRandom[] streams;
private final PackWorld[] scopedWorlds;
private int current = NO_STAGE;
StageInvocation(ResolvedGraph graph, long invocationSeed, ConfiguredSettings settings) {
@@ -35,6 +37,7 @@ final class StageInvocation {
Arrays.fill(outputs, PENDING);
this.invocationSeed = invocationSeed;
streams = new WorldRandom[graph.size()];
scopedWorlds = new PackWorld[graph.size()];
}
boolean isActive(int position) {
@@ -107,6 +110,17 @@ final class StageInvocation {
return streams[current];
}
/** {@code world} as the running stage's module sees it, whose log is the module's own. Between stages it is {@code world}. */
PackWorld world(PackWorld world) {
if (current == NO_STAGE) {
return world;
}
if (scopedWorlds[current] == null) {
scopedWorlds[current] = world.withLog(graph.executable(current).log());
}
return scopedWorlds[current];
}
private ExecutableStage currentStage() {
if (current == NO_STAGE) {
throw new IllegalStateException("Stage outputs can only be read while a stage runs");
@@ -1,5 +1,6 @@
package com.volmit.world;
import com.volmit.ModuleLog;
import com.volmit.config.PackSettings;
import com.volmit.resource.PackResources;
import java.util.function.Function;
@@ -38,4 +39,14 @@ public interface PackWorld {
* stopped, asking for state throws IllegalStateException.
*/
<T> T state(Class<T> type, Function<? super PackWorld, ? extends T> create);
/** The log of the module this world was handed to: every service call, lifecycle hook and stage body gets a view of
* the world whose log is that module's own, so a line is labelled with the module that wrote it.
*/
ModuleLog log();
/** For the host: this world as {@code log}'s module sees it, sharing everything else, state included. The host calls it
* once per module it hands a world to; a module has no reason to.
*/
PackWorld withLog(ModuleLog log);
}