Compare commits
25
Commits
07dc3f0fad
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b71d163909 | ||
|
|
9f5871905a | ||
|
|
32fab0c1d4 | ||
|
|
a5766f3a1b | ||
|
|
22c74a0030 | ||
|
|
c79a90b88f | ||
|
|
9af951b4be | ||
|
|
9fcde10fed | ||
|
|
b10504e9af | ||
|
|
1664bb6f28 | ||
|
|
b4d70c3d3a | ||
|
|
7ac442c4f6 | ||
|
|
36ac320c9c | ||
|
|
7b721490cb | ||
|
|
8a8db34b69 | ||
|
|
28b3510c10 | ||
|
|
1576d8a38b | ||
|
|
68f090061f | ||
|
|
be08756c36 | ||
|
|
49af536786 | ||
|
|
9178d36168 | ||
|
|
e61026a3d4 | ||
|
|
99f4f49a7c | ||
|
|
43df96391c | ||
|
|
607d5b2b32 |
No files matched your search
+151
-35
@@ -5,54 +5,68 @@ described in the [README](README.md#mods).
|
||||
|
||||
## Project setup
|
||||
|
||||
A mod is a normal Gradle project with the ZomboidForge plugin. It needs JDK 25 (Project
|
||||
Zomboid's runtime); the plugin sets the Java toolchain to 25.
|
||||
A mod project starts as one file. It needs JDK 25 (Project Zomboid's runtime); the plugin sets
|
||||
the Java toolchain to 25.
|
||||
|
||||
`settings.gradle.kts`:
|
||||
1. Create a directory with this `settings.gradle.kts`, with your mod's id, version, and entry
|
||||
point:
|
||||
|
||||
```kotlin
|
||||
pluginManagement {
|
||||
repositories {
|
||||
maven("https://git.security-command.org/api/packages/overlord/maven")
|
||||
gradlePluginPortal()
|
||||
}
|
||||
repositories { maven("https://git.security-command.org/api/packages/overlord/maven") }
|
||||
}
|
||||
|
||||
dependencyResolutionManagement {
|
||||
repositories {
|
||||
maven("https://git.security-command.org/api/packages/overlord/maven")
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
rootProject.name = "shop"
|
||||
```
|
||||
|
||||
`build.gradle.kts`:
|
||||
|
||||
```kotlin
|
||||
plugins {
|
||||
id("dev.overlord.zomboidforge.mod") version "0.3.0" // the plugin's version is the API version
|
||||
id("dev.overlord.zomboidforge") version "0.6.0" // the plugin's version is the API version
|
||||
}
|
||||
|
||||
version = "1.2.0"
|
||||
|
||||
zomboidForge {
|
||||
id = "shop"
|
||||
version = "1.0.0"
|
||||
entrypoint = "com.example.shop.ShopMod"
|
||||
game("42") // only when the mod uses game classes
|
||||
dependsOn("economy", "2.1") // other mods: id and minimum version
|
||||
}
|
||||
```
|
||||
|
||||
2. Run in that directory (Linux, macOS, Windows; on Windows PowerShell 5.1 write `curl.exe`):
|
||||
|
||||
```
|
||||
curl -fsSL https://git.security-command.org/Overlord/ZomboidForge/raw/branch/master/zomboidforge.jsh | jshell -
|
||||
```
|
||||
|
||||
The command sets the newest ZomboidForge version in `settings.gradle.kts`, writes the Gradle
|
||||
wrapper (`gradlew`, `gradlew.bat`, `gradle/wrapper/`), creates `.gitignore` and the entry point
|
||||
class when they are missing, and builds the mod. It needs no installed Gradle.
|
||||
|
||||
The same command updates a project to the newest version; a given version goes in
|
||||
`-R-Dzomboidforge.version`:
|
||||
|
||||
```
|
||||
curl -fsSL https://git.security-command.org/Overlord/ZomboidForge/raw/branch/master/zomboidforge.jsh | jshell -R-Dzomboidforge.version=0.7.0 -
|
||||
```
|
||||
|
||||
It prints links to this document in the new version and to the changes since the old one, and
|
||||
ends with a build, so code that the new version breaks shows at once. Files other than the
|
||||
version line in `settings.gradle.kts` and the wrapper stay as they are.
|
||||
|
||||
The root project is named after the mod id. The plugin adds the API
|
||||
(`dev.overlord.zomboidforge:api`) as a compile-only dependency, and the game jar for mods that
|
||||
declare `game` versions. Default settings go into
|
||||
`src/main/resources/META-INF/zomboidforge/config.toml`.
|
||||
|
||||
Libraries and other mods go into an optional `build.gradle.kts`, which can also set any
|
||||
`zomboidForge { }` setting:
|
||||
|
||||
```kotlin
|
||||
dependencies {
|
||||
implementation("com.google.code.gson:gson:2.11.0") // libraries go into the mod's lib/
|
||||
forgeMods("com.example:economy:2.1") // other mods to compile against
|
||||
}
|
||||
```
|
||||
|
||||
The plugin adds the API (`dev.overlord.zomboidforge:api`) as a compile-only dependency, and the
|
||||
game jar for mods that declare `game` versions. Default settings go into
|
||||
`src/main/resources/META-INF/zomboidforge/config.toml`.
|
||||
zomboidForge {
|
||||
game("42") // only when the mod uses game classes
|
||||
dependsOn("economy", "2.1") // other mods: id and minimum version
|
||||
}
|
||||
```
|
||||
|
||||
### `zomboidForge { }`
|
||||
|
||||
@@ -61,7 +75,7 @@ game jar for mods that declare `game` versions. Default settings go into
|
||||
| `id` | (required) | lowercase letters, digits, single underscores; at most 32 characters |
|
||||
| `entrypoint` | (required) | the class that extends `Mod` |
|
||||
| `name` | the id | display name |
|
||||
| `version` | the project version | the mod's version |
|
||||
| `version` | (required) | the mod's version, such as `1.2.0` |
|
||||
| `api` | the plugin's version | ZomboidForge API version the mod is built against |
|
||||
| `game(...)` | none | supported Project Zomboid versions: `"42"`, `"42.21"`, `"42.21.0"` |
|
||||
| `dependsOn(id, version)` | none | another mod this one needs, with its minimum version |
|
||||
@@ -99,14 +113,15 @@ The game jar has to be one of the declared `game` versions; the check below fail
|
||||
### Tasks
|
||||
|
||||
| Task | Does |
|
||||
|----------------|---------------------------------------------------------------------------------------------|
|
||||
|---------------------|---------------------------------------------------------------------------------------------|
|
||||
| `build` | compiles, runs `checkMod`, and assembles the mod |
|
||||
| `checkMod` | the server's load checks, at build time (see [Checks at startup](#checks-at-startup)) |
|
||||
| `checkMod` | the server's load checks, at build time (see [checks at startup](#checks-at-startup)) |
|
||||
| `modFolder` | `build/mod/<id>/` with `<id>.jar` and `lib/`, as a server expects it in `<forge>/mods` |
|
||||
| `modZip` | the same as `build/distributions/<id>-<version>.zip` |
|
||||
| `runServer` | a ZomboidForge server in a container with the mod; Ctrl+C stops it after it saved the world |
|
||||
| `deployMod` | copies the mod folder into `deployDirectory`; keeps the server's `config.toml` of the mod |
|
||||
| `downloadGame` | installs the dedicated server for its game jar; runs only when needed |
|
||||
| `zomboidForgeSetup` | creates `.gitignore` and the entry point class when they are missing |
|
||||
|
||||
`runServer` is reachable from this machine only, unless `serverAddress` says otherwise. Without
|
||||
`adminPassword`, the first run generates a random admin password for the volume, prints it, and
|
||||
@@ -186,6 +201,25 @@ Methods of `Mod`, usable from the constructor on, and in field initializers:
|
||||
| `commands()` | `Commands` | admin commands for chat, the server console, and RCON |
|
||||
| `clientCommands()` | `ClientCommands` | server commands to clients, received by their Lua mods |
|
||||
|
||||
## Settings
|
||||
|
||||
`config().bind(Settings.class)` reads `config.toml` into a record. Keys are the component names
|
||||
in `snake_case` (`maxBalance` reads `max_balance`); defaults come from the jar's
|
||||
`META-INF/zomboidforge/config.toml`.
|
||||
|
||||
```java
|
||||
record Settings(
|
||||
@Key("max_hp_regen") int healthRegenPerHour, // keeps its key after a rename
|
||||
@Min(1) @Max(100) int maxPlayers, // bounds for numbers, also inside List, Map, Optional
|
||||
String greeting
|
||||
) {}
|
||||
```
|
||||
|
||||
A missing, mistyped, or out-of-bounds value stops the server, and the log lists every problem
|
||||
with its key (`'max_players' must be at most 100, found 250.`). `@Key` names are `snake_case`
|
||||
and differ within a record; `@Min`/`@Max` only fit numeric components and may be fractions
|
||||
(`@Max(0.5) double ratio`).
|
||||
|
||||
## Threads
|
||||
|
||||
Game objects belong to the server's main thread. Everything else should stay off it, because
|
||||
@@ -218,6 +252,47 @@ Listeners are matched by the event's exact class. Events that carry live game ob
|
||||
removed after ten failures; both `onMain` and `onModThread` return a `Subscription` to remove
|
||||
it earlier.
|
||||
|
||||
The same listeners as annotated methods (`dev.overlord.zomboidforge.api.annotations`):
|
||||
|
||||
```java
|
||||
@OnMain
|
||||
void onTick(TickEvent event) { ... }
|
||||
|
||||
@OnModThread
|
||||
void onGreeting(SomeEvent event) { ... }
|
||||
```
|
||||
|
||||
- **The entry point's methods** are registered after its constructor and before `onLoad()`, so
|
||||
they run before the listeners that `onLoad()` registers for the same event. Other objects
|
||||
opt in with `this.events().register(object)`, which returns one `Subscription` for all of
|
||||
their methods. Registering an object twice throws; the entry point is registered already.
|
||||
- **A listener method** returns `void` and has one parameter: the event class, not an
|
||||
interface or an abstract class. It may be static or private, and may be declared in a
|
||||
superclass. An override listens only when it carries the annotation itself.
|
||||
- **Order:** superclass methods first, the methods of one class by name. When two listeners of
|
||||
one event need a specific order, register them with `onMain` instead.
|
||||
- A method that breaks these rules stops the server with every problem in the log;
|
||||
`register` throws an `IllegalArgumentException` instead.
|
||||
|
||||
### 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
|
||||
@@ -248,9 +323,14 @@ public class HelloCommand extends CommandBase
|
||||
public void onLoad() { this.commands().register(HelloCommand.class); }
|
||||
```
|
||||
|
||||
Or `@RegisterCommand` on the class (`dev.overlord.zomboidforge.api.annotations`), without the
|
||||
call: ZomboidForge registers the annotated classes of the mod's own jar (not of `lib/`) by name,
|
||||
before `onLoad()`.
|
||||
|
||||
- **Registration** happens in the entry point's constructor or `onLoad()`; later calls throw.
|
||||
`register` checks the class and throws `IllegalArgumentException` listing every problem,
|
||||
which stops the server like any other exception in `onLoad()`.
|
||||
which stops the server like any other exception in `onLoad()`; an annotated class that breaks
|
||||
the rules stops it the same way.
|
||||
- **The class** is public and not abstract, with one public constructor
|
||||
`(String, Role, String, UdpConnection)`.
|
||||
- **Names** (`@CommandName`, repeatable for aliases) consist of letters, digits, and `_` and
|
||||
@@ -291,6 +371,16 @@ this.events().onMain(ClientCommandEvent.class, event ->
|
||||
});
|
||||
```
|
||||
|
||||
The same as an annotated listener method (see [Events](#events)), which filters and cancels:
|
||||
|
||||
```java
|
||||
@OnClientCommand(module = "Shop", command = "buy", cancel = true) // command optional: every command of the module
|
||||
void buy(ClientCommandEvent event) { ... }
|
||||
```
|
||||
|
||||
`cancel = true` cancels the event before the method runs, so Lua does not receive the command
|
||||
even when the method throws.
|
||||
|
||||
Server to client: `clientCommands().send(player, ...)` and `sendToAll(...)`; the Lua mod
|
||||
receives them in `Events.OnServerCommand`.
|
||||
|
||||
@@ -349,7 +439,9 @@ this.storage().transaction(() -> { // all or nothin
|
||||
| `Instant` | ISO-8601 text |
|
||||
| `byte[]` | blob |
|
||||
|
||||
Table and column names are `snake_case`: `lastPaid` is stored as `last_paid`.
|
||||
Table and column names are `snake_case`: `lastPaid` is stored as `last_paid`. `@Key("paid_at")`
|
||||
on a component sets the column name instead, so a renamed component keeps its column and data.
|
||||
`@Min`/`@Max` are for settings; storage ignores them.
|
||||
|
||||
When the record changes between versions of the mod:
|
||||
|
||||
@@ -367,6 +459,23 @@ Table<Balance> balances = this.storage().define("balances", Balance.class)
|
||||
.open();
|
||||
```
|
||||
|
||||
The same on the record (`dev.overlord.zomboidforge.api.annotations`), so `table(...)` is enough:
|
||||
|
||||
```java
|
||||
@Schema(version = 2)
|
||||
record Balance(long coins, @Nullable Instant lastPaid)
|
||||
{
|
||||
@Migrate(from = 1)
|
||||
static Balance fromV1(Row row) { return new Balance(row.getLong("coins"), null); }
|
||||
}
|
||||
|
||||
Table<Balance> balances = this.storage().table("balances", Balance.class);
|
||||
```
|
||||
|
||||
A `@Migrate` method is static, takes a `Row`, returns the record, and may be private. `define`
|
||||
starts from the annotations: `version(...)` replaces the `@Schema` version, and `migrate(...)`
|
||||
adds migrations. Each version has one migration at most; a second one throws.
|
||||
|
||||
Things to know:
|
||||
|
||||
1. Storage calls block. On the main thread they are only allowed during `onLoad`; once the
|
||||
@@ -391,6 +500,13 @@ mod and its libraries. The server does not start when a mod
|
||||
3. uses ZomboidForge classes outside the API, or
|
||||
4. contains classes in a ZomboidForge package, or a class with the name of a game class.
|
||||
|
||||
While it loads a mod, the server also checks the annotations: the entry point's listener and
|
||||
scheduled methods, `@Schema`/`@Migrate`/`@Key`/`@Min`/`@Max` on records, and the
|
||||
`@RegisterCommand` classes. `checkMod` runs the same rules on the built jar (records only when
|
||||
they carry one of these annotations), loading the classes without running any of their code.
|
||||
Objects passed to `events().register(...)` are only checked on the server, when they are
|
||||
registered.
|
||||
|
||||
Every problem of every mod is listed in the log.
|
||||
|
||||
## What a mod can see
|
||||
@@ -413,4 +529,4 @@ file system it can reach anything the server can, including other mods' data in
|
||||
|
||||
Main-thread tasks and event listener calls appear in JFR recordings as the event
|
||||
`zomboidforge.ModTask`, with the mod's id and the kind of work (`task`, or `listener` and the
|
||||
event class).
|
||||
event class, followed by `#<method>` for a listener method).
|
||||
@@ -39,7 +39,7 @@ podman run -d --name zomboidforge \
|
||||
Unset variables keep the value in the server `.ini` (or the game default).
|
||||
|
||||
| Variable | Default | |
|
||||
|----------------------|--------------------------|-----------------------------------------------------------------------------------------------------|
|
||||
|--------------------------------|--------------------------|-----------------------------------------------------------------------------------------------------------------------------|
|
||||
| `SERVER_NAME` | `zomboidforge` | Server config name (`/data/Server/<name>.ini`) |
|
||||
| `SERVER_PASSWORD` | | Password clients need to join (`.ini` `Password`) |
|
||||
| `PUBLIC` | | `true`/`false`: listed in the in-game server browser |
|
||||
@@ -56,8 +56,10 @@ Unset variables keep the value in the server `.ini` (or the game default).
|
||||
| `JVM_MIN_HEAP` | JVM default | `-Xms`; unused heap memory is returned to the system only down to this size |
|
||||
| `JVM_MAX_HEAP` | 75 % of the memory limit | `-Xmx`; `8g` when the container has no memory limit |
|
||||
| `JVM_UNCOMMIT_DELAY` | `60` | Seconds after which unused heap memory is returned to the system (`-XX:ZUncommitDelay`) |
|
||||
| `JVM_EXPERIMENTAL_PERFORMANCE` | `false` | `true`/`false`: `-XX:+UseCompactObjectHeaders` and `-XX:+UseTransparentHugePages` (see below) |
|
||||
| `STEAM` | `1` | `0` runs the server without Steam |
|
||||
| `SOFT_RESET` | | `true` starts once in soft reset mode (`-Dsoftreset`); unset it afterwards |
|
||||
| `ZF_EXPERIMENTAL_PERFORMANCE` | `false` | `true`/`false`: performance changes that alter timing or resource use (more threads, shorter waits); overrides `forge.toml` |
|
||||
|
||||
Notes:
|
||||
|
||||
@@ -75,6 +77,9 @@ Notes:
|
||||
rest stays for native memory. The startup briefly needs a large heap; with 8 players
|
||||
exploring, the heap held up to 4.4 GB of live data in tests. A limit below about 6 GB is
|
||||
not recommended. Without a limit the heap is `8g`, as in vanilla.
|
||||
- **Huge pages:** `JVM_EXPERIMENTAL_PERFORMANCE=true` maps the heap with transparent huge pages
|
||||
only when the host's `/sys/kernel/mm/transparent_hugepage/shmem_enabled` is `advise` or
|
||||
`always` (a container cannot change it); otherwise the JVM logs a warning and runs without them.
|
||||
- **Stopping:** `SIGTERM` triggers the game's own save-and-quit. Allow enough time for large worlds.
|
||||
|
||||
For local testing use `compose.yaml` (`podman compose up --build`, settings from `.env`).
|
||||
@@ -130,6 +135,9 @@ budget_ms = 2 # time per tick for tasks that mods hand to the main thread
|
||||
|
||||
[shutdown]
|
||||
timeout_s = 10 # time the mods' threads get to finish when the server stops
|
||||
|
||||
[features]
|
||||
experimental_performance = false # default false; ZF_EXPERIMENTAL_PERFORMANCE takes precedence when set
|
||||
```
|
||||
|
||||
### Mod development
|
||||
|
||||
@@ -32,6 +32,9 @@ publishing {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// Published as a compile-time dependency, so mods see the API's annotations; never in their lib/.
|
||||
compileOnlyApi(libs.jetbrains.annotations)
|
||||
|
||||
testImplementation(platform(libs.junit.bom))
|
||||
testImplementation(libs.junit.jupiter)
|
||||
testRuntimeOnly(libs.junit.platform.launcher)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
@@ -9,6 +11,7 @@ import java.util.concurrent.Executor;
|
||||
* task, named {@code zf-async-<id>-<n>}. ZomboidForge shuts it down when the server stops; tasks
|
||||
* submitted after that are rejected with a {@link java.util.concurrent.RejectedExecutionException}.
|
||||
*/
|
||||
@ApiStatus.NonExtendable
|
||||
public interface AsyncExecutor extends Executor
|
||||
{
|
||||
/** Runs {@code task} on a new virtual thread. An exception it throws is logged with the mod's id. */
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import org.jetbrains.annotations.Unmodifiable;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
@@ -42,7 +44,7 @@ public final class ClientCommandEvent implements MainThreadEvent, Cancellable
|
||||
|
||||
public String command() { return this.command; }
|
||||
|
||||
public Map<Object, Object> args() { return this.args; }
|
||||
public @Unmodifiable Map<Object, Object> args() { return this.args; }
|
||||
|
||||
@Override
|
||||
public void cancel() { this.cancelled = true; }
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
@@ -17,6 +19,7 @@ import java.util.Map;
|
||||
* sent on the main thread, at once when called there, otherwise with the mod's queued
|
||||
* main-thread tasks.
|
||||
*/
|
||||
@ApiStatus.NonExtendable
|
||||
public interface ClientCommands
|
||||
{
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import dev.overlord.zomboidforge.api.annotations.RegisterCommand;
|
||||
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
/**
|
||||
* Registration of admin commands. A registered command works wherever Project Zomboid's own
|
||||
* admin commands work: in the in-game chat ({@code /name}), the server console, and RCON. It
|
||||
@@ -21,11 +25,13 @@ package dev.overlord.zomboidforge.api;
|
||||
* Project Zomboid creates a new instance for every use and calls its {@code Command()}, whose
|
||||
* result is the reply.
|
||||
*/
|
||||
@ApiStatus.NonExtendable
|
||||
public interface Commands
|
||||
{
|
||||
/**
|
||||
* Registers {@code command}. Only on the main thread while the mod loads: in the entry point's
|
||||
* constructor or {@link Mod#onLoad()}.
|
||||
* constructor or {@link Mod#onLoad()}. Classes annotated with {@link RegisterCommand} are
|
||||
* registered without this call.
|
||||
*
|
||||
* @throws IllegalArgumentException when {@code command} does not meet the rules above, or is
|
||||
* registered already
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
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;
|
||||
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Registration of event listeners. Listeners of one event run in registration order. A listener
|
||||
* that throws is logged with the mod's id; one that throws repeatedly is removed.
|
||||
*/
|
||||
@ApiStatus.NonExtendable
|
||||
public interface Events
|
||||
{
|
||||
/**
|
||||
@@ -21,4 +30,35 @@ public interface Events
|
||||
* @throws IllegalArgumentException when {@code type} is a {@link MainThreadEvent}
|
||||
*/
|
||||
<E extends Event> Subscription onModThread(Class<E> type, Consumer<? super E> listener);
|
||||
|
||||
/**
|
||||
* Registers the methods of {@code listener} annotated with {@link OnMain},
|
||||
* {@link OnModThread}, or {@link OnClientCommand}, as {@link #onMain} and {@link #onModThread}
|
||||
* 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}. 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>
|
||||
* <li>may be static, private, and declared in a superclass of {@code listener}'s class.
|
||||
* An instance method that a subclass overrides listens only when the override carries
|
||||
* the annotation itself.</li>
|
||||
* </ul>
|
||||
*
|
||||
* 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 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
|
||||
*/
|
||||
Subscription register(Object listener);
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.Range;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
@@ -14,6 +17,7 @@ import java.util.concurrent.Executor;
|
||||
* main thread: {@code submit(...).thenAcceptAsync(result -> ..., modThread())} moves the
|
||||
* follow-up work back. The main thread must never wait for another thread's result.
|
||||
*/
|
||||
@ApiStatus.NonExtendable
|
||||
public interface MainThread extends Executor
|
||||
{
|
||||
/**
|
||||
@@ -37,7 +41,7 @@ public interface MainThread extends Executor
|
||||
*
|
||||
* @throws IllegalArgumentException when {@code ticks} is less than 1
|
||||
*/
|
||||
void runLater(int ticks, Runnable task);
|
||||
void runLater(@Range(from = 1, to = Integer.MAX_VALUE) int ticks, Runnable task);
|
||||
|
||||
/** Whether the calling thread is the main thread. */
|
||||
boolean isMainThread();
|
||||
|
||||
@@ -3,6 +3,9 @@ package dev.overlord.zomboidforge.api;
|
||||
import dev.overlord.zomboidforge.api.internal.ModBinding;
|
||||
import dev.overlord.zomboidforge.api.storage.ModStorage;
|
||||
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.NonBlocking;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
@@ -15,12 +18,21 @@ import java.nio.file.Path;
|
||||
*
|
||||
* <p>Lifecycle, in this order:
|
||||
* <ol>
|
||||
* <li>Listener methods: the methods annotated with
|
||||
* {@link dev.overlord.zomboidforge.api.annotations.OnMain OnMain},
|
||||
* {@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()} stops the server.
|
||||
* An exception thrown by the constructor or {@link #onLoad()}, or a listener method that breaks
|
||||
* the rules, stops the server.
|
||||
*/
|
||||
public abstract class Mod
|
||||
{
|
||||
@@ -42,6 +54,7 @@ public abstract class Mod
|
||||
public final String version() { return this.context.version(); }
|
||||
|
||||
/** Called once on the main thread, after the instance is created. */
|
||||
@ApiStatus.OverrideOnly
|
||||
@SuppressWarnings("RedundantThrows")
|
||||
public void onLoad() throws Exception {}
|
||||
|
||||
@@ -49,12 +62,15 @@ public abstract class Mod
|
||||
* Called once on the main thread, after the world is loaded, the network port is open, and
|
||||
* RCON is initialized; directly before the main loop starts.
|
||||
*/
|
||||
@ApiStatus.OverrideOnly
|
||||
@NonBlocking
|
||||
public void onServerStarted() {}
|
||||
|
||||
/**
|
||||
* Called once on the shutdown thread when the server stops, before the world is saved.
|
||||
* The main thread may still be finishing a tick. Mods are stopped in reverse load order.
|
||||
*/
|
||||
@ApiStatus.OverrideOnly
|
||||
public void onStopping() {}
|
||||
|
||||
/** The running Project Zomboid version. */
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import dev.overlord.zomboidforge.api.annotations.Key;
|
||||
import dev.overlord.zomboidforge.api.annotations.Max;
|
||||
import dev.overlord.zomboidforge.api.annotations.Min;
|
||||
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
@@ -8,8 +14,10 @@ import java.util.Optional;
|
||||
* default. The table {@code [forge]} belongs to ZomboidForge and is not part of these settings.
|
||||
*
|
||||
* <p>Keys are {@code snake_case}; record components and paths use the same names converted
|
||||
* from {@code camelCase} ({@code maxBalance} reads {@code max_balance}).
|
||||
* from {@code camelCase} ({@code maxBalance} reads {@code max_balance}), or the name of the
|
||||
* component's {@link Key}.
|
||||
*/
|
||||
@ApiStatus.NonExtendable
|
||||
public interface ModConfig
|
||||
{
|
||||
/**
|
||||
@@ -18,9 +26,13 @@ public interface ModConfig
|
||||
* wrappers), enums (by constant name), records (TOML tables), {@code List<T>},
|
||||
* {@code Map<String, T>} (tables with free keys), and {@code Optional<T>} for values that
|
||||
* may be missing. Every other component must have a value. Keys without a component are
|
||||
* logged as warnings.
|
||||
* logged as warnings. {@link Min} and {@link Max} bound numeric components.
|
||||
*
|
||||
* @throws IllegalStateException listing every missing or mistyped value
|
||||
* @throws IllegalStateException listing every missing, mistyped, or out-of-bounds value
|
||||
* @throws IllegalArgumentException when {@code type} has a component that configuration
|
||||
* values cannot have, an invalid or repeated {@link Key},
|
||||
* or {@link Min}/{@link Max} on a component that is not
|
||||
* numeric or with the minimum above the maximum
|
||||
*/
|
||||
<T extends Record> T bind(Class<T> type);
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
import dev.overlord.zomboidforge.api.storage.ModStorage;
|
||||
|
||||
import java.nio.file.Path;
|
||||
@@ -8,6 +10,7 @@ import java.nio.file.Path;
|
||||
* What ZomboidForge provides to one mod. Mods reach it through the methods of {@link Mod};
|
||||
* ZomboidForge implements it.
|
||||
*/
|
||||
@ApiStatus.NonExtendable
|
||||
public interface ModContext
|
||||
{
|
||||
/** The mod's id from {@code mod.toml}. */
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
@@ -12,6 +14,7 @@ import java.util.concurrent.ScheduledFuture;
|
||||
* that are rejected with a {@link java.util.concurrent.RejectedExecutionException}. It must not
|
||||
* touch game objects; that goes through {@code main()}.
|
||||
*/
|
||||
@ApiStatus.NonExtendable
|
||||
public interface ModThread extends Executor
|
||||
{
|
||||
/** Runs {@code task} on the mod thread. An exception it throws is logged with the mod's id. */
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package dev.overlord.zomboidforge.api;
|
||||
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
/** A registered event listener. */
|
||||
@ApiStatus.NonExtendable
|
||||
public interface Subscription
|
||||
{
|
||||
/** Removes the listener; it receives no further events. Calling it again has no effect. */
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package dev.overlord.zomboidforge.api.annotations;
|
||||
|
||||
import dev.overlord.zomboidforge.api.ModConfig;
|
||||
import dev.overlord.zomboidforge.api.storage.ModStorage;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* The key of a record component, instead of the one converted from its name ({@code maxBalance}
|
||||
* to {@code max_balance}): the {@code config.toml} key for {@link ModConfig#bind}, the column
|
||||
* name for {@link ModStorage} tables. A component keeps its key when it is renamed:
|
||||
*
|
||||
* <pre>{@code
|
||||
* record Settings(@Key("max_hp_regen") int healthRegenPerHour) {}
|
||||
* }</pre>
|
||||
*
|
||||
* The key is {@code snake_case}: lowercase letters, digits, and single underscores, starting with
|
||||
* a letter. Two components of a record cannot have the same key. For a storage record, giving an
|
||||
* existing component another key renames its column, which the table treats as a removed and a
|
||||
* new column, as when the component is renamed without {@code @Key}.
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.RECORD_COMPONENT)
|
||||
public @interface Key
|
||||
{
|
||||
String value();
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package dev.overlord.zomboidforge.api.annotations;
|
||||
|
||||
import dev.overlord.zomboidforge.api.ModConfig;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* The largest value a numeric component of a configuration record accepts; see {@link Min}.
|
||||
* {@link ModConfig#bind} reports a larger value in {@code config.toml} with its key.
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.RECORD_COMPONENT)
|
||||
public @interface Max
|
||||
{
|
||||
double value();
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package dev.overlord.zomboidforge.api.annotations;
|
||||
|
||||
import dev.overlord.zomboidforge.api.storage.Row;
|
||||
import dev.overlord.zomboidforge.api.storage.TableDefinition;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* A migration of a storage record, as {@link TableDefinition#migrate} adds one: turns a row stored
|
||||
* with schema version {@link #from} into the record. Declared in the record itself, as a static
|
||||
* method with one {@link Row} parameter that returns the record; it may be private. A record has
|
||||
* at most one migration per version, whether from this annotation or from
|
||||
* {@link TableDefinition#migrate}. See {@link Schema}.
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
public @interface Migrate
|
||||
{
|
||||
/** The stored schema version this method migrates from; at least 1. */
|
||||
int from();
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package dev.overlord.zomboidforge.api.annotations;
|
||||
|
||||
import dev.overlord.zomboidforge.api.ModConfig;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* The smallest value a numeric component of a configuration record accepts. {@link ModConfig#bind}
|
||||
* reports a smaller value in {@code config.toml} with its key, together with every other
|
||||
* problem. On a {@code List}, {@code Map}, or {@code Optional} component, it applies to each
|
||||
* value. The bound may be a fraction ({@code @Min(0.1)}); it is not {@code NaN}. Values are
|
||||
* compared as {@code double}. Storage records ignore it.
|
||||
*
|
||||
* <pre>{@code
|
||||
* record Settings(@Min(1) @Max(100) int maxPlayers) {}
|
||||
* }</pre>
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.RECORD_COMPONENT)
|
||||
public @interface Min
|
||||
{
|
||||
double value();
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package dev.overlord.zomboidforge.api.annotations;
|
||||
|
||||
import dev.overlord.zomboidforge.api.ClientCommandEvent;
|
||||
import dev.overlord.zomboidforge.api.Events;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Registers the method with {@link Events#onMain} for the {@link ClientCommandEvent}s of one
|
||||
* module, and optionally one command. The method has one parameter, a {@code ClientCommandEvent};
|
||||
* otherwise the rules of {@link Events#register(Object)} apply, and the method carries none of
|
||||
* the other listener annotations.
|
||||
*
|
||||
* <pre>{@code
|
||||
* @OnClientCommand(module = "Shop", command = "buy", cancel = true)
|
||||
* void buy(ClientCommandEvent event) { ... }
|
||||
* }</pre>
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
public @interface OnClientCommand
|
||||
{
|
||||
/** The Lua module, matched exactly; not blank. */
|
||||
String module();
|
||||
|
||||
/** The command, matched exactly; empty matches every command of the module. */
|
||||
String command() default "";
|
||||
|
||||
/**
|
||||
* Cancels the event before the method runs, so Lua's {@code OnClientCommand} does not
|
||||
* receive the command, also when the method throws.
|
||||
*/
|
||||
boolean cancel() default false;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package dev.overlord.zomboidforge.api.annotations;
|
||||
|
||||
import dev.overlord.zomboidforge.api.Events;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Registers the method with {@link Events#onMain} for the event type of its only parameter. Read
|
||||
* on the entry point before {@code onLoad()}, and on objects passed to
|
||||
* {@link Events#register(Object)}, which lists the rules for the method.
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
public @interface OnMain {}
|
||||
@@ -0,0 +1,19 @@
|
||||
package dev.overlord.zomboidforge.api.annotations;
|
||||
|
||||
import dev.overlord.zomboidforge.api.Events;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Registers the method with {@link Events#onModThread} for the event type of its only parameter.
|
||||
* Read on the entry point before {@code onLoad()}, and on objects passed to
|
||||
* {@link Events#register(Object)}, which lists the rules for the method.
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
public @interface OnModThread {}
|
||||
@@ -0,0 +1,28 @@
|
||||
package dev.overlord.zomboidforge.api.annotations;
|
||||
|
||||
import dev.overlord.zomboidforge.api.Commands;
|
||||
import dev.overlord.zomboidforge.api.Mod;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Registers the class as an admin command, as {@link Commands#register} does, while the mod
|
||||
* loads: after the entry point's listener methods and before {@link Mod#onLoad()}. Only classes
|
||||
* in the mod's own jar are found, not those of its libraries; several are registered in the
|
||||
* order of their names. The class follows the rules of {@link Commands}.
|
||||
*
|
||||
* <pre>{@code
|
||||
* @RegisterCommand
|
||||
* @CommandName(name = "zfhello")
|
||||
* @RequiredCapability(requiredCapability = Capability.LoginOnServer)
|
||||
* public class HelloCommand extends CommandBase { ... }
|
||||
* }</pre>
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.TYPE)
|
||||
public @interface RegisterCommand {}
|
||||
@@ -0,0 +1,35 @@
|
||||
package dev.overlord.zomboidforge.api.annotations;
|
||||
|
||||
import dev.overlord.zomboidforge.api.storage.ModStorage;
|
||||
import dev.overlord.zomboidforge.api.storage.TableDefinition;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* The schema version of a storage record, read by {@link ModStorage#table} and
|
||||
* {@link ModStorage#define}; {@link TableDefinition#version} overrides it. Records without it
|
||||
* have version 1. The migrations from older versions are the record's {@link Migrate} methods.
|
||||
*
|
||||
* <pre>{@code
|
||||
* @Schema(version = 2)
|
||||
* record Balance(long coins, @Nullable Instant lastPaid)
|
||||
* {
|
||||
* @Migrate(from = 1)
|
||||
* static Balance fromV1(Row row) {
|
||||
* return new Balance(row.getLong("coins"), null);
|
||||
* }
|
||||
* }
|
||||
* }</pre>
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.TYPE)
|
||||
public @interface Schema
|
||||
{
|
||||
/** At least 1. */
|
||||
int version();
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* Annotations that stand for calls a mod can also make through the services of
|
||||
* {@link dev.overlord.zomboidforge.api.Mod}.
|
||||
*
|
||||
* @noinspection UnstableApiUsage, RedundantSuppression
|
||||
*/
|
||||
@NotNullByDefault
|
||||
package dev.overlord.zomboidforge.api.annotations;
|
||||
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
@@ -1,5 +1,11 @@
|
||||
package dev.overlord.zomboidforge.api.storage;
|
||||
|
||||
import dev.overlord.zomboidforge.api.annotations.Migrate;
|
||||
import dev.overlord.zomboidforge.api.annotations.Schema;
|
||||
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.Blocking;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
@@ -16,12 +22,26 @@ import java.util.function.Supplier;
|
||||
* once the server runs they throw an {@link IllegalStateException}, so database I/O never costs
|
||||
* tick time. Use {@code modThread()} or {@code async()}.
|
||||
*/
|
||||
@ApiStatus.NonExtendable
|
||||
public interface ModStorage
|
||||
{
|
||||
/** Opens the table {@code name} with schema version 1 and no migrations. */
|
||||
/**
|
||||
* Opens the table {@code name} with the schema version and migrations that {@code type}
|
||||
* declares with {@link Schema} and {@link Migrate}; without them, version 1 and no migrations.
|
||||
*
|
||||
* @throws IllegalArgumentException when the name, or a {@link Schema} or {@link Migrate} of
|
||||
* {@code type}, is invalid
|
||||
*/
|
||||
@Blocking
|
||||
<R extends Record> Table<R> table(String name, Class<R> type);
|
||||
|
||||
/** A table with a schema version and migrations; see {@link TableDefinition}. */
|
||||
/**
|
||||
* A table to open with a schema version and migrations, starting from those of
|
||||
* {@link Schema} and {@link Migrate} on {@code type}; see {@link TableDefinition}.
|
||||
*
|
||||
* @throws IllegalArgumentException when the name, or a {@link Schema} or {@link Migrate} of
|
||||
* {@code type}, is invalid
|
||||
*/
|
||||
<R extends Record> TableDefinition<R> define(String name, Class<R> type);
|
||||
|
||||
/**
|
||||
@@ -32,8 +52,10 @@ public interface ModStorage
|
||||
* other threads, for example with {@code main().submit(...).join()}. A backup waits at most
|
||||
* 10 seconds for it and then runs without pausing storage.
|
||||
*/
|
||||
@Blocking
|
||||
void transaction(Runnable work);
|
||||
|
||||
/** Like {@link #transaction(Runnable)}, returning the result of {@code work}. */
|
||||
@Blocking
|
||||
<T> T transaction(Supplier<T> work);
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package dev.overlord.zomboidforge.api.storage;
|
||||
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.jetbrains.annotations.Unmodifiable;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
@@ -10,12 +12,13 @@ import java.util.Set;
|
||||
* numbers as {@code Double}, texts (also UUIDs, instants, and enum constants) as
|
||||
* {@code String}, bytes as {@code byte[]}.
|
||||
*/
|
||||
@ApiStatus.NonExtendable
|
||||
public interface Row
|
||||
{
|
||||
String key();
|
||||
|
||||
/** The names of the stored columns. */
|
||||
Set<String> columns();
|
||||
@Unmodifiable Set<String> columns();
|
||||
|
||||
/** The stored value, or {@code null} when it is null. @throws IllegalArgumentException for an unknown column */
|
||||
@Nullable Object get(String column);
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
package dev.overlord.zomboidforge.api.storage;
|
||||
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.Blocking;
|
||||
import org.jetbrains.annotations.Unmodifiable;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -13,6 +17,8 @@ import java.util.function.UnaryOperator;
|
||||
* unless it runs inside {@link ModStorage#transaction}. Calls block; on the main thread they
|
||||
* are only allowed during startup.
|
||||
*/
|
||||
@ApiStatus.NonExtendable
|
||||
@Blocking
|
||||
public interface Table<R extends Record>
|
||||
{
|
||||
/** Stores {@code value} under {@code key}, replacing an existing row. */
|
||||
@@ -24,7 +30,7 @@ public interface Table<R extends Record>
|
||||
Optional<R> get(String key);
|
||||
|
||||
/** The rows of the given keys that exist. */
|
||||
Map<String, R> getAll(Collection<String> keys);
|
||||
@Unmodifiable Map<String, R> getAll(Collection<String> keys);
|
||||
|
||||
boolean contains(String key);
|
||||
|
||||
@@ -35,7 +41,7 @@ public interface Table<R extends Record>
|
||||
int deleteAll(Collection<String> keys);
|
||||
|
||||
/** Every key, sorted. */
|
||||
List<String> keys();
|
||||
@Unmodifiable List<String> keys();
|
||||
|
||||
/**
|
||||
* Calls {@code action} for every row, sorted by key, without loading all rows at once.
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
package dev.overlord.zomboidforge.api.storage;
|
||||
|
||||
import dev.overlord.zomboidforge.api.annotations.Migrate;
|
||||
import dev.overlord.zomboidforge.api.annotations.Schema;
|
||||
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.Blocking;
|
||||
import org.jetbrains.annotations.Range;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* A table to open with a schema version and migrations:
|
||||
* A table to open with a schema version and migrations. It starts from the record's
|
||||
* {@link Schema} and {@link Migrate} methods, if any; the calls below add to them:
|
||||
*
|
||||
* <pre>{@code
|
||||
* Table<Balance> balances = this.storage().define("balances", Balance.class)
|
||||
@@ -12,15 +20,19 @@ import java.util.function.Function;
|
||||
* .open();
|
||||
* }</pre>
|
||||
*/
|
||||
@ApiStatus.NonExtendable
|
||||
public interface TableDefinition<R extends Record>
|
||||
{
|
||||
/** Schema version of the record, at least 1. Default: 1. */
|
||||
TableDefinition<R> version(int version);
|
||||
/** Schema version of the record, at least 1. Default: the record's {@link Schema}, or 1. */
|
||||
TableDefinition<R> version(@Range(from = 1, to = Integer.MAX_VALUE) int version);
|
||||
|
||||
/**
|
||||
* How to turn a row stored with schema version {@code from} into the current record. Needed
|
||||
* when the stored version is older than {@link #version} or the record changed in a way that
|
||||
* cannot be applied without data.
|
||||
*
|
||||
* @throws IllegalArgumentException when a migration from {@code from} exists already, also one
|
||||
* from a {@link Migrate} method of the record
|
||||
*/
|
||||
TableDefinition<R> migrate(int from, Function<Row, R> migration);
|
||||
|
||||
@@ -29,5 +41,6 @@ public interface TableDefinition<R extends Record>
|
||||
*
|
||||
* @throws StorageException when the stored table does not match and no migration applies
|
||||
*/
|
||||
@Blocking
|
||||
Table<R> open();
|
||||
}
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Publishes the mod API (dev.overlord.zomboidforge:api), the mod tools (mod-tools), and the
|
||||
# Gradle plugin (dev.overlord.zomboidforge.mod) to the Maven registry of the ZomboidForge Gitea,
|
||||
# in the version of the v* git tag on HEAD, without the "v".
|
||||
# Gradle plugin (dev.overlord.zomboidforge) to the Maven registry of the ZomboidForge Gitea, in
|
||||
# the version of the v* git tag on HEAD, without the "v".
|
||||
#
|
||||
# A pre-release version (containing "-", e.g. 0.3.0-rc.1) is built and tested but never
|
||||
# published. Without a v* tag on HEAD nothing is published.
|
||||
|
||||
+3
-1
@@ -38,7 +38,9 @@ public final class B42PatchSet implements PatchSet
|
||||
new ZipBackupWaitPerformancePatch(),
|
||||
new ServerPlayersVehiclesRoundPerformancePatch(),
|
||||
new ServerPlayersVehiclesStopPerformancePatch(),
|
||||
new ServerPlayerDBSaveWaitPerformancePatch()
|
||||
new ServerPlayerDBSaveWaitPerformancePatch(),
|
||||
new GameServerAssetLoadingPerformancePatch(),
|
||||
new ServerMapQuitSleepPerformancePatch()
|
||||
);
|
||||
|
||||
@Override
|
||||
|
||||
+6
-1
@@ -13,7 +13,12 @@ import java.util.List;
|
||||
*
|
||||
* <pre>{@code
|
||||
* if (!ClientCommandHooks.onClientCommand(module, command, player, tbl))
|
||||
* LuaEventManager.triggerEvent("OnClientCommand", module, command, player, tbl);
|
||||
* {
|
||||
* LuaEventManager.triggerEvent(
|
||||
* "OnClientCommand", module,
|
||||
* command, player, tbl
|
||||
* );
|
||||
* }
|
||||
* }</pre>
|
||||
*
|
||||
* The arguments are the method's local variables of these names.
|
||||
|
||||
-1
@@ -15,7 +15,6 @@ import java.util.List;
|
||||
*/
|
||||
public final class CommandListPatch extends ReturnHookPatch
|
||||
{
|
||||
/** The whole method: {@code getstatic childrenClasses}, {@code areturn}. */
|
||||
private static final Anchor.Sequence ANCHOR = new Anchor.Sequence(
|
||||
new Anchor.Method("getSubClasses", "()[Ljava/lang/Class;"),
|
||||
new Anchor.Instruction.Opcode(Opcodes.GETSTATIC),
|
||||
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.Hook;
|
||||
import dev.overlord.zomboidforge.patcher.patches.PerformancePatch;
|
||||
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.MethodInsnNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
|
||||
/**
|
||||
* Replaces the update call of the asset loop in {@code GameServer.doMinimumInit}:
|
||||
*
|
||||
* <pre>{@code
|
||||
* while (GameWindow.fileSystem.hasWork()) {
|
||||
* // GameWindow.fileSystem.updateAsyncTransactions()
|
||||
* AssetLoadingHooks.updateAsyncTransactions(GameWindow.fileSystem);
|
||||
* }
|
||||
* }</pre>
|
||||
*
|
||||
* With the feature {@code experimental_performance} the hook grows the loader pool to one thread
|
||||
* per CPU but one and parks the main thread between updates instead of spinning. The
|
||||
* per-frame call in {@code GameServer.main} stays.
|
||||
*/
|
||||
public final class GameServerAssetLoadingPerformancePatch extends PerformancePatch
|
||||
{
|
||||
private static final String FILE_SYSTEM = "zombie/fileSystem/FileSystem";
|
||||
|
||||
private static final Anchor.Call ANCHOR = new Anchor.Call(
|
||||
new Anchor.Method("doMinimumInit", "()V"),
|
||||
GameServerAssetLoadingPerformancePatch.FILE_SYSTEM, "updateAsyncTransactions", "()V"
|
||||
);
|
||||
|
||||
private static final Hook HOOK = new Hook(
|
||||
"dev/overlord/zomboidforge/compat/b42/hooks/AssetLoadingHooks", "updateAsyncTransactions", "(L" + GameServerAssetLoadingPerformancePatch.FILE_SYSTEM + ";)V"
|
||||
);
|
||||
|
||||
public GameServerAssetLoadingPerformancePatch() {
|
||||
super("zombie/network/GameServer", GameServerAssetLoadingPerformancePatch.ANCHOR, GameServerAssetLoadingPerformancePatch.HOOK);
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Override
|
||||
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
|
||||
|
||||
@Override
|
||||
public void apply(ClassNode node)
|
||||
{
|
||||
MethodNode method = GameServerAssetLoadingPerformancePatch.ANCHOR.in().resolve(node);
|
||||
MethodInsnNode update = GameServerAssetLoadingPerformancePatch.ANCHOR.resolve(node);
|
||||
|
||||
if (update.getOpcode() != Opcodes.INVOKEVIRTUAL)
|
||||
throw new IllegalStateException("'" + node.name + ".doMinimumInit': 'FileSystem.updateAsyncTransactions' is not called virtually.");
|
||||
|
||||
// The hook takes the receiver of the virtual call as its argument: the stack is unchanged.
|
||||
method.instructions.set(update, new MethodInsnNode(Opcodes.INVOKESTATIC, GameServerAssetLoadingPerformancePatch.HOOK.owner(),
|
||||
GameServerAssetLoadingPerformancePatch.HOOK.name(), GameServerAssetLoadingPerformancePatch.HOOK.desc(), false));
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.Hook;
|
||||
import dev.overlord.zomboidforge.patcher.patches.ThreadSleepPerformancePatch;
|
||||
|
||||
/**
|
||||
* {@code ServerMap.QueuedQuit()} sleeps 5 s after the world save and the {@code ServerQuit}
|
||||
* broadcast, so the clients can disconnect. The sleep becomes {@code QuitHooks.quitSleep}. With
|
||||
* the feature {@code experimental_performance} enabled, the shutdown continues as soon as no
|
||||
* client is connected, after at most 5s. With the feature disabled, it keeps the vanilla sleep.
|
||||
*/
|
||||
public final class ServerMapQuitSleepPerformancePatch extends ThreadSleepPerformancePatch
|
||||
{
|
||||
private static final Hook HOOK = new Hook("dev/overlord/zomboidforge/compat/b42/hooks/QuitHooks", "quitSleep", "(J)V");
|
||||
|
||||
public ServerMapQuitSleepPerformancePatch() {
|
||||
super("zombie/network/ServerMap", new Anchor.Method("QueuedQuit", "()V"), 1, ServerMapQuitSleepPerformancePatch.HOOK);
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Override
|
||||
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.objectweb.asm.Label;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.MethodInsnNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
|
||||
import static org.objectweb.asm.Opcodes.ACC_STATIC;
|
||||
import static org.objectweb.asm.Opcodes.GETSTATIC;
|
||||
import static org.objectweb.asm.Opcodes.GOTO;
|
||||
import static org.objectweb.asm.Opcodes.IFEQ;
|
||||
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
|
||||
import static org.objectweb.asm.Opcodes.RETURN;
|
||||
import static org.objectweb.asm.Opcodes.V25;
|
||||
|
||||
class GameServerAssetLoadingPerformancePatchTest
|
||||
{
|
||||
private static final String GAME_SERVER = "zombie/network/GameServer";
|
||||
private static final String FILE_SYSTEM = "zombie/fileSystem/FileSystem";
|
||||
|
||||
/**
|
||||
* {@code GameServer} with the loop of {@code doMinimumInit} and the per-frame call of
|
||||
* {@code main}: {@code while (GameWindow.fileSystem.hasWork()) GameWindow.fileSystem.updateAsyncTransactions();}
|
||||
* and {@code GameWindow.fileSystem.updateAsyncTransactions();}.
|
||||
*/
|
||||
private static ClassNode gameServer()
|
||||
{
|
||||
ClassNode node = new ClassNode();
|
||||
node.visit(V25, ACC_PUBLIC, GameServerAssetLoadingPerformancePatchTest.GAME_SERVER, null, "java/lang/Object", null);
|
||||
|
||||
MethodVisitor init = node.visitMethod(ACC_PUBLIC | ACC_STATIC, "doMinimumInit", "()V", null, null);
|
||||
Label check = new Label();
|
||||
Label end = new Label();
|
||||
init.visitLabel(check);
|
||||
init.visitFieldInsn(GETSTATIC, "zombie/GameWindow", "fileSystem", "L" + GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM + ";");
|
||||
init.visitMethodInsn(INVOKEVIRTUAL, GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM, "hasWork", "()Z", false);
|
||||
init.visitJumpInsn(IFEQ, end);
|
||||
init.visitFieldInsn(GETSTATIC, "zombie/GameWindow", "fileSystem", "L" + GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM + ";");
|
||||
init.visitMethodInsn(INVOKEVIRTUAL, GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM, "updateAsyncTransactions", "()V", false);
|
||||
init.visitJumpInsn(GOTO, check);
|
||||
init.visitLabel(end);
|
||||
init.visitInsn(RETURN);
|
||||
init.visitMaxs(0, 0);
|
||||
|
||||
MethodVisitor main = node.visitMethod(ACC_PUBLIC | ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
|
||||
main.visitFieldInsn(GETSTATIC, "zombie/GameWindow", "fileSystem", "L" + GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM + ";");
|
||||
main.visitMethodInsn(INVOKEVIRTUAL, GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM, "updateAsyncTransactions", "()V", false);
|
||||
main.visitInsn(RETURN);
|
||||
main.visitMaxs(0, 0);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
private static List<String> calls(ClassNode node, String name)
|
||||
{
|
||||
MethodNode method = node.methods.stream().filter(candidate -> candidate.name.equals(name)).findFirst().orElseThrow();
|
||||
List<String> calls = new ArrayList<>();
|
||||
|
||||
for (AbstractInsnNode instruction : method.instructions) {
|
||||
if (instruction instanceof MethodInsnNode call) calls.add(call.owner.substring(call.owner.lastIndexOf('/') + 1) + "." + call.name + call.desc);
|
||||
}
|
||||
|
||||
return calls;
|
||||
}
|
||||
|
||||
@Test
|
||||
void anchorMatchesTheTarget()
|
||||
{
|
||||
new GameServerAssetLoadingPerformancePatch().anchor().verify(GameServerAssetLoadingPerformancePatchTest.gameServer());
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacesTheUpdateInTheStartupLoopOnly()
|
||||
{
|
||||
ClassNode node = GameServerAssetLoadingPerformancePatchTest.gameServer();
|
||||
new GameServerAssetLoadingPerformancePatch().apply(node);
|
||||
|
||||
assertEquals(
|
||||
List.of("FileSystem.hasWork()Z", "AssetLoadingHooks.updateAsyncTransactions(Lzombie/fileSystem/FileSystem;)V"),
|
||||
GameServerAssetLoadingPerformancePatchTest.calls(node, "doMinimumInit")
|
||||
);
|
||||
assertEquals(List.of("FileSystem.updateAsyncTransactions()V"), GameServerAssetLoadingPerformancePatchTest.calls(node, "main"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void patchedClassIsValid() throws ClassNotFoundException
|
||||
{
|
||||
ClassNode node = GameServerAssetLoadingPerformancePatchTest.gameServer();
|
||||
new GameServerAssetLoadingPerformancePatch().apply(node);
|
||||
|
||||
// Initializing links the class, which runs the bytecode verifier on the changed loop.
|
||||
ClassDefiner definer = new ClassDefiner();
|
||||
definer.define(node);
|
||||
Class.forName(node.name.replace('/', '.'), true, definer);
|
||||
}
|
||||
|
||||
@Test
|
||||
void appliesOnlyToVerifiedVersions()
|
||||
{
|
||||
GameServerAssetLoadingPerformancePatch patch = new GameServerAssetLoadingPerformancePatch();
|
||||
|
||||
assertTrue(patch.appliesTo(GameVersion.parse("42.21.0")));
|
||||
assertTrue(patch.appliesTo(GameVersion.parse("42.21.3")));
|
||||
assertFalse(patch.appliesTo(GameVersion.parse("42.20.3")));
|
||||
assertFalse(patch.appliesTo(GameVersion.parse("42.22.0")));
|
||||
}
|
||||
}
|
||||
+11
-10
@@ -26,13 +26,13 @@ import static org.objectweb.asm.Opcodes.LCONST_1;
|
||||
import static org.objectweb.asm.Opcodes.RETURN;
|
||||
import static org.objectweb.asm.Opcodes.V25;
|
||||
|
||||
/** The five Build 42 waiting-loop patches: each with its target, number of sleeps and hook. */
|
||||
/** The Build 42 patches that redirect {@code Thread.sleep}: each with its target, number of sleeps and hook. */
|
||||
class ThreadSleepPatchesTest
|
||||
{
|
||||
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/WaitHooks";
|
||||
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/";
|
||||
|
||||
/** Each patch with its target method, number of sleeps and hook. */
|
||||
private record Case(ThreadSleepPerformancePatch patch, String target, String method, int sleeps, String hook)
|
||||
/** Each patch with its target method, number of sleeps, hook class and hook. */
|
||||
private record Case(ThreadSleepPerformancePatch patch, String target, String method, int sleeps, String hooks, String hook)
|
||||
{
|
||||
@Override
|
||||
public @NonNull String toString() { return this.patch.getClass().getSimpleName(); }
|
||||
@@ -41,11 +41,12 @@ class ThreadSleepPatchesTest
|
||||
private static Stream<Case> cases()
|
||||
{
|
||||
return Stream.of(
|
||||
new Case(new ServerChunkLoaderQuitPerformancePatch(), "zombie/network/ServerChunkLoader", "quit", 2, "pollSleep"),
|
||||
new Case(new ZipBackupWaitPerformancePatch(), "zombie/core/backup/ZipBackup", "waitFinish", 1, "pollSleep"),
|
||||
new Case(new ServerPlayersVehiclesRoundPerformancePatch(), "zombie/network/ServerPlayersVehicles$SPVThread", "runInner", 1, "vehicleRoundSleep"),
|
||||
new Case(new ServerPlayersVehiclesStopPerformancePatch(), "zombie/network/ServerPlayersVehicles", "stop", 1, "wakeVehiclesAndPoll"),
|
||||
new Case(new ServerPlayerDBSaveWaitPerformancePatch(), "zombie/savefile/ServerPlayerDB", "saveFinishWait", 1, "wakeVehiclesAndPoll")
|
||||
new Case(new ServerChunkLoaderQuitPerformancePatch(), "zombie/network/ServerChunkLoader", "quit", 2, "WaitHooks", "pollSleep"),
|
||||
new Case(new ZipBackupWaitPerformancePatch(), "zombie/core/backup/ZipBackup", "waitFinish", 1, "WaitHooks", "pollSleep"),
|
||||
new Case(new ServerPlayersVehiclesRoundPerformancePatch(), "zombie/network/ServerPlayersVehicles$SPVThread", "runInner", 1, "WaitHooks", "vehicleRoundSleep"),
|
||||
new Case(new ServerPlayersVehiclesStopPerformancePatch(), "zombie/network/ServerPlayersVehicles", "stop", 1, "WaitHooks", "wakeVehiclesAndPoll"),
|
||||
new Case(new ServerPlayerDBSaveWaitPerformancePatch(), "zombie/savefile/ServerPlayerDB", "saveFinishWait", 1, "WaitHooks", "wakeVehiclesAndPoll"),
|
||||
new Case(new ServerMapQuitSleepPerformancePatch(), "zombie/network/ServerMap", "QueuedQuit", 1, "QuitHooks", "quitSleep")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -97,7 +98,7 @@ class ThreadSleepPatchesTest
|
||||
for (MethodInsnNode call : calls)
|
||||
{
|
||||
assertEquals(INVOKESTATIC, call.getOpcode());
|
||||
assertEquals(ThreadSleepPatchesTest.HOOKS, call.owner);
|
||||
assertEquals(ThreadSleepPatchesTest.HOOKS + test.hooks(), call.owner);
|
||||
assertEquals(test.hook(), call.name);
|
||||
assertEquals("(J)V", call.desc);
|
||||
}
|
||||
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
|
||||
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
|
||||
import dev.overlord.zomboidforge.core.config.Feature;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.VarHandle;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.locks.LockSupport;
|
||||
|
||||
import zombie.fileSystem.FileSystem;
|
||||
import zombie.fileSystem.FileSystemImpl;
|
||||
|
||||
/**
|
||||
* Hooks for the asset loading at startup ({@link Feature#EXPERIMENTAL_PERFORMANCE}): the loop
|
||||
* in {@code GameServer.doMinimumInit}
|
||||
*
|
||||
* <pre>{@code
|
||||
* while (GameWindow.fileSystem.hasWork()) GameWindow.fileSystem.updateAsyncTransactions();
|
||||
* }</pre>
|
||||
*
|
||||
* hands file tasks (model and animation imports, 16 at most in flight) to the loader threads of
|
||||
* {@code FileSystemImpl} and collects their results on the main thread. It spins: the main
|
||||
* thread takes a CPU that the loaders could use. Vanilla has 2 loader threads with up to 4
|
||||
* CPUs, 4 with more.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public final class AssetLoadingHooks
|
||||
{
|
||||
/** Pause of the main thread after each update; one task takes about 8 ms of loader time. */
|
||||
private static final long PARK_NANOS = 500_000L;
|
||||
|
||||
/** {@code FileSystemImpl.executor}, private; {@code null} when it cannot be reached. */
|
||||
private static final @Nullable VarHandle EXECUTOR;
|
||||
|
||||
static
|
||||
{
|
||||
VarHandle executor = null;
|
||||
try
|
||||
{
|
||||
executor = MethodHandles.privateLookupIn(FileSystemImpl.class, MethodHandles.lookup())
|
||||
.findVarHandle(FileSystemImpl.class, "executor", ExecutorService.class);
|
||||
}
|
||||
catch (ReflectiveOperationException e) { System.out.println("[ZomboidForge] Unable to register hook 'AssetLoadingHooks.updateAsyncTransactions': 'FileSystemImpl.executor' not found: " + e); }
|
||||
|
||||
EXECUTOR = executor;
|
||||
}
|
||||
|
||||
/** Whether the loader pool was checked; the main thread is the only caller. */
|
||||
private static boolean poolChecked;
|
||||
|
||||
private AssetLoadingHooks() {}
|
||||
|
||||
/**
|
||||
* Replaces {@code fileSystem.updateAsyncTransactions()} in that loop. With the feature off,
|
||||
* only that call. On: the first call grows the loader pool to one thread per CPU but one (at
|
||||
* least 2), and every call parks the main thread for 0.5 ms after the update instead of
|
||||
* spinning. Fewer threads with a spinning main thread, or more threads alone, load slower.
|
||||
* The pool keeps its size after startup; the loaders run the same tasks as in vanilla.
|
||||
*/
|
||||
public static void updateAsyncTransactions(FileSystem fileSystem)
|
||||
{
|
||||
if (!ForgeInstance.FORGE.settings().enabled(Feature.EXPERIMENTAL_PERFORMANCE))
|
||||
{
|
||||
fileSystem.updateAsyncTransactions();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!AssetLoadingHooks.poolChecked)
|
||||
{
|
||||
AssetLoadingHooks.poolChecked = true;
|
||||
|
||||
Object executor = AssetLoadingHooks.EXECUTOR != null && fileSystem instanceof FileSystemImpl ? AssetLoadingHooks.EXECUTOR.get(fileSystem) : null;
|
||||
int threads = Math.max(2, Runtime.getRuntime().availableProcessors() - 1);
|
||||
|
||||
// A fixed pool: maximum first, the core size may not exceed it.
|
||||
if (executor instanceof ThreadPoolExecutor pool && pool.getMaximumPoolSize() < threads)
|
||||
{
|
||||
System.out.println("[ZomboidForge] Loader threads: " + pool.getMaximumPoolSize() + " -> " + threads + ".");
|
||||
pool.setMaximumPoolSize(threads);
|
||||
pool.setCorePoolSize(threads);
|
||||
}
|
||||
}
|
||||
|
||||
fileSystem.updateAsyncTransactions();
|
||||
LockSupport.parkNanos(AssetLoadingHooks.PARK_NANOS);
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
|
||||
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
|
||||
import dev.overlord.zomboidforge.core.config.Feature;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.VarHandle;
|
||||
import java.util.Map;
|
||||
|
||||
import zombie.core.raknet.UdpEngine;
|
||||
import zombie.network.GameServer;
|
||||
|
||||
/**
|
||||
* Hooks for the shutdown sleep in {@code ServerMap.QueuedQuit} ({@link Feature#EXPERIMENTAL_PERFORMANCE}).
|
||||
* After the world save, vanilla broadcasts {@code ServerQuit} and sleeps 5 s, so the clients
|
||||
* receive it and disconnect, then closes the databases and the network.
|
||||
*
|
||||
* <p>The connections are those of {@code UdpEngine.connectionMap}: the network thread
|
||||
* ({@code UdpEngine}) removes a connection from it as soon as RakNet reports the disconnect
|
||||
* notification or the lost connection. {@code GameServer.udpEngine.connections} is updated only
|
||||
* by the main thread, which is in {@code QueuedQuit} at this point.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public final class QuitHooks
|
||||
{
|
||||
private static final long POLL_MILLIS = 10L;
|
||||
|
||||
/** {@code UdpEngine.connectionMap}, private; {@code null} when it cannot be reached. */
|
||||
private static final @Nullable VarHandle CONNECTIONS;
|
||||
|
||||
static
|
||||
{
|
||||
VarHandle connections = null;
|
||||
try
|
||||
{
|
||||
connections = MethodHandles.privateLookupIn(UdpEngine.class, MethodHandles.lookup())
|
||||
.findVarHandle(UdpEngine.class, "connectionMap", Map.class);
|
||||
}
|
||||
catch (ReflectiveOperationException e) { System.out.println("[ZomboidForge] Unable to register hook 'QuitHooks.quitSleep': 'UdpEngine.connectionMap' not found: " + e); }
|
||||
|
||||
CONNECTIONS = connections;
|
||||
}
|
||||
|
||||
private QuitHooks() {}
|
||||
|
||||
/**
|
||||
* Replaces {@code Thread.sleep(5000L)} in {@code QueuedQuit}. Sleeps {@code millis} when the
|
||||
* feature is off, {@code connectionMap} is unreachable, or there is no {@code udpEngine};
|
||||
* otherwise returns once no client is connected, polling every 10 ms, after at most
|
||||
* {@code millis}.
|
||||
*/
|
||||
@SuppressWarnings("BusyWait")
|
||||
public static void quitSleep(long millis) throws InterruptedException
|
||||
{
|
||||
UdpEngine engine = GameServer.udpEngine;
|
||||
|
||||
if (!ForgeInstance.FORGE.settings().enabled(Feature.EXPERIMENTAL_PERFORMANCE) || QuitHooks.CONNECTIONS == null || engine == null)
|
||||
{
|
||||
Thread.sleep(millis);
|
||||
return;
|
||||
}
|
||||
|
||||
long deadline = System.nanoTime() + millis * 1_000_000L;
|
||||
|
||||
while (true)
|
||||
{
|
||||
// The network thread writes the map without synchronisation.
|
||||
VarHandle.acquireFence();
|
||||
int connected = ((Map<?, ?>) QuitHooks.CONNECTIONS.get(engine)).size();
|
||||
|
||||
long now = System.nanoTime();
|
||||
if (connected == 0 || now >= deadline) return;
|
||||
|
||||
Thread.sleep(Math.min(QuitHooks.POLL_MILLIS, (deadline - now) / 1_000_000L + 1L));
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -33,7 +33,7 @@ public final class RolesHooks
|
||||
connection = MethodHandles.privateLookupIn(ServerWorldDatabase.class, MethodHandles.lookup())
|
||||
.findVarHandle(ServerWorldDatabase.class, "conn", Connection.class);
|
||||
}
|
||||
catch (ReflectiveOperationException e) { System.out.println("[ZomboidForge] Roles are saved without a transaction: 'ServerWorldDatabase.conn' not found: " + e); }
|
||||
catch (ReflectiveOperationException e) { System.out.println("[ZomboidForge] Unable to register hook 'RolesHooks.beginSave': 'ServerWorldDatabase.conn' not found: " + e); }
|
||||
|
||||
CONNECTION = connection;
|
||||
}
|
||||
@@ -58,7 +58,7 @@ public final class RolesHooks
|
||||
connection.setAutoCommit(false);
|
||||
RolesHooks.transaction = connection;
|
||||
}
|
||||
catch (SQLException e) { System.out.println("[ZomboidForge] Roles are saved without a transaction: " + e); }
|
||||
catch (SQLException e) { System.out.println("[ZomboidForge] Unable to begin the roles transaction: " + e); }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -72,11 +72,11 @@ public final class RolesHooks
|
||||
if (connection == null) return;
|
||||
|
||||
try { connection.commit(); }
|
||||
catch (SQLException e) { System.out.println("[ZomboidForge] Committing the saved roles failed: " + e); }
|
||||
catch (SQLException e) { System.out.println("[ZomboidForge] Unable to commit the roles transaction: " + e); }
|
||||
finally
|
||||
{
|
||||
try { connection.setAutoCommit(true); }
|
||||
catch (SQLException e) { System.out.println("[ZomboidForge] Switching the database back to autocommit failed: " + e); }
|
||||
catch (SQLException e) { System.out.println("[ZomboidForge] Unable to restore autocommit: " + e); }
|
||||
}
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
|
||||
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
|
||||
import dev.overlord.zomboidforge.core.Forge;
|
||||
import dev.overlord.zomboidforge.core.config.Feature;
|
||||
import dev.overlord.zomboidforge.core.config.ForgeSettings;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import zombie.fileSystem.FileSystemImpl;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.time.Duration;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/** The hook on a real {@code FileSystemImpl}; the feature is switched through the settings of {@code ForgeInstance.FORGE}. */
|
||||
class AssetLoadingHooksTest
|
||||
{
|
||||
private static void settings(ForgeSettings settings) throws ReflectiveOperationException
|
||||
{
|
||||
Field field = Forge.class.getDeclaredField("settings");
|
||||
field.setAccessible(true);
|
||||
field.set(ForgeInstance.FORGE, settings);
|
||||
}
|
||||
|
||||
private static ThreadPoolExecutor pool(FileSystemImpl fileSystem) throws ReflectiveOperationException
|
||||
{
|
||||
Field field = FileSystemImpl.class.getDeclaredField("executor");
|
||||
field.setAccessible(true);
|
||||
return (ThreadPoolExecutor) field.get(fileSystem);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void resetSettings() throws ReflectiveOperationException
|
||||
{
|
||||
AssetLoadingHooksTest.settings(ForgeSettings.DEFAULTS);
|
||||
}
|
||||
|
||||
/** One test: the first call with the feature on grows the pool once per JVM. */
|
||||
@Test
|
||||
void growsTheLoaderPoolOnlyWithTheFeature() throws ReflectiveOperationException
|
||||
{
|
||||
FileSystemImpl fileSystem = new FileSystemImpl();
|
||||
ThreadPoolExecutor pool = AssetLoadingHooksTest.pool(fileSystem);
|
||||
int vanilla = Runtime.getRuntime().availableProcessors() <= 4 ? 2 : 4;
|
||||
int expected = Math.max(vanilla, Math.max(2, Runtime.getRuntime().availableProcessors() - 1));
|
||||
|
||||
try
|
||||
{
|
||||
assertEquals(vanilla, pool.getMaximumPoolSize());
|
||||
|
||||
AssetLoadingHooks.updateAsyncTransactions(fileSystem);
|
||||
assertEquals(vanilla, pool.getCorePoolSize());
|
||||
assertEquals(vanilla, pool.getMaximumPoolSize());
|
||||
|
||||
AssetLoadingHooksTest.settings(new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10), Set.of(Feature.EXPERIMENTAL_PERFORMANCE)));
|
||||
AssetLoadingHooks.updateAsyncTransactions(fileSystem);
|
||||
AssetLoadingHooks.updateAsyncTransactions(fileSystem);
|
||||
assertEquals(expected, pool.getCorePoolSize());
|
||||
assertEquals(expected, pool.getMaximumPoolSize());
|
||||
}
|
||||
finally { pool.shutdownNow(); }
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
|
||||
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
|
||||
import dev.overlord.zomboidforge.core.Forge;
|
||||
import dev.overlord.zomboidforge.core.config.Feature;
|
||||
import dev.overlord.zomboidforge.core.config.ForgeSettings;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import zombie.core.raknet.UdpEngine;
|
||||
import zombie.network.GameServer;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** The paths without a network engine; the wait for disconnects is checked on a running server. */
|
||||
class QuitHooksTest
|
||||
{
|
||||
private static final long MILLIS = 50L;
|
||||
|
||||
private static void settings(ForgeSettings settings) throws ReflectiveOperationException
|
||||
{
|
||||
Field field = Forge.class.getDeclaredField("settings");
|
||||
field.setAccessible(true);
|
||||
field.set(ForgeInstance.FORGE, settings);
|
||||
}
|
||||
|
||||
private static long sleptMillis() throws InterruptedException
|
||||
{
|
||||
long start = System.nanoTime();
|
||||
QuitHooks.quitSleep(QuitHooksTest.MILLIS);
|
||||
return (System.nanoTime() - start) / 1_000_000L;
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void resetSettings() throws ReflectiveOperationException
|
||||
{
|
||||
QuitHooksTest.settings(ForgeSettings.DEFAULTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sleepsTheFullTimeWithoutTheFeature() throws InterruptedException
|
||||
{
|
||||
assertTrue(QuitHooksTest.sleptMillis() >= QuitHooksTest.MILLIS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sleepsTheFullTimeWithoutANetworkEngine() throws Exception
|
||||
{
|
||||
assertNull(GameServer.udpEngine);
|
||||
QuitHooksTest.settings(new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10), Set.of(Feature.EXPERIMENTAL_PERFORMANCE)));
|
||||
|
||||
assertTrue(QuitHooksTest.sleptMillis() >= QuitHooksTest.MILLIS);
|
||||
}
|
||||
|
||||
/** The hook reads this field; without it the shutdown keeps the vanilla sleep. */
|
||||
@Test
|
||||
void connectionMapExistsInTheGame() throws NoSuchFieldException
|
||||
{
|
||||
assertEquals(Map.class, UdpEngine.class.getDeclaredField("connectionMap").getType());
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,8 @@ services:
|
||||
JVM_MIN_HEAP: ${JVM_MIN_HEAP:-}
|
||||
JVM_MAX_HEAP: ${JVM_MAX_HEAP:-}
|
||||
JVM_UNCOMMIT_DELAY: ${JVM_UNCOMMIT_DELAY:-}
|
||||
JVM_EXPERIMENTAL_PERFORMANCE: ${JVM_EXPERIMENTAL_PERFORMANCE:-}
|
||||
ZF_EXPERIMENTAL_PERFORMANCE: ${ZF_EXPERIMENTAL_PERFORMANCE:-}
|
||||
ports:
|
||||
# Host and container ports must be equal: the server reports its own port
|
||||
# to Steam and to clients, so a remapped port is unreachable.
|
||||
|
||||
@@ -10,6 +10,7 @@ import dev.overlord.zomboidforge.api.storage.StorageException;
|
||||
import dev.overlord.zomboidforge.core.commands.ClientCommandSender;
|
||||
import dev.overlord.zomboidforge.core.commands.CommandRegistry;
|
||||
import dev.overlord.zomboidforge.core.commands.ModClientCommands;
|
||||
import dev.overlord.zomboidforge.core.config.Feature;
|
||||
import dev.overlord.zomboidforge.core.config.ForgeSettings;
|
||||
import dev.overlord.zomboidforge.core.mods.GameClasses;
|
||||
import dev.overlord.zomboidforge.core.mods.ModDiscovery;
|
||||
@@ -32,6 +33,7 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -100,6 +102,9 @@ public final class Forge
|
||||
|
||||
public Lifecycle.Phase phase() { return this.lifecycle.phase(); }
|
||||
|
||||
/** The settings from {@code forge.toml} and the system properties; {@link ForgeSettings#DEFAULTS} until {@link #load} reads them. */
|
||||
public ForgeSettings settings() { return this.settings; }
|
||||
|
||||
public List<ModLoader.LoadedMod> mods() { return this.mods; }
|
||||
|
||||
/** The admin command classes that mods registered, in registration order. */
|
||||
@@ -119,8 +124,14 @@ public final class Forge
|
||||
{
|
||||
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); }
|
||||
try { this.settings = ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE), System.getProperties()); }
|
||||
catch (IllegalArgumentException e) { throw new ModLoadException("'" + ForgeSettings.FILE + "' or system properties: " + e.getMessage(), e); }
|
||||
|
||||
if (!this.settings.features().isEmpty())
|
||||
{
|
||||
String features = this.settings.features().stream().sorted().map(Feature::key).collect(Collectors.joining(", "));
|
||||
this.logger.log(System.Logger.Level.INFO, "Features on: " + features + ".");
|
||||
}
|
||||
|
||||
this.queue.budget(this.settings.mainThreadBudget());
|
||||
this.queue.bindToCurrentThread();
|
||||
@@ -142,11 +153,11 @@ public final class Forge
|
||||
|
||||
try (GameClasses gameClasses = GameClasses.open(gameJar))
|
||||
{
|
||||
ModVerifier.verify(ordered, gameClasses, game);
|
||||
Map<String, List<String>> annotatedCommands = ModVerifier.verify(ordered, gameClasses, game);
|
||||
|
||||
for (ModDiscovery.Candidate candidate : ordered) ModTables.adoptPreviousIds(storage, candidate.id(), candidate.descriptor().previousIds(), installed);
|
||||
|
||||
this.mods = ModLoader.load(ordered, game, parent, gameClasses, this::services);
|
||||
this.mods = ModLoader.load(ordered, game, parent, gameClasses, this::services, annotatedCommands);
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
@@ -173,16 +184,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());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package dev.overlord.zomboidforge.core.config;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Optional behavior of ZomboidForge, off by default. Each feature has one key, from which its
|
||||
* switches follow:
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@code features.<key> = true|false} in {@code forge.toml};</li>
|
||||
* <li>the system property {@code zomboidforge.features.<key>=true|false}, which takes
|
||||
* precedence; the container entrypoint sets it from the environment variable
|
||||
* {@code ZF_<KEY>}.</li>
|
||||
* </ul>
|
||||
*
|
||||
* Code that a feature switches reads it through {@link ForgeSettings#enabled(Feature)} of the
|
||||
* running {@code Forge}, which has the defaults (every feature off) until the settings are read
|
||||
* at load.
|
||||
*/
|
||||
public enum Feature
|
||||
{
|
||||
/**
|
||||
* Performance changes that alter timing or resource use: more threads, shorter waits. Off,
|
||||
* the patched code does what vanilla does.
|
||||
*/
|
||||
EXPERIMENTAL_PERFORMANCE;
|
||||
|
||||
/** Prefix of the system properties: {@code zomboidforge.features.<key>}. */
|
||||
public static final String PROPERTY_PREFIX = "zomboidforge.features.";
|
||||
|
||||
/** The key in {@code forge.toml} and in the property name: the lowercase constant name. */
|
||||
public String key() { return this.name().toLowerCase(Locale.ROOT); }
|
||||
|
||||
/** The system property that switches this feature. */
|
||||
public String property() { return Feature.PROPERTY_PREFIX + this.key(); }
|
||||
|
||||
/** The feature with {@code key}. */
|
||||
public static Optional<Feature> byKey(String key)
|
||||
{
|
||||
return Arrays.stream(Feature.values()).filter(feature -> feature.key().equals(key)).findFirst();
|
||||
}
|
||||
}
|
||||
@@ -7,47 +7,58 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.TreeSet;
|
||||
|
||||
/**
|
||||
* 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>
|
||||
* Global settings from {@code <forge>/forge.toml}.
|
||||
* The system property {@code zomboidforge.features.<key>}
|
||||
* of a feature takes precedence over its key in the file.
|
||||
*
|
||||
* @param mainThreadBudget at least 1 ms
|
||||
* @param shutdownTimeout 0 or more
|
||||
* @param features the features that are enabled
|
||||
*/
|
||||
public record ForgeSettings(Duration mainThreadBudget, Duration shutdownTimeout)
|
||||
public record ForgeSettings(Duration mainThreadBudget, Duration shutdownTimeout, Set<Feature> features)
|
||||
{
|
||||
public static final String FILE = "forge.toml";
|
||||
public static final ForgeSettings DEFAULTS = new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10));
|
||||
public static final ForgeSettings DEFAULTS = new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10), Set.of());
|
||||
|
||||
private record Document(Optional<MainThread> mainThread, Optional<Shutdown> shutdown) {}
|
||||
public ForgeSettings
|
||||
{
|
||||
features = Set.copyOf(features);
|
||||
}
|
||||
|
||||
/** Whether {@code feature} is on. */
|
||||
public boolean enabled(Feature feature) { return this.features.contains(feature); }
|
||||
|
||||
private record Document(Optional<MainThread> mainThread, Optional<Shutdown> shutdown, Optional<Map<String, Boolean>> features) {}
|
||||
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.
|
||||
* The settings in {@code file}, the defaults for what it leaves out or when it does not
|
||||
* exist; then the features switched in {@code properties} (the system properties).
|
||||
*
|
||||
* @throws IllegalArgumentException listing every problem: invalid TOML, unknown keys, values
|
||||
* of the wrong type or out of range
|
||||
* of the wrong type or out of range, feature properties that
|
||||
* name no feature or are not {@code true} or {@code false}
|
||||
*/
|
||||
public static ForgeSettings read(Path file)
|
||||
public static ForgeSettings read(Path file, Properties properties)
|
||||
{
|
||||
if (!Files.isRegularFile(file)) return ForgeSettings.DEFAULTS;
|
||||
|
||||
Map<String, Object> values;
|
||||
Map<String, Object> values = Map.of();
|
||||
|
||||
if (Files.isRegularFile(file))
|
||||
{
|
||||
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, "");
|
||||
@@ -63,8 +74,31 @@ public record ForgeSettings(Duration mainThreadBudget, Duration shutdownTimeout)
|
||||
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 + ".");
|
||||
|
||||
Set<Feature> features = EnumSet.noneOf(Feature.class);
|
||||
|
||||
for (Map.Entry<String, Boolean> entry : new TreeMap<>(document.features().orElse(Map.of())).entrySet())
|
||||
{
|
||||
Optional<Feature> feature = Feature.byKey(entry.getKey());
|
||||
|
||||
if (feature.isEmpty()) problems.add("Unknown key 'features." + entry.getKey() + "'.");
|
||||
else if (entry.getValue()) features.add(feature.get());
|
||||
}
|
||||
|
||||
for (String name : new TreeSet<>(properties.stringPropertyNames()))
|
||||
{
|
||||
if (!name.startsWith(Feature.PROPERTY_PREFIX)) continue;
|
||||
|
||||
Optional<Feature> feature = Feature.byKey(name.substring(Feature.PROPERTY_PREFIX.length()));
|
||||
String value = properties.getProperty(name);
|
||||
|
||||
if (feature.isEmpty()) problems.add("Unknown system property '" + name + "'.");
|
||||
else if (value.equalsIgnoreCase("true")) features.add(feature.get());
|
||||
else if (value.equalsIgnoreCase("false")) features.remove(feature.get());
|
||||
else problems.add("System property '" + name + "' must be true or false, found \"" + value + "\".");
|
||||
}
|
||||
|
||||
if (!problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems));
|
||||
|
||||
return new ForgeSettings(Duration.ofMillis(budget), Duration.ofSeconds(timeout));
|
||||
return new ForgeSettings(Duration.ofMillis(budget), Duration.ofSeconds(timeout), features);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
package dev.overlord.zomboidforge.core.config;
|
||||
|
||||
import dev.overlord.zomboidforge.api.annotations.Key;
|
||||
import dev.overlord.zomboidforge.api.annotations.Max;
|
||||
import dev.overlord.zomboidforge.api.annotations.Min;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
@@ -16,14 +20,26 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Converts {@link TomlTree} values to records and other Java types. Collects every problem
|
||||
* instead of stopping at the first one, and records the keys no component reads.
|
||||
* instead of stopping at the first one, and records the keys no component reads. Record
|
||||
* components are read by their {@link Key} or converted name, and checked against their
|
||||
* {@link Min} and {@link Max}.
|
||||
*/
|
||||
public final class RecordBinder
|
||||
{
|
||||
/** Bounds of a numeric component from {@link Min} and {@link Max}; {@code null} when absent. */
|
||||
private record Bounds(@Nullable Double min, @Nullable Double max)
|
||||
{
|
||||
static final Bounds NONE = new Bounds(null, null);
|
||||
}
|
||||
|
||||
private static final Pattern KEY = Pattern.compile("[a-z][a-z0-9]*(_[a-z0-9]+)*");
|
||||
private static final Set<Class<?>> NUMBERS = Set.of(long.class, Long.class, int.class, Integer.class, double.class, Double.class, float.class, Float.class);
|
||||
|
||||
private final List<String> problems = new ArrayList<>();
|
||||
private final Set<String> unknownKeys = new TreeSet<>();
|
||||
|
||||
@@ -51,20 +67,69 @@ public final class RecordBinder
|
||||
return key.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* The keys of the components of {@code type}, in component order: each component's
|
||||
* {@link Key}, or its name converted by {@link #key(String)}.
|
||||
*
|
||||
* @throws IllegalArgumentException when a {@link Key} is not {@code snake_case}, or two
|
||||
* components have the same key
|
||||
*/
|
||||
public static List<String> keys(Class<? extends Record> type)
|
||||
{
|
||||
List<String> keys = new ArrayList<>();
|
||||
|
||||
for (RecordComponent component : type.getRecordComponents())
|
||||
{
|
||||
Key annotation = component.getAnnotation(Key.class);
|
||||
String key = annotation == null ? RecordBinder.key(component.getName()) : annotation.value();
|
||||
|
||||
if (annotation != null && !RecordBinder.KEY.matcher(key).matches())
|
||||
throw new IllegalArgumentException("'" + type.getName() + "." + component.getName() + "' has @Key(\"" + key + "\"); keys are lowercase letters, digits, and single underscores, starting with a letter.");
|
||||
|
||||
if (keys.contains(key))
|
||||
throw new IllegalArgumentException("'" + type.getName() + "' has two components with the key '" + key + "'.");
|
||||
|
||||
keys.add(key);
|
||||
}
|
||||
|
||||
return keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* The problems of the {@link Key}, {@link Min}, and {@link Max} annotations of {@code type}'s
|
||||
* components, as {@link #keys} and binding report them; empty when there are none. For
|
||||
* build-time checks.
|
||||
*/
|
||||
public static List<String> check(Class<? extends Record> type)
|
||||
{
|
||||
List<String> problems = new ArrayList<>();
|
||||
|
||||
try { RecordBinder.keys(type); }
|
||||
catch (IllegalArgumentException e) { problems.add(e.getMessage()); }
|
||||
|
||||
for (RecordComponent component : type.getRecordComponents()) {
|
||||
try { RecordBinder.bounds(component); }
|
||||
catch (IllegalArgumentException e) { problems.add(e.getMessage()); }
|
||||
}
|
||||
|
||||
return List.copyOf(problems);
|
||||
}
|
||||
|
||||
/** A record of {@code type} from {@code table}, or {@code null} when a problem was found. */
|
||||
public <T extends Record> @Nullable T record(Map<String, Object> table, Class<T> type, String path)
|
||||
{
|
||||
RecordComponent[] components = type.getRecordComponents();
|
||||
List<String> names = RecordBinder.keys(type);
|
||||
@Nullable Object[] arguments = new Object[components.length];
|
||||
Set<String> keys = new TreeSet<>(table.keySet());
|
||||
int before = this.problems.size();
|
||||
|
||||
for (int i = 0; i < components.length; i++)
|
||||
{
|
||||
String key = RecordBinder.key(components[i].getName());
|
||||
String key = names.get(i);
|
||||
keys.remove(key);
|
||||
|
||||
arguments[i] = this.value(table.get(key), components[i].getGenericType(), RecordBinder.join(path, key));
|
||||
arguments[i] = this.value(table.get(key), components[i].getGenericType(), RecordBinder.join(path, key), RecordBinder.bounds(components[i]));
|
||||
}
|
||||
|
||||
for (String key : keys) this.unknownKeys.add(RecordBinder.join(path, key));
|
||||
@@ -94,7 +159,10 @@ public final class RecordBinder
|
||||
* {@code raw} converted to {@code target}, or {@code null} after recording a problem.
|
||||
* {@code raw == null} means the key is missing.
|
||||
*/
|
||||
public @Nullable Object value(@Nullable Object raw, Type target, String path)
|
||||
public @Nullable Object value(@Nullable Object raw, Type target, String path) { return this.value(raw, target, path, Bounds.NONE); }
|
||||
|
||||
/** Like {@link #value(Object, Type, String)}; numbers, also inside an {@code Optional}, {@code List}, or {@code Map}, are checked against {@code bounds}. */
|
||||
private @Nullable Object value(@Nullable Object raw, Type target, String path, Bounds bounds)
|
||||
{
|
||||
Class<?> type = RecordBinder.rawType(target);
|
||||
|
||||
@@ -102,7 +170,7 @@ public final class RecordBinder
|
||||
{
|
||||
if (raw == null) return Optional.empty();
|
||||
|
||||
Object element = this.value(raw, RecordBinder.typeArgument(target, 0), path);
|
||||
Object element = this.value(raw, RecordBinder.typeArgument(target, 0), path, bounds);
|
||||
return element == null ? null : Optional.of(element);
|
||||
}
|
||||
|
||||
@@ -110,14 +178,14 @@ public final class RecordBinder
|
||||
|
||||
if (type == String.class) return raw instanceof String ? raw : this.mistyped(path, "a string", raw);
|
||||
if (type == boolean.class || type == Boolean.class) return raw instanceof Boolean ? raw : this.mistyped(path, "true or false", raw);
|
||||
if (type == long.class || type == Long.class) return raw instanceof Long ? raw : this.mistyped(path, "an integer", raw);
|
||||
if (type == int.class || type == Integer.class) return this.integer(raw, path);
|
||||
if (type == double.class || type == Double.class) return raw instanceof Long || raw instanceof Double ? ((Number) raw).doubleValue() : this.mistyped(path, "a number", raw);
|
||||
if (type == float.class || type == Float.class) return raw instanceof Long || raw instanceof Double ? ((Number) raw).floatValue() : this.mistyped(path, "a number", raw);
|
||||
if (type == long.class || type == Long.class) return this.bounded(raw instanceof Long ? raw : this.mistyped(path, "an integer", raw), path, bounds);
|
||||
if (type == int.class || type == Integer.class) return this.bounded(this.integer(raw, path), path, bounds);
|
||||
if (type == double.class || type == Double.class) return this.bounded(raw instanceof Long || raw instanceof Double ? ((Number) raw).doubleValue() : this.mistyped(path, "a number", raw), path, bounds);
|
||||
if (type == float.class || type == Float.class) return this.bounded(raw instanceof Long || raw instanceof Double ? ((Number) raw).floatValue() : this.mistyped(path, "a number", raw), path, bounds);
|
||||
if (type.isEnum()) return this.constant(raw, type, path);
|
||||
if (type.isRecord()) return raw instanceof Map<?, ?> table ? this.record(TomlTree.cast(table), type.asSubclass(Record.class), path) : this.mistyped(path, "a table", raw);
|
||||
if (type == List.class) return this.list(raw, RecordBinder.typeArgument(target, 0), path);
|
||||
if (type == Map.class) return this.map(raw, target, path);
|
||||
if (type == List.class) return this.list(raw, RecordBinder.typeArgument(target, 0), path, bounds);
|
||||
if (type == Map.class) return this.map(raw, target, path, bounds);
|
||||
|
||||
throw new IllegalArgumentException("'" + path + "' has the type '" + target.getTypeName() + "', which configuration values cannot have.");
|
||||
}
|
||||
@@ -144,7 +212,23 @@ public final class RecordBinder
|
||||
return this.mistyped(path, "one of " + allowed, raw);
|
||||
}
|
||||
|
||||
private @Nullable Object list(Object raw, Type element, String path)
|
||||
/** {@code value} when it is within {@code bounds}; {@code null} after recording a problem, or when {@code value} is {@code null} already. */
|
||||
private @Nullable Object bounded(@Nullable Object value, String path, Bounds bounds)
|
||||
{
|
||||
if (value == null || bounds == Bounds.NONE) return value;
|
||||
|
||||
// Integers above 2^53 lose precision as doubles; configuration values do not get there.
|
||||
double number = ((Number) value).doubleValue();
|
||||
Double min = bounds.min();
|
||||
Double max = bounds.max();
|
||||
|
||||
if (min != null && number < min) return this.problem(path, "must be at least " + RecordBinder.bound(min) + ", found " + value);
|
||||
if (max != null && number > max) return this.problem(path, "must be at most " + RecordBinder.bound(max) + ", found " + value);
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
private @Nullable Object list(Object raw, Type element, String path, Bounds bounds)
|
||||
{
|
||||
if (!(raw instanceof List<?> list)) return this.mistyped(path, "a list", raw);
|
||||
|
||||
@@ -153,14 +237,14 @@ public final class RecordBinder
|
||||
|
||||
for (int i = 0; i < list.size(); i++)
|
||||
{
|
||||
Object value = this.value(list.get(i), element, path + "[" + i + "]");
|
||||
Object value = this.value(list.get(i), element, path + "[" + i + "]", bounds);
|
||||
if (value != null) values.add(value);
|
||||
}
|
||||
|
||||
return this.problems.size() > before ? null : List.copyOf(values);
|
||||
}
|
||||
|
||||
private @Nullable Object map(Object raw, Type target, String path)
|
||||
private @Nullable Object map(Object raw, Type target, String path, Bounds bounds)
|
||||
{
|
||||
if (RecordBinder.typeArgument(target, 0) != String.class)
|
||||
throw new IllegalArgumentException("'" + path + "' has the type '" + target.getTypeName() + "'; configuration maps need String keys.");
|
||||
@@ -172,7 +256,7 @@ public final class RecordBinder
|
||||
|
||||
for (Map.Entry<String, Object> entry : TomlTree.cast(table).entrySet())
|
||||
{
|
||||
Object value = this.value(entry.getValue(), RecordBinder.typeArgument(target, 1), RecordBinder.join(path, entry.getKey()));
|
||||
Object value = this.value(entry.getValue(), RecordBinder.typeArgument(target, 1), RecordBinder.join(path, entry.getKey()), bounds);
|
||||
if (value != null) values.put(entry.getKey(), value);
|
||||
}
|
||||
|
||||
@@ -191,6 +275,44 @@ public final class RecordBinder
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The bounds of {@code component} from its {@link Min} and {@link Max}.
|
||||
*
|
||||
* @throws IllegalArgumentException when the component's values are not numbers, a bound is
|
||||
* {@code NaN}, or the minimum is above the maximum
|
||||
*/
|
||||
private static Bounds bounds(RecordComponent component)
|
||||
{
|
||||
Min min = component.getAnnotation(Min.class);
|
||||
Max max = component.getAnnotation(Max.class);
|
||||
|
||||
if (min == null && max == null) return Bounds.NONE;
|
||||
|
||||
String where = "'" + component.getDeclaringRecord().getName() + "." + component.getName() + "'";
|
||||
|
||||
if (!RecordBinder.isNumeric(component.getGenericType()))
|
||||
throw new IllegalArgumentException(where + " has @Min or @Max, but its values are not numbers.");
|
||||
|
||||
if ((min != null && Double.isNaN(min.value())) || (max != null && Double.isNaN(max.value())))
|
||||
throw new IllegalArgumentException(where + " has a @Min or @Max that is not a number.");
|
||||
|
||||
if (min != null && max != null && min.value() > max.value())
|
||||
throw new IllegalArgumentException(where + " has @Min(" + RecordBinder.bound(min.value()) + ") above @Max(" + RecordBinder.bound(max.value()) + ").");
|
||||
|
||||
return new Bounds(min == null ? null : min.value(), max == null ? null : max.value());
|
||||
}
|
||||
|
||||
/** Whether values of {@code type} are numbers, also as the values of an {@code Optional}, {@code List}, or {@code Map}. */
|
||||
private static boolean isNumeric(Type type)
|
||||
{
|
||||
Class<?> raw = RecordBinder.rawType(type);
|
||||
|
||||
if (raw == Optional.class || raw == List.class) return RecordBinder.isNumeric(RecordBinder.typeArgument(type, 0));
|
||||
if (raw == Map.class) return RecordBinder.isNumeric(RecordBinder.typeArgument(type, 1));
|
||||
|
||||
return RecordBinder.NUMBERS.contains(raw);
|
||||
}
|
||||
|
||||
private static Class<?> rawType(Type type)
|
||||
{
|
||||
return switch (type)
|
||||
@@ -208,5 +330,12 @@ public final class RecordBinder
|
||||
throw new IllegalArgumentException("'" + type.getTypeName() + "' needs type arguments in configuration records.");
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code value} for messages: whole numbers without a decimal point ({@code 100}), others as
|
||||
* they are ({@code 0.5}). Beyond 10^15 the {@code double} form stays, as a {@code long} would
|
||||
* not hold every such value.
|
||||
*/
|
||||
private static String bound(double value) { return value == Math.rint(value) && Math.abs(value) < 1e15 ? String.valueOf((long) value) : String.valueOf(value); }
|
||||
|
||||
private static String join(String path, String key) { return path.isEmpty() ? key : path + "." + key; }
|
||||
}
|
||||
@@ -29,8 +29,9 @@ import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Creates the class loaders and entry points of resolved mods, in order, and calls
|
||||
* {@link Mod#onLoad()} on each. Stops at the first mod that fails.
|
||||
* Creates the class loaders and entry points of resolved mods, in order, registers each entry
|
||||
* point's listener methods and the mod's {@code @RegisterCommand} classes, and calls
|
||||
* {@link Mod#onLoad()}. Stops at the first mod that fails.
|
||||
*/
|
||||
public final class ModLoader
|
||||
{
|
||||
@@ -62,9 +63,11 @@ public final class ModLoader
|
||||
* @param gameClasses classes of the Project Zomboid jar, visible to mods that declare
|
||||
* {@code game} versions
|
||||
* @param services creates each mod's threads and event registration
|
||||
* @param commands mod id to its classes annotated with {@code @RegisterCommand}, as
|
||||
* returned by {@link ModVerifier#verify}
|
||||
* @throws ModLoadException naming the mod that failed and why
|
||||
*/
|
||||
public static List<LoadedMod> load(List<ModDiscovery.Candidate> ordered, GameVersion game, ClassLoader parent, GameClasses gameClasses, ModServices.Factory services) throws ModLoadException
|
||||
public static List<LoadedMod> load(List<ModDiscovery.Candidate> ordered, GameVersion game, ClassLoader parent, GameClasses gameClasses, ModServices.Factory services, Map<String, List<String>> commands) throws ModLoadException
|
||||
{
|
||||
Map<String, ModClassLoader> loaders = new HashMap<>();
|
||||
List<LoadedMod> loaded = new ArrayList<>();
|
||||
@@ -102,7 +105,7 @@ public final class ModLoader
|
||||
provided.clientCommands()
|
||||
);
|
||||
|
||||
loaded.add(new LoadedMod(descriptor, candidate.directory(), loader, ModLoader.create(descriptor, loader, context)));
|
||||
loaded.add(new LoadedMod(descriptor, candidate.directory(), loader, ModLoader.create(descriptor, loader, context, commands.getOrDefault(descriptor.id(), List.of()))));
|
||||
}
|
||||
|
||||
return List.copyOf(loaded);
|
||||
@@ -114,7 +117,8 @@ public final class ModLoader
|
||||
}
|
||||
}
|
||||
|
||||
private static Mod create(ModDescriptor descriptor, ClassLoader loader, ModContext context) throws ModLoadException
|
||||
/** @param commands binary names of the mod's classes annotated with {@code @RegisterCommand} */
|
||||
private static Mod create(ModDescriptor descriptor, ClassLoader loader, ModContext context, List<String> commands) throws ModLoadException
|
||||
{
|
||||
String id = descriptor.id();
|
||||
|
||||
@@ -135,6 +139,12 @@ public final class ModLoader
|
||||
throw new ModLoadException(ModLoader.sentence("'" + id + "': cannot create '" + descriptor.entrypoint() + "': " + e), e);
|
||||
}
|
||||
|
||||
// Listener methods of the entry point; a mistake stops the server before onLoad() has side effects.
|
||||
try { context.events().register(mod); }
|
||||
catch (IllegalArgumentException e) { throw new ModLoadException("'" + id + "': " + e.getMessage(), e); }
|
||||
|
||||
for (String command : commands) ModLoader.registerCommand(descriptor, loader, context, command);
|
||||
|
||||
try { mod.onLoad(); }
|
||||
catch (Exception e) { throw new ModLoadException(ModLoader.sentence("'" + id + "': onLoad() threw " + e), e); }
|
||||
catch (LinkageError e) { throw new ModLoadException(ModLoader.sentence("'" + id + "': onLoad() failed with " + e), e); }
|
||||
@@ -142,6 +152,19 @@ public final class ModLoader
|
||||
return mod;
|
||||
}
|
||||
|
||||
/** Registers the class {@code command}, annotated with {@code @RegisterCommand}. */
|
||||
private static void registerCommand(ModDescriptor descriptor, ClassLoader loader, ModContext context, String command) throws ModLoadException
|
||||
{
|
||||
String id = descriptor.id();
|
||||
Class<?> type;
|
||||
|
||||
try { type = Class.forName(command, false, loader); }
|
||||
catch (ClassNotFoundException | LinkageError e) { throw new ModLoadException(ModLoader.sentence("'" + id + "': the command '" + command + "' cannot be loaded: " + e), e); }
|
||||
|
||||
try { context.commands().register(type); }
|
||||
catch (IllegalArgumentException e) { throw new ModLoadException("'" + id + "': " + e.getMessage(), e); }
|
||||
}
|
||||
|
||||
private static Constructor<? extends Mod> constructor(ModDescriptor descriptor, ClassLoader loader) throws ModLoadException
|
||||
{
|
||||
String id = descriptor.id();
|
||||
|
||||
@@ -4,6 +4,7 @@ import dev.overlord.zomboidforge.api.GameVersion;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import org.objectweb.asm.AnnotationVisitor;
|
||||
import org.objectweb.asm.ClassReader;
|
||||
import org.objectweb.asm.ClassVisitor;
|
||||
import org.objectweb.asm.FieldVisitor;
|
||||
@@ -20,6 +21,7 @@ import java.io.UncheckedIOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Deque;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
@@ -45,6 +47,8 @@ import java.util.stream.Collectors;
|
||||
* </ul>
|
||||
*
|
||||
* Annotations are not checked: the JVM does not load annotation types a class only carries.
|
||||
* The classes of a mod's own jar annotated with {@code @RegisterCommand} are collected for the
|
||||
* loader.
|
||||
*/
|
||||
public final class ModVerifier
|
||||
{
|
||||
@@ -53,6 +57,8 @@ public final class ModVerifier
|
||||
private static final String API_INTERNAL = "dev/overlord/zomboidforge/api/internal/";
|
||||
private static final int EXAMPLES = 5;
|
||||
|
||||
private static final String REGISTER_COMMAND = "Ldev/overlord/zomboidforge/api/annotations/RegisterCommand;";
|
||||
|
||||
/** A field or method that a mod's code uses. */
|
||||
private record Member(boolean method, String owner, String name, String desc) implements Comparable<Member>
|
||||
{
|
||||
@@ -68,12 +74,15 @@ public final class ModVerifier
|
||||
/**
|
||||
* @param ordered mods in load order, as returned by {@link ModResolver#resolve}
|
||||
* @param version the version of {@code game}, for messages; {@code null} with {@link GameClasses#none()}
|
||||
* @return mod id to the binary names of the classes in its own jar annotated with
|
||||
* {@code @RegisterCommand}, sorted
|
||||
* @throws ModLoadException listing every problem of every mod
|
||||
*/
|
||||
public static void verify(List<ModDiscovery.Candidate> ordered, GameClasses game, @Nullable GameVersion version) throws ModLoadException
|
||||
public static Map<String, List<String>> verify(List<ModDiscovery.Candidate> ordered, GameClasses game, @Nullable GameVersion version) throws ModLoadException
|
||||
{
|
||||
Hierarchy hierarchy = new Hierarchy(game);
|
||||
Map<String, Set<String>> ownByMod = new HashMap<>();
|
||||
Map<String, List<String>> commands = new HashMap<>();
|
||||
List<String> problems = new ArrayList<>();
|
||||
|
||||
for (ModDiscovery.Candidate candidate : ordered)
|
||||
@@ -85,6 +94,7 @@ public final class ModVerifier
|
||||
for (Path library : candidate.libraries()) libraries.putAll(ModVerifier.classes(library));
|
||||
|
||||
ownByMod.put(id, own.keySet());
|
||||
commands.put(id, ModVerifier.registeredCommands(own.values()));
|
||||
|
||||
Set<String> provided = new HashSet<>(own.keySet());
|
||||
provided.addAll(libraries.keySet());
|
||||
@@ -144,6 +154,25 @@ public final class ModVerifier
|
||||
}
|
||||
|
||||
if (!problems.isEmpty()) throw new ModLoadException(problems);
|
||||
|
||||
return Map.copyOf(commands);
|
||||
}
|
||||
|
||||
/** Binary names of the classes annotated with {@code @RegisterCommand}, sorted. */
|
||||
private static List<String> registeredCommands(Collection<byte[]> classes)
|
||||
{
|
||||
List<String> names = new ArrayList<>();
|
||||
|
||||
for (byte[] bytes : classes)
|
||||
{
|
||||
CommandAnnotation annotation = new CommandAnnotation();
|
||||
new ClassReader(bytes).accept(annotation, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
|
||||
|
||||
if (annotation.name != null) names.add(ModVerifier.dotted(annotation.name));
|
||||
}
|
||||
|
||||
names.sort(null);
|
||||
return List.copyOf(names);
|
||||
}
|
||||
|
||||
/** Internal class name to class file, for every class in {@code jar} outside {@code META-INF/}. */
|
||||
@@ -178,6 +207,27 @@ public final class ModVerifier
|
||||
|
||||
private static String dotted(String internalName) { return internalName.replace('/', '.'); }
|
||||
|
||||
/** Reads whether a class carries {@code @RegisterCommand}. */
|
||||
private static final class CommandAnnotation extends ClassVisitor
|
||||
{
|
||||
/** The internal name of the class when it carries the annotation. */
|
||||
private @Nullable String name;
|
||||
|
||||
private @Nullable String visited;
|
||||
|
||||
private CommandAnnotation() { super(Opcodes.ASM9); }
|
||||
|
||||
@Override
|
||||
public void visit(int version, int access, String name, @Nullable String signature, @Nullable String superName, String @Nullable [] interfaces) { this.visited = name; }
|
||||
|
||||
@Override
|
||||
public @Nullable AnnotationVisitor visitAnnotation(String descriptor, boolean visible)
|
||||
{
|
||||
if (ModVerifier.REGISTER_COMMAND.equals(descriptor)) this.name = this.visited;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Collects the classes and members that code uses; skips annotations and debug information. */
|
||||
private static final class References extends ClassVisitor
|
||||
{
|
||||
|
||||
@@ -3,16 +3,24 @@ 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;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
@@ -20,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
|
||||
{
|
||||
@@ -27,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); }
|
||||
@@ -77,10 +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;
|
||||
|
||||
private ModEvents(String id, Executor modThread, 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<>());
|
||||
|
||||
/** 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;
|
||||
@@ -99,15 +137,79 @@ public final class EventBus
|
||||
return this.register(type, listener, this.modThread);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Subscription register(Object listener)
|
||||
{
|
||||
Objects.requireNonNull(listener, "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 = 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");
|
||||
Objects.requireNonNull(listener, "listener");
|
||||
|
||||
Listener registered = new Listener(this.id, type, event -> listener.accept(type.cast(event)), executor, this.logger);
|
||||
EventBus.this.add(registered);
|
||||
return this.add(type, event -> listener.accept(type.cast(event)), executor, null);
|
||||
}
|
||||
|
||||
return registered;
|
||||
/** @param method the name of the listener method, or {@code null} for a lambda */
|
||||
private Listener add(Class<?> type, Consumer<Object> action, @Nullable Executor executor, @Nullable String method)
|
||||
{
|
||||
Listener listener = new Listener(this.id, type, method, action, executor, this.logger);
|
||||
EventBus.this.add(listener);
|
||||
|
||||
return listener;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,6 +218,7 @@ public final class EventBus
|
||||
private final String mod;
|
||||
private final Class<?> type;
|
||||
private final String kind;
|
||||
private final String name;
|
||||
private final Consumer<Object> action;
|
||||
private final @Nullable Executor executor;
|
||||
private final System.Logger logger;
|
||||
@@ -123,11 +226,13 @@ public final class EventBus
|
||||
|
||||
private volatile boolean active = true;
|
||||
|
||||
private Listener(String mod, Class<?> type, Consumer<Object> action, @Nullable Executor executor, System.Logger logger)
|
||||
/** @param method the name of the listener method, or {@code null} for a lambda */
|
||||
private Listener(String mod, Class<?> type, @Nullable String method, Consumer<Object> action, @Nullable Executor executor, System.Logger logger)
|
||||
{
|
||||
this.mod = mod;
|
||||
this.type = type;
|
||||
this.kind = "listener " + type.getSimpleName();
|
||||
this.kind = "listener " + type.getSimpleName() + (method == null ? "" : "#" + method);
|
||||
this.name = method == null ? "Listener for '" + type.getSimpleName() + "'" : "Listener '" + method + "' for '" + type.getSimpleName() + "'";
|
||||
this.action = action;
|
||||
this.executor = executor;
|
||||
this.logger = logger;
|
||||
@@ -161,12 +266,66 @@ public final class EventBus
|
||||
if (failure == null) return;
|
||||
|
||||
int count = this.failures.incrementAndGet();
|
||||
this.logger.log(System.Logger.Level.ERROR, "Listener for '" + this.type.getSimpleName() + "' threw (failure " + count + " of " + EventBus.MAX_FAILURES + ").", failure);
|
||||
this.logger.log(System.Logger.Level.ERROR, this.name + " threw (failure " + count + " of " + EventBus.MAX_FAILURES + ").", failure);
|
||||
|
||||
if (count >= EventBus.MAX_FAILURES)
|
||||
{
|
||||
this.cancel();
|
||||
this.logger.log(System.Logger.Level.ERROR, "Listener for '" + this.type.getSimpleName() + "' removed after " + EventBus.MAX_FAILURES + " failures.");
|
||||
this.logger.log(System.Logger.Level.ERROR, this.name + " removed after " + EventBus.MAX_FAILURES + " failures.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
package dev.overlord.zomboidforge.core.runtime;
|
||||
|
||||
import dev.overlord.zomboidforge.api.ClientCommandEvent;
|
||||
import dev.overlord.zomboidforge.api.Event;
|
||||
import dev.overlord.zomboidforge.api.MainThreadEvent;
|
||||
import dev.overlord.zomboidforge.api.Mod;
|
||||
import dev.overlord.zomboidforge.api.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 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. 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.
|
||||
*
|
||||
* <p>{@link #check} runs the same rules on a class without an object, for build-time checks.
|
||||
*/
|
||||
public 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}, {@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 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 Found scan(Object target)
|
||||
{
|
||||
List<String> problems = new ArrayList<>();
|
||||
Found found = ListenerScanner.scan(target.getClass(), target, problems);
|
||||
|
||||
if (!problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems));
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
/**
|
||||
* The problems that {@code Events.register(Object)} reports for an object of {@code type}, one
|
||||
* per method or class; empty when there are none. Nothing is called.
|
||||
*/
|
||||
public static List<String> check(Class<?> type)
|
||||
{
|
||||
List<String> problems = new ArrayList<>();
|
||||
|
||||
try { ListenerScanner.scan(type, null, problems); }
|
||||
catch (IllegalArgumentException e) { problems.add(e.getMessage()); }
|
||||
|
||||
return List.copyOf(problems);
|
||||
}
|
||||
|
||||
/**
|
||||
* The annotated methods of {@code type}, bound to {@code target}; without a target, their
|
||||
* actions do nothing. Adds the problems to {@code problems}.
|
||||
*
|
||||
* @throws IllegalArgumentException when the methods of a class cannot be read
|
||||
*/
|
||||
private static Found scan(Class<?> type, @Nullable Object target, List<String> problems)
|
||||
{
|
||||
Map<Class<?>, Method[]> hierarchy = ListenerScanner.declaredMethods(type);
|
||||
List<Class<?>> types = List.copyOf(hierarchy.keySet());
|
||||
List<ListenerMethod> listeners = new ArrayList<>();
|
||||
List<ScheduledMethod> schedules = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < types.size(); i++)
|
||||
{
|
||||
List<Class<?>> subclasses = types.subList(i + 1, types.size());
|
||||
|
||||
for (Method method : hierarchy.get(types.get(i)))
|
||||
{
|
||||
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 (kinds == 0 || method.isBridge() || method.isSynthetic()) continue;
|
||||
if (ListenerScanner.isOverridden(method, subclasses, hierarchy)) continue;
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
return new Found(List.copyOf(listeners), List.copyOf(schedules));
|
||||
}
|
||||
|
||||
/**
|
||||
* The declared methods of {@code type} and its superclasses up to {@link Mod} or
|
||||
* {@code Object}, superclass first, each sorted by {@link #ORDER}.
|
||||
*
|
||||
* @throws IllegalArgumentException when the methods of a class cannot be read
|
||||
*/
|
||||
private static Map<Class<?>, Method[]> declaredMethods(Class<?> type)
|
||||
{
|
||||
List<Class<?>> classes = new ArrayList<>();
|
||||
for (Class<?> current = type; current != null && current != Object.class && current != Mod.class; current = current.getSuperclass()) classes.addFirst(current);
|
||||
|
||||
Map<Class<?>, Method[]> hierarchy = new LinkedHashMap<>();
|
||||
List<String> problems = new ArrayList<>();
|
||||
|
||||
for (Class<?> current : classes)
|
||||
{
|
||||
// Reading the methods loads every parameter and return type they name.
|
||||
try
|
||||
{
|
||||
Method[] methods = current.getDeclaredMethods();
|
||||
Arrays.sort(methods, ListenerScanner.ORDER);
|
||||
hierarchy.put(current, methods);
|
||||
}
|
||||
catch (LinkageError e) { problems.add("Cannot read the methods of '" + current.getName() + "': " + e + "."); }
|
||||
}
|
||||
|
||||
if (!problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems));
|
||||
|
||||
return hierarchy;
|
||||
}
|
||||
|
||||
/** Whether one of {@code subclasses} declares a method that overrides {@code method}. */
|
||||
private static boolean isOverridden(Method method, List<Class<?>> subclasses, Map<Class<?>, Method[]> hierarchy)
|
||||
{
|
||||
int modifiers = method.getModifiers();
|
||||
if (Modifier.isStatic(modifiers) || Modifier.isPrivate(modifiers)) return false;
|
||||
|
||||
Class<?> owner = method.getDeclaringClass();
|
||||
boolean packagePrivate = !Modifier.isPublic(modifiers) && !Modifier.isProtected(modifiers);
|
||||
|
||||
for (Class<?> subclass : subclasses)
|
||||
{
|
||||
// A package-private method is only overridden in the same runtime package.
|
||||
if (packagePrivate && (subclass.getClassLoader() != owner.getClassLoader() || !subclass.getPackageName().equals(owner.getPackageName()))) continue;
|
||||
|
||||
for (Method candidate : hierarchy.get(subclass))
|
||||
{
|
||||
if (Modifier.isStatic(candidate.getModifiers()) || Modifier.isPrivate(candidate.getModifiers())) continue;
|
||||
if (candidate.getName().equals(method.getName()) && Arrays.equals(candidate.getParameterTypes(), method.getParameterTypes())) return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The listener for {@code method}, or {@code null} after adding its problems to {@code problems}. */
|
||||
private static @Nullable ListenerMethod listener(@Nullable Object target, Method method, boolean modThread, @Nullable OnClientCommand clientCommand, String where, List<String> problems)
|
||||
{
|
||||
Class<?>[] parameters = method.getParameterTypes();
|
||||
int before = problems.size();
|
||||
|
||||
if (method.getReturnType() != void.class) problems.add(where + " must return void.");
|
||||
if (clientCommand != null && clientCommand.module().isBlank()) problems.add(where + ": @OnClientCommand needs a module.");
|
||||
|
||||
if (parameters.length != 1)
|
||||
{
|
||||
problems.add(where + " must have one parameter, the event; found " + parameters.length + ".");
|
||||
return null;
|
||||
}
|
||||
|
||||
Class<?> type = parameters[0];
|
||||
|
||||
if (!Event.class.isAssignableFrom(type))
|
||||
problems.add(where + ": the parameter type '" + type.getName() + "' does not implement Event.");
|
||||
else if (type.isInterface() || Modifier.isAbstract(type.getModifiers()))
|
||||
problems.add(where + ": the parameter type '" + type.getName() + "' is " + (type.isInterface() ? "an interface" : "abstract") + "; listeners are matched by the event's exact class.");
|
||||
else if (modThread && MainThreadEvent.class.isAssignableFrom(type))
|
||||
problems.add(where + ": '" + type.getName() + "' is a main-thread event; annotate the method with @OnMain.");
|
||||
else if (clientCommand != null && type != ClientCommandEvent.class)
|
||||
problems.add(where + ": @OnClientCommand methods take a ClientCommandEvent, found '" + type.getName() + "'.");
|
||||
|
||||
if (problems.size() > before) return null;
|
||||
|
||||
MethodHandle invoker = ListenerScanner.handle(target, method, MethodType.methodType(void.class, Object.class), where, problems);
|
||||
if (invoker == null) return null;
|
||||
|
||||
Consumer<Object> call = event -> {
|
||||
try { invoker.invokeExact(event); }
|
||||
catch (Throwable t) { throw ListenerScanner.<RuntimeException>rethrow(t); }
|
||||
};
|
||||
|
||||
return clientCommand == null
|
||||
? new ListenerMethod(type, !modThread, method.getName(), call)
|
||||
: new ListenerMethod(type, true, method.getName(), ListenerScanner.filter(clientCommand, call));
|
||||
}
|
||||
|
||||
/** The {@link TickEvent} listener for an {@link EveryNTicks} method, or {@code null} after adding its problems to {@code problems}. */
|
||||
private static @Nullable ListenerMethod everyNTicks(@Nullable 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(@Nullable 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}. Without a target, the
|
||||
* access is checked and the handle does nothing.
|
||||
*/
|
||||
private static @Nullable MethodHandle handle(@Nullable Object target, Method method, MethodType type, String where, List<String> problems)
|
||||
{
|
||||
try
|
||||
{
|
||||
MethodHandle handle = MethodHandles.privateLookupIn(method.getDeclaringClass(), MethodHandles.lookup()).unreflect(method);
|
||||
|
||||
if (target == null) return MethodHandles.empty(type);
|
||||
if (!Modifier.isStatic(method.getModifiers())) handle = handle.bindTo(target);
|
||||
|
||||
return handle.asType(type);
|
||||
}
|
||||
catch (IllegalAccessException e)
|
||||
{
|
||||
problems.add(where + " cannot be accessed: " + e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 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)
|
||||
{
|
||||
String module = annotation.module();
|
||||
String command = annotation.command();
|
||||
boolean cancel = annotation.cancel();
|
||||
|
||||
return event -> {
|
||||
ClientCommandEvent received = (ClientCommandEvent) event;
|
||||
|
||||
if (!received.module().equals(module)) return;
|
||||
if (!command.isEmpty() && !received.command().equals(command)) return;
|
||||
|
||||
if (cancel) received.cancel();
|
||||
call.accept(event);
|
||||
};
|
||||
}
|
||||
|
||||
/** Throws {@code t} unchanged, also a checked exception; the listener's caller logs every {@code Throwable}. */
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T extends Throwable> RuntimeException rethrow(Throwable t) throws T { throw (T) t; }
|
||||
}
|
||||
@@ -19,7 +19,7 @@ final class ModTaskEvent extends jdk.jfr.Event
|
||||
@Label("Mod")
|
||||
String mod = "";
|
||||
|
||||
/** {@code task}, or {@code listener <event class>}. */
|
||||
/** {@code task}, {@code listener <event class>}, or {@code listener <event class>#<method>} for a listener method. */
|
||||
@Label("Kind")
|
||||
String kind = "";
|
||||
|
||||
|
||||
@@ -36,6 +36,9 @@ import java.util.stream.Collectors;
|
||||
* <li>a new primitive component, a changed type, or a different schema version needs a
|
||||
* migration from the stored version, which rebuilds the table in one transaction.</li>
|
||||
* </ul>
|
||||
*
|
||||
* The schema version and the migrations come from the record ({@link RecordSchema}), and the
|
||||
* calls of {@code TableDefinition} add to them.
|
||||
*/
|
||||
public final class ModTables implements ModStorage
|
||||
{
|
||||
@@ -110,7 +113,7 @@ public final class ModTables implements ModStorage
|
||||
if (name.length() > ModTables.NAME_MAX_LENGTH || !RecordCodec.NAME.matcher(name).matches())
|
||||
throw new IllegalArgumentException("'" + name + "' is not a valid table name: lowercase letters, digits, and single underscores, at most " + ModTables.NAME_MAX_LENGTH + " characters.");
|
||||
|
||||
return new Definition<>(name, type);
|
||||
return new Definition<>(name, type, RecordSchema.of(type));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -124,12 +127,16 @@ public final class ModTables implements ModStorage
|
||||
private final String name;
|
||||
private final Class<R> type;
|
||||
private final Map<Integer, Function<Row, R>> migrations = new HashMap<>();
|
||||
private int version = 1;
|
||||
private int version;
|
||||
|
||||
private Definition(String name, Class<R> type)
|
||||
/** @param declared the record's {@code @Schema} and {@code @Migrate} methods, which the builder calls add to */
|
||||
private Definition(String name, Class<R> type, RecordSchema<R> declared)
|
||||
{
|
||||
this.name = name;
|
||||
this.type = type;
|
||||
this.version = declared.version();
|
||||
|
||||
this.migrations.putAll(declared.migrations());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -144,7 +151,11 @@ public final class ModTables implements ModStorage
|
||||
@Override
|
||||
public TableDefinition<R> migrate(int from, Function<Row, R> migration)
|
||||
{
|
||||
this.migrations.put(from, Objects.requireNonNull(migration, "migration"));
|
||||
Objects.requireNonNull(migration, "migration");
|
||||
|
||||
if (this.migrations.putIfAbsent(from, migration) != null)
|
||||
throw new IllegalArgumentException("'" + this.type.getName() + "' has a migration from version " + from + " already, from @Migrate or migrate().");
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,8 @@ import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Converts records of one type to table rows and back. Components become columns named in
|
||||
* {@code snake_case}; accessors and the canonical constructor are resolved once.
|
||||
* {@code snake_case}, or by their {@code @Key}; accessors and the canonical constructor are
|
||||
* resolved once. {@code @Min} and {@code @Max} are for configuration records and ignored here.
|
||||
*
|
||||
* <p>Stored forms: integers and booleans as {@code INTEGER}, other numbers as {@code REAL},
|
||||
* texts, UUIDs, instants (ISO-8601), and enum constants (by name) as {@code TEXT}, bytes as
|
||||
@@ -51,10 +52,14 @@ final class RecordCodec<R extends Record>
|
||||
static <R extends Record> RecordCodec<R> of(Class<R> type)
|
||||
{
|
||||
RecordComponent[] components = type.getRecordComponents();
|
||||
List<String> names;
|
||||
List<Column> columns = new ArrayList<>();
|
||||
Class<?>[] types = new Class<?>[components.length];
|
||||
MethodHandle[] accessors = new MethodHandle[components.length];
|
||||
|
||||
try { names = RecordBinder.keys(type); }
|
||||
catch (IllegalArgumentException e) { throw new StorageException(e.getMessage(), e); }
|
||||
|
||||
try
|
||||
{
|
||||
MethodHandles.Lookup lookup = MethodHandles.privateLookupIn(type, MethodHandles.lookup());
|
||||
@@ -62,7 +67,7 @@ final class RecordCodec<R extends Record>
|
||||
for (int i = 0; i < components.length; i++)
|
||||
{
|
||||
RecordComponent component = components[i];
|
||||
String name = RecordBinder.key(component.getName());
|
||||
String name = names.get(i);
|
||||
String where = "'" + type.getSimpleName() + "." + component.getName() + "'";
|
||||
|
||||
if (!RecordCodec.NAME.matcher(name).matches()) throw new StorageException(where + " gives the column name '" + name + "'; column names are lowercase letters, digits, and single underscores.");
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package dev.overlord.zomboidforge.core.storage;
|
||||
|
||||
import dev.overlord.zomboidforge.api.annotations.Migrate;
|
||||
import dev.overlord.zomboidforge.api.annotations.Schema;
|
||||
import dev.overlord.zomboidforge.api.storage.Row;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.lang.invoke.MethodHandle;
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.lang.reflect.UndeclaredThrowableException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* The schema version and migrations that a storage record declares with {@link Schema} and
|
||||
* {@link Migrate}. Migration methods are called through method handles from a private lookup,
|
||||
* as {@link RecordCodec} reads records.
|
||||
*
|
||||
* @param version from {@link Schema}, or 1 without it
|
||||
* @param migrations stored schema version to migration, from the {@link Migrate} methods
|
||||
*/
|
||||
public record RecordSchema<R extends Record>(int version, Map<Integer, Function<Row, R>> migrations)
|
||||
{
|
||||
public RecordSchema
|
||||
{
|
||||
migrations = Map.copyOf(migrations);
|
||||
}
|
||||
|
||||
/**
|
||||
* The problems that {@link #of} reports for {@code type}, in one message; empty when there are
|
||||
* none. For build-time checks.
|
||||
*/
|
||||
public static List<String> check(Class<? extends Record> type)
|
||||
{
|
||||
try { RecordSchema.of(type); }
|
||||
catch (IllegalArgumentException e) { return List.of(e.getMessage()); }
|
||||
|
||||
return List.of();
|
||||
}
|
||||
|
||||
/** @throws IllegalArgumentException listing every invalid annotation of {@code type} */
|
||||
static <R extends Record> RecordSchema<R> of(Class<R> type)
|
||||
{
|
||||
Schema schema = type.getAnnotation(Schema.class);
|
||||
int version = schema == null ? 1 : schema.version();
|
||||
List<String> problems = new ArrayList<>();
|
||||
|
||||
if (version < 1) problems.add("'" + type.getName() + "': @Schema(version = " + version + ") is not a version; versions start at 1.");
|
||||
|
||||
Method[] methods;
|
||||
|
||||
// Reading the methods loads every parameter and return type they name.
|
||||
try { methods = type.getDeclaredMethods(); }
|
||||
catch (LinkageError e) { throw new IllegalArgumentException("Cannot read the methods of '" + type.getName() + "': " + e + ".", e); }
|
||||
|
||||
Arrays.sort(methods, Comparator.comparing(Method::getName));
|
||||
|
||||
Map<Integer, Function<Row, R>> migrations = new HashMap<>();
|
||||
|
||||
for (Method method : methods)
|
||||
{
|
||||
Migrate migrate = method.getAnnotation(Migrate.class);
|
||||
if (migrate == null) continue;
|
||||
|
||||
Function<Row, R> migration = RecordSchema.migration(type, method, migrate, migrations, problems);
|
||||
if (migration != null) migrations.put(migrate.from(), migration);
|
||||
}
|
||||
|
||||
if (!problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems));
|
||||
|
||||
return new RecordSchema<>(version, migrations);
|
||||
}
|
||||
|
||||
/** The migration of {@code method}, or {@code null} after adding its problems to {@code problems}. */
|
||||
private static <R extends Record> @Nullable Function<Row, R> migration(Class<R> type, Method method, Migrate migrate, Map<Integer, Function<Row, R>> found, List<String> problems)
|
||||
{
|
||||
String where = "'" + type.getName() + "." + method.getName() + "'";
|
||||
int before = problems.size();
|
||||
|
||||
if (!Modifier.isStatic(method.getModifiers())) problems.add(where + " must be static.");
|
||||
if (method.getParameterCount() != 1 || method.getParameterTypes()[0] != Row.class) problems.add(where + " must have one parameter, a Row.");
|
||||
if (method.getReturnType() != type) problems.add(where + " must return '" + type.getSimpleName() + "'.");
|
||||
|
||||
if (migrate.from() < 1) problems.add(where + ": @Migrate(from = " + migrate.from() + ") is not a version; versions start at 1.");
|
||||
else if (found.containsKey(migrate.from())) problems.add(where + ": another @Migrate method migrates from version " + migrate.from() + ".");
|
||||
|
||||
if (problems.size() > before) return null;
|
||||
|
||||
try
|
||||
{
|
||||
MethodHandle handle = MethodHandles.privateLookupIn(type, MethodHandles.lookup()).unreflect(method);
|
||||
|
||||
return row -> {
|
||||
// Checked exceptions are wrapped: the caller reports RuntimeExceptions of a migration with the row.
|
||||
try { return type.cast(handle.invoke(row)); }
|
||||
catch (RuntimeException | Error e) { throw e; }
|
||||
catch (Throwable t) { throw new UndeclaredThrowableException(t, t.toString()); }
|
||||
};
|
||||
}
|
||||
catch (IllegalAccessException e)
|
||||
{
|
||||
problems.add(where + " cannot be accessed: " + e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -117,7 +117,7 @@ final class SqlTable<R extends Record> implements Table<R>
|
||||
return found;
|
||||
});
|
||||
|
||||
return found;
|
||||
return Collections.unmodifiableMap(found);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -168,7 +168,7 @@ final class SqlTable<R extends Record> implements Table<R>
|
||||
while (rows.next()) keys.add(rows.getString(1));
|
||||
}
|
||||
|
||||
return keys;
|
||||
return Collections.unmodifiableList(keys);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -11,10 +11,14 @@ import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import testmods.AnnotatedCommandMod;
|
||||
import testmods.CommandMod;
|
||||
import testmods.ContextMod;
|
||||
import testmods.ErrorMod;
|
||||
import testmods.InvalidListenerMod;
|
||||
import testmods.ListenerMod;
|
||||
import testmods.Recorder;
|
||||
import testmods.ScheduleMod;
|
||||
import testmods.ThreadMod;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -25,6 +29,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;
|
||||
|
||||
@@ -329,6 +334,122 @@ class ForgeTest
|
||||
assertEquals(Lifecycle.Phase.STOPPING, forge.phase());
|
||||
}
|
||||
|
||||
@Test
|
||||
void registersListenerMethodsOfTheEntryPointBeforeOnLoad() throws Exception
|
||||
{
|
||||
TestMods.folder(this.mods, "listener", TestMods.toml("listener", ListenerMod.class.getName(), ""), Map.of(
|
||||
"testmods/ListenerMod", TestMods.classFile(ListenerMod.class)
|
||||
));
|
||||
|
||||
Forge forge = this.load();
|
||||
Object mod = forge.mods().getFirst().mod();
|
||||
|
||||
forge.started();
|
||||
forge.tick();
|
||||
|
||||
assertEquals(List.of("method 1", "lambda 1"), ForgeTest.field(mod, "log"), "annotated listeners come before those of onLoad()");
|
||||
|
||||
IllegalArgumentException second = assertInstanceOf(IllegalArgumentException.class, ForgeTest.field(mod, "secondRegistration"));
|
||||
assertTrue(second.getMessage().contains("testmods.ListenerMod"), second.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsBeforeOnLoadWhenAListenerMethodBreaksTheRules() throws IOException
|
||||
{
|
||||
TestMods.folder(this.mods, "invalid", TestMods.toml("invalid", InvalidListenerMod.class.getName(), ForgeTest.USES_GAME), Map.of(
|
||||
"testmods/InvalidListenerMod", TestMods.classFile(InvalidListenerMod.class)
|
||||
));
|
||||
|
||||
ModLoadException e = assertThrows(ModLoadException.class, this::load);
|
||||
|
||||
assertEquals(1, e.problems().size());
|
||||
ForgeTest.assertContainsAll(e.problems().getFirst(), "'invalid'", "testmods.InvalidListenerMod.onTick", "java.lang.String");
|
||||
assertTrue(Recorder.EVENTS.isEmpty(), "onLoad() does not run");
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsWhenTheEntryPointNamesAMissingClassInAMethod() throws IOException
|
||||
{
|
||||
// ModVerifier reports missing classes only in the game's packages, so only the scan finds this one.
|
||||
TestMods.folder(this.mods, "missing", TestMods.toml("missing", "missing.MissingMod", ""), Map.of(
|
||||
"missing/MissingMod", TestMods.type("missing/MissingMod", "dev/overlord/zomboidforge/api/Mod", null, "helper:(Lgone/Type;)V")
|
||||
));
|
||||
|
||||
ModLoadException e = assertThrows(ModLoadException.class, this::load);
|
||||
|
||||
assertEquals(1, e.problems().size());
|
||||
ForgeTest.assertContainsAll(e.problems().getFirst(), "'missing'", "missing.MissingMod", "NoClassDefFoundError", "gone/Type");
|
||||
}
|
||||
|
||||
@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();
|
||||
}
|
||||
|
||||
/** {@link AnnotatedCommandMod} and its command classes, packaged as the mod {@code commands}. */
|
||||
private void annotatedCommandMod() throws IOException
|
||||
{
|
||||
TestMods.folder(this.mods, "commands", TestMods.toml("commands", AnnotatedCommandMod.class.getName(), ""), Map.of(
|
||||
"testmods/AnnotatedCommandMod", TestMods.classFile(AnnotatedCommandMod.class),
|
||||
"testmods/AnnotatedCommandMod$Hello", TestMods.classFile(AnnotatedCommandMod.Hello.class),
|
||||
"testmods/AnnotatedCommandMod$Bye", TestMods.classFile(AnnotatedCommandMod.Bye.class),
|
||||
"testmods/AnnotatedCommandMod$Manual", TestMods.classFile(AnnotatedCommandMod.Manual.class)
|
||||
));
|
||||
}
|
||||
|
||||
@Test
|
||||
void registersAnnotatedCommandsByNameBeforeOnLoad() throws Exception
|
||||
{
|
||||
this.annotatedCommandMod();
|
||||
|
||||
Forge forge = this.load();
|
||||
String mod = AnnotatedCommandMod.class.getName();
|
||||
|
||||
assertEquals(List.of(mod + "$Bye after 0", mod + "$Hello after 1", mod + "$Manual after 2"), this.checkedCommands);
|
||||
assertEquals(3, forge.commands().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsWhenAnAnnotatedCommandBreaksTheRules() throws IOException
|
||||
{
|
||||
this.annotatedCommandMod();
|
||||
|
||||
Forge forge = new Forge(
|
||||
this.directory,
|
||||
ModVersion.parse("0.3.0"),
|
||||
(command, registered) -> { throw new IllegalArgumentException("'" + command.getName() + "' has no @CommandName."); },
|
||||
(player, module, command, args) -> () -> {}
|
||||
);
|
||||
|
||||
ModLoadException e = assertThrows(ModLoadException.class, () -> forge.load(ForgeTest.GAME, this.gameJar, ForgeTest.class.getClassLoader(), this.storageFile));
|
||||
|
||||
assertEquals(1, e.problems().size());
|
||||
ForgeTest.assertContainsAll(e.problems().getFirst(), "'commands'", "AnnotatedCommandMod$Bye");
|
||||
}
|
||||
|
||||
private static void assertContainsAll(String message, String... parts)
|
||||
{
|
||||
for (String part : parts) assertTrue(message.contains(part), "'" + part + "' missing in: " + message);
|
||||
}
|
||||
|
||||
private static void await(BooleanSupplier condition) throws InterruptedException
|
||||
{
|
||||
long deadline = System.nanoTime() + 5_000_000_000L;
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package dev.overlord.zomboidforge.core.config;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class FeatureTest
|
||||
{
|
||||
@Test
|
||||
void keyAndPropertyFollowFromTheName()
|
||||
{
|
||||
assertEquals("experimental_performance", Feature.EXPERIMENTAL_PERFORMANCE.key());
|
||||
assertEquals("zomboidforge.features.experimental_performance", Feature.EXPERIMENTAL_PERFORMANCE.property());
|
||||
}
|
||||
|
||||
@Test
|
||||
void findsFeaturesByKey()
|
||||
{
|
||||
assertEquals(Optional.of(Feature.EXPERIMENTAL_PERFORMANCE), Feature.byKey("experimental_performance"));
|
||||
assertEquals(Optional.empty(), Feature.byKey("EXPERIMENTAL_PERFORMANCE"));
|
||||
assertEquals(Optional.empty(), Feature.byKey("faster"));
|
||||
}
|
||||
}
|
||||
@@ -6,9 +6,13 @@ import org.junit.jupiter.api.io.TempDir;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
|
||||
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 ForgeSettingsTest
|
||||
{
|
||||
@@ -16,27 +20,41 @@ class ForgeSettingsTest
|
||||
Path directory;
|
||||
|
||||
private ForgeSettings read(String toml) throws Exception
|
||||
{
|
||||
return this.read(toml, new Properties());
|
||||
}
|
||||
|
||||
private ForgeSettings read(String toml, Properties properties) throws Exception
|
||||
{
|
||||
Path file = this.directory.resolve(ForgeSettings.FILE);
|
||||
Files.writeString(file, toml);
|
||||
|
||||
return ForgeSettings.read(file);
|
||||
return ForgeSettings.read(file, properties);
|
||||
}
|
||||
|
||||
private static Properties properties(String... namesAndValues)
|
||||
{
|
||||
Properties properties = new Properties();
|
||||
for (int i = 0; i < namesAndValues.length; i += 2) properties.setProperty(namesAndValues[i], namesAndValues[i + 1]);
|
||||
|
||||
return properties;
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultsWithoutFileOrKeys() throws Exception
|
||||
{
|
||||
assertEquals(ForgeSettings.DEFAULTS, ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE)));
|
||||
assertEquals(ForgeSettings.DEFAULTS, ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE), new Properties()));
|
||||
assertEquals(ForgeSettings.DEFAULTS, this.read("[main_thread]\n"));
|
||||
assertEquals(new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10)), ForgeSettings.DEFAULTS);
|
||||
assertEquals(new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10), Set.of()), ForgeSettings.DEFAULTS);
|
||||
assertFalse(ForgeSettings.DEFAULTS.enabled(Feature.EXPERIMENTAL_PERFORMANCE));
|
||||
}
|
||||
|
||||
@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")
|
||||
new ForgeSettings(Duration.ofMillis(5), Duration.ofSeconds(0), Set.of(Feature.EXPERIMENTAL_PERFORMANCE)),
|
||||
this.read("[main_thread]\nbudget_ms = 5\n\n[shutdown]\ntimeout_s = 0\n\n[features]\nexperimental_performance = true\n")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -52,4 +70,50 @@ class ForgeSettingsTest
|
||||
IllegalArgumentException type = assertThrows(IllegalArgumentException.class, () -> this.read("[shutdown]\ntimeout_s = \"10\"\n"));
|
||||
assertEquals("'shutdown.timeout_s' must be an integer, found \"10\".", type.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void featuresAreOffUnlessSwitchedOn() throws Exception
|
||||
{
|
||||
assertFalse(this.read("[features]\nexperimental_performance = false\n").enabled(Feature.EXPERIMENTAL_PERFORMANCE));
|
||||
assertTrue(this.read("[features]\nexperimental_performance = true\n").enabled(Feature.EXPERIMENTAL_PERFORMANCE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void systemPropertyTakesPrecedenceOverTheFile() throws Exception
|
||||
{
|
||||
String property = Feature.EXPERIMENTAL_PERFORMANCE.property();
|
||||
|
||||
assertTrue(this.read("", ForgeSettingsTest.properties(property, "true")).enabled(Feature.EXPERIMENTAL_PERFORMANCE));
|
||||
assertTrue(this.read("[features]\nexperimental_performance = false\n", ForgeSettingsTest.properties(property, "TRUE")).enabled(Feature.EXPERIMENTAL_PERFORMANCE));
|
||||
assertFalse(this.read("[features]\nexperimental_performance = true\n", ForgeSettingsTest.properties(property, "false")).enabled(Feature.EXPERIMENTAL_PERFORMANCE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void systemPropertyAppliesWithoutFile()
|
||||
{
|
||||
Properties properties = ForgeSettingsTest.properties(Feature.EXPERIMENTAL_PERFORMANCE.property(), "true");
|
||||
|
||||
assertTrue(ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE), properties).enabled(Feature.EXPERIMENTAL_PERFORMANCE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsUnknownFeaturesAndInvalidPropertyValues()
|
||||
{
|
||||
IllegalArgumentException key = assertThrows(IllegalArgumentException.class, () -> this.read("[features]\nexperimental_performance = \"yes\"\nfaster = true\n"));
|
||||
assertEquals("'features.experimental_performance' must be true or false, found \"yes\".", key.getMessage());
|
||||
|
||||
IllegalArgumentException unknown = assertThrows(IllegalArgumentException.class, () -> this.read("[features]\nfaster = true\n"));
|
||||
assertEquals("Unknown key 'features.faster'.", unknown.getMessage());
|
||||
|
||||
Properties properties = ForgeSettingsTest.properties(
|
||||
"zomboidforge.features.faster", "true",
|
||||
Feature.EXPERIMENTAL_PERFORMANCE.property(), "yes",
|
||||
"zomboidforge.dir", "/forge"
|
||||
);
|
||||
IllegalArgumentException property = assertThrows(IllegalArgumentException.class, () -> this.read("", properties));
|
||||
assertEquals(
|
||||
"System property 'zomboidforge.features.experimental_performance' must be true or false, found \"yes\". Unknown system property 'zomboidforge.features.faster'.",
|
||||
property.getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
package dev.overlord.zomboidforge.core.config;
|
||||
|
||||
import dev.overlord.zomboidforge.api.annotations.Key;
|
||||
import dev.overlord.zomboidforge.api.annotations.Max;
|
||||
import dev.overlord.zomboidforge.api.annotations.Min;
|
||||
import dev.overlord.zomboidforge.core.ConsoleLogger;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -9,7 +12,9 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class TomlModConfigTest
|
||||
{
|
||||
@@ -30,6 +35,28 @@ class TomlModConfigTest
|
||||
Optional<Integer> httpPort
|
||||
) {}
|
||||
|
||||
private record Renamed(@Key("max_hp_regen") int healthRegenPerHour, String name) {}
|
||||
|
||||
private record InvalidKey(@Key("Max HP") int maxHp) {}
|
||||
|
||||
private record RepeatedKey(@Key("value") int amount, int value) {}
|
||||
|
||||
private record Bounded(
|
||||
@Min(1) @Max(100) int maxPlayers,
|
||||
@Min(0) double ratio,
|
||||
@Max(10) List<Long> levels,
|
||||
@Min(1) Optional<Integer> port,
|
||||
@Min(1) Map<String, Long> prices
|
||||
) {}
|
||||
|
||||
private record FractionalBounds(@Min(0.1) @Max(0.5) double ratio) {}
|
||||
|
||||
private record BoundedText(@Min(1) String name) {}
|
||||
|
||||
private record NotANumberBound(@Min(Double.NaN) double ratio) {}
|
||||
|
||||
private record InvertedBounds(@Min(5) @Max(1) int amount) {}
|
||||
|
||||
private static TomlModConfig config(String defaults, String settings)
|
||||
{
|
||||
return new TomlModConfig(TomlTree.merge(TomlTree.parse(defaults), TomlTree.parse(settings)), new ConsoleLogger("test"));
|
||||
@@ -133,4 +160,88 @@ class TomlModConfigTest
|
||||
|
||||
assertEquals(Map.of("a", 1L, "b", 2.5, "t", Map.of("x", 1L, "y", 3L)), merged);
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsComponentsByTheirKeyAnnotation()
|
||||
{
|
||||
Renamed renamed = TomlModConfigTest.config("max_hp_regen = 5\nname = \"a\"\n", "").bind(Renamed.class);
|
||||
|
||||
assertEquals(new Renamed(5, "a"), renamed);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsInvalidAndRepeatedKeys()
|
||||
{
|
||||
TomlModConfig config = TomlModConfigTest.config("value = 1\n", "");
|
||||
|
||||
IllegalArgumentException invalid = assertThrows(IllegalArgumentException.class, () -> config.bind(InvalidKey.class));
|
||||
IllegalArgumentException repeated = assertThrows(IllegalArgumentException.class, () -> config.bind(RepeatedKey.class));
|
||||
|
||||
TomlModConfigTest.assertContainsAll(invalid.getMessage(), InvalidKey.class.getName() + ".maxHp", "Max HP");
|
||||
TomlModConfigTest.assertContainsAll(repeated.getMessage(), RepeatedKey.class.getName(), "'value'");
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsValuesOutsideTheirBoundsWithEveryOtherProblem()
|
||||
{
|
||||
String valid = """
|
||||
max_players = 100
|
||||
ratio = 0.0
|
||||
levels = [10]
|
||||
port = 1
|
||||
|
||||
[prices]
|
||||
apple = 1
|
||||
""";
|
||||
|
||||
assertEquals(new Bounded(100, 0.0, List.of(10L), Optional.of(1), Map.of("apple", 1L)), TomlModConfigTest.config(valid, "").bind(Bounded.class));
|
||||
|
||||
TomlModConfig invalid = TomlModConfigTest.config("""
|
||||
max_players = 250
|
||||
ratio = -0.5
|
||||
levels = [1, 11]
|
||||
port = 0
|
||||
|
||||
[prices]
|
||||
apple = 0
|
||||
""", "");
|
||||
|
||||
IllegalStateException e = assertThrows(IllegalStateException.class, () -> invalid.bind(Bounded.class));
|
||||
|
||||
TomlModConfigTest.assertContainsAll(e.getMessage(), "'max_players'", "100", "250", "'ratio'", "-0.5", "'levels[1]'", "11", "'port'", "'prices.apple'");
|
||||
assertFalse(e.getMessage().contains("100.0"), "whole bounds without a decimal point: " + e.getMessage());
|
||||
assertFalse(e.getMessage().contains("levels[0]"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsBoundsOnNonNumbersAndInvertedBounds()
|
||||
{
|
||||
TomlModConfig config = TomlModConfigTest.config("name = \"a\"\namount = 3\n", "");
|
||||
|
||||
IllegalArgumentException text = assertThrows(IllegalArgumentException.class, () -> config.bind(BoundedText.class));
|
||||
IllegalArgumentException inverted = assertThrows(IllegalArgumentException.class, () -> config.bind(InvertedBounds.class));
|
||||
|
||||
TomlModConfigTest.assertContainsAll(text.getMessage(), BoundedText.class.getName() + ".name");
|
||||
TomlModConfigTest.assertContainsAll(inverted.getMessage(), InvertedBounds.class.getName() + ".amount", "5", "1");
|
||||
|
||||
IllegalArgumentException notANumber = assertThrows(IllegalArgumentException.class, () -> TomlModConfigTest.config("ratio = 0.5\n", "").bind(NotANumberBound.class));
|
||||
TomlModConfigTest.assertContainsAll(notANumber.getMessage(), NotANumberBound.class.getName() + ".ratio");
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsFractionalBounds()
|
||||
{
|
||||
assertEquals(new FractionalBounds(0.5), TomlModConfigTest.config("ratio = 0.5\n", "").bind(FractionalBounds.class));
|
||||
|
||||
IllegalStateException above = assertThrows(IllegalStateException.class, () -> TomlModConfigTest.config("ratio = 0.75\n", "").bind(FractionalBounds.class));
|
||||
IllegalStateException below = assertThrows(IllegalStateException.class, () -> TomlModConfigTest.config("ratio = 0.05\n", "").bind(FractionalBounds.class));
|
||||
|
||||
TomlModConfigTest.assertContainsAll(above.getMessage(), "'ratio'", "0.5", "0.75");
|
||||
TomlModConfigTest.assertContainsAll(below.getMessage(), "'ratio'", "0.1", "0.05");
|
||||
}
|
||||
|
||||
private static void assertContainsAll(String message, String... parts)
|
||||
{
|
||||
for (String part : parts) assertTrue(message.contains(part), "'" + part + "' missing in: " + message);
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,22 @@ class ModVerifierTest
|
||||
return e.problems();
|
||||
}
|
||||
|
||||
@Test
|
||||
void collectsTheRegisteredCommandsOfEachModsOwnJar() throws Exception
|
||||
{
|
||||
String annotation = "Ldev/overlord/zomboidforge/api/annotations/RegisterCommand;";
|
||||
|
||||
ModDiscovery.Candidate mod = this.mod("commands", "", Map.of(
|
||||
"a/Zeta", TestMods.type("a/Zeta", "java/lang/Object", annotation),
|
||||
"a/Alpha", TestMods.type("a/Alpha", "java/lang/Object", annotation),
|
||||
"a/Plain", TestMods.type("a/Plain", "java/lang/Object", null)
|
||||
), Map.of("lib/Bundled", TestMods.type("lib/Bundled", "java/lang/Object", annotation)));
|
||||
|
||||
Map<String, List<String>> commands = assertDoesNotThrow(() -> ModVerifier.verify(List.of(mod), this.game, ModVerifierTest.GAME));
|
||||
|
||||
assertEquals(Map.of("commands", List.of("a.Alpha", "a.Zeta")), commands, "sorted, own jar only");
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsGameUseWithDeclaredVersionsThatLinks() throws Exception
|
||||
{
|
||||
|
||||
@@ -1,16 +1,33 @@
|
||||
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;
|
||||
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.concurrent.Executor;
|
||||
import java.util.Map;
|
||||
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;
|
||||
@@ -21,13 +38,204 @@ class EventBusTest
|
||||
{
|
||||
private record Joined(String player) implements Event {}
|
||||
|
||||
private record Left(String player) implements Event {}
|
||||
|
||||
private abstract static class AbstractEvent implements Event {}
|
||||
|
||||
/** Listener methods in a superclass of {@link Listeners}. */
|
||||
private static class BaseListeners
|
||||
{
|
||||
static final List<String> LOG = new ArrayList<>();
|
||||
|
||||
@OnMain
|
||||
void base(Joined event) { BaseListeners.LOG.add("base " + event.player()); }
|
||||
|
||||
/** Overridden without the annotation, so it does not listen. */
|
||||
@OnMain
|
||||
void replaced(Joined event) { BaseListeners.LOG.add("base replaced"); }
|
||||
|
||||
/** Overridden with the annotation, so the override listens once. */
|
||||
@OnMain
|
||||
void kept(Joined event) { BaseListeners.LOG.add("base kept"); }
|
||||
}
|
||||
|
||||
private static final class Listeners extends BaseListeners
|
||||
{
|
||||
@OnMain
|
||||
static void a(Joined event) { BaseListeners.LOG.add("static a " + event.player()); }
|
||||
|
||||
@OnMain
|
||||
private void b(Joined event) { BaseListeners.LOG.add("private b " + event.player()); }
|
||||
|
||||
@Override
|
||||
void replaced(Joined event) { BaseListeners.LOG.add("override replaced"); }
|
||||
|
||||
@OnMain
|
||||
@Override
|
||||
void kept(Joined event) { BaseListeners.LOG.add("override kept"); }
|
||||
|
||||
@OnModThread
|
||||
void left(Left event) { BaseListeners.LOG.add("left " + event.player()); }
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
void notAListener(Joined event) { BaseListeners.LOG.add("not a listener"); }
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private static final class InvalidListeners
|
||||
{
|
||||
@OnMain
|
||||
@OnModThread
|
||||
void both(Joined event) {}
|
||||
|
||||
@OnMain
|
||||
String returns(Joined event) { return ""; }
|
||||
|
||||
@OnMain
|
||||
void two(Joined first, Joined second) {}
|
||||
|
||||
@OnMain
|
||||
void notEvent(String text) {}
|
||||
|
||||
@OnMain
|
||||
void anInterface(Event event) {}
|
||||
|
||||
@OnMain
|
||||
void anAbstract(AbstractEvent event) {}
|
||||
|
||||
@OnModThread
|
||||
void mainOnly(TickEvent event) {}
|
||||
|
||||
@OnClientCommand(module = "Shop")
|
||||
void wrongEvent(Joined event) {}
|
||||
|
||||
@OnClientCommand(module = " ")
|
||||
void noModule(ClientCommandEvent event) {}
|
||||
|
||||
@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}. */
|
||||
private static final class ShopCommands
|
||||
{
|
||||
final List<String> log = new ArrayList<>();
|
||||
|
||||
@OnClientCommand(module = "Shop")
|
||||
void any(ClientCommandEvent event) { this.log.add("any " + event.command() + (event.isCancelled() ? " cancelled" : "")); }
|
||||
|
||||
@OnClientCommand(module = "Shop", command = "buy", cancel = true)
|
||||
void buy(ClientCommandEvent event) { this.log.add("buy" + (event.isCancelled() ? " cancelled" : "")); }
|
||||
}
|
||||
|
||||
private static final class FailingCommand
|
||||
{
|
||||
@OnClientCommand(module = "Shop", cancel = true)
|
||||
void fail(ClientCommandEvent event) { throw new IllegalStateException("broken"); }
|
||||
}
|
||||
|
||||
private static final class FailingListener
|
||||
{
|
||||
@OnMain
|
||||
void fail(Joined event) throws IOException { throw new IOException("broken"); }
|
||||
}
|
||||
|
||||
private final EventBus bus = new EventBus();
|
||||
private final RecordingLogger logger = new RecordingLogger();
|
||||
private final List<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()
|
||||
@@ -102,4 +310,171 @@ class EventBusTest
|
||||
|
||||
assertTrue(this.received.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void registersAnnotatedMethodsOfAnObjectAndItsSuperclasses()
|
||||
{
|
||||
Events a = this.bus.forMod("a", this.modThread, this.logger);
|
||||
BaseListeners.LOG.clear();
|
||||
|
||||
a.register(new Listeners());
|
||||
this.bus.post(new Joined("bob"));
|
||||
this.bus.post(new Left("eve"));
|
||||
|
||||
assertEquals(List.of("base bob", "static a bob", "private b bob", "override kept"), BaseListeners.LOG, "superclass first, then by name; overridden methods once");
|
||||
assertEquals(1, this.modTasks.size());
|
||||
|
||||
this.modTasks.getFirst().run();
|
||||
assertEquals("left eve", BaseListeners.LOG.getLast());
|
||||
}
|
||||
|
||||
@Test
|
||||
void registersAnObjectOnceUntilItsSubscriptionIsCancelled()
|
||||
{
|
||||
Events a = this.bus.forMod("a", this.modThread, this.logger);
|
||||
Listeners listeners = new Listeners();
|
||||
Subscription subscription = a.register(listeners);
|
||||
|
||||
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> a.register(listeners));
|
||||
assertTrue(e.getMessage().contains(Listeners.class.getName()), e.getMessage());
|
||||
|
||||
subscription.cancel();
|
||||
assertFalse(this.bus.hasListeners(Joined.class));
|
||||
assertFalse(this.bus.hasListeners(Left.class));
|
||||
|
||||
Subscription again = a.register(listeners);
|
||||
subscription.cancel();
|
||||
assertTrue(this.bus.hasListeners(Joined.class), "cancelling the old subscription again leaves the new one");
|
||||
|
||||
again.cancel();
|
||||
assertFalse(this.bus.hasListeners(Joined.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsInvalidListenerMethodsWithEveryProblem()
|
||||
{
|
||||
Events a = this.bus.forMod("a", this.modThread, this.logger);
|
||||
|
||||
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> a.register(new InvalidListeners()));
|
||||
|
||||
// Every method, and the parameter types that break a rule.
|
||||
for (String method : List.of("anAbstract", "anInterface", "both", "mainOnly", "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");
|
||||
assertFalse(this.bus.hasListeners(Joined.class), "nothing is registered");
|
||||
}
|
||||
|
||||
@Test
|
||||
void logsWhatListenerMethodsThrowWithTheirName()
|
||||
{
|
||||
this.bus.forMod("a", this.modThread, this.logger).register(new FailingListener());
|
||||
|
||||
this.bus.post(new Joined("bob"));
|
||||
|
||||
assertEquals(1, this.logger.messages.size());
|
||||
EventBusTest.assertContainsAll(this.logger.messages.getFirst(), "ERROR", "'fail'", "Joined", "java.io.IOException: broken");
|
||||
}
|
||||
|
||||
@Test
|
||||
void clientCommandMethodsReceiveTheirModuleAndCommandOnly()
|
||||
{
|
||||
Events a = this.bus.forMod("a", this.modThread, this.logger);
|
||||
ShopCommands commands = new ShopCommands();
|
||||
a.register(commands);
|
||||
|
||||
ClientCommandEvent buy = EventBusTest.command("Shop", "buy");
|
||||
ClientCommandEvent sell = EventBusTest.command("Shop", "sell");
|
||||
ClientCommandEvent other = EventBusTest.command("Bank", "buy");
|
||||
|
||||
this.bus.post(buy);
|
||||
this.bus.post(sell);
|
||||
this.bus.post(other);
|
||||
|
||||
assertEquals(List.of("any buy", "buy cancelled", "any sell"), commands.log, "cancelled before the method runs, after the listeners before it");
|
||||
assertTrue(buy.isCancelled());
|
||||
assertFalse(sell.isCancelled());
|
||||
assertFalse(other.isCancelled());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clientCommandMethodsCancelAlsoWhenTheyThrow()
|
||||
{
|
||||
this.bus.forMod("a", this.modThread, this.logger).register(new FailingCommand());
|
||||
|
||||
ClientCommandEvent event = EventBusTest.command("Shop", "buy");
|
||||
this.bus.post(event);
|
||||
|
||||
assertTrue(event.isCancelled());
|
||||
assertEquals(1, this.logger.messages.size());
|
||||
EventBusTest.assertContainsAll(this.logger.messages.getFirst(), "'fail'", "ClientCommandEvent", "broken");
|
||||
}
|
||||
|
||||
@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)
|
||||
{
|
||||
for (String part : parts) assertTrue(message.contains(part), "'" + part + "' missing in: " + message);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,11 @@
|
||||
package dev.overlord.zomboidforge.core.storage;
|
||||
|
||||
import dev.overlord.zomboidforge.api.annotations.Key;
|
||||
import dev.overlord.zomboidforge.api.annotations.Migrate;
|
||||
import dev.overlord.zomboidforge.api.annotations.Min;
|
||||
import dev.overlord.zomboidforge.api.annotations.Schema;
|
||||
import dev.overlord.zomboidforge.api.storage.ModStorage;
|
||||
import dev.overlord.zomboidforge.api.storage.Row;
|
||||
import dev.overlord.zomboidforge.api.storage.StorageException;
|
||||
import dev.overlord.zomboidforge.api.storage.Table;
|
||||
import dev.overlord.zomboidforge.core.RecordingLogger;
|
||||
@@ -11,6 +16,7 @@ import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
@@ -53,6 +59,48 @@ class ModTablesTest
|
||||
|
||||
private record RenamedDifficulty(RenamedMode mode) {}
|
||||
|
||||
/** {@link Balance} with the component renamed; {@code @Min} only applies to configuration. */
|
||||
private record RenamedBalance(@Key("coins") @Min(100) long amount) {}
|
||||
|
||||
private record RepeatedColumn(@Key("coins") long amount, long coins) {}
|
||||
|
||||
@Schema(version = 2)
|
||||
private record AnnotatedLevel(long coins, int level)
|
||||
{
|
||||
@Migrate(from = 1)
|
||||
private static AnnotatedLevel fromV1(Row row) { return new AnnotatedLevel(row.getLong("coins") * 10, 1); }
|
||||
}
|
||||
|
||||
@Schema(version = 2)
|
||||
private record FailingMigration(long coins, int level)
|
||||
{
|
||||
@Migrate(from = 1)
|
||||
static FailingMigration fromV1(Row row) throws IOException { throw new IOException("broken"); }
|
||||
}
|
||||
|
||||
@Schema(version = 0)
|
||||
@SuppressWarnings("unused")
|
||||
private record InvalidSchema(long coins)
|
||||
{
|
||||
@Migrate(from = 0)
|
||||
static InvalidSchema zero(Row row) { return new InvalidSchema(0); }
|
||||
|
||||
@Migrate(from = 1)
|
||||
InvalidSchema notStatic(Row row) { return this; }
|
||||
|
||||
@Migrate(from = 2)
|
||||
static InvalidSchema twoParameters(Row row, Row other) { return new InvalidSchema(0); }
|
||||
|
||||
@Migrate(from = 3)
|
||||
static String wrongReturn(Row row) { return ""; }
|
||||
|
||||
@Migrate(from = 4)
|
||||
static InvalidSchema first(Row row) { return new InvalidSchema(0); }
|
||||
|
||||
@Migrate(from = 4)
|
||||
static InvalidSchema second(Row row) { return new InvalidSchema(0); }
|
||||
}
|
||||
|
||||
@TempDir
|
||||
Path directory;
|
||||
|
||||
@@ -277,6 +325,63 @@ class ModTablesTest
|
||||
assertEquals(Optional.of(new Balance(1)), this.storage("shop").table("balances", Balance.class).get("a"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void migratesWithTheRecordsAnnotationsAlone()
|
||||
{
|
||||
this.storage("shop").table("balances", Balance.class).setAll(Map.of("a", new Balance(1), "b", new Balance(2)));
|
||||
|
||||
Table<AnnotatedLevel> migrated = this.storage("shop").table("balances", AnnotatedLevel.class);
|
||||
|
||||
assertEquals(Map.of("a", new AnnotatedLevel(10, 1), "b", new AnnotatedLevel(20, 1)), migrated.getAll(List.of("a", "b")));
|
||||
ModTablesTest.assertContainsAll(this.logger.messages.getLast(), "'balances'", "2 row(s)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void builderCallsOverrideTheVersionAndKeepTheAnnotatedMigrations()
|
||||
{
|
||||
this.storage("shop").table("balances", Balance.class).set("a", new Balance(1));
|
||||
|
||||
Table<AnnotatedLevel> migrated = this.storage("shop").define("balances", AnnotatedLevel.class).version(3).open();
|
||||
assertEquals(Optional.of(new AnnotatedLevel(10, 1)), migrated.get("a"));
|
||||
|
||||
StorageException older = assertThrows(StorageException.class, () -> this.storage("shop").table("balances", AnnotatedLevel.class));
|
||||
ModTablesTest.assertContainsAll(older.getMessage(), "'balances'", "3", "2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowsOneMigrationPerVersion()
|
||||
{
|
||||
IllegalArgumentException annotated = assertThrows(IllegalArgumentException.class, () -> this.storage("shop").define("balances", AnnotatedLevel.class)
|
||||
.migrate(1, row -> new AnnotatedLevel(0, 0)));
|
||||
ModTablesTest.assertContainsAll(annotated.getMessage(), AnnotatedLevel.class.getName(), "1");
|
||||
|
||||
IllegalArgumentException twice = assertThrows(IllegalArgumentException.class, () -> this.storage("shop").define("balances", BalanceWithLevel.class)
|
||||
.migrate(1, row -> new BalanceWithLevel(0, 0))
|
||||
.migrate(1, row -> new BalanceWithLevel(1, 1)));
|
||||
ModTablesTest.assertContainsAll(twice.getMessage(), BalanceWithLevel.class.getName(), "1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsInvalidSchemaAnnotationsWithEveryProblem()
|
||||
{
|
||||
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> this.storage("shop").define("invalid", InvalidSchema.class));
|
||||
|
||||
ModTablesTest.assertContainsAll(e.getMessage(), "@Schema", "zero", "notStatic", "twoParameters", "wrongReturn", "second");
|
||||
assertFalse(e.getMessage().contains(".first'"), "the first migration from 4 is valid: " + e.getMessage());
|
||||
assertFalse(Files.exists(this.file), "nothing is stored");
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsCheckedExceptionsOfAnnotatedMigrationsWithTheRow()
|
||||
{
|
||||
this.storage("shop").table("balances", Balance.class).set("a", new Balance(1));
|
||||
|
||||
StorageException e = assertThrows(StorageException.class, () -> this.storage("shop").table("balances", FailingMigration.class));
|
||||
|
||||
ModTablesTest.assertContainsAll(e.getMessage(), "'a'", "java.io.IOException: broken");
|
||||
assertEquals(Optional.of(new Balance(1)), this.storage("shop").table("balances", Balance.class).get("a"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void adoptsTheTablesOfPreviousIdsOnce()
|
||||
{
|
||||
@@ -391,4 +496,23 @@ class ModTablesTest
|
||||
this.database.close();
|
||||
assertThrows(StorageException.class, () -> empty.contains("a"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void keyAnnotationsKeepTheColumnOfARenamedComponent()
|
||||
{
|
||||
this.storage("shop").table("balances", Balance.class).set("a", new Balance(5));
|
||||
|
||||
Table<RenamedBalance> renamed = this.storage("shop").table("balances", RenamedBalance.class);
|
||||
|
||||
assertEquals(Optional.of(new RenamedBalance(5)), renamed.get("a"), "the column is the same, and @Min does not apply");
|
||||
assertTrue(this.logger.messages.isEmpty(), "no column is reported as removed: " + this.logger.messages);
|
||||
|
||||
StorageException repeated = assertThrows(StorageException.class, () -> this.storage("shop").table("repeated", RepeatedColumn.class));
|
||||
ModTablesTest.assertContainsAll(repeated.getMessage(), RepeatedColumn.class.getName(), "'coins'");
|
||||
}
|
||||
|
||||
private static void assertContainsAll(String message, String... parts)
|
||||
{
|
||||
for (String part : parts) assertTrue(message.contains(part), "'" + part + "' missing in: " + message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package testmods;
|
||||
|
||||
import dev.overlord.zomboidforge.api.Mod;
|
||||
import dev.overlord.zomboidforge.api.annotations.RegisterCommand;
|
||||
|
||||
/**
|
||||
* Entry point that tests package into a mod jar. Two command classes carry
|
||||
* {@link RegisterCommand}; {@code onLoad()} registers a third.
|
||||
*/
|
||||
public final class AnnotatedCommandMod extends Mod
|
||||
{
|
||||
/** Stands in for a command class; the tests' validator accepts any class. */
|
||||
@RegisterCommand
|
||||
public static final class Hello {}
|
||||
|
||||
@RegisterCommand
|
||||
public static final class Bye {}
|
||||
|
||||
public static final class Manual {}
|
||||
|
||||
@Override
|
||||
public void onLoad() { this.commands().register(AnnotatedCommandMod.Manual.class); }
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package testmods;
|
||||
|
||||
import dev.overlord.zomboidforge.api.Mod;
|
||||
import dev.overlord.zomboidforge.api.annotations.OnMain;
|
||||
|
||||
/** Entry point that tests package into a mod jar. Its listener method takes no event. */
|
||||
public final class InvalidListenerMod extends Mod
|
||||
{
|
||||
@Override
|
||||
public void onLoad() { Recorder.record("invalid:onLoad"); }
|
||||
|
||||
@OnMain
|
||||
@SuppressWarnings("unused")
|
||||
void onTick(String text) {}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package testmods;
|
||||
|
||||
import dev.overlord.zomboidforge.api.Mod;
|
||||
import dev.overlord.zomboidforge.api.TickEvent;
|
||||
import dev.overlord.zomboidforge.api.annotations.OnMain;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
/**
|
||||
* Entry point that tests package into a mod jar. Listens for ticks with an annotated method and
|
||||
* with a listener from {@code onLoad()}, and tries to register itself again there.
|
||||
*/
|
||||
public final class ListenerMod extends Mod
|
||||
{
|
||||
public final List<String> log = new CopyOnWriteArrayList<>();
|
||||
|
||||
public volatile @Nullable RuntimeException secondRegistration;
|
||||
|
||||
@Override
|
||||
public void onLoad()
|
||||
{
|
||||
this.events().onMain(TickEvent.class, event -> this.log.add("lambda " + event.tick()));
|
||||
|
||||
try { this.events().register(this); }
|
||||
catch (RuntimeException e) { this.secondRegistration = e; }
|
||||
}
|
||||
|
||||
@OnMain
|
||||
void onTick(TickEvent event) { this.log.add("method " + event.tick()); }
|
||||
}
|
||||
@@ -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()); }
|
||||
}
|
||||
@@ -32,8 +32,9 @@ public final class ThreadMod extends Mod
|
||||
public void onServerStarted()
|
||||
{
|
||||
this.modThread().execute(() -> {
|
||||
this.log.add("work on " + Thread.currentThread().getName());
|
||||
// Hand-off before the log entry: tests that see the entry know the task is queued.
|
||||
this.main().execute(() -> this.log.add("result on " + Thread.currentThread().getName()));
|
||||
this.log.add("work on " + Thread.currentThread().getName());
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -45,10 +45,21 @@
|
||||
# JVM_UNCOMMIT_DELAY
|
||||
# Seconds of disuse after which ZGC returns heap memory to the system
|
||||
# (-XX:ZUncommitDelay). Default: 60 (JVM default: 300)
|
||||
# JVM_EXPERIMENTAL_PERFORMANCE
|
||||
# true/false: compact object headers (-XX:+UseCompactObjectHeaders) and
|
||||
# transparent huge pages for the heap (-XX:+UseTransparentHugePages).
|
||||
# Huge pages need the host's
|
||||
# /sys/kernel/mm/transparent_hugepage/shmem_enabled at advise or always;
|
||||
# otherwise the JVM logs a warning and runs without them. Default: false
|
||||
#
|
||||
# Maintenance
|
||||
# SOFT_RESET true: start in Project Zomboid's soft reset mode (-Dsoftreset).
|
||||
# Intended for a single start; unset it afterwards.
|
||||
#
|
||||
# ZomboidForge features (also /forge/forge.toml [features]; a set variable takes precedence)
|
||||
# ZF_EXPERIMENTAL_PERFORMANCE
|
||||
# true/false: performance changes that alter timing or resource use
|
||||
# (more threads, shorter waits). Default: false
|
||||
|
||||
set -o errexit
|
||||
set -o nounset
|
||||
@@ -78,6 +89,7 @@ readonly RCON_PASSWORD="${RCON_PASSWORD:-}"
|
||||
readonly JVM_MIN_HEAP="${JVM_MIN_HEAP:-}"
|
||||
readonly JVM_MAX_HEAP="${JVM_MAX_HEAP:-}"
|
||||
readonly JVM_UNCOMMIT_DELAY="${JVM_UNCOMMIT_DELAY:-60}"
|
||||
readonly JVM_EXPERIMENTAL_PERFORMANCE="${JVM_EXPERIMENTAL_PERFORMANCE:-}"
|
||||
readonly SOFT_RESET="${SOFT_RESET:-}"
|
||||
|
||||
readonly SERVER_INI="${DATA_DIR}/Server/${SERVER_NAME}.ini"
|
||||
@@ -86,6 +98,9 @@ readonly SERVER_DB="${DATA_DIR}/db/${SERVER_NAME}.db"
|
||||
# Target of the /opt/pz/steamapps symlink; Steam stores Workshop downloads there.
|
||||
readonly STEAMAPPS_DIR="${DATA_DIR}/steamapps"
|
||||
readonly CGROUP_MEMORY_MAX="/sys/fs/cgroup/memory.max"
|
||||
# Keys of the ZomboidForge features (core/config/Feature): ZF_<KEY> becomes
|
||||
# -Dzomboidforge.features.<key>.
|
||||
readonly FEATURES=(experimental_performance)
|
||||
readonly UNLIMITED_MAX_HEAP="8g"
|
||||
|
||||
log() {
|
||||
@@ -272,6 +287,30 @@ default_max_heap() {
|
||||
echo "$(( limit * 3 / 4 / 1024 / 1024 ))m"
|
||||
}
|
||||
|
||||
# Appends -Dzomboidforge.features.<key>=true|false for every feature whose ZF_<KEY> is set.
|
||||
# Unset or empty: no property, so forge.toml or the default (off) decides.
|
||||
add_feature_properties() {
|
||||
local key
|
||||
local variable
|
||||
local value
|
||||
|
||||
for key in "${FEATURES[@]}"; do
|
||||
variable="ZF_${key^^}"
|
||||
value="${!variable:-}"
|
||||
|
||||
if [[ -z "${value}" ]]; then
|
||||
continue
|
||||
fi
|
||||
if is_true "${value}"; then
|
||||
jvm_args+=("-Dzomboidforge.features.${key}=true")
|
||||
elif is_false "${value}"; then
|
||||
jvm_args+=("-Dzomboidforge.features.${key}=false")
|
||||
else
|
||||
fail "${variable} must be true or false, got '${value}'."
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
# Same JVM setup as the vanilla ProjectZomboid64.json and start-server.sh.
|
||||
# Java runs directly instead of through the native ProjectZomboid64 launcher.
|
||||
build_jvm_args() {
|
||||
@@ -304,10 +343,18 @@ build_jvm_args() {
|
||||
if [[ -n "${JVM_MIN_HEAP}" ]]; then
|
||||
jvm_args+=("-Xms${JVM_MIN_HEAP}")
|
||||
fi
|
||||
if [[ -n "${JVM_EXPERIMENTAL_PERFORMANCE}" ]]; then
|
||||
if is_true "${JVM_EXPERIMENTAL_PERFORMANCE}"; then
|
||||
jvm_args+=("-XX:+UseCompactObjectHeaders" "-XX:+UseTransparentHugePages")
|
||||
elif ! is_false "${JVM_EXPERIMENTAL_PERFORMANCE}"; then
|
||||
fail "JVM_EXPERIMENTAL_PERFORMANCE must be true or false, got '${JVM_EXPERIMENTAL_PERFORMANCE}'."
|
||||
fi
|
||||
fi
|
||||
if [[ -n "${SOFT_RESET}" ]] && is_true "${SOFT_RESET}"; then
|
||||
log "SOFT_RESET is set: starting in soft reset mode. Unset it for the next start."
|
||||
jvm_args+=("-Dsoftreset")
|
||||
fi
|
||||
add_feature_properties
|
||||
}
|
||||
|
||||
build_server_args() {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Gradle plugin for mod authors (id dev.overlord.zomboidforge.mod): dependencies, mod.toml,
|
||||
// build-time checks, packaging, and a local test server. Runs inside the mod's Gradle JVM, so
|
||||
// it targets Java 17; the checks run in a separate Java 25 process (mod-tools).
|
||||
// Gradle plugin for mod authors (id dev.overlord.zomboidforge, for settings.gradle.kts):
|
||||
// dependencies, mod.toml, build-time checks, packaging, and a local test server. Runs inside the
|
||||
// mod's Gradle JVM, so it targets Java 17; the checks run in a separate Java 25 process
|
||||
// (mod-tools).
|
||||
|
||||
plugins {
|
||||
id("zomboidforge.java-conventions")
|
||||
@@ -15,10 +16,10 @@ tasks.withType<JavaCompile>().configureEach {
|
||||
gradlePlugin {
|
||||
plugins {
|
||||
create("mod") {
|
||||
id = "dev.overlord.zomboidforge.mod"
|
||||
implementationClass = "dev.overlord.zomboidforge.gradle.ZomboidForgeModPlugin"
|
||||
id = "dev.overlord.zomboidforge"
|
||||
implementationClass = "dev.overlord.zomboidforge.gradle.ZomboidForgeSettingsPlugin"
|
||||
displayName = "ZomboidForge mod"
|
||||
description = "Builds, checks, and packages server-side Java mods for ZomboidForge."
|
||||
description = "Builds, checks, and packages server-side Java mods for ZomboidForge from a single settings.gradle.kts."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -38,9 +39,19 @@ dependencies {
|
||||
}
|
||||
|
||||
tasks.test {
|
||||
// The functional tests resolve api and mod-tools from the repository in build/repo.
|
||||
dependsOn(":api:publishAllPublicationsToBuildRepository", ":mod-tools:publishAllPublicationsToBuildRepository")
|
||||
// The functional tests resolve api and mod-tools from the repository in build/repo, the
|
||||
// updater tests the plugin as well.
|
||||
dependsOn(
|
||||
":api:publishAllPublicationsToBuildRepository",
|
||||
":mod-tools:publishAllPublicationsToBuildRepository",
|
||||
"publishAllPublicationsToBuildRepository",
|
||||
)
|
||||
|
||||
val repository = layout.settingsDirectory.dir("build/repo").asFile.absolutePath
|
||||
systemProperty("zomboidforge.testRepository", repository)
|
||||
|
||||
// The updater tests run zomboidforge.jsh with the wrapper of the repository root.
|
||||
val root = layout.settingsDirectory.asFile.absolutePath
|
||||
inputs.file(layout.settingsDirectory.file("zomboidforge.jsh"))
|
||||
systemProperty("zomboidforge.root", root)
|
||||
}
|
||||
+37
-23
@@ -1,7 +1,6 @@
|
||||
package dev.overlord.zomboidforge.gradle;
|
||||
|
||||
import org.gradle.api.GradleException;
|
||||
import org.gradle.api.Plugin;
|
||||
import org.gradle.api.Project;
|
||||
import org.gradle.api.artifacts.Configuration;
|
||||
import org.gradle.api.artifacts.Dependency;
|
||||
@@ -28,7 +27,8 @@ import java.util.List;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* The plugin {@code dev.overlord.zomboidforge.mod}. Applies {@code java} and adds:
|
||||
* The root project of a mod, as {@code dev.overlord.zomboidforge} configures it. Applies
|
||||
* {@code java} and adds:
|
||||
*
|
||||
* <ul>
|
||||
* <li>dependencies: {@code dev.overlord.zomboidforge:api} (compile only), the game jar for
|
||||
@@ -42,14 +42,16 @@ import java.util.Properties;
|
||||
* <li>{@code runServer}: a ZomboidForge server in a container with the mod;
|
||||
* {@code deployMod}: copies the mod into a server's mods directory;</li>
|
||||
* <li>{@code downloadGame}: installs the dedicated server with steamcmd when no game jar is
|
||||
* configured or installed.</li>
|
||||
* configured or installed;</li>
|
||||
* <li>{@code zomboidForgeSetup}: creates {@code .gitignore} and the entry point class when
|
||||
* they are missing.</li>
|
||||
* </ul>
|
||||
*
|
||||
* Java compiles for Java 25 (the game's runtime) unless the build sets another toolchain.
|
||||
*/
|
||||
public final class ZomboidForgeModPlugin implements Plugin<Project>
|
||||
final class ModProject
|
||||
{
|
||||
public static final String GROUP = "zomboidforge";
|
||||
static final String GROUP = "zomboidforge";
|
||||
|
||||
private static final String API = "dev.overlord.zomboidforge:api:";
|
||||
private static final String TOOLS = "dev.overlord.zomboidforge:mod-tools:";
|
||||
@@ -58,27 +60,28 @@ public final class ZomboidForgeModPlugin implements Plugin<Project>
|
||||
private static final String MOD_CONFIG = "config.toml";
|
||||
private static final int JAVA = 25;
|
||||
|
||||
@Override
|
||||
public void apply(Project project)
|
||||
private ModProject() {}
|
||||
|
||||
/** Configures {@code project} with the settings' {@code zomboidForge { }}. */
|
||||
static void configure(Project project, ZomboidForgeExtension extension)
|
||||
{
|
||||
project.getPluginManager().apply(JavaPlugin.class);
|
||||
|
||||
String version = ZomboidForgeModPlugin.version();
|
||||
String version = ModProject.version();
|
||||
ProjectLayout layout = project.getLayout();
|
||||
DependencyHandler handler = project.getDependencies();
|
||||
ZomboidForgeExtension extension = project.getExtensions().create("zomboidForge", ZomboidForgeExtension.class);
|
||||
|
||||
extension.getName().convention(extension.getId());
|
||||
extension.getVersion().convention(project.provider(() -> project.getVersion().toString()));
|
||||
extension.getApi().convention(version);
|
||||
extension.getSteamBranch().convention("public");
|
||||
extension.getServerImage().convention(ZomboidForgeModPlugin.DEFAULT_IMAGE);
|
||||
extension.getServerImage().convention(ModProject.DEFAULT_IMAGE);
|
||||
extension.getServerAddress().convention("127.0.0.1");
|
||||
extension.getDataVolume().convention(extension.getId().map(id -> "zomboidforge-" + id));
|
||||
extension.getGameJar().convention(layout.file(project.getProviders().gradleProperty("zomboidforge.gameJar").map(File::new)));
|
||||
|
||||
JavaPluginExtension java = project.getExtensions().getByType(JavaPluginExtension.class);
|
||||
java.getToolchain().getLanguageVersion().convention(JavaLanguageVersion.of(ZomboidForgeModPlugin.JAVA));
|
||||
java.getToolchain().getLanguageVersion().convention(JavaLanguageVersion.of(ModProject.JAVA));
|
||||
|
||||
// Game jar: configured, else installed, else downloaded.
|
||||
Provider<String> branch = extension.getSteamBranch();
|
||||
@@ -89,7 +92,7 @@ public final class ZomboidForgeModPlugin implements Plugin<Project>
|
||||
|
||||
TaskProvider<DownloadGame> downloadGame = project.getTasks().register("downloadGame", DownloadGame.class, task ->
|
||||
{
|
||||
task.setGroup(ZomboidForgeModPlugin.GROUP);
|
||||
task.setGroup(ModProject.GROUP);
|
||||
task.setDescription("Installs the Project Zomboid dedicated server with steamcmd for its projectzomboid.jar, when no game jar is configured or installed.");
|
||||
task.getInstallDirectory().set(layout.dir(branch.map(name -> new File(cache, name))));
|
||||
task.getBranch().set(branch);
|
||||
@@ -123,7 +126,7 @@ public final class ZomboidForgeModPlugin implements Plugin<Project>
|
||||
{
|
||||
configuration.setDescription("The ZomboidForge mod tools that checkMod runs.");
|
||||
configuration.setCanBeConsumed(false);
|
||||
configuration.getDependencies().add(handler.create(ZomboidForgeModPlugin.TOOLS + version));
|
||||
configuration.getDependencies().add(handler.create(ModProject.TOOLS + version));
|
||||
});
|
||||
|
||||
for (String name : List.of(JavaPlugin.COMPILE_ONLY_CONFIGURATION_NAME, JavaPlugin.TEST_IMPLEMENTATION_CONFIGURATION_NAME))
|
||||
@@ -131,7 +134,7 @@ public final class ZomboidForgeModPlugin implements Plugin<Project>
|
||||
Configuration configuration = project.getConfigurations().getByName(name);
|
||||
|
||||
configuration.extendsFrom(forgeMods);
|
||||
configuration.getDependencies().add(handler.create(ZomboidForgeModPlugin.API + version));
|
||||
configuration.getDependencies().add(handler.create(ModProject.API + version));
|
||||
}
|
||||
|
||||
for (String name : List.of(JavaPlugin.COMPILE_ONLY_CONFIGURATION_NAME, JavaPlugin.TEST_COMPILE_ONLY_CONFIGURATION_NAME))
|
||||
@@ -148,7 +151,7 @@ public final class ZomboidForgeModPlugin implements Plugin<Project>
|
||||
|
||||
TaskProvider<GenerateModDescriptor> generate = project.getTasks().register("generateModDescriptor", GenerateModDescriptor.class, task ->
|
||||
{
|
||||
task.setGroup(ZomboidForgeModPlugin.GROUP);
|
||||
task.setGroup(ModProject.GROUP);
|
||||
task.setDescription("Writes META-INF/zomboidforge/mod.toml from zomboidForge { }.");
|
||||
task.getModId().set(extension.getId());
|
||||
task.getModName().set(extension.getName());
|
||||
@@ -176,9 +179,9 @@ public final class ZomboidForgeModPlugin implements Plugin<Project>
|
||||
{
|
||||
task.setGroup(LifecycleBasePlugin.VERIFICATION_GROUP);
|
||||
task.setDescription("Checks the mod the way the server does when it loads it, against the game jar.");
|
||||
task.getMainClass().set(ZomboidForgeModPlugin.TOOLS_MAIN);
|
||||
task.getMainClass().set(ModProject.TOOLS_MAIN);
|
||||
task.setClasspath(tools);
|
||||
task.getJavaLauncher().set(toolchains.launcherFor(spec -> spec.getLanguageVersion().set(JavaLanguageVersion.of(ZomboidForgeModPlugin.JAVA))));
|
||||
task.getJavaLauncher().set(toolchains.launcherFor(spec -> spec.getLanguageVersion().set(JavaLanguageVersion.of(ModProject.JAVA))));
|
||||
task.dependsOn(downloadGame);
|
||||
|
||||
CheckModArguments arguments = project.getObjects().newInstance(CheckModArguments.class);
|
||||
@@ -201,7 +204,7 @@ public final class ZomboidForgeModPlugin implements Plugin<Project>
|
||||
|
||||
TaskProvider<Sync> modFolder = project.getTasks().register("modFolder", Sync.class, task ->
|
||||
{
|
||||
task.setGroup(ZomboidForgeModPlugin.GROUP);
|
||||
task.setGroup(ModProject.GROUP);
|
||||
task.setDescription("Assembles build/mod/<id>/ with <id>.jar and lib/, as a server expects it in <forge>/mods.");
|
||||
task.dependsOn(checkMod);
|
||||
task.into(layout.getBuildDirectory().dir(id.map(name -> "mod/" + name)));
|
||||
@@ -211,7 +214,7 @@ public final class ZomboidForgeModPlugin implements Plugin<Project>
|
||||
|
||||
TaskProvider<Zip> modZip = project.getTasks().register("modZip", Zip.class, task ->
|
||||
{
|
||||
task.setGroup(ZomboidForgeModPlugin.GROUP);
|
||||
task.setGroup(ModProject.GROUP);
|
||||
task.setDescription("Packs the mod folder as build/distributions/<id>-<version>.zip, ready to unpack into <forge>/mods.");
|
||||
task.from(modFolder, spec -> spec.into(id));
|
||||
task.getArchiveFileName().set(id.zip(extension.getVersion(), (name, modVersion) -> name + "-" + modVersion + ".zip"));
|
||||
@@ -225,7 +228,7 @@ public final class ZomboidForgeModPlugin implements Plugin<Project>
|
||||
|
||||
project.getTasks().register("runServer", RunServer.class, task ->
|
||||
{
|
||||
task.setGroup(ZomboidForgeModPlugin.GROUP);
|
||||
task.setGroup(ModProject.GROUP);
|
||||
task.setDescription("Runs a ZomboidForge server in a container with this mod; stop the build to stop the server.");
|
||||
task.dependsOn(modFolder);
|
||||
task.getModsDirectory().set(layout.getBuildDirectory().dir("mod"));
|
||||
@@ -240,19 +243,30 @@ public final class ZomboidForgeModPlugin implements Plugin<Project>
|
||||
|
||||
project.getTasks().register("deployMod", Sync.class, task ->
|
||||
{
|
||||
task.setGroup(ZomboidForgeModPlugin.GROUP);
|
||||
task.setGroup(ModProject.GROUP);
|
||||
task.setDescription("Copies the mod folder into zomboidForge.deployDirectory (a server's mods directory); keeps the server's config.toml of the mod.");
|
||||
task.from(modFolder);
|
||||
task.preserve(filter -> filter.include(ZomboidForgeModPlugin.MOD_CONFIG));
|
||||
task.preserve(filter -> filter.include(ModProject.MOD_CONFIG));
|
||||
task.into(extension.getDeployDirectory().dir(id).orElse(layout.getBuildDirectory().dir("deploy-not-configured")));
|
||||
task.onlyIf("zomboidForge.deployDirectory is set", element -> extension.getDeployDirectory().isPresent());
|
||||
});
|
||||
|
||||
// Project setup.
|
||||
TaskProvider<SetupMod> setup = project.getTasks().register("zomboidForgeSetup", SetupMod.class, task ->
|
||||
{
|
||||
task.setGroup(ModProject.GROUP);
|
||||
task.setDescription("Creates .gitignore and the entry point class when they are missing.");
|
||||
task.getProjectDirectory().set(layout.getProjectDirectory());
|
||||
task.getEntrypoint().set(extension.getEntrypoint());
|
||||
});
|
||||
|
||||
project.getTasks().named(JavaPlugin.COMPILE_JAVA_TASK_NAME, task -> task.mustRunAfter(setup));
|
||||
}
|
||||
|
||||
/** The plugin's version, which is also the version of the API and mod tools it uses. */
|
||||
static String version()
|
||||
{
|
||||
try (InputStream in = ZomboidForgeModPlugin.class.getResourceAsStream("plugin.properties"))
|
||||
try (InputStream in = ModProject.class.getResourceAsStream("plugin.properties"))
|
||||
{
|
||||
if (in == null) throw new GradleException("The ZomboidForge plugin has no plugin.properties.");
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package dev.overlord.zomboidforge.gradle;
|
||||
|
||||
import org.gradle.api.DefaultTask;
|
||||
import org.gradle.api.file.DirectoryProperty;
|
||||
import org.gradle.api.provider.Property;
|
||||
import org.gradle.api.tasks.Input;
|
||||
import org.gradle.api.tasks.Internal;
|
||||
import org.gradle.api.tasks.TaskAction;
|
||||
import org.gradle.api.tasks.UntrackedTask;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
* Creates the files a new mod project needs and does not have yet: {@code .gitignore} and the
|
||||
* entry point class with an empty {@code onLoad()}. Existing files stay as they are.
|
||||
*/
|
||||
@UntrackedTask(because = "Creates missing files once and never changes existing ones")
|
||||
public abstract class SetupMod extends DefaultTask
|
||||
{
|
||||
private static final String GITIGNORE = """
|
||||
.gradle/
|
||||
build/
|
||||
""";
|
||||
|
||||
private static final String ENTRY_POINT = """
|
||||
%simport dev.overlord.zomboidforge.api.Mod;
|
||||
|
||||
public final class %s extends Mod
|
||||
{
|
||||
@Override
|
||||
public void onLoad() {}
|
||||
}
|
||||
""";
|
||||
|
||||
@Internal
|
||||
public abstract DirectoryProperty getProjectDirectory();
|
||||
|
||||
@Input
|
||||
public abstract Property<String> getEntrypoint();
|
||||
|
||||
@TaskAction
|
||||
public void setup() throws IOException
|
||||
{
|
||||
Path directory = this.getProjectDirectory().get().getAsFile().toPath();
|
||||
String entrypoint = this.getEntrypoint().get();
|
||||
int dot = entrypoint.lastIndexOf('.');
|
||||
String packageLine = dot < 0 ? "" : "package " + entrypoint.substring(0, dot) + ";\n\n";
|
||||
String className = entrypoint.substring(dot + 1);
|
||||
|
||||
this.create(directory, ".gitignore", SetupMod.GITIGNORE);
|
||||
this.create(directory, "src/main/java/" + entrypoint.replace('.', '/') + ".java", SetupMod.ENTRY_POINT.formatted(packageLine, className));
|
||||
}
|
||||
|
||||
private void create(Path directory, String path, String content) throws IOException
|
||||
{
|
||||
Path file = directory.resolve(path);
|
||||
|
||||
if (Files.exists(file)) return;
|
||||
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.writeString(file, content);
|
||||
this.getLogger().lifecycle("Created '{}'.", path);
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package dev.overlord.zomboidforge.gradle;
|
||||
|
||||
import org.gradle.api.Plugin;
|
||||
import org.gradle.api.initialization.Settings;
|
||||
import org.gradle.api.provider.Provider;
|
||||
|
||||
/**
|
||||
* The plugin {@code dev.overlord.zomboidforge} for {@code settings.gradle.kts}, which makes a
|
||||
* mod project a single file:
|
||||
*
|
||||
* <pre>{@code
|
||||
* plugins {
|
||||
* id("dev.overlord.zomboidforge") version "0.6.0"
|
||||
* }
|
||||
*
|
||||
* zomboidForge {
|
||||
* id = "shop"
|
||||
* version = "1.0.0"
|
||||
* entrypoint = "com.example.shop.ShopMod"
|
||||
* }
|
||||
* }</pre>
|
||||
*
|
||||
* Adds {@code zomboidForge { }} to the settings and names the root project after the mod id.
|
||||
* The root project gets the ZomboidForge Maven registry and Maven Central as repositories, the
|
||||
* same {@code zomboidForge { }}, and the tasks of {@link ModProject}. The Gradle property
|
||||
* {@code zomboidforge.repository} replaces the registry's URL.
|
||||
*/
|
||||
public final class ZomboidForgeSettingsPlugin implements Plugin<Settings>
|
||||
{
|
||||
static final String EXTENSION = "zomboidForge";
|
||||
static final String REPOSITORY = "https://git.security-command.org/api/packages/overlord/maven";
|
||||
|
||||
@Override
|
||||
public void apply(Settings settings)
|
||||
{
|
||||
ZomboidForgeExtension extension = settings.getExtensions().create(ZomboidForgeSettingsPlugin.EXTENSION, ZomboidForgeExtension.class);
|
||||
Provider<String> repository = settings.getProviders().gradleProperty("zomboidforge.repository").orElse(ZomboidForgeSettingsPlugin.REPOSITORY);
|
||||
|
||||
settings.getGradle().settingsEvaluated(evaluated ->
|
||||
{
|
||||
if (extension.getId().isPresent()) evaluated.getRootProject().setName(extension.getId().get());
|
||||
});
|
||||
|
||||
settings.getGradle().rootProject(project ->
|
||||
{
|
||||
project.getRepositories().maven(maven -> maven.setUrl(repository.get()));
|
||||
project.getRepositories().mavenCentral();
|
||||
project.getExtensions().add(ZomboidForgeExtension.class, ZomboidForgeSettingsPlugin.EXTENSION, extension);
|
||||
ModProject.configure(project, extension);
|
||||
});
|
||||
}
|
||||
}
|
||||
+13
-18
@@ -38,7 +38,7 @@ import static org.objectweb.asm.Opcodes.RETURN;
|
||||
import static org.objectweb.asm.Opcodes.V25;
|
||||
|
||||
/** Builds mod projects with the plugin, against api and mod-tools published to build/repo. */
|
||||
class ZomboidForgeModPluginTest
|
||||
class ModProjectTest
|
||||
{
|
||||
private static final String REPOSITORY = System.getProperty("zomboidforge.testRepository");
|
||||
|
||||
@@ -56,25 +56,19 @@ class ZomboidForgeModPluginTest
|
||||
private void modProject(String extra, String body) throws IOException
|
||||
{
|
||||
this.write("settings.gradle.kts", """
|
||||
rootProject.name = "shop"
|
||||
|
||||
dependencyResolutionManagement {
|
||||
repositories {
|
||||
maven { url = uri("%s") }
|
||||
}
|
||||
}
|
||||
""".formatted(Path.of(ZomboidForgeModPluginTest.REPOSITORY).toUri()));
|
||||
|
||||
this.write("build.gradle.kts", """
|
||||
plugins {
|
||||
id("dev.overlord.zomboidforge.mod")
|
||||
id("dev.overlord.zomboidforge")
|
||||
}
|
||||
|
||||
version = "1.2.0"
|
||||
|
||||
zomboidForge {
|
||||
id = "shop"
|
||||
version = "1.2.0"
|
||||
entrypoint = "com.example.shop.ShopMod"
|
||||
}
|
||||
""");
|
||||
|
||||
this.write("build.gradle.kts", """
|
||||
zomboidForge {
|
||||
%s
|
||||
}
|
||||
|
||||
@@ -96,12 +90,13 @@ class ZomboidForgeModPluginTest
|
||||
""".formatted(body));
|
||||
|
||||
Files.createDirectories(this.project.resolve("libs"));
|
||||
ZomboidForgeModPluginTest.jar(this.project.resolve("libs/util.jar"), Map.of("util/Util.class", ZomboidForgeModPluginTest.emptyClass("util/Util")));
|
||||
ModProjectTest.jar(this.project.resolve("libs/util.jar"), Map.of("util/Util.class", ModProjectTest.emptyClass("util/Util")));
|
||||
}
|
||||
|
||||
private GradleRunner runner(String... arguments)
|
||||
{
|
||||
List<String> all = new ArrayList<>(List.of(arguments));
|
||||
all.add("-Pzomboidforge.repository=" + Path.of(ModProjectTest.REPOSITORY).toUri());
|
||||
all.add("--stacktrace");
|
||||
|
||||
return GradleRunner.create().withProjectDir(this.project.toFile()).withPluginClasspath().withArguments(all).forwardOutput();
|
||||
@@ -227,11 +222,11 @@ class ZomboidForgeModPluginTest
|
||||
void failsWhenTheEntryPointIsMissing() throws IOException
|
||||
{
|
||||
this.modProject("", "");
|
||||
this.write("build.gradle.kts", Files.readString(this.project.resolve("build.gradle.kts")).replace("com.example.shop.ShopMod", "com.example.shop.Missing"));
|
||||
this.write("settings.gradle.kts", Files.readString(this.project.resolve("settings.gradle.kts")).replace("com.example.shop.ShopMod", "com.example.shop.Missing"));
|
||||
|
||||
BuildResult result = this.runner("build").buildAndFail();
|
||||
|
||||
assertTrue(result.getOutput().contains("The entry point 'com.example.shop.Missing' is not in 'shop-1.2.0.jar'."), result.getOutput());
|
||||
assertTrue(result.getOutput().contains("'com.example.shop.Missing'"), result.getOutput());
|
||||
}
|
||||
|
||||
/** {@code game/projectzomboid.jar} with a {@code zombie/core/Core} that reports {@code major.minor} and has {@code versionText()}. */
|
||||
@@ -262,7 +257,7 @@ class ZomboidForgeModPluginTest
|
||||
|
||||
Path jar = this.project.resolve("game/projectzomboid.jar");
|
||||
Files.createDirectories(jar.getParent());
|
||||
ZomboidForgeModPluginTest.jar(jar, Map.of("zombie/core/Core.class", writer.toByteArray()));
|
||||
ModProjectTest.jar(jar, Map.of("zombie/core/Core.class", writer.toByteArray()));
|
||||
}
|
||||
|
||||
private static byte[] emptyClass(String name)
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
package dev.overlord.zomboidforge.gradle;
|
||||
|
||||
import org.gradle.testkit.runner.BuildResult;
|
||||
import org.gradle.testkit.runner.GradleRunner;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.jar.JarFile;
|
||||
import java.util.jar.JarOutputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** Builds mod projects that consist of a settings.gradle.kts with dev.overlord.zomboidforge. */
|
||||
class ZomboidForgeSettingsPluginTest
|
||||
{
|
||||
private static final String REPOSITORY = System.getProperty("zomboidforge.testRepository");
|
||||
|
||||
private static final String SETTINGS = """
|
||||
plugins {
|
||||
id("dev.overlord.zomboidforge")
|
||||
}
|
||||
|
||||
zomboidForge {
|
||||
id = "shop"
|
||||
version = "1.0.0"
|
||||
entrypoint = "com.example.shop.ShopMod"
|
||||
}
|
||||
""";
|
||||
|
||||
@TempDir
|
||||
Path project;
|
||||
|
||||
private void write(String path, String content) throws IOException
|
||||
{
|
||||
Path file = this.project.resolve(path);
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.writeString(file, content);
|
||||
}
|
||||
|
||||
private GradleRunner runner(String... arguments)
|
||||
{
|
||||
List<String> all = new ArrayList<>(List.of(arguments));
|
||||
all.add("-Pzomboidforge.repository=" + Path.of(ZomboidForgeSettingsPluginTest.REPOSITORY).toUri());
|
||||
all.add("--stacktrace");
|
||||
|
||||
return GradleRunner.create().withProjectDir(this.project.toFile()).withPluginClasspath().withArguments(all).forwardOutput();
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildsAProjectOfOneFile() throws IOException
|
||||
{
|
||||
this.write("settings.gradle.kts", ZomboidForgeSettingsPluginTest.SETTINGS);
|
||||
|
||||
BuildResult result = this.runner("zomboidForgeSetup", "build", "--configuration-cache").build();
|
||||
|
||||
assertTrue(result.getOutput().contains("Created '.gitignore'."), result.getOutput());
|
||||
assertTrue(result.getOutput().contains("Mod 'shop' 1.0.0 passed the checks"), result.getOutput());
|
||||
assertTrue(Files.readString(this.project.resolve(".gitignore")).contains("build/"));
|
||||
assertTrue(Files.readString(this.project.resolve("src/main/java/com/example/shop/ShopMod.java")).contains("public final class ShopMod extends Mod"));
|
||||
assertTrue(Files.isRegularFile(this.project.resolve("build/distributions/shop-1.0.0.zip")), "the root project is named after the mod id");
|
||||
|
||||
BuildResult again = this.runner("zomboidForgeSetup", "build", "--configuration-cache").build();
|
||||
assertTrue(again.getOutput().contains("Configuration cache entry reused."), again.getOutput());
|
||||
assertFalse(again.getOutput().contains("Created '"), "existing files stay");
|
||||
}
|
||||
|
||||
@Test
|
||||
void setupKeepsExistingFiles() throws IOException
|
||||
{
|
||||
this.write("settings.gradle.kts", ZomboidForgeSettingsPluginTest.SETTINGS);
|
||||
this.write(".gitignore", "out/\n");
|
||||
this.write("src/main/java/com/example/shop/ShopMod.java", "// own\n");
|
||||
|
||||
BuildResult result = this.runner("zomboidForgeSetup").build();
|
||||
|
||||
assertFalse(result.getOutput().contains("Created '"), result.getOutput());
|
||||
assertEquals("out/\n", Files.readString(this.project.resolve(".gitignore")));
|
||||
assertEquals("// own\n", Files.readString(this.project.resolve("src/main/java/com/example/shop/ShopMod.java")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setupCreatesAnEntryPointWithoutPackage() throws IOException
|
||||
{
|
||||
this.write("settings.gradle.kts", ZomboidForgeSettingsPluginTest.SETTINGS.replace("com.example.shop.ShopMod", "ShopMod"));
|
||||
|
||||
this.runner("zomboidForgeSetup", "compileJava").build();
|
||||
|
||||
String source = Files.readString(this.project.resolve("src/main/java/ShopMod.java"));
|
||||
assertTrue(source.startsWith("import dev.overlord.zomboidforge.api.Mod;"), source);
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildScriptSharesTheSettings() throws IOException
|
||||
{
|
||||
this.write("settings.gradle.kts", ZomboidForgeSettingsPluginTest.SETTINGS);
|
||||
this.write("build.gradle.kts", """
|
||||
zomboidForge {
|
||||
name = "Shop"
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(files("libs/util.jar"))
|
||||
}
|
||||
""");
|
||||
Files.createDirectories(this.project.resolve("libs"));
|
||||
try (OutputStream file = Files.newOutputStream(this.project.resolve("libs/util.jar"))) { new JarOutputStream(file).close(); }
|
||||
|
||||
this.runner("zomboidForgeSetup", "modFolder", "-x", "checkMod").build();
|
||||
|
||||
assertTrue(Files.isRegularFile(this.project.resolve("build/mod/shop/lib/util.jar")));
|
||||
|
||||
try (JarFile jar = new JarFile(this.project.resolve("build/mod/shop/shop.jar").toFile()))
|
||||
{
|
||||
String toml = new String(jar.getInputStream(jar.getEntry("META-INF/zomboidforge/mod.toml")).readAllBytes(), StandardCharsets.UTF_8);
|
||||
|
||||
assertTrue(toml.contains("\"shop\""), toml);
|
||||
assertTrue(toml.contains("\"Shop\""), toml);
|
||||
}
|
||||
}
|
||||
}
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
package dev.overlord.zomboidforge.gradle;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** Runs zomboidforge.jsh with JShell against build/repo and the wrapper of the repository root. */
|
||||
class ZomboidForgeUpdaterTest
|
||||
{
|
||||
private static final Path ROOT = Path.of(System.getProperty("zomboidforge.root"));
|
||||
private static final Path REPOSITORY = Path.of(System.getProperty("zomboidforge.testRepository"));
|
||||
private static final String VERSION = ModProject.version();
|
||||
|
||||
@TempDir
|
||||
Path directory;
|
||||
|
||||
private record Run(int exit, String output) {}
|
||||
|
||||
/** A project of one settings.gradle.kts in {@code project/}, declaring {@code version}. */
|
||||
private Path project(String version) throws IOException
|
||||
{
|
||||
Path project = this.directory.resolve("project");
|
||||
Files.createDirectories(project);
|
||||
|
||||
Files.writeString(project.resolve("settings.gradle.kts"), """
|
||||
pluginManagement {
|
||||
repositories { maven("%s") }
|
||||
}
|
||||
|
||||
plugins {
|
||||
id("dev.overlord.zomboidforge") version "%s"
|
||||
}
|
||||
|
||||
zomboidForge {
|
||||
id = "shop"
|
||||
version = "1.0.0"
|
||||
entrypoint = "com.example.shop.ShopMod"
|
||||
}
|
||||
""".formatted(ZomboidForgeUpdaterTest.REPOSITORY.toUri(), version));
|
||||
Files.writeString(project.resolve("gradle.properties"), "zomboidforge.repository=" + ZomboidForgeUpdaterTest.REPOSITORY.toUri() + "\n");
|
||||
|
||||
return project;
|
||||
}
|
||||
|
||||
/** {@code files/v<version>/} with the wrapper of the repository root, as a release tag has it. */
|
||||
private Path files(String version) throws IOException
|
||||
{
|
||||
Path files = this.directory.resolve("files");
|
||||
|
||||
for (String path : List.of("gradlew", "gradlew.bat", "gradle/wrapper/gradle-wrapper.jar", "gradle/wrapper/gradle-wrapper.properties"))
|
||||
{
|
||||
Path target = files.resolve("v" + version).resolve(path);
|
||||
Files.createDirectories(target.getParent());
|
||||
Files.copy(ZomboidForgeUpdaterTest.ROOT.resolve(path), target);
|
||||
}
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
private Run run(Path project, Path repository, Path files, String... properties) throws Exception
|
||||
{
|
||||
Path jshell = Path.of(System.getProperty("java.home"), "bin", "jshell");
|
||||
List<String> command = new ArrayList<>(List.of(jshell.toString()));
|
||||
|
||||
command.add("-R-Dzomboidforge.repository=" + repository.toUri());
|
||||
command.add("-R-Dzomboidforge.files=" + files.toUri());
|
||||
for (String property : properties) command.add("-R-D" + property);
|
||||
command.add("-");
|
||||
|
||||
Process process = new ProcessBuilder(command)
|
||||
.directory(project.toFile())
|
||||
.redirectErrorStream(true)
|
||||
.redirectInput(ZomboidForgeUpdaterTest.ROOT.resolve("zomboidforge.jsh").toFile())
|
||||
.start();
|
||||
|
||||
String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
|
||||
assertTrue(process.waitFor(5, TimeUnit.MINUTES), output);
|
||||
System.out.println(output);
|
||||
|
||||
return new Run(process.exitValue(), output);
|
||||
}
|
||||
|
||||
@Test
|
||||
void setsUpAndBuildsAProject() throws Exception
|
||||
{
|
||||
Path project = this.project("0.0.1");
|
||||
Run run = this.run(project, ZomboidForgeUpdaterTest.REPOSITORY, this.files(ZomboidForgeUpdaterTest.VERSION), "zomboidforge.version=" + ZomboidForgeUpdaterTest.VERSION);
|
||||
|
||||
assertEquals(0, run.exit(), run.output());
|
||||
assertTrue(run.output().contains("(was 0.0.1)"), run.output());
|
||||
assertTrue(run.output().contains("Created 'src/main/java/com/example/shop/ShopMod.java'."), run.output());
|
||||
assertTrue(Files.readString(project.resolve("settings.gradle.kts")).contains("version \"" + ZomboidForgeUpdaterTest.VERSION + "\""));
|
||||
assertTrue(Files.isExecutable(project.resolve("gradlew")));
|
||||
assertTrue(Files.isRegularFile(project.resolve("gradle/wrapper/gradle-wrapper.jar")));
|
||||
assertTrue(Files.isRegularFile(project.resolve("build/distributions/shop-1.0.0.zip")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void takesTheNewestVersionAndChangesNothingWhenADownloadFails() throws Exception
|
||||
{
|
||||
Path repository = this.directory.resolve("repository");
|
||||
Path metadata = repository.resolve("dev/overlord/zomboidforge/dev.overlord.zomboidforge.gradle.plugin/maven-metadata.xml");
|
||||
Files.createDirectories(metadata.getParent());
|
||||
Files.writeString(metadata, "<metadata><versioning><release>9.9.0</release><versions><version>0.1.0</version><version>9.9.0</version></versions></versioning></metadata>");
|
||||
|
||||
Path project = this.project("0.1.0");
|
||||
String settings = Files.readString(project.resolve("settings.gradle.kts"));
|
||||
Run run = this.run(project, repository, this.directory.resolve("files"));
|
||||
|
||||
assertEquals(1, run.exit(), run.output());
|
||||
assertTrue(run.output().contains("v9.9.0/gradlew"), run.output());
|
||||
assertEquals(settings, Files.readString(project.resolve("settings.gradle.kts")));
|
||||
assertTrue(Files.notExists(project.resolve("gradlew")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsForAVersionThatIsNotPublished() throws Exception
|
||||
{
|
||||
Path project = this.project("0.0.1");
|
||||
Run run = this.run(project, ZomboidForgeUpdaterTest.REPOSITORY, this.directory.resolve("files"), "zomboidforge.version=9.9.9");
|
||||
|
||||
assertEquals(1, run.exit(), run.output());
|
||||
assertTrue(run.output().contains("'9.9.9'"), run.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsWithoutThePluginInTheSettings() throws Exception
|
||||
{
|
||||
Path project = this.project("0.0.1");
|
||||
Files.writeString(project.resolve("settings.gradle.kts"), "rootProject.name = \"shop\"\n");
|
||||
|
||||
Run run = this.run(project, ZomboidForgeUpdaterTest.REPOSITORY, this.directory.resolve("files"));
|
||||
|
||||
assertEquals(1, run.exit(), run.output());
|
||||
assertTrue(run.output().contains("dev.overlord.zomboidforge"), run.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsWithoutSettings() throws Exception
|
||||
{
|
||||
Path project = this.directory.resolve("empty");
|
||||
Files.createDirectories(project);
|
||||
|
||||
Run run = this.run(project, ZomboidForgeUpdaterTest.REPOSITORY, this.directory.resolve("files"));
|
||||
|
||||
assertEquals(1, run.exit(), run.output());
|
||||
assertTrue(run.output().contains("settings.gradle.kts"), run.output());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package dev.overlord.zomboidforge.tools;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.core.config.RecordBinder;
|
||||
import dev.overlord.zomboidforge.core.config.TomlTree;
|
||||
import dev.overlord.zomboidforge.core.mods.GameClasses;
|
||||
import dev.overlord.zomboidforge.core.mods.ModDescriptor;
|
||||
@@ -8,16 +9,24 @@ import dev.overlord.zomboidforge.core.mods.ModDiscovery;
|
||||
import dev.overlord.zomboidforge.core.mods.ModLoadException;
|
||||
import dev.overlord.zomboidforge.core.mods.ModVerifier;
|
||||
import dev.overlord.zomboidforge.core.mods.ModVersion;
|
||||
import dev.overlord.zomboidforge.core.runtime.ListenerScanner;
|
||||
import dev.overlord.zomboidforge.core.storage.RecordSchema;
|
||||
import dev.overlord.zomboidforge.patcher.GameVersionReader;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.objectweb.asm.ClassReader;
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.tree.AnnotationNode;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
import org.objectweb.asm.tree.RecordComponentNode;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.net.URLClassLoader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
@@ -26,6 +35,8 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarFile;
|
||||
import java.util.zip.ZipEntry;
|
||||
|
||||
@@ -41,9 +52,18 @@ import java.util.zip.ZipEntry;
|
||||
* minimum version it satisfies;</li>
|
||||
* <li>the game jar is one of the declared {@code game} versions;</li>
|
||||
* <li>{@link ModVerifier}: game use requires {@code game} versions, every used game class
|
||||
* and member exists in the game jar, no ZomboidForge internals.</li>
|
||||
* and member exists in the game jar, no ZomboidForge internals;</li>
|
||||
* <li>the annotations the server reads while it loads the mod, through the server's own
|
||||
* rules: listener and scheduled methods of the entry point ({@link ListenerScanner}),
|
||||
* {@code @Schema}/{@code @Migrate} ({@link RecordSchema}) and {@code @Key}/{@code @Min}/
|
||||
* {@code @Max} ({@link RecordBinder}) on the jar's records that carry them, and the
|
||||
* {@code @RegisterCommand} classes.</li>
|
||||
* </ol>
|
||||
*
|
||||
* For the last check, the mod's classes are loaded without being initialized, so no mod code
|
||||
* runs. Objects that a mod passes to {@code Events.register} at runtime are only checked on the
|
||||
* server.
|
||||
*
|
||||
* <pre>
|
||||
* java -jar mod-tools.jar --jar <mod.jar> [--game-jar <projectzomboid.jar>]
|
||||
* [--library <jar>]... [--dependency <mod jar>]... [--report <file>]
|
||||
@@ -58,6 +78,14 @@ import java.util.zip.ZipEntry;
|
||||
public final class ModCheck
|
||||
{
|
||||
private static final String MOD_CLASS = "dev/overlord/zomboidforge/api/Mod";
|
||||
private static final String RECORD = "java/lang/Record";
|
||||
private static final String ANNOTATION = "Ldev/overlord/zomboidforge/api/annotations/";
|
||||
|
||||
/** Annotations that make a record worth loading for {@link #checkAnnotations}. */
|
||||
private static final Set<String> RECORD_ANNOTATIONS = Set.of(
|
||||
ModCheck.ANNOTATION + "Schema;", ModCheck.ANNOTATION + "Migrate;",
|
||||
ModCheck.ANNOTATION + "Key;", ModCheck.ANNOTATION + "Min;", ModCheck.ANNOTATION + "Max;"
|
||||
);
|
||||
|
||||
/** The command-line arguments. */
|
||||
public record Arguments(Path jar, @Nullable Path gameJar, List<Path> libraries, List<Path> dependencies, @Nullable Path report)
|
||||
@@ -201,7 +229,9 @@ public final class ModCheck
|
||||
{
|
||||
if (!descriptor.game().isEmpty()) problems.add("The mod declares " + descriptor.game() + ", so the check needs '--game-jar'.");
|
||||
|
||||
ModCheck.verify(candidates, GameClasses.none(), null, problems);
|
||||
Map<String, List<String>> commands = ModCheck.verify(candidates, GameClasses.none(), null, problems);
|
||||
ModCheck.checkAnnotations(arguments, descriptor, commands.getOrDefault(descriptor.id(), List.of()), problems);
|
||||
|
||||
return new Result(descriptor, null, problems);
|
||||
}
|
||||
|
||||
@@ -211,22 +241,147 @@ public final class ModCheck
|
||||
if (!descriptor.game().isEmpty() && descriptor.game().stream().noneMatch(gameVersion::matches))
|
||||
problems.add("The game jar '" + gameJar + "' is Project Zomboid " + gameVersion + ", but the mod declares " + descriptor.game() + "; the check needs a game jar of a declared version.");
|
||||
|
||||
Map<String, List<String>> commands = Map.of();
|
||||
|
||||
try (GameClasses game = GameClasses.open(gameJar))
|
||||
{
|
||||
ModCheck.verify(candidates, game, gameVersion, problems);
|
||||
commands = ModCheck.verify(candidates, game, gameVersion, problems);
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
problems.add("Cannot read the game jar '" + gameJar + "': " + e.getMessage());
|
||||
}
|
||||
|
||||
ModCheck.checkAnnotations(arguments, descriptor, commands.getOrDefault(descriptor.id(), List.of()), problems);
|
||||
|
||||
return new Result(descriptor, gameVersion, problems);
|
||||
}
|
||||
|
||||
private static void verify(List<ModDiscovery.Candidate> candidates, GameClasses game, @Nullable GameVersion version, List<String> problems)
|
||||
/** @return mod id to its {@code @RegisterCommand} classes; empty when the verifier found problems */
|
||||
private static Map<String, List<String>> verify(List<ModDiscovery.Candidate> candidates, GameClasses game, @Nullable GameVersion version, List<String> problems)
|
||||
{
|
||||
try { ModVerifier.verify(candidates, game, version); }
|
||||
try { return ModVerifier.verify(candidates, game, version); }
|
||||
catch (ModLoadException e) { problems.addAll(e.problems()); }
|
||||
|
||||
return Map.of();
|
||||
}
|
||||
|
||||
/**
|
||||
* The annotation rules of the server, run on the mod's classes: the entry point's listener and
|
||||
* scheduled methods, the records in the jar that carry {@code @Schema}, {@code @Migrate},
|
||||
* {@code @Key}, {@code @Min}, or {@code @Max}, and the {@code @RegisterCommand} classes.
|
||||
* Runs only when every other check passed, since classes that do not link cannot be loaded.
|
||||
*
|
||||
* @param commands binary names of the mod's {@code @RegisterCommand} classes
|
||||
*/
|
||||
private static void checkAnnotations(Arguments arguments, ModDescriptor descriptor, List<String> commands, List<String> problems)
|
||||
{
|
||||
if (!problems.isEmpty()) return;
|
||||
|
||||
List<Path> jars = new ArrayList<>();
|
||||
jars.add(arguments.jar());
|
||||
jars.addAll(arguments.libraries());
|
||||
jars.addAll(arguments.dependencies());
|
||||
if (arguments.gameJar() != null) jars.add(arguments.gameJar());
|
||||
|
||||
try (URLClassLoader loader = new URLClassLoader("mod-check", jars.stream().map(ModCheck::url).toArray(URL[]::new), ModCheck.class.getClassLoader()))
|
||||
{
|
||||
Class<?> entrypoint = ModCheck.load(loader, descriptor.entrypoint(), problems);
|
||||
if (entrypoint != null) problems.addAll(ListenerScanner.check(entrypoint));
|
||||
|
||||
for (String name : ModCheck.annotatedRecords(arguments.jar(), problems))
|
||||
{
|
||||
Class<?> type = ModCheck.load(loader, name, problems);
|
||||
if (type == null || !type.isRecord()) continue;
|
||||
|
||||
problems.addAll(RecordSchema.check(type.asSubclass(Record.class)));
|
||||
problems.addAll(RecordBinder.check(type.asSubclass(Record.class)));
|
||||
}
|
||||
|
||||
for (String name : commands)
|
||||
{
|
||||
Class<?> type = ModCheck.load(loader, name, problems);
|
||||
if (type == null) continue;
|
||||
|
||||
int modifiers = type.getModifiers();
|
||||
|
||||
if (!Modifier.isPublic(modifiers)) problems.add("The command '" + name + "' (@RegisterCommand) is not public.");
|
||||
if (Modifier.isAbstract(modifiers) || type.isInterface()) problems.add("The command '" + name + "' (@RegisterCommand) is abstract.");
|
||||
if (descriptor.game().isEmpty()) problems.add("The command '" + name + "' (@RegisterCommand) needs Project Zomboid's command framework, so 'mod.toml' needs 'game' versions.");
|
||||
}
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
problems.add("Cannot close the class loader of the check: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** The class {@code name}, loaded without initializing it, or {@code null} after adding the problem. */
|
||||
private static @Nullable Class<?> load(ClassLoader loader, String name, List<String> problems)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Class.forName(name, false, loader);
|
||||
}
|
||||
catch (ClassNotFoundException | LinkageError e)
|
||||
{
|
||||
problems.add("Cannot load '" + name + "' to check its annotations: " + e + ".");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Binary names of the records in {@code jar} that carry one of {@link #RECORD_ANNOTATIONS}, on the record, a component, or a method. */
|
||||
private static Set<String> annotatedRecords(Path jar, List<String> problems)
|
||||
{
|
||||
Set<String> records = new TreeSet<>();
|
||||
|
||||
try (JarFile file = new JarFile(jar.toFile()))
|
||||
{
|
||||
for (JarEntry entry : file.stream().toList())
|
||||
{
|
||||
String name = entry.getName();
|
||||
if (!name.endsWith(".class") || name.startsWith("META-INF/")) continue;
|
||||
|
||||
ClassNode node = new ClassNode();
|
||||
try (InputStream in = file.getInputStream(entry)) { new ClassReader(in.readAllBytes()).accept(node, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); }
|
||||
|
||||
if (ModCheck.RECORD.equals(node.superName) && ModCheck.carriesRecordAnnotation(node)) records.add(node.name.replace('/', '.'));
|
||||
}
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
problems.add("Cannot read '" + jar + "': " + e.getMessage());
|
||||
}
|
||||
|
||||
return records;
|
||||
}
|
||||
|
||||
private static boolean carriesRecordAnnotation(ClassNode node)
|
||||
{
|
||||
if (ModCheck.anyRecordAnnotation(node.visibleAnnotations)) return true;
|
||||
|
||||
for (MethodNode method : node.methods) {
|
||||
if (ModCheck.anyRecordAnnotation(method.visibleAnnotations)) return true;
|
||||
}
|
||||
|
||||
if (node.recordComponents != null) {
|
||||
for (RecordComponentNode component : node.recordComponents) {
|
||||
if (ModCheck.anyRecordAnnotation(component.visibleAnnotations)) return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean anyRecordAnnotation(@Nullable List<AnnotationNode> annotations)
|
||||
{
|
||||
return annotations != null && annotations.stream().anyMatch(annotation -> ModCheck.RECORD_ANNOTATIONS.contains(annotation.desc));
|
||||
}
|
||||
|
||||
private static URL url(Path path)
|
||||
{
|
||||
try { return path.toUri().toURL(); }
|
||||
catch (MalformedURLException e) { throw new IllegalArgumentException("'" + path + "' has no URL.", e); }
|
||||
}
|
||||
|
||||
private static ModDiscovery.Candidate candidate(Path jar, List<Path> libraries, ModDescriptor descriptor)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package checkmods;
|
||||
|
||||
import dev.overlord.zomboidforge.api.annotations.RegisterCommand;
|
||||
|
||||
/** A command class that tests package into a mod jar: neither public nor concrete. */
|
||||
@RegisterCommand
|
||||
abstract class AbstractCommand {}
|
||||
@@ -0,0 +1,16 @@
|
||||
package checkmods;
|
||||
|
||||
import dev.overlord.zomboidforge.api.Mod;
|
||||
import dev.overlord.zomboidforge.api.annotations.Every;
|
||||
import dev.overlord.zomboidforge.api.annotations.OnMain;
|
||||
|
||||
/** Entry point that tests package into a mod jar; its annotated methods break the rules. */
|
||||
@SuppressWarnings("unused")
|
||||
public class InvalidEntry extends Mod
|
||||
{
|
||||
@OnMain
|
||||
void tick(String text) {}
|
||||
|
||||
@Every(0)
|
||||
void report() {}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package checkmods;
|
||||
|
||||
import dev.overlord.zomboidforge.api.annotations.Key;
|
||||
import dev.overlord.zomboidforge.api.annotations.Max;
|
||||
import dev.overlord.zomboidforge.api.annotations.Min;
|
||||
import dev.overlord.zomboidforge.api.annotations.Schema;
|
||||
|
||||
/** Records that tests package into a mod jar, with valid and invalid annotations. */
|
||||
public final class Records
|
||||
{
|
||||
public record Fine(@Key("ok") @Min(1) int amount) {}
|
||||
|
||||
@Schema(version = 0)
|
||||
public record BadSchema(long amount) {}
|
||||
|
||||
public record BadKey(@Key("Bad Key") int amount) {}
|
||||
|
||||
public record BadBounds(@Min(5) @Max(1) int amount) {}
|
||||
|
||||
private Records() {}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package checkmods;
|
||||
|
||||
import dev.overlord.zomboidforge.api.Mod;
|
||||
import dev.overlord.zomboidforge.api.TickEvent;
|
||||
import dev.overlord.zomboidforge.api.annotations.Every;
|
||||
import dev.overlord.zomboidforge.api.annotations.EveryNTicks;
|
||||
import dev.overlord.zomboidforge.api.annotations.OnMain;
|
||||
|
||||
/** Entry point that tests package into a mod jar; every annotated method follows the rules. */
|
||||
@SuppressWarnings("unused")
|
||||
public class ValidEntry extends Mod
|
||||
{
|
||||
@OnMain
|
||||
void tick(TickEvent event) {}
|
||||
|
||||
@Every(1)
|
||||
void report() {}
|
||||
|
||||
@EveryNTicks(2)
|
||||
void sweep() {}
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
package dev.overlord.zomboidforge.tools;
|
||||
|
||||
import checkmods.InvalidEntry;
|
||||
import checkmods.Records;
|
||||
import checkmods.ValidEntry;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
@@ -7,6 +11,7 @@ import org.objectweb.asm.ClassWriter;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
@@ -17,6 +22,7 @@ import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarOutputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
|
||||
import static org.objectweb.asm.Opcodes.ALOAD;
|
||||
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
|
||||
@@ -67,6 +73,80 @@ class ModCheckTest
|
||||
assertEquals(List.of("The entry point 'a.Main' does not extend 'dev.overlord.zomboidforge.api.Mod'."), result.problems());
|
||||
}
|
||||
|
||||
@Test
|
||||
void passesValidAnnotations() throws IOException
|
||||
{
|
||||
Path mod = this.jar("shop.jar", ModCheckTest.toml(ValidEntry.class), Map.of(
|
||||
"checkmods/ValidEntry", ModCheckTest.classFile(ValidEntry.class),
|
||||
"checkmods/Records$Fine", ModCheckTest.classFile(Records.Fine.class)
|
||||
));
|
||||
|
||||
ModCheck.Result result = ModCheck.check(new ModCheck.Arguments(mod, null, List.of(), List.of(), null));
|
||||
|
||||
assertEquals(List.of(), result.problems());
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsListenerAndScheduledMethodsThatBreakTheRules() throws IOException
|
||||
{
|
||||
Path mod = this.jar("shop.jar", ModCheckTest.toml(InvalidEntry.class), Map.of("checkmods/InvalidEntry", ModCheckTest.classFile(InvalidEntry.class)));
|
||||
|
||||
String problems = String.join("\n", ModCheck.check(new ModCheck.Arguments(mod, null, List.of(), List.of(), null)).problems());
|
||||
|
||||
ModCheckTest.assertContainsAll(problems, "checkmods.InvalidEntry.tick", "java.lang.String", "checkmods.InvalidEntry.report");
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsRecordAnnotationsThatBreakTheRules() throws IOException
|
||||
{
|
||||
Path mod = this.jar("shop.jar", ModCheckTest.toml(ValidEntry.class), Map.of(
|
||||
"checkmods/ValidEntry", ModCheckTest.classFile(ValidEntry.class),
|
||||
"checkmods/Records$Fine", ModCheckTest.classFile(Records.Fine.class),
|
||||
"checkmods/Records$BadSchema", ModCheckTest.classFile(Records.BadSchema.class),
|
||||
"checkmods/Records$BadKey", ModCheckTest.classFile(Records.BadKey.class),
|
||||
"checkmods/Records$BadBounds", ModCheckTest.classFile(Records.BadBounds.class)
|
||||
));
|
||||
|
||||
List<String> problems = ModCheck.check(new ModCheck.Arguments(mod, null, List.of(), List.of(), null)).problems();
|
||||
|
||||
assertEquals(3, problems.size(), String.valueOf(problems));
|
||||
ModCheckTest.assertContainsAll(String.join("\n", problems), "Records$BadSchema", "Records$BadKey", "Bad Key", "Records$BadBounds");
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsRegisteredCommandsThatCannotBeRegistered() throws IOException
|
||||
{
|
||||
Path mod = this.jar("shop.jar", ModCheckTest.toml(ValidEntry.class), Map.of(
|
||||
"checkmods/ValidEntry", ModCheckTest.classFile(ValidEntry.class),
|
||||
"checkmods/AbstractCommand", ModCheckTest.classFile("checkmods/AbstractCommand")
|
||||
));
|
||||
|
||||
String problems = String.join("\n", ModCheck.check(new ModCheck.Arguments(mod, null, List.of(), List.of(), null)).problems());
|
||||
|
||||
ModCheckTest.assertContainsAll(problems, "checkmods.AbstractCommand", "not public", "abstract", "'game'");
|
||||
}
|
||||
|
||||
/** {@link #TOML} with {@code entrypoint} as the entry point. */
|
||||
private static String toml(Class<?> entrypoint) { return ModCheckTest.TOML.replace("a.Main", entrypoint.getName()); }
|
||||
|
||||
/** The class file of a class on the test class path. */
|
||||
private static byte[] classFile(Class<?> type) throws IOException { return ModCheckTest.classFile(type.getName().replace('.', '/')); }
|
||||
|
||||
/** The class file of the class {@code internalName} on the test class path. */
|
||||
private static byte[] classFile(String internalName) throws IOException
|
||||
{
|
||||
try (InputStream in = ModCheckTest.class.getResourceAsStream("/" + internalName + ".class"))
|
||||
{
|
||||
if (in == null) throw new IOException("No class file for '" + internalName + "'.");
|
||||
return in.readAllBytes();
|
||||
}
|
||||
}
|
||||
|
||||
private static void assertContainsAll(String message, String... parts)
|
||||
{
|
||||
for (String part : parts) assertTrue(message.contains(part), "'" + part + "' missing in: " + message);
|
||||
}
|
||||
|
||||
/** A public class extending {@code superName} with a public constructor without parameters. */
|
||||
private static byte[] type(String name, String superName)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
// Sets up or updates the ZomboidForge mod project in the current directory, whose
|
||||
// settings.gradle.kts applies the plugin dev.overlord.zomboidforge. Runs with JShell (JDK 25),
|
||||
// the same way on Linux, macOS, and Windows:
|
||||
//
|
||||
// curl -fsSL https://git.security-command.org/Overlord/ZomboidForge/raw/branch/master/zomboidforge.jsh | jshell -
|
||||
// curl -fsSL https://git.security-command.org/Overlord/ZomboidForge/raw/branch/master/zomboidforge.jsh | jshell -R-Dzomboidforge.version=0.7.0 -
|
||||
//
|
||||
// Steps: sets the plugin version in settings.gradle.kts, writes the Gradle wrapper of that
|
||||
// ZomboidForge version, then runs "gradlew zomboidForgeSetup build".
|
||||
//
|
||||
// System properties (-R-D<name>=<value>):
|
||||
// zomboidforge.version the version to set; default: the newest published one
|
||||
// zomboidforge.repository Maven repository with the plugin; default: the ZomboidForge registry
|
||||
// zomboidforge.files base URL of the wrapper files, as <base>/v<version>/<path>;
|
||||
// default: the release tags of the ZomboidForge repository
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.net.URLConnection;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
class ZomboidForgeUpdater
|
||||
{
|
||||
static final String WEBSITE = "https://git.security-command.org/Overlord/ZomboidForge";
|
||||
static final String REPOSITORY = ZomboidForgeUpdater.property("zomboidforge.repository", "https://git.security-command.org/api/packages/overlord/maven");
|
||||
static final String FILES = ZomboidForgeUpdater.property("zomboidforge.files", ZomboidForgeUpdater.WEBSITE + "/raw/tag");
|
||||
static final String METADATA = "/dev/overlord/zomboidforge/dev.overlord.zomboidforge.gradle.plugin/maven-metadata.xml";
|
||||
static final Path SETTINGS = Path.of("settings.gradle.kts");
|
||||
static final Pattern PLUGIN = Pattern.compile("id\\(\"dev\\.overlord\\.zomboidforge\"\\)\\s*version\\s*\"([^\"]*)\"");
|
||||
static final Pattern VERSION = Pattern.compile("<version>([^<]+)</version>");
|
||||
static final Pattern RELEASE = Pattern.compile("<release>([^<]+)</release>");
|
||||
static final List<String> WRAPPER = List.of("gradlew", "gradlew.bat", "gradle/wrapper/gradle-wrapper.jar", "gradle/wrapper/gradle-wrapper.properties");
|
||||
static final int TIMEOUT = 30_000;
|
||||
|
||||
static int run()
|
||||
{
|
||||
try
|
||||
{
|
||||
ZomboidForgeUpdater.update();
|
||||
return 0;
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
System.err.println("[zomboidforge] " + e.getMessage());
|
||||
return 1;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
System.err.println("[zomboidforge] Unable to update: " + e);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
static void update() throws Exception
|
||||
{
|
||||
if (!Files.isRegularFile(ZomboidForgeUpdater.SETTINGS)) throw new IOException("Unable to update: no 'settings.gradle.kts' in '" + Path.of("").toAbsolutePath() + "'.");
|
||||
|
||||
String settings = Files.readString(ZomboidForgeUpdater.SETTINGS);
|
||||
Matcher plugin = ZomboidForgeUpdater.PLUGIN.matcher(settings);
|
||||
|
||||
if (!plugin.find()) throw new IOException("Unable to update: 'settings.gradle.kts' has no 'id(\"dev.overlord.zomboidforge\") version \"...\"'.");
|
||||
|
||||
String current = plugin.group(1);
|
||||
String target = ZomboidForgeUpdater.target();
|
||||
|
||||
// Every download finishes before the first file changes.
|
||||
Map<String, byte[]> wrapper = new LinkedHashMap<>();
|
||||
for (String path : ZomboidForgeUpdater.WRAPPER) wrapper.put(path, ZomboidForgeUpdater.download(ZomboidForgeUpdater.FILES + "/v" + target + "/" + path));
|
||||
|
||||
if (!current.equals(target)) Files.writeString(ZomboidForgeUpdater.SETTINGS, settings.substring(0, plugin.start(1)) + target + settings.substring(plugin.end(1)));
|
||||
|
||||
for (Map.Entry<String, byte[]> file : wrapper.entrySet())
|
||||
{
|
||||
Path path = Path.of(file.getKey());
|
||||
|
||||
if (path.getParent() != null) Files.createDirectories(path.getParent());
|
||||
Files.write(path, file.getValue());
|
||||
}
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
Path.of("gradlew").toFile().setExecutable(true);
|
||||
|
||||
System.out.println("[zomboidforge] ZomboidForge " + target + (current.equals(target) ? "" : " (was " + current + ")") + ".");
|
||||
System.out.println("[zomboidforge] Documentation: " + ZomboidForgeUpdater.WEBSITE + "/src/tag/v" + target + "/MOD_DEVELOPMENT.md");
|
||||
if (!current.equals(target)) System.out.println("[zomboidforge] Changes: " + ZomboidForgeUpdater.WEBSITE + "/compare/v" + current + "...v" + target);
|
||||
|
||||
int exit = ZomboidForgeUpdater.gradle("zomboidForgeSetup", "build");
|
||||
if (exit != 0) throw new IOException("Unable to build the mod: 'gradlew zomboidForgeSetup build' exited with " + exit + ".");
|
||||
}
|
||||
|
||||
/** The version from {@code zomboidforge.version}, else the newest one; either has to be published. */
|
||||
static String target() throws IOException
|
||||
{
|
||||
String metadata = new String(ZomboidForgeUpdater.download(ZomboidForgeUpdater.REPOSITORY + ZomboidForgeUpdater.METADATA), StandardCharsets.UTF_8);
|
||||
List<String> published = new ArrayList<>();
|
||||
Matcher versions = ZomboidForgeUpdater.VERSION.matcher(metadata);
|
||||
Matcher release = ZomboidForgeUpdater.RELEASE.matcher(metadata);
|
||||
|
||||
while (versions.find()) published.add(versions.group(1));
|
||||
|
||||
if (published.isEmpty()) throw new IOException("Unable to update: no published versions in '" + ZomboidForgeUpdater.REPOSITORY + ZomboidForgeUpdater.METADATA + "'.");
|
||||
|
||||
String newest = release.find() ? release.group(1) : published.getLast();
|
||||
String target = ZomboidForgeUpdater.property("zomboidforge.version", newest);
|
||||
|
||||
if (!published.contains(target)) throw new IOException("Unable to update: version '" + target + "' is not published; published: " + published + ".");
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
static byte[] download(String url) throws IOException
|
||||
{
|
||||
try
|
||||
{
|
||||
URLConnection connection = URI.create(url).toURL().openConnection();
|
||||
connection.setConnectTimeout(ZomboidForgeUpdater.TIMEOUT);
|
||||
connection.setReadTimeout(ZomboidForgeUpdater.TIMEOUT);
|
||||
|
||||
try (InputStream in = connection.getInputStream()) { return in.readAllBytes(); }
|
||||
}
|
||||
catch (FileNotFoundException e)
|
||||
{
|
||||
throw new IOException("Unable to download '" + url + "': not found.", e);
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
throw new IOException("Unable to download '" + url + "': " + e, e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs the wrapper in the current directory and copies its output; JShell drops inherited output. */
|
||||
static int gradle(String... tasks) throws IOException, InterruptedException
|
||||
{
|
||||
boolean windows = System.getProperty("os.name").startsWith("Windows");
|
||||
List<String> command = new ArrayList<>();
|
||||
|
||||
command.add(Path.of(windows ? "gradlew.bat" : "gradlew").toAbsolutePath().toString());
|
||||
command.addAll(List.of(tasks));
|
||||
|
||||
Process process = new ProcessBuilder(command).redirectErrorStream(true).start();
|
||||
process.getOutputStream().close();
|
||||
|
||||
try (InputStream out = process.getInputStream()) { out.transferTo(System.out); }
|
||||
|
||||
return process.waitFor();
|
||||
}
|
||||
|
||||
static String property(String name, String fallback)
|
||||
{
|
||||
String value = System.getProperty(name, "").strip();
|
||||
|
||||
return value.isEmpty() ? fallback : value.replaceAll("/+$", "");
|
||||
}
|
||||
}
|
||||
|
||||
int status = ZomboidForgeUpdater.run();
|
||||
/exit status
|
||||
Reference in new issue
Block a user