diff --git a/CONTRACTS.md b/CONTRACTS.md index e75816330..3d7c605ec 100644 --- a/CONTRACTS.md +++ b/CONTRACTS.md @@ -105,6 +105,10 @@ running Iris is the pack publisher's responsibility. themselves. - Name the packages of the classes Iris describes itself with `ModuleHost.describingHostTypesIn(...)`, decode them as Iris does, and render each `HostKind` with Iris's own description of the class. +- Back each module's log with the host's own: `ModuleHost.loggingTo(logger)` where `logger` writes `DEBUG` only when the + host's debug setting is on and writes an `ERROR` with a cause as the host reports its own failures. Implement + `PackWorld.log()` and `withLog(log)` (a view of the world sharing everything else) and hand services a world scoped to the + provider's module (`ServiceRegistration.scope`); the runners do it for stages and hooks. - Hand modules heights above the dimension's bottom (0 = bottom block, whatever the platform's minimum height is) in every value that carries Y: samples, bounds, block views, placement edits, the mantle, hunks. X and Z stay world coordinates. Convert in one place at the boundary. diff --git a/DESIGN.md b/DESIGN.md index 8a449531e..12577125b 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -963,6 +963,32 @@ each world a state store and tells modules when worlds start and stop. streams, warm-up, placement workers, structure indexes) is per world; per-world state built from pack data costs a little duplication when several worlds share a pack. +## Module logging + +Iris's features logged through its static `IrisLogging`, which a module jar cannot see and a host cannot label. The API +gives each module a `ModuleLog` instead. + +- **Shape.** `debug`, `info`, `warn`, `warnOnce(key, message)` and `error(message, cause)`: the levels the features used, + the "state it once" helper they all grew (a condition met per block must not flood the log), and error reporting with the + failure attached. Messages are plain text, so a `%` or `{` in a pack's names never breaks a line. +- **One log per module, labelled by the host.** `DiscoveredModule.log()` is created when the host discovers the module + (built-in modules once, pack modules per pack load) from the `System.Logger` the host passed to `ModuleHost.loggingTo`, + the same one the load summary uses, and puts `[module id] ` in front of every message. The host's logger decides what + `DEBUG` means (Iris follows its debug setting) and what an `ERROR` with a cause does (Iris reports it like its own + failures). The reference `ModuleLogs.labelled` implements the labelling, the once-keys and the debug check; a host only + supplies the `System.Logger`. `warnOnce` keys are kept per log, so they belong to the module, and past a few hundred new + keys it only debugs, which keeps a key space nobody bounded from growing. +- **Where a module reaches it.** `InvocationContext.log()` for stage bodies and generators, `PackWorld.log()` for services + and lifecycle hooks, `FeatureRegistry.log()` during `register`. The world and the context agree: the runners hand a stage a + view of the world whose log is its module's (`PackWorld.withLog`, a host method; the view shares the state store), and + `LifecycleRunner` and `ServiceRegistration.scope` do the same for hooks and providers. A host that calls a provider itself + must scope the world, or the provider's lines carry the host's label. +- **Why not `System.Logger` for modules.** A module that logs through the JDK works where the host installed a logger + finder and silently goes elsewhere where it did not (Iris's plugin class loader is not the system loader), and nothing + tells the host which module spoke. +- **Not added:** format arguments (callers build the message; a string concatenation is cheap beside what a debug line + costs when it is on), and a `ValidationContext` log (validators report problems as values, `Problem`). + ## Services Iris core still asks feature classes directly: which objects a chunk gets, where a structure is, which tree grows diff --git a/README.md b/README.md index 8d894069d..e70b738a6 100644 --- a/README.md +++ b/README.md @@ -269,6 +269,31 @@ public final class RuinsModule implements IrisModule, ModuleLifecycle { starting, naming the module (modules that had started get `worldStopped`); every `worldStopped` runs even when one fails. +## Logging + +A module writes to its own `ModuleLog`, which the host labels with the module's id and writes to its own log: + +```java +private static void decorate(ChunkStageContext context) { + context.log().warnOnce("empty:" + biomeKey, "Empty block data for " + biomeKey); // [Iris/WARN] [iris:decorant] Empty block data for plains + context.log().debug("decorated chunk " + context.originX() + "," + context.originZ()); +} +``` + +| Method | Use | +| --- | --- | +| `debug(message)` | Detail for people debugging the module. Written only when the host's debug setting is on. Building the message still costs, so keep it cheap or guard it. | +| `info(message)` | What a server owner may want to see once, such as what the module did at startup. | +| `warn(message)` | Something is wrong or unusual and the module carries on. | +| `warnOnce(key, message)` | `warn` the first time the key is used on this module's log, `debug` every time after. For a condition met per block or per chunk. Keys belong to the module, so another module's identical key does not hide yours; keep the key space small (a biome name, never a coordinate). | +| `error(message, cause)` | A failure the module caught and cannot recover from. The host logs it and reports `cause` like its own failures. A null `cause` only logs. | + +- A message is plain text, never a format string. +- `context.log()` (stage bodies, object generators), `world.log()` (services and lifecycle hooks, which get a world as + their argument) and `registry.log()` (while `register` runs) are the same module's log. Keep the registry's log in a + field when `packLoaded`, which has no world, needs to log. `registry.log()` outside `register` throws. +- Do not use `System.out`, `System.getLogger` or a logging library of your own: the host cannot label or report them. + ## Services The host asks modules for what only they know, such as which objects a chunk gets or where a structure is, through diff --git a/src/main/java/com/volmit/FeatureRegistry.java b/src/main/java/com/volmit/FeatureRegistry.java index 050828d3f..4d51e0f96 100644 --- a/src/main/java/com/volmit/FeatureRegistry.java +++ b/src/main/java/com/volmit/FeatureRegistry.java @@ -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 diff --git a/src/main/java/com/volmit/ModuleLog.java b/src/main/java/com/volmit/ModuleLog.java new file mode 100644 index 000000000..17e2e0f89 --- /dev/null +++ b/src/main/java/com/volmit/ModuleLog.java @@ -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. + * + *

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); +} diff --git a/src/main/java/com/volmit/generation/InvocationContext.java b/src/main/java/com/volmit/generation/InvocationContext.java index a7875ba2a..8c78b0e6b 100644 --- a/src/main/java/com/volmit/generation/InvocationContext.java +++ b/src/main/java/com/volmit/generation/InvocationContext.java @@ -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(); + } } diff --git a/src/main/java/com/volmit/host/ChunkInvocation.java b/src/main/java/com/volmit/host/ChunkInvocation.java index daa2de820..bc5f7fe2e 100644 --- a/src/main/java/com/volmit/host/ChunkInvocation.java +++ b/src/main/java/com/volmit/host/ChunkInvocation.java @@ -68,7 +68,7 @@ final class ChunkInvocation implements ChunkStageContext { @Override public PackWorld world() { - return inputs.world(); + return stages.world(inputs.world()); } @Override diff --git a/src/main/java/com/volmit/host/DiscoveredModule.java b/src/main/java/com/volmit/host/DiscoveredModule.java index 6c474db17..1097443e9 100644 --- a/src/main/java/com/volmit/host/DiscoveredModule.java +++ b/src/main/java/com/volmit/host/DiscoveredModule.java @@ -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; diff --git a/src/main/java/com/volmit/host/ExecutableStage.java b/src/main/java/com/volmit/host/ExecutableStage.java index ce04be771..d2441668e 100644 --- a/src/main/java/com/volmit/host/ExecutableStage.java +++ b/src/main/java/com/volmit/host/ExecutableStage.java @@ -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; diff --git a/src/main/java/com/volmit/host/GraphResolver.java b/src/main/java/com/volmit/host/GraphResolver.java index f5925024c..b41a48af4 100644 --- a/src/main/java/com/volmit/host/GraphResolver.java +++ b/src/main/java/com/volmit/host/GraphResolver.java @@ -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())); } diff --git a/src/main/java/com/volmit/host/LabelledModuleLog.java b/src/main/java/com/volmit/host/LabelledModuleLog.java new file mode 100644 index 000000000..f10ab9e7d --- /dev/null +++ b/src/main/java/com/volmit/host/LabelledModuleLog.java @@ -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 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)); + } +} diff --git a/src/main/java/com/volmit/host/LifecycleRegistration.java b/src/main/java/com/volmit/host/LifecycleRegistration.java index b08dbb0eb..0629025e0 100644 --- a/src/main/java/com/volmit/host/LifecycleRegistration.java +++ b/src/main/java/com/volmit/host/LifecycleRegistration.java @@ -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()); + } } diff --git a/src/main/java/com/volmit/host/LifecycleRunner.java b/src/main/java/com/volmit/host/LifecycleRunner.java index 7ccdc8782..e52afc211 100644 --- a/src/main/java/com/volmit/host/LifecycleRunner.java +++ b/src/main/java/com/volmit/host/LifecycleRunner.java @@ -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) { diff --git a/src/main/java/com/volmit/host/MantleInvocation.java b/src/main/java/com/volmit/host/MantleInvocation.java index bbd17b3f7..8aeb09523 100644 --- a/src/main/java/com/volmit/host/MantleInvocation.java +++ b/src/main/java/com/volmit/host/MantleInvocation.java @@ -62,7 +62,7 @@ final class MantleInvocation implements MantleStageContext { @Override public PackWorld world() { - return inputs.world(); + return stages.world(inputs.world()); } @Override diff --git a/src/main/java/com/volmit/host/ModuleHost.java b/src/main/java/com/volmit/host/ModuleHost.java index 305739d36..74766571e 100644 --- a/src/main/java/com/volmit/host/ModuleHost.java +++ b/src/main/java/com/volmit/host/ModuleHost.java @@ -61,7 +61,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(), 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); } diff --git a/src/main/java/com/volmit/host/ModuleLogs.java b/src/main/java/com/volmit/host/ModuleLogs.java new file mode 100644 index 000000000..99c19984e --- /dev/null +++ b/src/main/java/com/volmit/host/ModuleLogs.java @@ -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) { + } + } +} diff --git a/src/main/java/com/volmit/host/ModuleRegistry.java b/src/main/java/com/volmit/host/ModuleRegistry.java index a84b5cb18..20e91f039 100644 --- a/src/main/java/com/volmit/host/ModuleRegistry.java +++ b/src/main/java/com/volmit/host/ModuleRegistry.java @@ -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 void registerObject( Class featureType, diff --git a/src/main/java/com/volmit/host/PackModules.java b/src/main/java/com/volmit/host/PackModules.java index 0f683a973..7a11d78ad 100644 --- a/src/main/java/com/volmit/host/PackModules.java +++ b/src/main/java/com/volmit/host/PackModules.java @@ -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 modules; private final List 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 findModuleJars(Path packRoot) { @@ -155,10 +155,11 @@ public final class PackModules implements AutoCloseable { } private static PackModules defineModules( - Path packRoot, List jars, List missingClasses, ClassLoader host, JarSnapshot snapshot) { + Path packRoot, List jars, List 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 createModules(List jars, ClassLoader loader, JarSnapshot snapshot) { - return jars.stream().flatMap(jar -> jar.createModules(loader, snapshot).stream()).toList(); + private static List createModules( + List 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 diff --git a/src/main/java/com/volmit/host/PlacementInvocation.java b/src/main/java/com/volmit/host/PlacementInvocation.java index ed14c48e0..236853668 100644 --- a/src/main/java/com/volmit/host/PlacementInvocation.java +++ b/src/main/java/com/volmit/host/PlacementInvocation.java @@ -114,7 +114,7 @@ final class PlacementInvocation implements BlockStageContext { @Override public PackWorld world() { - return inputs.world(); + return stages.world(inputs.world()); } @Override diff --git a/src/main/java/com/volmit/host/ServiceRegistration.java b/src/main/java/com/volmit/host/ServiceRegistration.java index 408f9b1cf..603fe6b16 100644 --- a/src/main/java/com/volmit/host/ServiceRegistration.java +++ b/src/main/java/com/volmit/host/ServiceRegistration.java @@ -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; diff --git a/src/main/java/com/volmit/host/StageDeclaration.java b/src/main/java/com/volmit/host/StageDeclaration.java index 1e7fdaf67..9b2d952a9 100644 --- a/src/main/java/com/volmit/host/StageDeclaration.java +++ b/src/main/java/com/volmit/host/StageDeclaration.java @@ -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> requirements = new ArrayList<>(); private final List softAfter = new ArrayList<>(); private final List softBefore = new ArrayList<>(); @@ -25,9 +27,10 @@ final class StageDeclaration { private final List> 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> requirements() { return List.copyOf(requirements); } diff --git a/src/main/java/com/volmit/host/StageGraphBuilder.java b/src/main/java/com/volmit/host/StageGraphBuilder.java index 976f22347..5ffd57cf4 100644 --- a/src/main/java/com/volmit/host/StageGraphBuilder.java +++ b/src/main/java/com/volmit/host/StageGraphBuilder.java @@ -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 " diff --git a/src/main/java/com/volmit/host/StageInvocation.java b/src/main/java/com/volmit/host/StageInvocation.java index d6d3a8e31..9ef5a744e 100644 --- a/src/main/java/com/volmit/host/StageInvocation.java +++ b/src/main/java/com/volmit/host/StageInvocation.java @@ -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"); diff --git a/src/main/java/com/volmit/world/PackWorld.java b/src/main/java/com/volmit/world/PackWorld.java index cfc052f67..a944650c1 100644 --- a/src/main/java/com/volmit/world/PackWorld.java +++ b/src/main/java/com/volmit/world/PackWorld.java @@ -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 state(Class type, Function 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); } diff --git a/src/test/java/com/volmit/host/ModuleLogTest.java b/src/test/java/com/volmit/host/ModuleLogTest.java new file mode 100644 index 000000000..56a0fe78a --- /dev/null +++ b/src/test/java/com/volmit/host/ModuleLogTest.java @@ -0,0 +1,275 @@ +package com.volmit.host; + +import com.volmit.FeatureRegistry; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleLifecycle; +import com.volmit.ModuleLog; +import com.volmit.stage.ChunkStage; +import com.volmit.stage.Pipeline; +import com.volmit.stage.Stage; +import com.volmit.stage.StageGraph; +import com.volmit.support.TestContexts; +import com.volmit.support.TestModuleJar; +import com.volmit.support.TestWorld; +import com.volmit.world.PackWorld; +import java.lang.System.Logger.Level; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.ResourceBundle; +import java.util.Set; +import java.nio.file.Path; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import static org.junit.jupiter.api.Assertions.*; + +class ModuleLogTest { + private static final String ALPHA = "test:alpha"; + private static final String BETA = "test:beta"; + private static final int ONCE_KEY_CAP = 512; + + /** A host logger that remembers what it was asked to write. */ + private static final class RecordingLogger implements System.Logger { + record Line(Level level, String message, Throwable thrown) {} + + final List lines = new ArrayList<>(); + boolean debugEnabled = true; + + @Override + public String getName() { + return "recording"; + } + + @Override + public boolean isLoggable(Level level) { + return level != Level.DEBUG || debugEnabled; + } + + @Override + public void log(Level level, ResourceBundle bundle, String message, Throwable thrown) { + lines.add(new Line(level, message, thrown)); + } + + @Override + public void log(Level level, ResourceBundle bundle, String format, Object... params) { + lines.add(new Line(level, format, null)); + } + + List messages() { + return lines.stream().map(Line::message).toList(); + } + } + + private static IrisModule module(String id) { + return new IrisModule() { + public ModuleInfo info() { return ModuleInfo.of(id, "Log " + id, "1"); } + public void install(StageGraph graph) {} + }; + } + + @Test + void labelsEveryLineWithTheModuleIdAndKeepsTheLevel() { + var logger = new RecordingLogger(); + var log = ModuleLogs.labelled(ALPHA, logger); + + log.debug("d"); + log.info("i"); + log.warn("w"); + log.error("e", null); + + assertEquals(List.of("[test:alpha] d", "[test:alpha] i", "[test:alpha] w", "[test:alpha] e"), logger.messages()); + assertEquals(List.of(Level.DEBUG, Level.INFO, Level.WARNING, Level.ERROR), + logger.lines.stream().map(RecordingLogger.Line::level).toList()); + } + + @Test + void aMessageIsPlainTextNotAFormat() { + var logger = new RecordingLogger(); + + ModuleLogs.labelled(ALPHA, logger).warn("100% {0} %s"); + + assertEquals(List.of("[test:alpha] 100% {0} %s"), logger.messages()); + } + + @Test + void debugIsWrittenOnlyWhenTheHostLogsDebug() { + var logger = new RecordingLogger(); + logger.debugEnabled = false; + var log = ModuleLogs.labelled(ALPHA, logger); + + log.debug("hidden"); + log.info("shown"); + logger.debugEnabled = true; + log.debug("now shown"); + + assertEquals(List.of("[test:alpha] shown", "[test:alpha] now shown"), logger.messages()); + } + + @Test + void errorHandsTheCauseToTheHostToReport() { + var logger = new RecordingLogger(); + var cause = new IllegalStateException("boom"); + + ModuleLogs.labelled(ALPHA, logger).error("Failed to place", cause); + + assertEquals(1, logger.lines.size()); + assertEquals(Level.ERROR, logger.lines.get(0).level()); + assertEquals("[test:alpha] Failed to place", logger.lines.get(0).message()); + assertSame(cause, logger.lines.get(0).thrown()); + } + + @Test + void warnOnceWarnsTheFirstTimeAndDebugsAfterwards() { + var logger = new RecordingLogger(); + var log = ModuleLogs.labelled(ALPHA, logger); + + log.warnOnce("empty", "first"); + log.warnOnce("empty", "second"); + log.warnOnce("other", "third"); + + assertEquals(List.of(Level.WARNING, Level.DEBUG, Level.WARNING), + logger.lines.stream().map(RecordingLogger.Line::level).toList()); + assertEquals(List.of("[test:alpha] first", "[test:alpha] second", "[test:alpha] third"), logger.messages()); + } + + @Test + void warnOnceKeysBelongToTheModule() { + var logger = new RecordingLogger(); + var alpha = ModuleLogs.labelled(ALPHA, logger); + var beta = ModuleLogs.labelled(BETA, logger); + + alpha.warnOnce("shared", "alpha says"); + beta.warnOnce("shared", "beta says"); + + assertEquals(List.of(Level.WARNING, Level.WARNING), logger.lines.stream().map(RecordingLogger.Line::level).toList()); + } + + @Test + void warnOnceStopsClaimingKeysPastTheCap() { + var logger = new RecordingLogger(); + var log = ModuleLogs.labelled(ALPHA, logger); + for (int key = 0; key < ONCE_KEY_CAP; key++) { + log.warnOnce("key" + key, "claimed"); + } + logger.lines.clear(); + + log.warnOnce("one too many", "dropped to debug"); + + assertEquals(List.of(Level.DEBUG), logger.lines.stream().map(RecordingLogger.Line::level).toList()); + } + + @Test + void discardingLogWritesNothingAndNeverThrows() { + var log = ModuleLogs.discarding(); + + assertDoesNotThrow(() -> { + log.debug("d"); + log.info("i"); + log.warn("w"); + log.warnOnce("k", "m"); + log.error("e", new RuntimeException()); + }); + } + + @Test + void builtInModulesLogThroughTheHostLogger() { + var logger = new RecordingLogger(); + var host = ModuleHost.of(List.of(module(ALPHA))).loggingTo(logger); + + host.builtIns().get(0).log().warn("hello"); + + assertEquals(List.of("[test:alpha] hello"), logger.messages()); + } + + @Test + void packModulesLogThroughTheLoadersLogger(@TempDir Path pack, @TempDir Path copies) { + var logger = new RecordingLogger(); + TestModuleJar.module("pack.gamma.GammaModule", "gamma:core", "", "") + .writeInto(pack, "gamma.jar"); + + try (var modules = PackModules.load(pack, List.of(), copies, logger)) { + logger.lines.clear(); + modules.modules().get(0).log().warn("from a jar"); + } + + assertEquals(List.of("[gamma:core] from a jar"), logger.messages()); + } + + @Test + void theRegistryGivesTheRegisteringModuleItsLogDuringRegister() { + var logger = new RecordingLogger(); + var logs = new ArrayList(); + var registering = new IrisModule() { + public ModuleInfo info() { return ModuleInfo.of(BETA, "Registers", "1"); } + public void install(StageGraph graph) {} + public void register(FeatureRegistry registry) { logs.add(registry.log()); } + }; + var registry = new ModuleRegistry(); + + registry.register(DiscoveredModule.builtIn(registering).loggingTo(logger)); + logs.get(0).info("registered"); + + assertEquals(List.of("[test:beta] registered"), logger.messages()); + assertThrows(IllegalStateException.class, registry::log); + } + + @Test + void aStageBodySeesItsOwnModulesLogOnTheContextAndOnTheWorld() { + var logger = new RecordingLogger(); + var alphaStage = Stage.chunk("test:alpha/first"); + var betaStage = Stage.chunk("test:beta/second"); + var builder = new StageGraphBuilder(); + builder.install(DiscoveredModule.builtIn(stagedModule(ALPHA, alphaStage, null)).loggingTo(logger)); + builder.install(DiscoveredModule.builtIn(stagedModule(BETA, betaStage, alphaStage)).loggingTo(logger)); + var runner = new ChunkRunner(builder.resolve(Pipeline.CHUNK)); + + try (var world = new TestWorld()) { + runner.generate(TestContexts.generation(Map.of(), null, null, world), TestContexts.SEED); + } + + assertEquals(List.of("[test:alpha] context", "[test:alpha] world", "[test:beta] context", "[test:beta] world"), + logger.messages()); + } + + private static IrisModule stagedModule(String id, ChunkStage stage, ChunkStage after) { + return new IrisModule() { + public ModuleInfo info() { return ModuleInfo.of(id, "Stage " + id, "1"); } + public void install(StageGraph graph) { + var definition = graph.define(stage); + if (after != null) { + definition.softAfter(after.ref()); + } + definition.run(context -> { + context.log().info("context"); + context.world().log().info("world"); + }); + } + }; + } + + @Test + void lifecycleHooksAndServicesGetAWorldWhoseLogIsTheModules() { + var logger = new RecordingLogger(); + var seen = new ArrayList(); + var module = new IrisModule() { + public ModuleInfo info() { return ModuleInfo.of(ALPHA, "Hooks", "1"); } + public void install(StageGraph graph) {} + public void register(FeatureRegistry registry) { + registry.registerLifecycle(new ModuleLifecycle() { + public void worldStarted(PackWorld world) { seen.add(world.log()); } + }); + } + }; + var discovered = DiscoveredModule.builtIn(module).loggingTo(logger); + var catalog = LoadedModules.load(List.of(discovered), Map.of(), Set.of(), Set.of()).catalog(); + + try (var world = new TestWorld()) { + new LifecycleRunner(catalog).worldStarted(world); + new ServiceRegistration(Runnable.class, (Runnable) () -> {}, discovered).scope(world).log().warn("from a service"); + } + seen.get(0).info("from a hook"); + + assertEquals(List.of("[test:alpha] from a service", "[test:alpha] from a hook"), logger.messages()); + } +} diff --git a/src/test/java/com/volmit/support/TestWorld.java b/src/test/java/com/volmit/support/TestWorld.java index 2b009bd5f..22efd93db 100644 --- a/src/test/java/com/volmit/support/TestWorld.java +++ b/src/test/java/com/volmit/support/TestWorld.java @@ -1,8 +1,10 @@ package com.volmit.support; import com.volmit.IrisFeature; +import com.volmit.ModuleLog; import com.volmit.config.FeatureSettings.Entry; import com.volmit.config.PackSettings; +import com.volmit.host.ModuleLogs; import com.volmit.host.WorldStates; import com.volmit.resource.PackResources; import com.volmit.world.PackWorld; @@ -11,7 +13,17 @@ import java.util.function.Function; /** A world for tests: the test seed, no resources, no declared settings, and a real state store. */ public final class TestWorld implements PackWorld, AutoCloseable { - private final WorldStates states = new WorldStates(); + private final WorldStates states; + private final ModuleLog log; + + public TestWorld() { + this(new WorldStates(), ModuleLogs.discarding()); + } + + private TestWorld(WorldStates states, ModuleLog log) { + this.states = states; + this.log = log; + } @Override public long seed() { @@ -37,6 +49,16 @@ public final class TestWorld implements PackWorld, AutoCloseable { return states.state(type, () -> create.apply(this)); } + @Override + public ModuleLog log() { + return log; + } + + @Override + public PackWorld withLog(ModuleLog log) { + return new TestWorld(states, log); + } + @Override public void close() { states.close();