Add support for @Every and @EveryNTicks annotations to schedule periodic and tick-based method execution.

This commit is contained in:
Overlord committed 2026-10-07 20:02:29 +02:00
1 parent b10504e9af
commit 9fcde10fed
11 files changed
+624 -50

No files matched your search

+19
View File
@@ -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-<id>; 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
@@ -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.
*
* <p>Each annotated method:
* <ul>
* <li>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;</li>
* <li>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;</li>
* <li>carries one of the annotations; {@link OnModThread} not for a
* {@link MainThreadEvent}, {@link OnClientCommand} only for a
* {@link ClientCommandEvent};</li>
@@ -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
@@ -20,12 +20,15 @@ import java.nio.file.Path;
* <ol>
* <li>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)}).</li>
* <li>{@link #onLoad()}: registration and setup. The server database, Lua, and the world do
* not exist yet.</li>
* <li>{@link #onServerStarted()}: the world is loaded and the network port is open.</li>
* <li>{@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.</li>
* <li>{@link #onStopping()}: the server stops; the world has not been saved yet.</li>
* </ol>
* An exception thrown by the constructor or {@link #onLoad()}, or a listener method that breaks
@@ -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.
*
* <p>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.
*
* <pre>{@code
* @Every(value = 1, unit = ChronoUnit.MINUTES)
* void report() { ... }
* }</pre>
*/
@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;
}
@@ -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.
*
* <p>The method has no parameters and returns {@code void}; otherwise the rules of
* {@link Events#register(Object)} apply.
*
* <pre>{@code
* @EveryNTicks(10)
* void sweep() { ... }
* }</pre>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface EveryNTicks
{
/** n, at least 1. */
int value();
}
@@ -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());
}
}
@@ -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.
*
* <p>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<Class<?>, Listener[]> listeners = new ConcurrentHashMap<>();
private final Map<String, ModEvents> 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<? extends Event> 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<Object> 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<Schedule> 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<ListenerScanner.ListenerMethod> 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<Listener> listeners = methods.stream()
List<Listener> listeners = found.listeners().stream()
.map(method -> this.add(method.type(), method.action(), method.main() ? null : this.modThread, method.name()))
.toList();
List<Schedule> 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<Schedule> schedules;
synchronized (this.pending)
{
this.started = true;
schedules = List.copyOf(this.pending);
this.pending.clear();
}
schedules.forEach(Schedule::start);
}
private <E extends Event> Subscription register(Class<E> type, Consumer<? super E> 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();
}
}
}
}
@@ -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.
*
* <p>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<ListenerMethod> listeners, List<ScheduledMethod> 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<Object> 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<Method> 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<ChronoUnit> 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<ListenerMethod> scan(Object target)
static Found scan(Object target)
{
Map<Class<?>, Method[]> hierarchy = ListenerScanner.declaredMethods(target.getClass());
List<Class<?>> types = List.copyOf(hierarchy.keySet());
List<ListenerMethod> found = new ArrayList<>();
List<ListenerMethod> listeners = new ArrayList<>();
List<ScheduledMethod> schedules = new ArrayList<>();
List<String> 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 (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<String> problems)
private static @Nullable ListenerMethod listener(Object target, Method method, boolean modThread, @Nullable OnClientCommand clientCommand, String where, List<String> 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 (clientCommand != null && clientCommand.module().isBlank()) problems.add(where + ": @OnClientCommand needs a module.");
if (parameters.length != 1)
@@ -174,21 +216,101 @@ final class ListenerScanner
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 = ListenerScanner.handle(target, method, MethodType.methodType(void.class, Object.class), where, problems);
if (invoker == null) return null;
MethodHandle invoker = handle.asType(MethodType.methodType(void.class, Object.class));
Consumer<Object> call = event -> {
try { invoker.invokeExact(event); }
catch (Throwable t) { throw ListenerScanner.<RuntimeException>rethrow(t); }
};
return clientCommand == null
? new ListenerMethod(type, main, method.getName(), call)
? 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<String> 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.<RuntimeException>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<String> 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.<RuntimeException>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<String> 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<String> problems)
{
try
{
MethodHandle handle = MethodHandles.privateLookupIn(method.getDeclaringClass(), MethodHandles.lookup()).unreflect(method);
if (!Modifier.isStatic(method.getModifiers())) handle = handle.bindTo(target);
return handle.asType(type);
}
catch (IllegalAccessException e)
{
problems.add(where + " cannot be accessed: " + e.getMessage());
@@ -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<Object> filter(OnClientCommand annotation, Consumer<Object> call)
{
@@ -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);
@@ -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<String> 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<Runnable> tasks = new ArrayList<>();
final List<String> schedules = new ArrayList<>();
final List<Runnable> runs = new ArrayList<>();
final List<FakeFuture> futures = new ArrayList<>();
@Override
public void execute(Runnable task) { this.tasks.add(task); }
@Override
public <T> CompletableFuture<T> submit(Callable<T> 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<Object> implements ScheduledFuture<Object>
{
@Override
public long getDelay(TimeUnit unit) { return 0; }
@Override
public int compareTo(Delayed other) { return 0; }
}
/** Client command handlers of the module {@code Shop}. */
@@ -134,10 +234,8 @@ class EventBusTest
private final EventBus bus = new EventBus();
private final RecordingLogger logger = new RecordingLogger();
private final List<String> received = new ArrayList<>();
private final List<Runnable> modTasks = new ArrayList<>();
/** Collects the tasks for the mod thread instead of running them. */
private final Executor modThread = this.modTasks::add;
private final FakeModThread modThread = new FakeModThread();
private final List<Runnable> 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)
@@ -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<String> 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()); }
}