Introduce event-driven API, modular threading, and enhanced server lifecycle tools

Add `Events` and `EventBus` for mod-driven event handling with support for main-thread and mod-thread execution. Introduce `MainThread` and `AsyncExecutor` for modular threading and background task management. Add `ForgeSettings` to manage global mod configuration through `forge.toml`. Include tests for events, threading, and configuration parsing to improve robustness and maintainability.
This commit is contained in:
Overlord committed 2026-10-02 12:58:40 +02:00
1 parent 3b21fc3aa6
commit a0d1ec2feb
30 files changed
+1678 -14

No files matched your search

+3 -1
View File
@@ -70,7 +70,9 @@ Notes:
the folder is writable by UID 1000. `[forge]` `enabled = false` in it switches the mod off. the folder is writable by UID 1000. `[forge]` `enabled = false` in it switches the mod off.
A mod that cannot be loaded (missing dependency, wrong game version, game classes that do A mod that cannot be loaded (missing dependency, wrong game version, game classes that do
not exist in the running version, failing `onLoad`) stops the server with exit code 1 and not exist in the running version, failing `onLoad`) stops the server with exit code 1 and
lists every problem in the log. lists every problem in the log. Optional `/forge/forge.toml`: `[main_thread] budget_ms`
(time per tick for mods' main-thread tasks, default 2) and `[shutdown] timeout_s` (time
mod threads get to finish when the server stops, default 10).
- **Stopping:** `SIGTERM` triggers the game's own save-and-quit. Allow enough time for large - **Stopping:** `SIGTERM` triggers the game's own save-and-quit. Allow enough time for large
worlds (`podman stop -t 120`, `stop_grace_period` in compose). worlds (`podman stop -t 120`, `stop_grace_period` in compose).
@@ -0,0 +1,20 @@
package dev.overlord.zomboidforge.api;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
/**
* Virtual threads for a mod's blocking work, such as HTTP calls or file I/O: one thread per
* task, named {@code zf-async-<id>-<n>}. ZomboidForge shuts it down when the server stops; tasks
* submitted after that are rejected with a {@link java.util.concurrent.RejectedExecutionException}.
*/
public interface AsyncExecutor extends Executor
{
/** Runs {@code task} on a new virtual thread. An exception it throws is logged with the mod's id. */
@Override
void execute(Runnable task);
/** Runs {@code task} on a new virtual thread; the future completes with its result or exception. */
<T> CompletableFuture<T> submit(Callable<T> task);
}
@@ -0,0 +1,7 @@
package dev.overlord.zomboidforge.api;
/**
* Something that happened in the server, delivered to listeners registered with
* {@link Events}. Listeners are matched by the event's exact class.
*/
public interface Event {}
@@ -0,0 +1,24 @@
package dev.overlord.zomboidforge.api;
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.
*/
public interface Events
{
/**
* {@code listener} runs on the main thread while the event is posted. It may touch game
* objects and must return quickly: it runs inside the tick.
*/
<E extends Event> Subscription onMain(Class<E> type, Consumer<? super E> listener);
/**
* {@code listener} runs later on the mod's own thread. It must not touch game objects;
* main-thread work goes through {@code main()}.
*
* @throws IllegalArgumentException when {@code type} is a {@link MainThreadEvent}
*/
<E extends Event> Subscription onModThread(Class<E> type, Consumer<? super E> listener);
}
@@ -0,0 +1,44 @@
package dev.overlord.zomboidforge.api;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
/**
* Runs a mod's code on the server's main thread, which owns every game object. Tasks from other
* threads are queued and run during the next ticks, within a time budget per tick
* ({@code forge.toml}); a task is never interrupted. Called on the main thread itself,
* {@link #execute} and {@link #submit} run the task immediately.
*
* <p>Callbacks of the returned futures run on the thread that completes them, which is the
* main thread: {@code submit(...).thenAcceptAsync(result -> ..., modThread())} moves the
* follow-up work back. The main thread must never wait for another thread's result.
*/
public interface MainThread extends Executor
{
/**
* Runs {@code task} on the main thread. An exception it throws is logged with the mod's id.
*
* @throws java.util.concurrent.RejectedExecutionException after the server started stopping
*/
@Override
void execute(Runnable task);
/**
* Runs {@code task} on the main thread; the future completes with its result or exception.
*
* @throws java.util.concurrent.RejectedExecutionException after the server started stopping
*/
<T> CompletableFuture<T> submit(Callable<T> task);
/**
* Queues {@code task} to run on the main thread {@code ticks} frames from now, also when
* called on the main thread.
*
* @throws IllegalArgumentException when {@code ticks} is less than 1
*/
void runLater(int ticks, Runnable task);
/** Whether the calling thread is the main thread. */
boolean isMainThread();
}
@@ -0,0 +1,7 @@
package dev.overlord.zomboidforge.api;
/**
* An event that carries live game state or only makes sense during the tick. Listeners for it
* run on the main thread only; {@link Events#onModThread} rejects it.
*/
public interface MainThreadEvent extends Event {}
@@ -67,4 +67,17 @@ public abstract class Mod
/** The mod's settings from {@code config.toml}. */ /** The mod's settings from {@code config.toml}. */
protected final ModConfig config() { return this.context.config(); } protected final ModConfig config() { return this.context.config(); }
/** Event listener registration. */
protected final Events events() { return this.context.events(); }
/** The server's main thread, for everything that touches game objects. */
@SuppressWarnings("ConfusingMainMethod")
protected final MainThread main() { return this.context.main(); }
/** The mod's own platform thread, {@code zf-mod-<id>}: one task at a time, in order. */
protected final ModThread modThread() { return this.context.modThread(); }
/** Virtual threads for blocking work such as HTTP calls or file I/O. */
protected final AsyncExecutor async() { return this.context.async(); }
} }
@@ -25,4 +25,16 @@ public interface ModContext
/** The mod's settings from {@code config.toml}. */ /** The mod's settings from {@code config.toml}. */
ModConfig config(); ModConfig config();
/** Event listener registration. */
Events events();
/** The server's main thread, for everything that touches game objects. */
MainThread main();
/** The mod's own platform thread, {@code zf-mod-<id>}: one task at a time, in order. */
ModThread modThread();
/** Virtual threads for blocking work such as HTTP calls or file I/O. */
AsyncExecutor async();
} }
@@ -0,0 +1,41 @@
package dev.overlord.zomboidforge.api;
import java.time.Duration;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledFuture;
/**
* The mod's own platform thread, {@code zf-mod-<id>}: runs one task at a time, in the order
* they were submitted. ZomboidForge shuts it down when the server stops; tasks submitted after
* that are rejected with a {@link java.util.concurrent.RejectedExecutionException}. It must not
* touch game objects; that goes through {@code main()}.
*/
public interface ModThread extends Executor
{
/** Runs {@code task} on the mod thread. An exception it throws is logged with the mod's id. */
@Override
void execute(Runnable task);
/** Runs {@code task} on the mod thread; the future completes with its result or exception. */
<T> CompletableFuture<T> submit(Callable<T> task);
/** Runs {@code task} once after {@code delay}. An exception it throws is logged. */
ScheduledFuture<?> schedule(Runnable task, Duration delay);
/**
* Runs {@code task} after {@code initialDelay}, then every {@code period}, measured from the
* start of each run. A run that throws is logged and ends the schedule.
*/
ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration initialDelay, Duration period);
/**
* Runs {@code task} after {@code initialDelay}, then again {@code delay} after each run
* finished. A run that throws is logged and ends the schedule.
*/
ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration initialDelay, Duration delay);
/** Whether the calling thread is this mod thread. */
boolean isModThread();
}
@@ -0,0 +1,8 @@
package dev.overlord.zomboidforge.api;
/** A registered event listener. */
public interface Subscription
{
/** Removes the listener; it receives no further events. Calling it again has no effect. */
void cancel();
}
@@ -0,0 +1,9 @@
package dev.overlord.zomboidforge.api;
/**
* Posted on the main thread once per frame of the main loop, before the queued main-thread
* tasks run.
*
* @param tick number of the frame, counted from 1 at the first frame after the server started
*/
public record TickEvent(long tick) implements MainThreadEvent {}
@@ -77,9 +77,14 @@ public final class ServerHooks
/** /**
* Called on the main thread for every frame of the main loop, directly after * Called on the main thread for every frame of the main loop, directly after
* {@code ServerMap.instance.preupdate()}, inside the {@code frameStep} profiling probe. Not * {@code ServerMap.instance.preupdate()}, inside the {@code frameStep} profiling probe. Not
* called while the update limiter skips a frame. * called while the update limiter skips a frame. Posts the tick event and runs the mods'
* queued main-thread tasks.
*/ */
public static void onTick() {} public static void onTick()
{
try { ServerHooks.FORGE.tick(); }
catch (RuntimeException e) { e.printStackTrace(); }
}
/** /**
* Called once on the shutdown hook thread ({@code GameServer$1}), after * Called once on the shutdown hook thread ({@code GameServer$1}), after
@@ -1,27 +1,36 @@
package dev.overlord.zomboidforge.core; package dev.overlord.zomboidforge.core;
import dev.overlord.zomboidforge.api.Event;
import dev.overlord.zomboidforge.api.GameVersion; import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.api.Mod; import dev.overlord.zomboidforge.api.Mod;
import dev.overlord.zomboidforge.api.TickEvent;
import dev.overlord.zomboidforge.api.ZomboidForge; import dev.overlord.zomboidforge.api.ZomboidForge;
import dev.overlord.zomboidforge.core.config.ForgeSettings;
import dev.overlord.zomboidforge.core.mods.GameClasses; import dev.overlord.zomboidforge.core.mods.GameClasses;
import dev.overlord.zomboidforge.core.mods.ModDiscovery; import dev.overlord.zomboidforge.core.mods.ModDiscovery;
import dev.overlord.zomboidforge.core.mods.ModLoadException; import dev.overlord.zomboidforge.core.mods.ModLoadException;
import dev.overlord.zomboidforge.core.mods.ModLoader; import dev.overlord.zomboidforge.core.mods.ModLoader;
import dev.overlord.zomboidforge.core.mods.ModResolver; import dev.overlord.zomboidforge.core.mods.ModResolver;
import dev.overlord.zomboidforge.core.mods.ModServices;
import dev.overlord.zomboidforge.core.mods.ModVerifier; import dev.overlord.zomboidforge.core.mods.ModVerifier;
import dev.overlord.zomboidforge.core.mods.ModVersion; import dev.overlord.zomboidforge.core.mods.ModVersion;
import dev.overlord.zomboidforge.core.runtime.EventBus;
import dev.overlord.zomboidforge.core.runtime.MainThreadQueue;
import dev.overlord.zomboidforge.core.runtime.ModThreads;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.time.Duration;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
* ZomboidForge inside a running server: the lifecycle phase and the loaded mods. The compat * ZomboidForge inside a running server: the lifecycle phase, the loaded mods, and their threads
* hooks call {@link #load}, {@link #started()}, and {@link #stopping()}. * and events. The compat hooks call {@link #load}, {@link #started()}, {@link #tick()}, and
* {@link #stopping()}.
*/ */
public final class Forge public final class Forge
{ {
@@ -33,11 +42,15 @@ public final class Forge
private final Lifecycle lifecycle = new Lifecycle(); private final Lifecycle lifecycle = new Lifecycle();
private final System.Logger logger = new ConsoleLogger("ZomboidForge"); private final System.Logger logger = new ConsoleLogger("ZomboidForge");
private final MainThreadQueue queue = new MainThreadQueue(ForgeSettings.DEFAULTS.mainThreadBudget());
private final EventBus events = new EventBus();
private final ModThreads threads = new ModThreads();
private final Path directory; private final Path directory;
private final @Nullable ModVersion api; private final @Nullable ModVersion api;
private volatile List<ModLoader.LoadedMod> mods = List.of(); private volatile List<ModLoader.LoadedMod> mods = List.of();
private volatile ForgeSettings settings = ForgeSettings.DEFAULTS;
/** /**
* @param directory the ZomboidForge directory * @param directory the ZomboidForge directory
@@ -70,8 +83,9 @@ public final class Forge
public List<ModLoader.LoadedMod> mods() { return this.mods; } public List<ModLoader.LoadedMod> mods() { return this.mods; }
/** /**
* Discovers, checks, and loads every mod in {@code <directory>/mods}. Called once on the * Reads {@code forge.toml}, then discovers, checks, and loads every mod in
* main thread. * {@code <directory>/mods}. Called once on the main thread, which becomes the thread of
* {@code main()}. When a mod fails, the threads of the mods created so far are stopped.
* *
* @param gameJar the Project Zomboid jar the server runs * @param gameJar the Project Zomboid jar the server runs
* @param parent parent of the mods' class loaders; loads the game, the API, and ZomboidForge * @param parent parent of the mods' class loaders; loads the game, the API, and ZomboidForge
@@ -81,6 +95,12 @@ public final class Forge
{ {
Path modsDirectory = this.directory.resolve(Forge.MODS); Path modsDirectory = this.directory.resolve(Forge.MODS);
try { this.settings = ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE)); }
catch (IllegalArgumentException e) { throw new ModLoadException("'" + ForgeSettings.FILE + "': " + e.getMessage(), e); }
this.queue.budget(this.settings.mainThreadBudget());
this.queue.bindToCurrentThread();
if (this.api == null) this.logger.log(System.Logger.Level.WARNING, "ZomboidForge " + ZomboidForge.VERSION + " is not a release; the API versions of mods are not checked."); if (this.api == null) this.logger.log(System.Logger.Level.WARNING, "ZomboidForge " + ZomboidForge.VERSION + " is not a release; the API versions of mods are not checked.");
List<ModDiscovery.Candidate> candidates = Files.isDirectory(modsDirectory) List<ModDiscovery.Candidate> candidates = Files.isDirectory(modsDirectory)
@@ -95,12 +115,17 @@ public final class Forge
try (GameClasses gameClasses = GameClasses.open(gameJar)) try (GameClasses gameClasses = GameClasses.open(gameJar))
{ {
ModVerifier.verify(ordered, gameClasses, game); ModVerifier.verify(ordered, gameClasses, game);
this.mods = ModLoader.load(ordered, game, parent, gameClasses); this.mods = ModLoader.load(ordered, game, parent, gameClasses, this::services);
} }
catch (IOException e) catch (IOException e)
{ {
throw new ModLoadException("Cannot read the Project Zomboid jar '" + gameJar + "': " + e.getMessage(), e); throw new ModLoadException("Cannot read the Project Zomboid jar '" + gameJar + "': " + e.getMessage(), e);
} }
catch (ModLoadException | RuntimeException e)
{
this.stopThreads(Duration.ZERO);
throw e;
}
this.lifecycle.loaded(); this.lifecycle.loaded();
@@ -122,8 +147,26 @@ public final class Forge
} }
/** /**
* Calls {@link Mod#onStopping()} of every mod in reverse load order, once. Called on the * Posts {@link TickEvent} (only when a listener exists), then runs queued main-thread tasks
* shutdown thread. * within the budget. Main thread, once per frame of the main loop.
*/
public void tick()
{
if (this.events.hasListeners(TickEvent.class)) this.events.post(new TickEvent(this.queue.tick() + 1));
this.queue.drain();
}
/**
* Delivers {@code event} to the mods' listeners: main listeners run now on the calling
* thread, which must be the main thread; mod-thread listeners get a task on their mod's
* thread.
*/
public void post(Event event) { this.events.post(event); }
/**
* Once: calls {@link Mod#onStopping()} of every mod in reverse load order, then stops the
* mods' threads and events (see {@link #stopThreads}). Called on the shutdown thread.
*/ */
public void stopping() public void stopping()
{ {
@@ -133,5 +176,25 @@ public final class Forge
try { mod.mod().onStopping(); } try { mod.mod().onStopping(); }
catch (RuntimeException e) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onStopping() threw.", e); } catch (RuntimeException e) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onStopping() threw.", e); }
} }
this.stopThreads(this.settings.shutdownTimeout());
}
/**
* Rejects further main-thread tasks and cancels the queued ones, stops event delivery, and
* gives the mods' threads {@code timeout} to finish before they are interrupted.
*/
private void stopThreads(Duration timeout)
{
this.queue.close();
this.events.close();
this.threads.shutdown(timeout, this.logger);
}
private ModServices services(String id, System.Logger logger)
{
ModThreads.ModExecutors executors = this.threads.create(id, logger);
return new ModServices(this.events.forMod(id, executors.modThread(), logger), this.queue.forMod(id, logger), executors.modThread(), executors.async());
} }
} }
@@ -0,0 +1,70 @@
package dev.overlord.zomboidforge.core.config;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Global settings from {@code <forge>/forge.toml}. Every key is optional:
*
* <pre>
* [main_thread]
* budget_ms = 2 # time per tick for tasks that mods hand to the main thread
*
* [shutdown]
* timeout_s = 10 # how long mod threads get to finish when the server stops
* </pre>
*
* @param mainThreadBudget at least 1 ms
* @param shutdownTimeout 0 or more
*/
public record ForgeSettings(Duration mainThreadBudget, Duration shutdownTimeout)
{
public static final String FILE = "forge.toml";
public static final ForgeSettings DEFAULTS = new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10));
private record Document(Optional<MainThread> mainThread, Optional<Shutdown> shutdown) {}
private record MainThread(Optional<Long> budgetMs) {}
private record Shutdown(Optional<Long> timeoutS) {}
/**
* The settings in {@code file}, or {@link #DEFAULTS} when it does not exist.
*
* @throws IllegalArgumentException listing every problem: invalid TOML, unknown keys, values
* of the wrong type or out of range
*/
public static ForgeSettings read(Path file)
{
if (!Files.isRegularFile(file)) return ForgeSettings.DEFAULTS;
Map<String, Object> values;
try { values = TomlTree.parse(Files.readString(file)); }
catch (IOException e) { throw new IllegalArgumentException("Cannot read '" + file + "': " + e.getMessage(), e); }
RecordBinder binder = new RecordBinder();
@Nullable Document document = binder.record(values, Document.class, "");
List<String> problems = new ArrayList<>(binder.problems());
for (String key : binder.unknownKeys()) problems.add("Unknown key '" + key + "'.");
if (document == null || !problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems));
long budget = document.mainThread().flatMap(MainThread::budgetMs).orElse(ForgeSettings.DEFAULTS.mainThreadBudget().toMillis());
long timeout = document.shutdown().flatMap(Shutdown::timeoutS).orElse(ForgeSettings.DEFAULTS.shutdownTimeout().toSeconds());
if (budget < 1) problems.add("'main_thread.budget_ms' must be at least 1, found " + budget + ".");
if (timeout < 0) problems.add("'shutdown.timeout_s' must not be negative, found " + timeout + ".");
if (!problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems));
return new ForgeSettings(Duration.ofMillis(budget), Duration.ofSeconds(timeout));
}
}
@@ -30,7 +30,7 @@ public final class RecordBinder
public List<String> problems() { return List.copyOf(this.problems); } public List<String> problems() { return List.copyOf(this.problems); }
/** Dotted paths of keys that no record component reads, sorted. */ /** Dotted paths of keys that no record component reads, sorted. */
public Set<String> unknownKeys() { return Set.copyOf(this.unknownKeys); } public List<String> unknownKeys() { return List.copyOf(this.unknownKeys); }
/** Record component name to TOML key: {@code maxBalance} to {@code max_balance}, {@code httpPort} to {@code http_port}. */ /** Record component name to TOML key: {@code maxBalance} to {@code max_balance}, {@code httpPort} to {@code http_port}. */
public static String key(String component) public static String key(String component)
@@ -1,9 +1,13 @@
package dev.overlord.zomboidforge.core.mods; package dev.overlord.zomboidforge.core.mods;
import dev.overlord.zomboidforge.api.AsyncExecutor;
import dev.overlord.zomboidforge.api.Events;
import dev.overlord.zomboidforge.api.GameVersion; import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.api.MainThread;
import dev.overlord.zomboidforge.api.Mod; import dev.overlord.zomboidforge.api.Mod;
import dev.overlord.zomboidforge.api.ModConfig; import dev.overlord.zomboidforge.api.ModConfig;
import dev.overlord.zomboidforge.api.ModContext; import dev.overlord.zomboidforge.api.ModContext;
import dev.overlord.zomboidforge.api.ModThread;
import dev.overlord.zomboidforge.api.internal.ModBinding; import dev.overlord.zomboidforge.api.internal.ModBinding;
import dev.overlord.zomboidforge.core.ConsoleLogger; import dev.overlord.zomboidforge.core.ConsoleLogger;
import dev.overlord.zomboidforge.core.config.TomlModConfig; import dev.overlord.zomboidforge.core.config.TomlModConfig;
@@ -30,7 +34,18 @@ public final class ModLoader
/** A mod whose entry point was created and whose {@link Mod#onLoad()} returned. */ /** A mod whose entry point was created and whose {@link Mod#onLoad()} returned. */
public record LoadedMod(ModDescriptor descriptor, Path directory, ClassLoader classLoader, Mod mod) {} public record LoadedMod(ModDescriptor descriptor, Path directory, ClassLoader classLoader, Mod mod) {}
private record Context(String id, String version, GameVersion gameVersion, System.Logger logger, Path directory, ModConfig config) implements ModContext {} private record Context(
String id,
String version,
GameVersion gameVersion,
System.Logger logger,
Path directory,
ModConfig config,
Events events,
MainThread main,
ModThread modThread,
AsyncExecutor async
) implements ModContext {}
private ModLoader() {} private ModLoader() {}
@@ -40,9 +55,10 @@ public final class ModLoader
* @param parent parent of every mod's class loader * @param parent parent of every mod's class loader
* @param gameClasses classes of the Project Zomboid jar, visible to mods that declare * @param gameClasses classes of the Project Zomboid jar, visible to mods that declare
* {@code game} versions * {@code game} versions
* @param services creates each mod's threads and event registration
* @throws ModLoadException naming the mod that failed and why * @throws ModLoadException naming the mod that failed and why
*/ */
public static List<LoadedMod> load(List<ModDiscovery.Candidate> ordered, GameVersion game, ClassLoader parent, GameClasses gameClasses) throws ModLoadException public static List<LoadedMod> load(List<ModDiscovery.Candidate> ordered, GameVersion game, ClassLoader parent, GameClasses gameClasses, ModServices.Factory services) throws ModLoadException
{ {
Map<String, ModClassLoader> loaders = new HashMap<>(); Map<String, ModClassLoader> loaders = new HashMap<>();
List<LoadedMod> loaded = new ArrayList<>(); List<LoadedMod> loaded = new ArrayList<>();
@@ -63,13 +79,18 @@ public final class ModLoader
loaders.put(descriptor.id(), loader); loaders.put(descriptor.id(), loader);
System.Logger logger = new ConsoleLogger("ZomboidForge/" + descriptor.id()); System.Logger logger = new ConsoleLogger("ZomboidForge/" + descriptor.id());
ModServices provided = services.create(descriptor.id(), logger);
Context context = new Context( Context context = new Context(
descriptor.id(), descriptor.id(),
descriptor.version().toString(), descriptor.version().toString(),
game, game,
logger, logger,
candidate.directory(), candidate.directory(),
new TomlModConfig(candidate.config(), logger) new TomlModConfig(candidate.config(), logger),
provided.events(),
provided.main(),
provided.modThread(),
provided.async()
); );
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)));
@@ -0,0 +1,17 @@
package dev.overlord.zomboidforge.core.mods;
import dev.overlord.zomboidforge.api.AsyncExecutor;
import dev.overlord.zomboidforge.api.Events;
import dev.overlord.zomboidforge.api.MainThread;
import dev.overlord.zomboidforge.api.ModThread;
/** The threads and event registration of one mod, created before its entry point. */
public record ModServices(Events events, MainThread main, ModThread modThread, AsyncExecutor async)
{
/** Creates the services of one mod. */
@FunctionalInterface
public interface Factory
{
ModServices create(String id, System.Logger logger);
}
}
@@ -0,0 +1,173 @@
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.Subscription;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
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.
*/
public final class EventBus
{
/** Failures after which a listener is removed. */
static final int MAX_FAILURES = 10;
private final Map<Class<?>, Listener[]> listeners = 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); }
/** Whether any listener is registered for exactly this class. */
public boolean hasListeners(Class<? extends Event> type) { return this.listeners.containsKey(type); }
/**
* Delivers {@code event}: main listeners run now, on the calling thread, which must be the
* main thread; mod-thread listeners get a task on their mod's thread. A listener's exception
* is logged and never reaches the caller.
*/
public void post(Event event)
{
if (this.closed) return;
Listener[] listeners = this.listeners.get(event.getClass());
if (listeners == null) return;
for (Listener listener : listeners) listener.deliver(event);
}
/** Stops delivering events. */
public void close() { this.closed = true; }
private synchronized void add(Listener listener)
{
Listener[] current = this.listeners.getOrDefault(listener.type, new Listener[0]);
Listener[] updated = Arrays.copyOf(current, current.length + 1);
updated[current.length] = listener;
this.listeners.put(listener.type, updated);
}
private synchronized void remove(Listener listener)
{
Listener[] current = this.listeners.get(listener.type);
if (current == null) return;
Listener[] updated = Arrays.stream(current).filter(other -> other != listener).toArray(Listener[]::new);
if (updated.length == 0) this.listeners.remove(listener.type);
else this.listeners.put(listener.type, updated);
}
private final class ModEvents implements Events
{
private final String id;
private final Executor modThread;
private final System.Logger logger;
private ModEvents(String id, Executor modThread, System.Logger logger)
{
this.id = id;
this.modThread = modThread;
this.logger = logger;
}
@Override
public <E extends Event> Subscription onMain(Class<E> type, Consumer<? super E> listener) { return this.register(type, listener, null); }
@Override
public <E extends Event> Subscription onModThread(Class<E> type, Consumer<? super E> listener)
{
if (MainThreadEvent.class.isAssignableFrom(type))
throw new IllegalArgumentException("'" + type.getName() + "' is a main-thread event; listen with onMain().");
return this.register(type, listener, this.modThread);
}
private <E extends Event> Subscription register(Class<E> type, Consumer<? super E> 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 registered;
}
}
private final class Listener implements Subscription
{
private final String mod;
private final Class<?> type;
private final String kind;
private final Consumer<Object> action;
private final @Nullable Executor executor;
private final System.Logger logger;
private final AtomicInteger failures = new AtomicInteger();
private volatile boolean active = true;
private Listener(String mod, Class<?> type, Consumer<Object> action, @Nullable Executor executor, System.Logger logger)
{
this.mod = mod;
this.type = type;
this.kind = "listener " + type.getSimpleName();
this.action = action;
this.executor = executor;
this.logger = logger;
}
@Override
public void cancel()
{
this.active = false;
EventBus.this.remove(this);
}
private void deliver(Event event)
{
if (!this.active) return;
if (this.executor == null) {
this.invoke(event);
return;
}
try { this.executor.execute(() -> this.invoke(event)); }
catch (RejectedExecutionException e) { /* the mod's thread has been shut down */ }
}
private void invoke(Event event)
{
if (!this.active) return;
Throwable failure = ModTaskEvent.run(this.mod, this.kind, () -> this.action.accept(event));
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);
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.");
}
}
}
}
@@ -0,0 +1,209 @@
package dev.overlord.zomboidforge.core.runtime;
import dev.overlord.zomboidforge.api.MainThread;
import org.jetbrains.annotations.Nullable;
import java.time.Duration;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.RejectedExecutionException;
/**
* The main-thread tasks of every mod: one queue per mod, drained round-robin by
* {@link #drain()} once per tick until the time budget is used up. A task in progress is never
* interrupted, so the budget is a soft limit; at least one task runs per tick while any is
* queued.
*/
public final class MainThreadQueue
{
private record Task(Runnable action, @Nullable CompletableFuture<?> future) {}
private record Delayed(long due, long sequence, Task task) {}
private volatile long budgetNanos;
private volatile @Nullable Thread mainThread;
private volatile boolean closed;
private volatile ModQueue[] queues = new ModQueue[0];
private volatile long tick;
/** Index of the mod queue the next {@link #drain()} starts with; main thread only. */
private int next;
public MainThreadQueue(Duration budget) { this.budgetNanos = budget.toNanos(); }
/** Sets the time per {@link #drain()} for queued tasks. */
public void budget(Duration budget) { this.budgetNanos = budget.toNanos(); }
/** Makes the calling thread the main thread. */
public void bindToCurrentThread() { this.mainThread = Thread.currentThread(); }
public boolean isMainThread() { return Thread.currentThread() == this.mainThread; }
/** Number of the last frame {@link #drain()} ran for; 0 before the first. */
public long tick() { return this.tick; }
/** The {@link MainThread} of one mod; its tasks are tagged with {@code id}. */
public synchronized MainThread forMod(String id, System.Logger logger)
{
ModQueue queue = new ModQueue(id, logger);
ModQueue[] queues = Arrays.copyOf(this.queues, this.queues.length + 1);
queues[queues.length - 1] = queue;
this.queues = queues;
return queue;
}
/**
* Starts the next frame: moves due delayed tasks into the queues, then runs queued tasks
* round-robin until every queue is empty or the budget is used up. Main thread only.
*/
public void drain()
{
long deadline = System.nanoTime() + this.budgetNanos;
ModQueue[] queues = this.queues;
long tick = this.tick + 1;
this.tick = tick;
for (ModQueue queue : queues) queue.promote(tick);
int count = queues.length;
int index = count == 0 ? 0 : this.next % count;
int empty = 0;
while (empty < count && !this.closed)
{
ModQueue queue = queues[index];
index = (index + 1) % count;
Task task = queue.tasks.poll();
if (task == null) {
empty++;
continue;
}
empty = 0;
queue.run(task.action());
if (System.nanoTime() >= deadline) break;
}
this.next = index;
}
/** Rejects further tasks and cancels the queued ones (their futures are cancelled). Any thread. */
public void close()
{
this.closed = true;
for (ModQueue queue : this.queues) queue.cancelAll();
}
private final class ModQueue implements MainThread
{
private final String id;
private final System.Logger logger;
private final Queue<Task> tasks = new ConcurrentLinkedQueue<>();
private final PriorityQueue<Delayed> delayed = new PriorityQueue<>(Comparator.comparingLong(Delayed::due).thenComparingLong(Delayed::sequence));
/** Guarded by {@link #delayed}. */
private long sequence;
private ModQueue(String id, System.Logger logger)
{
this.id = id;
this.logger = logger;
}
@Override
public void execute(Runnable task)
{
Objects.requireNonNull(task, "task");
this.requireOpen();
if (MainThreadQueue.this.isMainThread()) this.run(task);
else this.enqueue(new Task(task, null));
}
@Override
public <T> CompletableFuture<T> submit(Callable<T> task)
{
Objects.requireNonNull(task, "task");
this.requireOpen();
CompletableFuture<T> future = new CompletableFuture<>();
Runnable action = () -> {
try { future.complete(task.call()); }
catch (Throwable t) { future.completeExceptionally(t); }
};
if (MainThreadQueue.this.isMainThread()) this.run(action);
else this.enqueue(new Task(action, future));
return future;
}
@Override
public void runLater(int ticks, Runnable task)
{
Objects.requireNonNull(task, "task");
if (ticks < 1) throw new IllegalArgumentException("'ticks' must be at least 1, found " + ticks + ".");
this.requireOpen();
synchronized (this.delayed) { this.delayed.add(new Delayed(MainThreadQueue.this.tick + ticks, this.sequence++, new Task(task, null))); }
if (MainThreadQueue.this.closed) this.cancelAll();
}
@Override
public boolean isMainThread() { return MainThreadQueue.this.isMainThread(); }
private void enqueue(Task task)
{
this.tasks.add(task);
// close() may have run between requireOpen() and add().
if (MainThreadQueue.this.closed) this.cancelAll();
}
private void promote(long tick)
{
synchronized (this.delayed)
{
while (!this.delayed.isEmpty() && this.delayed.element().due() <= tick) this.tasks.add(this.delayed.remove().task());
}
}
private void run(Runnable action)
{
Throwable failure = ModTaskEvent.run(this.id, "task", action);
if (failure != null) this.logger.log(System.Logger.Level.ERROR, "A main-thread task threw.", failure);
}
private void cancelAll()
{
for (Task task = this.tasks.poll(); task != null; task = this.tasks.poll())
{
CompletableFuture<?> future = task.future();
if (future != null) future.cancel(false);
}
synchronized (this.delayed) { this.delayed.clear(); }
}
private void requireOpen()
{
if (MainThreadQueue.this.closed) throw new RejectedExecutionException("The server is stopping; '" + this.id + "' cannot queue main-thread tasks.");
}
}
}
@@ -0,0 +1,59 @@
package dev.overlord.zomboidforge.core.runtime;
import org.jetbrains.annotations.Nullable;
import jdk.jfr.Category;
import jdk.jfr.Description;
import jdk.jfr.Label;
import jdk.jfr.Name;
import jdk.jfr.StackTrace;
/** JFR event for main-thread work of a mod: a queued task or an event listener. */
@Name("zomboidforge.ModTask")
@Label("Mod Task")
@Category("ZomboidForge")
@Description("Main-thread work of a mod: a queued task or an event listener")
@StackTrace(false)
final class ModTaskEvent extends jdk.jfr.Event
{
@Label("Mod")
String mod = "";
/** {@code task}, or {@code listener <event class>}. */
@Label("Kind")
String kind = "";
/**
* Runs {@code action} as a {@code zomboidforge.ModTask} event. Mod code must not end the
* calling thread's work, so failures are returned instead of thrown: runtime exceptions,
* missing classes or members ({@link LinkageError}), and stack overflows.
*
* @return the failure, or {@code null} when {@code action} returned normally
*/
static @Nullable Throwable run(String mod, String kind, Runnable action)
{
ModTaskEvent event = new ModTaskEvent();
event.begin();
try
{
action.run();
return null;
}
catch (RuntimeException | LinkageError | StackOverflowError e)
{
return e;
}
finally
{
event.end();
if (event.shouldCommit())
{
event.mod = mod;
event.kind = kind;
event.commit();
}
}
}
}
@@ -0,0 +1,228 @@
package dev.overlord.zomboidforge.core.runtime;
import dev.overlord.zomboidforge.api.AsyncExecutor;
import dev.overlord.zomboidforge.api.ModThread;
import org.jetbrains.annotations.Nullable;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* The own threads of every mod: one platform thread {@code zf-mod-<id>} that runs the mod's
* tasks in order, and virtual threads {@code zf-async-<id>-<n>} for blocking work. All threads
* are daemon threads, so they never keep the JVM alive.
*
* <p>Mods get them as {@link ModThread} and {@link AsyncExecutor}, which cannot shut the
* executors down; only {@link #shutdown} does.
*/
public final class ModThreads
{
/** The executors of one mod. */
public record ModExecutors(ModThread modThread, AsyncExecutor async) {}
/** The executors of one mod; plain fields, as the executors live until {@link #shutdown}. */
private static final class Entry
{
private final String id;
private final ModThreadExecutor modThread;
private final ExecutorService async;
private Entry(String id, ModThreadExecutor modThread, ExecutorService async)
{
this.id = id;
this.modThread = modThread;
this.async = async;
}
}
private final List<Entry> entries = new ArrayList<>();
/** Creates the executors of one mod. */
public synchronized ModExecutors create(String id, System.Logger logger)
{
Entry entry = new Entry(
id,
new ModThreadExecutor(id, logger),
Executors.newThreadPerTaskExecutor(
Thread.ofVirtual()
.name("zf-async-" + id + "-", 0)
.uncaughtExceptionHandler((thread, e) -> logger.log(System.Logger.Level.ERROR, "A task on '" + thread.getName() + "' threw.", e))
.factory()
)
);
this.entries.add(entry);
return new ModExecutors(new ModThreadHandle(entry.modThread), new AsyncHandle(entry.async));
}
/**
* Shuts every executor down: new tasks are rejected, delayed and periodic tasks of the mod
* threads are dropped, and running or queued tasks get until {@code timeout} (for all mods
* together) to finish. Threads still running then are interrupted.
*/
public synchronized void shutdown(Duration timeout, System.Logger logger)
{
long deadline = System.nanoTime() + timeout.toNanos();
for (Entry entry : this.entries)
{
entry.modThread.shutdown();
entry.async.shutdown();
}
for (Entry entry : this.entries)
{
// '&' instead of '&&': both executors get their share of the time.
boolean finished = ModThreads.await(entry.modThread, deadline) & ModThreads.await(entry.async, deadline);
if (!finished)
{
entry.modThread.shutdownNow();
entry.async.shutdownNow();
logger.log(System.Logger.Level.WARNING, "'" + entry.id + "': threads still running after " + timeout.toMillis() / 1000.0 + " s; interrupted.");
}
}
}
private static boolean await(ExecutorService executor, long deadline)
{
try
{
return executor.awaitTermination(Math.max(0, deadline - System.nanoTime()), TimeUnit.NANOSECONDS);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
return false;
}
}
/** {@code task} as a {@code Runnable} that completes {@code future} with its result or exception. */
private static <T> Runnable completing(Callable<T> task, CompletableFuture<T> future)
{
Objects.requireNonNull(task, "task");
return () -> {
try { future.complete(task.call()); }
catch (Throwable t) { future.completeExceptionally(t); }
};
}
/**
* Single daemon thread {@code zf-mod-<id>}. Every {@code Runnable} it runs through
* {@code execute}, {@code submit}, or {@code schedule...} is logged when it throws; the
* exception still reaches the task's future.
*/
private static final class ModThreadExecutor extends ScheduledThreadPoolExecutor
{
private final System.Logger logger;
/** The executor's thread, set when the thread is created. */
private volatile @Nullable Thread thread;
private ModThreadExecutor(String id, System.Logger logger)
{
super(1);
this.logger = logger;
this.setThreadFactory(task -> {
Thread created = new Thread(task, "zf-mod-" + id);
created.setDaemon(true);
this.thread = created;
return created;
});
this.setRemoveOnCancelPolicy(true);
this.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
this.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
}
// execute() and submit(Runnable) go through schedule(Runnable, ...).
@Override
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { return super.schedule(this.logged(command), delay, unit); }
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { return super.scheduleAtFixedRate(this.logged(command), initialDelay, period, unit); }
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { return super.scheduleWithFixedDelay(this.logged(command), initialDelay, delay, unit); }
private Runnable logged(Runnable command)
{
return () -> {
try
{
command.run();
}
catch (RuntimeException | Error e)
{
this.logger.log(System.Logger.Level.ERROR, "A task on the mod thread threw.", e);
throw e;
}
};
}
}
/** What a mod sees of its {@link ModThreadExecutor}. */
private static final class ModThreadHandle implements ModThread
{
private final ModThreadExecutor executor;
private ModThreadHandle(ModThreadExecutor executor) { this.executor = executor; }
@Override
public void execute(Runnable task) { this.executor.execute(task); }
@Override
public <T> CompletableFuture<T> submit(Callable<T> task)
{
CompletableFuture<T> future = new CompletableFuture<>();
this.executor.execute(ModThreads.completing(task, future));
return future;
}
@Override
public ScheduledFuture<?> schedule(Runnable task, Duration delay) { return this.executor.schedule(task, delay.toNanos(), TimeUnit.NANOSECONDS); }
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration initialDelay, Duration period) { return this.executor.scheduleAtFixedRate(task, initialDelay.toNanos(), period.toNanos(), TimeUnit.NANOSECONDS); }
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration initialDelay, Duration delay) { return this.executor.scheduleWithFixedDelay(task, initialDelay.toNanos(), delay.toNanos(), TimeUnit.NANOSECONDS); }
@Override
public boolean isModThread() { return Thread.currentThread() == this.executor.thread; }
}
/** What a mod sees of its virtual-thread executor. */
private static final class AsyncHandle implements AsyncExecutor
{
private final ExecutorService executor;
private AsyncHandle(ExecutorService executor) { this.executor = executor; }
@Override
public void execute(Runnable task) { this.executor.execute(task); }
@Override
public <T> CompletableFuture<T> submit(Callable<T> task)
{
CompletableFuture<T> future = new CompletableFuture<>();
this.executor.execute(ModThreads.completing(task, future));
return future;
}
}
}
@@ -0,0 +1,10 @@
/**
* Threads and events of loaded mods: the main-thread queue, each mod's own threads, and the
* event bus.
*
* @noinspection UnstableApiUsage, RedundantSuppression
*/
@NotNullByDefault
package dev.overlord.zomboidforge.core.runtime;
import org.jetbrains.annotations.NotNullByDefault;
@@ -1,5 +1,6 @@
package dev.overlord.zomboidforge.core; package dev.overlord.zomboidforge.core;
import dev.overlord.zomboidforge.api.Event;
import dev.overlord.zomboidforge.api.GameVersion; import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.core.mods.ModLoadException; import dev.overlord.zomboidforge.core.mods.ModLoadException;
import dev.overlord.zomboidforge.core.mods.ModVersion; import dev.overlord.zomboidforge.core.mods.ModVersion;
@@ -12,6 +13,7 @@ import org.junit.jupiter.api.io.TempDir;
import testmods.ContextMod; import testmods.ContextMod;
import testmods.Recorder; import testmods.Recorder;
import testmods.ThreadMod;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
@@ -20,6 +22,7 @@ import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.function.BooleanSupplier;
import java.util.stream.Stream; import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -220,4 +223,48 @@ class ForgeTest
} }
private static Object field(Object mod, String name) throws ReflectiveOperationException { return mod.getClass().getField(name).get(mod); } private static Object field(Object mod, String name) throws ReflectiveOperationException { return mod.getClass().getField(name).get(mod); }
@Test
void modsUseTheirThreadTheMainThreadAndEvents() throws Exception
{
TestMods.folder(this.mods, "threads", TestMods.toml("threads", ThreadMod.class.getName(), ""), Map.of(
"testmods/ThreadMod", TestMods.classFile(ThreadMod.class),
"testmods/ThreadMod$Greeting", TestMods.classFile(ThreadMod.Greeting.class)
));
Forge forge = this.load();
Object mod = forge.mods().getFirst().mod();
String main = Thread.currentThread().getName();
@SuppressWarnings("unchecked")
List<String> log = (List<String>) ForgeTest.field(mod, "log");
forge.started();
ForgeTest.await(() -> log.contains("work on zf-mod-threads"));
assertEquals(List.of("work on zf-mod-threads"), log, "the hand-off to main waits for the tick");
forge.tick();
assertEquals(1L, ForgeTest.field(mod, "ticks"));
assertEquals("result on " + main, log.getLast());
// The listener is registered for the Greeting class of the mod's own class loader.
Class<?> greeting = mod.getClass().getClassLoader().loadClass(ThreadMod.Greeting.class.getName());
forge.post((Event) greeting.getConstructor(String.class).newInstance("hi"));
ForgeTest.await(() -> log.contains("greeting hi on zf-mod-threads"));
forge.stopping();
assertEquals("stopping", log.getLast());
assertEquals(Lifecycle.Phase.STOPPING, forge.phase());
}
private static void await(BooleanSupplier condition) throws InterruptedException
{
long deadline = System.nanoTime() + 5_000_000_000L;
while (!condition.getAsBoolean())
{
if (System.nanoTime() > deadline) throw new AssertionError("Condition not met within 5 s.");
Thread.sleep(10);
}
}
} }
@@ -0,0 +1,33 @@
package dev.overlord.zomboidforge.core;
import org.jetbrains.annotations.Nullable;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ResourceBundle;
/** {@link System.Logger} that keeps every message as {@code "LEVEL: message"}, with {@code " (<exception>)"} when one is given. */
public final class RecordingLogger implements System.Logger
{
public final List<String> messages = Collections.synchronizedList(new ArrayList<>());
@Override
public String getName() { return "test"; }
@Override
public boolean isLoggable(Level level) { return true; }
@Override
public void log(Level level, @Nullable ResourceBundle bundle, @Nullable String message, @Nullable Throwable thrown)
{
this.messages.add(level.getName() + ": " + message + (thrown == null ? "" : " (" + thrown + ")"));
}
@Override
public void log(Level level, @Nullable ResourceBundle bundle, @Nullable String format, @Nullable Object @Nullable ... parameters)
{
this.log(level, bundle, format == null || parameters == null ? format : MessageFormat.format(format, parameters), (Throwable) null);
}
}
@@ -0,0 +1,55 @@
package dev.overlord.zomboidforge.core.config;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ForgeSettingsTest
{
@TempDir
Path directory;
private ForgeSettings read(String toml) throws Exception
{
Path file = this.directory.resolve(ForgeSettings.FILE);
Files.writeString(file, toml);
return ForgeSettings.read(file);
}
@Test
void defaultsWithoutFileOrKeys() throws Exception
{
assertEquals(ForgeSettings.DEFAULTS, ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE)));
assertEquals(ForgeSettings.DEFAULTS, this.read("[main_thread]\n"));
assertEquals(new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10)), ForgeSettings.DEFAULTS);
}
@Test
void readsEveryKey() throws Exception
{
assertEquals(
new ForgeSettings(Duration.ofMillis(5), Duration.ofSeconds(0)),
this.read("[main_thread]\nbudget_ms = 5\n\n[shutdown]\ntimeout_s = 0\n")
);
}
@Test
void reportsUnknownKeysAndInvalidValues()
{
IllegalArgumentException unknown = assertThrows(IllegalArgumentException.class, () -> this.read("[main_thread]\nbudget = 5\n[other]\n"));
assertEquals("Unknown key 'main_thread.budget'. Unknown key 'other'.", unknown.getMessage());
IllegalArgumentException range = assertThrows(IllegalArgumentException.class, () -> this.read("[main_thread]\nbudget_ms = 0\n[shutdown]\ntimeout_s = -1\n"));
assertEquals("'main_thread.budget_ms' must be at least 1, found 0. 'shutdown.timeout_s' must not be negative, found -1.", range.getMessage());
IllegalArgumentException type = assertThrows(IllegalArgumentException.class, () -> this.read("[shutdown]\ntimeout_s = \"10\"\n"));
assertEquals("'shutdown.timeout_s' must be an integer, found \"10\".", type.getMessage());
}
}
@@ -0,0 +1,105 @@
package dev.overlord.zomboidforge.core.runtime;
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.core.RecordingLogger;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
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 EventBusTest
{
private record Joined(String player) implements Event {}
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;
@Test
void deliversToMainListenersInOrderAndQueuesModThreadListeners()
{
Events a = this.bus.forMod("a", this.modThread, this.logger);
Events b = this.bus.forMod("b", this.modThread, this.logger);
a.onMain(Joined.class, event -> this.received.add("a main " + event.player()));
b.onModThread(Joined.class, event -> this.received.add("b mod thread " + event.player()));
b.onMain(Joined.class, event -> this.received.add("b main " + event.player()));
this.bus.post(new Joined("bob"));
assertEquals(List.of("a main bob", "b main bob"), this.received);
assertEquals(1, this.modTasks.size());
this.modTasks.getFirst().run();
assertEquals("b mod thread bob", this.received.getLast());
}
@Test
void matchesTheExactClassAndTracksListeners()
{
Events a = this.bus.forMod("a", this.modThread, this.logger);
Subscription subscription = a.onMain(TickEvent.class, event -> this.received.add("tick " + event.tick()));
assertTrue(this.bus.hasListeners(TickEvent.class));
assertFalse(this.bus.hasListeners(Joined.class));
this.bus.post(new Joined("bob"));
this.bus.post(new TickEvent(3));
subscription.cancel();
subscription.cancel();
this.bus.post(new TickEvent(4));
assertEquals(List.of("tick 3"), this.received);
assertFalse(this.bus.hasListeners(TickEvent.class));
}
@Test
void rejectsMainThreadEventsForTheModThread()
{
Events a = this.bus.forMod("a", this.modThread, this.logger);
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> a.onModThread(TickEvent.class, event -> {}));
assertEquals("'dev.overlord.zomboidforge.api.TickEvent' is a main-thread event; listen with onMain().", e.getMessage());
}
@Test
void removesListenersThatKeepFailing()
{
Events a = this.bus.forMod("a", this.modThread, this.logger);
a.onMain(Joined.class, event -> { throw new IllegalStateException("broken"); });
a.onMain(Joined.class, event -> this.received.add(event.player()));
for (int i = 0; i < EventBus.MAX_FAILURES + 2; i++) this.bus.post(new Joined("p" + i));
assertEquals(EventBus.MAX_FAILURES + 2, this.received.size(), "the other listener keeps receiving");
assertEquals(EventBus.MAX_FAILURES + 1, this.logger.messages.size());
assertEquals("ERROR: Listener for 'Joined' threw (failure 1 of 10). (java.lang.IllegalStateException: broken)", this.logger.messages.getFirst());
assertEquals("ERROR: Listener for 'Joined' removed after 10 failures.", this.logger.messages.getLast());
}
@Test
void deliversNothingAfterClose()
{
this.bus.forMod("a", this.modThread, this.logger).onMain(Joined.class, event -> this.received.add(event.player()));
this.bus.close();
this.bus.post(new Joined("bob"));
assertTrue(this.received.isEmpty());
}
}
@@ -0,0 +1,177 @@
package dev.overlord.zomboidforge.core.runtime;
import dev.overlord.zomboidforge.api.MainThread;
import dev.overlord.zomboidforge.core.RecordingLogger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
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;
/** The test thread is the main thread; other threads queue through a helper thread. */
class MainThreadQueueTest
{
private final RecordingLogger logger = new RecordingLogger();
private final List<String> ran = new ArrayList<>();
private MainThreadQueue queue;
@BeforeEach
void setUp()
{
this.queue = new MainThreadQueue(Duration.ofSeconds(10));
this.queue.bindToCurrentThread();
}
/** Runs {@code action} on another thread and waits for it. */
private static void fromOtherThread(Runnable action) throws InterruptedException
{
Thread thread = Thread.ofPlatform().start(action);
thread.join();
}
@Test
void runsTasksFromOtherThreadsOnTheNextTick() throws Exception
{
MainThread main = this.queue.forMod("a", this.logger);
MainThreadQueueTest.fromOtherThread(() -> {
assertFalse(main.isMainThread());
main.execute(() -> this.ran.add("a1 " + main.isMainThread()));
});
assertTrue(this.ran.isEmpty());
this.queue.drain();
assertEquals(List.of("a1 true"), this.ran);
assertEquals(1, this.queue.tick());
}
@Test
void runsImmediatelyOnTheMainThread() throws Exception
{
MainThread main = this.queue.forMod("a", this.logger);
main.execute(() -> this.ran.add("now"));
CompletableFuture<Integer> result = main.submit(() -> 42);
assertEquals(List.of("now"), this.ran);
assertEquals(42, result.getNow(0));
}
@Test
void drainsModsRoundRobin() throws Exception
{
MainThread a = this.queue.forMod("a", this.logger);
MainThread b = this.queue.forMod("b", this.logger);
MainThreadQueueTest.fromOtherThread(() -> {
for (int i = 1; i <= 3; i++) {
int n = i;
a.execute(() -> this.ran.add("a" + n));
}
b.execute(() -> this.ran.add("b1"));
});
this.queue.drain();
assertEquals(List.of("a1", "b1", "a2", "a3"), this.ran);
}
@Test
void stopsAtTheBudgetAndContinuesNextTick() throws Exception
{
this.queue.budget(Duration.ofMillis(1));
MainThread a = this.queue.forMod("a", this.logger);
MainThread b = this.queue.forMod("b", this.logger);
MainThreadQueueTest.fromOtherThread(() -> {
a.execute(() -> {
this.ran.add("a slow");
MainThreadQueueTest.sleep(5);
});
a.execute(() -> this.ran.add("a2"));
b.execute(() -> this.ran.add("b1"));
});
this.queue.drain();
assertEquals(List.of("a slow"), this.ran, "the slow task used up the budget");
this.queue.drain();
assertEquals(List.of("a slow", "b1", "a2"), this.ran, "the next tick starts with the next mod");
}
@Test
void runsDelayedTasksAfterTheirTicks()
{
MainThread a = this.queue.forMod("a", this.logger);
a.runLater(2, () -> this.ran.add("later 2"));
a.runLater(1, () -> this.ran.add("later 1"));
this.queue.drain();
assertEquals(List.of("later 1"), this.ran);
this.queue.drain();
assertEquals(List.of("later 1", "later 2"), this.ran);
assertThrows(IllegalArgumentException.class, () -> a.runLater(0, () -> {}));
}
@Test
void completesFuturesAndLogsFailedTasks() throws Exception
{
MainThread a = this.queue.forMod("a", this.logger);
List<CompletableFuture<Integer>> futures = new ArrayList<>();
MainThreadQueueTest.fromOtherThread(() -> {
futures.add(a.submit(() -> 7));
futures.add(a.submit(() -> { throw new IllegalStateException("submitted"); }));
a.execute(() -> { throw new IllegalStateException("executed"); });
});
this.queue.drain();
assertEquals(7, futures.get(0).get(1, TimeUnit.SECONDS));
ExecutionException e = assertThrows(ExecutionException.class, () -> futures.get(1).get(1, TimeUnit.SECONDS));
assertEquals("submitted", e.getCause().getMessage());
assertEquals(List.of("ERROR: A main-thread task threw. (java.lang.IllegalStateException: executed)"), this.logger.messages);
}
@Test
void closeCancelsQueuedTasksAndRejectsNewOnes() throws Exception
{
MainThread a = this.queue.forMod("a", this.logger);
List<CompletableFuture<Integer>> futures = new ArrayList<>();
MainThreadQueueTest.fromOtherThread(() -> futures.add(a.submit(() -> 7)));
a.runLater(1, () -> this.ran.add("later"));
this.queue.close();
this.queue.drain();
assertTrue(futures.getFirst().isCancelled());
assertTrue(this.ran.isEmpty());
assertThrows(RejectedExecutionException.class, () -> a.execute(() -> {}));
}
private static void sleep(long millis)
{
try { Thread.sleep(millis); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
}
@@ -0,0 +1,45 @@
package dev.overlord.zomboidforge.core.runtime;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import jdk.jfr.Recording;
import jdk.jfr.consumer.RecordedEvent;
import jdk.jfr.consumer.RecordingFile;
import java.nio.file.Path;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNull;
class ModTaskEventTest
{
@TempDir
Path directory;
@Test
void recordsModAndKindAndReturnsFailures() throws Exception
{
Path recording = this.directory.resolve("tasks.jfr");
try (Recording jfr = new Recording())
{
jfr.enable("zomboidforge.ModTask");
jfr.start();
assertNull(ModTaskEvent.run("shop", "task", () -> {}));
assertInstanceOf(IllegalStateException.class, ModTaskEvent.run("shop", "listener TickEvent", () -> { throw new IllegalStateException(); }));
jfr.stop();
jfr.dump(recording);
}
List<RecordedEvent> events = RecordingFile.readAllEvents(recording).stream()
.filter(event -> event.getEventType().getName().equals("zomboidforge.ModTask"))
.toList();
assertEquals(List.of("shop task", "shop listener TickEvent"), events.stream().map(event -> event.getString("mod") + " " + event.getString("kind")).toList());
}
}
@@ -0,0 +1,118 @@
package dev.overlord.zomboidforge.core.runtime;
import dev.overlord.zomboidforge.core.RecordingLogger;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
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 ModThreadsTest
{
private final ModThreads threads = new ModThreads();
private final RecordingLogger logger = new RecordingLogger();
@Test
void namesTheThreads() throws Exception
{
ModThreads.ModExecutors executors = this.threads.create("shop", this.logger);
Thread modThread = executors.modThread().submit(Thread::currentThread).get(5, TimeUnit.SECONDS);
Thread async = executors.async().submit(Thread::currentThread).get(5, TimeUnit.SECONDS);
boolean onModThread = executors.modThread().submit(() -> executors.modThread().isModThread()).get(5, TimeUnit.SECONDS);
assertEquals("zf-mod-shop", modThread.getName());
assertTrue(modThread.isDaemon());
assertTrue(onModThread);
assertFalse(executors.modThread().isModThread());
assertTrue(async.isVirtual());
assertTrue(async.getName().startsWith("zf-async-shop-"), async.getName());
this.threads.shutdown(Duration.ofSeconds(5), this.logger);
}
@Test
void logsExceptionsOfExecutedTasksAndCompletesSubmittedOnes() throws Exception
{
ModThreads.ModExecutors executors = this.threads.create("shop", this.logger);
CountDownLatch ran = new CountDownLatch(1);
executors.modThread().execute(() -> { throw new IllegalStateException("executed"); });
executors.modThread().execute(ran::countDown);
ran.await(5, TimeUnit.SECONDS);
CompletableFuture<Object> submitted = executors.modThread().submit(() -> { throw new IllegalStateException("submitted"); });
ExecutionException e = assertThrows(ExecutionException.class, () -> submitted.get(5, TimeUnit.SECONDS));
assertEquals("submitted", e.getCause().getMessage());
assertEquals(List.of("ERROR: A task on the mod thread threw. (java.lang.IllegalStateException: executed)"), this.logger.messages);
this.threads.shutdown(Duration.ofSeconds(5), this.logger);
}
@Test
void schedulesWithDurations() throws Exception
{
ModThreads.ModExecutors executors = this.threads.create("shop", this.logger);
CountDownLatch runs = new CountDownLatch(3);
executors.modThread().scheduleAtFixedRate(runs::countDown, Duration.ZERO, Duration.ofMillis(10));
assertTrue(runs.await(5, TimeUnit.SECONDS));
this.threads.shutdown(Duration.ofSeconds(5), this.logger);
}
@Test
void shutdownWaitsThenInterrupts() throws Exception
{
ModThreads.ModExecutors quick = this.threads.create("quick", this.logger);
ModThreads.ModExecutors stuck = this.threads.create("stuck", this.logger);
CountDownLatch started = new CountDownLatch(1);
CountDownLatch ended = new CountDownLatch(1);
AtomicBoolean interrupted = new AtomicBoolean();
AtomicBoolean finished = new AtomicBoolean();
quick.modThread().execute(() -> {
ModThreadsTest.sleep(50);
finished.set(true);
});
stuck.modThread().execute(() -> {
started.countDown();
try { Thread.sleep(60_000); }
catch (InterruptedException e) { interrupted.set(true); }
ended.countDown();
});
started.await(5, TimeUnit.SECONDS);
this.threads.shutdown(Duration.ofMillis(300), this.logger);
assertTrue(finished.get(), "running tasks get the timeout to finish");
assertTrue(ended.await(5, TimeUnit.SECONDS));
assertTrue(interrupted.get());
assertEquals(List.of("WARNING: 'stuck': threads still running after 0.3 s; interrupted."), this.logger.messages);
assertThrows(RejectedExecutionException.class, () -> quick.modThread().execute(() -> {}));
assertThrows(RejectedExecutionException.class, () -> quick.async().execute(() -> {}));
}
private static void sleep(long millis)
{
try { Thread.sleep(millis); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
}
@@ -0,0 +1,42 @@
package testmods;
import dev.overlord.zomboidforge.api.Event;
import dev.overlord.zomboidforge.api.Mod;
import dev.overlord.zomboidforge.api.TickEvent;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Entry point that tests package into a mod jar. Counts ticks, hands work from its own thread
* to the main thread, and listens for {@link Greeting} on its own thread.
*/
public final class ThreadMod extends Mod
{
/** Posted by tests. */
public record Greeting(String text) implements Event {}
/** What happened, with the name of the thread it happened on. */
public final List<String> log = new CopyOnWriteArrayList<>();
public volatile long ticks;
@Override
public void onLoad()
{
this.events().onMain(TickEvent.class, event -> this.ticks = event.tick());
this.events().onModThread(Greeting.class, event -> this.log.add("greeting " + event.text() + " on " + Thread.currentThread().getName()));
}
@Override
public void onServerStarted()
{
this.modThread().execute(() -> {
this.log.add("work on " + Thread.currentThread().getName());
this.main().execute(() -> this.log.add("result on " + Thread.currentThread().getName()));
});
}
@Override
public void onStopping() { this.log.add("stopping"); }
}