From 36ac320c9c137a648f52608fb03f8b43a57d3d8c Mon Sep 17 00:00:00 2001 From: Overlord Date: Wed, 7 Oct 2026 10:42:57 +0200 Subject: [PATCH 1/9] Add `compileOnlyApi` dependency for JetBrains annotations --- api/build.gradle.kts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/api/build.gradle.kts b/api/build.gradle.kts index 867ec6f..5d5de4a 100644 --- a/api/build.gradle.kts +++ b/api/build.gradle.kts @@ -32,6 +32,9 @@ publishing { } dependencies { + // Published as a compile-time dependency, so mods see the API's annotations; never in their lib/. + compileOnlyApi(libs.jetbrains.annotations) + testImplementation(platform(libs.junit.bom)) testImplementation(libs.junit.jupiter) testRuntimeOnly(libs.junit.platform.launcher) From 7ac442c4f6a80bce23315ede212379927a232866 Mon Sep 17 00:00:00 2001 From: Overlord Date: Wed, 7 Oct 2026 11:02:55 +0200 Subject: [PATCH 2/9] Annotate public APIs with JetBrains annotations and enforce immutability constraints on collections. --- .../dev/overlord/zomboidforge/api/AsyncExecutor.java | 3 +++ .../overlord/zomboidforge/api/ClientCommandEvent.java | 4 +++- .../dev/overlord/zomboidforge/api/ClientCommands.java | 3 +++ .../java/dev/overlord/zomboidforge/api/Commands.java | 3 +++ .../java/dev/overlord/zomboidforge/api/Events.java | 3 +++ .../java/dev/overlord/zomboidforge/api/MainThread.java | 6 +++++- .../main/java/dev/overlord/zomboidforge/api/Mod.java | 7 +++++++ .../java/dev/overlord/zomboidforge/api/ModConfig.java | 3 +++ .../java/dev/overlord/zomboidforge/api/ModContext.java | 3 +++ .../java/dev/overlord/zomboidforge/api/ModThread.java | 3 +++ .../dev/overlord/zomboidforge/api/Subscription.java | 3 +++ .../overlord/zomboidforge/api/storage/ModStorage.java | 7 +++++++ .../dev/overlord/zomboidforge/api/storage/Row.java | 5 ++++- .../dev/overlord/zomboidforge/api/storage/Table.java | 10 ++++++++-- .../zomboidforge/api/storage/TableDefinition.java | 8 +++++++- .../overlord/zomboidforge/core/storage/SqlTable.java | 4 ++-- 16 files changed, 67 insertions(+), 8 deletions(-) diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/AsyncExecutor.java b/api/src/main/java/dev/overlord/zomboidforge/api/AsyncExecutor.java index 5389738..6ee7040 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/AsyncExecutor.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/AsyncExecutor.java @@ -1,5 +1,7 @@ package dev.overlord.zomboidforge.api; +import org.jetbrains.annotations.ApiStatus; + import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; @@ -9,6 +11,7 @@ import java.util.concurrent.Executor; * task, named {@code zf-async--}. ZomboidForge shuts it down when the server stops; tasks * submitted after that are rejected with a {@link java.util.concurrent.RejectedExecutionException}. */ +@ApiStatus.NonExtendable public interface AsyncExecutor extends Executor { /** Runs {@code task} on a new virtual thread. An exception it throws is logged with the mod's id. */ diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/ClientCommandEvent.java b/api/src/main/java/dev/overlord/zomboidforge/api/ClientCommandEvent.java index 78f40d3..27417b6 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/ClientCommandEvent.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/ClientCommandEvent.java @@ -1,5 +1,7 @@ package dev.overlord.zomboidforge.api; +import org.jetbrains.annotations.Unmodifiable; + import java.util.Map; import java.util.Objects; @@ -42,7 +44,7 @@ public final class ClientCommandEvent implements MainThreadEvent, Cancellable public String command() { return this.command; } - public Map args() { return this.args; } + public @Unmodifiable Map args() { return this.args; } @Override public void cancel() { this.cancelled = true; } diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/ClientCommands.java b/api/src/main/java/dev/overlord/zomboidforge/api/ClientCommands.java index 4264e62..4429be5 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/ClientCommands.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/ClientCommands.java @@ -1,5 +1,7 @@ package dev.overlord.zomboidforge.api; +import org.jetbrains.annotations.ApiStatus; + import java.util.Map; /** @@ -17,6 +19,7 @@ import java.util.Map; * sent on the main thread, at once when called there, otherwise with the mod's queued * main-thread tasks. */ +@ApiStatus.NonExtendable public interface ClientCommands { /** diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/Commands.java b/api/src/main/java/dev/overlord/zomboidforge/api/Commands.java index e402c87..2ef17a8 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/Commands.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/Commands.java @@ -1,5 +1,7 @@ package dev.overlord.zomboidforge.api; +import org.jetbrains.annotations.ApiStatus; + /** * Registration of admin commands. A registered command works wherever Project Zomboid's own * admin commands work: in the in-game chat ({@code /name}), the server console, and RCON. It @@ -21,6 +23,7 @@ package dev.overlord.zomboidforge.api; * Project Zomboid creates a new instance for every use and calls its {@code Command()}, whose * result is the reply. */ +@ApiStatus.NonExtendable public interface Commands { /** 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 44ca57c..dc47d33 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/Events.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/Events.java @@ -1,11 +1,14 @@ package dev.overlord.zomboidforge.api; +import org.jetbrains.annotations.ApiStatus; + import java.util.function.Consumer; /** * Registration of event listeners. Listeners of one event run in registration order. A listener * that throws is logged with the mod's id; one that throws repeatedly is removed. */ +@ApiStatus.NonExtendable public interface Events { /** diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/MainThread.java b/api/src/main/java/dev/overlord/zomboidforge/api/MainThread.java index 7c4b779..efc57e9 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/MainThread.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/MainThread.java @@ -1,5 +1,8 @@ package dev.overlord.zomboidforge.api; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Range; + import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; @@ -14,6 +17,7 @@ import java.util.concurrent.Executor; * main thread: {@code submit(...).thenAcceptAsync(result -> ..., modThread())} moves the * follow-up work back. The main thread must never wait for another thread's result. */ +@ApiStatus.NonExtendable public interface MainThread extends Executor { /** @@ -37,7 +41,7 @@ public interface MainThread extends Executor * * @throws IllegalArgumentException when {@code ticks} is less than 1 */ - void runLater(int ticks, Runnable task); + void runLater(@Range(from = 1, to = Integer.MAX_VALUE) int ticks, Runnable task); /** Whether the calling thread is the main thread. */ boolean isMainThread(); 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 d5666f5..df6b3f2 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java @@ -3,6 +3,9 @@ package dev.overlord.zomboidforge.api; import dev.overlord.zomboidforge.api.internal.ModBinding; import dev.overlord.zomboidforge.api.storage.ModStorage; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NonBlocking; + import java.nio.file.Path; /** @@ -42,6 +45,7 @@ public abstract class Mod public final String version() { return this.context.version(); } /** Called once on the main thread, after the instance is created. */ + @ApiStatus.OverrideOnly @SuppressWarnings("RedundantThrows") public void onLoad() throws Exception {} @@ -49,12 +53,15 @@ public abstract class Mod * Called once on the main thread, after the world is loaded, the network port is open, and * RCON is initialized; directly before the main loop starts. */ + @ApiStatus.OverrideOnly + @NonBlocking public void onServerStarted() {} /** * Called once on the shutdown thread when the server stops, before the world is saved. * The main thread may still be finishing a tick. Mods are stopped in reverse load order. */ + @ApiStatus.OverrideOnly public void onStopping() {} /** The running Project Zomboid version. */ diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/ModConfig.java b/api/src/main/java/dev/overlord/zomboidforge/api/ModConfig.java index 9acfec6..0cfdf88 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/ModConfig.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/ModConfig.java @@ -1,5 +1,7 @@ package dev.overlord.zomboidforge.api; +import org.jetbrains.annotations.ApiStatus; + import java.util.Optional; /** @@ -10,6 +12,7 @@ import java.util.Optional; *

Keys are {@code snake_case}; record components and paths use the same names converted * from {@code camelCase} ({@code maxBalance} reads {@code max_balance}). */ +@ApiStatus.NonExtendable public interface ModConfig { /** diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/ModContext.java b/api/src/main/java/dev/overlord/zomboidforge/api/ModContext.java index 5f03a8c..ee6617d 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/ModContext.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/ModContext.java @@ -1,5 +1,7 @@ package dev.overlord.zomboidforge.api; +import org.jetbrains.annotations.ApiStatus; + import dev.overlord.zomboidforge.api.storage.ModStorage; import java.nio.file.Path; @@ -8,6 +10,7 @@ import java.nio.file.Path; * What ZomboidForge provides to one mod. Mods reach it through the methods of {@link Mod}; * ZomboidForge implements it. */ +@ApiStatus.NonExtendable public interface ModContext { /** The mod's id from {@code mod.toml}. */ diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/ModThread.java b/api/src/main/java/dev/overlord/zomboidforge/api/ModThread.java index 100ad21..c303f94 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/ModThread.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/ModThread.java @@ -1,5 +1,7 @@ package dev.overlord.zomboidforge.api; +import org.jetbrains.annotations.ApiStatus; + import java.time.Duration; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; @@ -12,6 +14,7 @@ import java.util.concurrent.ScheduledFuture; * that are rejected with a {@link java.util.concurrent.RejectedExecutionException}. It must not * touch game objects; that goes through {@code main()}. */ +@ApiStatus.NonExtendable public interface ModThread extends Executor { /** Runs {@code task} on the mod thread. An exception it throws is logged with the mod's id. */ diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/Subscription.java b/api/src/main/java/dev/overlord/zomboidforge/api/Subscription.java index 2b0f5c9..5c9fcbf 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/Subscription.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/Subscription.java @@ -1,6 +1,9 @@ package dev.overlord.zomboidforge.api; +import org.jetbrains.annotations.ApiStatus; + /** A registered event listener. */ +@ApiStatus.NonExtendable public interface Subscription { /** Removes the listener; it receives no further events. Calling it again has no effect. */ diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/storage/ModStorage.java b/api/src/main/java/dev/overlord/zomboidforge/api/storage/ModStorage.java index 41bb28f..8940051 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/storage/ModStorage.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/storage/ModStorage.java @@ -1,5 +1,8 @@ package dev.overlord.zomboidforge.api.storage; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Blocking; + import java.util.function.Supplier; /** @@ -16,9 +19,11 @@ import java.util.function.Supplier; * once the server runs they throw an {@link IllegalStateException}, so database I/O never costs * tick time. Use {@code modThread()} or {@code async()}. */ +@ApiStatus.NonExtendable public interface ModStorage { /** Opens the table {@code name} with schema version 1 and no migrations. */ + @Blocking Table table(String name, Class type); /** A table with a schema version and migrations; see {@link TableDefinition}. */ @@ -32,8 +37,10 @@ public interface ModStorage * other threads, for example with {@code main().submit(...).join()}. A backup waits at most * 10 seconds for it and then runs without pausing storage. */ + @Blocking void transaction(Runnable work); /** Like {@link #transaction(Runnable)}, returning the result of {@code work}. */ + @Blocking T transaction(Supplier work); } diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/storage/Row.java b/api/src/main/java/dev/overlord/zomboidforge/api/storage/Row.java index 23bae2c..c672678 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/storage/Row.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/storage/Row.java @@ -1,6 +1,8 @@ package dev.overlord.zomboidforge.api.storage; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Unmodifiable; import java.util.Set; @@ -10,12 +12,13 @@ import java.util.Set; * numbers as {@code Double}, texts (also UUIDs, instants, and enum constants) as * {@code String}, bytes as {@code byte[]}. */ +@ApiStatus.NonExtendable public interface Row { String key(); /** The names of the stored columns. */ - Set columns(); + @Unmodifiable Set columns(); /** The stored value, or {@code null} when it is null. @throws IllegalArgumentException for an unknown column */ @Nullable Object get(String column); diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/storage/Table.java b/api/src/main/java/dev/overlord/zomboidforge/api/storage/Table.java index 077afcc..bd4ab5a 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/storage/Table.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/storage/Table.java @@ -1,5 +1,9 @@ package dev.overlord.zomboidforge.api.storage; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Blocking; +import org.jetbrains.annotations.Unmodifiable; + import java.util.Collection; import java.util.List; import java.util.Map; @@ -13,6 +17,8 @@ import java.util.function.UnaryOperator; * unless it runs inside {@link ModStorage#transaction}. Calls block; on the main thread they * are only allowed during startup. */ +@ApiStatus.NonExtendable +@Blocking public interface Table { /** Stores {@code value} under {@code key}, replacing an existing row. */ @@ -24,7 +30,7 @@ public interface Table Optional get(String key); /** The rows of the given keys that exist. */ - Map getAll(Collection keys); + @Unmodifiable Map getAll(Collection keys); boolean contains(String key); @@ -35,7 +41,7 @@ public interface Table int deleteAll(Collection keys); /** Every key, sorted. */ - List keys(); + @Unmodifiable List keys(); /** * Calls {@code action} for every row, sorted by key, without loading all rows at once. diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/storage/TableDefinition.java b/api/src/main/java/dev/overlord/zomboidforge/api/storage/TableDefinition.java index f722528..648acb4 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/storage/TableDefinition.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/storage/TableDefinition.java @@ -1,5 +1,9 @@ package dev.overlord.zomboidforge.api.storage; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Blocking; +import org.jetbrains.annotations.Range; + import java.util.function.Function; /** @@ -12,10 +16,11 @@ import java.util.function.Function; * .open(); * } */ +@ApiStatus.NonExtendable public interface TableDefinition { /** Schema version of the record, at least 1. Default: 1. */ - TableDefinition version(int version); + TableDefinition version(@Range(from = 1, to = Integer.MAX_VALUE) int version); /** * How to turn a row stored with schema version {@code from} into the current record. Needed @@ -29,5 +34,6 @@ public interface TableDefinition * * @throws StorageException when the stored table does not match and no migration applies */ + @Blocking Table open(); } diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/storage/SqlTable.java b/core/src/main/java/dev/overlord/zomboidforge/core/storage/SqlTable.java index b7c146c..3204b83 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/storage/SqlTable.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/storage/SqlTable.java @@ -117,7 +117,7 @@ final class SqlTable implements Table return found; }); - return found; + return Collections.unmodifiableMap(found); } @Override @@ -168,7 +168,7 @@ final class SqlTable implements Table while (rows.next()) keys.add(rows.getString(1)); } - return keys; + return Collections.unmodifiableList(keys); }); } From b4d70c3d3a36f4d4f3db6d60cc63ee2e8021b231 Mon Sep 17 00:00:00 2001 From: Overlord Date: Wed, 7 Oct 2026 11:58:02 +0200 Subject: [PATCH 3/9] Add register listener methods annotated with @OnMain and @OnModThread; validate methods before mod loading. --- MOD_DEVELOPMENT.md | 26 ++- .../dev/overlord/zomboidforge/api/Events.java | 32 +++ .../dev/overlord/zomboidforge/api/Mod.java | 7 +- .../zomboidforge/api/annotations/OnMain.java | 19 ++ .../api/annotations/OnModThread.java | 19 ++ .../api/annotations/package-info.java | 10 + .../zomboidforge/core/mods/ModLoader.java | 8 +- .../zomboidforge/core/runtime/EventBus.java | 57 +++++- .../core/runtime/ListenerScanner.java | 187 ++++++++++++++++++ .../core/runtime/ModTaskEvent.java | 2 +- .../overlord/zomboidforge/core/ForgeTest.java | 54 +++++ .../core/runtime/EventBusTest.java | 148 ++++++++++++++ .../java/testmods/InvalidListenerMod.java | 15 ++ core/src/test/java/testmods/ListenerMod.java | 33 ++++ .../gradle/ZomboidForgeModPluginTest.java | 1 + 15 files changed, 605 insertions(+), 13 deletions(-) create mode 100644 api/src/main/java/dev/overlord/zomboidforge/api/annotations/OnMain.java create mode 100644 api/src/main/java/dev/overlord/zomboidforge/api/annotations/OnModThread.java create mode 100644 api/src/main/java/dev/overlord/zomboidforge/api/annotations/package-info.java create mode 100644 core/src/main/java/dev/overlord/zomboidforge/core/runtime/ListenerScanner.java create mode 100644 core/src/test/java/testmods/InvalidListenerMod.java create mode 100644 core/src/test/java/testmods/ListenerMod.java 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())); From 1664bb6f28b51d43a185a0e1fce134424f180343 Mon Sep 17 00:00:00 2001 From: Overlord Date: Wed, 7 Oct 2026 13:09:27 +0200 Subject: [PATCH 4/9] Add support for @OnClientCommand annotation to register and filter client command event handlers. --- MOD_DEVELOPMENT.md | 10 +++ .../dev/overlord/zomboidforge/api/Events.java | 14 ++-- .../dev/overlord/zomboidforge/api/Mod.java | 5 +- .../api/annotations/OnClientCommand.java | 39 +++++++++++ .../core/runtime/ListenerScanner.java | 63 +++++++++++++---- .../core/runtime/EventBusTest.java | 70 ++++++++++++++++++- 6 files changed, 177 insertions(+), 24 deletions(-) create mode 100644 api/src/main/java/dev/overlord/zomboidforge/api/annotations/OnClientCommand.java diff --git a/MOD_DEVELOPMENT.md b/MOD_DEVELOPMENT.md index 3e3eac5..3054fdb 100644 --- a/MOD_DEVELOPMENT.md +++ b/MOD_DEVELOPMENT.md @@ -313,6 +313,16 @@ this.events().onMain(ClientCommandEvent.class, event -> }); ``` +The same as an annotated listener method (see [Events](#events)), which filters and cancels: + +```java +@OnClientCommand(module = "Shop", command = "buy", cancel = true) // command optional: every command of the module +void buy(ClientCommandEvent event) { ... } +``` + +`cancel = true` cancels the event before the method runs, so Lua does not receive the command +even when the method throws. + Server to client: `clientCommands().send(player, ...)` and `sendToAll(...)`; the Lua mod receives them in `Events.OnServerCommand`. 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 1a7c137..04bcfea 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,6 @@ package dev.overlord.zomboidforge.api; +import dev.overlord.zomboidforge.api.annotations.OnClientCommand; import dev.overlord.zomboidforge.api.annotations.OnMain; import dev.overlord.zomboidforge.api.annotations.OnModThread; @@ -29,18 +30,19 @@ public interface Events 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. + * Registers the methods of {@code listener} annotated with {@link OnMain}, + * {@link OnModThread}, or {@link OnClientCommand}, 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};
  • + *
  • carries one of the annotations; {@link OnModThread} not for a + * {@link MainThreadEvent}, {@link OnClientCommand} only for a + * {@link ClientCommandEvent};
  • *
  • 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.
  • 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 db38c4e..af8fd7b 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java @@ -19,8 +19,9 @@ 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 dev.overlord.zomboidforge.api.annotations.OnMain OnMain}, + * {@link dev.overlord.zomboidforge.api.annotations.OnModThread OnModThread}, or + * {@link dev.overlord.zomboidforge.api.annotations.OnClientCommand OnClientCommand} 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. diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/annotations/OnClientCommand.java b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/OnClientCommand.java new file mode 100644 index 0000000..30e0482 --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/OnClientCommand.java @@ -0,0 +1,39 @@ +package dev.overlord.zomboidforge.api.annotations; + +import dev.overlord.zomboidforge.api.ClientCommandEvent; +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 {@link ClientCommandEvent}s of one + * module, and optionally one command. The method has one parameter, a {@code ClientCommandEvent}; + * otherwise the rules of {@link Events#register(Object)} apply, and the method carries none of + * the other listener annotations. + * + *
      {@code
      + * @OnClientCommand(module = "Shop", command = "buy", cancel = true)
      + * void buy(ClientCommandEvent event) { ... }
      + * }
      + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface OnClientCommand +{ + /** The Lua module, matched exactly; not blank. */ + String module(); + + /** The command, matched exactly; empty matches every command of the module. */ + String command() default ""; + + /** + * Cancels the event before the method runs, so Lua's {@code OnClientCommand} does not + * receive the command, also when the method throws. + */ + boolean cancel() default false; +} 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 index 170fc9e..d7a285e 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/runtime/ListenerScanner.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/runtime/ListenerScanner.java @@ -1,8 +1,10 @@ package dev.overlord.zomboidforge.core.runtime; +import dev.overlord.zomboidforge.api.ClientCommandEvent; import dev.overlord.zomboidforge.api.Event; import dev.overlord.zomboidforge.api.MainThreadEvent; import dev.overlord.zomboidforge.api.Mod; +import dev.overlord.zomboidforge.api.annotations.OnClientCommand; import dev.overlord.zomboidforge.api.annotations.OnMain; import dev.overlord.zomboidforge.api.annotations.OnModThread; @@ -23,9 +25,12 @@ 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. + * with {@link OnMain}, {@link OnModThread}, or {@link OnClientCommand} 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. + * + *

      An {@link OnClientCommand} method is a main-thread listener for {@link ClientCommandEvent} + * with a filter in front: only the commands of its module (and command) reach it. */ final class ListenerScanner { @@ -33,7 +38,8 @@ 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 main {@code true} for {@link OnMain} and {@link OnClientCommand}, {@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) {} @@ -63,14 +69,15 @@ final class ListenerScanner for (Method method : hierarchy.get(types.get(i))) { - boolean main = method.isAnnotationPresent(OnMain.class); - boolean modThread = method.isAnnotationPresent(OnModThread.class); + boolean main = method.isAnnotationPresent(OnMain.class); + boolean modThread = method.isAnnotationPresent(OnModThread.class); + OnClientCommand clientCommand = method.getAnnotation(OnClientCommand.class); // javac copies method annotations to bridge methods. - if ((!main && !modThread) || method.isBridge() || method.isSynthetic()) continue; - if (ListenerScanner.isOverridden(method, subclasses, hierarchy)) continue; + if ((!main && !modThread && clientCommand == null) || method.isBridge() || method.isSynthetic()) continue; + if (ListenerScanner.isOverridden(method, subclasses, hierarchy)) continue; - ListenerMethod listener = ListenerScanner.listener(target, method, main, modThread, problems); + ListenerMethod listener = ListenerScanner.listener(target, method, main, modThread, clientCommand, problems); if (listener != null) found.add(listener); } } @@ -136,15 +143,18 @@ final class ListenerScanner } /** 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) + private static @Nullable ListenerMethod listener(Object target, Method method, boolean main, boolean modThread, @Nullable OnClientCommand clientCommand, List problems) { String where = "'" + method.getDeclaringClass().getName() + "." + method.getName() + "'"; Class[] parameters = method.getParameterTypes(); int before = problems.size(); + int kinds = (main ? 1 : 0) + (modThread ? 1 : 0) + (clientCommand == null ? 0 : 1); - if (main && modThread) problems.add(where + " carries both @OnMain and @OnModThread."); + if (kinds > 1) problems.add(where + " carries more than one of @OnMain, @OnModThread, and @OnClientCommand."); if (method.getReturnType() != void.class) problems.add(where + " must return void."); + if (clientCommand != null && clientCommand.module().isBlank()) problems.add(where + ": @OnClientCommand needs a module."); + if (parameters.length != 1) { problems.add(where + " must have one parameter, the event; found " + parameters.length + "."); @@ -159,6 +169,8 @@ final class ListenerScanner 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."); + else if (clientCommand != null && type != ClientCommandEvent.class) + problems.add(where + ": @OnClientCommand methods take a ClientCommandEvent, found '" + type.getName() + "'."); if (problems.size() > before) return null; @@ -167,12 +179,15 @@ final class ListenerScanner 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 -> { + MethodHandle invoker = handle.asType(MethodType.methodType(void.class, Object.class)); + Consumer call = event -> { try { invoker.invokeExact(event); } catch (Throwable t) { throw ListenerScanner.rethrow(t); } - }); + }; + + return clientCommand == null + ? new ListenerMethod(type, main, method.getName(), call) + : new ListenerMethod(type, true, method.getName(), ListenerScanner.filter(clientCommand, call)); } catch (IllegalAccessException e) { @@ -181,6 +196,24 @@ final class ListenerScanner } } + /** {@code call} for the commands that {@code annotation} selects; cancels them first when it says so. */ + private static Consumer filter(OnClientCommand annotation, Consumer call) + { + String module = annotation.module(); + String command = annotation.command(); + boolean cancel = annotation.cancel(); + + return event -> { + ClientCommandEvent received = (ClientCommandEvent) event; + + if (!received.module().equals(module)) return; + if (!command.isEmpty() && !received.command().equals(command)) return; + + if (cancel) received.cancel(); + call.accept(event); + }; + } + /** 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/test/java/dev/overlord/zomboidforge/core/runtime/EventBusTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/runtime/EventBusTest.java index b405c53..4e93542 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 @@ -1,9 +1,12 @@ package dev.overlord.zomboidforge.core.runtime; +import dev.overlord.zomboidforge.api.ClientCommandEvent; import dev.overlord.zomboidforge.api.Event; import dev.overlord.zomboidforge.api.Events; +import dev.overlord.zomboidforge.api.PlayerRef; import dev.overlord.zomboidforge.api.Subscription; import dev.overlord.zomboidforge.api.TickEvent; +import dev.overlord.zomboidforge.api.annotations.OnClientCommand; import dev.overlord.zomboidforge.api.annotations.OnMain; import dev.overlord.zomboidforge.api.annotations.OnModThread; import dev.overlord.zomboidforge.core.RecordingLogger; @@ -13,6 +16,7 @@ import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.concurrent.Executor; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -91,6 +95,34 @@ class EventBusTest @OnModThread void mainOnly(TickEvent event) {} + + @OnClientCommand(module = "Shop") + void wrongEvent(Joined event) {} + + @OnClientCommand(module = " ") + void noModule(ClientCommandEvent event) {} + + @OnMain + @OnClientCommand(module = "Shop") + void mixed(ClientCommandEvent event) {} + } + + /** Client command handlers of the module {@code Shop}. */ + private static final class ShopCommands + { + final List log = new ArrayList<>(); + + @OnClientCommand(module = "Shop") + void any(ClientCommandEvent event) { this.log.add("any " + event.command() + (event.isCancelled() ? " cancelled" : "")); } + + @OnClientCommand(module = "Shop", command = "buy", cancel = true) + void buy(ClientCommandEvent event) { this.log.add("buy" + (event.isCancelled() ? " cancelled" : "")); } + } + + private static final class FailingCommand + { + @OnClientCommand(module = "Shop", cancel = true) + void fail(ClientCommandEvent event) { throw new IllegalStateException("broken"); } } private static final class FailingListener @@ -228,7 +260,7 @@ class EventBusTest 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")) + for (String method : List.of("anAbstract", "anInterface", "both", "mainOnly", "mixed", "noModule", "notEvent", "returns", "two", "wrongEvent")) EventBusTest.assertContainsAll(e.getMessage(), InvalidListeners.class.getName() + "." + method); EventBusTest.assertContainsAll(e.getMessage(), AbstractEvent.class.getName(), Event.class.getName(), TickEvent.class.getName(), "java.lang.String"); @@ -246,6 +278,42 @@ class EventBusTest EventBusTest.assertContainsAll(this.logger.messages.getFirst(), "ERROR", "'fail'", "Joined", "java.io.IOException: broken"); } + @Test + void clientCommandMethodsReceiveTheirModuleAndCommandOnly() + { + Events a = this.bus.forMod("a", this.modThread, this.logger); + ShopCommands commands = new ShopCommands(); + a.register(commands); + + ClientCommandEvent buy = EventBusTest.command("Shop", "buy"); + ClientCommandEvent sell = EventBusTest.command("Shop", "sell"); + ClientCommandEvent other = EventBusTest.command("Bank", "buy"); + + this.bus.post(buy); + this.bus.post(sell); + this.bus.post(other); + + assertEquals(List.of("any buy", "buy cancelled", "any sell"), commands.log, "cancelled before the method runs, after the listeners before it"); + assertTrue(buy.isCancelled()); + assertFalse(sell.isCancelled()); + assertFalse(other.isCancelled()); + } + + @Test + void clientCommandMethodsCancelAlsoWhenTheyThrow() + { + this.bus.forMod("a", this.modThread, this.logger).register(new FailingCommand()); + + ClientCommandEvent event = EventBusTest.command("Shop", "buy"); + this.bus.post(event); + + assertTrue(event.isCancelled()); + assertEquals(1, this.logger.messages.size()); + EventBusTest.assertContainsAll(this.logger.messages.getFirst(), "'fail'", "ClientCommandEvent", "broken"); + } + + private static ClientCommandEvent command(String module, String command) { return new ClientCommandEvent(new PlayerRef(1, "bob"), module, command, Map.of()); } + private static void assertContainsAll(String message, String... parts) { for (String part : parts) assertTrue(message.contains(part), "'" + part + "' missing in: " + message); From b10504e9af2b283271f08fa028ee8d1d02844083 Mon Sep 17 00:00:00 2001 From: Overlord Date: Wed, 7 Oct 2026 14:47:57 +0200 Subject: [PATCH 5/9] Add support for `@Schema` and `@Migrate` annotations to declare storage record schema versions and migrations. --- MOD_DEVELOPMENT.md | 17 +++ .../zomboidforge/api/annotations/Migrate.java | 26 +++++ .../zomboidforge/api/annotations/Schema.java | 35 ++++++ .../zomboidforge/api/storage/ModStorage.java | 19 +++- .../api/storage/TableDefinition.java | 11 +- .../zomboidforge/core/storage/ModTables.java | 23 +++- .../core/storage/RecordSchema.java | 102 +++++++++++++++++ .../core/storage/ModTablesTest.java | 103 ++++++++++++++++++ 8 files changed, 326 insertions(+), 10 deletions(-) create mode 100644 api/src/main/java/dev/overlord/zomboidforge/api/annotations/Migrate.java create mode 100644 api/src/main/java/dev/overlord/zomboidforge/api/annotations/Schema.java create mode 100644 core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordSchema.java diff --git a/MOD_DEVELOPMENT.md b/MOD_DEVELOPMENT.md index 3054fdb..6c5b676 100644 --- a/MOD_DEVELOPMENT.md +++ b/MOD_DEVELOPMENT.md @@ -399,6 +399,23 @@ Table balances = this.storage().define("balances", Balance.class) .open(); ``` +The same on the record (`dev.overlord.zomboidforge.api.annotations`), so `table(...)` is enough: + +```java +@Schema(version = 2) +record Balance(long coins, @Nullable Instant lastPaid) +{ + @Migrate(from = 1) + static Balance fromV1(Row row) { return new Balance(row.getLong("coins"), null); } +} + +Table balances = this.storage().table("balances", Balance.class); +``` + +A `@Migrate` method is static, takes a `Row`, returns the record, and may be private. `define` +starts from the annotations: `version(...)` replaces the `@Schema` version, and `migrate(...)` +adds migrations. Each version has one migration at most; a second one throws. + Things to know: 1. Storage calls block. On the main thread they are only allowed during `onLoad`; once the diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Migrate.java b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Migrate.java new file mode 100644 index 0000000..2e29a99 --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Migrate.java @@ -0,0 +1,26 @@ +package dev.overlord.zomboidforge.api.annotations; + +import dev.overlord.zomboidforge.api.storage.Row; +import dev.overlord.zomboidforge.api.storage.TableDefinition; + +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; + +/** + * A migration of a storage record, as {@link TableDefinition#migrate} adds one: turns a row stored + * with schema version {@link #from} into the record. Declared in the record itself, as a static + * method with one {@link Row} parameter that returns the record; it may be private. A record has + * at most one migration per version, whether from this annotation or from + * {@link TableDefinition#migrate}. See {@link Schema}. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Migrate +{ + /** The stored schema version this method migrates from; at least 1. */ + int from(); +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Schema.java b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Schema.java new file mode 100644 index 0000000..1940c9c --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Schema.java @@ -0,0 +1,35 @@ +package dev.overlord.zomboidforge.api.annotations; + +import dev.overlord.zomboidforge.api.storage.ModStorage; +import dev.overlord.zomboidforge.api.storage.TableDefinition; + +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; + +/** + * The schema version of a storage record, read by {@link ModStorage#table} and + * {@link ModStorage#define}; {@link TableDefinition#version} overrides it. Records without it + * have version 1. The migrations from older versions are the record's {@link Migrate} methods. + * + *
      {@code
      + * @Schema(version = 2)
      + * record Balance(long coins, @Nullable Instant lastPaid)
      + * {
      + *     @Migrate(from = 1)
      + *     static Balance fromV1(Row row) {
      + *        return new Balance(row.getLong("coins"), null);
      + *     }
      + * }
      + * }
      + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface Schema +{ + /** At least 1. */ + int version(); +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/storage/ModStorage.java b/api/src/main/java/dev/overlord/zomboidforge/api/storage/ModStorage.java index 8940051..795daed 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/storage/ModStorage.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/storage/ModStorage.java @@ -1,5 +1,8 @@ package dev.overlord.zomboidforge.api.storage; +import dev.overlord.zomboidforge.api.annotations.Migrate; +import dev.overlord.zomboidforge.api.annotations.Schema; + import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Blocking; @@ -22,11 +25,23 @@ import java.util.function.Supplier; @ApiStatus.NonExtendable public interface ModStorage { - /** Opens the table {@code name} with schema version 1 and no migrations. */ + /** + * Opens the table {@code name} with the schema version and migrations that {@code type} + * declares with {@link Schema} and {@link Migrate}; without them, version 1 and no migrations. + * + * @throws IllegalArgumentException when the name, or a {@link Schema} or {@link Migrate} of + * {@code type}, is invalid + */ @Blocking Table table(String name, Class type); - /** A table with a schema version and migrations; see {@link TableDefinition}. */ + /** + * A table to open with a schema version and migrations, starting from those of + * {@link Schema} and {@link Migrate} on {@code type}; see {@link TableDefinition}. + * + * @throws IllegalArgumentException when the name, or a {@link Schema} or {@link Migrate} of + * {@code type}, is invalid + */ TableDefinition define(String name, Class type); /** diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/storage/TableDefinition.java b/api/src/main/java/dev/overlord/zomboidforge/api/storage/TableDefinition.java index 648acb4..5710aa2 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/storage/TableDefinition.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/storage/TableDefinition.java @@ -1,5 +1,8 @@ package dev.overlord.zomboidforge.api.storage; +import dev.overlord.zomboidforge.api.annotations.Migrate; +import dev.overlord.zomboidforge.api.annotations.Schema; + import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Blocking; import org.jetbrains.annotations.Range; @@ -7,7 +10,8 @@ import org.jetbrains.annotations.Range; import java.util.function.Function; /** - * A table to open with a schema version and migrations: + * A table to open with a schema version and migrations. It starts from the record's + * {@link Schema} and {@link Migrate} methods, if any; the calls below add to them: * *
      {@code
        * Table balances = this.storage().define("balances", Balance.class)
      @@ -19,13 +23,16 @@ import java.util.function.Function;
       @ApiStatus.NonExtendable
       public interface TableDefinition
       {
      -    /** Schema version of the record, at least 1. Default: 1. */
      +    /** Schema version of the record, at least 1. Default: the record's {@link Schema}, or 1. */
           TableDefinition version(@Range(from = 1, to = Integer.MAX_VALUE) int version);
       
           /**
            * How to turn a row stored with schema version {@code from} into the current record. Needed
            * when the stored version is older than {@link #version} or the record changed in a way that
            * cannot be applied without data.
      +     *
      +     * @throws IllegalArgumentException when a migration from {@code from} exists already, also one
      +     *                                  from a {@link Migrate} method of the record
            */
           TableDefinition migrate(int from, Function migration);
       
      diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/storage/ModTables.java b/core/src/main/java/dev/overlord/zomboidforge/core/storage/ModTables.java
      index 4bd0a15..53eea92 100644
      --- a/core/src/main/java/dev/overlord/zomboidforge/core/storage/ModTables.java
      +++ b/core/src/main/java/dev/overlord/zomboidforge/core/storage/ModTables.java
      @@ -36,6 +36,9 @@ import java.util.stream.Collectors;
        *   
    5. a new primitive component, a changed type, or a different schema version needs a * migration from the stored version, which rebuilds the table in one transaction.
    6. * + * + * The schema version and the migrations come from the record ({@link RecordSchema}), and the + * calls of {@code TableDefinition} add to them. */ public final class ModTables implements ModStorage { @@ -110,7 +113,7 @@ public final class ModTables implements ModStorage if (name.length() > ModTables.NAME_MAX_LENGTH || !RecordCodec.NAME.matcher(name).matches()) throw new IllegalArgumentException("'" + name + "' is not a valid table name: lowercase letters, digits, and single underscores, at most " + ModTables.NAME_MAX_LENGTH + " characters."); - return new Definition<>(name, type); + return new Definition<>(name, type, RecordSchema.of(type)); } @Override @@ -124,12 +127,16 @@ public final class ModTables implements ModStorage private final String name; private final Class type; private final Map> migrations = new HashMap<>(); - private int version = 1; + private int version; - private Definition(String name, Class type) + /** @param declared the record's {@code @Schema} and {@code @Migrate} methods, which the builder calls add to */ + private Definition(String name, Class type, RecordSchema declared) { - this.name = name; - this.type = type; + this.name = name; + this.type = type; + this.version = declared.version(); + + this.migrations.putAll(declared.migrations()); } @Override @@ -144,7 +151,11 @@ public final class ModTables implements ModStorage @Override public TableDefinition migrate(int from, Function migration) { - this.migrations.put(from, Objects.requireNonNull(migration, "migration")); + Objects.requireNonNull(migration, "migration"); + + if (this.migrations.putIfAbsent(from, migration) != null) + throw new IllegalArgumentException("'" + this.type.getName() + "' has a migration from version " + from + " already, from @Migrate or migrate()."); + return this; } diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordSchema.java b/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordSchema.java new file mode 100644 index 0000000..9a2552b --- /dev/null +++ b/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordSchema.java @@ -0,0 +1,102 @@ +package dev.overlord.zomboidforge.core.storage; + +import dev.overlord.zomboidforge.api.annotations.Migrate; +import dev.overlord.zomboidforge.api.annotations.Schema; +import dev.overlord.zomboidforge.api.storage.Row; + +import org.jetbrains.annotations.Nullable; + +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.UndeclaredThrowableException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; + +/** + * The schema version and migrations that a storage record declares with {@link Schema} and + * {@link Migrate}. Migration methods are called through method handles from a private lookup, + * as {@link RecordCodec} reads records. + * + * @param version from {@link Schema}, or 1 without it + * @param migrations stored schema version to migration, from the {@link Migrate} methods + */ +record RecordSchema(int version, Map> migrations) +{ + RecordSchema + { + migrations = Map.copyOf(migrations); + } + + /** @throws IllegalArgumentException listing every invalid annotation of {@code type} */ + static RecordSchema of(Class type) + { + Schema schema = type.getAnnotation(Schema.class); + int version = schema == null ? 1 : schema.version(); + List problems = new ArrayList<>(); + + if (version < 1) problems.add("'" + type.getName() + "': @Schema(version = " + version + ") is not a version; versions start at 1."); + + Method[] methods; + + // Reading the methods loads every parameter and return type they name. + try { methods = type.getDeclaredMethods(); } + catch (LinkageError e) { throw new IllegalArgumentException("Cannot read the methods of '" + type.getName() + "': " + e + ".", e); } + + Arrays.sort(methods, Comparator.comparing(Method::getName)); + + Map> migrations = new HashMap<>(); + + for (Method method : methods) + { + Migrate migrate = method.getAnnotation(Migrate.class); + if (migrate == null) continue; + + Function migration = RecordSchema.migration(type, method, migrate, migrations, problems); + if (migration != null) migrations.put(migrate.from(), migration); + } + + if (!problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems)); + + return new RecordSchema<>(version, migrations); + } + + /** The migration of {@code method}, or {@code null} after adding its problems to {@code problems}. */ + private static @Nullable Function migration(Class type, Method method, Migrate migrate, Map> found, List problems) + { + String where = "'" + type.getName() + "." + method.getName() + "'"; + int before = problems.size(); + + if (!Modifier.isStatic(method.getModifiers())) problems.add(where + " must be static."); + if (method.getParameterCount() != 1 || method.getParameterTypes()[0] != Row.class) problems.add(where + " must have one parameter, a Row."); + if (method.getReturnType() != type) problems.add(where + " must return '" + type.getSimpleName() + "'."); + + if (migrate.from() < 1) problems.add(where + ": @Migrate(from = " + migrate.from() + ") is not a version; versions start at 1."); + else if (found.containsKey(migrate.from())) problems.add(where + ": another @Migrate method migrates from version " + migrate.from() + "."); + + if (problems.size() > before) return null; + + try + { + MethodHandle handle = MethodHandles.privateLookupIn(type, MethodHandles.lookup()).unreflect(method); + + return row -> { + // Checked exceptions are wrapped: the caller reports RuntimeExceptions of a migration with the row. + try { return type.cast(handle.invoke(row)); } + catch (RuntimeException | Error e) { throw e; } + catch (Throwable t) { throw new UndeclaredThrowableException(t, t.toString()); } + }; + } + catch (IllegalAccessException e) + { + problems.add(where + " cannot be accessed: " + e.getMessage()); + return null; + } + } +} diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/storage/ModTablesTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/storage/ModTablesTest.java index 92dac79..bd57c51 100644 --- a/core/src/test/java/dev/overlord/zomboidforge/core/storage/ModTablesTest.java +++ b/core/src/test/java/dev/overlord/zomboidforge/core/storage/ModTablesTest.java @@ -1,6 +1,9 @@ package dev.overlord.zomboidforge.core.storage; +import dev.overlord.zomboidforge.api.annotations.Migrate; +import dev.overlord.zomboidforge.api.annotations.Schema; import dev.overlord.zomboidforge.api.storage.ModStorage; +import dev.overlord.zomboidforge.api.storage.Row; import dev.overlord.zomboidforge.api.storage.StorageException; import dev.overlord.zomboidforge.api.storage.Table; import dev.overlord.zomboidforge.core.RecordingLogger; @@ -11,6 +14,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; @@ -53,6 +57,43 @@ class ModTablesTest private record RenamedDifficulty(RenamedMode mode) {} + @Schema(version = 2) + private record AnnotatedLevel(long coins, int level) + { + @Migrate(from = 1) + private static AnnotatedLevel fromV1(Row row) { return new AnnotatedLevel(row.getLong("coins") * 10, 1); } + } + + @Schema(version = 2) + private record FailingMigration(long coins, int level) + { + @Migrate(from = 1) + static FailingMigration fromV1(Row row) throws IOException { throw new IOException("broken"); } + } + + @Schema(version = 0) + @SuppressWarnings("unused") + private record InvalidSchema(long coins) + { + @Migrate(from = 0) + static InvalidSchema zero(Row row) { return new InvalidSchema(0); } + + @Migrate(from = 1) + InvalidSchema notStatic(Row row) { return this; } + + @Migrate(from = 2) + static InvalidSchema twoParameters(Row row, Row other) { return new InvalidSchema(0); } + + @Migrate(from = 3) + static String wrongReturn(Row row) { return ""; } + + @Migrate(from = 4) + static InvalidSchema first(Row row) { return new InvalidSchema(0); } + + @Migrate(from = 4) + static InvalidSchema second(Row row) { return new InvalidSchema(0); } + } + @TempDir Path directory; @@ -277,6 +318,63 @@ class ModTablesTest assertEquals(Optional.of(new Balance(1)), this.storage("shop").table("balances", Balance.class).get("a")); } + @Test + void migratesWithTheRecordsAnnotationsAlone() + { + this.storage("shop").table("balances", Balance.class).setAll(Map.of("a", new Balance(1), "b", new Balance(2))); + + Table migrated = this.storage("shop").table("balances", AnnotatedLevel.class); + + assertEquals(Map.of("a", new AnnotatedLevel(10, 1), "b", new AnnotatedLevel(20, 1)), migrated.getAll(List.of("a", "b"))); + ModTablesTest.assertContainsAll(this.logger.messages.getLast(), "'balances'", "2 row(s)"); + } + + @Test + void builderCallsOverrideTheVersionAndKeepTheAnnotatedMigrations() + { + this.storage("shop").table("balances", Balance.class).set("a", new Balance(1)); + + Table migrated = this.storage("shop").define("balances", AnnotatedLevel.class).version(3).open(); + assertEquals(Optional.of(new AnnotatedLevel(10, 1)), migrated.get("a")); + + StorageException older = assertThrows(StorageException.class, () -> this.storage("shop").table("balances", AnnotatedLevel.class)); + ModTablesTest.assertContainsAll(older.getMessage(), "'balances'", "3", "2"); + } + + @Test + void allowsOneMigrationPerVersion() + { + IllegalArgumentException annotated = assertThrows(IllegalArgumentException.class, () -> this.storage("shop").define("balances", AnnotatedLevel.class) + .migrate(1, row -> new AnnotatedLevel(0, 0))); + ModTablesTest.assertContainsAll(annotated.getMessage(), AnnotatedLevel.class.getName(), "1"); + + IllegalArgumentException twice = assertThrows(IllegalArgumentException.class, () -> this.storage("shop").define("balances", BalanceWithLevel.class) + .migrate(1, row -> new BalanceWithLevel(0, 0)) + .migrate(1, row -> new BalanceWithLevel(1, 1))); + ModTablesTest.assertContainsAll(twice.getMessage(), BalanceWithLevel.class.getName(), "1"); + } + + @Test + void rejectsInvalidSchemaAnnotationsWithEveryProblem() + { + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> this.storage("shop").define("invalid", InvalidSchema.class)); + + ModTablesTest.assertContainsAll(e.getMessage(), "@Schema", "zero", "notStatic", "twoParameters", "wrongReturn", "second"); + assertFalse(e.getMessage().contains(".first'"), "the first migration from 4 is valid: " + e.getMessage()); + assertFalse(Files.exists(this.file), "nothing is stored"); + } + + @Test + void reportsCheckedExceptionsOfAnnotatedMigrationsWithTheRow() + { + this.storage("shop").table("balances", Balance.class).set("a", new Balance(1)); + + StorageException e = assertThrows(StorageException.class, () -> this.storage("shop").table("balances", FailingMigration.class)); + + ModTablesTest.assertContainsAll(e.getMessage(), "'a'", "java.io.IOException: broken"); + assertEquals(Optional.of(new Balance(1)), this.storage("shop").table("balances", Balance.class).get("a")); + } + @Test void adoptsTheTablesOfPreviousIdsOnce() { @@ -391,4 +489,9 @@ class ModTablesTest this.database.close(); assertThrows(StorageException.class, () -> empty.contains("a")); } + + private static void assertContainsAll(String message, String... parts) + { + for (String part : parts) assertTrue(message.contains(part), "'" + part + "' missing in: " + message); + } } From 9fcde10fed0e970f854b72477b9ad2fbc9bc0c1c Mon Sep 17 00:00:00 2001 From: Overlord Date: Wed, 7 Oct 2026 20:02:29 +0200 Subject: [PATCH 6/9] Add support for `@Every` and `@EveryNTicks` annotations to schedule periodic and tick-based method execution. --- MOD_DEVELOPMENT.md | 19 ++ .../dev/overlord/zomboidforge/api/Events.java | 15 +- .../dev/overlord/zomboidforge/api/Mod.java | 9 +- .../zomboidforge/api/annotations/Every.java | 48 +++++ .../api/annotations/EveryNTicks.java | 32 +++ .../dev/overlord/zomboidforge/core/Forge.java | 11 +- .../zomboidforge/core/runtime/EventBus.java | 126 +++++++++++- .../core/runtime/ListenerScanner.java | 189 +++++++++++++++--- .../overlord/zomboidforge/core/ForgeTest.java | 25 +++ .../core/runtime/EventBusTest.java | 177 +++++++++++++++- core/src/test/java/testmods/ScheduleMod.java | 39 ++++ 11 files changed, 632 insertions(+), 58 deletions(-) create mode 100644 api/src/main/java/dev/overlord/zomboidforge/api/annotations/Every.java create mode 100644 api/src/main/java/dev/overlord/zomboidforge/api/annotations/EveryNTicks.java create mode 100644 core/src/test/java/testmods/ScheduleMod.java diff --git a/MOD_DEVELOPMENT.md b/MOD_DEVELOPMENT.md index 6c5b676..d969f4c 100644 --- a/MOD_DEVELOPMENT.md +++ b/MOD_DEVELOPMENT.md @@ -240,6 +240,25 @@ void onGreeting(SomeEvent event) { ... } - A method that breaks these rules stops the server with every problem in the log; `register` throws an `IllegalArgumentException` instead. +### Scheduled methods + +```java +@Every(value = 1, unit = ChronoUnit.MINUTES) // on zf-mod-; optional: initialDelay, fixedDelay = true +void report() { ... } + +@EveryNTicks(10) // on the main thread, every 10th frame +void sweep() { ... } +``` + +- They follow the rules of listener methods, with no parameters. `unit` is `MILLIS`, + `SECONDS` (default), `MINUTES`, `HOURS`, or `DAYS`, and also applies to `initialDelay`. +- `@Every` starts after the mod's `onServerStarted()` (also when it threw), or at once for an + object registered later. Without `fixedDelay`, the period counts from the start of each + run; with it, from the end. A run that throws is logged and ends the schedule. +- `@EveryNTicks(n)` is a `TickEvent` listener for the ticks n, 2n, ...: it may touch game + objects and must return quickly. +- Cancelling the object's `Subscription` ends both; stopping the server ends `@Every`. + ## Commands Admin commands work wherever Project Zomboid's own commands work: in the in-game chat 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 04bcfea..92c3a96 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,7 @@ package dev.overlord.zomboidforge.api; +import dev.overlord.zomboidforge.api.annotations.Every; +import dev.overlord.zomboidforge.api.annotations.EveryNTicks; import dev.overlord.zomboidforge.api.annotations.OnClientCommand; import dev.overlord.zomboidforge.api.annotations.OnMain; import dev.overlord.zomboidforge.api.annotations.OnModThread; @@ -32,14 +34,15 @@ public interface Events /** * Registers the methods of {@code listener} annotated with {@link OnMain}, * {@link OnModThread}, or {@link OnClientCommand}, as {@link #onMain} and {@link #onModThread} - * do. ZomboidForge registers the mod's entry point this way after its constructor and before + * do, and schedules those annotated with {@link Every} or {@link EveryNTicks}. 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;
      • + *
      • returns {@code void}. A listener 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; a scheduled method has none;
      • *
      • carries one of the annotations; {@link OnModThread} not for a * {@link MainThreadEvent}, {@link OnClientCommand} only for a * {@link ClientCommandEvent};
      • @@ -51,8 +54,8 @@ public interface Events * 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 + * @return one subscription for every listener and scheduled 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 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 af8fd7b..7b9e59c 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java @@ -20,12 +20,15 @@ import java.nio.file.Path; *
          *
        1. Listener methods: the methods annotated with * {@link dev.overlord.zomboidforge.api.annotations.OnMain OnMain}, - * {@link dev.overlord.zomboidforge.api.annotations.OnModThread OnModThread}, or - * {@link dev.overlord.zomboidforge.api.annotations.OnClientCommand OnClientCommand} are registered (see + * {@link dev.overlord.zomboidforge.api.annotations.OnModThread OnModThread}, + * {@link dev.overlord.zomboidforge.api.annotations.OnClientCommand OnClientCommand}, or + * {@link dev.overlord.zomboidforge.api.annotations.EveryNTicks EveryNTicks} 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 #onServerStarted()}: the world is loaded and the network port is open. Once it + * returned, the methods annotated with + * {@link dev.overlord.zomboidforge.api.annotations.Every Every} start.
        8. *
        9. {@link #onStopping()}: the server stops; the world has not been saved yet.
        10. *
        * An exception thrown by the constructor or {@link #onLoad()}, or a listener method that breaks diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Every.java b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Every.java new file mode 100644 index 0000000..f5d84c8 --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Every.java @@ -0,0 +1,48 @@ +package dev.overlord.zomboidforge.api.annotations; + +import dev.overlord.zomboidforge.api.Events; +import dev.overlord.zomboidforge.api.ModThread; + +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; +import java.time.temporal.ChronoUnit; + +/** + * Runs the method periodically on the mod's own thread, as {@link ModThread#scheduleAtFixedRate} + * or {@link ModThread#scheduleWithFixedDelay} do. The schedule starts once the mod's + * {@code onServerStarted()} returned (also when it threw); for an object registered later with + * {@link Events#register(Object)}, at once. A run that throws is logged and ends the schedule; + * the schedule ends as well when the server stops or the object's subscription is cancelled. + * + *

        The method has no parameters and returns {@code void}; otherwise the rules of + * {@link Events#register(Object)} apply. Like any mod-thread work, it must not touch game + * objects. + * + *

        {@code
        + * @Every(value = 1, unit = ChronoUnit.MINUTES)
        + * void report() { ... }
        + * }
        + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Every +{ + /** The period, at least 1. */ + long value(); + + /** The unit of {@link #value} and {@link #initialDelay}: {@code MILLIS}, {@code SECONDS}, {@code MINUTES}, {@code HOURS}, or {@code DAYS}. */ + ChronoUnit unit() default ChronoUnit.SECONDS; + + /** The time before the first run, at least 0. */ + long initialDelay() default 0; + + /** + * {@code false}: the period counts from the start of each run (fixed rate); {@code true}: from + * the end of each run (fixed delay). + */ + boolean fixedDelay() default false; +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/annotations/EveryNTicks.java b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/EveryNTicks.java new file mode 100644 index 0000000..cc680d8 --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/EveryNTicks.java @@ -0,0 +1,32 @@ +package dev.overlord.zomboidforge.api.annotations; + +import dev.overlord.zomboidforge.api.Events; +import dev.overlord.zomboidforge.api.TickEvent; + +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; + +/** + * Runs the method on the main thread every n-th frame of the main loop: a {@link TickEvent} + * listener for the ticks that {@link #value} divides (n, 2n, ...). It may touch game objects and, + * like every main-thread listener, must return quickly. + * + *

        The method has no parameters and returns {@code void}; otherwise the rules of + * {@link Events#register(Object)} apply. + * + *

        {@code
        + * @EveryNTicks(10)
        + * void sweep() { ... }
        + * }
        + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface EveryNTicks +{ + /** n, at least 1. */ + int value(); +} diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java b/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java index a7f31a8..c8b26c7 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java @@ -183,16 +183,21 @@ public final class Forge } /** - * Calls {@link Mod#onServerStarted()} of every mod in load order. Main thread. Anything a - * mod throws is logged, and the next mod is called. + * Calls {@link Mod#onServerStarted()} of every mod in load order, then starts that mod's + * {@code @Every} methods. Main thread. Anything a mod throws is logged, and the next mod is + * called. */ public void started() { this.lifecycle.started(); - for (ModLoader.LoadedMod mod : this.mods) { + for (ModLoader.LoadedMod mod : this.mods) + { try { mod.mod().onServerStarted(); } catch (Throwable t) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onServerStarted() threw.", t); } + + // Also after a failed onServerStarted(): the mod's listeners stay active as well. + this.events.start(mod.descriptor().id()); } } 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 1c94db8..c43a94f 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 @@ -3,10 +3,12 @@ package dev.overlord.zomboidforge.core.runtime; import dev.overlord.zomboidforge.api.Event; import dev.overlord.zomboidforge.api.Events; import dev.overlord.zomboidforge.api.MainThreadEvent; +import dev.overlord.zomboidforge.api.ModThread; import dev.overlord.zomboidforge.api.Subscription; import org.jetbrains.annotations.Nullable; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.IdentityHashMap; @@ -17,6 +19,7 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; @@ -25,6 +28,9 @@ import java.util.function.Consumer; * Event dispatch for every mod. Listeners are matched by the event's exact class and called in * registration order. Registration replaces the listener array of a class, so {@link #post} * iterates a snapshot without locks. + * + *

        Also starts the methods annotated with {@code @Every} of registered objects, on their mod's + * thread, once {@link #start} was called for the mod. */ public final class EventBus { @@ -32,11 +38,29 @@ public final class EventBus static final int MAX_FAILURES = 10; private final Map, Listener[]> listeners = new ConcurrentHashMap<>(); + private final Map mods = new ConcurrentHashMap<>(); private volatile boolean closed; /** Registration for one mod; its listeners are tagged with {@code id}. */ - public Events forMod(String id, Executor modThread, System.Logger logger) { return new ModEvents(id, modThread, logger); } + public Events forMod(String id, ModThread modThread, System.Logger logger) + { + ModEvents events = new ModEvents(id, modThread, logger); + this.mods.put(id, events); + + return events; + } + + /** + * Starts the schedules of the {@code @Every} methods that the mod {@code id} registered so + * far; those it registers later start at once. Called after the mod's + * {@code onServerStarted()}. + */ + public void start(String id) + { + ModEvents events = this.mods.get(id); + if (events != null) events.start(); + } /** Whether any listener is registered for exactly this class. */ public boolean hasListeners(Class type) { return this.listeners.containsKey(type); } @@ -82,13 +106,19 @@ public final class EventBus private final class ModEvents implements Events { private final String id; - private final Executor modThread; + private final ModThread 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) + /** Schedules registered before {@link #start()}; guarded by itself. */ + private final List pending = new ArrayList<>(); + + /** Whether {@link #start()} ran; guarded by {@link #pending}. */ + private boolean started; + + private ModEvents(String id, ModThread modThread, System.Logger logger) { this.id = id; this.modThread = modThread; @@ -112,27 +142,59 @@ public final class EventBus { Objects.requireNonNull(listener, "listener"); - List methods = ListenerScanner.scan(listener); + ListenerScanner.Found found = 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() + List listeners = found.listeners().stream() .map(method -> this.add(method.type(), method.action(), method.main() ? null : this.modThread, method.name())) .toList(); + List schedules = found.schedules().stream() + .map(method -> new Schedule(method, this.modThread, this.logger)) + .toList(); + + boolean now; + + synchronized (this.pending) + { + now = this.started; + if (!now) this.pending.addAll(schedules); + } + + if (now) schedules.forEach(Schedule::start); + AtomicBoolean active = new AtomicBoolean(true); return () -> { if (!active.getAndSet(false)) return; listeners.forEach(Listener::cancel); + schedules.forEach(Schedule::cancel); + + synchronized (this.pending) { this.pending.removeAll(schedules); } synchronized (this.registered) { this.registered.remove(listener); } }; } + /** Starts the pending schedules; later ones start when they are registered. */ + private void start() + { + List schedules; + + synchronized (this.pending) + { + this.started = true; + schedules = List.copyOf(this.pending); + this.pending.clear(); + } + + schedules.forEach(Schedule::start); + } + private Subscription register(Class type, Consumer listener, @Nullable Executor executor) { Objects.requireNonNull(type, "type"); @@ -213,4 +275,58 @@ public final class EventBus } } } + + /** + * An {@code @Every} method on its mod's thread. A run that throws is logged and ends the + * schedule, as {@code ModThread.scheduleAtFixedRate} does. + */ + private static final class Schedule + { + private final ListenerScanner.ScheduledMethod method; + private final ModThread modThread; + private final System.Logger logger; + + /** Guarded by {@code this}. */ + private @Nullable ScheduledFuture future; + private boolean cancelled; + + private Schedule(ListenerScanner.ScheduledMethod method, ModThread modThread, System.Logger logger) + { + this.method = method; + this.modThread = modThread; + this.logger = logger; + } + + private synchronized void start() + { + if (this.cancelled || this.future != null) return; + + try + { + this.future = this.method.fixedDelay() + ? this.modThread.scheduleWithFixedDelay(this::run, this.method.initialDelay(), this.method.period()) + : this.modThread.scheduleAtFixedRate(this::run, this.method.initialDelay(), this.method.period()); + } + catch (RejectedExecutionException e) { /* the mod's thread has been shut down */ } + } + + private synchronized void cancel() + { + this.cancelled = true; + if (this.future != null) this.future.cancel(false); + } + + private void run() + { + try + { + this.method.action().run(); + } + catch (Throwable t) + { + this.logger.log(System.Logger.Level.ERROR, "Scheduled method '" + this.method.name() + "' threw; its schedule ends.", t); + this.cancel(); + } + } + } } 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 index d7a285e..ac82b9a 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/runtime/ListenerScanner.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/runtime/ListenerScanner.java @@ -4,63 +4,89 @@ import dev.overlord.zomboidforge.api.ClientCommandEvent; import dev.overlord.zomboidforge.api.Event; import dev.overlord.zomboidforge.api.MainThreadEvent; import dev.overlord.zomboidforge.api.Mod; +import dev.overlord.zomboidforge.api.TickEvent; +import dev.overlord.zomboidforge.api.annotations.Every; +import dev.overlord.zomboidforge.api.annotations.EveryNTicks; import dev.overlord.zomboidforge.api.annotations.OnClientCommand; import dev.overlord.zomboidforge.api.annotations.OnMain; import dev.overlord.zomboidforge.api.annotations.OnModThread; import org.jetbrains.annotations.Nullable; +import java.lang.annotation.Annotation; 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.time.Duration; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; +import java.util.EnumSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.Set; import java.util.function.Consumer; /** - * Finds the listener methods of an object for {@code Events.register(Object)}: methods annotated - * with {@link OnMain}, {@link OnModThread}, or {@link OnClientCommand} 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. + * Finds the annotated methods of an object for {@code Events.register(Object)}: methods annotated + * with {@link OnMain}, {@link OnModThread}, {@link OnClientCommand}, {@link Every}, or + * {@link EveryNTicks} 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. * *

        An {@link OnClientCommand} method is a main-thread listener for {@link ClientCommandEvent} - * with a filter in front: only the commands of its module (and command) reach it. + * with a filter in front: only the commands of its module (and command) reach it. An + * {@link EveryNTicks} method is a main-thread listener for {@link TickEvent} that only every n-th + * tick reaches. {@link Every} methods are returned as schedules. */ final class ListenerScanner { + /** What {@link #scan} found, each list in registration order. */ + record Found(List listeners, List schedules) {} + /** * One listener method, bound to its object. * * @param type the event class, the method's parameter type - * @param main {@code true} for {@link OnMain} and {@link OnClientCommand}, {@code false} for - * {@link OnModThread} + * @param main {@code true} for {@link OnMain}, {@link OnClientCommand}, and + * {@link EveryNTicks}, {@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) {} + /** + * One {@link Every} method, bound to its object. + * + * @param action calls the method; rethrows what the method throws, unchanged + */ + record ScheduledMethod(String name, Duration initialDelay, Duration period, boolean fixedDelay, Runnable action) {} + private static final Comparator ORDER = Comparator .comparing(Method::getName) .thenComparing(method -> Arrays.toString(method.getParameterTypes())); + /** Units of {@link Every}: {@code Duration.of} rejects estimated ones, and shorter ones make no sense on a shared thread. */ + private static final Set UNITS = EnumSet.of(ChronoUnit.MILLIS, ChronoUnit.SECONDS, ChronoUnit.MINUTES, ChronoUnit.HOURS, ChronoUnit.DAYS); + private ListenerScanner() {} /** - * @return the listener methods of {@code target}, in registration order: superclass methods + * @return the annotated 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) + static Found scan(Object target) { Map, Method[]> hierarchy = ListenerScanner.declaredMethods(target.getClass()); List> types = List.copyOf(hierarchy.keySet()); - List found = new ArrayList<>(); + List listeners = new ArrayList<>(); + List schedules = new ArrayList<>(); List problems = new ArrayList<>(); for (int i = 0; i < types.size(); i++) @@ -69,22 +95,42 @@ final class ListenerScanner for (Method method : hierarchy.get(types.get(i))) { - boolean main = method.isAnnotationPresent(OnMain.class); - boolean modThread = method.isAnnotationPresent(OnModThread.class); + OnModThread modThread = method.getAnnotation(OnModThread.class); OnClientCommand clientCommand = method.getAnnotation(OnClientCommand.class); + Every every = method.getAnnotation(Every.class); + EveryNTicks everyNTicks = method.getAnnotation(EveryNTicks.class); + long kinds = ListenerScanner.count(method.getAnnotation(OnMain.class), modThread, clientCommand, every, everyNTicks); // javac copies method annotations to bridge methods. - if ((!main && !modThread && clientCommand == null) || method.isBridge() || method.isSynthetic()) continue; - if (ListenerScanner.isOverridden(method, subclasses, hierarchy)) continue; + if (kinds == 0 || method.isBridge() || method.isSynthetic()) continue; + if (ListenerScanner.isOverridden(method, subclasses, hierarchy)) continue; - ListenerMethod listener = ListenerScanner.listener(target, method, main, modThread, clientCommand, problems); - if (listener != null) found.add(listener); + String where = "'" + method.getDeclaringClass().getName() + "." + method.getName() + "'"; + + if (kinds > 1) + { + problems.add(where + " carries more than one of @OnMain, @OnModThread, @OnClientCommand, @Every, and @EveryNTicks."); + continue; + } + + if (every != null) + { + ScheduledMethod schedule = ListenerScanner.every(target, method, every, where, problems); + if (schedule != null) schedules.add(schedule); + continue; + } + + ListenerMethod listener = everyNTicks != null + ? ListenerScanner.everyNTicks(target, method, everyNTicks, where, problems) + : ListenerScanner.listener(target, method, modThread != null, clientCommand, where, problems); + + if (listener != null) listeners.add(listener); } } if (!problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems)); - return List.copyOf(found); + return new Found(List.copyOf(listeners), List.copyOf(schedules)); } /** @@ -143,16 +189,12 @@ final class ListenerScanner } /** 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, @Nullable OnClientCommand clientCommand, List problems) + private static @Nullable ListenerMethod listener(Object target, Method method, boolean modThread, @Nullable OnClientCommand clientCommand, String where, List problems) { - String where = "'" + method.getDeclaringClass().getName() + "." + method.getName() + "'"; Class[] parameters = method.getParameterTypes(); int before = problems.size(); - int kinds = (main ? 1 : 0) + (modThread ? 1 : 0) + (clientCommand == null ? 0 : 1); - - if (kinds > 1) problems.add(where + " carries more than one of @OnMain, @OnModThread, and @OnClientCommand."); - if (method.getReturnType() != void.class) problems.add(where + " must return void."); + if (method.getReturnType() != void.class) problems.add(where + " must return void."); if (clientCommand != null && clientCommand.module().isBlank()) problems.add(where + ": @OnClientCommand needs a module."); if (parameters.length != 1) @@ -174,20 +216,100 @@ final class ListenerScanner if (problems.size() > before) return null; + MethodHandle invoker = ListenerScanner.handle(target, method, MethodType.methodType(void.class, Object.class), where, problems); + if (invoker == null) return null; + + Consumer call = event -> { + try { invoker.invokeExact(event); } + catch (Throwable t) { throw ListenerScanner.rethrow(t); } + }; + + return clientCommand == null + ? new ListenerMethod(type, !modThread, method.getName(), call) + : new ListenerMethod(type, true, method.getName(), ListenerScanner.filter(clientCommand, call)); + } + + /** The {@link TickEvent} listener for an {@link EveryNTicks} method, or {@code null} after adding its problems to {@code problems}. */ + private static @Nullable ListenerMethod everyNTicks(Object target, Method method, EveryNTicks annotation, String where, List problems) + { + int before = problems.size(); + int n = annotation.value(); + + ListenerScanner.checkScheduled(method, where, problems); + if (n < 1) problems.add(where + ": @EveryNTicks(" + n + ") must be at least 1."); + + if (problems.size() > before) return null; + + MethodHandle invoker = ListenerScanner.handle(target, method, MethodType.methodType(void.class), where, problems); + if (invoker == null) return null; + + return new ListenerMethod(TickEvent.class, true, method.getName(), event -> { + if (((TickEvent) event).tick() % n != 0) return; + + try { invoker.invokeExact(); } + catch (Throwable t) { throw ListenerScanner.rethrow(t); } + }); + } + + /** The schedule of an {@link Every} method, or {@code null} after adding its problems to {@code problems}. */ + private static @Nullable ScheduledMethod every(Object target, Method method, Every annotation, String where, List problems) + { + int before = problems.size(); + + ListenerScanner.checkScheduled(method, where, problems); + + if (annotation.value() < 1) problems.add(where + ": @Every(value = " + annotation.value() + ") must be at least 1."); + if (annotation.initialDelay() < 0) problems.add(where + ": @Every(initialDelay = " + annotation.initialDelay() + ") must be at least 0."); + if (!ListenerScanner.UNITS.contains(annotation.unit())) problems.add(where + ": @Every(unit = " + annotation.unit().name() + ") is not one of MILLIS, SECONDS, MINUTES, HOURS, and DAYS."); + + if (problems.size() > before) return null; + + Duration initialDelay; + Duration period; + + // The mod thread schedules in nanoseconds, so the durations have to fit a long of nanoseconds. + try + { + initialDelay = Duration.of(annotation.initialDelay(), annotation.unit()); + period = Duration.of(annotation.value(), annotation.unit()); + + initialDelay.toNanos(); + period.toNanos(); + } + catch (ArithmeticException e) + { + problems.add(where + ": @Every is longer than the mod thread can schedule (about 292 years)."); + return null; + } + + MethodHandle invoker = ListenerScanner.handle(target, method, MethodType.methodType(void.class), where, problems); + if (invoker == null) return null; + + return new ScheduledMethod(method.getName(), initialDelay, period, annotation.fixedDelay(), () -> { + try { invoker.invokeExact(); } + catch (Throwable t) { throw ListenerScanner.rethrow(t); } + }); + } + + /** Adds the problems of a scheduled method: it returns {@code void} and has no parameters. */ + private static void checkScheduled(Method method, String where, List problems) + { + if (method.getReturnType() != void.class) problems.add(where + " must return void."); + if (method.getParameterCount() != 0) problems.add(where + " must have no parameters; found " + method.getParameterCount() + "."); + } + + /** + * A handle for {@code method} of type {@code type}, bound to {@code target} for an instance + * method, or {@code null} after adding the problem to {@code problems}. + */ + private static @Nullable MethodHandle handle(Object target, Method method, MethodType type, String where, List problems) + { 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)); - Consumer call = event -> { - try { invoker.invokeExact(event); } - catch (Throwable t) { throw ListenerScanner.rethrow(t); } - }; - - return clientCommand == null - ? new ListenerMethod(type, main, method.getName(), call) - : new ListenerMethod(type, true, method.getName(), ListenerScanner.filter(clientCommand, call)); + return handle.asType(type); } catch (IllegalAccessException e) { @@ -196,6 +318,9 @@ final class ListenerScanner } } + /** The number of {@code annotations} that are present. */ + private static long count(@Nullable Annotation... annotations) { return Arrays.stream(annotations).filter(Objects::nonNull).count(); } + /** {@code call} for the commands that {@code annotation} selects; cancels them first when it says so. */ private static Consumer filter(OnClientCommand annotation, Consumer call) { 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 eb9d367..f917e1b 100644 --- a/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java +++ b/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java @@ -17,6 +17,7 @@ import testmods.ErrorMod; import testmods.InvalidListenerMod; import testmods.ListenerMod; import testmods.Recorder; +import testmods.ScheduleMod; import testmods.ThreadMod; import java.io.IOException; @@ -27,6 +28,7 @@ import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BooleanSupplier; import java.util.stream.Stream; @@ -378,6 +380,29 @@ class ForgeTest ForgeTest.assertContainsAll(e.problems().getFirst(), "'missing'", "missing.MissingMod", "NoClassDefFoundError", "gone/Type"); } + @Test + void startsEveryMethodsAfterOnServerStartedAlsoWhenItThrows() throws Exception + { + TestMods.folder(this.mods, "schedules", TestMods.toml("schedules", ScheduleMod.class.getName(), ""), Map.of( + "testmods/ScheduleMod", TestMods.classFile(ScheduleMod.class) + )); + + Forge forge = this.load(); + Object mod = forge.mods().getFirst().mod(); + String main = Thread.currentThread().getName(); + + AtomicInteger runs = (AtomicInteger) ForgeTest.field(mod, "runs"); + + forge.started(); + ForgeTest.await(() -> runs.get() >= 2); + assertEquals(false, ForgeTest.field(mod, "ranBeforeStarted")); + + for (int i = 0; i < 4; i++) forge.tick(); + assertEquals(List.of("started", "tick on " + main, "tick on " + main), ForgeTest.field(mod, "log")); + + forge.stopping(); + } + 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/dev/overlord/zomboidforge/core/runtime/EventBusTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/runtime/EventBusTest.java index 4e93542..ffdfe86 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 @@ -3,9 +3,12 @@ package dev.overlord.zomboidforge.core.runtime; import dev.overlord.zomboidforge.api.ClientCommandEvent; import dev.overlord.zomboidforge.api.Event; import dev.overlord.zomboidforge.api.Events; +import dev.overlord.zomboidforge.api.ModThread; import dev.overlord.zomboidforge.api.PlayerRef; import dev.overlord.zomboidforge.api.Subscription; import dev.overlord.zomboidforge.api.TickEvent; +import dev.overlord.zomboidforge.api.annotations.Every; +import dev.overlord.zomboidforge.api.annotations.EveryNTicks; import dev.overlord.zomboidforge.api.annotations.OnClientCommand; import dev.overlord.zomboidforge.api.annotations.OnMain; import dev.overlord.zomboidforge.api.annotations.OnModThread; @@ -14,10 +17,17 @@ import dev.overlord.zomboidforge.core.RecordingLogger; import org.junit.jupiter.api.Test; import java.io.IOException; +import java.time.Duration; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.concurrent.Executor; +import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Delayed; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -105,6 +115,96 @@ class EventBusTest @OnMain @OnClientCommand(module = "Shop") void mixed(ClientCommandEvent event) {} + + @Every(0) + void zeroPeriod() {} + + @Every(value = 1, unit = ChronoUnit.WEEKS) + void weeks() {} + + @Every(value = 1, initialDelay = -1) + void negativeDelay() {} + + @Every(1) + void withParameter(Joined event) {} + + @Every(value = Long.MAX_VALUE, unit = ChronoUnit.DAYS) + void tooLong() {} + + @EveryNTicks(0) + void zeroTicks() {} + + @Every(1) + @EveryNTicks(1) + void twoSchedules() {} + } + + /** Scheduled methods: two on the mod thread, one every third tick. */ + private static final class Scheduled + { + final List log = new ArrayList<>(); + + @Every(value = 1, unit = ChronoUnit.MINUTES) + void report() { this.log.add("report"); } + + @Every(value = 5, initialDelay = 2, fixedDelay = true) + void sweep() { this.log.add("sweep"); } + + @EveryNTicks(3) + void third() { this.log.add("third"); } + } + + private static final class FailingSchedule + { + @Every(1) + void fail() throws IOException { throw new IOException("broken"); } + } + + /** Collects the tasks and schedules for the mod thread instead of running them. */ + private static final class FakeModThread implements ModThread + { + final List tasks = new ArrayList<>(); + final List schedules = new ArrayList<>(); + final List runs = new ArrayList<>(); + final List futures = new ArrayList<>(); + + @Override + public void execute(Runnable task) { this.tasks.add(task); } + + @Override + public CompletableFuture submit(Callable task) { throw new UnsupportedOperationException(); } + + @Override + public ScheduledFuture schedule(Runnable task, Duration delay) { throw new UnsupportedOperationException(); } + + @Override + public ScheduledFuture scheduleAtFixedRate(Runnable task, Duration initialDelay, Duration period) { return this.add("rate " + period + " after " + initialDelay, task); } + + @Override + public ScheduledFuture scheduleWithFixedDelay(Runnable task, Duration initialDelay, Duration delay) { return this.add("delay " + delay + " after " + initialDelay, task); } + + @Override + public boolean isModThread() { return false; } + + private ScheduledFuture add(String schedule, Runnable task) + { + FakeFuture future = new FakeFuture(); + + this.schedules.add(schedule); + this.runs.add(task); + this.futures.add(future); + + return future; + } + } + + private static final class FakeFuture extends CompletableFuture implements ScheduledFuture + { + @Override + public long getDelay(TimeUnit unit) { return 0; } + + @Override + public int compareTo(Delayed other) { return 0; } } /** Client command handlers of the module {@code Shop}. */ @@ -131,13 +231,11 @@ class EventBusTest 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<>(); - private final List modTasks = new ArrayList<>(); - - /** Collects the tasks for the mod thread instead of running them. */ - private final Executor modThread = this.modTasks::add; + private final EventBus bus = new EventBus(); + private final RecordingLogger logger = new RecordingLogger(); + private final List received = new ArrayList<>(); + private final FakeModThread modThread = new FakeModThread(); + private final List modTasks = this.modThread.tasks; @Test void deliversToMainListenersInOrderAndQueuesModThreadListeners() @@ -260,7 +358,8 @@ class EventBusTest 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", "mixed", "noModule", "notEvent", "returns", "two", "wrongEvent")) + for (String method : List.of("anAbstract", "anInterface", "both", "mainOnly", "mixed", "noModule", "notEvent", "returns", "two", "wrongEvent", + "zeroPeriod", "weeks", "negativeDelay", "withParameter", "tooLong", "zeroTicks", "twoSchedules")) EventBusTest.assertContainsAll(e.getMessage(), InvalidListeners.class.getName() + "." + method); EventBusTest.assertContainsAll(e.getMessage(), AbstractEvent.class.getName(), Event.class.getName(), TickEvent.class.getName(), "java.lang.String"); @@ -312,6 +411,66 @@ class EventBusTest EventBusTest.assertContainsAll(this.logger.messages.getFirst(), "'fail'", "ClientCommandEvent", "broken"); } + @Test + void startsEveryMethodsWhenTheModStartsAndLaterOnesAtOnce() + { + Events a = this.bus.forMod("a", this.modThread, this.logger); + Scheduled scheduled = new Scheduled(); + + a.register(scheduled); + assertTrue(this.modThread.schedules.isEmpty(), "nothing is scheduled before the mod started"); + + this.bus.start("a"); + assertEquals(List.of("rate PT1M after PT0S", "delay PT5S after PT2S"), this.modThread.schedules); + + this.modThread.runs.getFirst().run(); + assertEquals(List.of("report"), scheduled.log); + + a.register(new FailingSchedule()); + assertEquals(3, this.modThread.schedules.size(), "registered after the start: scheduled at once"); + } + + @Test + void everyNTicksMethodsRunOnEveryNthTick() + { + Scheduled scheduled = new Scheduled(); + this.bus.forMod("a", this.modThread, this.logger).register(scheduled); + + for (long tick = 1; tick <= 7; tick++) this.bus.post(new TickEvent(tick)); + + assertEquals(List.of("third", "third"), scheduled.log); + } + + @Test + void cancellingTheSubscriptionEndsSchedulesAndTickMethods() + { + Subscription started = this.bus.forMod("a", this.modThread, this.logger).register(new Scheduled()); + this.bus.start("a"); + + started.cancel(); + assertTrue(this.modThread.futures.stream().allMatch(Future::isCancelled)); + assertFalse(this.bus.hasListeners(TickEvent.class)); + + Subscription pending = this.bus.forMod("b", this.modThread, this.logger).register(new Scheduled()); + pending.cancel(); + this.bus.start("b"); + + assertEquals(2, this.modThread.schedules.size(), "a schedule cancelled before the start never starts"); + } + + @Test + void aThrowingScheduledMethodIsLoggedAndEndsItsSchedule() + { + this.bus.forMod("a", this.modThread, this.logger).register(new FailingSchedule()); + this.bus.start("a"); + + this.modThread.runs.getFirst().run(); + + assertTrue(this.modThread.futures.getFirst().isCancelled()); + assertEquals(1, this.logger.messages.size()); + EventBusTest.assertContainsAll(this.logger.messages.getFirst(), "'fail'", "java.io.IOException: broken"); + } + private static ClientCommandEvent command(String module, String command) { return new ClientCommandEvent(new PlayerRef(1, "bob"), module, command, Map.of()); } private static void assertContainsAll(String message, String... parts) diff --git a/core/src/test/java/testmods/ScheduleMod.java b/core/src/test/java/testmods/ScheduleMod.java new file mode 100644 index 0000000..a80ec24 --- /dev/null +++ b/core/src/test/java/testmods/ScheduleMod.java @@ -0,0 +1,39 @@ +package testmods; + +import dev.overlord.zomboidforge.api.Mod; +import dev.overlord.zomboidforge.api.annotations.Every; +import dev.overlord.zomboidforge.api.annotations.EveryNTicks; + +import java.time.temporal.ChronoUnit; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Entry point that tests package into a mod jar. Runs one method every 10 ms on its thread and + * one every second tick; its {@code onServerStarted()} throws. + */ +public final class ScheduleMod extends Mod +{ + public final List log = new CopyOnWriteArrayList<>(); + public final AtomicInteger runs = new AtomicInteger(); + + public volatile boolean ranBeforeStarted; + + @Override + public void onServerStarted() + { + this.log.add("started"); + throw new IllegalStateException("started"); + } + + @Every(value = 10, unit = ChronoUnit.MILLIS) + void every() + { + if (!this.log.contains("started")) this.ranBeforeStarted = true; + this.runs.incrementAndGet(); + } + + @EveryNTicks(2) + void second() { this.log.add("tick on " + Thread.currentThread().getName()); } +} From 9af951b4be7344cac84f2b5a633429d6dc799a62 Mon Sep 17 00:00:00 2001 From: Overlord Date: Wed, 7 Oct 2026 23:02:14 +0200 Subject: [PATCH 7/9] Add support for `@RegisterCommand`, `@Key`, `@Min`, and `@Max` annotations for command registration, custom keys, and configuration bounds. --- MOD_DEVELOPMENT.md | 30 +++- .../overlord/zomboidforge/api/Commands.java | 5 +- .../overlord/zomboidforge/api/ModConfig.java | 15 +- .../zomboidforge/api/annotations/Key.java | 32 ++++ .../zomboidforge/api/annotations/Max.java | 21 +++ .../zomboidforge/api/annotations/Min.java | 28 ++++ .../api/annotations/RegisterCommand.java | 28 ++++ .../dev/overlord/zomboidforge/core/Forge.java | 5 +- .../core/config/RecordBinder.java | 139 ++++++++++++++++-- .../zomboidforge/core/mods/ModLoader.java | 27 +++- .../zomboidforge/core/mods/ModVerifier.java | 58 +++++++- .../core/storage/RecordCodec.java | 9 +- .../overlord/zomboidforge/core/ForgeTest.java | 42 ++++++ .../core/config/TomlModConfigTest.java | 111 ++++++++++++++ .../core/mods/ModVerifierTest.java | 16 ++ .../core/storage/ModTablesTest.java | 21 +++ .../java/testmods/AnnotatedCommandMod.java | 23 +++ 17 files changed, 577 insertions(+), 33 deletions(-) create mode 100644 api/src/main/java/dev/overlord/zomboidforge/api/annotations/Key.java create mode 100644 api/src/main/java/dev/overlord/zomboidforge/api/annotations/Max.java create mode 100644 api/src/main/java/dev/overlord/zomboidforge/api/annotations/Min.java create mode 100644 api/src/main/java/dev/overlord/zomboidforge/api/annotations/RegisterCommand.java create mode 100644 core/src/test/java/testmods/AnnotatedCommandMod.java diff --git a/MOD_DEVELOPMENT.md b/MOD_DEVELOPMENT.md index d969f4c..8e4e854 100644 --- a/MOD_DEVELOPMENT.md +++ b/MOD_DEVELOPMENT.md @@ -186,6 +186,25 @@ Methods of `Mod`, usable from the constructor on, and in field initializers: | `commands()` | `Commands` | admin commands for chat, the server console, and RCON | | `clientCommands()` | `ClientCommands` | server commands to clients, received by their Lua mods | +## Settings + +`config().bind(Settings.class)` reads `config.toml` into a record. Keys are the component names +in `snake_case` (`maxBalance` reads `max_balance`); defaults come from the jar's +`META-INF/zomboidforge/config.toml`. + +```java +record Settings( + @Key("max_hp_regen") int healthRegenPerHour, // keeps its key after a rename + @Min(1) @Max(100) int maxPlayers, // bounds for numbers, also inside List, Map, Optional + String greeting +) {} +``` + +A missing, mistyped, or out-of-bounds value stops the server, and the log lists every problem +with its key (`'max_players' must be at most 100, found 250.`). `@Key` names are `snake_case` +and differ within a record; `@Min`/`@Max` only fit numeric components and may be fractions +(`@Max(0.5) double ratio`). + ## Threads Game objects belong to the server's main thread. Everything else should stay off it, because @@ -289,9 +308,14 @@ public class HelloCommand extends CommandBase public void onLoad() { this.commands().register(HelloCommand.class); } ``` +Or `@RegisterCommand` on the class (`dev.overlord.zomboidforge.api.annotations`), without the +call: ZomboidForge registers the annotated classes of the mod's own jar (not of `lib/`) by name, +before `onLoad()`. + - **Registration** happens in the entry point's constructor or `onLoad()`; later calls throw. `register` checks the class and throws `IllegalArgumentException` listing every problem, - which stops the server like any other exception in `onLoad()`. + which stops the server like any other exception in `onLoad()`; an annotated class that breaks + the rules stops it the same way. - **The class** is public and not abstract, with one public constructor `(String, Role, String, UdpConnection)`. - **Names** (`@CommandName`, repeatable for aliases) consist of letters, digits, and `_` and @@ -400,7 +424,9 @@ this.storage().transaction(() -> { // all or nothin | `Instant` | ISO-8601 text | | `byte[]` | blob | -Table and column names are `snake_case`: `lastPaid` is stored as `last_paid`. +Table and column names are `snake_case`: `lastPaid` is stored as `last_paid`. `@Key("paid_at")` +on a component sets the column name instead, so a renamed component keeps its column and data. +`@Min`/`@Max` are for settings; storage ignores them. When the record changes between versions of the mod: diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/Commands.java b/api/src/main/java/dev/overlord/zomboidforge/api/Commands.java index 2ef17a8..85123eb 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/Commands.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/Commands.java @@ -1,5 +1,7 @@ package dev.overlord.zomboidforge.api; +import dev.overlord.zomboidforge.api.annotations.RegisterCommand; + import org.jetbrains.annotations.ApiStatus; /** @@ -28,7 +30,8 @@ public interface Commands { /** * Registers {@code command}. Only on the main thread while the mod loads: in the entry point's - * constructor or {@link Mod#onLoad()}. + * constructor or {@link Mod#onLoad()}. Classes annotated with {@link RegisterCommand} are + * registered without this call. * * @throws IllegalArgumentException when {@code command} does not meet the rules above, or is * registered already diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/ModConfig.java b/api/src/main/java/dev/overlord/zomboidforge/api/ModConfig.java index 0cfdf88..42c6f19 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/ModConfig.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/ModConfig.java @@ -1,5 +1,9 @@ package dev.overlord.zomboidforge.api; +import dev.overlord.zomboidforge.api.annotations.Key; +import dev.overlord.zomboidforge.api.annotations.Max; +import dev.overlord.zomboidforge.api.annotations.Min; + import org.jetbrains.annotations.ApiStatus; import java.util.Optional; @@ -10,7 +14,8 @@ import java.util.Optional; * default. The table {@code [forge]} belongs to ZomboidForge and is not part of these settings. * *

        Keys are {@code snake_case}; record components and paths use the same names converted - * from {@code camelCase} ({@code maxBalance} reads {@code max_balance}). + * from {@code camelCase} ({@code maxBalance} reads {@code max_balance}), or the name of the + * component's {@link Key}. */ @ApiStatus.NonExtendable public interface ModConfig @@ -21,9 +26,13 @@ public interface ModConfig * wrappers), enums (by constant name), records (TOML tables), {@code List}, * {@code Map} (tables with free keys), and {@code Optional} for values that * may be missing. Every other component must have a value. Keys without a component are - * logged as warnings. + * logged as warnings. {@link Min} and {@link Max} bound numeric components. * - * @throws IllegalStateException listing every missing or mistyped value + * @throws IllegalStateException listing every missing, mistyped, or out-of-bounds value + * @throws IllegalArgumentException when {@code type} has a component that configuration + * values cannot have, an invalid or repeated {@link Key}, + * or {@link Min}/{@link Max} on a component that is not + * numeric or with the minimum above the maximum */ T bind(Class type); diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Key.java b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Key.java new file mode 100644 index 0000000..c5b8b3d --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Key.java @@ -0,0 +1,32 @@ +package dev.overlord.zomboidforge.api.annotations; + +import dev.overlord.zomboidforge.api.ModConfig; +import dev.overlord.zomboidforge.api.storage.ModStorage; + +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; + +/** + * The key of a record component, instead of the one converted from its name ({@code maxBalance} + * to {@code max_balance}): the {@code config.toml} key for {@link ModConfig#bind}, the column + * name for {@link ModStorage} tables. A component keeps its key when it is renamed: + * + *

        {@code
        + * record Settings(@Key("max_hp_regen") int healthRegenPerHour) {}
        + * }
        + * + * The key is {@code snake_case}: lowercase letters, digits, and single underscores, starting with + * a letter. Two components of a record cannot have the same key. For a storage record, giving an + * existing component another key renames its column, which the table treats as a removed and a + * new column, as when the component is renamed without {@code @Key}. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.RECORD_COMPONENT) +public @interface Key +{ + String value(); +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Max.java b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Max.java new file mode 100644 index 0000000..c1b1835 --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Max.java @@ -0,0 +1,21 @@ +package dev.overlord.zomboidforge.api.annotations; + +import dev.overlord.zomboidforge.api.ModConfig; + +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; + +/** + * The largest value a numeric component of a configuration record accepts; see {@link Min}. + * {@link ModConfig#bind} reports a larger value in {@code config.toml} with its key. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.RECORD_COMPONENT) +public @interface Max +{ + double value(); +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Min.java b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Min.java new file mode 100644 index 0000000..2e228ac --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Min.java @@ -0,0 +1,28 @@ +package dev.overlord.zomboidforge.api.annotations; + +import dev.overlord.zomboidforge.api.ModConfig; + +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; + +/** + * The smallest value a numeric component of a configuration record accepts. {@link ModConfig#bind} + * reports a smaller value in {@code config.toml} with its key, together with every other + * problem. On a {@code List}, {@code Map}, or {@code Optional} component, it applies to each + * value. The bound may be a fraction ({@code @Min(0.1)}); it is not {@code NaN}. Values are + * compared as {@code double}. Storage records ignore it. + * + *
        {@code
        + * record Settings(@Min(1) @Max(100) int maxPlayers) {}
        + * }
        + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.RECORD_COMPONENT) +public @interface Min +{ + double value(); +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/annotations/RegisterCommand.java b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/RegisterCommand.java new file mode 100644 index 0000000..8dc9d30 --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/RegisterCommand.java @@ -0,0 +1,28 @@ +package dev.overlord.zomboidforge.api.annotations; + +import dev.overlord.zomboidforge.api.Commands; +import dev.overlord.zomboidforge.api.Mod; + +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 class as an admin command, as {@link Commands#register} does, while the mod + * loads: after the entry point's listener methods and before {@link Mod#onLoad()}. Only classes + * in the mod's own jar are found, not those of its libraries; several are registered in the + * order of their names. The class follows the rules of {@link Commands}. + * + *
        {@code
        + * @RegisterCommand
        + * @CommandName(name = "zfhello")
        + * @RequiredCapability(requiredCapability = Capability.LoginOnServer)
        + * public class HelloCommand extends CommandBase { ... }
        + * }
        + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface RegisterCommand {} diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java b/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java index c8b26c7..d44e6a0 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java @@ -33,6 +33,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @@ -152,11 +153,11 @@ public final class Forge try (GameClasses gameClasses = GameClasses.open(gameJar)) { - ModVerifier.verify(ordered, gameClasses, game); + Map> annotatedCommands = ModVerifier.verify(ordered, gameClasses, game); for (ModDiscovery.Candidate candidate : ordered) ModTables.adoptPreviousIds(storage, candidate.id(), candidate.descriptor().previousIds(), installed); - this.mods = ModLoader.load(ordered, game, parent, gameClasses, this::services); + this.mods = ModLoader.load(ordered, game, parent, gameClasses, this::services, annotatedCommands); } catch (IOException e) { diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/config/RecordBinder.java b/core/src/main/java/dev/overlord/zomboidforge/core/config/RecordBinder.java index 46677c4..25657e8 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/config/RecordBinder.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/config/RecordBinder.java @@ -1,5 +1,9 @@ package dev.overlord.zomboidforge.core.config; +import dev.overlord.zomboidforge.api.annotations.Key; +import dev.overlord.zomboidforge.api.annotations.Max; +import dev.overlord.zomboidforge.api.annotations.Min; + import org.jetbrains.annotations.Nullable; import java.lang.reflect.Constructor; @@ -16,14 +20,26 @@ import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeSet; +import java.util.regex.Pattern; import java.util.stream.Collectors; /** * Converts {@link TomlTree} values to records and other Java types. Collects every problem - * instead of stopping at the first one, and records the keys no component reads. + * instead of stopping at the first one, and records the keys no component reads. Record + * components are read by their {@link Key} or converted name, and checked against their + * {@link Min} and {@link Max}. */ public final class RecordBinder { + /** Bounds of a numeric component from {@link Min} and {@link Max}; {@code null} when absent. */ + private record Bounds(@Nullable Double min, @Nullable Double max) + { + static final Bounds NONE = new Bounds(null, null); + } + + private static final Pattern KEY = Pattern.compile("[a-z][a-z0-9]*(_[a-z0-9]+)*"); + private static final Set> NUMBERS = Set.of(long.class, Long.class, int.class, Integer.class, double.class, Double.class, float.class, Float.class); + private final List problems = new ArrayList<>(); private final Set unknownKeys = new TreeSet<>(); @@ -51,20 +67,49 @@ public final class RecordBinder return key.toString(); } + /** + * The keys of the components of {@code type}, in component order: each component's + * {@link Key}, or its name converted by {@link #key(String)}. + * + * @throws IllegalArgumentException when a {@link Key} is not {@code snake_case}, or two + * components have the same key + */ + public static List keys(Class type) + { + List keys = new ArrayList<>(); + + for (RecordComponent component : type.getRecordComponents()) + { + Key annotation = component.getAnnotation(Key.class); + String key = annotation == null ? RecordBinder.key(component.getName()) : annotation.value(); + + if (annotation != null && !RecordBinder.KEY.matcher(key).matches()) + throw new IllegalArgumentException("'" + type.getName() + "." + component.getName() + "' has @Key(\"" + key + "\"); keys are lowercase letters, digits, and single underscores, starting with a letter."); + + if (keys.contains(key)) + throw new IllegalArgumentException("'" + type.getName() + "' has two components with the key '" + key + "'."); + + keys.add(key); + } + + return keys; + } + /** A record of {@code type} from {@code table}, or {@code null} when a problem was found. */ public @Nullable T record(Map table, Class type, String path) { RecordComponent[] components = type.getRecordComponents(); + List names = RecordBinder.keys(type); @Nullable Object[] arguments = new Object[components.length]; Set keys = new TreeSet<>(table.keySet()); int before = this.problems.size(); for (int i = 0; i < components.length; i++) { - String key = RecordBinder.key(components[i].getName()); + String key = names.get(i); keys.remove(key); - arguments[i] = this.value(table.get(key), components[i].getGenericType(), RecordBinder.join(path, key)); + arguments[i] = this.value(table.get(key), components[i].getGenericType(), RecordBinder.join(path, key), RecordBinder.bounds(components[i])); } for (String key : keys) this.unknownKeys.add(RecordBinder.join(path, key)); @@ -94,7 +139,10 @@ public final class RecordBinder * {@code raw} converted to {@code target}, or {@code null} after recording a problem. * {@code raw == null} means the key is missing. */ - public @Nullable Object value(@Nullable Object raw, Type target, String path) + public @Nullable Object value(@Nullable Object raw, Type target, String path) { return this.value(raw, target, path, Bounds.NONE); } + + /** Like {@link #value(Object, Type, String)}; numbers, also inside an {@code Optional}, {@code List}, or {@code Map}, are checked against {@code bounds}. */ + private @Nullable Object value(@Nullable Object raw, Type target, String path, Bounds bounds) { Class type = RecordBinder.rawType(target); @@ -102,7 +150,7 @@ public final class RecordBinder { if (raw == null) return Optional.empty(); - Object element = this.value(raw, RecordBinder.typeArgument(target, 0), path); + Object element = this.value(raw, RecordBinder.typeArgument(target, 0), path, bounds); return element == null ? null : Optional.of(element); } @@ -110,14 +158,14 @@ public final class RecordBinder if (type == String.class) return raw instanceof String ? raw : this.mistyped(path, "a string", raw); if (type == boolean.class || type == Boolean.class) return raw instanceof Boolean ? raw : this.mistyped(path, "true or false", raw); - if (type == long.class || type == Long.class) return raw instanceof Long ? raw : this.mistyped(path, "an integer", raw); - if (type == int.class || type == Integer.class) return this.integer(raw, path); - if (type == double.class || type == Double.class) return raw instanceof Long || raw instanceof Double ? ((Number) raw).doubleValue() : this.mistyped(path, "a number", raw); - if (type == float.class || type == Float.class) return raw instanceof Long || raw instanceof Double ? ((Number) raw).floatValue() : this.mistyped(path, "a number", raw); + if (type == long.class || type == Long.class) return this.bounded(raw instanceof Long ? raw : this.mistyped(path, "an integer", raw), path, bounds); + if (type == int.class || type == Integer.class) return this.bounded(this.integer(raw, path), path, bounds); + if (type == double.class || type == Double.class) return this.bounded(raw instanceof Long || raw instanceof Double ? ((Number) raw).doubleValue() : this.mistyped(path, "a number", raw), path, bounds); + if (type == float.class || type == Float.class) return this.bounded(raw instanceof Long || raw instanceof Double ? ((Number) raw).floatValue() : this.mistyped(path, "a number", raw), path, bounds); if (type.isEnum()) return this.constant(raw, type, path); if (type.isRecord()) return raw instanceof Map table ? this.record(TomlTree.cast(table), type.asSubclass(Record.class), path) : this.mistyped(path, "a table", raw); - if (type == List.class) return this.list(raw, RecordBinder.typeArgument(target, 0), path); - if (type == Map.class) return this.map(raw, target, path); + if (type == List.class) return this.list(raw, RecordBinder.typeArgument(target, 0), path, bounds); + if (type == Map.class) return this.map(raw, target, path, bounds); throw new IllegalArgumentException("'" + path + "' has the type '" + target.getTypeName() + "', which configuration values cannot have."); } @@ -144,7 +192,23 @@ public final class RecordBinder return this.mistyped(path, "one of " + allowed, raw); } - private @Nullable Object list(Object raw, Type element, String path) + /** {@code value} when it is within {@code bounds}; {@code null} after recording a problem, or when {@code value} is {@code null} already. */ + private @Nullable Object bounded(@Nullable Object value, String path, Bounds bounds) + { + if (value == null || bounds == Bounds.NONE) return value; + + // Integers above 2^53 lose precision as doubles; configuration values do not get there. + double number = ((Number) value).doubleValue(); + Double min = bounds.min(); + Double max = bounds.max(); + + if (min != null && number < min) return this.problem(path, "must be at least " + RecordBinder.bound(min) + ", found " + value); + if (max != null && number > max) return this.problem(path, "must be at most " + RecordBinder.bound(max) + ", found " + value); + + return value; + } + + private @Nullable Object list(Object raw, Type element, String path, Bounds bounds) { if (!(raw instanceof List list)) return this.mistyped(path, "a list", raw); @@ -153,14 +217,14 @@ public final class RecordBinder for (int i = 0; i < list.size(); i++) { - Object value = this.value(list.get(i), element, path + "[" + i + "]"); + Object value = this.value(list.get(i), element, path + "[" + i + "]", bounds); if (value != null) values.add(value); } return this.problems.size() > before ? null : List.copyOf(values); } - private @Nullable Object map(Object raw, Type target, String path) + private @Nullable Object map(Object raw, Type target, String path, Bounds bounds) { if (RecordBinder.typeArgument(target, 0) != String.class) throw new IllegalArgumentException("'" + path + "' has the type '" + target.getTypeName() + "'; configuration maps need String keys."); @@ -172,7 +236,7 @@ public final class RecordBinder for (Map.Entry entry : TomlTree.cast(table).entrySet()) { - Object value = this.value(entry.getValue(), RecordBinder.typeArgument(target, 1), RecordBinder.join(path, entry.getKey())); + Object value = this.value(entry.getValue(), RecordBinder.typeArgument(target, 1), RecordBinder.join(path, entry.getKey()), bounds); if (value != null) values.put(entry.getKey(), value); } @@ -191,6 +255,44 @@ public final class RecordBinder return null; } + /** + * The bounds of {@code component} from its {@link Min} and {@link Max}. + * + * @throws IllegalArgumentException when the component's values are not numbers, a bound is + * {@code NaN}, or the minimum is above the maximum + */ + private static Bounds bounds(RecordComponent component) + { + Min min = component.getAnnotation(Min.class); + Max max = component.getAnnotation(Max.class); + + if (min == null && max == null) return Bounds.NONE; + + String where = "'" + component.getDeclaringRecord().getName() + "." + component.getName() + "'"; + + if (!RecordBinder.isNumeric(component.getGenericType())) + throw new IllegalArgumentException(where + " has @Min or @Max, but its values are not numbers."); + + if ((min != null && Double.isNaN(min.value())) || (max != null && Double.isNaN(max.value()))) + throw new IllegalArgumentException(where + " has a @Min or @Max that is not a number."); + + if (min != null && max != null && min.value() > max.value()) + throw new IllegalArgumentException(where + " has @Min(" + RecordBinder.bound(min.value()) + ") above @Max(" + RecordBinder.bound(max.value()) + ")."); + + return new Bounds(min == null ? null : min.value(), max == null ? null : max.value()); + } + + /** Whether values of {@code type} are numbers, also as the values of an {@code Optional}, {@code List}, or {@code Map}. */ + private static boolean isNumeric(Type type) + { + Class raw = RecordBinder.rawType(type); + + if (raw == Optional.class || raw == List.class) return RecordBinder.isNumeric(RecordBinder.typeArgument(type, 0)); + if (raw == Map.class) return RecordBinder.isNumeric(RecordBinder.typeArgument(type, 1)); + + return RecordBinder.NUMBERS.contains(raw); + } + private static Class rawType(Type type) { return switch (type) @@ -208,5 +310,12 @@ public final class RecordBinder throw new IllegalArgumentException("'" + type.getTypeName() + "' needs type arguments in configuration records."); } + /** + * {@code value} for messages: whole numbers without a decimal point ({@code 100}), others as + * they are ({@code 0.5}). Beyond 10^15 the {@code double} form stays, as a {@code long} would + * not hold every such value. + */ + private static String bound(double value) { return value == Math.rint(value) && Math.abs(value) < 1e15 ? String.valueOf((long) value) : String.valueOf(value); } + private static String join(String path, String key) { return path.isEmpty() ? key : path + "." + key; } } 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 c28719b..40fa209 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 @@ -30,7 +30,8 @@ import java.util.Objects; /** * 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. + * point's listener methods and the mod's {@code @RegisterCommand} classes, and calls + * {@link Mod#onLoad()}. Stops at the first mod that fails. */ public final class ModLoader { @@ -62,9 +63,11 @@ public final class ModLoader * @param gameClasses classes of the Project Zomboid jar, visible to mods that declare * {@code game} versions * @param services creates each mod's threads and event registration + * @param commands mod id to its classes annotated with {@code @RegisterCommand}, as + * returned by {@link ModVerifier#verify} * @throws ModLoadException naming the mod that failed and why */ - public static List load(List ordered, GameVersion game, ClassLoader parent, GameClasses gameClasses, ModServices.Factory services) throws ModLoadException + public static List load(List ordered, GameVersion game, ClassLoader parent, GameClasses gameClasses, ModServices.Factory services, Map> commands) throws ModLoadException { Map loaders = new HashMap<>(); List loaded = new ArrayList<>(); @@ -102,7 +105,7 @@ public final class ModLoader provided.clientCommands() ); - loaded.add(new LoadedMod(descriptor, candidate.directory(), loader, ModLoader.create(descriptor, loader, context))); + loaded.add(new LoadedMod(descriptor, candidate.directory(), loader, ModLoader.create(descriptor, loader, context, commands.getOrDefault(descriptor.id(), List.of())))); } return List.copyOf(loaded); @@ -114,7 +117,8 @@ public final class ModLoader } } - private static Mod create(ModDescriptor descriptor, ClassLoader loader, ModContext context) throws ModLoadException + /** @param commands binary names of the mod's classes annotated with {@code @RegisterCommand} */ + private static Mod create(ModDescriptor descriptor, ClassLoader loader, ModContext context, List commands) throws ModLoadException { String id = descriptor.id(); @@ -139,6 +143,8 @@ public final class ModLoader try { context.events().register(mod); } catch (IllegalArgumentException e) { throw new ModLoadException("'" + id + "': " + e.getMessage(), e); } + for (String command : commands) ModLoader.registerCommand(descriptor, loader, context, command); + 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); } @@ -146,6 +152,19 @@ public final class ModLoader return mod; } + /** Registers the class {@code command}, annotated with {@code @RegisterCommand}. */ + private static void registerCommand(ModDescriptor descriptor, ClassLoader loader, ModContext context, String command) throws ModLoadException + { + String id = descriptor.id(); + Class type; + + try { type = Class.forName(command, false, loader); } + catch (ClassNotFoundException | LinkageError e) { throw new ModLoadException(ModLoader.sentence("'" + id + "': the command '" + command + "' cannot be loaded: " + e), e); } + + try { context.commands().register(type); } + catch (IllegalArgumentException e) { throw new ModLoadException("'" + id + "': " + e.getMessage(), e); } + } + private static Constructor constructor(ModDescriptor descriptor, ClassLoader loader) throws ModLoadException { String id = descriptor.id(); diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModVerifier.java b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModVerifier.java index 84f1c63..d3c3a40 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModVerifier.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModVerifier.java @@ -4,6 +4,7 @@ import dev.overlord.zomboidforge.api.GameVersion; import org.jetbrains.annotations.Nullable; +import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.FieldVisitor; @@ -20,6 +21,7 @@ import java.io.UncheckedIOException; import java.nio.file.Path; import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.Collection; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; @@ -45,6 +47,8 @@ import java.util.stream.Collectors; * * * Annotations are not checked: the JVM does not load annotation types a class only carries. + * The classes of a mod's own jar annotated with {@code @RegisterCommand} are collected for the + * loader. */ public final class ModVerifier { @@ -53,6 +57,8 @@ public final class ModVerifier private static final String API_INTERNAL = "dev/overlord/zomboidforge/api/internal/"; private static final int EXAMPLES = 5; + private static final String REGISTER_COMMAND = "Ldev/overlord/zomboidforge/api/annotations/RegisterCommand;"; + /** A field or method that a mod's code uses. */ private record Member(boolean method, String owner, String name, String desc) implements Comparable { @@ -68,13 +74,16 @@ public final class ModVerifier /** * @param ordered mods in load order, as returned by {@link ModResolver#resolve} * @param version the version of {@code game}, for messages; {@code null} with {@link GameClasses#none()} + * @return mod id to the binary names of the classes in its own jar annotated with + * {@code @RegisterCommand}, sorted * @throws ModLoadException listing every problem of every mod */ - public static void verify(List ordered, GameClasses game, @Nullable GameVersion version) throws ModLoadException + public static Map> verify(List ordered, GameClasses game, @Nullable GameVersion version) throws ModLoadException { - Hierarchy hierarchy = new Hierarchy(game); - Map> ownByMod = new HashMap<>(); - List problems = new ArrayList<>(); + Hierarchy hierarchy = new Hierarchy(game); + Map> ownByMod = new HashMap<>(); + Map> commands = new HashMap<>(); + List problems = new ArrayList<>(); for (ModDiscovery.Candidate candidate : ordered) { @@ -85,6 +94,7 @@ public final class ModVerifier for (Path library : candidate.libraries()) libraries.putAll(ModVerifier.classes(library)); ownByMod.put(id, own.keySet()); + commands.put(id, ModVerifier.registeredCommands(own.values())); Set provided = new HashSet<>(own.keySet()); provided.addAll(libraries.keySet()); @@ -144,6 +154,25 @@ public final class ModVerifier } if (!problems.isEmpty()) throw new ModLoadException(problems); + + return Map.copyOf(commands); + } + + /** Binary names of the classes annotated with {@code @RegisterCommand}, sorted. */ + private static List registeredCommands(Collection classes) + { + List names = new ArrayList<>(); + + for (byte[] bytes : classes) + { + CommandAnnotation annotation = new CommandAnnotation(); + new ClassReader(bytes).accept(annotation, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); + + if (annotation.name != null) names.add(ModVerifier.dotted(annotation.name)); + } + + names.sort(null); + return List.copyOf(names); } /** Internal class name to class file, for every class in {@code jar} outside {@code META-INF/}. */ @@ -178,6 +207,27 @@ public final class ModVerifier private static String dotted(String internalName) { return internalName.replace('/', '.'); } + /** Reads whether a class carries {@code @RegisterCommand}. */ + private static final class CommandAnnotation extends ClassVisitor + { + /** The internal name of the class when it carries the annotation. */ + private @Nullable String name; + + private @Nullable String visited; + + private CommandAnnotation() { super(Opcodes.ASM9); } + + @Override + public void visit(int version, int access, String name, @Nullable String signature, @Nullable String superName, String @Nullable [] interfaces) { this.visited = name; } + + @Override + public @Nullable AnnotationVisitor visitAnnotation(String descriptor, boolean visible) + { + if (ModVerifier.REGISTER_COMMAND.equals(descriptor)) this.name = this.visited; + return null; + } + } + /** Collects the classes and members that code uses; skips annotations and debug information. */ private static final class References extends ClassVisitor { diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordCodec.java b/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordCodec.java index 1902866..d80b4e5 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordCodec.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordCodec.java @@ -21,7 +21,8 @@ import java.util.regex.Pattern; /** * Converts records of one type to table rows and back. Components become columns named in - * {@code snake_case}; accessors and the canonical constructor are resolved once. + * {@code snake_case}, or by their {@code @Key}; accessors and the canonical constructor are + * resolved once. {@code @Min} and {@code @Max} are for configuration records and ignored here. * *

        Stored forms: integers and booleans as {@code INTEGER}, other numbers as {@code REAL}, * texts, UUIDs, instants (ISO-8601), and enum constants (by name) as {@code TEXT}, bytes as @@ -51,10 +52,14 @@ final class RecordCodec static RecordCodec of(Class type) { RecordComponent[] components = type.getRecordComponents(); + List names; List columns = new ArrayList<>(); Class[] types = new Class[components.length]; MethodHandle[] accessors = new MethodHandle[components.length]; + try { names = RecordBinder.keys(type); } + catch (IllegalArgumentException e) { throw new StorageException(e.getMessage(), e); } + try { MethodHandles.Lookup lookup = MethodHandles.privateLookupIn(type, MethodHandles.lookup()); @@ -62,7 +67,7 @@ final class RecordCodec for (int i = 0; i < components.length; i++) { RecordComponent component = components[i]; - String name = RecordBinder.key(component.getName()); + String name = names.get(i); String where = "'" + type.getSimpleName() + "." + component.getName() + "'"; if (!RecordCodec.NAME.matcher(name).matches()) throw new StorageException(where + " gives the column name '" + name + "'; column names are lowercase letters, digits, and single underscores."); 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 f917e1b..5b60495 100644 --- a/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java +++ b/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java @@ -11,6 +11,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import testmods.AnnotatedCommandMod; import testmods.CommandMod; import testmods.ContextMod; import testmods.ErrorMod; @@ -403,6 +404,47 @@ class ForgeTest forge.stopping(); } + /** {@link AnnotatedCommandMod} and its command classes, packaged as the mod {@code commands}. */ + private void annotatedCommandMod() throws IOException + { + TestMods.folder(this.mods, "commands", TestMods.toml("commands", AnnotatedCommandMod.class.getName(), ""), Map.of( + "testmods/AnnotatedCommandMod", TestMods.classFile(AnnotatedCommandMod.class), + "testmods/AnnotatedCommandMod$Hello", TestMods.classFile(AnnotatedCommandMod.Hello.class), + "testmods/AnnotatedCommandMod$Bye", TestMods.classFile(AnnotatedCommandMod.Bye.class), + "testmods/AnnotatedCommandMod$Manual", TestMods.classFile(AnnotatedCommandMod.Manual.class) + )); + } + + @Test + void registersAnnotatedCommandsByNameBeforeOnLoad() throws Exception + { + this.annotatedCommandMod(); + + Forge forge = this.load(); + String mod = AnnotatedCommandMod.class.getName(); + + assertEquals(List.of(mod + "$Bye after 0", mod + "$Hello after 1", mod + "$Manual after 2"), this.checkedCommands); + assertEquals(3, forge.commands().size()); + } + + @Test + void failsWhenAnAnnotatedCommandBreaksTheRules() throws IOException + { + this.annotatedCommandMod(); + + Forge forge = new Forge( + this.directory, + ModVersion.parse("0.3.0"), + (command, registered) -> { throw new IllegalArgumentException("'" + command.getName() + "' has no @CommandName."); }, + (player, module, command, args) -> () -> {} + ); + + ModLoadException e = assertThrows(ModLoadException.class, () -> forge.load(ForgeTest.GAME, this.gameJar, ForgeTest.class.getClassLoader(), this.storageFile)); + + assertEquals(1, e.problems().size()); + ForgeTest.assertContainsAll(e.problems().getFirst(), "'commands'", "AnnotatedCommandMod$Bye"); + } + 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/dev/overlord/zomboidforge/core/config/TomlModConfigTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/config/TomlModConfigTest.java index 24787dd..c5319aa 100644 --- a/core/src/test/java/dev/overlord/zomboidforge/core/config/TomlModConfigTest.java +++ b/core/src/test/java/dev/overlord/zomboidforge/core/config/TomlModConfigTest.java @@ -1,5 +1,8 @@ package dev.overlord.zomboidforge.core.config; +import dev.overlord.zomboidforge.api.annotations.Key; +import dev.overlord.zomboidforge.api.annotations.Max; +import dev.overlord.zomboidforge.api.annotations.Min; import dev.overlord.zomboidforge.core.ConsoleLogger; import org.junit.jupiter.api.Test; @@ -9,7 +12,9 @@ import java.util.Map; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; class TomlModConfigTest { @@ -30,6 +35,28 @@ class TomlModConfigTest Optional httpPort ) {} + private record Renamed(@Key("max_hp_regen") int healthRegenPerHour, String name) {} + + private record InvalidKey(@Key("Max HP") int maxHp) {} + + private record RepeatedKey(@Key("value") int amount, int value) {} + + private record Bounded( + @Min(1) @Max(100) int maxPlayers, + @Min(0) double ratio, + @Max(10) List levels, + @Min(1) Optional port, + @Min(1) Map prices + ) {} + + private record FractionalBounds(@Min(0.1) @Max(0.5) double ratio) {} + + private record BoundedText(@Min(1) String name) {} + + private record NotANumberBound(@Min(Double.NaN) double ratio) {} + + private record InvertedBounds(@Min(5) @Max(1) int amount) {} + private static TomlModConfig config(String defaults, String settings) { return new TomlModConfig(TomlTree.merge(TomlTree.parse(defaults), TomlTree.parse(settings)), new ConsoleLogger("test")); @@ -133,4 +160,88 @@ class TomlModConfigTest assertEquals(Map.of("a", 1L, "b", 2.5, "t", Map.of("x", 1L, "y", 3L)), merged); } + + @Test + void readsComponentsByTheirKeyAnnotation() + { + Renamed renamed = TomlModConfigTest.config("max_hp_regen = 5\nname = \"a\"\n", "").bind(Renamed.class); + + assertEquals(new Renamed(5, "a"), renamed); + } + + @Test + void rejectsInvalidAndRepeatedKeys() + { + TomlModConfig config = TomlModConfigTest.config("value = 1\n", ""); + + IllegalArgumentException invalid = assertThrows(IllegalArgumentException.class, () -> config.bind(InvalidKey.class)); + IllegalArgumentException repeated = assertThrows(IllegalArgumentException.class, () -> config.bind(RepeatedKey.class)); + + TomlModConfigTest.assertContainsAll(invalid.getMessage(), InvalidKey.class.getName() + ".maxHp", "Max HP"); + TomlModConfigTest.assertContainsAll(repeated.getMessage(), RepeatedKey.class.getName(), "'value'"); + } + + @Test + void reportsValuesOutsideTheirBoundsWithEveryOtherProblem() + { + String valid = """ + max_players = 100 + ratio = 0.0 + levels = [10] + port = 1 + + [prices] + apple = 1 + """; + + assertEquals(new Bounded(100, 0.0, List.of(10L), Optional.of(1), Map.of("apple", 1L)), TomlModConfigTest.config(valid, "").bind(Bounded.class)); + + TomlModConfig invalid = TomlModConfigTest.config(""" + max_players = 250 + ratio = -0.5 + levels = [1, 11] + port = 0 + + [prices] + apple = 0 + """, ""); + + IllegalStateException e = assertThrows(IllegalStateException.class, () -> invalid.bind(Bounded.class)); + + TomlModConfigTest.assertContainsAll(e.getMessage(), "'max_players'", "100", "250", "'ratio'", "-0.5", "'levels[1]'", "11", "'port'", "'prices.apple'"); + assertFalse(e.getMessage().contains("100.0"), "whole bounds without a decimal point: " + e.getMessage()); + assertFalse(e.getMessage().contains("levels[0]"), e.getMessage()); + } + + @Test + void rejectsBoundsOnNonNumbersAndInvertedBounds() + { + TomlModConfig config = TomlModConfigTest.config("name = \"a\"\namount = 3\n", ""); + + IllegalArgumentException text = assertThrows(IllegalArgumentException.class, () -> config.bind(BoundedText.class)); + IllegalArgumentException inverted = assertThrows(IllegalArgumentException.class, () -> config.bind(InvertedBounds.class)); + + TomlModConfigTest.assertContainsAll(text.getMessage(), BoundedText.class.getName() + ".name"); + TomlModConfigTest.assertContainsAll(inverted.getMessage(), InvertedBounds.class.getName() + ".amount", "5", "1"); + + IllegalArgumentException notANumber = assertThrows(IllegalArgumentException.class, () -> TomlModConfigTest.config("ratio = 0.5\n", "").bind(NotANumberBound.class)); + TomlModConfigTest.assertContainsAll(notANumber.getMessage(), NotANumberBound.class.getName() + ".ratio"); + } + + @Test + void acceptsFractionalBounds() + { + assertEquals(new FractionalBounds(0.5), TomlModConfigTest.config("ratio = 0.5\n", "").bind(FractionalBounds.class)); + + IllegalStateException above = assertThrows(IllegalStateException.class, () -> TomlModConfigTest.config("ratio = 0.75\n", "").bind(FractionalBounds.class)); + IllegalStateException below = assertThrows(IllegalStateException.class, () -> TomlModConfigTest.config("ratio = 0.05\n", "").bind(FractionalBounds.class)); + + TomlModConfigTest.assertContainsAll(above.getMessage(), "'ratio'", "0.5", "0.75"); + TomlModConfigTest.assertContainsAll(below.getMessage(), "'ratio'", "0.1", "0.05"); + } + + 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/dev/overlord/zomboidforge/core/mods/ModVerifierTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModVerifierTest.java index ff4febd..8fab22e 100644 --- a/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModVerifierTest.java +++ b/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModVerifierTest.java @@ -53,6 +53,22 @@ class ModVerifierTest return e.problems(); } + @Test + void collectsTheRegisteredCommandsOfEachModsOwnJar() throws Exception + { + String annotation = "Ldev/overlord/zomboidforge/api/annotations/RegisterCommand;"; + + ModDiscovery.Candidate mod = this.mod("commands", "", Map.of( + "a/Zeta", TestMods.type("a/Zeta", "java/lang/Object", annotation), + "a/Alpha", TestMods.type("a/Alpha", "java/lang/Object", annotation), + "a/Plain", TestMods.type("a/Plain", "java/lang/Object", null) + ), Map.of("lib/Bundled", TestMods.type("lib/Bundled", "java/lang/Object", annotation))); + + Map> commands = assertDoesNotThrow(() -> ModVerifier.verify(List.of(mod), this.game, ModVerifierTest.GAME)); + + assertEquals(Map.of("commands", List.of("a.Alpha", "a.Zeta")), commands, "sorted, own jar only"); + } + @Test void acceptsGameUseWithDeclaredVersionsThatLinks() throws Exception { diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/storage/ModTablesTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/storage/ModTablesTest.java index bd57c51..fd7aaff 100644 --- a/core/src/test/java/dev/overlord/zomboidforge/core/storage/ModTablesTest.java +++ b/core/src/test/java/dev/overlord/zomboidforge/core/storage/ModTablesTest.java @@ -1,6 +1,8 @@ package dev.overlord.zomboidforge.core.storage; +import dev.overlord.zomboidforge.api.annotations.Key; import dev.overlord.zomboidforge.api.annotations.Migrate; +import dev.overlord.zomboidforge.api.annotations.Min; import dev.overlord.zomboidforge.api.annotations.Schema; import dev.overlord.zomboidforge.api.storage.ModStorage; import dev.overlord.zomboidforge.api.storage.Row; @@ -57,6 +59,11 @@ class ModTablesTest private record RenamedDifficulty(RenamedMode mode) {} + /** {@link Balance} with the component renamed; {@code @Min} only applies to configuration. */ + private record RenamedBalance(@Key("coins") @Min(100) long amount) {} + + private record RepeatedColumn(@Key("coins") long amount, long coins) {} + @Schema(version = 2) private record AnnotatedLevel(long coins, int level) { @@ -490,6 +497,20 @@ class ModTablesTest assertThrows(StorageException.class, () -> empty.contains("a")); } + @Test + void keyAnnotationsKeepTheColumnOfARenamedComponent() + { + this.storage("shop").table("balances", Balance.class).set("a", new Balance(5)); + + Table renamed = this.storage("shop").table("balances", RenamedBalance.class); + + assertEquals(Optional.of(new RenamedBalance(5)), renamed.get("a"), "the column is the same, and @Min does not apply"); + assertTrue(this.logger.messages.isEmpty(), "no column is reported as removed: " + this.logger.messages); + + StorageException repeated = assertThrows(StorageException.class, () -> this.storage("shop").table("repeated", RepeatedColumn.class)); + ModTablesTest.assertContainsAll(repeated.getMessage(), RepeatedColumn.class.getName(), "'coins'"); + } + 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/AnnotatedCommandMod.java b/core/src/test/java/testmods/AnnotatedCommandMod.java new file mode 100644 index 0000000..9d97d5a --- /dev/null +++ b/core/src/test/java/testmods/AnnotatedCommandMod.java @@ -0,0 +1,23 @@ +package testmods; + +import dev.overlord.zomboidforge.api.Mod; +import dev.overlord.zomboidforge.api.annotations.RegisterCommand; + +/** + * Entry point that tests package into a mod jar. Two command classes carry + * {@link RegisterCommand}; {@code onLoad()} registers a third. + */ +public final class AnnotatedCommandMod extends Mod +{ + /** Stands in for a command class; the tests' validator accepts any class. */ + @RegisterCommand + public static final class Hello {} + + @RegisterCommand + public static final class Bye {} + + public static final class Manual {} + + @Override + public void onLoad() { this.commands().register(AnnotatedCommandMod.Manual.class); } +} From c79a90b88f7aad4c310807d478740fb4e5c1d24b Mon Sep 17 00:00:00 2001 From: Overlord Date: Thu, 8 Oct 2026 12:44:23 +0200 Subject: [PATCH 8/9] Add mod validation for annotations: schemas, migrations, configuration bounds, listener methods, and commands. --- MOD_DEVELOPMENT.md | 7 + .../core/config/RecordBinder.java | 20 +++ .../core/runtime/ListenerScanner.java | 52 ++++-- .../core/storage/RecordSchema.java | 16 +- .../overlord/zomboidforge/tools/ModCheck.java | 167 +++++++++++++++++- .../test/java/checkmods/AbstractCommand.java | 7 + .../src/test/java/checkmods/InvalidEntry.java | 16 ++ .../src/test/java/checkmods/Records.java | 21 +++ .../src/test/java/checkmods/ValidEntry.java | 21 +++ .../zomboidforge/tools/ModCheckTest.java | 80 +++++++++ 10 files changed, 389 insertions(+), 18 deletions(-) create mode 100644 mod-tools/src/test/java/checkmods/AbstractCommand.java create mode 100644 mod-tools/src/test/java/checkmods/InvalidEntry.java create mode 100644 mod-tools/src/test/java/checkmods/Records.java create mode 100644 mod-tools/src/test/java/checkmods/ValidEntry.java diff --git a/MOD_DEVELOPMENT.md b/MOD_DEVELOPMENT.md index 8e4e854..6d4ceab 100644 --- a/MOD_DEVELOPMENT.md +++ b/MOD_DEVELOPMENT.md @@ -485,6 +485,13 @@ mod and its libraries. The server does not start when a mod 3. uses ZomboidForge classes outside the API, or 4. contains classes in a ZomboidForge package, or a class with the name of a game class. +While it loads a mod, the server also checks the annotations: the entry point's listener and +scheduled methods, `@Schema`/`@Migrate`/`@Key`/`@Min`/`@Max` on records, and the +`@RegisterCommand` classes. `checkMod` runs the same rules on the built jar (records only when +they carry one of these annotations), loading the classes without running any of their code. +Objects passed to `events().register(...)` are only checked on the server, when they are +registered. + Every problem of every mod is listed in the log. ## What a mod can see diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/config/RecordBinder.java b/core/src/main/java/dev/overlord/zomboidforge/core/config/RecordBinder.java index 25657e8..83272d8 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/config/RecordBinder.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/config/RecordBinder.java @@ -95,6 +95,26 @@ public final class RecordBinder return keys; } + /** + * The problems of the {@link Key}, {@link Min}, and {@link Max} annotations of {@code type}'s + * components, as {@link #keys} and binding report them; empty when there are none. For + * build-time checks. + */ + public static List check(Class type) + { + List problems = new ArrayList<>(); + + try { RecordBinder.keys(type); } + catch (IllegalArgumentException e) { problems.add(e.getMessage()); } + + for (RecordComponent component : type.getRecordComponents()) { + try { RecordBinder.bounds(component); } + catch (IllegalArgumentException e) { problems.add(e.getMessage()); } + } + + return List.copyOf(problems); + } + /** A record of {@code type} from {@code table}, or {@code null} when a problem was found. */ public @Nullable T record(Map table, Class type, String path) { 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 index ac82b9a..65e2f24 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/runtime/ListenerScanner.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/runtime/ListenerScanner.java @@ -43,8 +43,10 @@ import java.util.function.Consumer; * with a filter in front: only the commands of its module (and command) reach it. An * {@link EveryNTicks} method is a main-thread listener for {@link TickEvent} that only every n-th * tick reaches. {@link Every} methods are returned as schedules. + * + *

        {@link #check} runs the same rules on a class without an object, for build-time checks. */ -final class ListenerScanner +public final class ListenerScanner { /** What {@link #scan} found, each list in registration order. */ record Found(List listeners, List schedules) {} @@ -83,11 +85,40 @@ final class ListenerScanner */ static Found scan(Object target) { - Map, Method[]> hierarchy = ListenerScanner.declaredMethods(target.getClass()); + List problems = new ArrayList<>(); + Found found = ListenerScanner.scan(target.getClass(), target, problems); + + if (!problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems)); + + return found; + } + + /** + * The problems that {@code Events.register(Object)} reports for an object of {@code type}, one + * per method or class; empty when there are none. Nothing is called. + */ + public static List check(Class type) + { + List problems = new ArrayList<>(); + + try { ListenerScanner.scan(type, null, problems); } + catch (IllegalArgumentException e) { problems.add(e.getMessage()); } + + return List.copyOf(problems); + } + + /** + * The annotated methods of {@code type}, bound to {@code target}; without a target, their + * actions do nothing. Adds the problems to {@code problems}. + * + * @throws IllegalArgumentException when the methods of a class cannot be read + */ + private static Found scan(Class type, @Nullable Object target, List problems) + { + Map, Method[]> hierarchy = ListenerScanner.declaredMethods(type); List> types = List.copyOf(hierarchy.keySet()); List listeners = new ArrayList<>(); List schedules = new ArrayList<>(); - List problems = new ArrayList<>(); for (int i = 0; i < types.size(); i++) { @@ -128,8 +159,6 @@ final class ListenerScanner } } - if (!problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems)); - return new Found(List.copyOf(listeners), List.copyOf(schedules)); } @@ -189,7 +218,7 @@ final class ListenerScanner } /** 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 modThread, @Nullable OnClientCommand clientCommand, String where, List problems) + private static @Nullable ListenerMethod listener(@Nullable Object target, Method method, boolean modThread, @Nullable OnClientCommand clientCommand, String where, List problems) { Class[] parameters = method.getParameterTypes(); int before = problems.size(); @@ -230,7 +259,7 @@ final class ListenerScanner } /** The {@link TickEvent} listener for an {@link EveryNTicks} method, or {@code null} after adding its problems to {@code problems}. */ - private static @Nullable ListenerMethod everyNTicks(Object target, Method method, EveryNTicks annotation, String where, List problems) + private static @Nullable ListenerMethod everyNTicks(@Nullable Object target, Method method, EveryNTicks annotation, String where, List problems) { int before = problems.size(); int n = annotation.value(); @@ -252,7 +281,7 @@ final class ListenerScanner } /** The schedule of an {@link Every} method, or {@code null} after adding its problems to {@code problems}. */ - private static @Nullable ScheduledMethod every(Object target, Method method, Every annotation, String where, List problems) + private static @Nullable ScheduledMethod every(@Nullable Object target, Method method, Every annotation, String where, List problems) { int before = problems.size(); @@ -300,13 +329,16 @@ final class ListenerScanner /** * A handle for {@code method} of type {@code type}, bound to {@code target} for an instance - * method, or {@code null} after adding the problem to {@code problems}. + * method, or {@code null} after adding the problem to {@code problems}. Without a target, the + * access is checked and the handle does nothing. */ - private static @Nullable MethodHandle handle(Object target, Method method, MethodType type, String where, List problems) + private static @Nullable MethodHandle handle(@Nullable Object target, Method method, MethodType type, String where, List problems) { try { MethodHandle handle = MethodHandles.privateLookupIn(method.getDeclaringClass(), MethodHandles.lookup()).unreflect(method); + + if (target == null) return MethodHandles.empty(type); if (!Modifier.isStatic(method.getModifiers())) handle = handle.bindTo(target); return handle.asType(type); diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordSchema.java b/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordSchema.java index 9a2552b..6c60c67 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordSchema.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordSchema.java @@ -27,13 +27,25 @@ import java.util.function.Function; * @param version from {@link Schema}, or 1 without it * @param migrations stored schema version to migration, from the {@link Migrate} methods */ -record RecordSchema(int version, Map> migrations) +public record RecordSchema(int version, Map> migrations) { - RecordSchema + public RecordSchema { migrations = Map.copyOf(migrations); } + /** + * The problems that {@link #of} reports for {@code type}, in one message; empty when there are + * none. For build-time checks. + */ + public static List check(Class type) + { + try { RecordSchema.of(type); } + catch (IllegalArgumentException e) { return List.of(e.getMessage()); } + + return List.of(); + } + /** @throws IllegalArgumentException listing every invalid annotation of {@code type} */ static RecordSchema of(Class type) { diff --git a/mod-tools/src/main/java/dev/overlord/zomboidforge/tools/ModCheck.java b/mod-tools/src/main/java/dev/overlord/zomboidforge/tools/ModCheck.java index e5942cd..7a60cfd 100644 --- a/mod-tools/src/main/java/dev/overlord/zomboidforge/tools/ModCheck.java +++ b/mod-tools/src/main/java/dev/overlord/zomboidforge/tools/ModCheck.java @@ -1,6 +1,7 @@ package dev.overlord.zomboidforge.tools; import dev.overlord.zomboidforge.api.GameVersion; +import dev.overlord.zomboidforge.core.config.RecordBinder; import dev.overlord.zomboidforge.core.config.TomlTree; import dev.overlord.zomboidforge.core.mods.GameClasses; import dev.overlord.zomboidforge.core.mods.ModDescriptor; @@ -8,16 +9,24 @@ import dev.overlord.zomboidforge.core.mods.ModDiscovery; import dev.overlord.zomboidforge.core.mods.ModLoadException; import dev.overlord.zomboidforge.core.mods.ModVerifier; import dev.overlord.zomboidforge.core.mods.ModVersion; +import dev.overlord.zomboidforge.core.runtime.ListenerScanner; +import dev.overlord.zomboidforge.core.storage.RecordSchema; import dev.overlord.zomboidforge.patcher.GameVersionReader; import org.jetbrains.annotations.Nullable; import org.objectweb.asm.ClassReader; import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.tree.RecordComponentNode; import java.io.IOException; import java.io.InputStream; +import java.lang.reflect.Modifier; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -26,6 +35,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.TreeSet; +import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.zip.ZipEntry; @@ -41,9 +52,18 @@ import java.util.zip.ZipEntry; * minimum version it satisfies; *

      • the game jar is one of the declared {@code game} versions;
      • *
      • {@link ModVerifier}: game use requires {@code game} versions, every used game class - * and member exists in the game jar, no ZomboidForge internals.
      • + * and member exists in the game jar, no ZomboidForge internals; + *
      • the annotations the server reads while it loads the mod, through the server's own + * rules: listener and scheduled methods of the entry point ({@link ListenerScanner}), + * {@code @Schema}/{@code @Migrate} ({@link RecordSchema}) and {@code @Key}/{@code @Min}/ + * {@code @Max} ({@link RecordBinder}) on the jar's records that carry them, and the + * {@code @RegisterCommand} classes.
      • * * + * For the last check, the mod's classes are loaded without being initialized, so no mod code + * runs. Objects that a mod passes to {@code Events.register} at runtime are only checked on the + * server. + * *
          * java -jar mod-tools.jar --jar <mod.jar> [--game-jar <projectzomboid.jar>]
          *     [--library <jar>]... [--dependency <mod jar>]... [--report <file>]
        @@ -57,7 +77,15 @@ import java.util.zip.ZipEntry;
          */
         public final class ModCheck
         {
        -    private static final String MOD_CLASS = "dev/overlord/zomboidforge/api/Mod";
        +    private static final String MOD_CLASS  = "dev/overlord/zomboidforge/api/Mod";
        +    private static final String RECORD     = "java/lang/Record";
        +    private static final String ANNOTATION = "Ldev/overlord/zomboidforge/api/annotations/";
        +
        +    /** Annotations that make a record worth loading for {@link #checkAnnotations}. */
        +    private static final Set RECORD_ANNOTATIONS = Set.of(
        +        ModCheck.ANNOTATION + "Schema;", ModCheck.ANNOTATION + "Migrate;",
        +        ModCheck.ANNOTATION + "Key;", ModCheck.ANNOTATION + "Min;", ModCheck.ANNOTATION + "Max;"
        +    );
         
             /** The command-line arguments. */
             public record Arguments(Path jar, @Nullable Path gameJar, List libraries, List dependencies, @Nullable Path report)
        @@ -201,7 +229,9 @@ public final class ModCheck
                 {
                     if (!descriptor.game().isEmpty()) problems.add("The mod declares " + descriptor.game() + ", so the check needs '--game-jar'.");
         
        -            ModCheck.verify(candidates, GameClasses.none(), null, problems);
        +            Map> commands = ModCheck.verify(candidates, GameClasses.none(), null, problems);
        +            ModCheck.checkAnnotations(arguments, descriptor, commands.getOrDefault(descriptor.id(), List.of()), problems);
        +
                     return new Result(descriptor, null, problems);
                 }
         
        @@ -211,22 +241,147 @@ public final class ModCheck
                 if (!descriptor.game().isEmpty() && descriptor.game().stream().noneMatch(gameVersion::matches))
                     problems.add("The game jar '" + gameJar + "' is Project Zomboid " + gameVersion + ", but the mod declares " + descriptor.game() + "; the check needs a game jar of a declared version.");
         
        +        Map> commands = Map.of();
        +
                 try (GameClasses game = GameClasses.open(gameJar))
                 {
        -            ModCheck.verify(candidates, game, gameVersion, problems);
        +            commands = ModCheck.verify(candidates, game, gameVersion, problems);
                 }
                 catch (IOException e)
                 {
                     problems.add("Cannot read the game jar '" + gameJar + "': " + e.getMessage());
                 }
         
        +        ModCheck.checkAnnotations(arguments, descriptor, commands.getOrDefault(descriptor.id(), List.of()), problems);
        +
                 return new Result(descriptor, gameVersion, problems);
             }
         
        -    private static void verify(List candidates, GameClasses game, @Nullable GameVersion version, List problems)
        +    /** @return mod id to its {@code @RegisterCommand} classes; empty when the verifier found problems */
        +    private static Map> verify(List candidates, GameClasses game, @Nullable GameVersion version, List problems)
             {
        -        try                        { ModVerifier.verify(candidates, game, version); }
        +        try                        { return ModVerifier.verify(candidates, game, version); }
                 catch (ModLoadException e) { problems.addAll(e.problems()); }
        +
        +        return Map.of();
        +    }
        +
        +    /**
        +     * The annotation rules of the server, run on the mod's classes: the entry point's listener and
        +     * scheduled methods, the records in the jar that carry {@code @Schema}, {@code @Migrate},
        +     * {@code @Key}, {@code @Min}, or {@code @Max}, and the {@code @RegisterCommand} classes.
        +     * Runs only when every other check passed, since classes that do not link cannot be loaded.
        +     *
        +     * @param commands binary names of the mod's {@code @RegisterCommand} classes
        +     */
        +    private static void checkAnnotations(Arguments arguments, ModDescriptor descriptor, List commands, List problems)
        +    {
        +        if (!problems.isEmpty()) return;
        +
        +        List jars = new ArrayList<>();
        +        jars.add(arguments.jar());
        +        jars.addAll(arguments.libraries());
        +        jars.addAll(arguments.dependencies());
        +        if (arguments.gameJar() != null) jars.add(arguments.gameJar());
        +
        +        try (URLClassLoader loader = new URLClassLoader("mod-check", jars.stream().map(ModCheck::url).toArray(URL[]::new), ModCheck.class.getClassLoader()))
        +        {
        +            Class entrypoint = ModCheck.load(loader, descriptor.entrypoint(), problems);
        +            if (entrypoint != null) problems.addAll(ListenerScanner.check(entrypoint));
        +
        +            for (String name : ModCheck.annotatedRecords(arguments.jar(), problems))
        +            {
        +                Class type = ModCheck.load(loader, name, problems);
        +                if (type == null || !type.isRecord()) continue;
        +
        +                problems.addAll(RecordSchema.check(type.asSubclass(Record.class)));
        +                problems.addAll(RecordBinder.check(type.asSubclass(Record.class)));
        +            }
        +
        +            for (String name : commands)
        +            {
        +                Class type = ModCheck.load(loader, name, problems);
        +                if (type == null) continue;
        +
        +                int modifiers = type.getModifiers();
        +
        +                if (!Modifier.isPublic(modifiers))                        problems.add("The command '" + name + "' (@RegisterCommand) is not public.");
        +                if (Modifier.isAbstract(modifiers) || type.isInterface()) problems.add("The command '" + name + "' (@RegisterCommand) is abstract.");
        +                if (descriptor.game().isEmpty())                          problems.add("The command '" + name + "' (@RegisterCommand) needs Project Zomboid's command framework, so 'mod.toml' needs 'game' versions.");
        +            }
        +        }
        +        catch (IOException e)
        +        {
        +            problems.add("Cannot close the class loader of the check: " + e.getMessage());
        +        }
        +    }
        +
        +    /** The class {@code name}, loaded without initializing it, or {@code null} after adding the problem. */
        +    private static @Nullable Class load(ClassLoader loader, String name, List problems)
        +    {
        +        try
        +        {
        +            return Class.forName(name, false, loader);
        +        }
        +        catch (ClassNotFoundException | LinkageError e)
        +        {
        +            problems.add("Cannot load '" + name + "' to check its annotations: " + e + ".");
        +            return null;
        +        }
        +    }
        +
        +    /** Binary names of the records in {@code jar} that carry one of {@link #RECORD_ANNOTATIONS}, on the record, a component, or a method. */
        +    private static Set annotatedRecords(Path jar, List problems)
        +    {
        +        Set records = new TreeSet<>();
        +
        +        try (JarFile file = new JarFile(jar.toFile()))
        +        {
        +            for (JarEntry entry : file.stream().toList())
        +            {
        +                String name = entry.getName();
        +                if (!name.endsWith(".class") || name.startsWith("META-INF/")) continue;
        +
        +                ClassNode node = new ClassNode();
        +                try (InputStream in = file.getInputStream(entry)) { new ClassReader(in.readAllBytes()).accept(node, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); }
        +
        +                if (ModCheck.RECORD.equals(node.superName) && ModCheck.carriesRecordAnnotation(node)) records.add(node.name.replace('/', '.'));
        +            }
        +        }
        +        catch (IOException e)
        +        {
        +            problems.add("Cannot read '" + jar + "': " + e.getMessage());
        +        }
        +
        +        return records;
        +    }
        +
        +    private static boolean carriesRecordAnnotation(ClassNode node)
        +    {
        +        if (ModCheck.anyRecordAnnotation(node.visibleAnnotations)) return true;
        +
        +        for (MethodNode method : node.methods) {
        +            if (ModCheck.anyRecordAnnotation(method.visibleAnnotations)) return true;
        +        }
        +
        +        if (node.recordComponents != null) {
        +            for (RecordComponentNode component : node.recordComponents) {
        +                if (ModCheck.anyRecordAnnotation(component.visibleAnnotations)) return true;
        +            }
        +        }
        +
        +        return false;
        +    }
        +
        +    private static boolean anyRecordAnnotation(@Nullable List annotations)
        +    {
        +        return annotations != null && annotations.stream().anyMatch(annotation -> ModCheck.RECORD_ANNOTATIONS.contains(annotation.desc));
        +    }
        +
        +    private static URL url(Path path)
        +    {
        +        try                             { return path.toUri().toURL(); }
        +        catch (MalformedURLException e) { throw new IllegalArgumentException("'" + path + "' has no URL.", e); }
             }
         
             private static ModDiscovery.Candidate candidate(Path jar, List libraries, ModDescriptor descriptor)
        diff --git a/mod-tools/src/test/java/checkmods/AbstractCommand.java b/mod-tools/src/test/java/checkmods/AbstractCommand.java
        new file mode 100644
        index 0000000..3dbb9e9
        --- /dev/null
        +++ b/mod-tools/src/test/java/checkmods/AbstractCommand.java
        @@ -0,0 +1,7 @@
        +package checkmods;
        +
        +import dev.overlord.zomboidforge.api.annotations.RegisterCommand;
        +
        +/** A command class that tests package into a mod jar: neither public nor concrete. */
        +@RegisterCommand
        +abstract class AbstractCommand {}
        diff --git a/mod-tools/src/test/java/checkmods/InvalidEntry.java b/mod-tools/src/test/java/checkmods/InvalidEntry.java
        new file mode 100644
        index 0000000..2e29efe
        --- /dev/null
        +++ b/mod-tools/src/test/java/checkmods/InvalidEntry.java
        @@ -0,0 +1,16 @@
        +package checkmods;
        +
        +import dev.overlord.zomboidforge.api.Mod;
        +import dev.overlord.zomboidforge.api.annotations.Every;
        +import dev.overlord.zomboidforge.api.annotations.OnMain;
        +
        +/** Entry point that tests package into a mod jar; its annotated methods break the rules. */
        +@SuppressWarnings("unused")
        +public class InvalidEntry extends Mod
        +{
        +    @OnMain
        +    void tick(String text) {}
        +
        +    @Every(0)
        +    void report() {}
        +}
        diff --git a/mod-tools/src/test/java/checkmods/Records.java b/mod-tools/src/test/java/checkmods/Records.java
        new file mode 100644
        index 0000000..4fa4438
        --- /dev/null
        +++ b/mod-tools/src/test/java/checkmods/Records.java
        @@ -0,0 +1,21 @@
        +package checkmods;
        +
        +import dev.overlord.zomboidforge.api.annotations.Key;
        +import dev.overlord.zomboidforge.api.annotations.Max;
        +import dev.overlord.zomboidforge.api.annotations.Min;
        +import dev.overlord.zomboidforge.api.annotations.Schema;
        +
        +/** Records that tests package into a mod jar, with valid and invalid annotations. */
        +public final class Records
        +{
        +    public record Fine(@Key("ok") @Min(1) int amount) {}
        +
        +    @Schema(version = 0)
        +    public record BadSchema(long amount) {}
        +
        +    public record BadKey(@Key("Bad Key") int amount) {}
        +
        +    public record BadBounds(@Min(5) @Max(1) int amount) {}
        +
        +    private Records() {}
        +}
        diff --git a/mod-tools/src/test/java/checkmods/ValidEntry.java b/mod-tools/src/test/java/checkmods/ValidEntry.java
        new file mode 100644
        index 0000000..99cd59c
        --- /dev/null
        +++ b/mod-tools/src/test/java/checkmods/ValidEntry.java
        @@ -0,0 +1,21 @@
        +package checkmods;
        +
        +import dev.overlord.zomboidforge.api.Mod;
        +import dev.overlord.zomboidforge.api.TickEvent;
        +import dev.overlord.zomboidforge.api.annotations.Every;
        +import dev.overlord.zomboidforge.api.annotations.EveryNTicks;
        +import dev.overlord.zomboidforge.api.annotations.OnMain;
        +
        +/** Entry point that tests package into a mod jar; every annotated method follows the rules. */
        +@SuppressWarnings("unused")
        +public class ValidEntry extends Mod
        +{
        +    @OnMain
        +    void tick(TickEvent event) {}
        +
        +    @Every(1)
        +    void report() {}
        +
        +    @EveryNTicks(2)
        +    void sweep() {}
        +}
        diff --git a/mod-tools/src/test/java/dev/overlord/zomboidforge/tools/ModCheckTest.java b/mod-tools/src/test/java/dev/overlord/zomboidforge/tools/ModCheckTest.java
        index 8506e21..14a3d42 100644
        --- a/mod-tools/src/test/java/dev/overlord/zomboidforge/tools/ModCheckTest.java
        +++ b/mod-tools/src/test/java/dev/overlord/zomboidforge/tools/ModCheckTest.java
        @@ -1,5 +1,9 @@
         package dev.overlord.zomboidforge.tools;
         
        +import checkmods.InvalidEntry;
        +import checkmods.Records;
        +import checkmods.ValidEntry;
        +
         import org.jetbrains.annotations.Nullable;
         import org.junit.jupiter.api.Test;
         import org.junit.jupiter.api.io.TempDir;
        @@ -7,6 +11,7 @@ import org.objectweb.asm.ClassWriter;
         import org.objectweb.asm.MethodVisitor;
         
         import java.io.IOException;
        +import java.io.InputStream;
         import java.io.OutputStream;
         import java.nio.charset.StandardCharsets;
         import java.nio.file.Files;
        @@ -17,6 +22,7 @@ import java.util.jar.JarEntry;
         import java.util.jar.JarOutputStream;
         
         import static org.junit.jupiter.api.Assertions.assertEquals;
        +import static org.junit.jupiter.api.Assertions.assertTrue;
         import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
         import static org.objectweb.asm.Opcodes.ALOAD;
         import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
        @@ -67,6 +73,80 @@ class ModCheckTest
                 assertEquals(List.of("The entry point 'a.Main' does not extend 'dev.overlord.zomboidforge.api.Mod'."), result.problems());
             }
         
        +    @Test
        +    void passesValidAnnotations() throws IOException
        +    {
        +        Path mod = this.jar("shop.jar", ModCheckTest.toml(ValidEntry.class), Map.of(
        +            "checkmods/ValidEntry",   ModCheckTest.classFile(ValidEntry.class),
        +            "checkmods/Records$Fine", ModCheckTest.classFile(Records.Fine.class)
        +        ));
        +
        +        ModCheck.Result result = ModCheck.check(new ModCheck.Arguments(mod, null, List.of(), List.of(), null));
        +
        +        assertEquals(List.of(), result.problems());
        +    }
        +
        +    @Test
        +    void reportsListenerAndScheduledMethodsThatBreakTheRules() throws IOException
        +    {
        +        Path mod = this.jar("shop.jar", ModCheckTest.toml(InvalidEntry.class), Map.of("checkmods/InvalidEntry", ModCheckTest.classFile(InvalidEntry.class)));
        +
        +        String problems = String.join("\n", ModCheck.check(new ModCheck.Arguments(mod, null, List.of(), List.of(), null)).problems());
        +
        +        ModCheckTest.assertContainsAll(problems, "checkmods.InvalidEntry.tick", "java.lang.String", "checkmods.InvalidEntry.report");
        +    }
        +
        +    @Test
        +    void reportsRecordAnnotationsThatBreakTheRules() throws IOException
        +    {
        +        Path mod = this.jar("shop.jar", ModCheckTest.toml(ValidEntry.class), Map.of(
        +            "checkmods/ValidEntry",        ModCheckTest.classFile(ValidEntry.class),
        +            "checkmods/Records$Fine",      ModCheckTest.classFile(Records.Fine.class),
        +            "checkmods/Records$BadSchema", ModCheckTest.classFile(Records.BadSchema.class),
        +            "checkmods/Records$BadKey",    ModCheckTest.classFile(Records.BadKey.class),
        +            "checkmods/Records$BadBounds", ModCheckTest.classFile(Records.BadBounds.class)
        +        ));
        +
        +        List problems = ModCheck.check(new ModCheck.Arguments(mod, null, List.of(), List.of(), null)).problems();
        +
        +        assertEquals(3, problems.size(), String.valueOf(problems));
        +        ModCheckTest.assertContainsAll(String.join("\n", problems), "Records$BadSchema", "Records$BadKey", "Bad Key", "Records$BadBounds");
        +    }
        +
        +    @Test
        +    void reportsRegisteredCommandsThatCannotBeRegistered() throws IOException
        +    {
        +        Path mod = this.jar("shop.jar", ModCheckTest.toml(ValidEntry.class), Map.of(
        +            "checkmods/ValidEntry",      ModCheckTest.classFile(ValidEntry.class),
        +            "checkmods/AbstractCommand", ModCheckTest.classFile("checkmods/AbstractCommand")
        +        ));
        +
        +        String problems = String.join("\n", ModCheck.check(new ModCheck.Arguments(mod, null, List.of(), List.of(), null)).problems());
        +
        +        ModCheckTest.assertContainsAll(problems, "checkmods.AbstractCommand", "not public", "abstract", "'game'");
        +    }
        +
        +    /** {@link #TOML} with {@code entrypoint} as the entry point. */
        +    private static String toml(Class entrypoint) { return ModCheckTest.TOML.replace("a.Main", entrypoint.getName()); }
        +
        +    /** The class file of a class on the test class path. */
        +    private static byte[] classFile(Class type) throws IOException { return ModCheckTest.classFile(type.getName().replace('.', '/')); }
        +
        +    /** The class file of the class {@code internalName} on the test class path. */
        +    private static byte[] classFile(String internalName) throws IOException
        +    {
        +        try (InputStream in = ModCheckTest.class.getResourceAsStream("/" + internalName + ".class"))
        +        {
        +            if (in == null) throw new IOException("No class file for '" + internalName + "'.");
        +            return in.readAllBytes();
        +        }
        +    }
        +
        +    private static void assertContainsAll(String message, String... parts)
        +    {
        +        for (String part : parts) assertTrue(message.contains(part), "'" + part + "' missing in: " + message);
        +    }
        +
             /** A public class extending {@code superName} with a public constructor without parameters. */
             private static byte[] type(String name, String superName)
             {
        
        From 22c74a00305bd2b3e7bff55465b92c35a5243af1 Mon Sep 17 00:00:00 2001
        From: Overlord 
        Date: Sat, 10 Oct 2026 12:48:50 +0200
        Subject: [PATCH 9/9] Bump ZomboidForge plugin version to 0.6.0.
        
        ---
         MOD_DEVELOPMENT.md | 2 +-
         1 file changed, 1 insertion(+), 1 deletion(-)
        
        diff --git a/MOD_DEVELOPMENT.md b/MOD_DEVELOPMENT.md
        index 6d4ceab..7d18515 100644
        --- a/MOD_DEVELOPMENT.md
        +++ b/MOD_DEVELOPMENT.md
        @@ -32,7 +32,7 @@ rootProject.name = "shop"
         
         ```kotlin
         plugins {
        -    id("dev.overlord.zomboidforge.mod") version "0.3.0"   // the plugin's version is the API version
        +    id("dev.overlord.zomboidforge.mod") version "0.6.0"   // the plugin's version is the API version
         }
         
         version = "1.2.0"