diff --git a/MOD_DEVELOPMENT.md b/MOD_DEVELOPMENT.md index 277e450..3e3eac5 100644 --- a/MOD_DEVELOPMENT.md +++ b/MOD_DEVELOPMENT.md @@ -21,7 +21,7 @@ pluginManagement { dependencyResolutionManagement { repositories { maven("https://git.security-command.org/api/packages/overlord/maven") - mavenCentral() + mavenCentral() // the API depends on org.jetbrains:annotations } } @@ -218,6 +218,28 @@ Listeners are matched by the event's exact class. Events that carry live game ob removed after ten failures; both `onMain` and `onModThread` return a `Subscription` to remove it earlier. +The same listeners as annotated methods (`dev.overlord.zomboidforge.api.annotations`): + +```java +@OnMain +void onTick(TickEvent event) { ... } + +@OnModThread +void onGreeting(SomeEvent event) { ... } +``` + +- **The entry point's methods** are registered after its constructor and before `onLoad()`, so + they run before the listeners that `onLoad()` registers for the same event. Other objects + opt in with `this.events().register(object)`, which returns one `Subscription` for all of + their methods. Registering an object twice throws; the entry point is registered already. +- **A listener method** returns `void` and has one parameter: the event class, not an + interface or an abstract class. It may be static or private, and may be declared in a + superclass. An override listens only when it carries the annotation itself. +- **Order:** superclass methods first, the methods of one class by name. When two listeners of + one event need a specific order, register them with `onMain` instead. +- A method that breaks these rules stops the server with every problem in the log; + `register` throws an `IllegalArgumentException` instead. + ## Commands Admin commands work wherever Project Zomboid's own commands work: in the in-game chat @@ -413,4 +435,4 @@ file system it can reach anything the server can, including other mods' data in Main-thread tasks and event listener calls appear in JFR recordings as the event `zomboidforge.ModTask`, with the mod's id and the kind of work (`task`, or `listener` and the -event class). +event class, followed by `#` for a listener method). diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/Events.java b/api/src/main/java/dev/overlord/zomboidforge/api/Events.java index dc47d33..1a7c137 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/Events.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/Events.java @@ -1,5 +1,8 @@ package dev.overlord.zomboidforge.api; +import dev.overlord.zomboidforge.api.annotations.OnMain; +import dev.overlord.zomboidforge.api.annotations.OnModThread; + import org.jetbrains.annotations.ApiStatus; import java.util.function.Consumer; @@ -24,4 +27,33 @@ public interface Events * @throws IllegalArgumentException when {@code type} is a {@link MainThreadEvent} */ Subscription onModThread(Class type, Consumer listener); + + /** + * Registers the methods of {@code listener} annotated with {@link OnMain} or + * {@link OnModThread}, as {@link #onMain} and {@link #onModThread} do. ZomboidForge registers + * the mod's entry point this way after its constructor and before {@link Mod#onLoad()}; other + * objects opt in through this method. + * + *

Each annotated method: + *

    + *
  • returns {@code void} and has one parameter, a class that implements {@link Event} + * and is neither abstract nor an interface, because listeners are matched by the + * event's exact class;
  • + *
  • carries one of the two annotations; {@link OnModThread} not for a + * {@link MainThreadEvent};
  • + *
  • may be static, private, and declared in a superclass of {@code listener}'s class. + * An instance method that a subclass overrides listens only when the override carries + * the annotation itself.
  • + *
+ * + * Superclass methods are registered before subclass methods, and the methods of one class + * sorted by name, then by parameter type. + * + * @return one subscription for every listener method of {@code listener}; cancelling it + * allows registering {@code listener} again + * @throws IllegalArgumentException listing every method that breaks a rule, when a class + * the methods name cannot be loaded, or when + * {@code listener} is registered already + */ + Subscription register(Object listener); } diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java b/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java index df6b3f2..db38c4e 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java @@ -18,12 +18,17 @@ import java.nio.file.Path; * *

Lifecycle, in this order: *

    + *
  1. Listener methods: the methods annotated with + * {@link dev.overlord.zomboidforge.api.annotations.OnMain} or + * {@link dev.overlord.zomboidforge.api.annotations.OnModThread} are registered (see + * {@link Events#register(Object)}).
  2. *
  3. {@link #onLoad()}: registration and setup. The server database, Lua, and the world do * not exist yet.
  4. *
  5. {@link #onServerStarted()}: the world is loaded and the network port is open.
  6. *
  7. {@link #onStopping()}: the server stops; the world has not been saved yet.
  8. *
- * An exception thrown by the constructor or {@link #onLoad()} stops the server. + * An exception thrown by the constructor or {@link #onLoad()}, or a listener method that breaks + * the rules, stops the server. */ public abstract class Mod { diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/annotations/OnMain.java b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/OnMain.java new file mode 100644 index 0000000..ef767ef --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/OnMain.java @@ -0,0 +1,19 @@ +package dev.overlord.zomboidforge.api.annotations; + +import dev.overlord.zomboidforge.api.Events; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Registers the method with {@link Events#onMain} for the event type of its only parameter. Read + * on the entry point before {@code onLoad()}, and on objects passed to + * {@link Events#register(Object)}, which lists the rules for the method. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface OnMain {} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/annotations/OnModThread.java b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/OnModThread.java new file mode 100644 index 0000000..cbad953 --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/OnModThread.java @@ -0,0 +1,19 @@ +package dev.overlord.zomboidforge.api.annotations; + +import dev.overlord.zomboidforge.api.Events; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Registers the method with {@link Events#onModThread} for the event type of its only parameter. + * Read on the entry point before {@code onLoad()}, and on objects passed to + * {@link Events#register(Object)}, which lists the rules for the method. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface OnModThread {} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/annotations/package-info.java b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/package-info.java new file mode 100644 index 0000000..33dc764 --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/package-info.java @@ -0,0 +1,10 @@ +/** + * Annotations that stand for calls a mod can also make through the services of + * {@link dev.overlord.zomboidforge.api.Mod}. + * + * @noinspection UnstableApiUsage, RedundantSuppression + */ +@NotNullByDefault +package dev.overlord.zomboidforge.api.annotations; + +import org.jetbrains.annotations.NotNullByDefault; diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java index d988a9d..c28719b 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java @@ -29,8 +29,8 @@ import java.util.Map; import java.util.Objects; /** - * Creates the class loaders and entry points of resolved mods, in order, and calls - * {@link Mod#onLoad()} on each. Stops at the first mod that fails. + * Creates the class loaders and entry points of resolved mods, in order, registers each entry + * point's listener methods, and calls {@link Mod#onLoad()}. Stops at the first mod that fails. */ public final class ModLoader { @@ -135,6 +135,10 @@ public final class ModLoader throw new ModLoadException(ModLoader.sentence("'" + id + "': cannot create '" + descriptor.entrypoint() + "': " + e), e); } + // Listener methods of the entry point; a mistake stops the server before onLoad() has side effects. + try { context.events().register(mod); } + catch (IllegalArgumentException e) { throw new ModLoadException("'" + id + "': " + e.getMessage(), e); } + try { mod.onLoad(); } catch (Exception e) { throw new ModLoadException(ModLoader.sentence("'" + id + "': onLoad() threw " + e), e); } catch (LinkageError e) { throw new ModLoadException(ModLoader.sentence("'" + id + "': onLoad() failed with " + e), e); } diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/runtime/EventBus.java b/core/src/main/java/dev/overlord/zomboidforge/core/runtime/EventBus.java index 9623de9..1c94db8 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/runtime/EventBus.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/runtime/EventBus.java @@ -8,11 +8,16 @@ import dev.overlord.zomboidforge.api.Subscription; import org.jetbrains.annotations.Nullable; import java.util.Arrays; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; @@ -80,6 +85,9 @@ public final class EventBus private final Executor modThread; private final System.Logger logger; + /** Objects registered with {@link #register(Object)} whose subscription is active; guarded by itself. */ + private final Set registered = Collections.newSetFromMap(new IdentityHashMap<>()); + private ModEvents(String id, Executor modThread, System.Logger logger) { this.id = id; @@ -99,15 +107,47 @@ public final class EventBus return this.register(type, listener, this.modThread); } + @Override + public Subscription register(Object listener) + { + Objects.requireNonNull(listener, "listener"); + + List methods = ListenerScanner.scan(listener); + + synchronized (this.registered) + { + if (!this.registered.add(listener)) throw new IllegalArgumentException("This '" + listener.getClass().getName() + "' is already registered."); + } + + List listeners = methods.stream() + .map(method -> this.add(method.type(), method.action(), method.main() ? null : this.modThread, method.name())) + .toList(); + + AtomicBoolean active = new AtomicBoolean(true); + + return () -> { + if (!active.getAndSet(false)) return; + + listeners.forEach(Listener::cancel); + synchronized (this.registered) { this.registered.remove(listener); } + }; + } + private Subscription register(Class type, Consumer listener, @Nullable Executor executor) { Objects.requireNonNull(type, "type"); Objects.requireNonNull(listener, "listener"); - Listener registered = new Listener(this.id, type, event -> listener.accept(type.cast(event)), executor, this.logger); - EventBus.this.add(registered); + return this.add(type, event -> listener.accept(type.cast(event)), executor, null); + } - return registered; + /** @param method the name of the listener method, or {@code null} for a lambda */ + private Listener add(Class type, Consumer action, @Nullable Executor executor, @Nullable String method) + { + Listener listener = new Listener(this.id, type, method, action, executor, this.logger); + EventBus.this.add(listener); + + return listener; } } @@ -116,6 +156,7 @@ public final class EventBus private final String mod; private final Class type; private final String kind; + private final String name; private final Consumer action; private final @Nullable Executor executor; private final System.Logger logger; @@ -123,11 +164,13 @@ public final class EventBus private volatile boolean active = true; - private Listener(String mod, Class type, Consumer action, @Nullable Executor executor, System.Logger logger) + /** @param method the name of the listener method, or {@code null} for a lambda */ + private Listener(String mod, Class type, @Nullable String method, Consumer action, @Nullable Executor executor, System.Logger logger) { this.mod = mod; this.type = type; - this.kind = "listener " + type.getSimpleName(); + this.kind = "listener " + type.getSimpleName() + (method == null ? "" : "#" + method); + this.name = method == null ? "Listener for '" + type.getSimpleName() + "'" : "Listener '" + method + "' for '" + type.getSimpleName() + "'"; this.action = action; this.executor = executor; this.logger = logger; @@ -161,12 +204,12 @@ public final class EventBus if (failure == null) return; int count = this.failures.incrementAndGet(); - this.logger.log(System.Logger.Level.ERROR, "Listener for '" + this.type.getSimpleName() + "' threw (failure " + count + " of " + EventBus.MAX_FAILURES + ").", failure); + this.logger.log(System.Logger.Level.ERROR, this.name + " threw (failure " + count + " of " + EventBus.MAX_FAILURES + ").", failure); if (count >= EventBus.MAX_FAILURES) { this.cancel(); - this.logger.log(System.Logger.Level.ERROR, "Listener for '" + this.type.getSimpleName() + "' removed after " + EventBus.MAX_FAILURES + " failures."); + this.logger.log(System.Logger.Level.ERROR, this.name + " removed after " + EventBus.MAX_FAILURES + " failures."); } } } diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/runtime/ListenerScanner.java b/core/src/main/java/dev/overlord/zomboidforge/core/runtime/ListenerScanner.java new file mode 100644 index 0000000..170fc9e --- /dev/null +++ b/core/src/main/java/dev/overlord/zomboidforge/core/runtime/ListenerScanner.java @@ -0,0 +1,187 @@ +package dev.overlord.zomboidforge.core.runtime; + +import dev.overlord.zomboidforge.api.Event; +import dev.overlord.zomboidforge.api.MainThreadEvent; +import dev.overlord.zomboidforge.api.Mod; +import dev.overlord.zomboidforge.api.annotations.OnMain; +import dev.overlord.zomboidforge.api.annotations.OnModThread; + +import org.jetbrains.annotations.Nullable; + +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; + +/** + * Finds the listener methods of an object for {@code Events.register(Object)}: methods annotated + * with {@link OnMain} or {@link OnModThread} in its class and superclasses, up to {@link Mod} or + * {@code Object}. Methods do not have to be public; they are called through method handles from + * a private lookup, as {@code RecordCodec} reads records. + */ +final class ListenerScanner +{ + /** + * One listener method, bound to its object. + * + * @param type the event class, the method's parameter type + * @param main {@code true} for {@link OnMain}, {@code false} for {@link OnModThread} + * @param action calls the method; rethrows what the method throws, unchanged + */ + record ListenerMethod(Class type, boolean main, String name, Consumer action) {} + + private static final Comparator ORDER = Comparator + .comparing(Method::getName) + .thenComparing(method -> Arrays.toString(method.getParameterTypes())); + + private ListenerScanner() {} + + /** + * @return the listener methods of {@code target}, in registration order: superclass methods + * first, the methods of one class sorted by name, then by parameter type + * @throws IllegalArgumentException listing every problem, including classes whose methods + * cannot be read because a type they name is missing + */ + static List scan(Object target) + { + Map, Method[]> hierarchy = ListenerScanner.declaredMethods(target.getClass()); + List> types = List.copyOf(hierarchy.keySet()); + List found = new ArrayList<>(); + List problems = new ArrayList<>(); + + for (int i = 0; i < types.size(); i++) + { + List> subclasses = types.subList(i + 1, types.size()); + + for (Method method : hierarchy.get(types.get(i))) + { + boolean main = method.isAnnotationPresent(OnMain.class); + boolean modThread = method.isAnnotationPresent(OnModThread.class); + + // javac copies method annotations to bridge methods. + if ((!main && !modThread) || method.isBridge() || method.isSynthetic()) continue; + if (ListenerScanner.isOverridden(method, subclasses, hierarchy)) continue; + + ListenerMethod listener = ListenerScanner.listener(target, method, main, modThread, problems); + if (listener != null) found.add(listener); + } + } + + if (!problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems)); + + return List.copyOf(found); + } + + /** + * The declared methods of {@code type} and its superclasses up to {@link Mod} or + * {@code Object}, superclass first, each sorted by {@link #ORDER}. + * + * @throws IllegalArgumentException when the methods of a class cannot be read + */ + private static Map, Method[]> declaredMethods(Class type) + { + List> classes = new ArrayList<>(); + for (Class current = type; current != null && current != Object.class && current != Mod.class; current = current.getSuperclass()) classes.addFirst(current); + + Map, Method[]> hierarchy = new LinkedHashMap<>(); + List problems = new ArrayList<>(); + + for (Class current : classes) + { + // Reading the methods loads every parameter and return type they name. + try + { + Method[] methods = current.getDeclaredMethods(); + Arrays.sort(methods, ListenerScanner.ORDER); + hierarchy.put(current, methods); + } + catch (LinkageError e) { problems.add("Cannot read the methods of '" + current.getName() + "': " + e + "."); } + } + + if (!problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems)); + + return hierarchy; + } + + /** Whether one of {@code subclasses} declares a method that overrides {@code method}. */ + private static boolean isOverridden(Method method, List> subclasses, Map, Method[]> hierarchy) + { + int modifiers = method.getModifiers(); + if (Modifier.isStatic(modifiers) || Modifier.isPrivate(modifiers)) return false; + + Class owner = method.getDeclaringClass(); + boolean packagePrivate = !Modifier.isPublic(modifiers) && !Modifier.isProtected(modifiers); + + for (Class subclass : subclasses) + { + // A package-private method is only overridden in the same runtime package. + if (packagePrivate && (subclass.getClassLoader() != owner.getClassLoader() || !subclass.getPackageName().equals(owner.getPackageName()))) continue; + + for (Method candidate : hierarchy.get(subclass)) + { + if (Modifier.isStatic(candidate.getModifiers()) || Modifier.isPrivate(candidate.getModifiers())) continue; + if (candidate.getName().equals(method.getName()) && Arrays.equals(candidate.getParameterTypes(), method.getParameterTypes())) return true; + } + } + + return false; + } + + /** The listener for {@code method}, or {@code null} after adding its problems to {@code problems}. */ + private static @Nullable ListenerMethod listener(Object target, Method method, boolean main, boolean modThread, List problems) + { + String where = "'" + method.getDeclaringClass().getName() + "." + method.getName() + "'"; + Class[] parameters = method.getParameterTypes(); + int before = problems.size(); + + if (main && modThread) problems.add(where + " carries both @OnMain and @OnModThread."); + if (method.getReturnType() != void.class) problems.add(where + " must return void."); + + if (parameters.length != 1) + { + problems.add(where + " must have one parameter, the event; found " + parameters.length + "."); + return null; + } + + Class type = parameters[0]; + + if (!Event.class.isAssignableFrom(type)) + problems.add(where + ": the parameter type '" + type.getName() + "' does not implement Event."); + else if (type.isInterface() || Modifier.isAbstract(type.getModifiers())) + problems.add(where + ": the parameter type '" + type.getName() + "' is " + (type.isInterface() ? "an interface" : "abstract") + "; listeners are matched by the event's exact class."); + else if (modThread && MainThreadEvent.class.isAssignableFrom(type)) + problems.add(where + ": '" + type.getName() + "' is a main-thread event; annotate the method with @OnMain."); + + if (problems.size() > before) return null; + + try + { + MethodHandle handle = MethodHandles.privateLookupIn(method.getDeclaringClass(), MethodHandles.lookup()).unreflect(method); + if (!Modifier.isStatic(method.getModifiers())) handle = handle.bindTo(target); + + MethodHandle invoker = handle.asType(MethodType.methodType(void.class, Object.class)); + + return new ListenerMethod(type, main, method.getName(), event -> { + try { invoker.invokeExact(event); } + catch (Throwable t) { throw ListenerScanner.rethrow(t); } + }); + } + catch (IllegalAccessException e) + { + problems.add(where + " cannot be accessed: " + e.getMessage()); + return null; + } + } + + /** Throws {@code t} unchanged, also a checked exception; the listener's caller logs every {@code Throwable}. */ + @SuppressWarnings("unchecked") + private static RuntimeException rethrow(Throwable t) throws T { throw (T) t; } +} diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/runtime/ModTaskEvent.java b/core/src/main/java/dev/overlord/zomboidforge/core/runtime/ModTaskEvent.java index dac85ce..c2fc7f4 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/runtime/ModTaskEvent.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/runtime/ModTaskEvent.java @@ -19,7 +19,7 @@ final class ModTaskEvent extends jdk.jfr.Event @Label("Mod") String mod = ""; - /** {@code task}, or {@code listener }. */ + /** {@code task}, {@code listener }, or {@code listener #} for a listener method. */ @Label("Kind") String kind = ""; diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java index 6c584f0..eb9d367 100644 --- a/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java +++ b/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java @@ -14,6 +14,8 @@ import org.junit.jupiter.api.io.TempDir; import testmods.CommandMod; import testmods.ContextMod; import testmods.ErrorMod; +import testmods.InvalidListenerMod; +import testmods.ListenerMod; import testmods.Recorder; import testmods.ThreadMod; @@ -329,6 +331,58 @@ class ForgeTest assertEquals(Lifecycle.Phase.STOPPING, forge.phase()); } + @Test + void registersListenerMethodsOfTheEntryPointBeforeOnLoad() throws Exception + { + TestMods.folder(this.mods, "listener", TestMods.toml("listener", ListenerMod.class.getName(), ""), Map.of( + "testmods/ListenerMod", TestMods.classFile(ListenerMod.class) + )); + + Forge forge = this.load(); + Object mod = forge.mods().getFirst().mod(); + + forge.started(); + forge.tick(); + + assertEquals(List.of("method 1", "lambda 1"), ForgeTest.field(mod, "log"), "annotated listeners come before those of onLoad()"); + + IllegalArgumentException second = assertInstanceOf(IllegalArgumentException.class, ForgeTest.field(mod, "secondRegistration")); + assertTrue(second.getMessage().contains("testmods.ListenerMod"), second.getMessage()); + } + + @Test + void failsBeforeOnLoadWhenAListenerMethodBreaksTheRules() throws IOException + { + TestMods.folder(this.mods, "invalid", TestMods.toml("invalid", InvalidListenerMod.class.getName(), ForgeTest.USES_GAME), Map.of( + "testmods/InvalidListenerMod", TestMods.classFile(InvalidListenerMod.class) + )); + + ModLoadException e = assertThrows(ModLoadException.class, this::load); + + assertEquals(1, e.problems().size()); + ForgeTest.assertContainsAll(e.problems().getFirst(), "'invalid'", "testmods.InvalidListenerMod.onTick", "java.lang.String"); + assertTrue(Recorder.EVENTS.isEmpty(), "onLoad() does not run"); + } + + @Test + void failsWhenTheEntryPointNamesAMissingClassInAMethod() throws IOException + { + // ModVerifier reports missing classes only in the game's packages, so only the scan finds this one. + TestMods.folder(this.mods, "missing", TestMods.toml("missing", "missing.MissingMod", ""), Map.of( + "missing/MissingMod", TestMods.type("missing/MissingMod", "dev/overlord/zomboidforge/api/Mod", null, "helper:(Lgone/Type;)V") + )); + + ModLoadException e = assertThrows(ModLoadException.class, this::load); + + assertEquals(1, e.problems().size()); + ForgeTest.assertContainsAll(e.problems().getFirst(), "'missing'", "missing.MissingMod", "NoClassDefFoundError", "gone/Type"); + } + + private static void assertContainsAll(String message, String... parts) + { + for (String part : parts) assertTrue(message.contains(part), "'" + part + "' missing in: " + message); + } + private static void await(BooleanSupplier condition) throws InterruptedException { long deadline = System.nanoTime() + 5_000_000_000L; diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/runtime/EventBusTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/runtime/EventBusTest.java index 798c056..b405c53 100644 --- a/core/src/test/java/dev/overlord/zomboidforge/core/runtime/EventBusTest.java +++ b/core/src/test/java/dev/overlord/zomboidforge/core/runtime/EventBusTest.java @@ -4,10 +4,13 @@ import dev.overlord.zomboidforge.api.Event; import dev.overlord.zomboidforge.api.Events; import dev.overlord.zomboidforge.api.Subscription; import dev.overlord.zomboidforge.api.TickEvent; +import dev.overlord.zomboidforge.api.annotations.OnMain; +import dev.overlord.zomboidforge.api.annotations.OnModThread; import dev.overlord.zomboidforge.core.RecordingLogger; import org.junit.jupiter.api.Test; +import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; @@ -21,6 +24,81 @@ class EventBusTest { private record Joined(String player) implements Event {} + private record Left(String player) implements Event {} + + private abstract static class AbstractEvent implements Event {} + + /** Listener methods in a superclass of {@link Listeners}. */ + private static class BaseListeners + { + static final List LOG = new ArrayList<>(); + + @OnMain + void base(Joined event) { BaseListeners.LOG.add("base " + event.player()); } + + /** Overridden without the annotation, so it does not listen. */ + @OnMain + void replaced(Joined event) { BaseListeners.LOG.add("base replaced"); } + + /** Overridden with the annotation, so the override listens once. */ + @OnMain + void kept(Joined event) { BaseListeners.LOG.add("base kept"); } + } + + private static final class Listeners extends BaseListeners + { + @OnMain + static void a(Joined event) { BaseListeners.LOG.add("static a " + event.player()); } + + @OnMain + private void b(Joined event) { BaseListeners.LOG.add("private b " + event.player()); } + + @Override + void replaced(Joined event) { BaseListeners.LOG.add("override replaced"); } + + @OnMain + @Override + void kept(Joined event) { BaseListeners.LOG.add("override kept"); } + + @OnModThread + void left(Left event) { BaseListeners.LOG.add("left " + event.player()); } + + @SuppressWarnings("unused") + void notAListener(Joined event) { BaseListeners.LOG.add("not a listener"); } + } + + @SuppressWarnings("unused") + private static final class InvalidListeners + { + @OnMain + @OnModThread + void both(Joined event) {} + + @OnMain + String returns(Joined event) { return ""; } + + @OnMain + void two(Joined first, Joined second) {} + + @OnMain + void notEvent(String text) {} + + @OnMain + void anInterface(Event event) {} + + @OnMain + void anAbstract(AbstractEvent event) {} + + @OnModThread + void mainOnly(TickEvent event) {} + } + + private static final class FailingListener + { + @OnMain + void fail(Joined event) throws IOException { throw new IOException("broken"); } + } + private final EventBus bus = new EventBus(); private final RecordingLogger logger = new RecordingLogger(); private final List received = new ArrayList<>(); @@ -102,4 +180,74 @@ class EventBusTest assertTrue(this.received.isEmpty()); } + + @Test + void registersAnnotatedMethodsOfAnObjectAndItsSuperclasses() + { + Events a = this.bus.forMod("a", this.modThread, this.logger); + BaseListeners.LOG.clear(); + + a.register(new Listeners()); + this.bus.post(new Joined("bob")); + this.bus.post(new Left("eve")); + + assertEquals(List.of("base bob", "static a bob", "private b bob", "override kept"), BaseListeners.LOG, "superclass first, then by name; overridden methods once"); + assertEquals(1, this.modTasks.size()); + + this.modTasks.getFirst().run(); + assertEquals("left eve", BaseListeners.LOG.getLast()); + } + + @Test + void registersAnObjectOnceUntilItsSubscriptionIsCancelled() + { + Events a = this.bus.forMod("a", this.modThread, this.logger); + Listeners listeners = new Listeners(); + Subscription subscription = a.register(listeners); + + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> a.register(listeners)); + assertTrue(e.getMessage().contains(Listeners.class.getName()), e.getMessage()); + + subscription.cancel(); + assertFalse(this.bus.hasListeners(Joined.class)); + assertFalse(this.bus.hasListeners(Left.class)); + + Subscription again = a.register(listeners); + subscription.cancel(); + assertTrue(this.bus.hasListeners(Joined.class), "cancelling the old subscription again leaves the new one"); + + again.cancel(); + assertFalse(this.bus.hasListeners(Joined.class)); + } + + @Test + void rejectsInvalidListenerMethodsWithEveryProblem() + { + Events a = this.bus.forMod("a", this.modThread, this.logger); + + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> a.register(new InvalidListeners())); + + // Every method, and the parameter types that break a rule. + for (String method : List.of("anAbstract", "anInterface", "both", "mainOnly", "notEvent", "returns", "two")) + EventBusTest.assertContainsAll(e.getMessage(), InvalidListeners.class.getName() + "." + method); + + EventBusTest.assertContainsAll(e.getMessage(), AbstractEvent.class.getName(), Event.class.getName(), TickEvent.class.getName(), "java.lang.String"); + assertFalse(this.bus.hasListeners(Joined.class), "nothing is registered"); + } + + @Test + void logsWhatListenerMethodsThrowWithTheirName() + { + this.bus.forMod("a", this.modThread, this.logger).register(new FailingListener()); + + this.bus.post(new Joined("bob")); + + assertEquals(1, this.logger.messages.size()); + EventBusTest.assertContainsAll(this.logger.messages.getFirst(), "ERROR", "'fail'", "Joined", "java.io.IOException: broken"); + } + + private static void assertContainsAll(String message, String... parts) + { + for (String part : parts) assertTrue(message.contains(part), "'" + part + "' missing in: " + message); + } } diff --git a/core/src/test/java/testmods/InvalidListenerMod.java b/core/src/test/java/testmods/InvalidListenerMod.java new file mode 100644 index 0000000..1aed709 --- /dev/null +++ b/core/src/test/java/testmods/InvalidListenerMod.java @@ -0,0 +1,15 @@ +package testmods; + +import dev.overlord.zomboidforge.api.Mod; +import dev.overlord.zomboidforge.api.annotations.OnMain; + +/** Entry point that tests package into a mod jar. Its listener method takes no event. */ +public final class InvalidListenerMod extends Mod +{ + @Override + public void onLoad() { Recorder.record("invalid:onLoad"); } + + @OnMain + @SuppressWarnings("unused") + void onTick(String text) {} +} diff --git a/core/src/test/java/testmods/ListenerMod.java b/core/src/test/java/testmods/ListenerMod.java new file mode 100644 index 0000000..76befca --- /dev/null +++ b/core/src/test/java/testmods/ListenerMod.java @@ -0,0 +1,33 @@ +package testmods; + +import dev.overlord.zomboidforge.api.Mod; +import dev.overlord.zomboidforge.api.TickEvent; +import dev.overlord.zomboidforge.api.annotations.OnMain; + +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * Entry point that tests package into a mod jar. Listens for ticks with an annotated method and + * with a listener from {@code onLoad()}, and tries to register itself again there. + */ +public final class ListenerMod extends Mod +{ + public final List log = new CopyOnWriteArrayList<>(); + + public volatile @Nullable RuntimeException secondRegistration; + + @Override + public void onLoad() + { + this.events().onMain(TickEvent.class, event -> this.log.add("lambda " + event.tick())); + + try { this.events().register(this); } + catch (RuntimeException e) { this.secondRegistration = e; } + } + + @OnMain + void onTick(TickEvent event) { this.log.add("method " + event.tick()); } +} diff --git a/gradle-plugin/src/test/java/dev/overlord/zomboidforge/gradle/ZomboidForgeModPluginTest.java b/gradle-plugin/src/test/java/dev/overlord/zomboidforge/gradle/ZomboidForgeModPluginTest.java index 67ce66d..c3eec57 100644 --- a/gradle-plugin/src/test/java/dev/overlord/zomboidforge/gradle/ZomboidForgeModPluginTest.java +++ b/gradle-plugin/src/test/java/dev/overlord/zomboidforge/gradle/ZomboidForgeModPluginTest.java @@ -61,6 +61,7 @@ class ZomboidForgeModPluginTest dependencyResolutionManagement { repositories { maven { url = uri("%s") } + mavenCentral() } } """.formatted(Path.of(ZomboidForgeModPluginTest.REPOSITORY).toUri()));